diff --git a/dashboard/e2e/thread.test.ts b/dashboard/e2e/thread.test.ts index a506d06..28db211 100644 --- a/dashboard/e2e/thread.test.ts +++ b/dashboard/e2e/thread.test.ts @@ -944,3 +944,58 @@ test('a sub agent is a closed card that shows its run when opened', async () => await close(); } }); + +test('the predicted next prompt fills the empty draft on Tab and on a long press, and the draft grows to show it', async () => { + /** A suggestion that needs more than one line on a phone. */ + const long = 'run the whole test suite again and then tell me which of the failing tests are new'; + await start({ + prompts: [ + { + match: () => true, + updates: [ + ...reply('Done.'), + { + sessionUpdate: 'session_info_update', + _meta: { promptSuggestions: { suggestions: [{ text: long }] } }, + } as ThreadUpdate, + ], + }, + ], + }); + + const { page, errors, close } = await openPage( + stub.url, + `/boxes/${BOX.id}/threads/${BOX.threadId}`, + ); + try { + await expect.poll(() => page.getByText('connected').isVisible()).toBe(true); + const input = page.getByLabel('Message input'); + const oneLine = (await input.boundingBox())!.height; + + await input.fill('fix the build'); + await input.press('Control+Enter'); + await expect.poll(() => input.getAttribute('placeholder')).toBe(long); + // The empty draft grows to show the whole suggestion. + await expect.poll(async () => (await input.boundingBox())!.height).toBeGreaterThan(oneLine); + await shoot(page, 'thread-prompt-suggestion'); + + await input.press('Tab'); + expect(await input.inputValue()).toBe(long); + expect(stub.gateway.prompts).toEqual(['fix the build']); + + // A short touch does nothing, a long one takes the suggestion. + await input.fill(''); + const touch = { pointerType: 'touch', isPrimary: true, pointerId: 7 }; + await input.dispatchEvent('pointerdown', touch); + await input.dispatchEvent('pointerup', touch); + await page.waitForTimeout(700); + expect(await input.inputValue()).toBe(''); + await input.dispatchEvent('pointerdown', touch); + await expect.poll(() => input.inputValue()).toBe(long); + await input.dispatchEvent('pointerup', touch); + + expect(errors).toEqual([]); + } finally { + await close(); + } +}); diff --git a/dashboard/src/components/assistant-ui/elements/thread.aui.tsx b/dashboard/src/components/assistant-ui/elements/thread.aui.tsx index 521884d..7b9911e 100644 --- a/dashboard/src/components/assistant-ui/elements/thread.aui.tsx +++ b/dashboard/src/components/assistant-ui/elements/thread.aui.tsx @@ -48,6 +48,7 @@ import { type ImageMessagePartComponent, type ToolCallMessagePartComponent, unstable_useComposerInputHistory, + useAui, useAuiEvent, useAuiState, } from "@assistant-ui/react"; @@ -70,6 +71,9 @@ import { useState, type ComponentType, type FC, + type KeyboardEvent, + type MouseEvent, + type PointerEvent, type PropsWithChildren, type ReactNode, } from "react"; @@ -116,6 +120,11 @@ export type ThreadProps = { * that loads the older messages of a cut thread. */ aboveMessages?: ReactNode | undefined; + /** + * Boxes edit: the prompt that the agent expects the user to send next. The + * composer offers it in an empty draft. + */ + promptSuggestion?: string | null | undefined; }; /** The overrides when the caller gives none. */ @@ -180,12 +189,14 @@ const ThreadHistorySkeleton: FC = () => ( * @param autoFocus True to focus the composer on mount. * @param aboveComposer Boxes edit: content shown directly above the composer. * @param aboveMessages Boxes edit: content shown above the first message. + * @param promptSuggestion Boxes edit: the prompt that the agent expects next. */ export const Thread: FC = ({ components = EMPTY_COMPONENTS, autoFocus = true, aboveComposer, aboveMessages, + promptSuggestion, }) => { const isEmpty = useAuiState(isNewChatView); @@ -196,6 +207,7 @@ export const Thread: FC = ({ autoFocus={autoFocus} aboveComposer={aboveComposer} aboveMessages={aboveMessages} + promptSuggestion={promptSuggestion ?? null} /> ); @@ -208,6 +220,7 @@ export const Thread: FC = ({ * @param autoFocus True to focus the composer on mount. * @param aboveComposer Content shown directly above the composer. * @param aboveMessages Content shown above the first message. + * @param promptSuggestion The prompt that the agent expects next, or null. */ const ThreadRoot: FC<{ /** True while the thread shows as a new chat. */ @@ -218,7 +231,9 @@ const ThreadRoot: FC<{ aboveComposer?: ReactNode | undefined; /** Content shown above the first message. */ aboveMessages?: ReactNode | undefined; -}> = ({ isEmpty, autoFocus, aboveComposer, aboveMessages }) => { + /** The prompt that the agent expects next, or null. */ + promptSuggestion: string | null; +}> = ({ isEmpty, autoFocus, aboveComposer, aboveMessages, promptSuggestion }) => { const { Welcome = ThreadWelcome } = useContext(ThreadComponentsContext); // Boxes edit: keeps the newest output in view once a turn outgrows the // screen. The turn anchor alone holds the prompt at the top and follows nothing. @@ -289,7 +304,7 @@ const ThreadRoot: FC<{ {/* Boxes edit: the last thing read before typing. */} {aboveComposer} - + isNewChatView(s) && s.composer.isEmpty}> @@ -449,19 +464,57 @@ const ThreadSuggestionItem: FC = () => { ); }; +/** Boxes edit: how long a touch must stay down, in milliseconds, to take the suggestion. */ +const LONG_PRESS_MS = 500; + /** * The message composer, with attachments and the slash-command list. * * @param autoFocus True to focus the input on mount. + * @param suggestion The prompt that the agent expects next, or null. */ const Composer: FC<{ /** True to focus the input on mount. */ autoFocus: boolean; -}> = ({ autoFocus }) => { + /** Boxes edit: the prompt that the agent expects next, or null. */ + suggestion: string | null; +}> = ({ autoFocus, suggestion }) => { // Boxes edit: ArrowUp on an empty draft walks back through sent messages, // and ArrowDown returns to the draft. const history = unstable_useComposerInputHistory(); const inputRef = useRef(null); + const aui = useAui(); + + // Boxes edit: the agent's predicted next prompt shows as the placeholder of + // an empty draft, and Tab takes it into the draft without sending it. + const onKeyDown = (e: KeyboardEvent) => { + history.onKeyDown(e); + if (e.defaultPrevented || e.key !== "Tab" || !suggestion) return; + if (e.shiftKey || e.ctrlKey || e.metaKey || e.altKey || e.nativeEvent.isComposing) return; + if (e.currentTarget.value !== "") return; + e.preventDefault(); + aui.composer.setText(suggestion); + }; + + // Boxes edit: on touch, a long press on the empty draft takes the suggestion, + // because a phone has no Tab key. iOS sends no contextmenu event for a long + // press, so a timer measures the press. + const pressTimer = useRef(undefined); + const pressTook = useRef(false); + const onPointerDown = (e: PointerEvent) => { + pressTook.current = false; + if (e.pointerType !== "touch" || !suggestion || e.currentTarget.value !== "") return; + pressTimer.current = window.setTimeout(() => { + if (inputRef.current?.value !== "") return; + pressTook.current = true; + aui.composer.setText(suggestion); + }, LONG_PRESS_MS); + }; + const endPress = () => window.clearTimeout(pressTimer.current); + // Android opens its text menu after the same long press. + const onContextMenu = (e: MouseEvent) => { + if (pressTook.current) e.preventDefault(); + }; // Boxes edit: keeps the caret in the composer after a send, so the next // prompt needs no tap. @@ -486,7 +539,7 @@ const Composer: FC<{ diff --git a/dashboard/src/stores/thread/acp-types.ts b/dashboard/src/stores/thread/acp-types.ts index bd468be..443caf2 100644 --- a/dashboard/src/stores/thread/acp-types.ts +++ b/dashboard/src/stores/thread/acp-types.ts @@ -182,6 +182,7 @@ export type ThreadUpdate = | { sessionUpdate: typeof UPDATE_KIND.configOption; configOptions?: ThreadConfigOption[] } | (SubagentSpawned & { sessionUpdate: typeof UPDATE_KIND.subagentSpawned }) | (SubagentState & { sessionUpdate: typeof UPDATE_KIND.subagentState }) + | { sessionUpdate: typeof UPDATE_KIND.sessionInfo; _meta?: Record | null } // Forward compatibility, because an adapter can send a kind that is newer than this build. | { sessionUpdate: string; [key: string]: unknown }; diff --git a/dashboard/src/stores/thread/thread-store.test.ts b/dashboard/src/stores/thread/thread-store.test.ts index c91aee7..f5ad61e 100644 --- a/dashboard/src/stores/thread/thread-store.test.ts +++ b/dashboard/src/stores/thread/thread-store.test.ts @@ -1040,3 +1040,15 @@ test('a refused full history leaves the thread as it was', async () => { assert.equal(snapshot.loadingHistory, false); assert.equal(snapshot.error, 'The agent is working on this thread.'); }); + +test('the store publishes the predicted next prompt and a send clears it', async () => { + const { store, client } = makeStore(); + push(client, { + sessionUpdate: 'session_info_update', + _meta: { promptSuggestions: { suggestions: [{ text: 'run the tests' }] } }, + } as ThreadUpdate); + assert.equal(store.getSnapshot().promptSuggestion, 'run the tests'); + + await store.send([{ type: 'text', text: 'deploy it' }]); + assert.equal(store.getSnapshot().promptSuggestion, null); +}); diff --git a/dashboard/src/stores/thread/thread-store.ts b/dashboard/src/stores/thread/thread-store.ts index 1409f81..d7fabf5 100644 --- a/dashboard/src/stores/thread/thread-store.ts +++ b/dashboard/src/stores/thread/thread-store.ts @@ -61,6 +61,8 @@ export interface ThreadSnapshot { plan: PlanEntry[] | null; /** The slash commands the adapter accepts, for the composer to complete. */ commands: AvailableCommand[]; + /** The prompt that the agent expects the user to send next, or null. */ + promptSuggestion: string | null; /** The last send or connection error, or null. */ error: string | null; /** @@ -94,6 +96,7 @@ export const INITIAL_SNAPSHOT: ThreadSnapshot = { configOptions: [], plan: null, commands: [], + promptSuggestion: null, error: null, loading: true, truncated: false, @@ -413,6 +416,7 @@ export class ThreadStore { messages: this.messageViews(null), plan: this.model.plan, commands: this.model.commands, + promptSuggestion: this.model.promptSuggestion, loading: false, truncated: this.truncated, rebuilds: this.rebuilds, @@ -463,13 +467,15 @@ export class ThreadStore { this.snapshot.modes !== this.model.modes || this.snapshot.configOptions !== this.model.configOptions || this.snapshot.plan !== this.model.plan || - this.snapshot.commands !== this.model.commands + this.snapshot.commands !== this.model.commands || + this.snapshot.promptSuggestion !== this.model.promptSuggestion ) { this.emit({ modes: this.model.modes, configOptions: this.model.configOptions, plan: this.model.plan, commands: this.model.commands, + promptSuggestion: this.model.promptSuggestion, }); } this.refreshMessages(touched); @@ -558,7 +564,9 @@ export class ThreadStore { if (!sessionId) throw new Error('no ACP thread yet'); if (blocks.length === 0) return; - this.emit({ error: null }); + // The prompt answers the suggestion, so the composer stops showing it. + this.model.promptSuggestion = null; + this.emit({ error: null, promptSuggestion: null }); try { await client.request(ACP_METHOD.sessionPrompt, { sessionId, diff --git a/dashboard/src/stores/thread/translate.test.ts b/dashboard/src/stores/thread/translate.test.ts index d978e48..4c8880f 100644 --- a/dashboard/src/stores/thread/translate.test.ts +++ b/dashboard/src/stores/thread/translate.test.ts @@ -694,3 +694,46 @@ test('a raw text result stands in when the content gives no text', () => { ); assert.equal(toolOutputText(findTool(model, 'read-1')!), 'alpha\nbeta\n'); }); + +/** + * Builds a session_info_update that carries a predicted next prompt. + * + * @param texts The texts of the suggestions. + * @returns The update. + */ +function suggest(...texts: string[]): ThreadUpdate { + return { + sessionUpdate: 'session_info_update', + _meta: { promptSuggestions: { suggestions: texts.map((text) => ({ text })) } }, + } as ThreadUpdate; +} + +test('a session info update sets the predicted next prompt', () => { + const model = fold(chunk('agent_message_chunk', 'Done.'), suggest(' ', 'run the tests ')); + assert.equal(model.promptSuggestion, 'run the tests'); + assert.equal(model.unknown.size, 0); +}); + +test('an empty suggestion list clears the predicted prompt', () => { + assert.equal(fold(suggest('run the tests'), suggest()).promptSuggestion, null); +}); + +test('a session info update without a suggestion keeps the predicted prompt', () => { + const model = fold(suggest('run the tests'), { + sessionUpdate: 'session_info_update', + title: 'A title', + } as ThreadUpdate); + assert.equal(model.promptSuggestion, 'run the tests'); +}); + +test('a user message clears the predicted prompt', () => { + const model = fold(suggest('run the tests'), chunk('user_message_chunk', 'deploy it')); + assert.equal(model.promptSuggestion, null); +}); + +test('the updates of a sub agent neither set nor clear the predicted prompt', () => { + const model = fold(spawned('child-1'), suggest('run the tests')); + applyUpdate(model, chunk('user_message_chunk', 'a task notification'), 'child-1'); + applyUpdate(model, suggest('something else'), 'child-1'); + assert.equal(model.promptSuggestion, 'run the tests'); +}); diff --git a/dashboard/src/stores/thread/translate.ts b/dashboard/src/stores/thread/translate.ts index e623f0a..5015f6c 100644 --- a/dashboard/src/stores/thread/translate.ts +++ b/dashboard/src/stores/thread/translate.ts @@ -179,6 +179,8 @@ export interface ThreadModel { plan: PlanEntry[] | null; /** The slash commands the adapter accepts, for the composer to complete. */ commands: AvailableCommand[]; + /** The prompt that the agent expects the user to send next, or null. */ + promptSuggestion: string | null; /** * Kinds of update this build does not know, by name. * @@ -209,6 +211,7 @@ export function emptyModel(): ThreadModel { configOptions: [], plan: null, commands: [], + promptSuggestion: null, unknown: new Set(), tools: new Map(), subagents: new Map(), @@ -425,6 +428,9 @@ export function applyUpdate( switch (update.sessionUpdate) { case UPDATE_KIND.userMessageChunk: { const u = update as UpdateOf; + // The user has answered, so the suggestion for this answer is old. A sub agent's + // user message is no answer of the user. + if (!owner) model.promptSuggestion = null; const message = messageFor(messages, 'user', u.messageId); appendBlock(message, 'text', u.content); return owner ?? message; @@ -512,12 +518,44 @@ export function applyUpdate( if (model.modes) model.modes = { ...model.modes, currentModeId: u.currentModeId }; return null; } + case UPDATE_KIND.sessionInfo: { + // The suggestion is for the prompt of the user, which only the thread itself takes. + if (owner) return null; + const u = update as UpdateOf; + const suggestion = promptSuggestionOf(u._meta); + if (suggestion !== undefined) model.promptSuggestion = suggestion; + return null; + } default: model.unknown.add(update.sessionUpdate); return null; } } +/** The `_meta` key under which `claude-agent-acp` sends the predicted next prompt. */ +export const PROMPT_SUGGESTIONS_META_KEY = 'promptSuggestions'; + +/** + * Reads the predicted next prompt from the `_meta` of a session_info_update. + * + * The value is `{ suggestions: [{ text }] }`. An empty list clears the prediction. + * + * @param meta The `_meta` of the update. + * @returns The first text that is not blank, null when the update clears the prediction, or undefined when the + * update says nothing about it. + */ +function promptSuggestionOf( + meta: Record | null | undefined, +): string | null | undefined { + const value = meta?.[PROMPT_SUGGESTIONS_META_KEY] as { suggestions?: unknown } | undefined; + if (!value || !Array.isArray(value.suggestions)) return undefined; + for (const entry of value.suggestions) { + const text = (entry as { text?: unknown } | null)?.text; + if (typeof text === 'string' && text.trim()) return text.trim(); + } + return null; +} + /** * Folds a tool_call or a tool_call_update into the thread. The update merges * into its call, or starts a new card when the call does not exist yet. diff --git a/dashboard/src/views/BoxThread.tsx b/dashboard/src/views/BoxThread.tsx index 6b3b54a..74ea236 100644 --- a/dashboard/src/views/BoxThread.tsx +++ b/dashboard/src/views/BoxThread.tsx @@ -393,6 +393,8 @@ export function BoxThread() { ) : (