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.

feat(chat): draw shell mode and `!` commands as Claude Code's TUI does

Paul Robertson5797114c7e2c
diff --git a/CLAUDE.md b/CLAUDE.md
index a2bfbe969..24f71dce2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4594,6 +4594,17 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
terminal equivalent. Surfaces: Desktop + Server Edition identical (dictation and uploads already
bridge — `files.saveUpload`, `speech.*`); SSH nodes upload to the host; kanban card modal shares
ChatPanel and wires both props; relay tabs keep the panel's existing refusal; mobile N/A.
+ **Shell mode is drawn as Claude Code's TUI draws it** (`lib/chatShellMode.ts`, claude and custom
+ agents built on it; MEASURED on 2.1.319): a draft starting with `!` — typed into an empty box or at
+ the start of existing text, the TUI's rule — shows its `!` in `--sys-pink` beside the textarea, not
+ in it, with a pink border and the TUI's own "! for shell mode" under the box; Backspace at the very
+ start leaves it. The DRAFT keeps the `!` (it is what the send types and what puts the TUI in shell
+ mode); only the display changes, and the completion/highlight stand down (the caret snapshot holds
+ the shown text, not the draft). The `!` slot is always rendered so the textarea is never remounted.
+ A `!` command in the THREAD (`nodes/ChatShellCommand.tsx`) is the TUI's `! cmd` with its output's
+ first line under a `⎿`, opening to the whole output: the reader keeps a bash-family output's lines
+ (`BASH_OUTPUT_MAX`, 16384) instead of `summarizeResult`, and gives a command that printed nothing
+ `result: ""` (chat-fixtures README rules 4-5).
Fix-round rules (same day): the composer is its OWN component (`nodes/ChatComposer.tsx`) so the
thread and the composer restyle independently. A label click is an explicit "go to the
terminal", so the flip FOCUSES the xterm whatever its entry state was
diff --git a/src/core/chat-fixtures.test.ts b/src/core/chat-fixtures.test.ts
index 0bd457c70..9fc6845b4 100644
--- a/src/core/chat-fixtures.test.ts
+++ b/src/core/chat-fixtures.test.ts
@@ -359,6 +359,9 @@ function bashMode(): string {
isMeta(user(CAVEAT)),
user('<bash-input>cat missing.txt</bash-input>'),
user('<bash-stdout></bash-stdout><bash-stderr>cat: missing.txt: No such file or directory</bash-stderr>'),
+ isMeta(user(CAVEAT)),
+ user('<bash-input>true</bash-input>'),
+ user('<bash-stdout></bash-stdout><bash-stderr></bash-stderr>'),
user('What was in a.txt?'),
assistant([text('Twelve bytes of demo text.')])
])
diff --git a/src/core/transcript-reader.test.ts b/src/core/transcript-reader.test.ts
index c96d7b381..7e529e023 100644
--- a/src/core/transcript-reader.test.ts
+++ b/src/core/transcript-reader.test.ts
@@ -1,5 +1,6 @@
import fs from 'fs'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { BASH_OUTPUT_MAX } from '../shared/chat-command'
import {
parseTranscriptLines,
pickSessionName,
@@ -1068,11 +1069,35 @@ describe('parseChatMessages — local-command records', () => {
).split('\n')
)
expect(msgs).toEqual([
- { role: 'assistant', parts: [{ kind: 'tool', name: '!', arg: 'ls -la', result: 'a.txt b.txt warn' }] },
+ { role: 'assistant', parts: [{ kind: 'tool', name: '!', arg: 'ls -la', result: 'a.txt\nb.txt\nwarn' }] },
{ role: 'assistant', parts: [{ kind: 'tool', name: '!', arg: 'false', result: 'failed' }] }
])
})
+ it('bash mode keeps the output lines, up to BASH_OUTPUT_MAX', () => {
+ const long = Array.from({ length: 4000 }, (_, i) => `line ${i}`).join('\n')
+
+ const msgs = parseChatMessages(
+ (userStr('<bash-input>seq</bash-input>') + userStr(`<bash-stdout>${long}</bash-stdout><bash-stderr></bash-stderr>`)).split('\n')
+ )
+
+ const result = (msgs[0].parts[0] as { result?: string }).result ?? ''
+ expect(result.length).toBe(BASH_OUTPUT_MAX)
+ expect(result.startsWith('line 0\nline 1\nline 2\n')).toBe(true)
+ })
+
+ it('bash mode records a command that printed nothing, and drops empty output with no command', () => {
+ const msgs = parseChatMessages(
+ (
+ userStr('<bash-input>true</bash-input>') +
+ userStr('<bash-stdout></bash-stdout><bash-stderr></bash-stderr>') +
+ userStr('<bash-stdout></bash-stdout><bash-stderr></bash-stderr>')
+ ).split('\n')
+ )
+
+ expect(msgs).toEqual([{ role: 'assistant', parts: [{ kind: 'tool', name: '!', arg: 'true', result: '' }] }])
+ })
+
it('bash output never attaches to a slash command (and vice versa)', () => {
const msgs = parseChatMessages((cmdRec('/model') + userStr('<bash-stdout>x</bash-stdout><bash-stderr></bash-stderr>')).split('\n'))
expect(msgs[0].parts[0]).toEqual({ kind: 'tool', name: '/model', arg: '' })
diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.ts
index 1890f9c85..a40a07880 100644
--- a/src/core/transcript-reader.ts
+++ b/src/core/transcript-reader.ts
@@ -12,7 +12,7 @@ import { capText, toolBody } from './chat-tool-body'
import { isRecord } from '../shared/is-record'
import { CLAUDE_TOOL_INTERRUPT_MARKER, claudeInterruptMarkerOf } from '../shared/agents/claude-interrupt'
import { ASK_USER_QUESTION_TOOL, readQuestions } from '../shared/agents/permission-answer'
-import { BASH_COMMAND_TOOL, CHAT_TOOL_ARG_MAX, COMMAND_OUTPUT_TOOL } from '../shared/chat-command'
+import { BASH_COMMAND_TOOL, BASH_OUTPUT_MAX, CHAT_TOOL_ARG_MAX, COMMAND_OUTPUT_TOOL } from '../shared/chat-command'
import {
AGENT_MESSAGE_TOOL,
BACKGROUND_TASK_TOOL,
@@ -119,6 +119,13 @@ function outputText(tags: Map<string, string>): string {
.join('\n')
}
+/** A command's output as its tool part's `result`. A `!` command's keeps its lines, capped at
+ * BASH_OUTPUT_MAX (the chat view shows the first line under the command, all of it when opened); a
+ * slash command's is summarized like a tool result. */
+function commandOutputResult(family: 'slash' | 'bash', text: string): string {
+ return family === 'bash' ? text.slice(0, BASH_OUTPUT_MAX) : summarizeResult(text)
+}
+
/** A command's arg: trimmed, then capped like `toolArg` (the composer's `sentCommand` agrees). */
const capArg = (v: string | undefined): string => (v ?? '').trim().slice(0, CHAT_TOOL_ARG_MAX)
@@ -801,12 +808,13 @@ function parseChatRecords(
push({ role: 'assistant', parts: [part] }, offset)
awaitingOutput = { family: cmd.family, part }
} else if (cmd?.kind === 'output') {
- const s = summarizeResult(cmd.text)
- if (!s) continue
- if (awaitingOutput && awaitingOutput.family === cmd.family) {
+ const s = commandOutputResult(cmd.family, cmd.text)
+ // A `!` command that printed nothing still gets its (empty) result, so the chat view can say
+ // so instead of looking unfinished. Any other empty output is skipped, as before.
+ if (awaitingOutput && awaitingOutput.family === cmd.family && (s !== '' || cmd.family === 'bash')) {
awaitingOutput.part.result = s
awaitingOutput = null
- } else {
+ } else if (s !== '') {
push({ role: 'assistant', parts: [{ kind: 'tool', name: COMMAND_OUTPUT_TOOL, arg: '', result: s }] }, offset)
}
} else {
diff --git a/src/renderer/lib/chatShellMode.test.ts b/src/renderer/lib/chatShellMode.test.ts
new file mode 100644
index 000000000..d22cd2432
--- /dev/null
+++ b/src/renderer/lib/chatShellMode.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest'
+import { draftFromDisplay, isShellDraft, shellDisplayText, showsShellMode } from './chatShellMode'
+
+describe('chatShellMode', () => {
+ it('styles shell mode for claude only', () => {
+ expect(showsShellMode('claude')).toBe(true)
+ expect(showsShellMode('codex')).toBe(false)
+ expect(showsShellMode(undefined)).toBe(false)
+ })
+
+ it('is shell mode exactly when the draft starts with `!`', () => {
+ expect(isShellDraft('!ls')).toBe(true)
+ expect(isShellDraft('!')).toBe(true)
+ expect(isShellDraft('ls !')).toBe(false)
+ expect(isShellDraft('')).toBe(false)
+ })
+
+ it('shows the text after the `!`, and puts it back', () => {
+ expect(shellDisplayText('!ls', true)).toBe('ls')
+ expect(draftFromDisplay('ls', true)).toBe('!ls')
+ expect(shellDisplayText('!ls', false)).toBe('!ls')
+ expect(draftFromDisplay('!ls', false)).toBe('!ls')
+ })
+})
diff --git a/src/renderer/lib/chatShellMode.ts b/src/renderer/lib/chatShellMode.ts
new file mode 100644
index 000000000..56d6e934d
--- /dev/null
+++ b/src/renderer/lib/chatShellMode.ts
@@ -0,0 +1,34 @@
+import { capabilityAgentId } from '@shared/agents/config'
+
+// Shell mode in the ⌘M chat composer, drawn the way Claude Code's TUI draws it. MEASURED on Claude
+// Code 2.1.319 in a private tmux server: a `!` typed into the input box — empty, or at the start of
+// existing text — switches the box to shell mode. The `!` is not part of the text any more: it
+// replaces the `❯` prompt, the box's rules turn pink (256-colour 211), and the status lines under the
+// box are replaced by `! for shell mode` in the same pink. Backspace in an empty box leaves it.
+//
+// The chat draft keeps the leading `!` (it is what the send types, and what puts the TUI in shell
+// mode), so "the draft starts with `!`" is exactly the TUI's rule. Only the composer's DISPLAY
+// changes: the textarea shows the text after the `!`, and the `!` is drawn beside it.
+//
+// Claude only (and custom agents built on it): no other agent's shell mode has been measured.
+
+/** Claude Code's own hint under the box, verbatim. */
+export const SHELL_MODE_HINT = '! for shell mode'
+
+export function showsShellMode(agentId: string | undefined | null): boolean {
+ return typeof agentId === 'string' && capabilityAgentId(agentId) === 'claude'
+}
+
+export function isShellDraft(draft: string): boolean {
+ return draft.startsWith('!')
+}
+
+/** What the textarea shows for a draft: the text after the `!` in shell mode, else the draft. */
+export function shellDisplayText(draft: string, shell: boolean): string {
+ return shell ? draft.slice(1) : draft
+}
+
+/** The draft for what the textarea now shows. */
+export function draftFromDisplay(text: string, shell: boolean): string {
+ return shell ? `!${text}` : text
+}
diff --git a/src/renderer/nodes/ChatComposer.shell.test.tsx b/src/renderer/nodes/ChatComposer.shell.test.tsx
new file mode 100644
index 000000000..bde886508
--- /dev/null
+++ b/src/renderer/nodes/ChatComposer.shell.test.tsx
@@ -0,0 +1,177 @@
+// @vitest-environment jsdom
+import { act, useState } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+/**
+ * Shell mode in the ⌘M composer against the REAL component (lib/chatShellMode.ts): a draft starting
+ * with `!` shows the `!` beside the textarea instead of in it, gets the shell-mode border and Claude
+ * Code's "! for shell mode" hint, and Backspace at the start leaves it. The draft itself keeps the
+ * `!`, because that is what the send types into the terminal.
+ */
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const { api } = vi.hoisted(() => ({
+ api: {
+ pty: { sendText: vi.fn(async () => true as const) },
+ chat: { catalog: vi.fn(async () => ({ version: 1, entries: [] })) },
+ files: { quickOpen: vi.fn(async () => []) }
+ }
+}))
+vi.mock('../session/session', () => ({ useSession: () => ({ api }) }))
+
+import { ChatComposer } from './ChatComposer'
+
+let host: HTMLDivElement
+let root: Root
+let draft: () => string
+let onSend: ReturnType<typeof vi.fn<() => void>>
+
+function Harness({ agentId = 'claude', initial = '' }: { agentId?: string; initial?: string }) {
+ const [value, setValue] = useState(initial)
+ draft = () => value
+ return (
+ <ChatComposer
+ nodeId="n1"
+ agentId={agentId}
+ agentLabel="Agent"
+ value={value}
+ onChange={setValue}
+ onSend={() => onSend()}
+ placeholder="Message"
+ disabled={false}
+ onWriteRefused={() => {}}
+ />
+ )
+}
+
+const ta = () => host.querySelector('textarea') as HTMLTextAreaElement
+const box = () => host.querySelector('.term-chat__composer') as HTMLDivElement
+const mark = () => host.querySelector('.term-chat__shell-mark')
+const hint = () => host.querySelector('.term-chat__shell-hint')
+
+async function mount(props: { agentId?: string; initial?: string } = {}): Promise<void> {
+ await act(async () => root.render(<Harness {...props} />))
+}
+
+/** Types into the textarea: its shown text becomes `text`, with the caret at `caret`. */
+async function type(text: string, caret = text.length): Promise<void> {
+ const el = ta()
+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!
+ await act(async () => {
+ setter.call(el, text)
+ el.setSelectionRange(caret, caret)
+ el.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+}
+
+async function press(key: string, caret = 0): Promise<void> {
+ const el = ta()
+ el.setSelectionRange(caret, caret)
+ await act(async () => {
+ el.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }))
+ })
+}
+
+beforeEach(() => {
+ onSend = vi.fn<() => void>()
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+afterEach(async () => {
+ await act(async () => root.unmount())
+ host.remove()
+})
+
+describe('ChatComposer shell mode', () => {
+ it('enters shell mode on a `!` typed into an empty box', async () => {
+ await mount()
+
+ await type('!')
+
+ expect(draft()).toBe('!')
+ expect(ta().value).toBe('')
+ expect(mark()?.textContent).toBe('!')
+ expect(box().classList.contains('term-chat__composer--shell')).toBe(true)
+ expect(hint()?.textContent).toBe('! for shell mode')
+ expect(ta().getAttribute('aria-describedby')).toBe(hint()?.id)
+ })
+
+ it('shows the command without its `!`, and keeps the `!` in the draft', async () => {
+ await mount({ initial: '!ls' })
+
+ await type('ls -la')
+
+ expect(ta().value).toBe('ls -la')
+ expect(draft()).toBe('!ls -la')
+ })
+
+ it('enters shell mode on a `!` typed at the start of existing text, with the caret still before it', async () => {
+ await mount({ initial: 'abc' })
+
+ await type('!abc', 1)
+
+ expect(draft()).toBe('!abc')
+ expect(ta().value).toBe('abc')
+ expect(ta().selectionStart).toBe(0)
+ })
+
+ it('leaves shell mode on Backspace at the start, keeping the text', async () => {
+ await mount({ initial: '!ls' })
+
+ await press('Backspace', 0)
+
+ expect(draft()).toBe('ls')
+ expect(mark()).toBeNull()
+ expect(hint()).toBeNull()
+ expect(box().classList.contains('term-chat__composer--shell')).toBe(false)
+ })
+
+ it('treats Backspace elsewhere in the line as an ordinary delete', async () => {
+ await mount({ initial: '!ls' })
+
+ await press('Backspace', 2)
+
+ expect(draft()).toBe('!ls')
+ })
+
+ it('sends the draft with its `!`', async () => {
+ await mount({ initial: '!ls' })
+
+ await press('Enter', 2)
+
+ expect(onSend).toHaveBeenCalledTimes(1)
+ expect(draft()).toBe('!ls')
+ })
+
+ it('offers no `/` menu in shell mode', async () => {
+ await mount({ initial: '!' })
+
+ await type('/he')
+
+ expect(host.querySelector('[role="listbox"]')).toBeNull()
+ })
+
+ it('keeps the textarea (and the keyboard) across the switch', async () => {
+ await mount()
+ const before = ta()
+ before.focus()
+
+ await type('!')
+
+ expect(ta()).toBe(before)
+ expect(document.activeElement).toBe(before)
+ })
+
+ it('leaves another agent\'s `!` as plain text', async () => {
+ await mount({ agentId: 'codex' })
+
+ await type('!ls')
+
+ expect(ta().value).toBe('!ls')
+ expect(mark()).toBeNull()
+ expect(hint()).toBeNull()
+ })
+})
diff --git a/src/renderer/nodes/ChatComposer.tsx b/src/renderer/nodes/ChatComposer.tsx
index f9c3092f8..3d02dc3b9 100644
--- a/src/renderer/nodes/ChatComposer.tsx
+++ b/src/renderer/nodes/ChatComposer.tsx
@@ -27,6 +27,7 @@ import { Spinner } from '../components/Spinner'
import { builtinSlashCommands, sanitizeChatCatalog, type ChatCatalogEntry } from '@shared/chat-catalog'
import { prepareQuickOpenFiles, type QuickOpenIndexedFile } from '../lib/quickOpenSearch'
import { commandSegments, mentionsSlashToken } from '../lib/chatComposerHighlight'
+import { SHELL_MODE_HINT, draftFromDisplay, isShellDraft, shellDisplayText, showsShellMode } from '../lib/chatShellMode'
import {
CATALOG_REUSE_MS,
applyCompletion,
@@ -148,6 +149,24 @@ export function ChatComposer({
// Until the core catalog answers — and for good on a surface that has none (a relay tab) — the `/`
// menu shows the shared built-in table for this agent.
const listboxId = useId()
+ // Shell mode (lib/chatShellMode.ts): a draft starting with `!` shows its `!` beside the textarea,
+ // not in it. The completion below then stands down by itself: the caret snapshot holds the TEXT
+ // the textarea shows, which is not the draft, so no trigger is derived (Claude's TUI offers no
+ // `/` menu in shell mode either).
+ const shell = showsShellMode(agentId) && isShellDraft(value)
+ const display = shellDisplayText(value, shell)
+ const shellHintId = useId()
+ // Where to put the caret after the textarea's text shifted by the `!` (entering or leaving shell
+ // mode): a controlled value change moves it to the end.
+ const pendingCaretRef = useRef<number | null>(null)
+ useLayoutEffect(() => {
+ const at = pendingCaretRef.current
+ const el = inputRef.current
+ if (at === null || el === null) return
+ pendingCaretRef.current = null
+ el.setSelectionRange(at, at)
+ // Keyed on the DRAFT: typing `!` into an empty box changes the draft but not what is shown.
+ }, [value])
const [caretSnap, setCaretSnap] = useState<{ value: string; start: number; end: number } | null>(null)
const trigger: CompletionTrigger | null =
!disabled && caretSnap && caretSnap.value === value ? completionTriggerAt(value, caretSnap.start, caretSnap.end) : null
@@ -219,7 +238,8 @@ export function ChatComposer({
// text or none, and a command name is not a word. A half-typed `/tid` keeps its underline: until it
// names a command, it is a misspelling.
const knownNames = useMemo(() => new Set(catalog.map((e) => e.name)), [catalog])
- const segments = useMemo(() => commandSegments(value, knownNames), [value, knownNames])
+ // None in shell mode: the line is a shell command, not a prompt.
+ const segments = useMemo(() => (shell ? null : commandSegments(value, knownNames)), [shell, value, knownNames])
const highlightRef = useRef<HTMLDivElement>(null)
const syncHighlightScroll = useCallback(() => {
const ta = inputRef.current
@@ -460,6 +480,14 @@ export function ChatComposer({
})
return
}
+ // Backspace at the very start of a shell-mode line leaves shell mode, as in Claude's TUI: the `!`
+ // goes and the text stays.
+ if (shell && e.key === 'Backspace' && !composing && e.currentTarget.selectionStart === 0 && e.currentTarget.selectionEnd === 0) {
+ e.preventDefault()
+ pendingCaretRef.current = 0
+ onChange(display)
+ return
+ }
if (menuOpen && e.key === 'Enter') closeMenu()
// Shift+Enter falls through to the textarea's own newline; an IME commit is not a send.
const action = chatKeyAction({
@@ -520,7 +548,7 @@ export function ChatComposer({
ref={composerRef}
className={`term-chat__composer${dropping ? ' term-chat__composer--drop' : ''}${
disabled ? ' term-chat__composer--disabled' : ''
- }`}
+ }${shell ? ' term-chat__composer--shell' : ''}`}
// Read by the shortcut dictation paths (lib/chatComposerDictation.ts
// `composerFromElement`) so ⌘⇧D / hold-to-talk with the caret here fills THIS draft.
data-chat-composer-id={composerId}
@@ -529,6 +557,14 @@ export function ChatComposer({
onDragLeave={onDragLeave}
onDrop={onDrop}
>
+ <div className="term-chat__composer-row">
+ {/* Always this slot, so the field after it keeps its position and the textarea is never
+ remounted (which would drop the keyboard) when shell mode starts or ends. */}
+ {shell && (
+ <span className="term-chat__shell-mark" aria-hidden="true">
+ !
+ </span>
+ )}
<div className="term-chat__composer-field">
{segments !== null && (
<div ref={highlightRef} className="term-chat__composer-highlight" aria-hidden="true">
@@ -550,9 +586,15 @@ export function ChatComposer({
className={`term-chat__composer-input${segments !== null ? ' term-chat__composer-input--over' : ''}`}
spellCheck={segments === null}
onScroll={syncHighlightScroll}
- value={value}
+ value={display}
+ aria-describedby={shell ? shellHintId : undefined}
onChange={(e) => {
- onChange(e.target.value)
+ const next = draftFromDisplay(e.target.value, shell)
+ // A `!` typed at the very start enters shell mode: it leaves the text, so the caret
+ // moves back one.
+ const entering = !shell && showsShellMode(agentId) && isShellDraft(next)
+ if (entering) pendingCaretRef.current = Math.max(0, (e.target.selectionStart ?? 1) - 1)
+ onChange(next)
const caret = e.target.selectionStart ?? e.target.value.length
// A new token (or none) forgets an Esc on the previous one.
if (dismissedAt !== null && completionTriggerAt(e.target.value, caret)?.start !== dismissedAt) setDismissedAt(null)
@@ -582,6 +624,7 @@ export function ChatComposer({
rows={2}
/>
</div>
+ </div>
<div className="term-chat__toolbar">
{pathsForFiles && (
<>
@@ -657,6 +700,11 @@ export function ChatComposer({
</button>
</div>
</div>
+ {shell && (
+ <div id={shellHintId} className="term-chat__shell-hint">
+ {SHELL_MODE_HINT}
+ </div>
+ )}
</div>
)
}
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 699200704..35da1aff0 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -49,7 +49,8 @@ import {
turnEndReloadCarries,
windowFocusHint
} from '../lib/chatLive'
-import { sentCommand } from '@shared/chat-command'
+import { BASH_COMMAND_TOOL, sentCommand } from '@shared/chat-command'
+import { ChatShellCommand } from './ChatShellCommand'
import { isInteractiveBuiltin } from '@shared/chat-catalog'
import { capabilityAgentId, chatReadsLocalOnly, readsScreenDialogs } from '@shared/agents/config'
import { ChatLoadingStatus } from './ChatPanelFallback'
@@ -1152,6 +1153,9 @@ export function ChatPanel({
<span className="term-chat__interrupt-hook" aria-hidden="true">⎿</span>
{CLAUDE_INTERRUPT_LINE}
</div>
+ ) : p.kind === 'tool' && p.name === BASH_COMMAND_TOOL ? (
+ // A `!` command the user ran: the TUI's `! cmd` with its output's first line under a `⎿`.
+ <ChatShellCommand key={key} arg={p.arg} result={p.result} />
) : p.body && !staleTodo(p, i, latestTodo) ? (
// A plan / question / the latest todo list is the content itself, not plumbing: shown
// expanded, in full, flowing with the thread (no inner scroll box). The answer stays under it.
diff --git a/src/renderer/nodes/ChatShellCommand.test.tsx b/src/renderer/nodes/ChatShellCommand.test.tsx
new file mode 100644
index 000000000..6b2555590
--- /dev/null
+++ b/src/renderer/nodes/ChatShellCommand.test.tsx
@@ -0,0 +1,62 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { ChatShellCommand } from './ChatShellCommand'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+let host: HTMLDivElement
+let root: Root
+
+async function render(arg: string, result?: string): Promise<HTMLDetailsElement> {
+ await act(async () => root.render(<ChatShellCommand arg={arg} result={result} />))
+ return host.querySelector('details') as HTMLDetailsElement
+}
+
+const first = () => host.querySelector('.term-chat__shell-first')
+
+beforeEach(() => {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+afterEach(async () => {
+ await act(async () => root.unmount())
+ host.remove()
+})
+
+describe('ChatShellCommand', () => {
+ it('shows the command and the first line of its output, closed', async () => {
+ const row = await render('ls -la', 'total 0\ndrwxr-xr-x 3 me wheel 96 .\ndrwx------ 53 me wheel 1696 ..')
+
+ expect(row.open).toBe(false)
+ expect(host.querySelector('.term-chat__shell-bang')?.textContent).toBe('!')
+ expect(host.querySelector('.term-chat__shell-cmd')?.textContent).toBe('ls -la')
+ expect(first()?.textContent).toBe('⎿total 0')
+ expect(first()?.classList.contains('term-chat__shell-first--more')).toBe(true)
+ })
+
+ it('opens to the whole output', async () => {
+ const out = 'total 0\ndrwxr-xr-x 3 me wheel 96 .'
+ await render('ls -la', out)
+
+ const pre = host.querySelector('pre.term-chat__shell-text')
+
+ expect(pre?.textContent).toBe(out)
+ })
+
+ it('says a command printed nothing', async () => {
+ await render('true', '')
+
+ expect(first()?.textContent).toBe('⎿(no output)')
+ expect(first()?.classList.contains('term-chat__shell-first--more')).toBe(false)
+ })
+
+ it('draws no output line before the output has been recorded', async () => {
+ await render('sleep 30')
+
+ expect(first()).toBeNull()
+ expect(host.querySelector('pre')).toBeNull()
+ })
+})
diff --git a/src/renderer/nodes/ChatShellCommand.tsx b/src/renderer/nodes/ChatShellCommand.tsx
new file mode 100644
index 000000000..98f0ed950
--- /dev/null
+++ b/src/renderer/nodes/ChatShellCommand.tsx
@@ -0,0 +1,41 @@
+/**
+ * A `!` shell command the user ran (the reader's tool part named `!`), drawn as Claude Code's TUI
+ * draws it: the command after a pink `!`, and its output's first line indented under a `⎿` hook. The
+ * row opens to the whole output (the reader keeps it, `BASH_OUTPUT_MAX`). The point of the line is
+ * feedback that the command ran; the output is for the agent, so it stays one line until asked for.
+ * - `result` absent: no output record yet (still running, or never saved): no hook line.
+ * - `result` empty: it ran and printed nothing.
+ */
+export function ChatShellCommand({ arg, result }: { arg: string; result?: string }): JSX.Element {
+ const lines = result === undefined ? null : result.split('\n')
+ const first = lines === null ? null : lines[0] === '' ? '(no output)' : lines[0]
+ const more = lines !== null && lines.length > 1
+ return (
+ <details className="term-chat__shell">
+ <summary>
+ <span className="term-chat__shell-line">
+ <span className="term-chat__shell-bang" aria-hidden="true">
+ !
+ </span>
+ <span className="term-chat__shell-cmd">{arg}</span>
+ </span>
+ {first !== null && (
+ <span className={`term-chat__shell-out term-chat__shell-first${more ? ' term-chat__shell-first--more' : ''}`}>
+ <span className="term-chat__shell-hook" aria-hidden="true">
+ ⎿
+ </span>
+ <span className="term-chat__shell-text">{first}</span>
+ </span>
+ )}
+ </summary>
+ {lines !== null && (
+ <div className="term-chat__shell-out">
+ <span className="term-chat__shell-hook" aria-hidden="true">
+ ⎿
+ </span>
+ <pre className="term-chat__shell-text">{first === '(no output)' ? first : result}</pre>
+ </div>
+ )}
+ </details>
+ )
+}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 5d8de15f9..915f3d5f4 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -3702,6 +3702,68 @@ body,
.term-chat__interrupt-hook {
font-family: ui-monospace, monospace;
}
+/* A `!` shell command the user ran (nodes/ChatShellCommand.tsx), as Claude Code's TUI draws it: the
+ command after a pink `!`, and under it, behind a `⎿`, its output's first line. Opened, the first
+ line gives way to the whole output. No chip: it is the user's own line, not an agent tool call. */
+.term-chat__shell {
+ margin: 4px 0;
+ font-size: 12px;
+}
+.term-chat__shell summary {
+ display: block;
+ cursor: pointer;
+ list-style: none;
+}
+.term-chat__shell summary::-webkit-details-marker {
+ display: none;
+}
+.term-chat__shell-line,
+.term-chat__shell-out {
+ display: flex;
+ align-items: baseline;
+ gap: 6px;
+ min-width: 0;
+ font-family: ui-monospace, monospace;
+}
+.term-chat__shell-bang {
+ flex: 0 0 auto;
+ font-weight: 600;
+ color: var(--sys-pink);
+}
+.term-chat__shell-cmd {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--text-strong);
+}
+.term-chat__shell-out {
+ padding-left: 12px;
+ color: var(--muted);
+}
+.term-chat__shell-hook {
+ flex: 0 0 auto;
+}
+.term-chat__shell-first .term-chat__shell-text {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+/* More than one line: say there is more, the way a cut-off line would. */
+.term-chat__shell-first--more .term-chat__shell-text::after {
+ content: ' …';
+}
+.term-chat__shell[open] .term-chat__shell-first {
+ display: none;
+}
+.term-chat__shell pre.term-chat__shell-text {
+ margin: 0;
+ min-width: 0;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ font: inherit;
+}
/* An Edit / Write call (nodes/ChatToolDiff.tsx): the chip's summary ends in the `+N −M` counts, and
it opens to the line diff. The block is a one-column grid sized to its widest line (at least the
chip's width), so a line's tint spans the whole row even while the block is scrolled sideways;
@@ -4082,6 +4144,37 @@ body,
border-color: var(--accent);
border-style: dashed;
}
+/* Shell mode (lib/chatShellMode.ts): a draft starting with `!` is drawn as Claude Code's TUI draws
+ it — the `!` beside the text instead of in it, the box's border in the TUI's shell-mode pink, and
+ its "! for shell mode" hint under the box. The textarea and its highlight layer share one row with
+ the mark, so their own layout is unchanged. */
+.term-chat__composer-row {
+ display: flex;
+ align-items: flex-start;
+ min-width: 0;
+}
+.term-chat__composer-row > .term-chat__composer-field {
+ flex: 1 1 auto;
+ min-width: 0;
+}
+.term-chat__shell-mark {
+ flex: 0 0 auto;
+ padding: 4px 0 4px 6px;
+ font-family: var(--md-code-font-family, ui-monospace, monospace);
+ font-size: var(--md-font-size);
+ font-weight: 600;
+ line-height: normal;
+ color: var(--sys-pink);
+}
+.term-chat__composer--shell,
+.term-chat__composer--shell:focus-within {
+ border-color: var(--sys-pink);
+}
+.term-chat__shell-hint {
+ padding: 3px 8px 0;
+ font-size: 11px;
+ color: var(--sys-pink);
+}
/* A text field in the ⌘M view: the plan "Revise…" textarea and the question "Other" input
(ChatAnswerControls) — a visible, bordered field with an accent border on focus. */
.term-chat__input {
diff --git a/src/shared/chat-command.ts b/src/shared/chat-command.ts
index 6b5f02a36..94da06b39 100644
--- a/src/shared/chat-command.ts
+++ b/src/shared/chat-command.ts
@@ -10,6 +10,11 @@ export const CHAT_TOOL_ARG_MAX = 200
/** The tool-part name the reader gives a `!` bash-mode command. */
export const BASH_COMMAND_TOOL = '!'
+/** The most of a `!` command's output the reader keeps, in UTF-16 code units. Its lines are kept
+ * (the chat view shows the first under the command and all of them when opened); a slash command's
+ * output is summarized like a tool result instead. */
+export const BASH_OUTPUT_MAX = 16384
+
/** The name an output record's tool part gets when there is no command to attach it to. */
export const COMMAND_OUTPUT_TOOL = 'command output'
diff --git a/src/shared/chat-fixtures/README.md b/src/shared/chat-fixtures/README.md
index 7de42b8bd..574dd9740 100644
--- a/src/shared/chat-fixtures/README.md
+++ b/src/shared/chat-fixtures/README.md
@@ -83,7 +83,7 @@ the production paging, not a second implementation of it.
| `model-effort-utf16` | The 100-character cap counts **UTF-16 code units** (Swift `utf16.count`), not bytes or scalars. A model of 50 × U+1F9EA (100 units) is kept, and an effort of 101 units is absent. |
| `thinking` | Thinking blocks (`thinking`, `redacted_thinking`). The reader **drops** them by default: a thinking-only record yields no message, and a mixed record keeps only its text. The port must match this. (The desktop ⌘M panel opts in with `page.thinking: true` and then gets a `{kind:"thinking", text, ms?}` part for each block whose `thinking` text is non-blank: `text` is capped at 16384 UTF-16 units, and `ms` is this record's timestamp minus that of the newest `user` record before it (a prompt, a `tool_result` or a hidden meta line), present only when both stamps exist and the gap is ≥ 0 — see the `ChatPart` doc in `src/shared/types.ts`. The phone's `chat.page` never sets it, so these fixtures are unchanged.) |
| `local-commands` | Slash-command records (see **Local commands** below). An `isMeta` caveat is skipped; `/model` plus its ANSI-coloured `<local-command-stdout>` become ONE assistant tool part `{name:"/model", arg:"", result}`; `/effort` with padded args (trimmed) answered on `<local-command-stderr>`; `/compact` with an arg longer than the 200-unit cap; `/exit` with an empty stdout (no `result`); a skill invocation (`<command-message>` before `<command-name>`) whose `isMeta` array body is skipped; a stdout with no command right before it (its own `command output` tool, capped to three lines); and a user message that only mentions `<command-name>` in prose (stays a user message). |
-| `bash-mode` | `!` bash-mode records: `<bash-input>` becomes a tool part named `!` with the command as `arg`; the ONE following record carrying `<bash-stdout>…</bash-stdout><bash-stderr>…</bash-stderr>` sets its `result` (non-empty parts joined by `\n`, then the `summarizeResult` cap), including an empty stdout with a stderr. |
+| `bash-mode` | `!` bash-mode records: `<bash-input>` becomes a tool part named `!` with the command as `arg`; the ONE following record carrying `<bash-stdout>…</bash-stdout><bash-stderr>…</bash-stderr>` sets its `result` (non-empty parts joined by `\n`, lines kept, the `BASH_OUTPUT_MAX` cap), including an empty stdout with a stderr, and a command that printed nothing (`result: ""`). |
| `meta-turns` | `isMeta` rule 1: a peer hand-back (`promptSource` + `origin.kind:"peer"` + `turnOrigin`), a scheduled wakeup (`turnOrigin:"scheduled"` + `scheduledTaskId`), an auto-continuation (`origin.kind:"auto-continuation"`), a `promptSource`-only, an `origin`-only and a `turnOrigin`-only record (the last two with no `promptSource`, so each field is pinned on its own) are all KEPT; the caveat and a skill body (none of the three fields) are skipped. Three of the kept records then render as system chips (see **System-injected records**): BOTH `origin.kind:"peer"` records — the hand-back and the `origin`-only one — as `Agent message`, and the auto-continuation as `System`; the others stay user messages. |
| `system-records` | Every rule of **System-injected records**: a full agent completion (nested `<usage>`, a result over three lines), a status + summary completion, a monitor `<event>`, a summary alone (the `notified` result), a repeated `<task-id>` with a summary over the 200-unit cap, a whole element with no `origin`, the same whole element sent by a human (`origin.kind:"human"`, and `promptSource:"typed"` with no `origin`; both stay user messages), two malformed notifications (unknown tags only; plain prose), a message that only MENTIONS the element (stays a user message), a subagent `<agent-message>` hand-back with its frame lines, a `<cross-session-message>` (its `from-name` is the arg), a report over the 16384-unit cap, a peer record with no element, an auto-continuation and a multi-line coordinator prompt. |
| `teammate-messages` | Rule **2b** of **System-injected records**: an idle notification with a report, one with no fields, a failed one (`failureReason`), a plain message whose summary is escaped (`&quot;`) and whose body quotes the close tag, a record holding two elements (a report, then a message), an unverified sender (`verified="false"`), the same text typed by a human (by `origin` and by `promptSource` alone — both stay user messages), the frame line with no element and an element with no `teammate_id` (both stay user messages). |
@@ -168,13 +168,18 @@ on the paged and unpaged paths alike:
{`bash-stdout`, `bash-stderr`} (bash family) → **output**. Its text is each tag's content, in
record order, with ANSI escapes removed (`\x1b[` CSI `[0-?]*[ -/]*[@-~]`, then OSC
`\x1b][^\x07\x1b]*(\x07|\x1b\\)`, then two-byte `\x1b[@-_]`), trimmed, empty parts dropped,
- joined by `\n`, then capped like a tool result (first three lines joined by a space, first 500
- UTF-16 units). An empty text produces nothing.
-5. A non-empty output sets `result` on the command's tool part when the **last pushed message** is
- a command of the **same family** that has no result yet. Otherwise it is pushed as its own
- assistant message `{kind:"tool", name:"command output", arg:"", result}`. Any pushed message
- ends the wait, and so does an attached output (a second output does not overwrite). A record
- that pushes nothing does NOT end it: a skipped `isMeta` record, an empty output, a metadata-only
+ joined by `\n`. The **bash** family's text then keeps its lines, capped at its first 16384 UTF-16
+ units (`BASH_OUTPUT_MAX`: the chat view shows the first line under the command and the rest when
+ opened); the **slash** family's is capped like a tool result (first three lines joined by a
+ space, first 500 UTF-16 units). An empty slash text produces nothing.
+5. An output sets `result` on the command's tool part when the **last pushed message** is a command
+ of the **same family** that has no result yet — for the bash family even when it is empty (`""`:
+ the command ran and printed nothing); for the slash family only when it is non-empty. Otherwise
+ a non-empty output is pushed as its own assistant message
+ `{kind:"tool", name:"command output", arg:"", result}`, and an empty one pushes nothing. Any
+ pushed message ends the wait, and so does an attached output (a second output does not
+ overwrite). A record that pushes nothing does NOT end it: a skipped `isMeta` record, an empty
+ slash output, an empty bash output with no command waiting, a metadata-only
record, a thinking-only assistant record or a tool_result-only user record.
6. "Trimmed" everywhere in these rules means JS `String.prototype.trim`, which strips JS `\s`:
ASCII whitespace plus U+00A0, U+FEFF, U+1680, U+2000–U+200A, U+2028, U+2029, U+202F, U+205F and
diff --git a/src/shared/chat-fixtures/expected/bash-mode.pages.json b/src/shared/chat-fixtures/expected/bash-mode.pages.json
index 2986aa3f4..123922274 100644
--- a/src/shared/chat-fixtures/expected/bash-mode.pages.json
+++ b/src/shared/chat-fixtures/expected/bash-mode.pages.json
@@ -13,7 +13,7 @@
"kind": "tool",
"name": "!",
"arg": "ls /srv/demo",
- "result": "a.txt b.txt ls: warning: demo"
+ "result": "a.txt\nb.txt\nls: warning: demo"
}
],
"at": 1790362801000,
@@ -32,6 +32,19 @@
"at": 1790362804000,
"key": 1636
},
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "!",
+ "arg": "true",
+ "result": ""
+ }
+ ],
+ "at": 1790362807000,
+ "key": 2779
+ },
{
"role": "user",
"parts": [
@@ -40,8 +53,8 @@
"text": "What was in a.txt?"
}
],
- "at": 1790362806000,
- "key": 2271
+ "at": 1790362809000,
+ "key": 3360
},
{
"role": "assistant",
@@ -51,8 +64,8 @@
"text": "Twelve bytes of demo text."
}
],
- "at": 1790362807000,
- "key": 2538
+ "at": 1790362810000,
+ "key": 3627
}
],
"olderCursor": null,
diff --git a/src/shared/chat-fixtures/inputs/bash-mode.jsonl b/src/shared/chat-fixtures/inputs/bash-mode.jsonl
index d0dfc2b6f..5e1a15f63 100644
--- a/src/shared/chat-fixtures/inputs/bash-mode.jsonl
+++ b/src/shared/chat-fixtures/inputs/bash-mode.jsonl
@@ -4,5 +4,8 @@
{"type":"user","message":{"role":"user","content":"<local-command-caveat>Caveat: The messages below were generated by the user while running local commands. DO NOT respond to these messages or otherwise consider them in your response unless the user explicitly asks you to.</local-command-caveat>"},"isMeta":true,"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000003","timestamp":"2026-09-25T19:00:03.000Z"}
{"type":"user","message":{"role":"user","content":"<bash-input>cat missing.txt</bash-input>"},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000004","timestamp":"2026-09-25T19:00:04.000Z"}
{"type":"user","message":{"role":"user","content":"<bash-stdout></bash-stdout><bash-stderr>cat: missing.txt: No such file or directory</bash-stderr>"},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000005","timestamp":"2026-09-25T19:00:05.000Z"}
-{"type":"user","message":{"role":"user","content":"What was in a.txt?"},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000006","timestamp":"2026-09-25T19:00:06.000Z"}
-{"type":"assistant","effort":"high","message":{"id":"msg_synthetic","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"Twelve bytes of demo text."}],"stop_reason":null},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000007","timestamp":"2026-09-25T19:00:07.000Z"}
+{"type":"user","message":{"role":"user","content":"<local-command-caveat>Caveat: The messages below were generated by the user while running local commands. DO NOT respond to these messages or otherwise consider them in your response unless the user explicitly asks you to.</local-command-caveat>"},"isMeta":true,"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000006","timestamp":"2026-09-25T19:00:06.000Z"}
+{"type":"user","message":{"role":"user","content":"<bash-input>true</bash-input>"},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000007","timestamp":"2026-09-25T19:00:07.000Z"}
+{"type":"user","message":{"role":"user","content":"<bash-stdout></bash-stdout><bash-stderr></bash-stderr>"},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000008","timestamp":"2026-09-25T19:00:08.000Z"}
+{"type":"user","message":{"role":"user","content":"What was in a.txt?"},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000009","timestamp":"2026-09-25T19:00:09.000Z"}
+{"type":"assistant","effort":"high","message":{"id":"msg_synthetic","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"Twelve bytes of demo text."}],"stop_reason":null},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000010","timestamp":"2026-09-25T19:00:10.000Z"}