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): claude.ai-style composer — attach, dictation, model/effort labels

review37be86304769
diff --git a/CLAUDE.md b/CLAUDE.md
index 1e90c1d48..88ece919a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2543,6 +2543,35 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
`readQuestions`), and only while the pane is in a dialog state. They send a `PermissionAnswer`
through `answerPermission`; a refusal is a quiet retryable error pointing at the terminal. Plan's
default button is `restore` — never auto. See docs/hook-reply-approvals.md.
+ **The composer (2026-09-26, claude.ai-style)** is one rounded box — textarea on top, a toolbar
+ under it: "+" attach on the left; model label, muted effort label and a mic on the right (pure
+ decisions in `lib/chatComposer.ts`). Four rules: (1) **attach = paths in the DRAFT, resolved the
+ way a drop onto that node's terminal is** — the mount site passes `pathsForFiles` built on
+ `droppedPaths` with the node's own SSH scope (`dropProjectId` in TerminalNode; `spawn.ssh` in the
+ card modal), so an SSH node's file is uploaded to its HOST and the composer never grows a second
+ resolver; "+" / drop / file-or-screenshot paste all feed it, and nothing is ever sent. (2) **The
+ mic targets THIS composer's textarea, never the pane**: `nodeterm:dictate` carries a per-MOUNT
+ `composerId` (the canvas node and the card modal can both mount one session's composer),
+ `DictationTarget` gained `kind: 'chat-composer'`, and the overlay hands the take over
+ `nodeterm:chat-dictation` (`lib/chatComposerDictation.ts`), saying so if the composer closed
+ mid-take. (3) **The labels read the ContextMeter's store** (`useContextUsage` — ONE reader) and
+ a click TYPES the agent's own picker command (`/model`, `/effort`) through the SAME
+ `chatSendRefusal` gate as a message, re-read at click time, then flips to the terminal
+ (`onShowTerminal`); `sendText` must answer `=== true` to flip. Measured for claude only
+ (`composerPickerCommand`, via `capabilityAgentId`): any other agent shows no label, since a label
+ that opens nothing is a lie. Hidden when the model is unknown; effort hidden with it. (4) **Effort
+ was measured, not assumed** (Claude Code 2.1.283): read = the top-level `effort` the CLI writes on
+ every assistant record it sent with one (`...E!==void 0&&{effort:E}`; its own history reader
+ walks the same field; a transcript flips `medium`→`xhigh` on the first request after `/effort`);
+ change = `/effort` (a `local-jsx` picker, levels `low|medium|high|xhigh|max`). `parseLatestUsage`
+ takes it from the LATEST usage record only — never carried forward, a record without it means
+ that model takes no effort — and both context tails push on an effort-only change
+ (`ContextWindowUsage.effort`, optional: older hosts and other agents simply omit it). Like the
+ model, it lags until the next request. Narrow composers drop effort first, then the model
+ (`composerToolbarLayout`); "+" and the mic stay. No voice-conversation button: there is no
+ 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.
- **Subagent visualization** (agents in `SUBAGENT_CAPABLE`) — `subagent-start`/`subagent-end`
normalized events (from Claude's `PreToolUse`/`PostToolUse` on tool `Agent`/`Task`, correlated
by `tool_use_id`) drive a transient `state/agentNodes.ts` store. Claude launches subagents
diff --git a/src/core/context-tail.test.ts b/src/core/context-tail.test.ts
index 7483f7f93..993e6f234 100644
--- a/src/core/context-tail.test.ts
+++ b/src/core/context-tail.test.ts
@@ -13,6 +13,27 @@ describe('parseLatestUsage', () => {
].join('\n')
expect(parseLatestUsage(text)).toEqual({ used: 120, model: 'claude-y' })
})
+ it("reads the reasoning effort Claude Code records on the LATEST usage record (top-level `effort`)", () => {
+ // Shape measured on 2.1.283 transcripts: `effort` sits beside `message`, and changes on the
+ // first request after `/effort`.
+ const text = [
+ JSON.stringify({ type: 'assistant', effort: 'medium', perTurnEffort: 'medium', message: { model: 'claude-x', usage: { input_tokens: 10 } } }),
+ JSON.stringify({ type: 'assistant', effort: 'xhigh', perTurnEffort: 'xhigh', message: { model: 'claude-x', usage: { input_tokens: 20 } } })
+ ].join('\n')
+ expect(parseLatestUsage(text)).toEqual({ used: 20, model: 'claude-x', effort: 'xhigh' })
+ })
+ it('does NOT carry an older effort forward: a latest record with none (a model without effort) has none', () => {
+ const text = [
+ JSON.stringify({ type: 'assistant', effort: 'high', message: { model: 'claude-opus-5', usage: { input_tokens: 10 } } }),
+ JSON.stringify({ type: 'assistant', message: { model: 'claude-haiku-4-5', usage: { input_tokens: 20 } } })
+ ].join('\n')
+ expect(parseLatestUsage(text)).toEqual({ used: 20, model: 'claude-haiku-4-5' })
+ expect(parseLatestUsage(text)).not.toHaveProperty('effort')
+ })
+ it('ignores a non-string effort', () => {
+ const text = JSON.stringify({ type: 'assistant', effort: { level: 'x' }, message: { model: 'm', usage: { input_tokens: 5 } } })
+ expect(parseLatestUsage(text)).toEqual({ used: 5, model: 'm' })
+ })
it('ignores non-assistant lines, zero-usage, and garbled JSON; null when none', () => {
expect(parseLatestUsage('not json\n{"type":"assistant","message":{"usage":{"input_tokens":0}}}')).toBeNull()
expect(parseLatestUsage('')).toBeNull()
@@ -312,3 +333,36 @@ describe('session-scoped context configuration (#818)', () => {
}
})
})
+
+describe('createContextTail — effort (the ⌘M composer label)', () => {
+ it('pushes the recorded effort, and pushes again when ONLY the effort changed (a `/effort` pick)', async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ctxtail-effort-'))
+ const file = path.join(dir, 'sess.jsonl')
+ const rec = (effort: string) =>
+ JSON.stringify({ type: 'assistant', effort, message: { model: 'claude-opus-5', usage: { input_tokens: 100 } } }) + '\n'
+ fs.writeFileSync(file, rec('medium'))
+ const send = vi.fn()
+ const tail = createContextTail(send)
+ tail.track('s1', file)
+ await new Promise((r) => setTimeout(r, 300))
+ // Same used tokens, same model: before effort was part of the snapshot this was no push at all.
+ fs.appendFileSync(file, rec('xhigh'))
+ await new Promise((r) => setTimeout(r, 1300))
+ tail.untrack('s1')
+ const efforts = send.mock.calls.map((c) => (c[0] as { effort?: string }).effort)
+ expect(efforts).toEqual(['medium', 'xhigh'])
+ }, 6000)
+
+ it('omits the field when the transcript records none (older CLI / other agent)', async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ctxtail-noeffort-'))
+ const file = path.join(dir, 'sess.jsonl')
+ fs.writeFileSync(file, JSON.stringify({ type: 'assistant', message: { model: 'claude-opus-5', usage: { input_tokens: 100 } } }) + '\n')
+ const send = vi.fn()
+ const tail = createContextTail(send)
+ tail.track('s1', file)
+ await new Promise((r) => setTimeout(r, 300))
+ tail.untrack('s1')
+ expect(send).toHaveBeenCalledTimes(1)
+ expect(send.mock.calls[0][0]).not.toHaveProperty('effort')
+ })
+})
diff --git a/src/core/context-tail.ts b/src/core/context-tail.ts
index f1602644d..a8945aa6a 100644
--- a/src/core/context-tail.ts
+++ b/src/core/context-tail.ts
@@ -30,15 +30,16 @@ const toLines = (text: string | string[]): string[] =>
*/
export function parseLatestUsage(
text: string | string[]
-): { used: number; model: string | null } | null {
+): { used: number; model: string | null; effort?: string } | null {
const lines = toLines(text)
let found = false
let usedTokens = 0
let model: string | null = null
+ let effort: string | undefined
for (let i = lines.length - 1; i >= 0; i--) {
const s = lines[i].trim()
if (!s || !s.includes('"usage"') || !s.includes('"assistant"')) continue
- let o: { type?: string; message?: { model?: string; usage?: Record<string, number> } }
+ let o: { type?: string; effort?: unknown; message?: { model?: string; usage?: Record<string, number> } }
try {
o = JSON.parse(s)
} catch {
@@ -52,13 +53,20 @@ export function parseLatestUsage(
if (!found) {
found = true
usedTokens = used // the LATEST usage — earlier lines are visited only to resolve the model
+ // The reasoning effort of that same request: Claude Code writes a top-level `effort` on each
+ // assistant record it sent with one (`...E!==void 0&&{effort:E}` in the 2.1.283 bundle — the
+ // same field the CLI's own history reader walks). Taken from the LATEST record ONLY, never
+ // carried forward like the model: a record without it means that request had no effort (a
+ // model that does not take one), and an older value would be a stale claim.
+ if (typeof o.effort === 'string' && o.effort) effort = o.effort
}
// Same rule as the old forward scan's "carry the prior model forward": the effective model
// is the nearest usage line AT OR BEFORE the latest one that names it.
model = o.message.model ?? null
if (model !== null) break
}
- return found ? { used: usedTokens, model } : null
+ if (!found) return null
+ return effort === undefined ? { used: usedTokens, model } : { used: usedTokens, model, effort }
}
/**
@@ -162,7 +170,7 @@ export interface ContextTailOptions {
*/
parse?: (
text: string | string[]
- ) => { used: number; window?: number | null; model: string | null } | null
+ ) => { used: number; window?: number | null; model: string | null; effort?: string } | null
/**
* Re-read the tracked file from byte 0 on every tick instead of tailing an offset.
*
@@ -181,9 +189,12 @@ interface Tracked {
used: number
window: number
model: string | null
+ /** Reasoning effort of the latest request (claude only — see parseLatestUsage); null = none. */
+ effort: string | null
// Last pushed snapshot — a push fires only when one of these changes.
lastUsed: number
lastModel: string | null
+ lastEffort: string | null
lastWindow: number
sessionWindow: number | null
/** An async read is in flight — the next tick skips this session instead of double-reading. */
@@ -232,6 +243,7 @@ export function createContextTail(
windowTokens: t.window,
usedPercent,
model: t.model,
+ ...(t.effort !== null && { effort: t.effort }),
windowSource: customParse ? 'transcript' : t.sessionWindow === null ? 'estimate' : 'session-env',
updatedAt: Date.now()
}
@@ -291,6 +303,7 @@ export function createContextTail(
if (latest) {
t.used = latest.used
t.model = latest.model ?? t.model
+ t.effort = latest.effort ?? null
t.parsedWindow = latest.window ?? t.parsedWindow
}
if (opts?.onTaskNotification) {
@@ -311,12 +324,13 @@ export function createContextTail(
t.used > 0 &&
win !== null &&
win > 0 &&
- (t.used !== t.lastUsed || t.model !== t.lastModel || win !== t.lastWindow)
+ (t.used !== t.lastUsed || t.model !== t.lastModel || t.effort !== t.lastEffort || win !== t.lastWindow)
) {
t.window = win
push(sessionId, t)
t.lastUsed = t.used
t.lastModel = t.model
+ t.lastEffort = t.effort
t.lastWindow = win
}
} finally {
@@ -350,8 +364,10 @@ export function createContextTail(
used: 0,
window: 0,
model: null,
+ effort: null,
lastUsed: 0,
lastModel: null,
+ lastEffort: null,
lastWindow: 0,
sessionWindow: sessionWindow ?? null,
reading: false,
diff --git a/src/main/remote-context-tail.ts b/src/main/remote-context-tail.ts
index 52544ebbb..c7e8d80f0 100644
--- a/src/main/remote-context-tail.ts
+++ b/src/main/remote-context-tail.ts
@@ -45,11 +45,14 @@ interface Tracked {
window: number
parsedWindow: number | null
model: string | null
+ /** Reasoning effort of the latest request — see parseLatestUsage (context-tail.ts). */
+ effort: string | null
// In-flight guard: a slow ssh read must not overlap with the next tick.
reading: boolean
// Last pushed snapshot — a push fires only when one of these changes.
lastUsed: number
lastModel: string | null
+ lastEffort: string | null
lastWindow: number
sessionWindow: number | null
/** Partial trailing line held back until the next read completes it (see subagent-tail.ts). */
@@ -93,6 +96,7 @@ export function createRemoteContextTail(
if (latest) {
t.used = latest.used
t.model = latest.model ?? t.model
+ t.effort = latest.effort ?? null
t.parsedWindow = latest.window ?? t.parsedWindow
}
// A historical partial line may finish on a later poll; it still must not emit events.
@@ -115,6 +119,7 @@ export function createRemoteContextTail(
windowTokens: t.window,
usedPercent,
model: t.model,
+ ...(t.effort !== null && { effort: t.effort }),
windowSource: customParse ? 'transcript' : t.sessionWindow === null ? 'estimate' : 'session-env',
updatedAt: Date.now()
}
@@ -159,11 +164,12 @@ export function createRemoteContextTail(
const window = customParse ? t.parsedWindow : t.sessionWindow ?? cachedWindowFor(t.model)
if (sessions.get(sessionId) !== t) return
- if (t.used > 0 && window !== null && window > 0 && (t.used !== t.lastUsed || t.model !== t.lastModel || window !== t.lastWindow)) {
+ if (t.used > 0 && window !== null && window > 0 && (t.used !== t.lastUsed || t.model !== t.lastModel || t.effort !== t.lastEffort || window !== t.lastWindow)) {
t.window = window
push(sessionId, t)
t.lastUsed = t.used
t.lastModel = t.model
+ t.lastEffort = t.effort
t.lastWindow = window
}
}
@@ -206,9 +212,11 @@ export function createRemoteContextTail(
window: 0,
parsedWindow: null,
model: null,
+ effort: null,
reading: false,
lastUsed: 0,
lastModel: null,
+ lastEffort: null,
lastWindow: 0,
sessionWindow: sessionWindow ?? null,
carry: null
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 1e38d0665..3493b7de9 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -157,6 +157,7 @@ import { WelcomeScreen } from '../components/WelcomeScreen'
import { CloneRepoDialog } from '../components/CloneRepoDialog'
import { markMobileLaunchSeen, shouldShowMobileLaunch } from '../lib/mobileLaunch'
import type { DictationTarget } from '../components/DictationOverlay'
+import { dictationTargetFromRequest } from '../lib/chatComposerDictation'
import { describeOs, REPO_URL } from '../lib/bugReport'
import { shouldReleasePaneFocus } from '../lib/paneFocus'
import {
@@ -4457,15 +4458,15 @@ export function Canvas() {
// instance mounts fresh and starts recording into the new target immediately.
useEffect(() => {
const onDictate = (e: Event): void => {
- const d = (e as CustomEvent<{ nodeId: string }>).detail
+ // `composerId` = the mic in a ⌘M chat composer: the take goes into that composer's textarea
+ // (lib/chatComposerDictation.ts), not the pane. Absent = the header mic, unchanged.
+ const d = (e as CustomEvent<{ nodeId: string; composerId?: string }>).detail
if (!d?.nodeId) return
const n = nodesRef.current.find((x) => x.id === d.nodeId)
if (!n) return
- setDictationTarget({
- kind: 'terminal',
- nodeId: n.id,
- title: (n.data.title as string) || 'Untitled'
- })
+ setDictationTarget(
+ dictationTargetFromRequest({ nodeId: n.id, composerId: d.composerId }, (n.data.title as string) || 'Untitled')
+ )
setDictationOpen(true)
setDictationNonce((prev) => prev + 1)
}
diff --git a/src/renderer/components/ContextMeter.tsx b/src/renderer/components/ContextMeter.tsx
index 3f0dc5f1c..1aa527503 100644
--- a/src/renderer/components/ContextMeter.tsx
+++ b/src/renderer/components/ContextMeter.tsx
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react'
-import { useContextWindow } from '../state/contextWindow'
+import { useContextUsage } from '../state/contextWindow'
import { useSettings } from '../state/settings'
import { capabilityAgentId } from '@shared/agents/config'
import { barFillPercent, contextFillColor, contextPillText, formatModelLabel, formatTimeAgo, formatTokensShort, percentText } from '../lib/usageFormat'
@@ -17,11 +17,7 @@ export function ContextMeter({ sessionId, nodeId, remote = false, agentId }: {
const scoped = remote && !!agentId && capabilityAgentId(agentId) === 'codex'
// A copied rollout has the same session id on two hosts. SSH Codex observations belong
// to the node that requested them; never fall back to a local/session-only snapshot.
- const usage = useContextWindow((s) => {
- if (!sessionId) return undefined
- const value = scoped ? (nodeId ? s.byNodeId[nodeId] : undefined) : s.bySessionId[sessionId]
- return value?.sessionId === sessionId ? value : undefined
- })
+ const usage = useContextUsage({ sessionId, nodeId, scoped })
const percentMode = useSettings((s) => s.settings.usagePercentMode)
const [open, setOpen] = useState(false)
const ref = useRef<HTMLDivElement>(null)
diff --git a/src/renderer/components/DictationOverlay.tsx b/src/renderer/components/DictationOverlay.tsx
index c3b93caeb..ff8972281 100644
--- a/src/renderer/components/DictationOverlay.tsx
+++ b/src/renderer/components/DictationOverlay.tsx
@@ -20,12 +20,16 @@ import { PcmCapture } from '../lib/pcm-capture'
import { useSession } from '../session/session'
import { useSettings } from '../state/settings'
import { hasSpeechModel } from '@shared/speech'
+import { deliverToComposer } from '../lib/chatComposerDictation'
-export interface DictationTarget {
- kind: 'terminal'
- nodeId: string
- title: string
-}
+/**
+ * Where a take lands. `terminal` types it into the node's pane (`pty.sendText`, no Enter);
+ * `chat-composer` hands it to ONE mounted ⌘M composer's textarea by its per-mount id
+ * (lib/chatComposerDictation.ts) — a draft the user edits and sends, never typed into the pane.
+ */
+export type DictationTarget =
+ | { kind: 'terminal'; nodeId: string; title: string }
+ | { kind: 'chat-composer'; nodeId: string; composerId: string; title: string }
export interface DictationOverlayProps {
target: DictationTarget | null
@@ -157,11 +161,19 @@ export function DictationOverlay({ target, stopSignal, onClose, onOpenLicense }:
// An in-flight transcription can't be aborted — dropping the result honors the user's
// dismissal (nothing may land after a cancel).
if (discardedRef.current) return
- const ok = await api.pty.sendText(target.nodeId, transcribed, { enter: false })
- if (!ok) {
- setError('Could not insert — the terminal session is not available.')
- setPhase('idle')
- return
+ if (target.kind === 'chat-composer') {
+ if (!deliverToComposer(target.composerId, transcribed)) {
+ setError('Could not insert — the chat composer was closed.')
+ setPhase('idle')
+ return
+ }
+ } else {
+ const ok = await api.pty.sendText(target.nodeId, transcribed, { enter: false })
+ if (!ok) {
+ setError('Could not insert — the terminal session is not available.')
+ setPhase('idle')
+ return
+ }
}
// A stale (remounted-over) instance still delivers its own transcript into the
// terminal — the target closure is per-instance and correct — but must not close the
diff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsx
index 5382decf8..796f96ea5 100644
--- a/src/renderer/components/kanban/CardModal.tsx
+++ b/src/renderer/components/kanban/CardModal.tsx
@@ -34,7 +34,9 @@ import { useSession } from '../../session/session'
// use — NOT a bespoke resume path, so a click here gets the same WakeInputBuffer protection and
// retries. Importing one function out of the canvas node module is safe: TerminalNode.tsx already
// imports from `components/kanban/*`, and none of those re-import CardModal.
-import { wakeHibernatedNode } from '../../nodes/TerminalNode'
+import { sshConnectionScope, wakeHibernatedNode } from '../../nodes/TerminalNode'
+import { droppedPaths } from '../../terminal/file-drop'
+import { useProjects } from '../../state/projects'
import type { ProjectKanban } from '@shared/types'
import type { KanbanSession } from './KanbanView'
import { BoardLogPanel } from './BoardLogPanel'
@@ -545,6 +547,19 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,
cwd={session.spawn.cwd}
accountId={accountForReads}
agentId={createdAgent!}
+ // Same resolution as a drop onto this card's live viewer (ModalTerminal):
+ // an SSH node uploads over the master its PTY runs on.
+ pathsForFiles={(files) =>
+ droppedPaths(files, {
+ sshRemoteTmux: !!session.spawn.sshRemoteTmux,
+ projectId: session.spawn.sshRemoteTmux
+ ? session.spawn.ssh
+ ? sshConnectionScope(session.spawn.ssh)
+ : useProjects.getState().activeProjectId
+ : ''
+ })
+ }
+ onShowTerminal={() => setMdFor(null)}
/>
</Suspense>
) : (
diff --git a/src/renderer/lib/chatComposer.test.ts b/src/renderer/lib/chatComposer.test.ts
new file mode 100644
index 000000000..d172cd350
--- /dev/null
+++ b/src/renderer/lib/chatComposer.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, it } from 'vitest'
+import {
+ COMPOSER_EFFORT_MIN_WIDTH,
+ COMPOSER_MODEL_MIN_WIDTH,
+ appendToComposer,
+ composerLabels,
+ composerPickerCommand,
+ composerToolbarLayout,
+ effortLabel
+} from './chatComposer'
+
+describe('composerToolbarLayout', () => {
+ it('shows both labels when the width is unknown (no layout box measured yet)', () => {
+ expect(composerToolbarLayout(null)).toEqual({ model: true, effort: true })
+ })
+
+ it('drops the effort label first, then the model label, as the composer narrows', () => {
+ expect(composerToolbarLayout(COMPOSER_EFFORT_MIN_WIDTH)).toEqual({ model: true, effort: true })
+ expect(composerToolbarLayout(COMPOSER_EFFORT_MIN_WIDTH - 1)).toEqual({ model: true, effort: false })
+ expect(composerToolbarLayout(COMPOSER_MODEL_MIN_WIDTH)).toEqual({ model: true, effort: false })
+ expect(composerToolbarLayout(COMPOSER_MODEL_MIN_WIDTH - 1)).toEqual({ model: false, effort: false })
+ })
+
+ it('never shows effort without room for the model (effort threshold is the higher one)', () => {
+ expect(COMPOSER_EFFORT_MIN_WIDTH).toBeGreaterThan(COMPOSER_MODEL_MIN_WIDTH)
+ })
+})
+
+describe('effortLabel', () => {
+ it('labels the levels Claude Code 2.1.283 records, in its own spelling', () => {
+ expect(effortLabel('low')).toBe('Low')
+ expect(effortLabel('medium')).toBe('Medium')
+ expect(effortLabel('high')).toBe('High')
+ expect(effortLabel('xhigh')).toBe('xHigh')
+ expect(effortLabel('max')).toBe('Max')
+ })
+
+ it('says nothing for an absent or unrecognised value — a guess must degrade to nothing', () => {
+ expect(effortLabel(undefined)).toBeNull()
+ expect(effortLabel(null)).toBeNull()
+ expect(effortLabel('')).toBeNull()
+ expect(effortLabel('turbo')).toBeNull()
+ expect(effortLabel('constructor')).toBeNull()
+ })
+})
+
+describe('composerPickerCommand', () => {
+ it("opens claude's own pickers", () => {
+ expect(composerPickerCommand('claude', 'model')).toBe('/model')
+ expect(composerPickerCommand('claude', 'effort')).toBe('/effort')
+ })
+
+ it('has no command for an agent whose picker was never measured (grok)', () => {
+ expect(composerPickerCommand('grok', 'model')).toBeNull()
+ expect(composerPickerCommand('grok', 'effort')).toBeNull()
+ })
+})
+
+describe('composerLabels', () => {
+ it('shows the model and effort of a claude session', () => {
+ expect(composerLabels({ agentId: 'claude', model: 'claude-fable-5-1', effort: 'medium', width: 600 })).toEqual({
+ model: 'Fable 5.1',
+ effort: 'Medium'
+ })
+ })
+
+ it('hides the model label when the model is unknown, and effort with it', () => {
+ expect(composerLabels({ agentId: 'claude', model: null, effort: 'high', width: 600 })).toEqual({
+ model: null,
+ effort: null
+ })
+ })
+
+ it('hides labels the width has no room for', () => {
+ expect(composerLabels({ agentId: 'claude', model: 'claude-opus-5', effort: 'high', width: COMPOSER_MODEL_MIN_WIDTH })).toEqual({
+ model: 'Opus 5',
+ effort: null
+ })
+ expect(composerLabels({ agentId: 'claude', model: 'claude-opus-5', effort: 'high', width: 10 })).toEqual({
+ model: null,
+ effort: null
+ })
+ })
+
+ it('shows no label for an agent with no picker to open (a label that does nothing on click)', () => {
+ expect(composerLabels({ agentId: 'grok', model: 'grok-4.6', effort: undefined, width: 600 })).toEqual({
+ model: null,
+ effort: null
+ })
+ })
+})
+
+describe('appendToComposer', () => {
+ it('inserts into an empty composer as-is', () => {
+ expect(appendToComposer('', 'hello')).toBe('hello')
+ })
+
+ it('separates from existing text with one space', () => {
+ expect(appendToComposer('look at', '/tmp/a.png ')).toBe('look at /tmp/a.png ')
+ })
+
+ it('does not double a separator the text already ends with', () => {
+ expect(appendToComposer('look at ', 'x')).toBe('look at x')
+ expect(appendToComposer('line\n', 'x')).toBe('line\nx')
+ })
+
+ it('ignores an empty insert', () => {
+ expect(appendToComposer('keep', '')).toBe('keep')
+ expect(appendToComposer('keep', ' ')).toBe('keep')
+ })
+})
diff --git a/src/renderer/lib/chatComposer.ts b/src/renderer/lib/chatComposer.ts
new file mode 100644
index 000000000..7c7710dbf
--- /dev/null
+++ b/src/renderer/lib/chatComposer.ts
@@ -0,0 +1,94 @@
+// Pure decisions behind the ⌘M chat composer's toolbar (ChatPanel): which labels fit, what they
+// say, and which of the agent's own pickers a click opens. No React, no store — see ChatPanel.tsx
+// for the glue and chatComposer.test.ts for the pins.
+import { capabilityAgentId } from '@shared/agents/config'
+import { formatModelLabel } from './usageFormat'
+
+/**
+ * Below these composer widths a label is dropped — effort first, then the model — so a narrow node
+ * keeps the controls that DO something (+ and the mic) instead of wrapping the toolbar. Measured
+ * against the toolbar's own row: "+" and the mic are ~28px each, "Fable 5.1" ~70px, "xHigh" ~45px.
+ */
+export const COMPOSER_MODEL_MIN_WIDTH = 220
+export const COMPOSER_EFFORT_MIN_WIDTH = 300
+
+/** Which labels the toolbar has room for. `null` = not measured yet (jsdom, a first paint before
+ * the ResizeObserver reported): show everything rather than flash an empty toolbar. */
+export function composerToolbarLayout(width: number | null): { model: boolean; effort: boolean } {
+ if (width === null) return { model: true, effort: true }
+ return { model: width >= COMPOSER_MODEL_MIN_WIDTH, effort: width >= COMPOSER_EFFORT_MIN_WIDTH }
+}
+
+/**
+ * The effort levels Claude Code records on each assistant transcript record (`"effort":"…"`), in
+ * the CLI's own display spelling. Measured against the installed 2.1.283 bundle: its level list is
+ * `["low","medium","high","xhigh","max"]`, and its picker prints xhigh as "xHigh" and the others
+ * capitalised. A CLOSED table on purpose: an unknown value is a CLI we have not measured, and a
+ * wrong label presented as a fact is worse than none (it also closes the prototype-key hole a
+ * bare `value in table` lookup would open).
+ */
+const EFFORT_LABELS: Readonly<Record<string, string>> = Object.freeze({
+ low: 'Low',
+ medium: 'Medium',
+ high: 'High',
+ xhigh: 'xHigh',
+ max: 'Max'
+})
+
+export function effortLabel(effort: string | null | undefined): string | null {
+ if (!effort || !Object.prototype.hasOwnProperty.call(EFFORT_LABELS, effort)) return null
+ return EFFORT_LABELS[effort]
+}
+
+export type ComposerPicker = 'model' | 'effort'
+
+/**
+ * The slash command that opens the agent's OWN picker in its pane. Typed through `pty.sendText`
+ * (paste + Enter), so the session is never restarted — the user picks in the TUI. Measured for
+ * claude only (2.1.283: `/model` and `/effort` are both `local-jsx` pickers when given no
+ * argument); a custom agent built on claude inherits it through `capabilityAgentId`. Any other
+ * agent gets no command, and therefore no label: a label that does nothing on click is a lie.
+ */
+const PICKER_COMMANDS: Readonly<Record<string, Readonly<Record<ComposerPicker, string>>>> = Object.freeze({
+ claude: Object.freeze({ model: '/model', effort: '/effort' })
+})
+
+export function composerPickerCommand(agentId: string, picker: ComposerPicker): string | null {
+ const base = capabilityAgentId(agentId)
+ if (!Object.prototype.hasOwnProperty.call(PICKER_COMMANDS, base)) return null
+ return PICKER_COMMANDS[base][picker]
+}
+
+/**
+ * What the toolbar's right side says. The model label is hidden while the model is unknown (the
+ * same `ContextWindowUsage.model` the header ContextMeter shows — no second reader), and effort is
+ * hidden with it: an effort with no model beside it reads as the model's name.
+ */
+export function composerLabels({
+ agentId,
+ model,
+ effort,
+ width
+}: {
+ agentId: string
+ model: string | null | undefined
+ effort: string | null | undefined
+ width: number | null
+}): { model: string | null; effort: string | null } {
+ const fits = composerToolbarLayout(width)
+ const modelText = fits.model && composerPickerCommand(agentId, 'model') ? formatModelLabel(model ?? null) : null
+ const effortText =
+ modelText && fits.effort && composerPickerCommand(agentId, 'effort') ? effortLabel(effort) : null
+ return { model: modelText, effort: effortText }
+}
+
+/**
+ * Text arriving from outside the keyboard (dictation, attached file paths) is APPENDED to what the
+ * user already typed, never replacing it, separated by a single space unless the draft already
+ * ends in whitespace. An empty insert changes nothing.
+ */
+export function appendToComposer(current: string, insert: string): string {
+ if (!insert.trim()) return current
+ if (!current || /\s$/.test(current)) return current + insert
+ return `${current} ${insert}`
+}
diff --git a/src/renderer/lib/chatComposerDictation.test.ts b/src/renderer/lib/chatComposerDictation.test.ts
new file mode 100644
index 000000000..2e7cf7666
--- /dev/null
+++ b/src/renderer/lib/chatComposerDictation.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ deliverToComposer,
+ dictationTargetFromRequest,
+ requestComposerDictation,
+ subscribeComposerDictation
+} from './chatComposerDictation'
+
+const unsubs: Array<() => void> = []
+afterEach(() => {
+ while (unsubs.length) unsubs.pop()!()
+})
+
+describe('dictationTargetFromRequest', () => {
+ it('targets the terminal for a bare node request (the header mic, unchanged)', () => {
+ expect(dictationTargetFromRequest({ nodeId: 'n1' }, 'shell')).toEqual({ kind: 'terminal', nodeId: 'n1', title: 'shell' })
+ })
+
+ it('targets ONE composer when the request names it', () => {
+ expect(dictationTargetFromRequest({ nodeId: 'n1', composerId: 'c1' }, 'shell')).toEqual({
+ kind: 'chat-composer',
+ nodeId: 'n1',
+ composerId: 'c1',
+ title: 'shell'
+ })
+ })
+
+ it('ignores a composer id that is not a non-empty string (falls back to the terminal)', () => {
+ expect(dictationTargetFromRequest({ nodeId: 'n1', composerId: '' }, 't').kind).toBe('terminal')
+ expect(dictationTargetFromRequest({ nodeId: 'n1', composerId: 7 as unknown as string }, 't').kind).toBe('terminal')
+ })
+})
+
+describe('composer dictation delivery', () => {
+ it('delivers to the named composer only and reports that it landed', () => {
+ const a = vi.fn()
+ const b = vi.fn()
+ unsubs.push(subscribeComposerDictation('a', a), subscribeComposerDictation('b', b))
+ expect(deliverToComposer('b', 'hello')).toBe(true)
+ expect(b).toHaveBeenCalledWith('hello')
+ expect(a).not.toHaveBeenCalled()
+ })
+
+ it('reports false when the composer is gone — the overlay must say so, not drop the take', () => {
+ expect(deliverToComposer('closed', 'hello')).toBe(false)
+ })
+
+ it('stops delivering after unsubscribe', () => {
+ const a = vi.fn()
+ const off = subscribeComposerDictation('a', a)
+ off()
+ expect(deliverToComposer('a', 'x')).toBe(false)
+ expect(a).not.toHaveBeenCalled()
+ })
+
+ it('requestComposerDictation asks the canvas for dictation into that composer', () => {
+ const seen = vi.fn()
+ const h = (e: Event) => seen((e as CustomEvent).detail)
+ window.addEventListener('nodeterm:dictate', h)
+ unsubs.push(() => window.removeEventListener('nodeterm:dictate', h))
+ requestComposerDictation('n1', 'c1')
+ expect(seen).toHaveBeenCalledWith({ nodeId: 'n1', composerId: 'c1' })
+ })
+})
diff --git a/src/renderer/lib/chatComposerDictation.ts b/src/renderer/lib/chatComposerDictation.ts
new file mode 100644
index 000000000..08ef8d228
--- /dev/null
+++ b/src/renderer/lib/chatComposerDictation.ts
@@ -0,0 +1,59 @@
+// Dictation INTO the ⌘M chat composer's textarea, reusing the one dictation machine
+// (`nodeterm:dictate` → Canvas → DictationOverlay). The overlay's terminal target types the take
+// into the pane with `pty.sendText`; a composer target must not — the composer is a draft the user
+// edits and sends themselves — so the take is handed to the composer that asked, by id.
+//
+// Keyed by a per-mount COMPOSER id, not the node id: one session can have two composers mounted at
+// once (the canvas node's ⌘M face and the kanban card modal's), and a take must land in the one
+// whose mic was clicked, exactly once.
+import type { DictationTarget } from '../components/DictationOverlay'
+
+interface ComposerDictationDetail {
+ composerId: string
+ text: string
+ /** Set by the listener that took the text — `dispatchEvent` is synchronous, so the sender reads
+ * it right after dispatching. */
+ delivered: boolean
+}
+
+/** The `nodeterm:dictate` request the composer's mic sends. */
+export function requestComposerDictation(nodeId: string, composerId: string): void {
+ window.dispatchEvent(new CustomEvent('nodeterm:dictate', { detail: { nodeId, composerId } }))
+}
+
+/**
+ * What a `nodeterm:dictate` request targets. A bare `{nodeId}` (the terminal header mic, the card
+ * modal's mic) keeps its terminal target byte-for-byte; a request naming a composer targets that
+ * composer's textarea instead.
+ */
+export function dictationTargetFromRequest(
+ detail: { nodeId: string; composerId?: unknown },
+ title: string
+): DictationTarget {
+ const composerId = detail.composerId
+ if (typeof composerId === 'string' && composerId) {
+ return { kind: 'chat-composer', nodeId: detail.nodeId, composerId, title }
+ }
+ return { kind: 'terminal', nodeId: detail.nodeId, title }
+}
+
+/** Hand a transcribed take to the composer that asked for it. `false` = no such composer is
+ * mounted any more (the ⌘M view was closed mid-take): the caller must say so, since nothing else
+ * will — the text went nowhere. */
+export function deliverToComposer(composerId: string, text: string): boolean {
+ const detail: ComposerDictationDetail = { composerId, text, delivered: false }
+ window.dispatchEvent(new CustomEvent('nodeterm:chat-dictation', { detail }))
+ return detail.delivered
+}
+
+/** A composer's end of `deliverToComposer`. Returns the unsubscribe. */
+export function subscribeComposerDictation(composerId: string, onText: (text: string) => void): () => void {
+ const handler = (e: Event): void => {
+ const d = (e as CustomEvent<ComposerDictationDetail>).detail
+ if (!d || d.composerId !== composerId || d.delivered) return
+ d.delivered = true
+ onText(d.text)
+ }
+ window.addEventListener('nodeterm:chat-dictation', handler)
+ return () => window.removeEventListener('nodeterm:chat-dictation', handler)
+}
diff --git a/src/renderer/nodes/ChatPanel.composer.test.tsx b/src/renderer/nodes/ChatPanel.composer.test.tsx
new file mode 100644
index 000000000..7bbd36db9
--- /dev/null
+++ b/src/renderer/nodes/ChatPanel.composer.test.tsx
@@ -0,0 +1,352 @@
+// @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 { useAgentStatus } from '../state/agentStatus'
+import { useContextWindow } from '../state/contextWindow'
+import { deliverToComposer } from '../lib/chatComposerDictation'
+import { COMPOSER_EFFORT_MIN_WIDTH, COMPOSER_MODEL_MIN_WIDTH } from '../lib/chatComposer'
+
+/**
+ * The claude.ai-style composer (lib/chatComposer.ts is the pure half). This file pins the GLUE:
+ * "+" / drop / paste turn files into paths IN THE DRAFT, the mic targets THIS composer and the take
+ * lands in the textarea, and the model / effort labels type the agent's own picker command through
+ * the SAME send gate as a message before flipping to the terminal.
+ */
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const { sendText, session } = vi.hoisted(() => {
+ const sendText = vi.fn(async (_id: string, _text: string): Promise<boolean | 'pasted-not-submitted'> => true)
+ const session = {
+ api: {
+ chat: { readTranscript: async () => ({ messages: [], found: true }) },
+ pty: { sendText }
+ }
+ }
+ return { sendText, session }
+})
+vi.mock('../session/session', () => ({ useSession: () => session }))
+
+import { ChatPanel } from './ChatPanel'
+
+const NODE = 'n-composer'
+const SESSION = 's-composer'
+let host: HTMLDivElement
+let root: Root
+let pathsForFiles: ReturnType<typeof vi.fn>
+let onShowTerminal: ReturnType<typeof vi.fn>
+
+function setAgentState(state: 'working' | 'waiting' | 'done' | undefined): void {
+ useAgentStatus.setState((s) => ({
+ byId: { ...s.byId, [NODE]: { ...(s.byId[NODE] ?? {}), state } as (typeof s.byId)[string] }
+ }))
+}
+
+function setUsage(model: string | null, effort?: string): void {
+ useContextWindow.getState().set({
+ sessionId: SESSION,
+ usedTokens: 10,
+ windowTokens: 100,
+ usedPercent: 10,
+ model,
+ ...(effort ? { effort } : {}),
+ windowSource: 'transcript',
+ updatedAt: Date.now()
+ })
+}
+
+async function mount(props: { withPicker?: boolean; withFiles?: boolean } = {}): Promise<void> {
+ const { withPicker = true, withFiles = true } = props
+ await act(async () => {
+ root.render(
+ <ChatPanel
+ nodeId={NODE}
+ sessionId={SESSION}
+ agentId="claude"
+ pathsForFiles={withFiles ? (pathsForFiles as never) : undefined}
+ onShowTerminal={withPicker ? (onShowTerminal as never) : undefined}
+ />
+ )
+ })
+}
+
+const textarea = () => host.querySelector('.term-chat__compose textarea') as HTMLTextAreaElement
+const button = (label: string) => host.querySelector(`button[aria-label="${label}"]`) as HTMLButtonElement | null
+const modelBtn = () => host.querySelector('.term-chat__model') as HTMLButtonElement | null
+const effortBtn = () => host.querySelector('.term-chat__effort') as HTMLButtonElement | null
+
+function type(ta: HTMLTextAreaElement, text: string): void {
+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!
+ setter.call(ta, text)
+ ta.dispatchEvent(new Event('input', { bubbles: true }))
+}
+
+const flush = () => act(async () => {
+ await new Promise((r) => setTimeout(r, 0))
+})
+
+beforeEach(() => {
+ sendText.mockReset()
+ sendText.mockResolvedValue(true)
+ pathsForFiles = vi.fn(async (files: File[]) => files.map((f) => `/tmp/${f.name.replace(/ /g, '\\ ')}`))
+ onShowTerminal = vi.fn()
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+
+afterEach(async () => {
+ await act(async () => root.unmount())
+ host.remove()
+ vi.unstubAllGlobals()
+ useAgentStatus.setState((s) => {
+ const byId = { ...s.byId }
+ delete byId[NODE]
+ return { byId }
+ })
+ useContextWindow.setState((s) => {
+ const bySessionId = { ...s.bySessionId }
+ delete bySessionId[SESSION]
+ return { bySessionId }
+ })
+})
+
+describe('composer attach ("+", paste, drop)', () => {
+ it('"+" opens the file picker, and the picked files land in the draft as paths', async () => {
+ setAgentState('done')
+ await mount()
+ await act(async () => type(textarea(), 'look at'))
+ const input = host.querySelector('.term-chat__compose input[type="file"]') as HTMLInputElement
+ const clicked = vi.spyOn(input, 'click')
+ await act(async () => button('Attach files')!.click())
+ expect(clicked).toHaveBeenCalled()
+
+ const file = new File(['x'], 'shot 1.png', { type: 'image/png' })
+ Object.defineProperty(input, 'files', { configurable: true, value: [file] })
+ await act(async () => {
+ input.dispatchEvent(new Event('change', { bubbles: true }))
+ })
+ await flush()
+ expect(pathsForFiles).toHaveBeenCalledWith([file])
+ expect(textarea().value).toBe('look at /tmp/shot\\ 1.png ')
+ // Attaching never sends: the user decides when.
+ expect(sendText).not.toHaveBeenCalled()
+ })
+
+ it('a pasted file (a screenshot) becomes a path in the draft, not raw text', async () => {
+ setAgentState('done')
+ await mount()
+ const file = new File(['x'], 'paste.png', { type: 'image/png' })
+ const ev = new Event('paste', { bubbles: true, cancelable: true })
+ Object.defineProperty(ev, 'clipboardData', {
+ value: { files: [file], items: [], getData: () => '' }
+ })
+ await act(async () => {
+ textarea().dispatchEvent(ev)
+ })
+ await flush()
+ expect(ev.defaultPrevented).toBe(true)
+ expect(textarea().value).toBe('/tmp/paste.png ')
+ })
+
+ it('a text paste is left to the textarea', async () => {
+ setAgentState('done')
+ await mount()
+ const ev = new Event('paste', { bubbles: true, cancelable: true })
+ Object.defineProperty(ev, 'clipboardData', {
+ value: { files: [], items: [], getData: (t: string) => (t === 'text/plain' ? 'hi' : '') }
+ })
+ await act(async () => {
+ textarea().dispatchEvent(ev)
+ })
+ expect(ev.defaultPrevented).toBe(false)
+ expect(pathsForFiles).not.toHaveBeenCalled()
+ })
+
+ it('a file dropped on the composer lands in the draft and never reaches the canvas', async () => {
+ setAgentState('done')
+ await mount()
+ // The canvas's image-drop listener is on `window`; React's stopPropagation must keep it there.
+ const outer = vi.fn()
+ window.addEventListener('drop', outer)
+ const file = new File(['x'], 'notes.md', { type: 'text/markdown' })
+ const ev = new Event('drop', { bubbles: true, cancelable: true })
+ Object.defineProperty(ev, 'dataTransfer', { value: { files: [file], types: ['Files'] } })
+ await act(async () => {
+ host.querySelector('.term-chat__composer')!.dispatchEvent(ev)
+ })
+ await flush()
+ window.removeEventListener('drop', outer)
+ expect(ev.defaultPrevented).toBe(true)
+ expect(outer).not.toHaveBeenCalled()
+ expect(textarea().value).toBe('/tmp/notes.md ')
+ })
+
+ it('says so when no path could be resolved (an upload that failed)', async () => {
+ setAgentState('done')
+ pathsForFiles.mockResolvedValue([])
+ await mount()
+ const ev = new Event('drop', { bubbles: true, cancelable: true })
+ Object.defineProperty(ev, 'dataTransfer', {
+ value: { files: [new File(['x'], 'a.png')], types: ['Files'] }
+ })
+ await act(async () => {
+ host.querySelector('.term-chat__composer')!.dispatchEvent(ev)
+ })
+ await flush()
+ expect(textarea().value).toBe('')
+ expect(host.querySelector('.term-chat__attach-note--failed')?.textContent).toMatch(/Could not attach/)
+ })
+
+ it('has no "+" when the mount site cannot resolve files', async () => {
+ setAgentState('done')
+ await mount({ withFiles: false })
+ expect(button('Attach files')).toBeNull()
+ })
+})
+
+describe('composer mic', () => {
+ it('asks for dictation INTO this composer, and the take lands in the textarea (not the pane)', async () => {
+ setAgentState('done')
+ await mount()
+ await act(async () => type(textarea(), 'please'))
+ const seen: Array<{ nodeId: string; composerId?: string }> = []
+ const h = (e: Event) => seen.push((e as CustomEvent).detail)
+ window.addEventListener('nodeterm:dictate', h)
+ await act(async () => button('Dictate into the message')!.click())
+ window.removeEventListener('nodeterm:dictate', h)
+ expect(seen).toHaveLength(1)
+ expect(seen[0].nodeId).toBe(NODE)
+ expect(typeof seen[0].composerId).toBe('string')
+
+ let delivered = false
+ await act(async () => {
+ delivered = deliverToComposer(seen[0].composerId!, 'fix the tests')
+ })
+ expect(delivered).toBe(true)
+ expect(textarea().value).toBe('please fix the tests')
+ expect(sendText).not.toHaveBeenCalled()
+ })
+})
+
+describe('model / effort labels', () => {
+ it('shows the session model and effort from the ContextMeter source', async () => {
+ setAgentState('done')
+ setUsage('claude-fable-5-1', 'medium')
+ await mount()
+ expect(modelBtn()?.textContent).toBe('Fable 5.1')
+ expect(effortBtn()?.textContent).toBe('Medium')
+ })
+
+ it('hides the model label when the model is unknown', async () => {
+ setAgentState('done')
+ await mount()
+ expect(modelBtn()).toBeNull()
+ expect(effortBtn()).toBeNull()
+ })
+
+ it('hides both labels when the mount site cannot flip to the terminal', async () => {
+ setAgentState('done')
+ setUsage('claude-opus-5', 'high')
+ await mount({ withPicker: false })
+ expect(modelBtn()).toBeNull()
+ expect(effortBtn()).toBeNull()
+ })
+
+ it('clicking the model sends /model through the send gate and flips to the terminal', async () => {
+ setAgentState('done')
+ setUsage('claude-opus-5', 'high')
+ await mount()
+ await act(async () => modelBtn()!.click())
+ await flush()
+ expect(sendText).toHaveBeenCalledWith(NODE, '/model')
+ expect(onShowTerminal).toHaveBeenCalledTimes(1)
+ })
+
+ it('clicking the effort sends /effort and flips to the terminal', async () => {
+ setAgentState('done')
+ setUsage('claude-opus-5', 'xhigh')
+ await mount()
+ expect(effortBtn()?.textContent).toBe('xHigh')
+ await act(async () => effortBtn()!.click())
+ await flush()
+ expect(sendText).toHaveBeenCalledWith(NODE, '/effort')
+ expect(onShowTerminal).toHaveBeenCalledTimes(1)
+ })
+
+ it('is disabled while the agent works or a dialog is up (a picker command would answer it)', async () => {
+ setUsage('claude-opus-5', 'high')
+ setAgentState('working')
+ await mount()
+ expect(modelBtn()!.disabled).toBe(true)
+ await act(async () => setAgentState('waiting'))
+ expect(modelBtn()!.disabled).toBe(true)
+ expect(effortBtn()!.disabled).toBe(true)
+ })
+
+ it('re-reads the gate at click time: a dialog that arrived after the last render still blocks', async () => {
+ setUsage('claude-opus-5', 'high')
+ setAgentState('done')
+ await mount()
+ await act(async () => {
+ setAgentState('waiting')
+ modelBtn()!.click()
+ })
+ await flush()
+ expect(sendText).not.toHaveBeenCalled()
+ expect(onShowTerminal).not.toHaveBeenCalled()
+ })
+
+ it('does not flip when the command was pasted but not submitted', async () => {
+ setUsage('claude-opus-5', 'high')
+ setAgentState('done')
+ sendText.mockResolvedValue('pasted-not-submitted')
+ await mount()
+ await act(async () => modelBtn()!.click())
+ await flush()
+ expect(sendText).toHaveBeenCalledWith(NODE, '/model')
+ expect(onShowTerminal).not.toHaveBeenCalled()
+ })
+
+ it('a refused write (session gone) neither flips nor pretends: the composer goes read-only', async () => {
+ setUsage('claude-opus-5', 'high')
+ setAgentState('done')
+ sendText.mockResolvedValue(false)
+ await mount()
+ await act(async () => modelBtn()!.click())
+ await flush()
+ expect(onShowTerminal).not.toHaveBeenCalled()
+ expect(textarea().disabled).toBe(true)
+ expect(textarea().placeholder).toMatch(/Can't write to this session/)
+ })
+
+ it('drops the effort label first, then the model label, as the composer narrows', async () => {
+ let fire: (width: number) => void = () => {}
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(cb: (entries: Array<{ contentRect: { width: number } }>) => void) {
+ fire = (width) => cb([{ contentRect: { width } }])
+ }
+ observe(): void {}
+ disconnect(): void {}
+ }
+ )
+ setAgentState('done')
+ setUsage('claude-opus-5', 'high')
+ await mount()
+ await act(async () => fire(COMPOSER_EFFORT_MIN_WIDTH + 50))
+ expect(modelBtn()).not.toBeNull()
+ expect(effortBtn()).not.toBeNull()
+ await act(async () => fire(COMPOSER_EFFORT_MIN_WIDTH - 1))
+ expect(modelBtn()).not.toBeNull()
+ expect(effortBtn()).toBeNull()
+ await act(async () => fire(COMPOSER_MODEL_MIN_WIDTH - 1))
+ expect(modelBtn()).toBeNull()
+ expect(effortBtn()).toBeNull()
+ // The controls that DO something stay at every width.
+ expect(button('Attach files')).not.toBeNull()
+ expect(button('Dictate into the message')).not.toBeNull()
+ })
+})
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 8486968b9..0d3df8f9d 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -1,5 +1,17 @@
import { TEXT_NOT_SUBMITTED } from '@shared/text-delivery'
-import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react'
+import {
+ memo,
+ useCallback,
+ useEffect,
+ useId,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ClipboardEvent as ReactClipboardEvent,
+ type DragEvent as ReactDragEvent,
+ type KeyboardEvent
+} from 'react'
import { renderMarkdown } from '../lib/markdown'
import { useAgentStatus } from '../state/agentStatus'
import { useSession } from '../session/session'
@@ -24,6 +36,11 @@ import { ChatLoadingStatus } from './ChatPanelFallback'
import { activeAnswerCard } from '../lib/chatAnswer'
import { PlanAnswerControls, QuestionAnswerControls } from './ChatAnswerControls'
import type { PermissionAnswer } from '@shared/agents/permission-answer'
+import { IconMic, IconPlus } from '../components/icons'
+import { useContextUsage } from '../state/contextWindow'
+import { appendToComposer, composerLabels, composerPickerCommand, type ComposerPicker } from '../lib/chatComposer'
+import { requestComposerDictation, subscribeComposerDictation } from '../lib/chatComposerDictation'
+import { clipboardImages, pasteHasText, pastedFiles } from '../terminal/file-drop'
// Memoized bubble: marked+DOMPurify re-ran for EVERY message on each ChatPanel render (each
// turn-finish reload, each keystroke re-render). Text is stable per message, so cache per text.
@@ -56,6 +73,21 @@ interface ChatPanelProps {
title?: string
/** Rendered at the right of the bar in place of the ⌘M exit hint. */
hint?: string
+ /**
+ * Resolve attached files (the composer's "+", a drop, a pasted file or screenshot) to the paths
+ * the agent should read — the SAME resolution a drop onto the node's terminal uses
+ * (`droppedPaths`), supplied by the mount site because only it knows the node's scope (an SSH
+ * node uploads to its host over the master it runs on; a local one uses the local path, or the
+ * uploads dir for clipboard bytes). Absent = no attach affordance.
+ */
+ pathsForFiles?: (files: File[]) => Promise<string[]>
+ /**
+ * Leave the ⌘M view for the node's terminal. The toolbar's model / effort labels type the
+ * agent's own picker command (`/model`, `/effort`) into the pane and then call this, so the user
+ * sees the picker they just opened. Absent = no labels (a label that opens a picker nobody can
+ * see is worse than none).
+ */
+ onShowTerminal?: () => void
}
/**
@@ -102,7 +134,9 @@ export function ChatPanel({
agentId,
readOnly,
title,
- hint
+ hint,
+ pathsForFiles,
+ onShowTerminal
}: ChatPanelProps) {
// This node's core api (stable for the session — the chat transcript and the tmux session
// both live on the core this panel's project belongs to).
@@ -500,6 +534,134 @@ export function ChatPanel({
setInput('')
}, [api, input, nodeId, agentId])
+ // ── Composer toolbar (lib/chatComposer.ts) ────────────────────────────────────────────────
+ const inputRef = useRef<HTMLTextAreaElement>(null)
+ const composerRef = useRef<HTMLDivElement>(null)
+ const fileInputRef = useRef<HTMLInputElement>(null)
+ // Per-MOUNT id, not the node id: the canvas node and the kanban card modal can both have this
+ // session's composer mounted, and a dictated take must land in the one whose mic was clicked.
+ const composerId = useId()
+ // The model / effort the header ContextMeter shows, from the SAME reader (no second transcript
+ // read). Never node-scoped: that is for remote Codex, which never mounts this panel.
+ const usage = useContextUsage({ sessionId, nodeId, scoped: false })
+ const [composerWidth, setComposerWidth] = useState<number | null>(null)
+ const [attachNote, setAttachNote] = useState<{ text: string; failed?: boolean } | null>(null)
+ const [dropping, setDropping] = useState(false)
+ const labels = composerLabels({ agentId, model: usage?.model, effort: usage?.effort, width: composerWidth })
+ const composerDisabled = readonly || refusal !== null
+
+ // The labels drop by the composer's OWN width (a narrow node, a split card modal), not the
+ // window's. Guarded like the thread's observer: jsdom and old engines have none, and then every
+ // label shows (`composerToolbarLayout(null)`).
+ useEffect(() => {
+ const el = composerRef.current
+ if (!el || typeof ResizeObserver === 'undefined') return
+ const ro = new ResizeObserver((entries?: ResizeObserverEntry[]) => {
+ // No box (collapsed node, display:none) reports 0: keep the last real width rather than
+ // collapsing the toolbar to its narrowest form while nobody can see it.
+ const w = entries?.[entries.length - 1]?.contentRect?.width ?? el.clientWidth
+ if (typeof w === 'number' && w > 0) setComposerWidth(Math.round(w))
+ })
+ ro.observe(el)
+ return () => ro.disconnect()
+ }, [readOnly])
+
+ const insertIntoComposer = useCallback((text: string) => {
+ setInput((cur) => appendToComposer(cur, text))
+ inputRef.current?.focus()
+ }, [])
+
+ // A dictated take for THIS composer lands in the draft, never in the pane.
+ useEffect(() => subscribeComposerDictation(composerId, insertIntoComposer), [composerId, insertIntoComposer])
+
+ const attachFiles = useCallback(
+ async (files: File[]) => {
+ if (!files.length || !pathsForFiles) return
+ setAttachNote({ text: `Attaching ${files.length === 1 ? files[0].name || 'file' : `${files.length} files`}…` })
+ let paths: string[] = []
+ try {
+ paths = await pathsForFiles(files)
+ } catch {
+ paths = []
+ }
+ if (!paths.length) {
+ setAttachNote({ text: 'Could not attach', failed: true })
+ return
+ }
+ setAttachNote(null)
+ // Same shape a drop into the terminal pastes: escaped paths, space-separated, trailing space.
+ insertIntoComposer(paths.join(' ') + ' ')
+ },
+ [pathsForFiles, insertIntoComposer]
+ )
+ useEffect(() => {
+ if (!attachNote?.failed) return
+ const t = setTimeout(() => setAttachNote(null), 2500)
+ return () => clearTimeout(t)
+ }, [attachNote])
+
+ // Files arriving by drop or paste become paths in the DRAFT (the terminal's own drop handlers
+ // stand aside while the ⌘M view covers it — `terminalOwnsFileInput`). Stopped here so the
+ // canvas's window-level drop (image nodes) never sees a drop aimed at the composer.
+ const onComposerDragOver = (e: ReactDragEvent) => {
+ if (!pathsForFiles || composerDisabled || !Array.from(e.dataTransfer.types).includes('Files')) return
+ e.preventDefault()
+ e.stopPropagation()
+ e.dataTransfer.dropEffect = 'copy'
+ if (!dropping) setDropping(true)
+ }
+ const onComposerDragLeave = (e: ReactDragEvent) => {
+ const rt = e.relatedTarget as Node | null
+ if (!rt || !(e.currentTarget as HTMLElement).contains(rt)) setDropping(false)
+ }
+ const onComposerDrop = (e: ReactDragEvent) => {
+ setDropping(false)
+ if (!pathsForFiles || composerDisabled) return
+ const files = Array.from(e.dataTransfer.files)
+ if (!files.length) return
+ e.preventDefault()
+ e.stopPropagation()
+ void attachFiles(files)
+ }
+ const onComposerPaste = (e: ReactClipboardEvent<HTMLTextAreaElement>) => {
+ if (!pathsForFiles) return
+ const files = pastedFiles(e.clipboardData)
+ if (files.length) {
+ e.preventDefault()
+ e.stopPropagation()
+ void attachFiles(files)
+ return
+ }
+ // Ordinary text is the textarea's; only an image-only clipboard Chromium filtered to nothing
+ // on its way to a text target asks the async Clipboard API (see `clipboardImages`).
+ if (pasteHasText(e.clipboardData)) return
+ void clipboardImages().then((images) => {
+ if (images.length) void attachFiles(images)
+ })
+ }
+
+ // The model / effort label: type the agent's own picker command into the pane — through the
+ // SAME send gate as a message, re-read at click time (a picker command typed into a dialog would
+ // answer it; into a shell it would run) — then flip to the terminal so the picker is in view.
+ const openPicker = useCallback(
+ async (picker: ComposerPicker) => {
+ const command = composerPickerCommand(agentId, picker)
+ if (!command || !onShowTerminal) return
+ if (chatSendRefusal(agentId, useAgentStatus.getState().byId[nodeId] ?? {}) !== null) return
+ const ok = await api.pty.sendText(nodeId, command)
+ if (ok === 'pasted-not-submitted') {
+ window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message: TEXT_NOT_SUBMITTED } }))
+ return
+ }
+ if (ok !== true) {
+ setReadonly(true)
+ return
+ }
+ onShowTerminal()
+ },
+ [api, agentId, nodeId, onShowTerminal]
+ )
+
// Answer the held request through core, which validates the answer against the pending request
// file and builds what the hook prints. The ticket is re-checked against the store at SEND time:
// a hold that ended (answered in the TUI, timed out, replaced) while the user was choosing must
@@ -662,21 +824,105 @@ export function ChatPanel({
</div>
{!readOnly && (
<div className="term-chat__compose">
- <textarea
- className="term-chat__input"
- value={input}
- onChange={(e) => setInput(e.target.value)}
- onKeyDown={onKeyDown}
- placeholder={chatComposerPlaceholder({
- readonly,
- refusal,
- agentLabel,
- chip: mdChip,
- answerOnCard: answerCard !== null
- })}
- disabled={readonly || refusal !== null}
- rows={2}
- />
+ <div
+ ref={composerRef}
+ className={`term-chat__composer${dropping ? ' term-chat__composer--drop' : ''}${
+ composerDisabled ? ' term-chat__composer--disabled' : ''
+ }`}
+ onDragOver={onComposerDragOver}
+ onDragLeave={onComposerDragLeave}
+ onDrop={onComposerDrop}
+ >
+ <textarea
+ ref={inputRef}
+ className="term-chat__input"
+ value={input}
+ onChange={(e) => setInput(e.target.value)}
+ onKeyDown={onKeyDown}
+ onPaste={onComposerPaste}
+ placeholder={chatComposerPlaceholder({
+ readonly,
+ refusal,
+ agentLabel,
+ chip: mdChip,
+ answerOnCard: answerCard !== null
+ })}
+ disabled={composerDisabled}
+ rows={2}
+ />
+ <div className="term-chat__toolbar">
+ {pathsForFiles && (
+ <>
+ <button
+ type="button"
+ className="term-chat__tool-btn"
+ title="Attach files — their paths go into the message"
+ aria-label="Attach files"
+ disabled={composerDisabled}
+ onClick={() => fileInputRef.current?.click()}
+ >
+ <IconPlus />
+ </button>
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ hidden
+ tabIndex={-1}
+ aria-hidden="true"
+ onChange={(e) => {
+ const files = Array.from(e.target.files ?? [])
+ // Reset so picking the same file again still fires `change`.
+ e.target.value = ''
+ void attachFiles(files)
+ }}
+ />
+ </>
+ )}
+ {attachNote && (
+ <span
+ className={`term-chat__attach-note${attachNote.failed ? ' term-chat__attach-note--failed' : ''}`}
+ role="status"
+ >
+ {!attachNote.failed && <Spinner />}
+ {attachNote.text}
+ </span>
+ )}
+ <span className="term-chat__toolbar-spacer" />
+ {onShowTerminal && labels.model && (
+ <button
+ type="button"
+ className="term-chat__model"
+ title={`Change model — opens ${agentLabel}'s /model picker in the terminal`}
+ disabled={composerDisabled}
+ onClick={() => void openPicker('model')}
+ >
+ {labels.model}
+ </button>
+ )}
+ {onShowTerminal && labels.effort && (
+ <button
+ type="button"
+ className="term-chat__effort"
+ title={`Change effort — opens ${agentLabel}'s /effort picker in the terminal`}
+ disabled={composerDisabled}
+ onClick={() => void openPicker('effort')}
+ >
+ {labels.effort}
+ </button>
+ )}
+ <button
+ type="button"
+ className="term-chat__tool-btn"
+ title="Dictate into the message"
+ aria-label="Dictate into the message"
+ disabled={composerDisabled}
+ onClick={() => requestComposerDictation(nodeId, composerId)}
+ >
+ <IconMic />
+ </button>
+ </div>
+ </div>
</div>
)}
</div>
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index e87e41aa9..c79c208b6 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -5108,6 +5108,13 @@ export function TerminalNode({
const rt = e.relatedTarget as Node | null
if (!rt || !(e.currentTarget as HTMLElement).contains(rt)) setDropping(false)
}
+ // Uploads go over the master this node's PTY runs on — its scope, which for an attached node is
+ // the host attachment, not the (local) project. Shared by the terminal drop and the ⌘M composer's
+ // attach, so the two can never upload one file to two different machines.
+ const dropProjectId = (): string => {
+ const dropConn = data.ssh as SshConnection | undefined
+ return dropConn ? sshConnectionScope(dropConn) : useProjects.getState().activeProjectId
+ }
/**
* Files arriving by DROP or by PASTE become paths in the terminal — what a native terminal does
* on a drop, and the only thing a shell (or an agent reading its prompt) can act on. Shared so
@@ -5127,12 +5134,7 @@ export function TerminalNode({
// Remote terminal: uploading over the ControlMaster takes seconds and pastes nothing until
// it's done, so show an overlay while it runs — without it a drop looks like it silently did
// nothing. (The upload + REMOTE-path resolution itself lives in the shared droppedPaths.)
- // Uploads go over the master this node's PTY runs on — its scope, which for an attached
- // node is the host attachment, not the (local) project.
- const dropConn = data.ssh as SshConnection | undefined
- const projectId = dropConn
- ? sshConnectionScope(dropConn)
- : useProjects.getState().activeProjectId
+ const projectId = dropProjectId()
if (uploadNoteTimer.current) clearTimeout(uploadNoteTimer.current)
setUploadNote({
text: `Uploading ${files.length === 1 ? files[0].name : `${files.length} files`}…`,
@@ -6070,6 +6072,14 @@ export function TerminalNode({
// system-root one. Spawn/env identity is unaffected — that stays creation-time.
accountId={accountForReads}
agentId={agentId}
+ // The composer's attach resolves files exactly as a drop onto THIS terminal does.
+ pathsForFiles={(files) =>
+ droppedPaths(files, {
+ sshRemoteTmux: !!data.sshRemoteTmux,
+ projectId: data.sshRemoteTmux ? dropProjectId() : ''
+ })
+ }
+ onShowTerminal={() => updateNodeData(id, () => ({ mdMode: false }))}
/>
</Suspense>
) : (
diff --git a/src/renderer/state/contextWindow.ts b/src/renderer/state/contextWindow.ts
index b2c47d6cc..ce624ff8b 100644
--- a/src/renderer/state/contextWindow.ts
+++ b/src/renderer/state/contextWindow.ts
@@ -82,3 +82,27 @@ export const useContextWindow = create<ContextWindowState>((set) => ({
return { bySessionId }
})
}))
+
+/**
+ * The ONE reader of a node's context usage — the header ContextMeter and the ⌘M composer's model /
+ * effort labels both call it, so they can never show different models for one session.
+ *
+ * A copied rollout has the same session id on two hosts: SSH Codex observations belong to the node
+ * that requested them (`scoped`), never to a local/session-only snapshot. Everything else is keyed
+ * by session id, and a value whose session id does not match is not this session's.
+ */
+export function useContextUsage({
+ sessionId,
+ nodeId,
+ scoped
+}: {
+ sessionId: string | null | undefined
+ nodeId?: string
+ scoped: boolean
+}): ContextWindowUsage | undefined {
+ return useContextWindow((s) => {
+ if (!sessionId) return undefined
+ const value = scoped ? (nodeId ? s.byNodeId[nodeId] : undefined) : s.bySessionId[sessionId]
+ return value?.sessionId === sessionId ? value : undefined
+ })
+}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 159ae48bc..afa4b462f 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -3445,25 +3445,122 @@ body,
padding: 8px;
border-top: 1px solid rgba(var(--tint-rgb), 0.08);
}
+/* The claude.ai-style composer (ChatPanel): ONE rounded box holding the textarea on top and a
+ compact toolbar under it — "+" attach on the left; model label, muted effort label and the mic
+ on the right. The focus ring belongs to the BOX, so the textarea itself draws no border. */
+.term-chat__composer {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 6px 6px 4px;
+ background: rgba(var(--tint-rgb), 0.06);
+ border: 1px solid rgba(var(--tint-rgb), 0.12);
+ border-radius: 12px;
+ transition: border-color 0.12s ease;
+}
+.term-chat__composer:focus-within {
+ border-color: var(--accent);
+}
+.term-chat__composer--drop {
+ border-color: var(--accent);
+ border-style: dashed;
+}
.term-chat__input {
box-sizing: border-box;
width: 100%;
resize: none;
- padding: 8px;
+ padding: 4px 6px;
font-family: inherit;
font-size: 13px;
color: var(--text-strong);
- background: rgba(var(--tint-rgb), 0.06);
- border: 1px solid rgba(var(--tint-rgb), 0.12);
- border-radius: 8px;
+ background: transparent;
+ border: none;
+ border-radius: 0;
}
.term-chat__input:focus {
outline: none;
- border-color: var(--accent);
}
.term-chat__input:disabled {
opacity: 0.5;
}
+.term-chat__toolbar {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ min-width: 0;
+ min-height: 26px;
+}
+.term-chat__toolbar-spacer {
+ flex: 1 1 auto;
+ min-width: 4px;
+}
+.term-chat__tool-btn {
+ flex: 0 0 auto;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 26px;
+ height: 26px;
+ padding: 0;
+ color: var(--muted);
+ background: none;
+ border: none;
+ border-radius: 6px;
+ cursor: pointer;
+}
+.term-chat__tool-btn svg {
+ width: 15px;
+ height: 15px;
+}
+.term-chat__tool-btn:hover:not(:disabled),
+.term-chat__model:hover:not(:disabled),
+.term-chat__effort:hover:not(:disabled) {
+ color: var(--text-strong);
+ background: rgba(var(--tint-rgb), 0.08);
+}
+.term-chat__tool-btn:disabled,
+.term-chat__model:disabled,
+.term-chat__effort:disabled {
+ opacity: 0.45;
+ cursor: default;
+}
+/* The model name reads as the primary label, effort beside it muted — the reference's
+ "Fable 5.1 Medium". Both are buttons: a click opens the agent's own picker in the terminal. */
+.term-chat__model,
+.term-chat__effort {
+ flex: 0 1 auto;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ padding: 3px 6px;
+ font-family: inherit;
+ font-size: 12px;
+ background: none;
+ border: none;
+ border-radius: 6px;
+ cursor: pointer;
+}
+.term-chat__model {
+ color: var(--text);
+}
+.term-chat__effort {
+ color: var(--muted);
+}
+.term-chat__attach-note {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ font-size: 11px;
+ color: var(--muted);
+}
+.term-chat__attach-note--failed {
+ color: var(--danger);
+}
.term-chat__bar-end {
display: flex;
align-items: center;
diff --git a/src/shared/types.ts b/src/shared/types.ts
index da009600a..e734d6f07 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2736,6 +2736,12 @@ export interface ContextWindowUsage {
usedPercent: number
/** Model id from the transcript, or null if not seen yet. */
model: string | null
+ /**
+ * Reasoning effort of the latest request, as Claude Code records it on the transcript's assistant
+ * record (`low`/`medium`/`high`/`xhigh`/`max` on 2.1.283). Absent = not recorded: another agent,
+ * an older host or CLI, or a model that takes no effort. Shown by the ⌘M composer's toolbar.
+ */
+ effort?: string
updatedAt: number
}