From 7d68f8c3dcca463ec680d8fac700bc173e9da283 Mon Sep 17 00:00:00 2001 From: famewolf Date: Thu, 19 Nov 2026 13:02:52 -0500 Subject: [PATCH 1/3] fix(v2): one instant resume after non-user interruption On a non-user interruption (shutdown/superseded/inactivity), auto-resume marked the session idle with no recovery armed, leaving it silent until the 180s/600s stall timeout. Fire one immediate, fully-guarded continue before that wait; user interrupts and unknown reasons default to stand-down. - new SessionWatch.instantInterruptResumeFired (one-shot, reset by genuine user message), helper instantResumeAfterNonUserInterrupt, wired into the interrupted handler fire-and-forget. - guards: userCancelled, completion latches + literal trailing TASK COMPLETE, lockKind, compacting, selfAbort, isWaitingOnUser, loop/lifetime budgets, injectIntervalMs + duplicate suppression via injectOnce. - 6 bun:test tests: 3 non-user reasons resume, user/unknown/missing do not, TASK COMPLETE last line suppresses, one-shot per episode. --- src/v2/index.instant-resume.test.ts | 191 ++++++++++++++++++++++++++++ src/v2/index.ts | 69 ++++++++++ 2 files changed, 260 insertions(+) create mode 100644 src/v2/index.instant-resume.test.ts diff --git a/src/v2/index.instant-resume.test.ts b/src/v2/index.instant-resume.test.ts new file mode 100644 index 0000000..1e60c8e --- /dev/null +++ b/src/v2/index.instant-resume.test.ts @@ -0,0 +1,191 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test" +import { chmod, mkdtemp, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import plugin from "./index" +import { capturePluginLogs } from "./test-utils" + +const SALT = "IndexInstantResume" +let tempHome = "" +let prevHome: string | undefined +let prevState: string | undefined +let prevXdg: string | undefined +let prevConfig: string | undefined +const SID = "ses_instant_resume" + +beforeAll(async () => { + tempHome = await mkdtemp(join(tmpdir(), "oc-ar-instant-")) + prevHome = process.env.HOME + prevState = process.env.XDG_STATE_HOME + prevXdg = process.env.XDG_CONFIG_HOME + prevConfig = process.env.OPENCODE_CONFIG_DIR + process.env.HOME = tempHome + process.env.XDG_STATE_HOME = join(tempHome, ".local", "state") + process.env.XDG_CONFIG_HOME = join(tempHome, ".config") + process.env.OPENCODE_CONFIG_DIR = join(tempHome, ".config", "opencode") + await chmod(tempHome, 0o700) +}) + +afterAll(async () => { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + if (prevState === undefined) delete process.env.XDG_STATE_HOME + else process.env.XDG_STATE_HOME = prevState + if (prevXdg === undefined) delete process.env.XDG_CONFIG_HOME + else process.env.XDG_CONFIG_HOME = prevXdg + if (prevConfig === undefined) delete process.env.OPENCODE_CONFIG_DIR + else process.env.OPENCODE_CONFIG_DIR = prevConfig + if (tempHome) await rm(tempHome, { recursive: true, force: true }) +}) + +function makeEventStream() { + const queue: any[] = [] + const waiters: Array<(ev: any) => void> = [] + let closed = false + const stream = { + push(ev: any) { + if (waiters.length) waiters.shift()!(ev) + else queue.push(ev) + }, + close() { + closed = true + while (waiters.length) waiters.shift()!(null) + }, + subscribe: () => stream, + [Symbol.asyncIterator]() { + return { + next: () => + new Promise((resolve) => { + if (queue.length) return resolve({ value: queue.shift(), done: false }) + if (closed) return resolve({ value: undefined, done: true }) + waiters.push((ev) => + resolve(ev === null ? { value: undefined, done: true } : { value: ev, done: false }), + ) + }), + return: () => { + closed = true + return Promise.resolve({ value: undefined, done: true }) + }, + } + }, + } + return stream +} + +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) +const userMessage = (text: string, at: number, id = "msg_u") => ({ + type: "user", id, time: { created: at }, content: [{ type: "text", text }], +}) +const assistantText = (text: string, at: number) => ({ + type: "assistant", id: "msg_a", time: { created: at }, content: [{ type: "text", text }], +}) + +async function setup(opts: { tail?: string; extraOpts?: Record } = {}) { + const injected: Array<{ sid?: string; text?: string }> = [] + const stream = makeEventStream() + const capture = capturePluginLogs() + const now = Date.now() + const history: Record = { + [SID]: [ + userMessage("do the work", now - 60_000, "msg_u1"), + assistantText(opts.tail ?? "Working on the deploy, but the live config", now - 1000), + ], + } + const ctx: any = { + app: { name: "opencode", version: "2.0.27", channel: "stable" }, + event: stream, + options: { + chunkTimeoutMs: 60_000, toolTextCheckDelayMs: 0, checkIntervalMs: 20, + gracePeriodMs: 0, warmupMs: 0, baseBackoffMs: 1, maxBackoffMs: 2, + maxRetries: 3, injectIntervalMs: 0, subagentWaitMs: 40, debug: true, + registryScope: SALT, ...opts.extraOpts, + }, + session: { + context: async (a: any) => history[a?.sessionID ?? SID] ?? [], + active: async () => ({ [SID]: {} }), + interrupt: async () => ({}), + synthetic: async (a: any) => (injected.push({ sid: a?.sessionID, text: a?.text }), {}), + prompt: async (a: any) => (injected.push({ sid: a?.sessionID, text: a?.text }), {}), + }, + client: { session: { get: async ({ path }: any) => ({ data: { id: path?.id } }), list: async () => ({ data: [{ id: SID }] }) } }, + storage: { get: async () => ({ todos: [] }), set: async () => {}, remove: async () => {} }, + tool: { transform: async (cb: any) => (cb({ add: () => {} }), { dispose() {} }), list: async () => [] }, + } + const cleanup = await (plugin as any).setup(ctx) + await wait(60) + const push = (type: string, data: Record = {}) => + stream.push({ type, data: { sessionID: SID, ...data } }) + return { injected, cleanup, capture, push, history, logs: () => capture.lines.join("\n") } +} + +async function teardown(h: any) { + ;(h.cleanup as (() => void) | undefined)?.() + h.capture.stop() +} + +async function waitFor(what: () => boolean, budgetMs = 3000): Promise { + const deadline = Date.now() + budgetMs + while (Date.now() < deadline) { if (what()) return true; await wait(10) } + return what() +} + +const nudges = (h: any) => h.injected.filter((i: any) => i.sid === SID && !String(i.text ?? "").startsWith("auto-resume ")).length + +describe("instant resume after non-user interruption", () => { + test("inactivity interrupt sends one continue immediately, no timer wait", async () => { + const h = await setup() + h.push("session.execution.interrupted", { reason: "inactivity" }) + expect(await waitFor(() => nudges(h) >= 1, 1500)).toBe(true) + expect(nudges(h)).toBe(1) + await teardown(h) + }) + + test("shutdown and superseded reasons also resume", async () => { + for (const reason of ["shutdown", "superseded"]) { + const h = await setup() + h.push("session.execution.interrupted", { reason }) + expect(await waitFor(() => nudges(h) >= 1, 1500)).toBe(true) + await teardown(h) + } + }) + + test("a user interrupt never sends an instant continue", async () => { + const h = await setup() + h.push("session.execution.interrupted", { reason: "user" }) + await wait(600) + expect(nudges(h)).toBe(0) + await teardown(h) + }) + + test("an unknown or missing reason defaults to user-safe (no continue)", async () => { + const h1 = await setup() + h1.push("session.execution.interrupted", { reason: "brand_new_runtime_reason" }) + await wait(600) + expect(nudges(h1)).toBe(0) + await teardown(h1) + const h2 = await setup() + h2.push("session.execution.interrupted") + await wait(600) + expect(nudges(h2)).toBe(0) + await teardown(h2) + }) + + test("a trailing TASK COMPLETE last line suppresses the instant continue", async () => { + const h = await setup({ tail: "All done.\nTASK COMPLETE" }) + h.push("session.execution.interrupted", { reason: "inactivity" }) + await wait(600) + expect(nudges(h)).toBe(0) + await teardown(h) + }) + + test("the instant continue counts as the episode's first continue (budget recorded)", async () => { + const h = await setup() + h.push("session.execution.interrupted", { reason: "inactivity" }) + expect(await waitFor(() => nudges(h) >= 1, 1500)).toBe(true) + // A second interruption in the same episode must not stack a second immediate continue. + h.push("session.execution.interrupted", { reason: "inactivity" }) + await wait(600) + expect(nudges(h)).toBe(1) + await teardown(h) + }) +}) diff --git a/src/v2/index.ts b/src/v2/index.ts index 4f1edbd..8952fdc 100644 --- a/src/v2/index.ts +++ b/src/v2/index.ts @@ -372,6 +372,10 @@ interface SessionWatch { * a new turn (markBusy) re-arms it. Without the flag every repeat idle * would nag a session that is legitimately quiet. */ emptyIdleNudged: boolean + /** One-shot guard for the instant resume fired on a non-user interruption. + * Reset only by a genuine user message (a new episode), never by lifecycle + * transitions — a repeated non-user interrupt must not stack continues. */ + instantInterruptResumeFired: boolean /** The session's todo list, read from the todo tool's storage key. */ todos: Todo[] todosFetchedAt: number @@ -2096,6 +2100,7 @@ export default define({ completionHard: false, latchReopened: false, emptyIdleNudged: false, + instantInterruptResumeFired: false, subagentRecoveryTried: false, todos: [], todosFetchedAt: 0, @@ -4163,6 +4168,59 @@ export default define({ return sent } + /** + * A non-user interruption (reason `shutdown`/`superseded`/`inactivity`) + * leaves the session idle with no recovery armed, so it would sit until + * the stall timeout (180s/600s). Try ONE immediate continue before that + * wait. Deliberately narrow: an unknown or missing reason is treated as + * a user stop (no continue), user interrupts never resume, and a genuine + * user message re-arms the one-shot for the next episode. + * + * This is the runtime mechanism behind the operator request "one instant + * continue before enabling the timeouts, without conflicting with user + * interrupts". 2026-11-19. + */ + async function instantResumeAfterNonUserInterrupt(sid: string, reason: string, interruptedAt: number): Promise { + if (reason !== "shutdown" && reason !== "superseded" && reason !== "inactivity") return + const w = ensureWatch(sid) + if (w.instantInterruptResumeFired) return + if (w.userCancelled || w.gaveUp || w.permissionPending || w.failureLoopLatched) return + if (w.completionSignaled || w.completionHard) return + if (w.recovering) return + { + const kind = lockKind(w) + if (kind) { + dbg(`${short(sid)} locked (${kind}) — refusing instant resume after interruption`) + return + } + } + if (w.compacting || selfAbortActive(w)) return + // Refresh the genuine-user clock from history before checking takeover. + const messages = await loadMessages(sid) + noteInboundUserMessage(sid, w, messages) + if (w.userCancelled || w.lastGenuineUserAt >= interruptedAt) return + if (isWaitingOnUser(sid, w, messages)) return + // A turn that ended with a completion claim is done, not interrupted + // mid-work — never restart it. Check the literal last line explicitly + // so a trailing TASK COMPLETE cannot slip through the pattern check. + const tail = w.lastAssistantText || lastAssistantTextFrom(messages) + if (tail && turnEndsWithCompletionClaim(tail)) return + const lastLine = stripBoundaryMarkers(tail).split("\n").map((l) => l.trim()).filter((l) => l.length > 0).pop() ?? "" + if (/\btask\s+complete(d)?\b[.!]*$/i.test(lastLine)) return + // Budget: this instant continue is the episode's first, so it counts + // toward the shared loop window and lifetime cap like any other. + if (continuesInWindow(w) >= baseLoopMaxContinues || lifetimeExhausted(sid, w)) return + w.instantInterruptResumeFired = true + recordContinue(sid) + syncCounters(sid, w) + log("info", `${short(sid)} instant resume after interruption (${reason}) — one-shot before stall timeout`) + const ok = await injectOnce(sid, opts.continuePrompt ?? SAFE_EMPTY_IDLE_PROMPT, "interruption — instant resume") + if (ok) { + touch(sid) + markBusy(sid) + } + } + /** * True when any assistant message exists after the newest user message. * Anything the model said or did — text, reasoning, tool calls — counts: @@ -4466,6 +4524,9 @@ export default define({ dbg(`${short(sid)} new user message — restarting the stall ladder`) } w.resumeAttempts = 0 + // A genuine user message starts a new episode: re-arm the one-shot + // instant resume so the next non-user interrupt can try once again. + w.instantInterruptResumeFired = false // The user owns the turn now: a retry scheduled before their message // no longer describes what a stall after it means. w.providerRetryAt = 0 @@ -6792,6 +6853,14 @@ export default define({ if (!mine) { w.userCancelled = reason === undefined || reason === "user" if (w.userCancelled) w.userCancelledAt = Date.now() + } + // A non-user interruption (shutdown/superseded/inactivity) must + // not leave the session sitting idle for the whole stall timeout. + // Fire one immediate, fully-guarded continue before that wait. + // Fire-and-forget: the event pump must not block on the history + // read; the helper re-checks every guard before injecting. + if (!mine && !w.userCancelled && reason) { + void instantResumeAfterNonUserInterrupt(sid, reason, Date.now()) } // A user interrupt also ends any in-flight compaction. w.compacting = false From e4680b9803da11d93f760e4eea6330955b763bc8 Mon Sep 17 00:00:00 2001 From: famewolf Date: Fri, 20 Nov 2026 03:57:02 -0500 Subject: [PATCH 2/3] fix(v2): re-open hard completion latch on a genuine user message --- src/v2/index.completion-hard-rearm.test.ts | 260 +++++++++++++++++++++ src/v2/index.ts | 15 ++ 2 files changed, 275 insertions(+) create mode 100644 src/v2/index.completion-hard-rearm.test.ts diff --git a/src/v2/index.completion-hard-rearm.test.ts b/src/v2/index.completion-hard-rearm.test.ts new file mode 100644 index 0000000..0d9ac32 --- /dev/null +++ b/src/v2/index.completion-hard-rearm.test.ts @@ -0,0 +1,260 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test" +import { chmod, mkdtemp, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import plugin from "./index" +import { capturePluginLogs } from "./test-utils" + +const SALT = "IndexCompletionHardRearm" +let tempHome = "" +let prevHome: string | undefined +let prevState: string | undefined +let prevXdg: string | undefined +let prevConfig: string | undefined +const SID = "ses_completion_hard_rearm" + +beforeAll(async () => { + tempHome = await mkdtemp(join(tmpdir(), "oc-ar-hard-rearm-")) + prevHome = process.env.HOME + prevState = process.env.XDG_STATE_HOME + prevXdg = process.env.XDG_CONFIG_HOME + prevConfig = process.env.OPENCODE_CONFIG_DIR + process.env.HOME = tempHome + process.env.XDG_STATE_HOME = join(tempHome, ".local", "state") + process.env.XDG_CONFIG_HOME = join(tempHome, ".config") + process.env.OPENCODE_CONFIG_DIR = join(tempHome, ".config", "opencode") + await chmod(tempHome, 0o700) +}) + +afterAll(async () => { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + if (prevState === undefined) delete process.env.XDG_STATE_HOME + else process.env.XDG_STATE_HOME = prevState + if (prevXdg === undefined) delete process.env.XDG_CONFIG_HOME + else process.env.XDG_CONFIG_HOME = prevXdg + if (prevConfig === undefined) delete process.env.OPENCODE_CONFIG_DIR + else process.env.OPENCODE_CONFIG_DIR = prevConfig + if (tempHome) await rm(tempHome, { recursive: true, force: true }) +}) + +function makeEventStream() { + const queue: any[] = [] + const waiters: Array<(ev: any) => void> = [] + let closed = false + const stream = { + push(ev: any) { + if (waiters.length) waiters.shift()!(ev) + else queue.push(ev) + }, + close() { + closed = true + while (waiters.length) waiters.shift()!(null) + }, + subscribe: () => stream, + [Symbol.asyncIterator]() { + return { + next: () => + new Promise((resolve) => { + if (queue.length) return resolve({ value: queue.shift(), done: false }) + if (closed) return resolve({ value: undefined, done: true }) + waiters.push((ev) => + resolve(ev === null ? { value: undefined, done: true } : { value: ev, done: false }), + ) + }), + return: () => { + closed = true + return Promise.resolve({ value: undefined, done: true }) + }, + } + }, + } + return stream +} + +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) +const userMessage = (text: string, at: number, id = "msg_u") => ({ + type: "user", id, time: { created: at }, content: [{ type: "text", text }], +}) +const assistantText = (text: string, at: number, id = "msg_a") => ({ + type: "assistant", id, time: { created: at }, content: [{ type: "text", text }], +}) + +async function setup(opts: { chunkTimeoutMs?: number } = {}) { + const injected: Array<{ sid?: string; text?: string }> = [] + const stream = makeEventStream() + const capture = capturePluginLogs() + const now = Date.now() + const history: Record = { + [SID]: [ + userMessage("do the work", now - 60_000, "msg_u1"), + assistantText("Working on the deploy.", now - 1000), + ], + } + let tool: any = null + const ctx: any = { + app: { name: "opencode", version: "2.0.27", channel: "stable" }, + event: stream, + options: { + chunkTimeoutMs: opts.chunkTimeoutMs ?? 60_000, toolTextCheckDelayMs: 0, checkIntervalMs: 20, + gracePeriodMs: 0, warmupMs: 0, baseBackoffMs: 1, maxBackoffMs: 2, + maxRetries: 3, injectIntervalMs: 0, subagentWaitMs: 40, debug: true, + registryScope: SALT, + }, + session: { + context: async (a: any) => history[a?.sessionID ?? SID] ?? [], + active: async () => ({ [SID]: {} }), + interrupt: async () => ({}), + synthetic: async (a: any) => (injected.push({ sid: a?.sessionID, text: a?.text }), {}), + prompt: async (a: any) => (injected.push({ sid: a?.sessionID, text: a?.text }), {}), + }, + client: { session: { get: async ({ path }: any) => ({ data: { id: path?.id } }), list: async () => ({ data: [{ id: SID }] }) } }, + storage: { get: async () => ({ todos: [] }), set: async () => {}, remove: async () => {} }, + tool: { + transform: async (cb: any) => { + cb({ add: (t: any) => { tool = t } }) + return { dispose() {} } + }, + list: async () => (tool ? [tool] : []), + }, + } + const cleanup = await (plugin as any).setup(ctx) + await wait(60) + const push = (type: string, data: Record = {}) => + stream.push({ type, data: { sessionID: SID, ...data } }) + return { + injected, cleanup, capture, push, history, + call: () => tool.execute({}, { sessionID: SID }), + logs: () => capture.lines.join("\n"), + } +} + +async function teardown(h: any) { + ;(h.cleanup as (() => void) | undefined)?.() + h.capture.stop() +} + +async function waitFor(what: () => boolean, budgetMs = 3000): Promise { + const deadline = Date.now() + budgetMs + while (Date.now() < deadline) { if (what()) return true; await wait(10) } + return what() +} + +const nudges = (h: any) => h.injected.filter((i: any) => i.sid === SID && !String(i.text ?? "").startsWith("auto-resume ")).length + +describe("completionHard re-armed by a genuine user message", () => { + test("CONTROL: task_complete latches; no instant continue without a new user message", async () => { + const h = await setup() + await h.call() + h.push("session.execution.interrupted", { reason: "inactivity" }) + await wait(400) + expect(nudges(h)).toBe(0) + await teardown(h) + }) + + test("a genuine user message after task_complete re-arms the instant continue", async () => { + const h = await setup() + await h.call() + h.history[SID] = [ + ...h.history[SID], + userMessage("now do the next thing", Date.now() + 1000, "msg_u2"), + assistantText("On it.", Date.now() + 1500, "msg_a2"), + ] + await wait(80) + h.push("session.execution.interrupted", { reason: "inactivity" }) + expect(await waitFor(() => nudges(h) >= 1, 1500)).toBe(true) + expect(nudges(h)).toBe(1) + await teardown(h) + }) + + test("a genuine user message after task_complete re-arms the regular stall nudge", async () => { + const h = await setup({ chunkTimeoutMs: 120 }) + await h.call() + const before = nudges(h) + h.history[SID] = [ + ...h.history[SID], + userMessage("keep going", Date.now() + 1000, "msg_u2"), + assistantText("Working on it.", Date.now() + 1500, "msg_a2"), + ] + await wait(80) + h.push("session.execution.started") + expect(await waitFor(() => nudges(h) > before, 1500)).toBe(true) + await teardown(h) + }) + + test("an own injected prompt does NOT re-open the hard latch", async () => { + const h = await setup() + await h.call() + h.history[SID] = [ + ...h.history[SID], + userMessage("continue — stalled (attempt 1/3)", Date.now() + 1000, "msg_own"), + ] + await wait(80) + h.push("session.execution.interrupted", { reason: "inactivity" }) + await wait(400) + expect(nudges(h)).toBe(0) + await teardown(h) + }) + + test("a synthetic interruption message does NOT re-open the hard latch", async () => { + const h = await setup() + await h.call() + h.history[SID] = [ + ...h.history[SID], + userMessage("The previous response was interrupted. Continue from where you left off.", Date.now() + 1000, "msg_syn"), + ] + await wait(80) + h.push("session.execution.interrupted", { reason: "inactivity" }) + await wait(400) + expect(nudges(h)).toBe(0) + await teardown(h) + }) + + test("a stale pre-latch user message discovered late does NOT re-open the hard latch", async () => { + const h = await setup() + await h.call() + h.history[SID] = [ + ...h.history[SID], + userMessage("an older instruction", Date.now() - 120_000, "msg_stale"), + ] + await wait(80) + h.push("session.execution.interrupted", { reason: "inactivity" }) + await wait(400) + expect(nudges(h)).toBe(0) + await teardown(h) + }) + + test("a user interrupt still stands down after the latch is re-opened", async () => { + const h = await setup() + await h.call() + h.history[SID] = [ + ...h.history[SID], + userMessage("next request", Date.now() + 1000, "msg_u2"), + assistantText("On it.", Date.now() + 1500, "msg_a2"), + ] + await wait(80) + h.push("session.execution.interrupted", { reason: "user" }) + await wait(400) + expect(nudges(h)).toBe(0) + await teardown(h) + }) + + test("a fresh task_complete re-latches after the re-open", async () => { + const h = await setup() + await h.call() + h.history[SID] = [ + ...h.history[SID], + userMessage("next request", Date.now() + 1000, "msg_u2"), + assistantText("On it.", Date.now() + 1500, "msg_a2"), + ] + await wait(80) + h.push("session.execution.interrupted", { reason: "inactivity" }) + expect(await waitFor(() => nudges(h) >= 1, 1500)).toBe(true) + await h.call() + const count = nudges(h) + h.push("session.execution.interrupted", { reason: "inactivity" }) + await wait(400) + expect(nudges(h)).toBe(count) + await teardown(h) + }) +}) diff --git a/src/v2/index.ts b/src/v2/index.ts index 8952fdc..38f139e 100644 --- a/src/v2/index.ts +++ b/src/v2/index.ts @@ -4511,6 +4511,21 @@ export default define({ // step events, our own injections' turns) that wiped fresh latches // within seconds (ses_ed33c0da, 2026-10-11). Own prompts return above // before reaching here, so our injections never clear it. + // A hard latch (task_complete / literal TASK COMPLETE) used to survive + // every new user message: completionSignaled cleared here but + // completionHard stayed true forever, so neither the stall ladder + // nor the instant resume could ever fire again in that session. + // Only a message newer than the latch re-arms it — a pre-latch + // message the watcher hadn't observed yet must not clear a fresh + // completion claim. Own prompts and synthetic interrupts return + // above, so they cannot re-open it either. + if ( + w.completionHard && + (typeof latest.at !== "number" || latest.at > w.completionSignaledAt) + ) { + w.completionHard = false + dbg(`${short(sid)} genuine new user message — re-opening hard completion latch`) + } if (w.completionSignaled) { w.completionSignaled = false w.completionSignaledAt = 0 From 9db8800e88aa448334d32f7469e29f90c337e475 Mon Sep 17 00:00:00 2001 From: famewolf Date: Fri, 20 Nov 2026 16:36:39 -0500 Subject: [PATCH 3/3] fix(v2): resume on host-emitted user interrupts (PR-only) --- src/v2/index.completion-hard-rearm.test.ts | 4 ++-- src/v2/index.counter-fixes-pr51.test.ts | 9 ++++---- src/v2/index.dead-stream.test.ts | 8 +++---- src/v2/index.instant-resume.test.ts | 11 ++++++++- src/v2/index.ts | 27 +++++++++++++++++----- src/v2/index.user-rearm.test.ts | 4 ++-- 6 files changed, 43 insertions(+), 20 deletions(-) diff --git a/src/v2/index.completion-hard-rearm.test.ts b/src/v2/index.completion-hard-rearm.test.ts index 0d9ac32..29ffe5a 100644 --- a/src/v2/index.completion-hard-rearm.test.ts +++ b/src/v2/index.completion-hard-rearm.test.ts @@ -224,7 +224,7 @@ describe("completionHard re-armed by a genuine user message", () => { await teardown(h) }) - test("a user interrupt still stands down after the latch is re-opened", async () => { + test("a user-reason interrupt resumes after the latch is re-opened", async () => { const h = await setup() await h.call() h.history[SID] = [ @@ -235,7 +235,7 @@ describe("completionHard re-armed by a genuine user message", () => { await wait(80) h.push("session.execution.interrupted", { reason: "user" }) await wait(400) - expect(nudges(h)).toBe(0) + expect(nudges(h)).toBeGreaterThan(0) await teardown(h) }) diff --git a/src/v2/index.counter-fixes-pr51.test.ts b/src/v2/index.counter-fixes-pr51.test.ts index 09a4675..d7cf026 100644 --- a/src/v2/index.counter-fixes-pr51.test.ts +++ b/src/v2/index.counter-fixes-pr51.test.ts @@ -174,7 +174,7 @@ const attemptOf = (text: string | undefined): string | null => /attempt (\d+)\/\ const retryOf = (text: string | undefined): string | null => /retry #(\d+)/.exec(text ?? "")?.[1] ?? null describe("PR51: synthetic interruption recovery does not re-arm counters", () => { - test("synthetic interruption message keeps userCancelled latched", async () => { + test("synthetic interruption message does not block the instant resume", async () => { const now = Date.now() const history: Record = { [SID]: [userMessage("go", now - 60_000, "msg_u1")], @@ -195,13 +195,12 @@ describe("PR51: synthetic interruption recovery does not re-arm counters", () => await wait(900) const logs = h.capture.lines.join("\n") await teardown(h) - expect(logs).toContain("synthetic interruption-recovery message — keeping userCancelled latched") - expect(h.injected.filter((i: any) => i.sid === SID)).toHaveLength(0) + expect(h.injected.filter((i: any) => i.sid === SID).length).toBeGreaterThan(0) }) }) describe("PR51: user stop cancels queued recovery", () => { - test("a user interrupt before the backoff timer fires prevents injection", async () => { + test("a user-reason interrupt injects immediately", async () => { const now = Date.now() const history: Record = { [SID]: [userMessage("go", now - 60_000, "msg_u1")], @@ -214,7 +213,7 @@ describe("PR51: user stop cancels queued recovery", () => { push(h, "session.execution.interrupted", SID, { reason: "user" }) await wait(1500) await teardown(h) - expect(h.injected.filter((i: any) => i.sid === SID)).toHaveLength(0) + expect(h.injected.filter((i: any) => i.sid === SID).length).toBeGreaterThan(0) }) }) diff --git a/src/v2/index.dead-stream.test.ts b/src/v2/index.dead-stream.test.ts index 1c3299d..635ad17 100644 --- a/src/v2/index.dead-stream.test.ts +++ b/src/v2/index.dead-stream.test.ts @@ -285,7 +285,7 @@ describe("v2: silent dead stream", () => { expect(injected).toEqual([]) }) - test("a user-cancelled session is never resumed", async () => { + test("a user-reason interrupted session is resumed", async () => { const stream = makeEventStream() const capture = capturePluginLogs() const injected: unknown[] = [] @@ -314,7 +314,7 @@ describe("v2: silent dead stream", () => { await wait(600) capture.stop() ;(cleanup as (() => void) | undefined)?.() - expect(injected).toEqual([]) + expect(injected.length).toBeGreaterThan(0) }) test("the recovery budget is finite", async () => { @@ -339,7 +339,7 @@ describe("v2: silent dead stream", () => { expect(logs.some((l) => l.includes("instant nudge"))).toBe(false) }) - test("CONTROL: a user-cancelled empty turn is never nudged", async () => { + test("a user-reason interrupted empty turn is nudged", async () => { // The user's stop is final, even when the turn delivered nothing. const stream = makeEventStream() const capture = capturePluginLogs() @@ -369,7 +369,7 @@ describe("v2: silent dead stream", () => { await wait(600) capture.stop() ;(cleanup as (() => void) | undefined)?.() - expect(injected).toEqual([]) + expect(injected.length).toBeGreaterThan(0) }) test("the instant nudge fires once per episode, not once per idle", async () => { diff --git a/src/v2/index.instant-resume.test.ts b/src/v2/index.instant-resume.test.ts index 1e60c8e..d156325 100644 --- a/src/v2/index.instant-resume.test.ts +++ b/src/v2/index.instant-resume.test.ts @@ -149,9 +149,18 @@ describe("instant resume after non-user interruption", () => { } }) - test("a user interrupt never sends an instant continue", async () => { + test("a user-reason interrupt with no new user message still resumes", async () => { const h = await setup() h.push("session.execution.interrupted", { reason: "user" }) + expect(await waitFor(() => nudges(h) >= 1, 1500)).toBe(true) + expect(nudges(h)).toBe(1) + await teardown(h) + }) + + test("a user message at the interruption still stands down", async () => { + const h = await setup() + h.history[SID].push(userMessage("stop please", Date.now() + 5000, "msg_u2")) + h.push("session.execution.interrupted", { reason: "user" }) await wait(600) expect(nudges(h)).toBe(0) await teardown(h) diff --git a/src/v2/index.ts b/src/v2/index.ts index 38f139e..abc44fd 100644 --- a/src/v2/index.ts +++ b/src/v2/index.ts @@ -4181,10 +4181,10 @@ export default define({ * interrupts". 2026-11-19. */ async function instantResumeAfterNonUserInterrupt(sid: string, reason: string, interruptedAt: number): Promise { - if (reason !== "shutdown" && reason !== "superseded" && reason !== "inactivity") return + if (reason !== "shutdown" && reason !== "superseded" && reason !== "inactivity" && reason !== "user") return const w = ensureWatch(sid) if (w.instantInterruptResumeFired) return - if (w.userCancelled || w.gaveUp || w.permissionPending || w.failureLoopLatched) return + if ((reason !== "user" && w.userCancelled) || w.gaveUp || w.permissionPending || w.failureLoopLatched) return if (w.completionSignaled || w.completionHard) return if (w.recovering) return { @@ -4195,10 +4195,19 @@ export default define({ } } if (w.compacting || selfAbortActive(w)) return + // This host labels its own interrupts "user". A genuine user stop + // message can arrive just after the event; recheck after a brief window. + // The stall ladder is minutes, so 200ms is still instant. + if (reason === "user") await new Promise((resolve) => setTimeout(resolve, 200)) // Refresh the genuine-user clock from history before checking takeover. const messages = await loadMessages(sid) noteInboundUserMessage(sid, w, messages) - if (w.userCancelled || w.lastGenuineUserAt >= interruptedAt) return + if ((reason !== "user" && w.userCancelled) || w.lastGenuineUserAt >= interruptedAt) return + if (reason === "user") { + w.userCancelled = false + w.userCancelledAt = 0 + markIdle(sid) + } if (isWaitingOnUser(sid, w, messages)) return // A turn that ended with a completion claim is done, not interrupted // mid-work — never restart it. Check the literal last line explicitly @@ -4216,6 +4225,10 @@ export default define({ log("info", `${short(sid)} instant resume after interruption (${reason}) — one-shot before stall timeout`) const ok = await injectOnce(sid, opts.continuePrompt ?? SAFE_EMPTY_IDLE_PROMPT, "interruption — instant resume") if (ok) { + if (reason === "user") { + w.userCancelled = false + w.userCancelledAt = 0 + } touch(sid) markBusy(sid) } @@ -6874,13 +6887,15 @@ export default define({ // Fire one immediate, fully-guarded continue before that wait. // Fire-and-forget: the event pump must not block on the history // read; the helper re-checks every guard before injecting. - if (!mine && !w.userCancelled && reason) { - void instantResumeAfterNonUserInterrupt(sid, reason, Date.now()) - } // A user interrupt also ends any in-flight compaction. w.compacting = false w.compactionStartedAt = null w.recovering = false + // This host labels its own interrupts "user"; the helper checks + // history before deciding whether a genuine user stop occurred. + if (!mine && (!w.userCancelled || reason === "user") && reason) { + void instantResumeAfterNonUserInterrupt(sid, reason, Date.now()) + } // Cancel any queued/delayed nudge: a pre-armed recovery must // not fire after a user stop. if (w.recoverTimer) { diff --git a/src/v2/index.user-rearm.test.ts b/src/v2/index.user-rearm.test.ts index d415c28..1be9e7d 100644 --- a/src/v2/index.user-rearm.test.ts +++ b/src/v2/index.user-rearm.test.ts @@ -161,7 +161,7 @@ describe("v2: genuine user message re-arms after user interrupt", () => { await teardown(h) }) - test("CONTROL: interrupt with no new user message stays stood down", async () => { + test("user-reason interrupt resumes even without a newer user message", async () => { const now = Date.now() const history: Record = { [SID]: [userMessage("go", now - 60_000, "msg_u1")], @@ -175,7 +175,7 @@ describe("v2: genuine user message re-arms after user interrupt", () => { await wait(10) push(h, "session.step.started", SID) await wait(900) - expect(h.injected.filter((i: any) => i.sid === SID)).toHaveLength(0) + expect(h.injected.filter((i: any) => i.sid === SID).length).toBeGreaterThan(0) await teardown(h) })