Skip to content

The agent that grows with you

fix(desktop): freeze @terminal context at the transport boundary

Jeremy1846f93e2c57
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx
index 5052ad69882..e15adf3d419 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx
@@ -1,15 +1,20 @@
import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { clearComposerTerminalSelections, setComposerTerminalSelection } from '@/store/composer'
import {
$parkedQueueSessions,
$queuedPromptsBySession,
enqueueQueuedPrompt,
+ getFrozenQueuedTransport,
getQueuedPrompts,
isQueueParked,
MAX_AUTO_DRAIN_ATTEMPTS,
- parkQueuedPrompts
+ parkQueuedPrompts,
+ resetFrozenQueuedTransportsForTests,
+ simulateComposerQueueReloadForTests
} from '@/store/composer-queue'
+import { $notifications, clearNotifications } from '@/store/notifications'
import { setSessionsLoading } from '@/store/session'
import type { QueueEditState } from '../composer-utils'
@@ -25,11 +30,14 @@ import { useComposerQueue } from './use-composer-queue'
const SESSION_KEY = 'stored-session-queue-hook'
-function renderQueueHook(overrides: { busy?: boolean; onCancel?: () => void; onSteer?: ChatBarProps['onSteer'] } = {}) {
+function renderQueueHook(
+ overrides: { busy?: boolean; draft?: string; onCancel?: () => void; onSteer?: ChatBarProps['onSteer'] } = {}
+) {
const onSubmit = vi.fn<ChatBarProps['onSubmit']>(async () => true)
const onCancel = overrides.onCancel ?? vi.fn()
const onSteer = overrides.onSteer
const queueEditRef: { current: QueueEditState | null } = { current: null }
+ const draftRef = { current: overrides.draft ?? '' }
const hook = renderHook(
({ busy }: { busy: boolean }) =>
@@ -37,10 +45,14 @@ function renderQueueHook(overrides: { busy?: boolean; onCancel?: () => void; onS
activeQueueSessionKey: SESSION_KEY,
attachments: [],
busy,
- clearDraft: () => undefined,
- draftRef: { current: '' },
+ clearDraft: () => {
+ draftRef.current = ''
+ },
+ draftRef,
focusInput: () => undefined,
- loadIntoComposer: () => undefined,
+ loadIntoComposer: (text: string) => {
+ draftRef.current = text
+ },
onCancel,
onSteer,
onSubmit,
@@ -51,7 +63,7 @@ function renderQueueHook(overrides: { busy?: boolean; onCancel?: () => void; onS
{ initialProps: { busy: overrides.busy ?? false } }
)
- return { hook, onCancel, onSubmit }
+ return { draftRef, hook, onCancel, onSubmit }
}
describe('useComposerQueue park integration', () => {
@@ -59,6 +71,9 @@ describe('useComposerQueue park integration', () => {
window.localStorage.clear()
$queuedPromptsBySession.set({})
$parkedQueueSessions.set({})
+ clearComposerTerminalSelections()
+ clearNotifications()
+ resetFrozenQueuedTransportsForTests()
setSessionsLoading(false)
})
@@ -67,6 +82,9 @@ describe('useComposerQueue park integration', () => {
vi.restoreAllMocks()
$queuedPromptsBySession.set({})
$parkedQueueSessions.set({})
+ clearComposerTerminalSelections()
+ clearNotifications()
+ resetFrozenQueuedTransportsForTests()
setSessionsLoading(true)
})
@@ -361,4 +379,63 @@ describe('useComposerQueue park integration', () => {
expect(onCancel).not.toHaveBeenCalled()
})
})
+
+ it('freezes @terminal selection at enqueue so a later label collision cannot inject unrelated output', async () => {
+ setComposerTerminalSelection('zsh:23-58', 'selection A')
+
+ const { draftRef, hook, onSubmit } = renderQueueHook({
+ busy: true,
+ draft: 'look at @terminal:`zsh:23-58`'
+ })
+
+ act(() => {
+ expect(hook.result.current.queueCurrentDraft()).toBe(true)
+ })
+
+ const queued = getQueuedPrompts(SESSION_KEY)
+
+ expect(queued).toHaveLength(1)
+ expect(queued[0]?.text).toBe('look at @terminal:`zsh:23-58`')
+ expect(queued[0]?.displayText).toBe('look at @terminal:`zsh:23-58`')
+ expect(queued[0]?.text).not.toContain('selection A')
+ expect(getFrozenQueuedTransport(queued[0]!.id)).toContain('selection A')
+ expect(draftRef.current).toBe('')
+
+ setComposerTerminalSelection('zsh:23-58', 'selection B from another tab')
+
+ await act(async () => {
+ await hook.result.current.drainNextQueued()
+ })
+
+ expect(onSubmit).toHaveBeenCalledTimes(1)
+ expect(onSubmit.mock.calls[0]?.[0]).toContain('selection A')
+ expect(onSubmit.mock.calls[0]?.[0]).not.toContain('selection B')
+ expect(onSubmit.mock.calls[0]?.[1]).toMatchObject({
+ displayText: 'look at @terminal:`zsh:23-58`',
+ fromQueue: true
+ })
+ })
+
+ it('blocks drain after a simulated reload when the runtime terminal payload is gone', async () => {
+ setComposerTerminalSelection('zsh:23-58', 'selection A')
+
+ const { hook, onSubmit } = renderQueueHook({
+ busy: true,
+ draft: 'look at @terminal:`zsh:23-58`'
+ })
+
+ act(() => {
+ expect(hook.result.current.queueCurrentDraft()).toBe(true)
+ })
+
+ simulateComposerQueueReloadForTests()
+
+ await act(async () => {
+ expect(await hook.result.current.drainNextQueued()).toBe(false)
+ })
+
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(getQueuedPrompts(SESSION_KEY)).toHaveLength(1)
+ expect($notifications.get().some(n => n.message.includes('Re-select the lines'))).toBe(true)
+ })
})
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
index 7a319fdfdbe..8b1da251107 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
@@ -5,7 +5,7 @@ import { useI18n } from '@/i18n'
import { isSlashCommandText } from '@/lib/chat-runtime'
import { triggerHaptic } from '@/lib/haptics'
import { useSessionSlice } from '@/lib/use-session-slice'
-import { type ComposerAttachment } from '@/store/composer'
+import { type ComposerAttachment, freezeComposerTransportPayload } from '@/store/composer'
import { resetBrowseState } from '@/store/composer-input-history'
import {
$parkedQueueSessions,
@@ -31,6 +31,36 @@ import { cloneAttachments, type QueueEditState } from '../composer-utils'
import { useComposerScope } from '../scope'
import type { ChatBarProps } from '../types'
+/** Freeze terminal chips for queue persistence. Returns null when a chip has
+ * no selection payload (caller should abort without mutating the queue). */
+function freezeQueuedDraftText(
+ text: string,
+ copy: { terminalSelectionMissingTitle: string; terminalSelectionMissingBody: string }
+): null | { text: string; displayText?: string } {
+ const trimmed = text.trim()
+
+ if (!trimmed) {
+ return { text }
+ }
+
+ const frozen = freezeComposerTransportPayload(trimmed)
+
+ if (frozen.missingLabels.length > 0) {
+ notify({
+ kind: 'warning',
+ title: copy.terminalSelectionMissingTitle,
+ message: copy.terminalSelectionMissingBody
+ })
+
+ return null
+ }
+
+ return {
+ text: frozen.transportText,
+ ...(frozen.displayText !== frozen.transportText ? { displayText: frozen.displayText } : {})
+ }
+}
+
interface UseComposerQueueArgs {
activeQueueSessionKey: string | null
attachments: ComposerAttachment[]
@@ -137,9 +167,18 @@ export function useComposerQueue({
return index >= 0 // at the oldest: swallow; missing entry: let it fall through
}
+ const frozen = draftRef.current.trim()
+ ? freezeQueuedDraftText(draftRef.current, t.composer)
+ : { text: draftRef.current }
+
+ if (!frozen) {
+ return true
+ }
+
const saved = updateQueuedPrompt(queueEdit.sessionKey, queueEdit.entryId, {
attachments: cloneAttachments(attachments),
- text: draftRef.current
+ text: frozen.text,
+ displayText: frozen.displayText ?? null
})
const next = queuedPrompts[target]
@@ -184,7 +223,17 @@ export function useComposerQueue({
return false
}
- const saved = updateQueuedPrompt(queueEdit.sessionKey, queueEdit.entryId, { attachments: next, text })
+ const frozen = text.trim() ? freezeQueuedDraftText(text, t.composer) : { text }
+
+ if (!frozen) {
+ return false
+ }
+
+ const saved = updateQueuedPrompt(queueEdit.sessionKey, queueEdit.entryId, {
+ attachments: next,
+ text: frozen.text,
+ displayText: frozen.displayText ?? null
+ })
triggerHaptic(saved ? 'success' : 'selection')
} else {
triggerHaptic('cancel')
@@ -217,7 +266,22 @@ export function useComposerQueue({
return false
}
- if (!enqueueQueuedPrompt(activeQueueSessionKey, { text, attachments })) {
+ // Freeze `@terminal:` chips into transport text + chip displayText before
+ // enqueue. The selection map is memory-only and label-colliding; drain
+ // must never re-resolve against it (#77078).
+ const frozen = text.trim() ? freezeQueuedDraftText(text, t.composer) : { text }
+
+ if (!frozen) {
+ return false
+ }
+
+ if (
+ !enqueueQueuedPrompt(activeQueueSessionKey, {
+ text: frozen.text,
+ attachments,
+ ...(frozen.displayText ? { displayText: frozen.displayText } : {})
+ })
+ ) {
return false
}
@@ -228,7 +292,7 @@ export function useComposerQueue({
triggerHaptic('selection')
return true
- }, [activeQueueSessionKey, attachments, clearDraft, draftRef, scope.attachments])
+ }, [activeQueueSessionKey, attachments, clearDraft, draftRef, scope.attachments, t.composer])
// All queue drain paths share one lock + send-then-remove sequence.
// `pickEntry` lets each caller choose head, by-id, or skip-edited, from the
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
index cf84770f6c6..7d9a84c86eb 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
@@ -5,7 +5,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import * as sessionOwnerUtils from '@/app/session/hooks/use-session-actions/utils'
import { PaneVisibleContext } from '@/components/pane-shell/pane-visibility'
import { $clarifyRequests } from '@/store/clarify'
-import type { ComposerAttachment } from '@/store/composer'
+import {
+ clearComposerTerminalSelections,
+ type ComposerAttachment,
+ setComposerTerminalSelection
+} from '@/store/composer'
import { clearQueuedPrompts, getQueuedPrompts } from '@/store/composer-queue'
import { $connectionRequests, type ConnectionRequest } from '@/store/connection-request'
import { $gateway } from '@/store/gateway'
@@ -341,6 +345,7 @@ describe('useComposerSubmit busy-turn routing', () => {
afterEach(() => {
cleanup()
vi.restoreAllMocks()
+ clearComposerTerminalSelections()
})
it('treats a payload mid-turn as send (steer), not stop', async () => {
@@ -465,6 +470,59 @@ describe('useComposerSubmit busy-turn routing', () => {
expect(onSubmit).toHaveBeenCalledWith('hello', expect.objectContaining({ composerScope: 'stored-session' }))
)
})
+
+ it('leaves idle @terminal chips for the submit transport freeze (does not expand here)', async () => {
+ setComposerTerminalSelection('zsh:23-58', 'selected terminal lines')
+
+ const { hook, onSteer, onSubmit, queueCurrentDraft } = renderSubmitHook({
+ text: 'look at @terminal:`zsh:23-58`'
+ })
+
+ act(() => {
+ hook.result.current.submitDraft()
+ })
+
+ await waitFor(() =>
+ expect(onSubmit).toHaveBeenCalledWith('look at @terminal:`zsh:23-58`', {
+ attachments: [],
+ composerScope: 'stored-session'
+ })
+ )
+ expect(onSteer).not.toHaveBeenCalled()
+ expect(queueCurrentDraft).not.toHaveBeenCalled()
+ })
+
+ it('expands @terminal selection chips before steering a busy turn', async () => {
+ setComposerTerminalSelection('zsh:23-58', 'selected terminal lines')
+
+ const { hook, onSteer, queueCurrentDraft } = renderSubmitHook({
+ busy: true,
+ text: 'look at @terminal:`zsh:23-58`'
+ })
+
+ act(() => {
+ hook.result.current.submitDraft()
+ })
+
+ await waitFor(() => expect(onSteer).toHaveBeenCalledWith('```terminal\nselected terminal lines\n```\n\nlook at'))
+ expect(queueCurrentDraft).not.toHaveBeenCalled()
+ })
+
+ it('refuses to steer when a restored @terminal chip has no selection payload', () => {
+ clearComposerTerminalSelections()
+
+ const { hook, onSteer, queueCurrentDraft } = renderSubmitHook({
+ busy: true,
+ text: 'look at @terminal:`zsh:23-58`'
+ })
+
+ act(() => {
+ hook.result.current.submitDraft()
+ })
+
+ expect(onSteer).not.toHaveBeenCalled()
+ expect(queueCurrentDraft).not.toHaveBeenCalled()
+ })
})
describe('useComposerSubmit with a clarify parked on the session', () => {
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
index 0add696c58a..f2ec59a47af 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
@@ -1,13 +1,13 @@
import { SLASH_COMMAND_RE } from '@hermes/shared'
import { type RefObject, useLayoutEffect, useRef } from 'react'
+import { translateNow, useI18n } from '@/i18n'
import { usePaneVisible } from '@/components/pane-shell/pane-visibility'
-import { useI18n } from '@/i18n'
import { isSlashCommandText } from '@/lib/chat-runtime'
import { isSideTaskSlashCommand } from '@/lib/desktop-slash-commands'
import { triggerHaptic } from '@/lib/haptics'
import { hasClarifyRequest, skipClarifyRequest } from '@/store/clarify'
-import { clearSessionDraft, type ComposerAttachment, isFreshDraftScope } from '@/store/composer'
+import { clearSessionDraft, type ComposerAttachment, freezeComposerTransportPayload, isFreshDraftScope } from '@/store/composer'
import { resetBrowseState } from '@/store/composer-input-history'
import { enqueueQueuedPrompt, type QueuedPromptEntry } from '@/store/composer-queue'
import { hasConnectionRequest, skipConnectionRequest } from '@/store/connection-request'
@@ -355,21 +355,45 @@ export function useComposerSubmit({
return
}
+ // Freeze `@terminal:` chips the same way idle submit / queue enqueue do.
+ // Steer used to forward the bare token only (#77078).
+ const frozen = freezeComposerTransportPayload(text)
+
+ if (frozen.missingLabels.length > 0) {
+ notify({
+ kind: 'warning',
+ title: translateNow('composer.terminalSelectionMissingTitle'),
+ message: translateNow('composer.terminalSelectionMissingBody')
+ })
+
+ return
+ }
+
triggerHaptic('submit')
clearDraft()
// The draft is already cleared, so a refused or failed redirect must keep
// the only copy: queue it for the next turn, or restore it when there is no
- // queue yet (a new chat is busy before its first session exists).
+ // queue yet (a new chat is busy before its first session exists). Keep the
+ // frozen transport for the queue; restoring to the composer keeps the chip
+ // form so the user can re-send it as-is.
+ const hasTerminalTransport = frozen.displayText !== frozen.transportText
+
const keep = () => {
if (activeQueueSessionKey) {
- enqueueQueuedPrompt(activeQueueSessionKey, { text, attachments: [] })
+ enqueueQueuedPrompt(activeQueueSessionKey, {
+ text: frozen.displayText,
+ attachments: [],
+ ...(hasTerminalTransport
+ ? { displayText: frozen.displayText, frozenTransport: frozen.transportText }
+ : {})
+ })
} else {
- loadIntoComposer(text, [])
+ loadIntoComposer(frozen.displayText, [])
}
}
- void Promise.resolve(onSteer(text))
+ void Promise.resolve(onSteer(frozen.transportText))
.then(accepted => {
if (!accepted) {
keep()
diff --git a/apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx b/apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx
index f4241b5bbb7..e996fd80472 100644
--- a/apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx
@@ -159,6 +159,30 @@ describe('useBackgroundQueueDrain', () => {
}
})
+ it('forwards queued displayText so frozen @terminal chips render in the bubble', async () => {
+ const runtimeMap = { current: new Map([['stored-session-a', 'rt-session-a']]) }
+ const submitText = vi.fn(async () => true)
+
+ enqueueQueuedPrompt('stored-session-a', {
+ text: '```terminal\nselection A\n```\n\nlook at',
+ displayText: 'look at @terminal:`zsh:23-58`',
+ attachments: []
+ })
+ clearAllSessionStates()
+
+ render(<Harness runtimeMap={runtimeMap} submitText={submitText} />)
+
+ await waitFor(() => {
+ expect(submitText).toHaveBeenCalledWith('```terminal\nselection A\n```\n\nlook at', {
+ attachments: [],
+ displayText: 'look at @terminal:`zsh:23-58`',
+ fromQueue: true,
+ sessionId: 'rt-session-a',
+ storedSessionId: 'stored-session-a'
+ })
+ })
+ })
+
it('leaves the selected session queue to the mounted ChatBar drainer', async () => {
const runtimeMap = { current: new Map([['stored-session-a', 'rt-session-a']]) }
const submitText = vi.fn(async () => true)
diff --git a/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts b/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts
index df1074ee80f..414c0da2848 100644
--- a/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts
+++ b/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts
@@ -176,6 +176,7 @@ export function useBackgroundQueueDrain({
const accepted = await Promise.resolve(
submitTextRef.current(liveEntry.text, {
attachments: liveEntry.attachments,
+ ...(liveEntry.displayText ? { displayText: liveEntry.displayText } : {}),
fromQueue: true,
sessionId: runtimeSessionId,
storedSessionId: sessionKey
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
index 82148a5aa61..25c838eed00 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
@@ -2,7 +2,7 @@ import type { PromptSubmitResult } from '@hermes/shared'
import { type MutableRefObject, useCallback } from 'react'
import { PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } from '@/hermes'
-import type { Translations } from '@/i18n'
+import { translateNow, type Translations } from '@/i18n'
import { type ChatMessage, finalizeInterruptedMessages, textPart } from '@/lib/chat-messages'
import { optimisticAttachmentRef } from '@/lib/chat-runtime'
import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'
@@ -17,9 +17,9 @@ import {
import {
$composerAttachments,
type ComposerAttachment,
+ freezeComposerTransportPayload,
mainComposerScope,
- revokeDiscardedAttachmentPreviews,
- terminalContextBlocksFromDraft
+ revokeDiscardedAttachmentPreviews
} from '@/store/composer'
import { noteMessageSent } from '@/store/desktop-metrics'
import { $hudMode } from '@/store/hud'
@@ -167,7 +167,6 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
return useCallback(
async (rawText: string, options?: SubmitTextOptions) => {
- const visibleText = sanitizeComposerInput(rawText).trim()
const usingComposerAttachments = !options?.attachments
// Drop undefined/null holes a session switch or draft restore can leave in
@@ -183,7 +182,34 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
a => typeof a.titlePreview === 'string' && a.titlePreview.trim()
)?.titlePreview
- const terminalContextBlocks = terminalContextBlocksFromDraft(rawText).join('\n\n')
+ // Freeze `@terminal:` chips into transport text before send. Queue drains
+ // already carry frozen transport (tokens stripped at enqueue) — never
+ // re-resolve against the live selection map, or a later Cmd+L that reused
+ // the same shell:row label silently injects unrelated output (#77078).
+ let transportRaw = rawText
+ let bubbleOverride = options?.displayText
+
+ if (!options?.fromQueue) {
+ const frozen = freezeComposerTransportPayload(rawText)
+
+ if (frozen.missingLabels.length > 0) {
+ notify({
+ kind: 'warning',
+ title: translateNow('composer.terminalSelectionMissingTitle'),
+ message: translateNow('composer.terminalSelectionMissingBody')
+ })
+
+ return false
+ }
+
+ transportRaw = frozen.transportText
+
+ if (!bubbleOverride && frozen.displayText !== frozen.transportText) {
+ bubbleOverride = frozen.displayText
+ }
+ }
+
+ const visibleText = sanitizeComposerInput(transportRaw).trim()
const hasImage = attachments.some(a => a.kind === 'image')
// Refs are recomputed after sync (file.attach rewrites @file: refs to
@@ -203,8 +229,9 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
.filter(Boolean)
.join('\n')
+ // Terminal fences live inside visibleText (frozen above / at enqueue).
return (
- [contextRefs, terminalContextBlocks, visibleText].filter(Boolean).join('\n\n') ||
+ [contextRefs, visibleText].filter(Boolean).join('\n\n') ||
(present.some(a => a.kind === 'image') ? 'What do you see in this image?' : '')
)
}
@@ -218,7 +245,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
// not the foreground flag: an explicit target (tile, queue drain) is
// frequently not the session on screen, so the foreground flag would gate
// one session's send on another session's turn.
- const hasSendable = Boolean(visibleText || terminalContextBlocks || attachments.length || hasImage)
+ const hasSendable = Boolean(visibleText || attachments.length || hasImage)
const guardSessionId = options?.sessionId ?? activeSessionIdRef.current
@@ -415,7 +442,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
// skill body as its text — model-facing scaffolding — so the dispatcher
// hands us the invocation to render instead. Everything else shows what
// was typed.
- const bubbleText = options?.displayText ?? visibleText
+ const bubbleText = bubbleOverride ?? visibleText
// Keep the user-send boundary stable when later ref resolution rewrites
// the optimistic bubble in place.
const submittedAt = Date.now() / 1000
diff --git a/apps/desktop/src/i18n/ar_chat.ts b/apps/desktop/src/i18n/ar_chat.ts
index 1e24ba3b1b5..adfb2540ea3 100644
--- a/apps/desktop/src/i18n/ar_chat.ts
+++ b/apps/desktop/src/i18n/ar_chat.ts
@@ -145,6 +145,11 @@ export const arChat = {
queueDroppedTitle: 'تم إسقاط عنصر قائمة الانتظار',
queueDroppedBody:
'أُسقط هذا العنصر في الخلفية لأن جلسته تعذّر استئنافها بعد محاولات متكررة. بقية قائمة الانتظار لم تتأثر.',
+ terminalSelectionMissingTitle: 'تحديد الطرفية غير متاح',
+ terminalSelectionMissingBody:
+ 'أعد تحديد أسطر الطرفية (Ctrl/Cmd+L) قبل الإرسال — لا يحتوي هذا الوسم على النص الأصلي.',
+ queuedTerminalSelectionExpiredBody:
+ 'تحديد الطرفية في قائمة الانتظار لم يعد متاحا. أعد تحديد الأسطر (Ctrl/Cmd+L) وضع الرسالة في القائمة مجددا.',
previewUnavailable: 'المعاينة غير متاحة',
previewLabel: label => `معاينة ${label}`,
couldNotPreview: label => `تعذرت معاينة ${label}`,
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 39a9f821af6..acb1788e27e 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -3958,6 +3958,11 @@ export const en: Translations = {
queueDroppedTitle: 'Queued prompt dropped',
queueDroppedBody:
'This background queue entry was dropped because its session could not be resumed after repeated attempts. Nothing else in the queue was affected.',
+ terminalSelectionMissingTitle: 'Terminal selection unavailable',
+ terminalSelectionMissingBody:
+ 'Re-select the terminal lines (Ctrl/Cmd+L) before sending — this chip has no original text.',
+ queuedTerminalSelectionExpiredBody:
+ 'This queued terminal selection is no longer available. Re-select the lines (Ctrl/Cmd+L) and queue the message again.',
previewUnavailable: 'Preview unavailable',
previewLabel: label => `Preview ${label}`,
couldNotPreview: label => `Could not preview ${label}`,
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 303dac642f4..6621b3beb8f 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -2854,6 +2854,11 @@ export const ja = defineLocale({
queueDroppedTitle: 'キューのエントリを破棄しました',
queueDroppedBody:
'このバックグラウンドのエントリは、セッションを繰り返し再開できなかったため破棄されました。キューの他のエントリには影響しません。',
+ terminalSelectionMissingTitle: 'ターミナル選択を利用できません',
+ terminalSelectionMissingBody:
+ '送信前にターミナル行を再選択(Ctrl/Cmd+L)してください — チップに元のテキストがありません。',
+ queuedTerminalSelectionExpiredBody:
+ 'キュー内のターミナル選択はもう利用できません。行を再選択(Ctrl/Cmd+L)して、もう一度キューに入れてください。',
previewUnavailable: 'プレビューは利用できません',
previewLabel: label => `${label} のプレビュー`,
couldNotPreview: label => `${label} をプレビューできませんでした`,
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index e22396430e1..43e8300ed52 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -3279,6 +3279,9 @@ export interface Translations {
queueStuckBody: string
queueDroppedTitle: string
queueDroppedBody: string
+ terminalSelectionMissingTitle: string
+ terminalSelectionMissingBody: string
+ queuedTerminalSelectionExpiredBody: string
previewUnavailable: string
previewLabel: (label: string) => string
couldNotPreview: (label: string) => string
diff --git a/apps/desktop/src/i18n/zh-hant_chat.ts b/apps/desktop/src/i18n/zh-hant_chat.ts
index 1469fd0186a..a4d3049865a 100644
--- a/apps/desktop/src/i18n/zh-hant_chat.ts
+++ b/apps/desktop/src/i18n/zh-hant_chat.ts
@@ -168,6 +168,9 @@ export const zhHantChat = {
queueStuckBody: '佇列中的對話多次傳送失敗。它仍在佇列中,請重試傳送。',
queueDroppedTitle: '已捨棄佇列內容',
queueDroppedBody: '該背景佇列項目因工作階段多次嘗試後仍無法恢復而遭捨棄。佇列中的其他內容不受影響。',
+ terminalSelectionMissingTitle: '無法使用終端選區',
+ terminalSelectionMissingBody: '傳送前請重新選擇終端行(Ctrl/Cmd+L)— 此標籤沒有原始文字。',
+ queuedTerminalSelectionExpiredBody: '佇列中的終端選區已無法使用。請重新選取行(Ctrl/Cmd+L)並再次加入佇列。',
previewUnavailable: '預覽不可用',
previewLabel: label => `預覽 ${label}`,
couldNotPreview: label => `無法預覽 ${label}`,
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index f15efba3ac9..a5419735005 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -3722,6 +3722,9 @@ export const zh = defineLocale({
queueStuckBody: '排队的对话多次发送失败。它仍在队列中,请重试发送。',
queueDroppedTitle: '已丢弃排队内容',
queueDroppedBody: '该后台队列条目因会话多次尝试后仍无法恢复而被丢弃。队列中的其他内容不受影响。',
+ terminalSelectionMissingTitle: '无法使用终端选区',
+ terminalSelectionMissingBody: '发送前请重新选择终端行(Ctrl/Cmd+L)— 此标签没有原始文本。',
+ queuedTerminalSelectionExpiredBody: '队列中的终端选区已不可用。请重新选择行(Ctrl/Cmd+L)并再次加入队列。',
previewUnavailable: '预览不可用',
previewLabel: label => `预览 ${label}`,
couldNotPreview: label => `无法预览 ${label}`,
diff --git a/apps/desktop/src/store/composer-queue.ts b/apps/desktop/src/store/composer-queue.ts
index ef990b82dad..8465a1e68f5 100644
--- a/apps/desktop/src/store/composer-queue.ts
+++ b/apps/desktop/src/store/composer-queue.ts
@@ -335,7 +335,7 @@ export const promoteQueuedPrompt = (key: string | null | undefined, id: string):
export const updateQueuedPrompt = (
key: string | null | undefined,
id: string,
- update: { text: string; attachments?: ComposerAttachment[] }
+ update: { text: string; attachments?: ComposerAttachment[]; displayText?: string | null }
): boolean => {
const sid = sidOf(key)
@@ -353,7 +353,14 @@ export const updateQueuedPrompt = (
const attachments = update.attachments ? cloneAttachments(update.attachments) : entry.attachments
- if (entry.text === update.text && !update.attachments) {
+ const nextDisplay =
+ update.displayText === undefined ? undefined : update.displayText === null ? undefined : update.displayText
+
+ if (
+ entry.text === update.text &&
+ !update.attachments &&
+ (update.displayText === undefined || nextDisplay === entry.displayText)
+ ) {
return entry
}
@@ -365,10 +372,15 @@ export const updateQueuedPrompt = (
// The user rewrote the text, so any display projection it carried (a
// `/skill` invocation standing in for the expanded body) no longer
- // describes it — what they typed is now what sends.
+ // describes it — unless the caller froze a new chip/display pair.
const { displayText: _dropped, ...rest } = entry
- return { ...rest, text: update.text, attachments }
+ return {
+ ...rest,
+ text: update.text,
+ attachments,
+ ...(nextDisplay ? { displayText: nextDisplay } : {})
+ }
})
return changed ? next : null
diff --git a/apps/desktop/src/store/composer.test.ts b/apps/desktop/src/store/composer.test.ts
index 244a4dc0e54..9eb88375d29 100644
--- a/apps/desktop/src/store/composer.test.ts
+++ b/apps/desktop/src/store/composer.test.ts
@@ -7,16 +7,19 @@ import {
addComposerAttachment,
adoptGoneSessionDraft,
announceGoneSessionDraft,
+ clearComposerTerminalSelections,
clearSessionDraft,
type ComposerAttachment,
createComposerAttachmentOccurrenceId,
createComposerAttachmentScope,
+ freezeComposerTransportPayload,
mainComposerScope,
migrateSessionDraft,
removeComposerAttachment,
requestVoiceConversationStart,
revokeAttachmentPreviewUrls,
SESSION_DRAFTS_STORAGE_KEY,
+ setComposerTerminalSelection,
stashSessionDraft,
takeSessionDraft,
takeVoiceConversationStart,
@@ -385,3 +388,57 @@ describe('session drafts', () => {
clearSessionDraft('to')
})
})
+
+describe('freezeComposerTransportPayload', () => {
+ afterEach(() => {
+ clearComposerTerminalSelections()
+ })
+
+ it('leaves ordinary text unchanged', () => {
+ const frozen = freezeComposerTransportPayload('just a question')
+
+ expect(frozen.transportText).toBe('just a question')
+ expect(frozen.displayText).toBe('just a question')
+ expect(frozen.missingLabels).toEqual([])
+ })
+
+ it('freezes @terminal chips into fenced transport and keeps chips for display', () => {
+ setComposerTerminalSelection('zsh:23-58', 'selected terminal lines')
+
+ const frozen = freezeComposerTransportPayload('look at @terminal:`zsh:23-58`')
+
+ expect(frozen.transportText).toBe('```terminal\nselected terminal lines\n```\n\nlook at')
+ expect(frozen.displayText).toBe('look at @terminal:`zsh:23-58`')
+ expect(frozen.missingLabels).toEqual([])
+ })
+
+ it('does not expand a second time when transport is already frozen', () => {
+ setComposerTerminalSelection('zsh:23-58', 'selected terminal lines')
+
+ const once = freezeComposerTransportPayload('look at @terminal:`zsh:23-58`')
+ const twice = freezeComposerTransportPayload(once.transportText)
+
+ expect(twice.transportText).toBe(once.transportText)
+ expect(twice.displayText).toBe(once.transportText)
+ expect((once.transportText.match(/```terminal/g) ?? []).length).toBe(1)
+ })
+
+ it('reports unresolved chips instead of sending a bare token', () => {
+ const frozen = freezeComposerTransportPayload('look at @terminal:`zsh:23-58`')
+
+ expect(frozen.missingLabels).toEqual(['zsh:23-58'])
+ expect(frozen.transportText).toBe('look at @terminal:`zsh:23-58`')
+ expect(frozen.displayText).toBe('look at @terminal:`zsh:23-58`')
+ })
+
+ it('freezes multiple selections in document order', () => {
+ setComposerTerminalSelection('zsh:10-12', 'first block')
+ setComposerTerminalSelection('bash:3-9', 'second block')
+
+ const frozen = freezeComposerTransportPayload('compare @terminal:`bash:3-9` with @terminal:`zsh:10-12`')
+
+ expect(frozen.transportText).toBe('```terminal\nsecond block\n```\n\n```terminal\nfirst block\n```\n\ncompare with')
+ expect(frozen.displayText).toBe('compare @terminal:`bash:3-9` with @terminal:`zsh:10-12`')
+ expect(frozen.missingLabels).toEqual([])
+ })
+})
diff --git a/apps/desktop/src/store/composer.ts b/apps/desktop/src/store/composer.ts
index 6ba04bb9e74..f24862e304d 100644
--- a/apps/desktop/src/store/composer.ts
+++ b/apps/desktop/src/store/composer.ts
@@ -791,6 +791,76 @@ export function reconcileComposerTerminalSelections(draft: string) {
}
}
+function terminalFence(text: string) {
+ return `\`\`\`terminal\n${text}\n\`\`\``
+}
+
+function stripTerminalRefTokens(draft: string) {
+ return draft
+ .replace(new RegExp(TERMINAL_REF_RE.source, 'g'), '')
+ .replace(/[ \t]{2,}/g, ' ')
+ .replace(/[ \t]+\n/g, '\n')
+ .replace(/\n[ \t]+/g, '\n')
+ .trim()
+}
+
+export interface ComposerTransportPayload {
+ /** Model-facing text: fenced selection blocks with `@terminal:` chips stripped. */
+ transportText: string
+ /** UI-facing text: original chip form, when it differs from transport. */
+ displayText: string
+ /** Chip labels whose selection text is missing from the in-memory map. */
+ missingLabels: string[]
+}
+
+/**
+ * Freeze `@terminal:` chips into transport text at the moment a message
+ * crosses a send/steer/enqueue boundary. The selection map is memory-only and
+ * label-colliding — later resolve against it can inject a different pane's
+ * output (#77078). Callers that cannot resolve every chip must fail closed.
+ *
+ * Idempotent: already-frozen transport (no chips) is returned unchanged.
+ */
+export function freezeComposerTransportPayload(
+ draft: string,
+ selections: Record<string, string> = $composerTerminalSelections.get()
+): ComposerTransportPayload {
+ const labels = terminalLabelsFromDraft(draft)
+
+ if (labels.length === 0) {
+ return { transportText: draft, displayText: draft, missingLabels: [] }
+ }
+
+ const missingLabels = labels.filter(label => !selections[label]?.trim())
+
+ if (missingLabels.length > 0) {
+ return { transportText: draft, displayText: draft, missingLabels }
+ }
+
+ const existingFences = new Set(draft.match(/```terminal\n[\s\S]*?\n```/g) ?? [])
+ const fences: string[] = []
+
+ for (const label of labels) {
+ const text = selections[label]?.trim()
+
+ if (!text) {
+ continue
+ }
+
+ const fence = terminalFence(text)
+
+ if (!existingFences.has(fence)) {
+ fences.push(fence)
+ existingFences.add(fence)
+ }
+ }
+
+ const remainder = stripTerminalRefTokens(draft)
+ const transportText = [...fences, remainder].filter(Boolean).join('\n\n')
+
+ return { transportText, displayText: draft, missingLabels: [] }
+}
+
export function terminalContextBlocksFromDraft(draft: string) {
const labels = terminalLabelsFromDraft(draft)
@@ -807,7 +877,7 @@ export function terminalContextBlocksFromDraft(draft: string) {
return []
}
- return `\`\`\`terminal\n${text}\n\`\`\``
+ return terminalFence(text)
})
}