Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(chat): keep a queued prompt's bubble across a remount

Paul Robertson0b59c66c3bd8
diff --git a/CLAUDE.md b/CLAUDE.md
index 5fc4fe359..85b3aafad 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4449,7 +4449,10 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
`renderer/lib/chatSendGate.ts`), with ONE exception: `working` for an agent in
`INPUT_QUEUE_CAPABLE` (claude — measured: a prompt submitted mid-turn waits in Claude Code's own
queue and reaches the model at the next tool boundary), where Enter QUEUES (`chatSendMode`) and
- the bubble reads "Queued" until the transcript has it. Only a plain prompt queues (`canQueue`):
+ the bubble reads "Queued" until the transcript has it. The bubble is kept per node in
+ `state/chatQueued.ts` (in memory), so a panel remounted mid-turn (a project switch, the card
+ modal) draws it again; once the agent is not working the queue was delivered or pulled back
+ (Esc) and the entry is forgotten. Only a plain prompt queues (`canQueue`):
a slash command or `!` line mid-turn is unmeasured and waits. While the agent works the textarea
stays editable for every agent (`composerStandsDown`) — only sending is gated. Never in
`waiting`/`blocked`:
diff --git a/src/renderer/lib/chatPaging.test.ts b/src/renderer/lib/chatPaging.test.ts
index 486f7bddd..144832f17 100644
--- a/src/renderer/lib/chatPaging.test.ts
+++ b/src/renderer/lib/chatPaging.test.ts
@@ -5,6 +5,7 @@ import {
applyOlder,
applyTail,
tailConfirmsSends,
+ unconfirmedQueuedSends,
attachCarried,
emptyThread,
shouldFetchOlder,
@@ -324,3 +325,43 @@ describe('held results whose tool is already loaded are dropped', () => {
expect(t.pending.has('t1')).toBe(false)
})
})
+
+describe('unconfirmedQueuedSends', () => {
+ const rec = (id: string, text: string, afterKey: number | null) => ({ id, text, afterKey })
+
+ it('keeps a send the transcript does not hold yet', () => {
+ const sends = [rec('a', 'next', 200)]
+
+ const left = unconfirmedQueuedSends(page([say(100, 'start', 'user'), say(200, 'ok')], null), sends)
+
+ expect(left).toEqual(sends)
+ })
+
+ it('drops a send confirmed by a user message newer than its afterKey', () => {
+ const left = unconfirmedQueuedSends(page([say(200, 'ok'), say(300, 'next', 'user')], null), [rec('a', 'next', 200)])
+
+ expect(left).toEqual([])
+ })
+
+ it('an identical message at or before afterKey does not confirm it', () => {
+ const sends = [rec('a', 'yes', 200)]
+
+ const left = unconfirmedQueuedSends(page([say(100, 'yes', 'user'), say(200, 'ok')], null), sends)
+
+ expect(left).toEqual(sends)
+ })
+
+ it('confirms one-for-one, oldest send first', () => {
+ const sends = [rec('a', 'yes', 200), rec('b', 'yes', 200)]
+
+ const left = unconfirmedQueuedSends(page([say(300, 'yes', 'user')], null), sends)
+
+ expect(left.map((s) => s.id)).toEqual(['b'])
+ })
+
+ it('with nothing keyed when sent, any user message may confirm it', () => {
+ const left = unconfirmedQueuedSends(page([say(10, 'next', 'user')], null), [rec('a', 'next', null)])
+
+ expect(left).toEqual([])
+ })
+})
diff --git a/src/renderer/lib/chatPaging.ts b/src/renderer/lib/chatPaging.ts
index 45f19ae26..37d8a853c 100644
--- a/src/renderer/lib/chatPaging.ts
+++ b/src/renderer/lib/chatPaging.ts
@@ -191,7 +191,14 @@ function unconfirmedSends(t: ChatThread, res: ChatTranscriptResult): ChatMessage
// last read by someone ELSE — the same command (or, on the exact-text path, the same text) typed
// in the TERMINAL — is indistinguishable from the composer's own send and confirms it early. The
// transcript records no sender to tell them apart.
- const fresh = res.messages.filter((m) => m.key === undefined || m.key > newest)
+ return unmatchedSends(trailing, res.messages.filter((m) => m.key === undefined || m.key > newest))
+}
+
+/**
+ * The sends a set of transcript messages does NOT confirm, ONE-FOR-ONE, by the rules
+ * `unconfirmedSends` describes. `fresh` is already narrowed to what may confirm them.
+ */
+function unmatchedSends(trailing: ChatMessage[], fresh: ChatMessage[]): ChatMessage[] {
const available = fresh.filter((m) => m.role === 'user').map(userText)
// A slash command / `!` line is recorded as a command, which the reader renders as an assistant
// tool part — never as the typed text — so a send of one is confirmed by that part instead.
@@ -216,6 +223,30 @@ function unconfirmedSends(t: ChatThread, res: ChatTranscriptResult): ChatMessage
})
}
+/** A send queued into the CLI mid-turn, kept outside the panel (`state/chatQueued.ts`). */
+export interface QueuedSendRecord {
+ id: string
+ text: string
+ /** The newest byte-offset key the thread had when it was sent; `null` = nothing was keyed. */
+ afterKey: number | null
+}
+
+/**
+ * Which remembered queued sends a remounted panel's first read does NOT yet carry, so it can draw
+ * them again as "Queued". Only messages NEWER than the oldest send's `afterKey` may confirm one —
+ * the rule `unconfirmedSends` uses, with the key the thread had when the send was made, since the
+ * remounted thread has never seen that key.
+ */
+export function unconfirmedQueuedSends(res: ChatTranscriptResult, sends: QueuedSendRecord[]): QueuedSendRecord[] {
+ if (sends.length === 0) return []
+ let cutoff = Infinity
+ for (const s of sends) cutoff = Math.min(cutoff, s.afterKey ?? -Infinity)
+ const fresh = res.messages.filter((m) => m.key === undefined || m.key > cutoff)
+ const asMessages = sends.map((s): ChatMessage => ({ role: 'user', parts: [{ kind: 'text', text: s.text }] }))
+ const left = new Set(unmatchedSends(asMessages, fresh))
+ return sends.filter((_, i) => left.has(asMessages[i]))
+}
+
/**
* Prepend an OLDER page (a read with `before` = the thread's cursor). Held results claim their
* tools in it; its own carried results (tools older still) join the held set; at the start of the
diff --git a/src/renderer/nodes/ChatPanel.queuedRemount.test.tsx b/src/renderer/nodes/ChatPanel.queuedRemount.test.tsx
new file mode 100644
index 000000000..421155027
--- /dev/null
+++ b/src/renderer/nodes/ChatPanel.queuedRemount.test.tsx
@@ -0,0 +1,157 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { ChatMessage, ChatTranscriptResult } from '@shared/types'
+import { useAgentStatus } from '../state/agentStatus'
+import { clearQueuedSendsForTest } from '../state/chatQueued'
+
+/**
+ * A prompt queued into the CLI mid-turn is not in the transcript until the CLI delivers it, so a
+ * panel remounted by a project switch must draw it again from `state/chatQueued.ts`. Pins the
+ * remount: the bubble comes back while the transcript lacks it, and goes once the transcript has it.
+ */
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const { transcript, session } = vi.hoisted(() => {
+ const transcript: { messages: ChatMessage[] } = { messages: [] }
+ const session = {
+ api: {
+ chat: {
+ readTranscript: async (): Promise<ChatTranscriptResult> => ({
+ messages: transcript.messages,
+ found: true,
+ olderCursor: null
+ })
+ },
+ pty: { sendChatPrompt: vi.fn(async () => true as const) }
+ }
+ }
+ return { transcript, session }
+})
+vi.mock('../session/session', () => ({ useSession: () => session }))
+
+import { ChatPanel } from './ChatPanel'
+
+const NODE = 'n-chat-queued-remount'
+let host: HTMLDivElement
+let root: Root
+
+const say = (key: number, text: string, role: 'user' | 'assistant'): ChatMessage => ({
+ role,
+ key,
+ parts: [{ kind: 'text', text }]
+})
+
+async function mount(): Promise<HTMLTextAreaElement> {
+ root = createRoot(host)
+ await act(async () => {
+ root.render(<ChatPanel nodeId={NODE} sessionId="s1" agentId="claude" />)
+ })
+ return host.querySelector('textarea') as HTMLTextAreaElement
+}
+
+async function unmount(): Promise<void> {
+ await act(async () => root.unmount())
+}
+
+async function queue(ta: HTMLTextAreaElement, text: string): Promise<void> {
+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!
+ await act(async () => {
+ setter.call(ta, text)
+ ta.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ await act(async () => {
+ ta.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
+ })
+}
+
+const queuedTexts = (): string[] =>
+ [...host.querySelectorAll('.term-chat__msg--queued')].map((el) => el.textContent ?? '')
+
+beforeEach(() => {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ clearQueuedSendsForTest()
+ useAgentStatus.setState((s) => ({
+ byId: { ...s.byId, [NODE]: { state: 'working' } as (typeof s.byId)[string] }
+ }))
+})
+
+afterEach(async () => {
+ await unmount()
+ host.remove()
+ transcript.messages = []
+ useAgentStatus.setState((s) => {
+ const byId = { ...s.byId }
+ delete byId[NODE]
+ return { byId }
+ })
+})
+
+describe('ChatPanel queued sends across a remount', () => {
+ it('draws a queued send again after a remount while the transcript does not have it', async () => {
+ transcript.messages = [say(100, 'start', 'user'), say(200, 'working on it', 'assistant')]
+ await queue(await mount(), 'and then this')
+ await unmount()
+
+ await mount()
+
+ expect(queuedTexts()).toEqual([expect.stringContaining('and then this')])
+ })
+
+ it('does not draw it again once the transcript has it', async () => {
+ transcript.messages = [say(100, 'start', 'user'), say(200, 'working on it', 'assistant')]
+ await queue(await mount(), 'and then this')
+ await unmount()
+ transcript.messages = [...transcript.messages, say(300, 'and then this', 'user')]
+
+ await mount()
+
+ expect(queuedTexts()).toEqual([])
+ expect(host.textContent?.split('and then this').length).toBe(2)
+ })
+
+ it('an identical message from before the send does not count as it', async () => {
+ transcript.messages = [say(100, 'yes', 'user'), say(200, 'working on it', 'assistant')]
+ await queue(await mount(), 'yes')
+ await unmount()
+
+ await mount()
+
+ expect(queuedTexts()).toEqual([expect.stringContaining('yes')])
+ })
+
+ it('is not drawn again, and is forgotten, when the agent is no longer working', async () => {
+ transcript.messages = [say(100, 'start', 'user')]
+ await queue(await mount(), 'next')
+ await unmount()
+ useAgentStatus.setState((st) => ({
+ byId: { ...st.byId, [NODE]: { state: 'done' } as (typeof st.byId)[string] }
+ }))
+ await mount()
+ await unmount()
+ useAgentStatus.setState((st) => ({
+ byId: { ...st.byId, [NODE]: { state: 'working' } as (typeof st.byId)[string] }
+ }))
+
+ await mount()
+
+ expect(queuedTexts()).toEqual([])
+ })
+
+ it('is forgotten once confirmed, so a later remount does not bring it back', async () => {
+ transcript.messages = [say(100, 'start', 'user')]
+ await queue(await mount(), 'next')
+ await unmount()
+ transcript.messages = [...transcript.messages, say(200, 'next', 'user')]
+ await mount()
+ await unmount()
+ transcript.messages = [say(100, 'start', 'user')]
+
+ await mount()
+
+ expect(queuedTexts()).toEqual([])
+ })
+})
diff --git a/src/renderer/nodes/ChatPanel.sendGate.test.tsx b/src/renderer/nodes/ChatPanel.sendGate.test.tsx
index c9aa9b652..63261369f 100644
--- a/src/renderer/nodes/ChatPanel.sendGate.test.tsx
+++ b/src/renderer/nodes/ChatPanel.sendGate.test.tsx
@@ -3,6 +3,7 @@ import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useAgentStatus } from '../state/agentStatus'
+import { clearQueuedSendsForTest } from '../state/chatQueued'
/**
* The composer must never type into a TUI dialog: `sendText` pastes and presses Enter, and Enter
@@ -62,6 +63,7 @@ const enter = (ta: HTMLTextAreaElement): void => {
beforeEach(() => {
sendChatPrompt.mockClear()
+ clearQueuedSendsForTest()
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 3f28f5e37..b1e16928d 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -16,6 +16,8 @@ import {
type ScreenBlock
} from '../lib/chatSendGate'
import type { ChatMessage, ChatPart } from '@shared/types'
+import { forgetQueuedSend, queuedSendsFor, rememberQueuedSend } from '../state/chatQueued'
+import { uuid } from '../lib/uuid'
import { chatPaneRefusal, chatPaneRefusalToast } from '../lib/chatPaneGate'
import { chatAgentLabel, isNearBottom, shouldFollowOnLoad, toolCardTitle, unseenAfter } from '../lib/chatPanel'
import { useSettings } from '../state/settings'
@@ -26,6 +28,7 @@ import {
applyOlder,
applyTail,
tailConfirmsSends,
+ unconfirmedQueuedSends,
emptyThread,
shouldFetchOlder,
type ChatThread
@@ -254,6 +257,24 @@ export function ChatPanel({
// when the read was issued.
const threadRef = useRef(thread)
threadRef.current = thread
+ // The optimistic bubbles sent into the CLI's queue mid-turn, drawn as "Queued" until the transcript
+ // has them, each with its id in `state/chatQueued.ts`. Object identity is enough: `applyTail`
+ // carries an unconfirmed send as the same object.
+ const queuedRef = useRef(new WeakMap<ChatMessage, string>())
+ // The identity whose remembered queued sends this mount has already drawn again (see `load`).
+ const queuedRestoredForRef = useRef<string | null>(null)
+ // The queued ids the thread showed at its last change: one that leaves the thread was confirmed
+ // by the transcript (or its session ended) and is forgotten.
+ const shownQueuedRef = useRef(new Set<string>())
+ useEffect(() => {
+ const now = new Set<string>()
+ for (const m of thread.messages) {
+ const id = queuedRef.current.get(m)
+ if (id !== undefined) now.add(id)
+ }
+ for (const id of shownQueuedRef.current) if (!now.has(id)) forgetQueuedSend(nodeId, id)
+ shownQueuedRef.current = now
+ }, [thread, nodeId])
const [loadState, setLoadState] = useState<LoadState>('loading')
// Mirror for `attemptLive`, which runs from timers and settles, outside any render.
const loadStateRef = useRef(loadState)
@@ -515,7 +536,30 @@ export function ChatPanel({
// command it is the ONLY signal (no hook fires). A command that starts a real turn is
// still covered — its `working` state keeps the row (and the send refusal) on its own.
if (tailConfirmsSends(threadRef.current, identity, res)) setOptimistic(false)
- setThread((t) => applyTail(t, identity, res, { carryUnconfirmed: carry }))
+ // A remounted panel (a project switch, the card modal) draws its queued sends again: the
+ // transcript does not hold a prompt the CLI has not delivered yet. Once per identity, and
+ // only mid-turn: a CLI queue exists only while a turn runs, so once the agent is not working
+ // the queue was delivered, or pulled back into the input box (Esc), and is forgotten.
+ const restored: ChatMessage[] = []
+ if (queuedRestoredForRef.current !== identity) {
+ queuedRestoredForRef.current = identity
+ const remembered = queuedSendsFor(nodeId, identity)
+ const working = useAgentStatus.getState().byId[nodeId]?.state === 'working'
+ const waiting = working ? unconfirmedQueuedSends(res, remembered) : []
+ for (const r of remembered) if (!waiting.includes(r)) forgetQueuedSend(nodeId, r.id)
+ for (const r of waiting) {
+ const m: ChatMessage = { role: 'user', parts: [{ kind: 'text', text: r.text }] }
+ queuedRef.current.set(m, r.id)
+ restored.push(m)
+ }
+ }
+ setThread((t) => {
+ const next = applyTail(t, identity, res, { carryUnconfirmed: carry })
+ if (restored.length === 0) return next
+ const shown = new Set(next.messages.map((m) => queuedRef.current.get(m)))
+ const missing = restored.filter((m) => !shown.has(queuedRef.current.get(m)))
+ return missing.length === 0 ? next : { ...next, messages: [...next.messages, ...missing] }
+ })
setLoadState('ok')
setHeldRead({ identity, pendingId: heldAtStart })
settleHeldReload(heldAtStart)
@@ -977,10 +1021,6 @@ export function ChatPanel({
markFollowing(true)
}
- // The optimistic bubbles sent into the CLI's queue mid-turn, drawn as "Queued" until the transcript
- // has them. Object identity is enough: `applyTail` carries an unconfirmed send as the same object.
- const queuedRef = useRef(new WeakSet<ChatMessage>())
-
const sendOnce = useCallback(async () => {
const text = input.trim()
if (!text) return
@@ -1028,7 +1068,15 @@ export function ChatPanel({
justSentRef.current = true
lastSentRef.current = text
const sent: ChatMessage = { role: 'user', parts: [{ kind: 'text', text }] }
- if (mode === 'queue') queuedRef.current.add(sent)
+ if (mode === 'queue') {
+ let afterKey: number | null = null
+ for (const m of threadRef.current.messages) {
+ if (m.key !== undefined && (afterKey === null || m.key > afterKey)) afterKey = m.key
+ }
+ const id = uuid()
+ queuedRef.current.set(sent, id)
+ rememberQueuedSend(nodeId, { id, identity, text, afterKey })
+ }
setThread((t) => ({ ...t, messages: [...t.messages, sent] }))
setOptimistic(true)
setInput('')
@@ -1055,7 +1103,7 @@ export function ChatPanel({
}
commandReadTimerRef.current = setTimeout(fire, CHAT_LIVE_RELOAD_MIN_MS)
}
- }, [api, input, nodeId, agentId, onShowTerminal, pollScreen])
+ }, [api, input, nodeId, agentId, identity, onShowTerminal, pollScreen])
// A send in flight. A typed send (core/typed-input.ts, claude) takes a moment — core waits for the
// pane to show the text before it presses Enter — and the draft is only cleared once it lands, so
// a second Enter in that window would send the same prompt twice. Ignore it instead.
diff --git a/src/renderer/state/chatQueued.ts b/src/renderer/state/chatQueued.ts
new file mode 100644
index 000000000..d2b52cf39
--- /dev/null
+++ b/src/renderer/state/chatQueued.ts
@@ -0,0 +1,46 @@
+import type { QueuedSendRecord } from '../lib/chatPaging'
+
+/**
+ * The ⌘M composer's sends that went into the agent CLI's own queue mid-turn and are not in the
+ * transcript yet, keyed by node id. The "Queued" bubble is optimistic panel state, and the panel
+ * unmounts on every project switch; without this a remounted panel rebuilt the thread from the
+ * transcript, which does not hold a queued prompt until the CLI delivers it, so the prompt looked
+ * lost while it was still waiting in the CLI's queue.
+ *
+ * In memory only, on purpose: after a reload the CLI's queue may have been delivered, edited (Esc
+ * pulls it back into the input box) or dropped, and a stale bubble is worse than none.
+ */
+interface StoredQueuedSend extends QueuedSendRecord {
+ /** The transcript identity the send was made under (ChatPanel's `identity`). */
+ identity: string
+}
+
+/** Per node. A queue this deep is already unusual; the oldest go first. */
+const PER_NODE_MAX = 20
+
+const byNode = new Map<string, StoredQueuedSend[]>()
+
+export function rememberQueuedSend(nodeId: string, send: StoredQueuedSend): void {
+ const list = [...(byNode.get(nodeId) ?? []), send]
+ byNode.set(nodeId, list.slice(-PER_NODE_MAX))
+}
+
+export function forgetQueuedSend(nodeId: string, id: string): void {
+ const list = byNode.get(nodeId)
+ if (list === undefined) return
+ const next = list.filter((s) => s.id !== id)
+ if (next.length === 0) byNode.delete(nodeId)
+ else byNode.set(nodeId, next)
+}
+
+/** The sends remembered for this node under this transcript identity, oldest first. */
+export function queuedSendsFor(nodeId: string, identity: string): QueuedSendRecord[] {
+ return (byNode.get(nodeId) ?? [])
+ .filter((s) => s.identity === identity)
+ .map(({ id, text, afterKey }) => ({ id, text, afterKey }))
+}
+
+/** Test-only reset. */
+export function clearQueuedSendsForTest(): void {
+ byNode.clear()
+}