Skip to content

Commit b0a0769

Browse files
committed
feat: cancel queued messages
Add the ability to cancel messages queued while the assistant is busy. Server: - Track messageID on queued callbacks in SessionPrompt - Add cancelQueued() to remove a callback and delete the message/parts - Add POST /:sessionID/message/:messageID/cancel route TUI: - Clicking a queued message shows Cancel/Copy instead of Revert/Copy/Fork - Cancel restores the message text to the prompt input - Undo keybind (messages_undo) cancels last queued message before falling back to abort+revert
1 parent 19b1222 commit b0a0769

8 files changed

Lines changed: 345 additions & 95 deletions

File tree

‎packages/opencode/src/cli/cmd/tui/component/prompt/history.tsx‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,20 @@ import { createStore, produce } from "solid-js/store"
55
import { clone } from "remeda"
66
import { createSimpleContext } from "../../context/helper"
77
import { appendFile, writeFile } from "fs/promises"
8-
import type { AgentPart, FilePart, TextPart } from "@opencode-ai/sdk/v2"
8+
import type { AgentPart, FilePart, Part, TextPart } from "@opencode-ai/sdk/v2"
9+
10+
export function extractPromptInfo(parts: Part[]): PromptInfo {
11+
return parts.reduce(
12+
(agg, part) => {
13+
if (part.type === "text") {
14+
if (!part.synthetic) agg.input += part.text
15+
}
16+
if (part.type === "file") agg.parts.push(part)
17+
return agg
18+
},
19+
{ input: "", parts: [] as PromptInfo["parts"] },
20+
)
21+
}
922

