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): show Claude's suggested next prompt in the ⌘M composer

Paul Robertsone3c82462146c
diff --git a/CLAUDE.md b/CLAUDE.md
index 839a4f8b0..d17365e80 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4454,6 +4454,21 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
re-reads at once; unknown focus polls), to disable the composer and show the dialog's lines; SSH and relay panes are not polled (a round trip per read) and rely
on the send-time check. Another CLI's layout would read as a permanent dialog, so an agent joins
the list only with its own measured reader.
+ **Claude's suggested next prompt is the composer's placeholder** (`readClaudeSuggestion`,
+ `pty.readChatScreen`). A few seconds after a turn ends, and only when there is an obvious next
+ step, Claude draws a suggestion as plain DIM text on its prompt line (MEASURED on 2.1.318); → in
+ its TUI accepts it, and → in an EMPTY composer does the same here: it fills the draft with the
+ caret at the end, and nothing is sent. The poll now makes ONE styled read for both the dialog
+ check and the suggestion (a styled capture is the only way to tell dim text from a draft; a pane
+ with no styled capture still gets the dialog check from the plain one). Two other dim texts sit
+ in the same place and are refused: the fresh-session tips (always `Try "…"`) and `Press up to
+ edit queued messages`. Shown only while a message could be sent and no dialog is on screen;
+ cleared on every state change and on send. Claude draws it 1.1-2.2 s after the turn ends
+ (measured, 5 turns), and the 2 s poll added up to 2 s more, which read as a lag; so after a turn
+ ends a local pane is read every 300 ms for up to 5 s, stopping at the first suggestion
+ (`SUGGESTION_BURST_MS`, at most ~15 extra reads per turn). An SSH node is never polled, so it is
+ read twice after each turn (`REMOTE_SUGGESTION_READ_DELAYS_MS`, 2.5 s and 6 s); relay tabs offer
+ none.
**Live progress (2026-09).** While the agent works, a `role=status` row closes the thread (the ONE
spinner + the placeholder's own "<agent> is working…"/"waiting for an answer" sentence; optimistic
right after a send, bounded by `CHAT_OPTIMISTIC_WORKING_MS`), and every hook event re-reads the
diff --git a/src/core/pty-manager.chat-screen.test.ts b/src/core/pty-manager.chat-screen.test.ts
new file mode 100644
index 000000000..641f6114d
--- /dev/null
+++ b/src/core/pty-manager.chat-screen.test.ts
@@ -0,0 +1,60 @@
+// `PtyManager.readChatScreen` — the ⌘M chat view's one screen read: the dialog check and the prompt
+// Claude suggests next, from a STYLED capture (only styling tells a dim suggestion from typed text).
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform } from './platform-fake'
+
+vi.mock('node-pty', () => ({ spawn: () => ({}) }))
+
+const NODE = 'node-1'
+const RULE = '─'.repeat(80)
+const SUGGESTING = [RULE, '\x1b[39m❯ \x1b[2mrun it in the background\x1b[0m', RULE, ' ? for shortcuts'].join('\n')
+const TRUST = [RULE, ' Accessing workspace:', ' ❯ No, exit', ' Yes, I trust this folder', ' Enter to confirm · Esc to cancel'].join('\n')
+
+type Private = { captureStyledScreen: (key: string) => Promise<string> }
+
+async function manager(styled: string, plain: string) {
+ const { PtyManager } = await import('./pty-manager')
+ const mgr = new PtyManager()
+ const captureStyled = vi.spyOn(mgr as unknown as Private, 'captureStyledScreen').mockResolvedValue(styled)
+ const captureSession = vi.spyOn(mgr, 'captureSession').mockResolvedValue(plain)
+ return { mgr, captureStyled, captureSession }
+}
+
+describe('PtyManager.readChatScreen', () => {
+ beforeEach(() => {
+ vi.resetModules()
+ initPlatform(fakePlatform())
+ })
+ afterEach(() => {
+ resetPlatformForTests()
+ })
+
+ it("reads Claude's prompt and its suggestion from one styled capture", async () => {
+ const { mgr, captureSession } = await manager(SUGGESTING, '')
+
+ const result = await mgr.readChatScreen(NODE, 'claude')
+
+ expect(result).toEqual({ screen: { kind: 'prompt' }, suggestion: 'run it in the background' })
+ expect(captureSession).not.toHaveBeenCalled()
+ })
+
+ it('still answers the dialog check from the plain capture when no styled one exists', async () => {
+ const { mgr } = await manager('', TRUST)
+
+ const result = await mgr.readChatScreen(NODE, 'claude')
+
+ expect(result.screen.kind).toBe('dialog')
+ expect(result.suggestion).toBeNull()
+ })
+
+ it('reads nothing for an agent without a measured screen reader', async () => {
+ const { mgr, captureStyled, captureSession } = await manager(SUGGESTING, SUGGESTING)
+
+ const result = await mgr.readChatScreen(NODE, 'codex')
+
+ expect(result).toEqual({ screen: { kind: 'unknown' }, suggestion: null })
+ expect(captureStyled).not.toHaveBeenCalled()
+ expect(captureSession).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 2f1293b5c..fe4e99a3d 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -1,5 +1,12 @@
import type { ChatPromptBlocked, ChatPromptResult, EmptyPromptResult, TextDeliveryResult } from '../shared/text-delivery'
-import { claudeScreenBlocksInput, readClaudeComposer, readClaudeDraft, readClaudeScreen } from '../shared/agents/claude-screen'
+import {
+ claudeScreenBlocksInput,
+ readClaudeComposer,
+ readClaudeDraft,
+ readClaudeScreen,
+ readClaudeSuggestion,
+ type ChatScreenRead
+} from '../shared/agents/claude-screen'
import os from 'os'
import fs from 'fs'
import path from 'path'
@@ -2283,6 +2290,10 @@ export class PtyManager {
// Like `agentId` above: it only picks the composer reader, and a non-string picks none.
this.sendToEmptyPrompt(persistKey, text, typeof agentId === 'string' ? agentId : '')
)
+ platform().handle(IPC.ptyReadChatScreen, (persistKey: string, agentId: unknown) =>
+ // Like the chat-prompt handler: `agentId` only picks the screen reader, and a non-string picks none.
+ this.readChatScreen(persistKey, typeof agentId === 'string' ? agentId : '')
+ )
platform().handle(IPC.ptyTmuxStatus, () => this.tmuxStatus())
platform().handle(IPC.ptyPaneCommand, (persistKey: string, opts?: { resolveUnmounted?: boolean }) =>
this.paneCommand(persistKey, opts?.resolveUnmounted === true ? { resolveUnmounted: true } : undefined)
@@ -6827,6 +6838,19 @@ export class PtyManager {
})
}
+ /**
+ * One read of the pane for the ⌘M chat view's screen poll: the dialog check the poll always made,
+ * plus the prompt the agent suggests next. A STYLED capture, because only the styling tells
+ * Claude's dim suggestion from typed text (`readClaudeSuggestion`). Where no styled capture exists
+ * (a native Windows pane), the plain capture still answers the dialog check, with no suggestion.
+ */
+ async readChatScreen(persistKey: string, agentId: string): Promise<ChatScreenRead> {
+ if (!readsScreenDialogs(agentId)) return { screen: { kind: 'unknown' }, suggestion: null }
+ const styled = await this.captureStyledScreen(persistKey)
+ if (styled === '') return { screen: readClaudeScreen(await this.captureSession(persistKey)), suggestion: null }
+ return { screen: readClaudeScreen(styled), suggestion: readClaudeSuggestion(styled) }
+ }
+
/** The visible screen WITH its SGR, for `readClaudeComposer`: an ssh-project node's capture already
* carries `-e` (`remoteCapturePaneArgs`), everything else is `captureSnapshot`. '' on any failure. */
private async captureStyledScreen(persistKey: string): Promise<string> {
diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.ts
index 61c18acd3..55f8f9d43 100644
--- a/src/core/relay/access-policy.ts
+++ b/src/core/relay/access-policy.ts
@@ -344,6 +344,8 @@ export const EDITOR_ONLY: ReadonlySet<string> = new Set<string>([
IPC.ptySendText,
IPC.ptySendChatPrompt,
IPC.ptySendToEmptyPrompt,
+ // The composer's screen poll; only an editor has a composer.
+ IPC.ptyReadChatScreen,
IPC.ptyPaneOwner,
// A host filesystem path, not a view of the terminal — a viewer's file links keep the node cwd.
IPC.ptyPaneCwd,
diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.ts
index d79cea959..ac3147e36 100644
--- a/src/core/relay/scoped-guest-policy.ts
+++ b/src/core/relay/scoped-guest-policy.ts
@@ -389,6 +389,7 @@ export const SCOPED: Readonly<Record<string, Check>> = Object.freeze({
[IPC.ptySendText]: nodeArg0,
[IPC.ptySendChatPrompt]: nodeArg0,
[IPC.ptySendToEmptyPrompt]: nodeArg0,
+ [IPC.ptyReadChatScreen]: nodeArg0,
[IPC.ptyTmuxStatus]: pass,
[IPC.ptyPaneCommand]: nodeArg0,
[IPC.ptyPaneCwd]: nodeArg0,
diff --git a/src/preload/index.ts b/src/preload/index.ts
index be706b38f..30f36c601 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -115,6 +115,7 @@ const api: NodeTerminalApi = {
ipcRenderer.invoke(IPC.ptySendChatPrompt, persistKey, text, agentId),
sendToEmptyPrompt: (persistKey, text, agentId) =>
ipcRenderer.invoke(IPC.ptySendToEmptyPrompt, persistKey, text, agentId),
+ readChatScreen: (persistKey, agentId) => ipcRenderer.invoke(IPC.ptyReadChatScreen, persistKey, agentId),
tmuxStatus: () => ipcRenderer.invoke(IPC.ptyTmuxStatus),
paneCommand: (persistKey, opts) => ipcRenderer.invoke(IPC.ptyPaneCommand, persistKey, opts),
paneCwd: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCwd, persistKey),
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index a90941bd4..344d1a31e 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -29,6 +29,7 @@ import {
} from '../../shared/rpc'
import { IPC } from '../../shared/ipc'
import type { ChatPromptResult, EmptyPromptResult } from '../../shared/text-delivery'
+import type { ChatScreenRead } from '../../shared/agents/claude-screen'
import type { GitHubControlApi, GitHubIssuesApi } from '../../shared/github-issues'
import {
UNKNOWN_CLAUDE_CLI_CAPS,
@@ -303,6 +304,11 @@ export function buildRealApi(
client.request(IPC.ptySendChatPrompt, persistKey, text, agentId) as Promise<ChatPromptResult>,
sendToEmptyPrompt: (persistKey, text, agentId) =>
client.request(IPC.ptySendToEmptyPrompt, persistKey, text, agentId) as Promise<EmptyPromptResult>,
+ // Real: core registers it. A failed read is "could not tell", never a dialog.
+ readChatScreen: (persistKey, agentId) =>
+ client
+ .request(IPC.ptyReadChatScreen, persistKey, agentId)
+ .catch(() => ({ screen: { kind: 'unknown' }, suggestion: null })) as Promise<ChatScreenRead>,
// A failed read is unknown, never evidence that persistence is available.
tmuxStatus: () =>
client
diff --git a/src/renderer/lib/chatLive.ts b/src/renderer/lib/chatLive.ts
index 687bc9ea4..c4a67e6a3 100644
--- a/src/renderer/lib/chatLive.ts
+++ b/src/renderer/lib/chatLive.ts
@@ -50,6 +50,27 @@ export function turnEndReloadCarries(s: { final: boolean; working: boolean }): b
*/
export const CHAT_SCREEN_POLL_MS = 2000
+/**
+ * When Claude draws its suggested next prompt. MEASURED on Claude Code 2.1.318 (5 turns, Haiku, a
+ * sandboxed tmux server): 1.1-2.2 s after the turn ended; one more turn got none.
+ *
+ * Locally, the regular 2 s poll added up to 2 s on top, which read as a lag after the reply. So for
+ * a few seconds after a turn ends the panel reads faster, and stops at the first suggestion: about
+ * 15 more local screen reads per turn, at most.
+ */
+export const SUGGESTION_BURST_MS = 300
+export const SUGGESTION_BURST_WINDOW_MS = 5000
+
+/** Did this state change end a turn? Only then is a suggestion on its way (`SUGGESTION_BURST_MS`). */
+export function endsTurn(prev: string | undefined, next: string | undefined): boolean {
+ return next === 'done' && (prev === 'working' || prev === 'waiting' || prev === 'blocked')
+}
+
+/** When an SSH node's chat view reads the pane for the suggestion, counted from the turn's end. An
+ * SSH pane is never polled (each read is a round trip to the host), so it is read twice instead,
+ * after the measured window above and once more later. */
+export const REMOTE_SUGGESTION_READ_DELAYS_MS: readonly number[] = [2500, 6000]
+
/**
* Should the panel poll the pane's screen? Only for an agent whose screen we can read, only for a
* LOCAL pane (each read of an SSH or relay pane is a network round trip, every two seconds, for as
diff --git a/src/renderer/nodes/ChatComposer.tsx b/src/renderer/nodes/ChatComposer.tsx
index 0f80d7e57..6b625fe3b 100644
--- a/src/renderer/nodes/ChatComposer.tsx
+++ b/src/renderer/nodes/ChatComposer.tsx
@@ -46,6 +46,12 @@ export interface ChatComposerProps {
/** Enter (not Shift+Enter, not an IME commit). ChatPanel's send re-checks the gate itself. */
onSend: () => void
placeholder: string
+ /**
+ * The prompt the agent suggests next (`readClaudeSuggestion`), already shown as the placeholder by
+ * ChatPanel. With an empty draft, → fills the draft with it and puts the caret at the end, as →
+ * does in Claude Code's own TUI. It is never sent: Enter stays the user's.
+ */
+ suggestion?: string | null
/** Read-only session or a send-gate refusal: the whole composer stands down with the textarea.
* Not while the agent merely works — see `agentBusy`. */
disabled: boolean
@@ -93,6 +99,7 @@ export function ChatComposer({
onChange,
onSend,
placeholder,
+ suggestion = null,
disabled,
agentBusy = false,
onWriteRefused,
@@ -399,6 +406,24 @@ export function ChatComposer({
return
}
}
+ if (
+ e.key === 'ArrowRight' &&
+ !composing &&
+ !e.shiftKey && !e.altKey && !e.ctrlKey && !e.metaKey &&
+ value === '' &&
+ suggestion !== null &&
+ suggestion !== '' &&
+ !disabled
+ ) {
+ e.preventDefault()
+ onChange(suggestion)
+ requestAnimationFrame(() => {
+ const el = inputRef.current
+ if (!el) return
+ el.setSelectionRange(suggestion.length, suggestion.length)
+ })
+ 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({
diff --git a/src/renderer/nodes/ChatPanel.screenDialog.test.tsx b/src/renderer/nodes/ChatPanel.screenDialog.test.tsx
index 6831df374..91dd52c16 100644
--- a/src/renderer/nodes/ChatPanel.screenDialog.test.tsx
+++ b/src/renderer/nodes/ChatPanel.screenDialog.test.tsx
@@ -4,7 +4,12 @@ import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ChatPromptResult } from '@shared/text-delivery'
import { useAgentStatus } from '../state/agentStatus'
-import { CHAT_SCREEN_POLL_MS } from '../lib/chatLive'
+import {
+ CHAT_SCREEN_POLL_MS,
+ REMOTE_SUGGESTION_READ_DELAYS_MS,
+ SUGGESTION_BURST_MS,
+ SUGGESTION_BURST_WINDOW_MS
+} from '../lib/chatLive'
/**
* The agent's OWN dialogs (folder trust, /model, setup questions) fire no hook, so the chat view
@@ -23,13 +28,17 @@ const TRUST = [RULE, ' Accessing workspace:', ' ❯ No, exit', ' Yes, I trust
const { screen, capture, sendChatPrompt, session } = vi.hoisted(() => {
const screen = { now: '' }
- const capture = vi.fn(async (_id: string) => screen.now)
+ // The panel's one screen read (`pty.readChatScreen`), answered by the REAL readers over the screen.
+ const capture = vi.fn(async (_id: string, _agent: string) => {
+ const { readClaudeScreen, readClaudeSuggestion } = await import('@shared/agents/claude-screen')
+ return { screen: readClaudeScreen(screen.now), suggestion: readClaudeSuggestion(screen.now) }
+ })
const sendChatPrompt = vi.fn(async (_id: string, _t: string, _a: string): Promise<ChatPromptResult> => true)
const session = {
source: 'local',
api: {
chat: { readTranscript: async () => ({ messages: [], found: true, olderCursor: null, unmatchedResults: [] }) },
- pty: { capture, sendChatPrompt, sendText: vi.fn() }
+ pty: { readChatScreen: capture, sendChatPrompt, sendText: vi.fn() }
}
}
return { screen, capture, sendChatPrompt, session }
@@ -116,12 +125,12 @@ describe('ChatPanel — the agent\'s own dialog on screen', () => {
expect(notice()).toBeNull()
})
- it('never polls a remote pane', async () => {
+ it('never polls a remote pane: it reads it only twice after a turn, for the suggestion', async () => {
await mount({ remote: true })
- await tick()
- await tick()
- expect(capture).not.toHaveBeenCalled()
+ for (let i = 0; i < 20; i++) await tick()
+
+ expect(capture).toHaveBeenCalledTimes(REMOTE_SUGGESTION_READ_DELAYS_MS.length)
})
it('never polls a relay tab (the pane is on the peer)', async () => {
@@ -220,3 +229,128 @@ describe('ChatPanel — the agent\'s own dialog on screen', () => {
expect(textarea().disabled).toBe(true)
})
})
+
+describe('ChatPanel — the prompt Claude suggests next', () => {
+ const SUGGESTING = [RULE, `\x1b[39m❯ \x1b[2mrun it in the background\x1b[0m`, RULE, ' ? for shortcuts'].join('\n')
+ const TIP = [RULE, `\x1b[39m❯ \x1b[2mTry "fix lint errors"\x1b[0m`, RULE, ' ? for shortcuts'].join('\n')
+ const arrowRight = (): KeyboardEvent => {
+ const e = new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true, cancelable: true })
+ textarea().dispatchEvent(e)
+ return e
+ }
+
+ it('shows the suggestion as the placeholder, and → puts it in the composer with the caret at the end', async () => {
+ screen.now = SUGGESTING
+ await mount()
+ await tick()
+ expect(textarea().placeholder).toBe('run it in the background')
+
+ let e: KeyboardEvent | undefined
+ await act(async () => {
+ e = arrowRight()
+ })
+ await tick()
+
+ expect(e?.defaultPrevented).toBe(true)
+ expect(textarea().value).toBe('run it in the background')
+ expect(textarea().selectionStart).toBe('run it in the background'.length)
+ expect(sendChatPrompt).not.toHaveBeenCalled()
+ })
+
+ it('leaves → alone with a draft in the composer', async () => {
+ screen.now = SUGGESTING
+ await mount()
+ await tick()
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(textarea(), 'my own')
+ textarea().dispatchEvent(new Event('input', { bubbles: true }))
+ })
+
+ let e: KeyboardEvent | undefined
+ await act(async () => {
+ e = arrowRight()
+ })
+
+ expect(e?.defaultPrevented).toBe(false)
+ expect(textarea().value).toBe('my own')
+ })
+
+ it('does not offer a fresh-session tip', async () => {
+ screen.now = TIP
+ await mount()
+ await tick()
+
+ expect(textarea().placeholder).not.toContain('fix lint errors')
+ })
+
+ it('hides the suggestion while the agent works', async () => {
+ screen.now = SUGGESTING
+ await mount()
+ await tick()
+
+ await act(async () => {
+ useAgentStatus.setState((s) => ({ byId: { ...s.byId, [NODE]: { state: 'working' } as (typeof s.byId)[string] } }))
+ })
+
+ expect(textarea().placeholder).not.toBe('run it in the background')
+ })
+
+ const endTurn = async (): Promise<void> => {
+ await act(async () => {
+ useAgentStatus.setState((s) => ({ byId: { ...s.byId, [NODE]: { state: 'working' } as (typeof s.byId)[string] } }))
+ })
+ await act(async () => {
+ useAgentStatus.setState((s) => ({ byId: { ...s.byId, [NODE]: { state: 'done' } as (typeof s.byId)[string] } }))
+ })
+ }
+ const advance = async (ms: number): Promise<void> => {
+ await act(async () => {
+ vi.advanceTimersByTime(ms)
+ })
+ }
+
+ it('reads fast right after a turn ends, so the suggestion shows within one fast read', async () => {
+ await mount()
+ await endTurn()
+ screen.now = SUGGESTING
+
+ await advance(SUGGESTION_BURST_MS)
+
+ expect(textarea().placeholder).toBe('run it in the background')
+ })
+
+ it('goes back to the regular poll once the fast window is over', async () => {
+ await mount()
+ await endTurn()
+ await advance(SUGGESTION_BURST_WINDOW_MS + SUGGESTION_BURST_MS)
+ capture.mockClear()
+
+ for (let i = 0; i < 3; i++) await advance(CHAT_SCREEN_POLL_MS)
+
+ expect(capture).toHaveBeenCalledTimes(3)
+ })
+
+ it('stops reading fast at the first suggestion', async () => {
+ await mount()
+ await endTurn()
+ screen.now = SUGGESTING
+ await advance(SUGGESTION_BURST_MS)
+ capture.mockClear()
+
+ await advance(CHAT_SCREEN_POLL_MS - SUGGESTION_BURST_MS)
+
+ // Only the regular poll's tick, not a fast read every 300 ms.
+ expect(capture.mock.calls.length).toBeLessThanOrEqual(1)
+ })
+
+ it('drops the suggestion once a message is sent', async () => {
+ screen.now = SUGGESTING
+ await mount()
+ await tick()
+
+ await typeAndEnter('something else')
+
+ expect(sendChatPrompt).toHaveBeenCalled()
+ expect(textarea().placeholder).not.toBe('run it in the background')
+ })
+})
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index f3b9628bb..54c7d0898 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -1,5 +1,5 @@
import { TEXT_NOT_SUBMITTED, isChatPromptBlocked } from '@shared/text-delivery'
-import { claudeScreenBlocksInput, readClaudeScreen } from '@shared/agents/claude-screen'
+import { claudeScreenBlocksInput, type ChatScreenRead } from '@shared/agents/claude-screen'
import { Fragment, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react'
import { renderMarkdown } from '../lib/markdown'
import { useAgentStatus } from '../state/agentStatus'
@@ -37,6 +37,10 @@ import {
CHAT_LIVE_RELOAD_MIN_MS,
CHAT_OPTIMISTIC_WORKING_MS,
CHAT_SCREEN_POLL_MS,
+ REMOTE_SUGGESTION_READ_DELAYS_MS,
+ SUGGESTION_BURST_MS,
+ SUGGESTION_BURST_WINDOW_MS,
+ endsTurn,
TURN_END_RELOAD_DELAYS_MS,
chatActivity,
planLiveReload,
@@ -293,6 +297,14 @@ export function ChatPanel({
remote: sshProjectId !== undefined || source !== 'local',
refusal
})
+ // The prompt Claude suggests next (`readClaudeSuggestion`), from the latest screen read. Shown as
+ // the composer's placeholder only while a message could be sent and nothing else is on screen.
+ const [suggestion, setSuggestion] = useState<string | null>(null)
+ const shownSuggestion = !readonly && refusal === null && screenBlock === null ? suggestion : null
+ // An SSH node, read after each turn instead of polled (`REMOTE_SUGGESTION_READ_DELAYS_MS`). Not a
+ // relay tab: that pane is on the peer, and it has its own composer there.
+ const readsRemoteSuggestion =
+ readsScreenDialogs(agentId) && readOnly !== true && sshProjectId !== undefined && source === 'local'
const agentLabel = chatAgentLabel(agentId, customAgents)
// What the row closing the thread says (lib/chatLive.ts). `optimistic` covers the gap between a
// send and the first hook event: set by `send`, retired by the next state change (the real state
@@ -702,10 +714,69 @@ export function ChatPanel({
prevState.current = state
}, [state, load, nodeId])
- // Any state change retires the optimistic working row: from here the real state speaks.
+ // Any state change retires the optimistic working row: from here the real state speaks. And a
+ // suggestion belongs to the turn that ended: the next read brings the new one.
useEffect(() => {
setOptimistic(false)
+ setSuggestion(null)
}, [state])
+
+ // Right after a turn ends, read faster until Claude's suggestion is on screen (`SUGGESTION_BURST_MS`).
+ // Same gates as the regular poll, which keeps running beside it for dialogs.
+ const lastTurnStateRef = useRef(state)
+ useEffect(() => {
+ const prev = lastTurnStateRef.current
+ lastTurnStateRef.current = state
+ if (!pollScreen || !endsTurn(prev, state)) return
+ let cancelled = false
+ let inFlight = false
+ const until = Date.now() + SUGGESTION_BURST_WINDOW_MS
+ const t = setInterval(() => {
+ if (Date.now() > until) {
+ clearInterval(t)
+ return
+ }
+ const el = msgsRef.current
+ if (inFlight || el === null || el.clientHeight === 0) return
+ if (!screenPollTickAllowed({ hidden: document.hidden, focused: windowFocusHint(document) })) return
+ inFlight = true
+ void api.pty
+ .readChatScreen(nodeId, agentId)
+ .then((r) => {
+ if (cancelled || r.screen.kind === 'unknown' || r.suggestion === null) return
+ setSuggestion(r.suggestion)
+ clearInterval(t)
+ })
+ .catch(() => undefined)
+ .finally(() => {
+ inFlight = false
+ })
+ }, SUGGESTION_BURST_MS)
+ return () => {
+ cancelled = true
+ clearInterval(t)
+ }
+ }, [pollScreen, state, api, nodeId, agentId])
+
+ useEffect(() => {
+ if (!readsRemoteSuggestion || state !== 'done') return
+ let cancelled = false
+ const read = async (): Promise<void> => {
+ const el = msgsRef.current
+ if (el === null || el.clientHeight === 0 || document.hidden) return
+ try {
+ const r = await api.pty.readChatScreen(nodeId, agentId)
+ if (!cancelled && r.screen.kind !== 'unknown') setSuggestion(r.suggestion)
+ } catch {
+ // A failed read offers nothing; the next turn reads again.
+ }
+ }
+ const timers = REMOTE_SUGGESTION_READ_DELAYS_MS.map((ms) => setTimeout(() => void read(), ms))
+ return () => {
+ cancelled = true
+ for (const t of timers) clearTimeout(t)
+ }
+ }, [readsRemoteSuggestion, state, api, nodeId, agentId])
useEffect(() => {
if (!optimistic) return
const t = setTimeout(() => setOptimistic(false), CHAT_OPTIMISTIC_WORKING_MS)
@@ -729,18 +800,20 @@ export function ChatPanel({
const el = msgsRef.current
if (el === null || el.clientHeight === 0 || inFlight) return
if (!screenPollTickAllowed({ hidden: document.hidden, focused: windowFocusHint(document) })) return
- let screen: string
+ let result: ChatScreenRead
inFlight = true
try {
- screen = await api.pty.capture(nodeId)
+ // One styled read answers both: who owns the keyboard, and the prompt Claude suggests next.
+ result = await api.pty.readChatScreen(nodeId, agentId)
} catch {
return
} finally {
inFlight = false
}
if (cancelled) return
- const read = readClaudeScreen(screen)
+ const read = result.screen
if (read.kind === 'unknown') return
+ setSuggestion(result.suggestion)
if (!claudeScreenBlocksInput(read)) setScreenBlock(null)
else if (read.kind === 'dialog') setScreenBlock({ kind: 'dialog', text: read.text, live: true })
else setScreenBlock({ kind: 'no-prompt', text: null, live: true })
@@ -756,7 +829,7 @@ export function ChatPanel({
window.removeEventListener('focus', onReturn)
document.removeEventListener('visibilitychange', onReturn)
}
- }, [pollScreen, api, nodeId])
+ }, [pollScreen, api, nodeId, agentId])
// Follow the newest message only when the user was already at the bottom or just sent; a user
// scrolled up reading an earlier answer keeps their place. Layout effect: the jump lands before
@@ -899,6 +972,7 @@ export function ChatPanel({
// Optimistic: show the prompt immediately. A live read keeps it until the transcript carries it
// (`carryUnconfirmed`); the turn-end reload / ↻ reconcile from the transcript outright.
setScreenBlock(null)
+ setSuggestion(null)
justSentRef.current = true
const sent: ChatMessage = { role: 'user', parts: [{ kind: 'text', text }] }
if (mode === 'queue') queuedRef.current.add(sent)
@@ -1251,15 +1325,19 @@ export function ChatPanel({
value={input}
onChange={setInput}
onSend={() => void send()}
- placeholder={chatComposerPlaceholder({
- readonly,
- refusal,
- agentLabel,
- chip: mdChip,
- answerOnCard: answerCard !== null,
- sendMode,
- screen: screenBlock?.live === true ? screenBlock.kind : null
- })}
+ placeholder={
+ shownSuggestion ??
+ chatComposerPlaceholder({
+ readonly,
+ refusal,
+ agentLabel,
+ chip: mdChip,
+ answerOnCard: answerCard !== null,
+ sendMode,
+ screen: screenBlock?.live === true ? screenBlock.kind : null
+ })
+ }
+ suggestion={shownSuggestion}
// A dialog the POLL found is also cleared by it; one a refused send found is not (a remote
// pane is never polled), so that one leaves the draft editable for the resend.
disabled={readonly || composerStandsDown(refusal) || screenBlock?.live === true}
diff --git a/src/shared/agents/claude-screen.suggestion.test.ts b/src/shared/agents/claude-screen.suggestion.test.ts
new file mode 100644
index 000000000..2cd7fce3a
--- /dev/null
+++ b/src/shared/agents/claude-screen.suggestion.test.ts
@@ -0,0 +1,59 @@
+// The prompt Claude Code suggests after a turn (`readClaudeSuggestion`). The screen shapes are the
+// ones MEASURED on Claude Code 2.1.318 in a sandboxed tmux server: a suggestion is plain dim text on
+// the prompt line; a fresh-session tip and the queued-message hint are dim there too and are not
+// suggestions.
+import { describe, expect, it } from 'vitest'
+import { readClaudeSuggestion } from './claude-screen'
+
+const RULE = '─'.repeat(80)
+const DIM = '\x1b[2m'
+const RESET = '\x1b[0m'
+const screen = (promptLine: string, below: string[] = []): string =>
+ [RULE, promptLine, ...below, RULE, ' 🧠 Haiku 5.5 | 6%', ' ⏵⏵ auto mode on (shift+tab to cycle)'].join('\n')
+
+describe('readClaudeSuggestion', () => {
+ it('reads the dim suggestion on the prompt line', () => {
+ const s = screen(`\x1b[39m❯ ${DIM}run it in the background${RESET}`)
+
+ const result = readClaudeSuggestion(s)
+
+ expect(result).toBe('run it in the background')
+ })
+
+ it('offers nothing for a fresh-session tip', () => {
+ const s = screen(`\x1b[39m❯ ${DIM}Try "create a util logging.py that..."${RESET}`)
+
+ expect(readClaudeSuggestion(s)).toBeNull()
+ })
+
+ it('offers nothing for the queued-message hint', () => {
+ const s = screen(`\x1b[38;5;246m❯ ${DIM}\x1b[39mPress up to edit queued messages${RESET}`)
+
+ expect(readClaudeSuggestion(s)).toBeNull()
+ })
+
+ it('offers nothing when the box holds a draft', () => {
+ expect(readClaudeSuggestion(screen('\x1b[39m❯ draft text here'))).toBeNull()
+ expect(readClaudeSuggestion(screen(`\x1b[39m❯ ${DIM}line one${RESET}`, [' line two']))).toBeNull()
+ })
+
+ it('offers nothing for an empty box', () => {
+ expect(readClaudeSuggestion(screen('\x1b[39m❯ '))).toBeNull()
+ })
+
+ it('offers nothing when a dialog owns the screen', () => {
+ const trust = [RULE, ' Accessing workspace:', ' ❯ No, exit', ' Yes, I trust this folder', ' Enter to confirm · Esc to cancel'].join(
+ '\n'
+ )
+
+ expect(readClaudeSuggestion(trust)).toBeNull()
+ })
+
+ it('offers nothing from a capture that lost its styling (the text could be a draft)', () => {
+ expect(readClaudeSuggestion(screen('❯ run it in the background'))).toBeNull()
+ })
+
+ it('offers nothing from an empty capture', () => {
+ expect(readClaudeSuggestion('')).toBeNull()
+ })
+})
diff --git a/src/shared/agents/claude-screen.ts b/src/shared/agents/claude-screen.ts
index 555a69f66..cbb87102d 100644
--- a/src/shared/agents/claude-screen.ts
+++ b/src/shared/agents/claude-screen.ts
@@ -103,6 +103,13 @@ export function readClaudeScreen(screen: string): ClaudeScreen {
return box ? { kind: 'prompt' } : { kind: 'no-prompt' }
}
+/** What the ⌘M chat view's screen poll learns from one read of the pane (`pty.readChatScreen`): who
+ * owns the keyboard, and the suggested next prompt, if any. */
+export interface ChatScreenRead {
+ screen: ClaudeScreen
+ suggestion: string | null
+}
+
/** Refuse to type: anything but a visible input box, except a screen we could not read at all. */
export function claudeScreenBlocksInput(s: ClaudeScreen): boolean {
return s.kind === 'dialog' || s.kind === 'no-prompt'
@@ -224,3 +231,33 @@ export function readClaudeDraft(styledScreen: string): string | null {
}
return draft.replace(/\s/g, '')
}
+
+/**
+ * The next prompt Claude Code suggests after a turn, read from a STYLED capture: the dim text on its
+ * prompt line while the input box holds no draft. null when there is none to offer.
+ *
+ * MEASURED on Claude Code 2.1.318: a few seconds after a turn ends, and only when there is an
+ * obvious next step, Claude draws a suggestion as plain dim text (`❯ run it in the background`);
+ * pressing → in its TUI accepts it. Two other dim texts sit in the same place and are NOT
+ * suggestions: the fresh-session tips, always `Try "…"`, and `Press up to edit queued messages`
+ * while a turn runs with a message queued. Both are refused here.
+ *
+ * Only dim text counts, so a capture that lost its SGR reads as a draft (`readClaudeComposer`) and
+ * offers nothing.
+ */
+export function readClaudeSuggestion(styledScreen: string): string | null {
+ const styled = styledScreen.split(/\r?\n/)
+ const lines = styled.map((l) => l.replace(ANSI, '').trimEnd())
+ if (lines.every((l) => l === '')) return null
+ if (readClaudeScreen(styledScreen).kind !== 'prompt') return null
+ // `empty`: a `❯` prompt line holding only dim text, and nothing on the lines under it.
+ if (readClaudeComposer(styledScreen) !== 'empty') return null
+ const box = inputBox(lines)
+ if (!box) return null
+ const suggestion = lines[box[0] + 1].slice(1).trim()
+ if (suggestion === '' || NOT_SUGGESTIONS.some((re) => re.test(suggestion))) return null
+ return suggestion
+}
+
+/** Dim texts on the prompt line that Claude Code draws but does not suggest (see above). */
+const NOT_SUGGESTIONS: readonly RegExp[] = [/^Try "/, /^Press up to edit queued messages$/]
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index e0828a3e2..b28e2f5f8 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -30,6 +30,7 @@ export const IPC = {
ptySendText: 'pty:send-text',
ptySendChatPrompt: 'pty:send-chat-prompt',
ptySendToEmptyPrompt: 'pty:send-to-empty-prompt',
+ ptyReadChatScreen: 'pty:read-chat-screen',
ptyTmuxStatus: 'pty:tmux-status',
/** The foreground command of a node's tmux pane (`#{pane_current_command}`) — how the in-place
* agent restart sees that the CLI has exited and a shell owns the pane again. */
diff --git a/src/shared/types.ts b/src/shared/types.ts
index f74f15a02..23ffbe77a 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1,4 +1,5 @@
import type { ChatPromptResult, EmptyPromptResult, TextDeliveryResult } from './text-delivery'
+import type { ChatScreenRead } from './agents/claude-screen'
import type { PushWebhookMinted, PushWebhookResult, PushWebhookTokenInfo } from './push-webhook'
import type { IdentitySeedEntry } from './agent-identity-seed'
import type { AgentStatusSnapshotEntry } from './agent-status-snapshot'
@@ -1423,6 +1424,10 @@ export interface PtyApi {
* (issue #1144 — the app's own link notes). Refused, with the reason, before anything is written
* when the composer holds a draft, a dialog owns the keyboard, or emptiness cannot be proven. */
sendToEmptyPrompt(persistKey: string, text: string, agentId: string): Promise<EmptyPromptResult>
+ /** One read of an agent's screen for the ⌘M chat view's poll: who owns the keyboard, and the
+ * prompt the agent suggests next (claude: `readClaudeSuggestion`). An agent with no measured
+ * reader, or a pane that could not be read, answers `{ screen: { kind: 'unknown' }, suggestion: null }`. */
+ readChatScreen(persistKey: string, agentId: string): Promise<ChatScreenRead>
/** Is tmux available on this host (else the silent plain-shell fallback), plus a suggested
* install command for the "tmux not found" banner. */
tmuxStatus(): Promise<TmuxStatus>