From 45b5bd4694174b926df3adfedd722c19e1010a8a Mon Sep 17 00:00:00 2001 From: Dan Smolsky <78942835+Tarquinen@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:33:45 -0500 Subject: [PATCH] feat: undo when interrupting before the model answers (#65505) --- .../app/e2e/regression/session-queue.spec.ts | 35 +++++++ packages/app/e2e/utils/mock-server.ts | 7 +- packages/app/src/session/composer/adapter.ts | 20 +++- .../app/src/session/composer/controller.ts | 2 + packages/app/src/session/composer/region.tsx | 1 + packages/app/src/session/revert.ts | 24 ++++- .../app/src/session/session-domain.test.ts | 28 +++++- packages/app/src/session/session-domain.ts | 22 +++++ packages/tui/src/component/prompt/index.tsx | 43 +++++++- .../tui/test/session-interrupt-undo.test.tsx | 98 +++++++++++++++++++ 10 files changed, 266 insertions(+), 14 deletions(-) create mode 100644 packages/tui/test/session-interrupt-undo.test.tsx diff --git a/packages/app/e2e/regression/session-queue.spec.ts b/packages/app/e2e/regression/session-queue.spec.ts index 78c06627e80..8f376fdb93c 100644 --- a/packages/app/e2e/regression/session-queue.spec.ts +++ b/packages/app/e2e/regression/session-queue.spec.ts @@ -341,6 +341,41 @@ test("a blank Enter leaves the running session alone while Stop still interrupts expect(mock.prompts).toEqual([]) }) +test("stopping before the model answers takes the prompt back, as in the TUI", async ({ page }) => { + const mock = createQueueMock( + [], + [ + { id: "msg_queue_unanswered", type: "user", text: "Reword this prompt", time: { created: 1 } }, + { + id: "msg_queue_thinking", + type: "assistant", + agent: "build", + model: { id: "queue-model", providerID: "opencode" }, + content: [{ type: "reasoning", text: "Thinking it over" }], + time: { created: 2 }, + }, + ], + ) + + const view = await openQueue(page, mock) + const requests: string[] = [] + page.on("request", (request) => { + const path = new URL(request.url()).pathname + + const step = ["/interrupt", "/wait", "/revert/stage", "/revert/commit"].find((suffix) => + path.endsWith(`/${sessionID}${suffix}`), + ) + + if (step) requests.push(step) + }) + + await expect(userRow(page, "msg_queue_unanswered")).toBeVisible() + await view.input.press("Escape") + + await expect.poll(() => requests).toEqual(["/interrupt", "/wait", "/revert/stage", "/revert/commit"]) + await expect(view.input).toHaveText("Reword this prompt") +}) + test.describe("touch keyboard", () => { test.use({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true }) diff --git a/packages/app/e2e/utils/mock-server.ts b/packages/app/e2e/utils/mock-server.ts index 624d288a45c..32e30a883e7 100644 --- a/packages/app/e2e/utils/mock-server.ts +++ b/packages/app/e2e/utils/mock-server.ts @@ -1444,8 +1444,11 @@ function mockHandlers( Effect.andThen(noContent), ) }, - // Like the server for an idle session: nothing was running to interrupt. - sessionInterrupt: () => Effect.succeed({ interrupted: false }), + // Like the server: an idle session has nothing running to interrupt. + sessionInterrupt: (ctx) => + Effect.succeed({ + interrupted: resolve(config.sessionStatus ?? {})[ctx.params.sessionID]?.type === "running", + }), // The mock runs no agent loop, so every session is already idle. sessionWait: () => noContent, sessionRevertStage: (ctx) => { diff --git a/packages/app/src/session/composer/adapter.ts b/packages/app/src/session/composer/adapter.ts index 3f4e96a44c0..4a1e61274fc 100644 --- a/packages/app/src/session/composer/adapter.ts +++ b/packages/app/src/session/composer/adapter.ts @@ -14,6 +14,7 @@ export function createActiveComposerAdapter(input: { submitted: () => void setEditor: (element: HTMLDivElement) => void background: NonNullable + takeBack: () => Promise }) { const id = input.sessionID @@ -53,11 +54,20 @@ export function createActiveComposerAdapter(input: { admitted: (messageID) => data.session.input.has(id, messageID) || !!data.session.message.get(id, messageID), background: input.background, }), - interrupt: () => - server.api.session - .interrupt({ sessionID: id, resume: true }) - .then(() => undefined) - .catch(() => undefined), + // Stopping before the model has answered with text or a tool call takes the prompt back, as undo does: the + // likeliest reason to stop that early is to reword what was just sent. A draft or a pending prompt means the user + // has moved on to something else, so those only stop. + interrupt: async () => { + const takeBack = + state.current().every((part) => part.type === "text" && part.content.trim() === "") && + state.context.items().length === 0 && + data.session.pending.list(id).length === 0 + + const result = await server.api.session.interrupt({ sessionID: id, resume: true }).catch(() => undefined) + + // A repeated Stop finds the execution already stopping and reports nothing interrupted. + if (takeBack && result?.interrupted) await input.takeBack().catch(() => undefined) + }, } return adapter diff --git a/packages/app/src/session/composer/controller.ts b/packages/app/src/session/composer/controller.ts index 85582106fe0..d60889236b7 100644 --- a/packages/app/src/session/composer/controller.ts +++ b/packages/app/src/session/composer/controller.ts @@ -16,6 +16,7 @@ export function createSessionComposerController(input: { sessionKey: Accessor controls: Accessor dock: Parameters[0] + takeBack: () => Promise }) { const settings = useSettings() const dialog = useDialog() @@ -31,6 +32,7 @@ export function createSessionComposerController(input: { controls: input.controls, submitted: region.onResponseSubmit, background, + takeBack: input.takeBack, setEditor: (element) => { setEditor(element) region.setPromptRef(element) diff --git a/packages/app/src/session/composer/region.tsx b/packages/app/src/session/composer/region.tsx index 63207e2071c..9d8471e31da 100644 --- a/packages/app/src/session/composer/region.tsx +++ b/packages/app/src/session/composer/region.tsx @@ -363,6 +363,7 @@ export function createActiveSessionRegion(input: { sessionKey: input.session.identity.sessionKey, controls, dock, + takeBack: () => revert.takeBack(sessionID), }) : undefined, ), diff --git a/packages/app/src/session/revert.ts b/packages/app/src/session/revert.ts index b943008e9f8..a0753b59391 100644 --- a/packages/app/src/session/revert.ts +++ b/packages/app/src/session/revert.ts @@ -15,6 +15,7 @@ import type { SessionModel } from "./model" import { createSessionRevertState, REVERT_TIMEOUT_MS, + selectCursorAfterRevert, transitionSessionRevert, viewSessionRevert, type SessionRevertEffect, @@ -22,7 +23,7 @@ import { type SessionRevertOperation, type SessionRevertState, } from "./revert-machine" -import { selectSessionUserMessages } from "./session-domain" +import { selectSessionUserMessages, selectUnansweredPrompt } from "./session-domain" const IDLE = createSessionRevertState() @@ -285,6 +286,27 @@ export function createSessionRevert(input: { revertMessageID: data.session.get(id)?.revert?.messageID, ...snapshot(id), })), + /** + * After Stop interrupted the Session: takes its latest prompt back if the model had not answered it yet. Nothing + * of an answer is lost, so the revert commits straight away instead of offering an Undo. + */ + takeBack: async (sessionID: string) => { + const target = { composer: prompt.capture(), directory: location().directory } + // Interrupt acknowledges before the execution settles, so the start of an answer may still be on its way. + await server.api.experimental.session.wait({ sessionID }) + const message = selectUnansweredPrompt(data.session.message.list(sessionID)) + + if (!message) return + // The commit releases the prompt's blob refs, so the draft takes local copies of its media first. + const restored = await pinPromptMedia(messageDraft(message, target.directory)) + // The model called no tool, so any file that changed meanwhile is the user's own edit. + await server.api.session.revert.stage({ sessionID, messageID: message.id, files: false }) + await server.api.session.revert.commit({ sessionID }) + restore(target, message, restored) + + if (input.session.identity.params.id === sessionID) + input.setActiveMessage(selectCursorAfterRevert(snapshot(sessionID), message.id)) + }, undo: () => request(input.session.identity.params.id, (id) => ({ type: "undo.requested", diff --git a/packages/app/src/session/session-domain.test.ts b/packages/app/src/session/session-domain.test.ts index 241a3d82da4..9a29bfaa4af 100644 --- a/packages/app/src/session/session-domain.test.ts +++ b/packages/app/src/session/session-domain.test.ts @@ -1,6 +1,6 @@ import { expect, test } from "bun:test" import type { SessionMessageAssistant, SessionMessageInfo, SessionMessageUser } from "@opencode/client/promise" -import { selectSessionUserMessages, selectVisibleSessionUserMessages } from "./session-domain" +import { selectSessionUserMessages, selectUnansweredPrompt, selectVisibleSessionUserMessages } from "./session-domain" const user = (id: string): SessionMessageUser => ({ id, @@ -29,3 +29,29 @@ test("selects user history strictly before the revert boundary", () => { expect(selectVisibleSessionUserMessages(users.slice(2), "msg_b")).toEqual([]) expect(selectVisibleSessionUserMessages(users)).toBe(users) }) + +test.each([ + ["only reasoning", [{ type: "reasoning", text: "Thinking" }], "msg_b"], + ["text", [{ type: "text", text: "Hello" }], undefined], +] satisfies [string, SessionMessageAssistant["content"], string | undefined][])( + "the latest prompt is unanswered until text or a tool call follows it: %s", + (_name, content, expected) => { + const reply = { ...assistant, id: "msg_c", content } + const messages: SessionMessageInfo[] = [user("msg_a"), assistant, user("msg_b"), reply] + + expect(selectUnansweredPrompt(messages)?.id).toBe(expected) + }, +) + +test("the latest prompt is not unanswered once something else has run after it", () => { + const shell: SessionMessageInfo = { + id: "msg_c", + type: "shell", + shellID: "shl_1", + command: "sleep 60", + status: "running", + time: { created: 0 }, + } + + expect(selectUnansweredPrompt([user("msg_a"), { ...assistant, id: "msg_b" }, shell])).toBeUndefined() +}) diff --git a/packages/app/src/session/session-domain.ts b/packages/app/src/session/session-domain.ts index 5d0866f32dc..bb174b87be5 100644 --- a/packages/app/src/session/session-domain.ts +++ b/packages/app/src/session/session-domain.ts @@ -4,6 +4,28 @@ export function selectSessionUserMessages(messages: SessionMessageInfo[]) { return messages.filter((message): message is SessionMessageUser => message.type === "user") } +/** + * The latest prompt, unless the model has already answered it with text or a tool call, or something else has run + * since: a shell command, a compaction and a synthetic prompt each start a run of their own. + */ +export function selectUnansweredPrompt(messages: SessionMessageInfo[]) { + const index = messages.findLastIndex((message) => message.type === "user") + const message = messages[index] + + if (message?.type !== "user") return + + const answered = messages.slice(index + 1).some((item) => { + if (item.type === "shell" || item.type === "compaction" || item.type === "synthetic") return true + + return ( + item.type === "assistant" && + item.content.some((part) => part.type === "tool" || (part.type === "text" && part.text.trim() !== "")) + ) + }) + + return answered ? undefined : message +} + export function selectVisibleSessionUserMessages(messages: SessionMessageUser[], revertMessageID?: string) { if (!revertMessageID) return messages diff --git a/packages/tui/src/component/prompt/index.tsx b/packages/tui/src/component/prompt/index.tsx index 1a28934219b..790d5458a28 100644 --- a/packages/tui/src/component/prompt/index.tsx +++ b/packages/tui/src/component/prompt/index.tsx @@ -31,7 +31,8 @@ import { expandPromptInputPastedText, realignPromptInputMentions } from "../../p import { parseSlashHead } from "../../prompt/parse" import { createStore, produce, unwrap } from "solid-js/store" import { emptyPrompt, usePromptHistory, type ChipData, type PromptInfo, type PromptPartRef } from "../../prompt/history" -import { registerComposer, saveDraft, takeDraft } from "./draft-stash" +import { appendToSessionPrompt, registerComposer, saveDraft, takeDraft } from "./draft-stash" +import { usePromptRestore } from "../../prompt/restore" import { Skill } from "@opencode/schema/skill" import { computePromptTraits } from "../../prompt/traits" import { expandPastedTextPlaceholders, expandTrackedPastedText } from "../../prompt/part" @@ -388,6 +389,39 @@ export function Prompt(props: PromptProps) { return pasteQueue } + const restorePrompt = usePromptRestore() + // Interrupting before the model has answered with text or a tool call takes the prompt back, as /undo does: the + // likeliest reason to stop that early is to reword what was just sent. A draft or a pending prompt means the user + // has moved on to something else, so those keep the plain interrupt. + async function interrupt(sessionID: string) { + const takeBack = !store.prompt.text.trim() && data.session.pending.list(sessionID).length === 0 + const result = await client.api.session.interrupt({ sessionID, resume: true }) + // A repeated press finds the execution already stopping and reports nothing interrupted. + if (!takeBack || !result.interrupted) return + await client.api.experimental.session.wait({ sessionID }) + const messages = data.session.message.list(sessionID) + const index = messages.findLastIndex((message) => message.type === "user") + const message = messages[index] + if (message?.type !== "user") return + // A shell command, a compaction and a synthetic prompt each start a run of their own, so the one just stopped + // wasn't this prompt's. + const answered = messages.slice(index + 1).some((item) => { + if (item.type === "shell" || item.type === "compaction" || item.type === "synthetic") return true + return ( + item.type === "assistant" && + item.content.some((part) => part.type === "tool" || (part.type === "text" && part.text.trim())) + ) + }) + if (answered) return + const restored = await restorePrompt(message) + // The model called no tool, so any file that changed meanwhile is the user's own edit. + await client.api.session.revert.stage({ sessionID, messageID: message.id, files: false }) + // Nothing of an answer is lost and the prompt is back in the composer, so drop it for good instead of leaving a + // "reverted" notice to redo from. + await client.api.session.revert.commit({ sessionID }) + appendToSessionPrompt(sessionID, restored, renderer.widthMethod) + } + const imageAttachments = createMemo(() => (deduplicatePromptImages(store.prompt.files) ?? []).filter((file) => file.uri.startsWith("data:image/")), ) @@ -516,10 +550,9 @@ export function Prompt(props: PromptProps) { }, 5000) if (store.interrupt >= 2) { - void client.api.session.interrupt({ - sessionID: props.sessionID, - resume: true, - }) + void interrupt(props.sessionID).catch((error) => + toast.show({ message: errorMessage(error), variant: "error", duration: 5000 }), + ) setStore("interrupt", 0) } dialog.clear() diff --git a/packages/tui/test/session-interrupt-undo.test.tsx b/packages/tui/test/session-interrupt-undo.test.tsx new file mode 100644 index 00000000000..f042fa3fd46 --- /dev/null +++ b/packages/tui/test/session-interrupt-undo.test.tsx @@ -0,0 +1,98 @@ +import { expect, test } from "bun:test" +import { createAppFixture } from "./fixture/app" +import { directory, json } from "./fixture/tui-client" +import { takeDraft } from "../src/component/prompt/draft-stash" +import { waitForHighlightedFrame } from "./fixture/frame" + +const session = { + id: "ses_interrupt_undo", + title: "Interrupt undo", + projectID: "proj_test", + location: { directory }, + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created: 0, updated: 0 }, +} +const ask = { type: "user", id: "msg_ask", text: "Reword this prompt", time: { created: 1 } } + +const INTERRUPT = `POST /api/session/${session.id}/interrupt` +const WAIT = `POST /api/experimental/session/${session.id}/wait` +const REVERT = `POST /api/session/${session.id}/revert/stage` +const COMMIT = `POST /api/session/${session.id}/revert/commit` + +/** Opens a running session whose last prompt got `content` back so far, and interrupts it. `calls` logs what that sent. */ +async function interrupt(input: { content: unknown[]; draft?: string }) { + // Drafts are stashed per tab for the whole process, so an earlier test or test file would prefill the composer. + for (const id of [undefined, session.id]) takeDraft(id) + const calls: string[] = [] + const respond: Partial Response>> = { + [INTERRUPT]: () => json({ interrupted: true }), + [WAIT]: () => new Response(null, { status: 204 }), + [REVERT]: () => json({ data: session }), + [COMMIT]: () => new Response(null, { status: 204 }), + } + const app = await createAppFixture({ + width: 100, + height: 30, + config: { animations: false, tabs: { enabled: false } }, + args: { sessionID: session.id }, + fetch: async (url, request) => { + if (url.pathname === "/api/session") return json({ data: [session], cursor: {} }) + if (url.pathname === "/api/session/active") return json({ data: { [session.id]: { type: "running" } } }) + if (url.pathname === `/api/session/${session.id}`) return json({ data: session }) + if (url.pathname === `/api/session/${session.id}/inbox`) return json({ data: [] }) + if (url.pathname === `/api/session/${session.id}/permission`) return json({ data: [] }) + if (url.pathname === `/api/session/${session.id}/message`) + return json({ + data: [ + { + type: "assistant", + id: "msg_reply", + agent: "build", + model: { providerID: "fixture", id: "fixture" }, + time: { created: 2 }, + content: input.content, + }, + ask, + ], + cursor: {}, + }) + const key = `${request.method} ${url.pathname}` + const response = respond[key]?.() + if (response) calls.push(key) + return response + }, + }) + await waitForHighlightedFrame(app, (frame) => frame.includes(ask.text) && frame.includes("interrupt")) + if (input.draft) await app.mockInput.typeText(input.draft) + app.mockInput.pressEscape() + await app.waitForFrame((frame) => frame.includes("again to interrupt")) + app.mockInput.pressEscape() + return Object.assign(app, { calls }) +} + +// How many times the frame shows the prompt: once in the transcript, twice once it is also back in the composer. +const shown = (frame: string) => frame.split(ask.text).length - 1 + +test("interrupting before the model answers with text or a tool call takes the prompt back", async () => { + await using app = await interrupt({ content: [{ type: "reasoning", text: "Thinking it over" }] }) + + await app.waitForFrame((frame) => shown(frame) === 2) + await app.waitForFrame(() => app.calls.length === 4) + expect(app.calls).toEqual([INTERRUPT, WAIT, REVERT, COMMIT]) +}, 20000) + +test.each([ + ["after the model answered", { content: [{ type: "text", text: "Here you go" }] }, [INTERRUPT, WAIT]], + ["with a draft in the composer", { content: [], draft: "something else" }, [INTERRUPT]], +])( + "interrupting %s only interrupts", + async (_name, input, expected) => { + await using app = await interrupt(input) + + await app.waitForFrame(() => app.calls.length === expected.length) + expect(shown(await app.waitForFrame(() => true))).toBe(1) + expect(app.calls).toEqual(expected) + }, + 20000, +)