diff --git a/src/handlers/background-tasks.ts b/src/handlers/background-tasks.ts index 9d5ef96e..f39d749a 100644 --- a/src/handlers/background-tasks.ts +++ b/src/handlers/background-tasks.ts @@ -395,6 +395,25 @@ export class BackgroundTaskListener implements EventListener { } } + /** True while a rewind command's replacement-turn claim is still open. */ + hasActiveRewindClaim(): boolean { + return this.rewindClaimAt !== null; + } + + /** Clear rewind-claim and notification-turn forwarding state after an + * explicit user cancel on a session with no pendingTurns entry. */ + clearRewindAndNotifyState(): void { + this.rewindClaimAt = null; + this.rewindClaimToken = null; + if (this.rewindClaimTimer) { + clearTimeout(this.rewindClaimTimer); + this.rewindClaimTimer = null; + } + this.activeNotifyTurnId = null; + this.windowTurnId = null; + this.firstMessageId = null; + } + /** * True while at least one subagent background task is still running: the * held-prompt turn loop keeps `session/prompt` open for exactly this work @@ -627,7 +646,16 @@ export class BackgroundTaskListener implements EventListener { // Foreign-turn running state (upstream taskActivityTracker parity): // a turn.started from ANY source — background_task wake, subagent_message, // control-only — marks the session running for every consumer that has - // no turn loop of its own to derive it from. + // no turn loop of its own to derive it from. Skip detached compaction's + // internal turn: compaction already owns busy state via + // `autoCompactInFlight`, and recording it in `foreignActiveTurns` would + // bypass the cancel guard and let ESC kill compaction. + if ( + inputSource !== "background_task" && + this.server.autoCompactInFlight?.has(this.zcodeSid) + ) { + return; + } this.trackForeignTurn(turnId, true); return; } @@ -1031,11 +1059,27 @@ export class BackgroundTaskListener implements EventListener { ): void { if (task.terminalPushed || p.taskKind === "workflow") return; task.terminalPushed = true; + const acpSid = this.server.acpSidByZcodeSid?.get(this.zcodeSid); + const label = pushSourceLabel(this.server, acpSid); + const desc = task.description.trim(); + const rawDetail = p.status && p.status !== "running" ? p.status : acpStatus; + if (isSubagentTask(task)) { + const title = + acpStatus === "completed" + ? "subagent completed" + : rawDetail !== "failed" + ? `subagent ${rawDetail}` + : "subagent failed"; + const body = desc ? `${desc} · ${rawDetail}` : rawDetail; + pushSettled(this.server, { kind: "task", label, title, body }); + return; + } + const statusLine = exitCode !== undefined ? `exit ${exitCode} · ${acpStatus}` : rawDetail; pushSettled(this.server, { kind: "task", - label: pushSourceLabel(this.server), - title: "background task done", - body: exitCode !== undefined ? `exit ${exitCode} · ${acpStatus}` : acpStatus, + label, + title: acpStatus === "completed" ? "background task done" : "background task failed", + body: desc ? `${desc} · ${statusLine}` : statusLine, }); } diff --git a/src/handlers/rewind.ts b/src/handlers/rewind.ts index 05aaf4d0..7aa4d41f 100644 --- a/src/handlers/rewind.ts +++ b/src/handlers/rewind.ts @@ -290,7 +290,7 @@ async function runRewind( zcodeSid: string, buildRequest: (snapshot: RowsRangeSnapshot) => RewindRequest, ): Promise> { - const listener = await server.ensureBackgroundListener(zcodeSid); + const listener = await server.ensureBackgroundListener(zcodeSid, { subscribe: true }); let accepted = false; let claimToken: number | null = null; await emitSessionTurnState(server, acpSid, true); diff --git a/src/handlers/session.ts b/src/handlers/session.ts index 1624bfea..a3e47165 100644 --- a/src/handlers/session.ts +++ b/src/handlers/session.ts @@ -1939,7 +1939,7 @@ export async function resumeSession( // above); without this, a loaded session has no readable root. server.sessionCwds.set(acpSid, cwd); log(`session/resume -> ${zcodeSid}`); - await server.ensureBackgroundListener(zcodeSid); + await server.ensureBackgroundListener(zcodeSid, { subscribe: true }); await adoptStoredTitle(server, acpSid, zcodeSid); // Martty's /resume rides session/resume (no history by ACP design) and only // folds updates addressed to a session id it has already adopted — i.e. @@ -2122,7 +2122,7 @@ export async function resumeIntoSession( const finalCwd = backendWs && !server.serveMode ? backendWs : cwd; server.sessionCwds.set(acpSid, finalCwd); recordMaterializedSession(acpSid, zcodeTarget, finalCwd); - await server.ensureBackgroundListener(zcodeTarget); + await server.ensureBackgroundListener(zcodeTarget, { subscribe: true }); await adoptStoredTitle(server, acpSid, zcodeTarget); } catch (e) { warn(`/resume: adopting ${zcodeTarget} failed (${e instanceof Error ? e.message : String(e)})`); @@ -2370,7 +2370,7 @@ export async function loadSession( // Same as resumeSession: backend-authoritative session root for file access. server.sessionCwds.set(acpSid, cwd); log(`session/load → ${zcodeSid}`); - await server.ensureBackgroundListener(zcodeSid); + await server.ensureBackgroundListener(zcodeSid, { subscribe: true }); await adoptStoredTitle(server, acpSid, zcodeSid); // Goal-loop restart recovery (ADR-0022 §6): surface a recovery hint at most @@ -2717,6 +2717,7 @@ export async function runOneTurn( differ.markSeen(await fetchMessagesSinceAnchor(server, zcodeSid, differ.historyAnchor)); snapshot = await listener.subscribe(() => server.nextId()); } + server.markSessionSubscribed?.(backend, zcodeSid); // A successful subscribe proves the resident runtime is live — refresh // the verification so concurrent/later entry points skip a reload. residentBackend = backend; @@ -2868,7 +2869,11 @@ export async function runOneTurn( return { stopReason: "end_turn", _meta: { - zcode: { delivery: outcome.kind, commandId: outcome.commandId }, + zcode: { + delivery: outcome.kind, + commandId: outcome.commandId, + ...(outcome.kind === "queued" ? { queueItemId: outcome.queueItemId } : {}), + }, }, }; } @@ -3828,10 +3833,46 @@ export function cancelSessionTurns( } catch (e) { log(`goal-loop pause request failed: ${e instanceof Error ? e.message : String(e)}`); } + // A backend-owned turn (rewind replacement, background notification, a + // failed orphan adopt, or a turn whose start was never observed) has no + // pendingTurns entry, yet is still running upstream. Still send the stop + // pair unless detached auto-compact owns the session's prompt lock (ESC + // during detached compaction must not kill compaction). + const foreignOrNotify = + server.foreignActiveTurns?.has(zcodeSid) === true || + server.notifyTurnActiveSince?.has(zcodeSid) === true || + server.backgroundListeners?.get(zcodeSid)?.hasActiveRewindClaim() === true; + const compactRunning = server.autoCompactInFlight?.has(zcodeSid) === true; + if (!compactRunning) { + void stopBackendTurn(server, zcodeSid, { zcodeSid, cancelled: true, sendAccepted: true }); + server.lastCancelledAt?.set(zcodeSid, Date.now()); + } + if (foreignOrNotify) { + server.foreignActiveTurns?.delete(zcodeSid); + server.notifyTurnActiveSince?.delete(zcodeSid); + server.backgroundListeners?.get(zcodeSid)?.clearRewindAndNotifyState(); + const acpSid = server.acpSidByZcodeSid?.get(zcodeSid); + if (acpSid && !compactRunning) { + void emitSessionTurnState(server, acpSid, false).catch(() => undefined); + } + } } return matched; } +/** + * Awaitable stop pair for an unowned backend turn (remote force-close): ensures + * `session/stop` + `v4/command stop` are written to the backend pipe BEFORE + * `session/close` evicts the resident runtime. + */ +export async function stopUnownedBackendTurn( + server: ZcodeAcpServer, + zcodeSid: string, +): Promise { + await stopBackendTurn(server, zcodeSid, { zcodeSid, cancelled: true, sendAccepted: true }); + server.lastCancelledAt?.set(zcodeSid, Date.now()); +} + /** * Raised by `runEventTurn` when the backend emits `turn.failed`. Carries the * structured error object (with its nested `cause`) so `prompt`'s retry loop diff --git a/src/push/push.ts b/src/push/push.ts index b8a1c0e3..67ca5470 100644 --- a/src/push/push.ts +++ b/src/push/push.ts @@ -206,6 +206,19 @@ export function pushTerminalNotification(data: PushEventData & { kind: "terminal dispatchPush(cfg, s, data); } +/** + * Push an interactive/authorization notice that needs human attention even when + * a remote client is connected (e.g. V2 MCP OAuth fallback opening the browser + * on the host machine while the user is on mobile). Gated by `push.notify.ask`. + */ +export function pushAskNotice(data: PushEventData & { kind: "permission" | "question" }): void { + const cfg = pushConfig(); + if (!cfg || !cfg.notify.ask) return; + const s = pushSender(); + if (!s) return; + dispatchPush(cfg, s, data); +} + /** * Derive the permission/question payload from the wire method+params (§4/§5.1) * — shared by the zero-clients push and the unanswered-ask watchdog. `label` diff --git a/src/remote/session-close-endpoint.ts b/src/remote/session-close-endpoint.ts index d82035cf..76982f3d 100644 --- a/src/remote/session-close-endpoint.ts +++ b/src/remote/session-close-endpoint.ts @@ -22,7 +22,8 @@ import type { IncomingMessage, ServerResponse } from "node:http"; import process from "node:process"; -import { cancelSessionTurns } from "../handlers/session.js"; +import { cancelSessionTurns, stopUnownedBackendTurn } from "../handlers/session.js"; +import { clearV4ConversationState } from "../v2/queue.js"; import { recordClosedSessionIds } from "../closed-sessions.js"; import type { ZcodeAcpServer } from "../server.js"; import { log } from "../utils.js"; @@ -225,6 +226,9 @@ export async function retireSession( const running = zcodeSid !== undefined && [...server.pendingTurns.values()].some((t) => t.zcodeSid === zcodeSid); + const foreignRunning = + zcodeSid !== undefined && + (server.foreignActiveTurns.has(zcodeSid) || server.notifyTurnActiveSince.has(zcodeSid)); if (running && !opts.force) return { error: "running" }; if (running && zcodeSid !== undefined) { // Force close (ADR-0006 amendment): ESC semantics without a client @@ -239,6 +243,19 @@ export async function retireSession( if (![...server.pendingTurns.values()].some((t) => t.zcodeSid === zcodeSid)) break; await sleep(50); } + } else if (opts.force && foreignRunning && zcodeSid !== undefined) { + // Unowned backend turn (rewind/notification/orphan): await the stop pair so + // session/stop + v4 stop land on stdin BEFORE session/close evicts the + // runtime, then give the terminal event a brief settle window. + await stopUnownedBackendTurn(server, zcodeSid); + log(`remote: force close stopping foreign turn(s) for ${zcodeSid}`); + const deadline = Date.now() + Math.min(forceSettleMs, 500); + while (Date.now() < deadline) { + if (!server.foreignActiveTurns.has(zcodeSid) && !server.notifyTurnActiveSince.has(zcodeSid)) { + break; + } + await sleep(50); + } } // Retire from discovery AND stamp the retirement: a turn that outlives the // force-settle bound settles after this point, and its terminal activity @@ -267,7 +284,12 @@ export async function retireSession( // The runtime eviction below kills any in-flight FOREIGN turn (background // wake / subagent_message) with no terminal event arriving — drop the // tracking entry or the retired conversation would keep reporting running. - if (zcodeSid) server.foreignActiveTurns.delete(zcodeSid); + if (zcodeSid) { + server.foreignActiveTurns.delete(zcodeSid); + server.notifyTurnActiveSince.delete(zcodeSid); + server.invalidateSessionSubscription?.(zcodeSid); + clearV4ConversationState(zcodeSid); + } if (zcodeSid && server.backend && !server.backend.isDead) { try { server.backend.send("session/close", { sessionId: zcodeSid }); diff --git a/src/server.ts b/src/server.ts index b5785c94..6819ba7c 100644 --- a/src/server.ts +++ b/src/server.ts @@ -57,7 +57,7 @@ import { pushInteractionIfOffline } from "./push/push.js"; import { ClientRegistry } from "./remote/broadcast.js"; import { envWithLoginShell } from "./remote/login-shell-env.js"; import { V2StateStore, noteStartupProgress, settleV2Compaction } from "./v2/state.js"; -import { ingestV4Frame } from "./v2/queue.js"; +import { clearV4ConversationState, ingestV4Frame } from "./v2/queue.js"; import { stopAllWorkflowRunPollers } from "./workflow/poller.js"; import { AGENT_INFO, clientConnectionRoot, PROTOCOL_VERSION, log, warn } from "./utils.js"; @@ -729,6 +729,19 @@ export class ZcodeAcpServer { * next turn, not just on resume/load). */ readonly backgroundListenerBackend = new Map(); + /** + * Backend instance each session has an active `session/subscribe` push on. + * Upstream turns on `session/event` push only once `session/subscribe` has + * been called for a live runtime — a bridge that only called `session/load` + * after a restart never received `turn.started` for rewind or backend-owned + * turns until a prompt subscribed. Cleared on respawn, runtime unload, and + * remote session/close eviction. + */ + readonly backendSubscribedSessions = new Map(); + private readonly backendSubscribeFlights = new Map< + string, + { backend: ZcodeBackend; promise: Promise } + >(); /** * Sessions (zcodeSid) whose background NOTIFICATION turn (the model * summarising a finished background task) is currently running, → start @@ -1203,6 +1216,8 @@ export class ZcodeAcpServer { // (the backend's "Session is not active" is swallowed by fetchMessages), // or a prefix when a sibling client's re-resume was still hydrating. this.backendLoadedSessions.clear(); + this.invalidateSessionSubscription(); + clearV4ConversationState(); // …and the foreign-turn tracking: the turns it holds ran on the dead // process and no terminal event will ever arrive for them. Best-effort // settle broadcast so a client left mid-"running" by the crash doesn't @@ -1350,6 +1365,8 @@ export class ZcodeAcpServer { */ applyLifecycleSnapshot(snap: ZcodeLifecycleSnapshot): void { if (snap.state === "ready") return; + this.invalidateSessionSubscription(snap.sessionId); + clearV4ConversationState(snap.sessionId); let touched = false; for (const [acpSid, zcodeSid] of this.sessionMap) { if (zcodeSid !== snap.sessionId) continue; @@ -1629,21 +1646,103 @@ export class ZcodeAcpServer { * forwarded to the client. The turn loop's own listener coexists via the * backend's per-session listener Set. */ - async ensureBackgroundListener(zcodeSid: string): Promise { + /** Record that `session/subscribe` succeeded for `zcodeSid` on `backend`. */ + markSessionSubscribed(backend: ZcodeBackend, zcodeSid: string): void { + if (this.backend === backend && !backend.isDead) { + this.backendSubscribedSessions.set(zcodeSid, backend); + } + } + + /** Drop cached event-stream subscription state (all sessions on respawn, or one on unload/close). */ + invalidateSessionSubscription(zcodeSid?: string): void { + if (zcodeSid === undefined) { + this.backendSubscribedSessions.clear(); + this.backendSubscribeFlights.clear(); + return; + } + this.backendSubscribedSessions.delete(zcodeSid); + this.backendSubscribeFlights.delete(zcodeSid); + } + + /** + * Best-effort `session/subscribe` (without snapshot) once per live backend + * runtime so out-of-band listeners (`BackgroundTaskListener`, title pushes, + * V2 orphan adoption) receive `turn.started` / task events even before the + * first `session/prompt` on this bridge process. + */ + private async ensureSessionEventStream(backend: ZcodeBackend, zcodeSid: string): Promise { + if (this.backendSubscribedSessions.get(zcodeSid) === backend) return; + const inflight = this.backendSubscribeFlights.get(zcodeSid); + if (inflight && inflight.backend === backend) { + await inflight.promise; + return; + } + let entry!: { backend: ZcodeBackend; promise: Promise }; + const promise = (async () => { + try { + const resp = await backend.request( + this.nextId(), + "session/subscribe", + { + sessionId: zcodeSid, + deliveryKind: "desktop-continuous", + includeSnapshot: false, + }, + 5000, + ); + if (!resp.error) { + if ( + this.backend === backend && + !backend.isDead && + this.backendSubscribeFlights.get(zcodeSid) === entry + ) { + this.backendSubscribedSessions.set(zcodeSid, backend); + } + } else { + log(` [bg] session/subscribe skipped for ${zcodeSid}: ${resp.error.message ?? ""}`); + } + } catch (e) { + log( + ` [bg] session/subscribe failed for ${zcodeSid}: ${ + e instanceof Error ? e.message : String(e) + }`, + ); + } + })(); + entry = { backend, promise }; + this.backendSubscribeFlights.set(zcodeSid, entry); + try { + await promise; + } finally { + if (this.backendSubscribeFlights.get(zcodeSid) === entry) { + this.backendSubscribeFlights.delete(zcodeSid); + } + } + } + + async ensureBackgroundListener( + zcodeSid: string, + opts?: { subscribe?: boolean }, + ): Promise { const backend = await this.ensureBackend(); const existing = this.backgroundListeners.get(zcodeSid); - if (existing && this.backgroundListenerBackend.get(zcodeSid) === backend) return existing; - // Fresh session, or the backend was respawned since registration — - // (re-)register on the CURRENT instance; the old instance's listener set - // died with it, so there is no duplicate-registration risk. - const listener = existing ?? new BackgroundTaskListener(this, zcodeSid); - this.backgroundListeners.set(zcodeSid, listener); - backend.registerEventListener(zcodeSid, listener); - // The session-scoped title listener rides the same registration site and - // lifetime: one registration covers both out-of-band consumers. - backend.registerEventListener(zcodeSid, new SessionTitleListener(this, zcodeSid)); - this.backgroundListenerBackend.set(zcodeSid, backend); - log(` [bg] background listener registered for ${zcodeSid}`); + let listener: BackgroundTaskListener; + if (existing && this.backgroundListenerBackend.get(zcodeSid) === backend) { + listener = existing; + } else { + // Fresh session, or the backend was respawned since registration — + // (re-)register on the CURRENT instance; the old instance's listener set + // died with it, so there is no duplicate-registration risk. + listener = existing ?? new BackgroundTaskListener(this, zcodeSid); + this.backgroundListeners.set(zcodeSid, listener); + backend.registerEventListener(zcodeSid, listener); + // The session-scoped title listener rides the same registration site and + // lifetime: one registration covers both out-of-band consumers. + backend.registerEventListener(zcodeSid, new SessionTitleListener(this, zcodeSid)); + this.backgroundListenerBackend.set(zcodeSid, backend); + log(` [bg] background listener registered for ${zcodeSid}`); + } + if (opts?.subscribe) await this.ensureSessionEventStream(backend, zcodeSid); return listener; } diff --git a/src/v2/orphan.ts b/src/v2/orphan.ts index 68ebfb40..6e57b422 100644 --- a/src/v2/orphan.ts +++ b/src/v2/orphan.ts @@ -22,11 +22,12 @@ import type * as acp from "@agentclientprotocol/sdk/unstable"; import { EventStreamListener, TurnMonitor } from "../backend/listener.js"; import type { ZcodeEvent } from "../backend/types.js"; import { emitSessionTurnState, reportInsertedUserMessage } from "../handlers/io.js"; +import { pushSettled, pushSourceLabel } from "../push/push.js"; import { forceRefreshQuota } from "../quota/live.js"; import type { PendingTurn, ZcodeAcpServer } from "../server.js"; import { log, warn } from "../utils.js"; import { nudgeV4QueueDrain } from "./queue.js"; -import { noteV2TurnClocks } from "./state.js"; +import { noteV2TurnClocks, noteV2TurnEnd } from "./state.js"; import { offerPromptSuggestions } from "./tools.js"; /** The turn loop entry and the session differ (shared with the prompt path). */ @@ -85,27 +86,46 @@ export async function runOrphanTurn( // Registered before the first await so a concurrent turn.started for the // same session sees a live loop and is not adopted twice. server.pendingTurns.set(requestId, turn); - const backend = await server.ensureBackend(); - const cx = server.clients.broadcast() as unknown as acp.AgentContext; - const listener = new EventStreamListener(backend, zcodeSid); - const monitor = new TurnMonitor(backend, zcodeSid, () => server.nextId()); + // `started` just arrived from the live backend's already-subscribed event + // stream: attach our listener synchronously before any await so subsequent + // chunks arrive directly with zero subscribe/replay RPC round trips (which + // timed out on saturated multi-thousand-message sessions and stranded the + // running turn outside pendingTurns). Fall back to ensureBackend + subscribe + // only when server.backend is absent/dead. + let backend = server.backend && !server.backend.isDead ? server.backend : null; + let listener: EventStreamListener | null = null; + if (backend) { + listener = new EventStreamListener(backend, zcodeSid); + listener.subscribed = true; + listener.handleEvent(started); + backend.registerEventListener(zcodeSid, listener); + } const differ = getOrCreateDiffer(server, zcodeSid); const startedAt = Date.now(); let turnStartedAt = startedAt; let lastUsage: acp.Usage | undefined; let lastLlmMs: number | undefined; let stopReason = "end_turn"; + let enteredLoop = false; + let errorMessage: string | undefined; try { - await listener.subscribe(() => server.nextId()); - const replayed = await listener.replayFrom(started.seq, () => server.nextId()); - if (!replayed) listener.handleEvent(started); - backend.registerEventListener(zcodeSid, listener); + if (!backend || !listener) { + backend = await server.ensureBackend(); + listener = new EventStreamListener(backend, zcodeSid); + await listener.subscribe(() => server.nextId()); + const replayed = await listener.replayFrom(started.seq, () => server.nextId()); + if (!replayed) listener.handleEvent(started); + backend.registerEventListener(zcodeSid, listener); + } + const monitor = new TurnMonitor(backend, zcodeSid, () => server.nextId()); + const cx = server.clients.broadcast() as unknown as acp.AgentContext; server.markBackendLoaded(acpSid); server.markSessionActive(acpSid); log(` [v2] adopted backend turn ${started.turnId?.slice(-8) ?? "?"} into the full turn path`); // The loop is registered, so the transition reads `running` on both faces. await emitSessionTurnState(server, acpSid, true); for (;;) { + enteredLoop = true; const result = await runEventTurn( server, listener, @@ -133,13 +153,29 @@ export async function runOrphanTurn( turnStartedAt = Date.now(); } } catch (e) { + errorMessage = e instanceof Error ? e.message : String(e); warn( ` [v2] backend-owned turn ${started.turnId?.slice(-8) ?? "?"} failed in the turn path: ` + - `${e instanceof Error ? e.message : String(e)}`, + errorMessage, ); stopReason = "error"; + if (!enteredLoop && !turn.cancelled && started.turnId && backend !== null && !backend.isDead) { + // Setup failed before entering the turn loop while the backend turn is + // still live — hand liveness back to foreignActiveTurns so the session + // does NOT broadcast a false idle or nudge the queue into preempting it. + server.foreignActiveTurns.set(zcodeSid, started.turnId); + } else if (enteredLoop) { + // runEventTurn threw (TurnFailedError or dead reader): the turn already + // terminated upstream. Record the error stop on the idle snapshot. + noteV2TurnEnd( + server, + acpSid, + { stopReason: "error", error: { message: errorMessage } }, + null, + ); + } } finally { - backend.unregisterEventListener(zcodeSid, listener); + if (backend && listener) backend.unregisterEventListener(zcodeSid, listener); server.pendingTurns.delete(requestId); if (!server.wasDiscoveryRetiredSince(acpSid, startedAt)) server.markSessionActive(acpSid); void forceRefreshQuota(); @@ -149,14 +185,31 @@ export async function runOrphanTurn( // An adopted turn has no prompt pipeline finally to record its clocks: // without this the idle snapshot kept the previous turn's turnMs / llmMs // (observed live: a 12s queued turn reporting its predecessor's 4s). - noteV2TurnClocks( - server, - acpSid, - lastUsage ? { turnMs: Date.now() - turnStartedAt, llmMs: lastLlmMs } : {}, - ); + if (!stillBusy) { + noteV2TurnClocks( + server, + acpSid, + lastUsage ? { turnMs: Date.now() - turnStartedAt, llmMs: lastLlmMs } : {}, + ); + } await emitSessionTurnState(server, acpSid, stillBusy); - void nudgeV4QueueDrain(server, zcodeSid); - void offerPromptSuggestions(server, acpSid).catch(() => undefined); + if (!stillBusy && enteredLoop) { + pushSettled(server, { + kind: "turn", + label: pushSourceLabel(server, acpSid), + title: + stopReason === "error" + ? "turn failed" + : stopReason === "end_turn" + ? "turn completed" + : `turn ended (${stopReason})`, + ...(errorMessage ? { body: errorMessage } : {}), + }); + } + if (!stillBusy && stopReason !== "error") { + void nudgeV4QueueDrain(server, zcodeSid); + void offerPromptSuggestions(server, acpSid).catch(() => undefined); + } } log(` [v2] backend turn chain ended (${stopReason})`); } diff --git a/src/v2/queue.ts b/src/v2/queue.ts index 940689cb..5d8313f3 100644 --- a/src/v2/queue.ts +++ b/src/v2/queue.ts @@ -195,6 +195,13 @@ export async function ensureV4Conversation( const backend = await server.ensureBackend(); const existing = subscriptions.get(zcodeSid); if (existing && existing.backend === backend) return; + if (existing && existing.backend !== backend) { + // Previous backend generation died — drop stale control/queue snapshots + // before re-subscribing so idle prompts never read a dead backend's phase. + states.delete(zcodeSid); + subscriptions.delete(zcodeSid); + nudgeAt.delete(zcodeSid); + } if (subscribing.has(zcodeSid)) return; subscribing.add(zcodeSid); try { @@ -256,14 +263,36 @@ export function hasQueuedInput(zcodeSid: string): boolean { return !!queue && Array.isArray(queue.items) && queue.items.length > 0; } +/** True when the v4 conversation snapshot reports active foreground work. */ +export function isV4ForegroundActive(zcodeSid: string): boolean { + const phase = states.get(zcodeSid)?.control?.phase; + return phase === "running" || phase === "prewarming"; +} + +/** + * Drop cached v4 conversation state when a backend respawns (omit `zcodeSid`) + * or a session runtime is unloaded/closed (pass `zcodeSid`). Prevents stale + * `control.phase: "running"` from surviving a respawn or HTTP close. + */ +export function clearV4ConversationState(zcodeSid?: string): void { + if (zcodeSid === undefined) { + states.clear(); + subscriptions.clear(); + subscribing.clear(); + fragments.clear(); + nudgeAt.clear(); + return; + } + states.delete(zcodeSid); + subscriptions.delete(zcodeSid); + subscribing.delete(zcodeSid); + nudgeAt.delete(zcodeSid); +} + /** Test seam: drop all tracker state. */ export function resetV4TrackerForTests(): void { - states.clear(); - subscriptions.clear(); - subscribing.clear(); + clearV4ConversationState(); frameConsumers.clear(); - fragments.clear(); - nudgeAt.clear(); } /** @@ -279,7 +308,8 @@ export async function nudgeV4QueueDrain(server: ZcodeAcpServer, zcodeSid: string [...server.pendingTurns.values()].some( (t) => t.zcodeSid === zcodeSid && !(t.face === "v2" && t.holding), ) || - server.foreignActiveTurns.has(zcodeSid) + server.foreignActiveTurns.has(zcodeSid) || + isV4ForegroundActive(zcodeSid) ) { return; } diff --git a/src/v2/session.ts b/src/v2/session.ts index 8db1193a..9ef40f39 100644 --- a/src/v2/session.ts +++ b/src/v2/session.ts @@ -25,13 +25,14 @@ import { type PromptRunOptions, } from "../handlers/session.js"; import { reportInsertedUserMessage } from "../handlers/io.js"; +import { noteUserActivity } from "../push/push.js"; import type { ClientHandle } from "../remote/client-handle.js"; import { announceSessionClosed, retireSession } from "../remote/session-close-endpoint.js"; import { asClientContext, type CommandList } from "./app.js"; import { submitV4Prompt } from "./commands.js"; import { projectCommand, projectConfigOption } from "./project.js"; import { lookupPromptKey, rememberPromptKey } from "./prompt-keys.js"; -import { hasQueuedInput, releaseV4Conversation } from "./queue.js"; +import { hasQueuedInput, isV4ForegroundActive, releaseV4Conversation } from "./queue.js"; import { attachV4Conversation, checkMcpAuthorization } from "./tools.js"; import { cancelV2Background, forgetBackground, parentOfChild } from "./background.js"; @@ -149,6 +150,7 @@ export async function promptV2( if (!Array.isArray(params.prompt) || params.prompt.length === 0) { throw new RequestError(-32602, "prompt must not be empty"); } + noteUserActivity(server); const acpSid = params.sessionId; const zcodeSid = server.resolveSid(acpSid); if (params.idempotencyKey) { @@ -186,7 +188,9 @@ async function submitPrompt( (t) => t.zcodeSid === ctx.zcodeSid && !(t.face === "v2" && t.holding), ); const held = - (ctx.zcodeSid !== undefined && hasQueuedInput(ctx.zcodeSid)) || server.v2.busy(server, acpSid); + (ctx.zcodeSid !== undefined && + (hasQueuedInput(ctx.zcodeSid) || isV4ForegroundActive(ctx.zcodeSid))) || + server.v2.busy(server, acpSid); // The v4 `sendText` carries text alone — its attachments are host-registered // refs the bridge cannot mint — so an input with images that would ride it @@ -331,9 +335,18 @@ async function runTurnPrompt( }); } if (delivery === "queued" || delivery === "guided") { - const commandId = (outcome.result._meta as { zcode?: { commandId?: string } } | undefined) - ?.zcode?.commandId; - return { messageId: provisionalId(commandId), _meta: { zcode: { delivery } } }; + const zcodeMeta = ( + outcome.result._meta as { zcode?: { commandId?: string; queueItemId?: string } } | undefined + )?.zcode; + return { + messageId: provisionalId(zcodeMeta?.commandId), + _meta: { + zcode: { + delivery, + ...(zcodeMeta?.queueItemId ? { queueItemId: zcodeMeta.queueItemId } : {}), + }, + }, + }; } // A local command (slash) answered without a backend turn. return { messageId: provisionalId() }; diff --git a/src/v2/tools.ts b/src/v2/tools.ts index b46157be..eb2d2506 100644 --- a/src/v2/tools.ts +++ b/src/v2/tools.ts @@ -23,6 +23,7 @@ import { z } from "zod"; import { buildConfigOptions } from "../config/options.js"; import { pendingBackgroundWork } from "../handlers/pending-background-work.js"; +import { pushAskNotice, pushSourceLabel } from "../push/push.js"; import type { ClientHandle } from "../remote/client-handle.js"; import type { ZcodeAcpServer } from "../server.js"; import { log } from "../utils.js"; @@ -211,13 +212,15 @@ function inputPredictionEnabled(): boolean { return value === "" || value === "1"; } +type PredictionResult = Record | null; + /** One read-only query; every failure is "no prediction". */ -async function inputPrediction( +async function requestPrediction( server: ZcodeAcpServer, zcodeSid: string, draft: string | undefined, requestId: string, -): Promise | null> { +): Promise { if (!inputPredictionEnabled()) return null; const backend = await server.ensureBackend(); const state = conversationOf(zcodeSid); @@ -236,7 +239,50 @@ async function inputPrediction( log(`input prediction unavailable: ${resp.error.message ?? ""}`); return null; } - return (resp.result ?? null) as Record | null; + return (resp.result ?? null) as PredictionResult; +} + +/** The session's prediction in flight, and the newest ask waiting for it. */ +const predictionInFlight = new Map>(); +const predictionWaiting = new Map< + string, + { + draft: string | undefined; + requestId: string; + settle: (result: PredictionResult | PromiseLike) => void; + } +>(); + +/** + * One prediction per session in flight, the newest draft wins. Upstream + * aborts an older request's MODEL call when a newer one arrives, but every + * request first loads the WHOLE transcript from the store, and that load is + * neither abortable nor cheap on a big session: the app asks after every + * typing pause, and on a 4900-message session those loads queued ahead of + * the reads a re-attach and a prompt depend on (session/messages and + * session/subscribe read the same store — observed as 45s and 11s timeouts + * and a failed turn). A superseded ask is released at once with no + * prediction: its caller has moved on to the newer draft. + */ +function inputPrediction( + server: ZcodeAcpServer, + zcodeSid: string, + draft: string | undefined, + requestId: string, +): Promise { + if (predictionInFlight.has(zcodeSid)) { + predictionWaiting.get(zcodeSid)?.settle(null); + return new Promise((settle) => predictionWaiting.set(zcodeSid, { draft, requestId, settle })); + } + const running = requestPrediction(server, zcodeSid, draft, requestId).finally(() => { + predictionInFlight.delete(zcodeSid); + const next = predictionWaiting.get(zcodeSid); + if (!next) return; + predictionWaiting.delete(zcodeSid); + next.settle(inputPrediction(server, zcodeSid, next.draft, next.requestId)); + }); + predictionInFlight.set(zcodeSid, running); + return running; } /** @@ -512,6 +558,12 @@ export async function checkMcpAuthorization(server: ZcodeAcpServer, acpSid: stri clearTimeout(openFallback); entry.openedLocal = true; openLocalBrowser(entry.url); + pushAskNotice({ + kind: "permission", + label: pushSourceLabel(server, acpSid), + title: "MCP authorization required", + body: `Authorize "${entry.serverName}" in browser`, + }); void emitV2Private(server, acpSid, "_zcode/mcp_authorization", { serverName: entry.serverName, openedLocal: true, @@ -589,6 +641,8 @@ export function resetToolsForTests(): void { observed.clear(); turnHeaders.clear(); pendingMcpAuths.clear(); + predictionInFlight.clear(); + predictionWaiting.clear(); } // --------------------------------------------------------------------------- diff --git a/tests/push-if-offline.test.ts b/tests/push-if-offline.test.ts index f99f8c8f..fc74f984 100644 --- a/tests/push-if-offline.test.ts +++ b/tests/push-if-offline.test.ts @@ -38,6 +38,7 @@ const { armAskWatchdog, clearAskWatchdog, noteUserActivity, + pushAskNotice, pushIfOffline, pushInteractionIfOffline, pushSettled, @@ -46,6 +47,7 @@ const { sendTestPush, setPushSenderForTests, } = await import("../src/push/push.js"); +const { BackgroundTaskListener } = await import("../src/handlers/background-tasks.js"); const { ZcodeAcpServer } = await import("../src/server.js"); // pushSourceLabel on a bare server falls back to basename(process.cwd()). @@ -193,3 +195,80 @@ describe("sendTestPush (§7)", () => { expect(sent).toEqual(["[test] Hi"]); }); }); + +describe("V2 WeCom push notifications (subagents, ask notices)", () => { + it("labels subagent completion with session title, subagent kind, and description", async () => { + h.cfg = { contentDetail: "full", notify: { task: true }, quietMs: 0 }; + const server = new ZcodeAcpServer(); + server.registerSession("acp_s1", "zs_s1"); + server.sessionTitles.set("acp_s1", "研究 ACP v2"); + server.notifyByZcodeSid = async () => true; + const btl = new BackgroundTaskListener(server, "zs_s1"); + + btl.handleEvent({ + sessionId: "zs_s1", + seq: 1, + type: "session.updated", + payload: { + taskId: "sub_1", + taskKind: "subagent", + childSessionId: "child_1", + description: "Audit bridge diff", + status: "running", + }, + } as never); + btl.handleEvent({ + sessionId: "zs_s1", + seq: 2, + type: "session.updated", + payload: { + taskId: "sub_1", + taskKind: "subagent", + childSessionId: "child_1", + description: "Audit bridge diff", + status: "completed", + }, + } as never); + await vi.waitFor(() => expect(sent).toHaveLength(1)); + expect(sent[0]).toBe( + `[${PROJ} / 研究 ACP v2] subagent completed\nAudit bridge diff · completed`, + ); + + btl.handleEvent({ + sessionId: "zs_s1", + seq: 3, + type: "session.updated", + payload: { + taskId: "sub_2", + taskKind: "subagent", + childSessionId: "child_2", + description: "Slow review", + status: "timed_out", + }, + } as never); + await vi.waitFor(() => expect(sent).toHaveLength(2)); + expect(sent[1]).toBe(`[${PROJ} / 研究 ACP v2] subagent timed_out\nSlow review · timed_out`); + }); + + it("gates pushAskNotice on push.notify.ask regardless of connected clients", () => { + h.cfg = { contentDetail: "full", notify: { ask: false } }; + pushAskNotice({ + kind: "permission", + label: `${PROJ} / s1`, + title: "MCP authorization required", + body: 'Authorize "github" in browser', + }); + expect(sent).toEqual([]); + + h.cfg = { contentDetail: "full", notify: { ask: true } }; + pushAskNotice({ + kind: "permission", + label: `${PROJ} / s1`, + title: "MCP authorization required", + body: 'Authorize "github" in browser', + }); + expect(sent).toEqual([ + `[${PROJ} / s1] MCP authorization required\nAuthorize "github" in browser`, + ]); + }); +}); diff --git a/tests/rewind.test.ts b/tests/rewind.test.ts index 47fb4cf1..22c7bebe 100644 --- a/tests/rewind.test.ts +++ b/tests/rewind.test.ts @@ -14,9 +14,10 @@ import { editUserMessage, retryTurn } from "../src/handlers/rewind.js"; import { ZcodeAcpServer } from "../src/server.js"; import type { ZcodeBackend } from "../src/backend/client.js"; -/** Recorded v4/conversation/rowsRange + v4/command frames (the wire under test). */ +/** Recorded v4/conversation/rowsRange + v4/command + session/subscribe frames. */ const rowsCalls: Array> = []; const commands: Array> = []; +const subscribeCalls: Array> = []; /** Per-test script: rowsRange answers, then a per-command ack queue. */ let rowsResults: Array | { error: { message: string } }>; @@ -90,6 +91,9 @@ function fakeBackend(): ZcodeBackend { const ack = acks.shift() ?? { status: "accepted" }; return { result: ack }; } + case "session/subscribe": + subscribeCalls.push(params!); + return { result: { eventSeq: 0 } }; case "session/messages": return { result: { messages: storedMessages } }; default: @@ -106,6 +110,7 @@ function fakeBackend(): ZcodeBackend { function setup(): ZcodeAcpServer { rowsCalls.length = 0; commands.length = 0; + subscribeCalls.length = 0; turnStates.length = 0; updates.length = 0; rowsResults = [{ rows: ROWS, atRevision: 11, atLogEpoch: "epoch-1", hasMore: false, atSeq: 4 }]; @@ -446,4 +451,25 @@ describe("claimed replacement turn (BackgroundTaskListener integration)", () => vi.useRealTimers(); } }); + + it("subscribes the backend event stream before rewind on a fresh session, and re-subscribes after unload", async () => { + const server = setup(); + await editUserMessage(server, { sessionId: "sess_rw", messageId: "msg_u1", newText: "x" }); + expect(subscribeCalls).toHaveLength(1); + expect(subscribeCalls[0]).toMatchObject({ + sessionId: "zs_rw", + deliveryKind: "desktop-continuous", + includeSnapshot: false, + }); + + // Idempotent on the same live backend runtime. + await server.ensureBackgroundListener("zs_rw", { subscribe: true }); + expect(subscribeCalls).toHaveLength(1); + + // A runtime eviction/unload drops the backend's subscription flag, so the + // next attach/rewind must re-subscribe. + server.applyLifecycleSnapshot({ sessionId: "zs_rw", state: "unloaded" }); + await server.ensureBackgroundListener("zs_rw", { subscribe: true }); + expect(subscribeCalls).toHaveLength(2); + }); }); diff --git a/tests/session-cancel.test.ts b/tests/session-cancel.test.ts index 98540797..96171982 100644 --- a/tests/session-cancel.test.ts +++ b/tests/session-cancel.test.ts @@ -15,6 +15,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const flushAsync = () => new Promise((resolve) => setImmediate(resolve)); import type { EventStreamListener, TurnMonitor } from "../src/backend/listener.js"; +import { BackgroundTaskListener } from "../src/handlers/background-tasks.js"; import type { ProjectionDiffer } from "../src/translators/projection-differ.js"; import { cancel, runEventTurn } from "../src/handlers/session.js"; import type { PendingTurn, ZcodeAcpServer } from "../src/server.js"; @@ -102,6 +103,52 @@ describe("session/cancel handler", () => { expect(send).not.toHaveBeenCalled(); }); + + it("still fires session/stop + v4 stop when a backend turn runs outside pendingTurns, and settles foreign state", async () => { + const turnStates: boolean[] = []; + const { server, sent } = makeServer([], (sid) => (sid === "acp_a" ? "sess_z" : undefined)); + server.foreignActiveTurns = new Map([["sess_z", "turn_bg"]]); + server.notifyTurnActiveSince = new Map([["sess_z", Date.now()]]); + server.acpSidByZcodeSid = new Map([["sess_z", "acp_a"]]); + server.sessionAliases = (sid: string) => [sid]; + (server as unknown as { clients: unknown }).clients = { + broadcast: () => ({ + notify: async (method: string, params: { running?: boolean }) => { + if (method === "$/zcode/turnState" && typeof params.running === "boolean") { + turnStates.push(params.running); + } + }, + }), + }; + + await cancel(server, { sessionId: "acp_a" } as acp.CancelNotification); + await flushAsync(); + + expect(sent.map((s) => s.method)).toEqual(["session/stop", "v4/command"]); + expect(sent[1]?.params).toMatchObject({ sessionId: "sess_z", type: "stop" }); + expect(server.foreignActiveTurns.has("sess_z")).toBe(false); + expect(server.notifyTurnActiveSince.has("sess_z")).toBe(false); + expect(server.lastCancelledAt.get("sess_z")).toBeGreaterThan(0); + expect(turnStates).toEqual([false]); + }); + + it("does not stop a detached auto-compact when cancelling with no pending or foreign turn", async () => { + const { server, sent } = makeServer([], (sid) => (sid === "acp_a" ? "sess_z" : undefined)); + server.autoCompactInFlight.add("sess_z"); + server.foreignActiveTurns = new Map(); + server.acpSidByZcodeSid = new Map([["sess_z", "acp_a"]]); + + // Compaction's own internal turn emits turn.started on the subscribed stream; + // it must NOT populate foreignActiveTurns or bypass the compact cancel guard. + const btl = new BackgroundTaskListener(server, "sess_z"); + btl.handleEvent({ type: "turn.started", turnId: "turn_compact", payload: {} } as never); + expect(server.foreignActiveTurns.has("sess_z")).toBe(false); + + await cancel(server, { sessionId: "acp_a" } as acp.CancelNotification); + await flushAsync(); + + expect(sent).toEqual([]); + }); }); /** Minimal fixtures for driving runEventTurn's cancel path in isolation. */ diff --git a/tests/v2-prompt.test.ts b/tests/v2-prompt.test.ts index 1e169d8b..8f370659 100644 --- a/tests/v2-prompt.test.ts +++ b/tests/v2-prompt.test.ts @@ -22,6 +22,7 @@ import { conversationOf, hasQueuedInput, ingestV4Frame, + isV4ForegroundActive, resetV4TrackerForTests, revisionSource, } from "../src/v2/queue.js"; @@ -466,9 +467,9 @@ describe("v2 backend-owned turns", () => { await vi.waitFor(() => expect([...server.pendingTurns.values()].some((t) => t.zcodeSid === ZSID)).toBe(true), ); - // The adopted loop replays the start from the log; its listener must be - // registered before the rest of the turn streams. - await vi.waitFor(() => expect(fake.listenerCount()).toBe(2)); + // BackgroundTaskListener + SessionTitleListener (2) plus the synchronously + // attached orphan EventStreamListener (3) before the rest of the turn streams. + await vi.waitFor(() => expect(fake.listenerCount()).toBe(3)); fake.push([ fake.ev("model.streaming", "N1", { kind: "text_delta", @@ -519,7 +520,7 @@ describe("v2 backend-owned turns", () => { }); fake.push([fake.ev("turn.started", "N1", { inputSource: "background_task" })]); - await vi.waitFor(() => expect(fake.listenerCount()).toBe(2)); + await vi.waitFor(() => expect(fake.listenerCount()).toBe(3)); fake.push([ fake.ev("model.streaming", "N1", { kind: "text_delta", @@ -548,6 +549,176 @@ describe("v2 backend-owned turns", () => { expect(meta.turnMs).not.toBe(4414); expect(meta.llmMs).not.toBe(4072); }); + + it("adopts a live backend-owned turn synchronously without a blocking session/subscribe RPC", async () => { + const fake = fakeBackend(); + const origReq = fake.backend.request.bind(fake.backend); + let subscribeAfterAttach = 0; + let blockSubscribe = false; + fake.backend.request = (async (id, method, params, timeoutMs) => { + if (method === "session/subscribe" && blockSubscribe) { + subscribeAfterAttach++; + return { error: { code: -32000, message: "timeout" } }; + } + return origReq(id, method, params, timeoutMs); + }) as typeof fake.backend.request; + + const server = setup(fake.backend); + const client = await attachedClient(server); + await server.ensureBackgroundListener(ZSID); + blockSubscribe = true; + + // A rewind/queued turn starts while session/subscribe would time out on a + // saturated large session — the live listener already rides the active stream. + fake.push([fake.ev("turn.started", "R1", {})]); + // Listener is registered synchronously on the same backend, so immediate + // streaming events land without waiting on any subscribe round trip. + fake.push([ + fake.ev("model.streaming", "R1", { + kind: "text_delta", + delta: "rewound reply", + assistantMessageId: "m_r1", + }), + fake.ev("turn.completed", "R1", { resultType: "success" }), + ]); + + await vi.waitFor(() => + expect( + client + .sessionUpdates(SESSION) + .some((p) => p.update.sessionUpdate === "agent_message_chunk"), + ).toBe(true), + ); + await vi.waitFor(() => + expect([...server.pendingTurns.values()].some((t) => t.zcodeSid === ZSID)).toBe(false), + ); + expect(subscribeAfterAttach).toBe(0); + expect( + client + .sessionUpdates(SESSION) + .filter((p) => p.update.sessionUpdate === "state_update") + .at(-1)?.update, + ).toMatchObject({ state: "idle", stopReason: "end_turn" }); + }); + + it("keeps the session busy and skips queue drain nudge when adoption fails before turn end", async () => { + const fake = fakeBackend({ + v4: (type) => ({ result: { status: "accepted", type } }), + }); + const server = setup(fake.backend); + const client = await attachedClient(server); + await server.ensureBackgroundListener(ZSID); + // Seed a queued auto-drain item in v4 state: a failed adopt must NOT nudge + // it while the backend turn is still running. + ingestV4Frame({ + frame: { + topic: `conversation/${ZSID}`, + payload: { + kind: "snapshot", + revision: 5, + snapshot: { + logEpoch: "ep1", + queue: { items: [{ id: "q1", text: "queued" }], autoDrain: true }, + }, + }, + }, + }); + // Force the fallback adopt path to fail before entering runEventTurn. + const origReq = fake.backend.request.bind(fake.backend); + fake.backend.request = (async (id, method, params, timeoutMs) => { + if (method === "session/subscribe") { + return { error: { code: -32000, message: "timeout" } }; + } + return origReq(id, method, params, timeoutMs); + }) as typeof fake.backend.request; + server.backend = null; + server.ensureBackend = async () => fake.backend; + + const btl = server.backgroundListeners.get(ZSID)!; + btl.handleEvent(fake.ev("turn.started", "F1", {})); + + await vi.waitFor(() => expect(server.foreignActiveTurns.get(ZSID)).toBe("F1")); + await new Promise((r) => setTimeout(r, 30)); + expect( + client + .sessionUpdates(SESSION) + .filter((p) => p.update.sessionUpdate === "state_update") + .some((p) => p.update.state === "idle"), + ).toBe(false); + expect(fake.v4Commands.some((c) => c.type === "setAutoDrain")).toBe(false); + }); + + it("routes a V2 prompt through v4 sendText instead of legacy session/send while v4 control reports running", async () => { + const fake = fakeBackend({ + v4: (type, _payload, env) => + type === "sendText" + ? { + result: { + commandId: env.commandId, + status: "accepted", + result: { type: "inputAccepted", delivery: "queue", inputId: "in_live" }, + }, + } + : { result: { status: "accepted" } }, + }); + const server = setup(fake.backend); + const client = await attachedClient(server); + ingestV4Frame({ + frame: { + topic: `conversation/${ZSID}`, + payload: { + kind: "snapshot", + revision: 9, + snapshot: { + logEpoch: "ep1", + control: { phase: "running", canStop: true, stopState: "stoppable" }, + inputRouting: { mode: "enqueue" }, + }, + }, + }, + }); + + const resp = await client.request("session/prompt", { + sessionId: SESSION, + prompt: [{ type: "text", text: "follow up" }], + }); + expect(resp.result).toMatchObject({ + _meta: { zcode: { delivery: "queued", queueItemId: "queue_in_live" } }, + }); + expect(fake.calls).not.toContain("session/send"); + expect(fake.v4Commands.some((c) => c.type === "sendText")).toBe(true); + + // Backend respawn drops the dead backend's stale v4 control state. + server.resetBackendGeneration(); + expect(isV4ForegroundActive(ZSID)).toBe(false); + }); + + it("settles idle with stopReason error when an adopted turn ends with turn.failed (never wedges running)", async () => { + const fake = fakeBackend(); + const server = setup(fake.backend); + const client = await attachedClient(server); + await server.ensureBackgroundListener(ZSID); + + fake.push([fake.ev("turn.started", "E1", {})]); + fake.push([ + fake.ev("turn.failed", "E1", { + error: { message: "provider exploded", code: "500" }, + }), + ]); + + await vi.waitFor(() => + expect([...server.pendingTurns.values()].some((t) => t.zcodeSid === ZSID)).toBe(false), + ); + expect(server.foreignActiveTurns.has(ZSID)).toBe(false); + const lastState = client + .sessionUpdates(SESSION) + .filter((p) => p.update.sessionUpdate === "state_update") + .at(-1)?.update; + expect(lastState).toMatchObject({ + state: "idle", + stopReason: "error", + }); + }); }); describe("v2 session/close", () => { diff --git a/tests/v2-tools.test.ts b/tests/v2-tools.test.ts index 598cf0c3..fc74fe54 100644 --- a/tests/v2-tools.test.ts +++ b/tests/v2-tools.test.ts @@ -463,6 +463,58 @@ describe("v2 draft completion", () => { ); }); + it("keeps ONE prediction in flight per session: a superseded draft never reaches the backend", async () => { + const { client, backend } = await setup(); + // A slow backend: every prediction settles only when the test says so. + const inFlight: Array<{ params: Record; settle: () => void }> = []; + let live = 0; + let maxLive = 0; + const request = backend.request.bind(backend); + backend.request = (async (id: number, method: string, params: Record = {}) => { + if (method !== "v4/conversation/inputPrediction") return request(id, method, params); + live++; + maxLive = Math.max(maxLive, live); + return new Promise((resolve) => { + inFlight.push({ + params, + settle: () => { + live--; + resolve({ result: { decision: "hide", candidates: [], requestId: params.requestId } }); + }, + }); + }); + }) as typeof backend.request; + // The app asks after every typing pause and does not wait for the previous ask. + for (const [i, draft] of ["r", "ru", "run"].entries()) { + void client.send({ + jsonrpc: "2.0", + id: 100 + i, + method: "_zcode/input_prediction", + params: { sessionId: SESSION, draft, requestId: String(i) }, + }); + } + await vi.waitFor(() => expect(inFlight.length).toBeGreaterThanOrEqual(1)); + // Every chance for the two later asks to reach the backend. + await new Promise((r) => setTimeout(r, 50)); + expect(inFlight.map((c) => c.params.draft)).toEqual(["r"]); + expect(maxLive).toBe(1); + + // The first settles: the drafts that arrived meanwhile collapsed into the + // newest one, and still only one is in flight. + inFlight[0]!.settle(); + await vi.waitFor(() => expect(inFlight.length).toBe(2)); + expect(inFlight[1]!.params.draft).toBe("run"); + inFlight[1]!.settle(); + const answers = () => client.received.filter((m) => [100, 101, 102].includes(m.id as number)); + await vi.waitFor(() => expect(answers()).toHaveLength(3)); + expect(maxLive).toBe(1); + // The newest ask got the backend's own answer. + expect(answers().find((m) => m.id === 102)?.result).toMatchObject({ + decision: "hide", + requestId: "2", + }); + }); + it("offers next-input suggestions to a holder that asked for them once the session is idle", async () => { const { server, client } = await setup( {