feat: undo when interrupting before the model answers (#65505)

This commit is contained in:
Dan Smolsky 2026-11-25 11:33:45 -05:00 • committed by GitHub
parent e0bf30832b
commit 45b5bd4694
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 266 additions and 14 deletions

View file

@ -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 })

View file

@ -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) => {

View file

@ -14,6 +14,7 @@ export function createActiveComposerAdapter(input: {
submitted: () => void
setEditor: (element: HTMLDivElement) => void
background: NonNullable<ComposerSession["background"]>
takeBack: () => Promise<void>
}) {
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

View file

@ -16,6 +16,7 @@ export function createSessionComposerController(input: {
sessionKey: Accessor<string>
controls: Accessor<ComposerControls>
dock: Parameters<typeof createSessionComposerRegionController>[0]
takeBack: () => Promise<void>
}) {
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)

View file

@ -363,6 +363,7 @@ export function createActiveSessionRegion(input: {
sessionKey: input.session.identity.sessionKey,
controls,
dock,
takeBack: () => revert.takeBack(sessionID),
})
: undefined,
),

View file

@ -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",

View file

@ -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()
})

View file

@ -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

View file

@ -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()

View file

@ -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<Record<string, () => 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,
)