1023
export type PromptInfo = {
1124
input: string

‎packages/opencode/src/cli/cmd/tui/routes/session/dialog-message.tsx‎

Lines changed: 110 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { DialogSelect } from "@tui/ui/dialog-select"
44
import { useSDK } from "@tui/context/sdk"
55
import { useRoute } from "@tui/context/route"
66
import { Clipboard } from "@tui/util/clipboard"
7-
import type { PromptInfo } from "@tui/component/prompt/history"
7+
import { extractPromptInfo, type PromptInfo } from "@tui/component/prompt/history"
88

99
export function DialogMessage(props: {
1010
messageID: string
@@ -16,94 +16,126 @@ export function DialogMessage(props: {
1616
const message = createMemo(() => sync.data.message[props.sessionID]?.find((x) => x.id === props.messageID))
1717
const route = useRoute()
1818

19+
const messages = createMemo(() => sync.data.message[props.sessionID] ?? [])
20+
const pending = createMemo(() => messages().findLast((x) => x.role === "assistant" && !x.time.completed)?.id)
21+
const queued = createMemo(() => {
22+
const msg = message()
23+
return msg && pending() && msg.id > pending()!
24+
})
25+
1926
return (
2027
<DialogSelect
2128
title="Message Actions"
22-
options={[
23-
{
24-
title: "Revert",
25-
value: "session.revert",
26-
description: "undo messages and file changes",
27-
onSelect: (dialog) => {
28-
const msg = message()
29-
if (!msg) return
30-
31-
sdk.client.session.revert({
32-
sessionID: props.sessionID,
33-
messageID: msg.id,
34-
})
29+
options={
30+
queued()
31+
? [
32+
{
33+
title: "Cancel",
34+
value: "message.cancel",
35+
description: "cancel queued message",
36+
onSelect: async (dialog) => {
37+
const msg = message()
38+
if (!msg) return
3539

36-
if (props.setPrompt) {
37-
const parts = sync.data.part[msg.id]
38-
const promptInfo = parts.reduce(
39-
(agg, part) => {
40-
if (part.type === "text") {
41-
if (!part.synthetic) agg.input += part.text
40+
if (props.setPrompt) {
41+
const parts = sync.data.part[msg.id] ?? []
42+
props.setPrompt(extractPromptInfo(parts))
4243
}
43-
if (part.type === "file") agg.parts.push(part)
44-
return agg
44+
45+
await sdk.client.session
46+
.cancel({
47+
sessionID: props.sessionID,
48+
messageID: msg.id,
49+
})
50+
.catch(() => {})
51+
52+
dialog.clear()
4553
},
46-
{ input: "", parts: [] as PromptInfo["parts"] },
47-
)
48-
props.setPrompt(promptInfo)
49-
}
54+
},
55+
{
56+
title: "Copy",
57+
value: "message.copy",
58+
description: "message text to clipboard",
59+
onSelect: async (dialog) => {
60+
const msg = message()
61+
if (!msg) return
62+
63+
const parts = sync.data.part[msg.id] ?? []
64+
const text = parts.reduce((agg, part) => {
65+
if (part.type === "text" && !part.synthetic) agg += part.text
66+
return agg
67+
}, "")
5068

51-
dialog.clear()
52-
},
53-
},
54-
{
55-
title: "Copy",
56-
value: "message.copy",
57-
description: "message text to clipboard",
58-
onSelect: async (dialog) => {
59-
const msg = message()
60-
if (!msg) return
69+
await Clipboard.copy(text)
70+
dialog.clear()
71+
},
72+
},
73+
]
74+
: [
75+
{
76+
title: "Revert",
77+
value: "session.revert",
78+
description: "undo messages and file changes",
79+
onSelect: (dialog) => {
80+
const msg = message()
81+
if (!msg) return
6182

62-
const parts = sync.data.part[msg.id]
63-
const text = parts.reduce((agg, part) => {
64-
if (part.type === "text" && !part.synthetic) {
65-
agg += part.text
66-
}
67-
return agg
68-
}, "")
83+
sdk.client.session.revert({
84+
sessionID: props.sessionID,
85+
messageID: msg.id,
86+
})
6987

70-
await Clipboard.copy(text)
71-
dialog.clear()
72-
},
73-
},
74-
{
75-
title: "Fork",
76-
value: "session.fork",
77-
description: "create a new session",
78-
onSelect: async (dialog) => {
79-
const result = await sdk.client.session.fork({
80-
sessionID: props.sessionID,
81-
messageID: props.messageID,
82-
})
83-
const initialPrompt = (() => {
84-
const msg = message()
85-
if (!msg) return undefined
86-
const parts = sync.data.part[msg.id]
87-
return parts.reduce(
88-
(agg, part) => {
89-
if (part.type === "text") {
90-
if (!part.synthetic) agg.input += part.text
88+
if (props.setPrompt) {
89+
const parts = sync.data.part[msg.id]
90+
props.setPrompt(extractPromptInfo(parts))
9191
}
92-
if (part.type === "file") agg.parts.push(part)
93-
return agg
92+
93+
dialog.clear()
94+
},
95+
},
96+
{
97+
title: "Copy",
98+
value: "message.copy",
99+
description: "message text to clipboard",
100+
onSelect: async (dialog) => {
101+
const msg = message()
102+
if (!msg) return
103+
104+
const parts = sync.data.part[msg.id]
105+
const text = parts.reduce((agg, part) => {
106+
if (part.type === "text" && !part.synthetic) agg += part.text
107+
return agg
108+
}, "")
109+
110+
await Clipboard.copy(text)
111+
dialog.clear()
112+
},
113+
},
114+
{
115+
title: "Fork",
116+
value: "session.fork",
117+
description: "create a new session",
118+
onSelect: async (dialog) => {
119+
const result = await sdk.client.session.fork({
120+
sessionID: props.sessionID,
121+
messageID: props.messageID,
122+
})
123+
const initialPrompt = (() => {
124+
const msg = message()
125+
if (!msg) return undefined
126+
const parts = sync.data.part[msg.id]
127+
return extractPromptInfo(parts)
128+
})()
129+
route.navigate({
130+
sessionID: result.data!.id,
131+
type: "session",
132+
initialPrompt,
133+
})
134+
dialog.clear()
94135
},
95-
{ input: "", parts: [] as PromptInfo["parts"] },
96-
)
97-
})()
98-
route.navigate({
99-
sessionID: result.data!.id,
100-
type: "session",
101-
initialPrompt,
102-
})
103-
dialog.clear()
104-
},
105-
},
106-
]}
136+
},
137+
]
138+
}
107139
/>
108140
)
109141
}

‎packages/opencode/src/cli/cmd/tui/routes/session/index.tsx‎

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ import { parsePatch } from "diff"
5454
import { useDialog } from "../../ui/dialog"
5555
import { TodoItem } from "../../component/todo-item"
5656
import { DialogMessage } from "./dialog-message"
57-
import type { PromptInfo } from "../../component/prompt/history"
57+
import { extractPromptInfo, type PromptInfo } from "../../component/prompt/history"
5858
import { DialogConfirm } from "@tui/ui/dialog-confirm"
5959
import { DialogTimeline } from "./dialog-timeline"
6060
import { DialogForkFromTimeline } from "./dialog-fork-from-timeline"
@@ -450,6 +450,23 @@ export function Session() {
450450
name: "undo",
451451
},
452452
onSelect: async (dialog) => {
453+
// If there's a queued message, cancel it instead of aborting
454+
const p = pending()
455+
if (p) {
456+
const queued = messages().findLast((x) => x.role === "user" && x.id > p)
457+
if (queued) {
458+
prompt.set(extractPromptInfo(sync.data.part[queued.id] ?? []))
459+
await sdk.client.session
460+
.cancel({
461+
sessionID: route.sessionID,
462+
messageID: queued.id,
463+
})
464+
.catch(() => {})
465+
dialog.clear()
466+
return
467+
}
468+
}
469+
453470
const status = sync.data.session_status?.[route.sessionID]
454471
if (status?.type !== "idle") await sdk.client.session.abort({ sessionID: route.sessionID }).catch(() => {})
455472
const revert = session()?.revert?.messageID
@@ -463,19 +480,7 @@ export function Session() {
463480
.then(() => {
464481
toBottom()
465482
})
466-
const parts = sync.data.part[message.id]
467-
prompt.set(
468-
parts.reduce(
469-
(agg, part) => {
470-
if (part.type === "text") {
471-
if (!part.synthetic) agg.input += part.text
472-
}
473-
if (part.type === "file") agg.parts.push(part)
474-
return agg
475-
},
476-
{ input: "", parts: [] as PromptInfo["parts"] },
477-
),
478-
)
483+
prompt.set(extractPromptInfo(sync.data.part[message.id] ?? []))
479484
dialog.clear()
480485
},
481486
},

‎packages/opencode/src/server/routes/session.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -694,6 +694,37 @@ export const SessionRoutes = lazy(() =>
694694
return c.json(part)
695695
},
696696
)
697+
.post(
698+
"/:sessionID/message/:messageID/cancel",
699+
describeRoute({
700+
summary: "Cancel queued message",
701+
description: "Cancel a queued message that hasn't been processed yet, removing it from the session.",
702+
operationId: "session.cancel",
703+
responses: {
704+
200: {
705+
description: "Whether the message was successfully cancelled",
706+
content: {
707+
"application/json": {
708+
schema: resolver(z.boolean()),
709+
},
710+
},
711+
},
712+
...errors(400, 404),
713+
},
714+
}),
715+
validator(
716+
"param",
717+
z.object({
718+
sessionID: z.string().meta({ description: "Session ID" }),
719+
messageID: z.string().meta({ description: "Message ID" }),
720+
}),
721+
),
722+
async (c) => {
723+
const params = c.req.valid("param")
724+
const result = await SessionPrompt.cancelQueued(params.sessionID, params.messageID)
725+
return c.json(result)
726+
},
727+
)
697728
.post(
698729
"/:sessionID/message",
699730
describeRoute({

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ export namespace SessionPrompt {
6161
{
6262
abort: AbortController
6363
callbacks: {
64+
messageID?: string
6465
resolve(input: MessageV2.WithParts): void
6566
reject(reason?: any): void
6667
}[]
@@ -174,7 +175,7 @@ export namespace SessionPrompt {
174175
return message
175176
}
176177

177-
return loop({ sessionID: input.sessionID })
178+
return loop({ sessionID: input.sessionID, messageID: message.info.id })
178179
})
179180

180181
export async function resolvePromptParts(template: string): Promise<PromptInput["parts"]> {
@@ -260,9 +261,31 @@ export namespace SessionPrompt {
260261
return
261262
}
262263

264+
// NOTE: splicing the callback without rejecting its promise is intentional.
265+
// See a458413 — rejecting queued promises caused unhandled errors. The
266+
// orphaned promise from the HTTP stream is cleaned up by client disconnect.
267+
export async function cancelQueued(sessionID: string, messageID: string) {
268+
const s = state()
269+
const match = s[sessionID]
270+
if (!match) return false
271+
272+
const index = match.callbacks.findIndex((cb) => cb.messageID === messageID)
273+
if (index === -1) return false
274+
275+
match.callbacks.splice(index, 1)
276+
277+
for (const part of await MessageV2.parts(messageID)) {
278+
await Session.removePart({ sessionID, messageID, partID: part.id })
279+
}
280+
await Session.removeMessage({ sessionID, messageID })
281+
282+
return true
283+
}
284+
263285
export const LoopInput = z.object({
264286
sessionID: Identifier.schema("session"),
265287
resume_existing: z.boolean().optional(),
288+
messageID: z.string().optional(),
266289
})
267290
export const loop = fn(LoopInput, async (input) => {
268291
const { sessionID, resume_existing } = input
@@ -271,7 +294,7 @@ export namespace SessionPrompt {
271294
if (!abort) {
272295
return new Promise<MessageV2.WithParts>((resolve, reject) => {
273296
const callbacks = state()[sessionID].callbacks
274-
callbacks.push({ resolve, reject })
297+
callbacks.push({ messageID: input.messageID, resolve, reject })
275298
})
276299
}
277300

0 commit comments

Comments
 (0)