Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions dashboard/e2e/thread.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
});
67 changes: 62 additions & 5 deletions dashboard/src/components/assistant-ui/elements/thread.aui.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import {
type ImageMessagePartComponent,
type ToolCallMessagePartComponent,
unstable_useComposerInputHistory,
useAui,
useAuiEvent,
useAuiState,
} from "@assistant-ui/react";
Expand All @@ -70,6 +71,9 @@ import {
useState,
type ComponentType,
type FC,
type KeyboardEvent,
type MouseEvent,
type PointerEvent,
type PropsWithChildren,
type ReactNode,
} from "react";
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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<ThreadProps> = ({
components = EMPTY_COMPONENTS,
autoFocus = true,
aboveComposer,
aboveMessages,
promptSuggestion,
}) => {
const isEmpty = useAuiState(isNewChatView);

Expand All @@ -196,6 +207,7 @@ export const Thread: FC<ThreadProps> = ({
autoFocus={autoFocus}
aboveComposer={aboveComposer}
aboveMessages={aboveMessages}
promptSuggestion={promptSuggestion ?? null}
/>
</ThreadComponentsContext.Provider>
);
Expand All @@ -208,6 +220,7 @@ export const Thread: FC<ThreadProps> = ({
* @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. */
Expand All @@ -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.
Expand Down Expand Up @@ -289,7 +304,7 @@ const ThreadRoot: FC<{
<ThreadFollowupSuggestions />
{/* Boxes edit: the last thing read before typing. */}
{aboveComposer}
<Composer autoFocus={autoFocus} />
<Composer autoFocus={autoFocus} suggestion={promptSuggestion} />
<AuiIf condition={(s) => isNewChatView(s) && s.composer.isEmpty}>
<ThreadSuggestions />
</AuiIf>
Expand Down Expand Up @@ -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<HTMLTextAreaElement>(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<HTMLTextAreaElement>) => {
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<number | undefined>(undefined);
const pressTook = useRef(false);
const onPointerDown = (e: PointerEvent<HTMLTextAreaElement>) => {
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<HTMLTextAreaElement>) => {
if (pressTook.current) e.preventDefault();
};

// Boxes edit: keeps the caret in the composer after a send, so the next
// prompt needs no tap.
Expand All @@ -486,7 +539,7 @@ const Composer: FC<{
<ComposerAttachments />
<ComposerPrimitive.Input
ref={inputRef}
placeholder="Send a message..."
placeholder={suggestion ?? "Send a message..."}
className="aui-composer-input caret-primary placeholder:text-muted-foreground/60 max-h-48 min-h-10 w-full resize-none bg-transparent px-2.5 py-1 text-base leading-6 outline-none"
rows={1}
autoFocus={autoFocus}
Expand All @@ -496,7 +549,11 @@ const Composer: FC<{
submitMode="ctrlEnter"
enterKeyHint="enter"
aria-label="Message input"
onKeyDown={history.onKeyDown}
onKeyDown={onKeyDown}
onPointerDown={onPointerDown}
onPointerUp={endPress}
onPointerCancel={endPress}
onContextMenu={onContextMenu}
/>
<ComposerAction />
</div>
Expand Down
1 change: 1 addition & 0 deletions dashboard/src/stores/thread/acp-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> | null }
// Forward compatibility, because an adapter can send a kind that is newer than this build.
| { sessionUpdate: string; [key: string]: unknown };

Expand Down
12 changes: 12 additions & 0 deletions dashboard/src/stores/thread/thread-store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
12 changes: 10 additions & 2 deletions dashboard/src/stores/thread/thread-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
/**
Expand Down Expand Up @@ -94,6 +96,7 @@ export const INITIAL_SNAPSHOT: ThreadSnapshot = {
configOptions: [],
plan: null,
commands: [],
promptSuggestion: null,
error: null,
loading: true,
truncated: false,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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,
Expand Down
43 changes: 43 additions & 0 deletions dashboard/src/stores/thread/translate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
Loading