diff --git a/app/src/components/channels/chat-transcript.tsx b/app/src/components/channels/chat-transcript.tsx index 73d48f1f55..4daaebabdc 100644 --- a/app/src/components/channels/chat-transcript.tsx +++ b/app/src/components/channels/chat-transcript.tsx @@ -78,9 +78,10 @@ import { publishThreadWork, threadWorkOf, } from "@/components/tasks/thread-work"; -import { foldTurnWork } from "@/components/tasks/turn-work"; +import { foldTurnWork, type TurnWork } from "@/components/tasks/turn-work"; import { isTaskThread, + TurnLine, useWaitingToolCalls, WorkedFor, } from "@/components/tasks/worked-for"; @@ -202,14 +203,20 @@ import { } from "./telemetry-assistant-message"; import { ActivityAppMarks, + AppMark, + appOfCall, attachmentReadName, dropRepeatedAppCards, + FoldGrid, groupToolSteps, - LiveConnectorStep, + LineShowsApp, + onlyApp, + rowApps, ServerStepIcon, ToolActivity, type ToolGroup, type TranscriptItem, + useAppName, useDrawnTool, useReportsDesktopActivity, } from "./tool-activity"; @@ -1949,7 +1956,6 @@ const ToolCallBody = memo(function ToolCallBody({ result, latest, spokeAfter, - liveConnector, }: { toolCallId: string; name: string; @@ -1959,7 +1965,6 @@ const ToolCallBody = memo(function ToolCallBody({ latest: boolean; /** The Bot said something after this call in its turn. See `ToolPlace`. */ spokeAfter: boolean; - liveConnector?: boolean; }) { const renderToolCall = useRenderToolCall(); const toolCall = useMemo( @@ -2029,7 +2034,6 @@ const ToolCallBody = memo(function ToolCallBody({ ) : ( { @@ -2130,11 +2135,14 @@ const ToolRow = memo(function ToolRow({ inFlight, latest, spokeAfter, - conversation, expanded, + folds, workAlone, }: ToolRowProps) { const [only] = steps; + // Inside a conversation turn's line, whose rows keep one grid (`FoldGrid`). + const inTurnLine = useContext(FoldGrid) !== undefined; + const isDrawn = useDrawnTool(); useReportsDesktopActivity(steps, active); return ( @@ -2143,13 +2151,22 @@ const ToolRow = memo(function ToolRow({ only && !workAlone && !isBrowserStep(only) && + // Drawn open among a "Worked for" line's rows, a lone app call is a step as theirs are, not + // a muted line of its own beside them (`ToolActivity`). Inside a conversation turn's line, + // so is every lone call the app doesn't draw a card for: "Looked for a tool" drew its + // wrench where the steps drew chevrons. A command, an edit, keeps its own card. + !( + expanded && + folds && + ((inTurnLine && !isDrawn(only.toolCall.function.name)) || + appOfCall(only.toolCall.function.name)) + ) && // A subtask is drawn as work even alone, so a second call joining it does not change its shape. only.toolCall.function.name !== SUBAGENT_TOOL ? ( @@ -2182,7 +2198,6 @@ export function ServerToolLine({ args, result, place, - liveConnector, }: { name: string; /** What the call was given, as the model wrote it. Read only for what a step acted on. */ @@ -2190,7 +2205,6 @@ export function ServerToolLine({ result?: string; /** Where this call sits in the conversation, for an app card that may carry the task on. */ place?: CardPlace; - liveConnector?: boolean; }) { const running = result === undefined; // Cut off with its outcome unknown: named as it is while under way, since nobody knows it was done. @@ -2200,10 +2214,16 @@ export function ServerToolLine({ const appId = !role && name.startsWith("mcp__") ? name.split("__")[1] : undefined; const folders = useContext(FolderNamesContext); + const appName = useAppName(); + // On the one app the folded line above it shows (`LineShowsApp`), it doesn't draw its logo again. + const lineShows = useContext(LineShowsApp); // The file a file step read or saved, as a computer's own file steps name it; a step on a folder - // on the person's computer names the folder too ("todo.txt in share"). + // on the person's computer names the folder too ("todo.txt in share"). An app's step doesn't say + // its app's name: its logo does, and names it on hover (`AppMark`). const detail = - (appId && named.detail === appId ? connectorName(appId) : named.detail) ?? + (appId && (named.detail === appId || named.detail === connectorName(appId)) + ? undefined + : named.detail) ?? folderStepSubject(name, args, folders) ?? ownToolSubject(name, args) ?? // The attached file a read was of, by the name its answer carries. @@ -2262,12 +2282,6 @@ export function ServerToolLine({ ? readAnotherAccountPrompt(answer) : null; if (another) return ; - if (running && liveConnector && appId) - return ( -
- -
- ); /* * THAT TOOL'S OTHER ANSWERS ARE FOR THE MODEL. An app nobody can name comes back as plain text * telling the Bot to say so plainly and not to browse to it — an instruction, which read by the @@ -2334,7 +2348,15 @@ export function ServerToolLine({ {...(failed && ownToolFailedLabel(name) ? { failedLabel: ownToolFailedLabel(name) ?? undefined } : {})} - icon={} + {...(appId && appId === lineShows + ? {} + : { + icon: appId ? ( + + ) : ( + + ), + })} label={label} refused={refused} failed={failed} @@ -2671,6 +2693,21 @@ function TranscriptRenderersWatch({ ); } +/** + * How far a row of app steps is drawn up under one drawn like it, so the two sit as two steps of one + * list do, 8px apart: a "Worked for" line's rows are 12px apart, and an open list of steps keeps 4px + * above and below it, a call on a line of its own 6px. + */ +const JOINED = { list: "-mt-3", line: "-mt-4" } as const; + +/** + * Whether a row with an app's steps is drawn as an open list of them or as one call's line: in a + * "Worked for" line, a run of them is a list, a lone one in a run included (`ToolRow`). + */ +function stepsShape(item: TranscriptItem): "list" | "line" { + return item.kind === "tools" ? "list" : "line"; +} + export function ChatTranscript({ threadId, busy = false, @@ -2724,7 +2761,13 @@ export function ChatTranscript({ const waiting = useWaitingToolCalls(queryClient); const folds = taskThread ? foldTurnWork(items, busy, waiting) - : foldTurnWork(items, busy || Boolean(stopped), waiting, "conversation"); + : foldTurnWork( + items, + busy || Boolean(stopped), + waiting, + "conversation", + isDrawn.known, + ); // What the task read and made, for its Details pane beside the thread (`thread-work.ts`). useEffect(() => { if (taskThread && threadId) @@ -2854,6 +2897,12 @@ export function ChatTranscript({ * says it is still working then, so the live line comes back under them until the Bot carries on. */ const reconnectingNow = busy && reconnecting; + /* + * A conversation turn's line says "Thinking" (or "Reconnecting…") itself while nothing has been + * said after its last step, in its own place under the person's message: not a second time below. + */ + const lastLine = [...folds.under.values()].at(-1); + const lineSaysIt = lastLine?.running === true && !lastLine.answered; const viewportRef = useRef(null); const newestUserMessageId = @@ -3187,8 +3236,8 @@ export function ChatTranscript({ > = turnStart} latest={index >= latestIndex} @@ -3234,6 +3283,54 @@ export function ChatTranscript({ * inside that row. */ const rowGuard = readOnly ? READ_ONLY_ROW : LIVE_ROW; + /* The rows a turn's work holds, drawn inside its line as they would be on their own. */ + const foldedRows = (work: TurnWork) => ( + row.item))}> + {work.rows.map((row, at) => { + // App steps the Bot's words had split into rows of their own sit as one list: its + // words are drawn outside this line, and the gap they left says nothing in here. Only + // rows drawn alike: a call on a line of its own is a muted line, a list's steps aren't. + const above = work.rows[at - 1]; + const shape = stepsShape(row.item); + // Only in a task's "Worked for" line: a conversation turn's line keeps one gap throughout. + const joins = + taskThread && + above !== undefined && + stepsShape(above.item) === shape && + rowApps(above.item).last !== undefined && + rowApps(row.item).first !== undefined; + const drawn = rowContent(row.item, row.index, !taskThread); + // What the Bot said on the way is muted in here: it is not the answer. + const muted = row.item.kind === "text"; + return ( + + {joins ? ( +
{drawn}
+ ) : muted && !taskThread ? ( +
+ {drawn} +
+ ) : ( + drawn + )} +
+ ); + })} +
+ ); + /* A conversation turn's one line, drawn under the person's message from the moment they send. */ + const turnLine = (work: TurnWork, opening: string) => ( + + + {foldedRows(work)} + + + ); const renderRow = (item: TranscriptItem, index: number) => { const work = taskWork.folds.at.get(item.id); if (work) @@ -3249,15 +3346,24 @@ export function ChatTranscript({ threadId={taskThread ? threadId : undefined} work={work} > - {work.rows.map((row) => ( - - {rowContent(row.item, row.index, !taskThread)} - - ))} + {foldedRows(work)} ); if (taskWork.folds.inside.has(item.id)) return null; + /* + * The person's message, and under it their turn's line: one fragment for every row, so the + * line arriving with the send (or a moment after it) never redraws the message above it. + */ + const line = taskWork.folds.under.get(item.id); + return ( + + {ownRow(item, index)} + {line ? turnLine(line, line.rows[0]?.item.id ?? item.id) : null} + + ); + }; + const ownRow = (item: TranscriptItem, index: number) => { // A refused turn's notice, under the last row of the person's message it answered. const refusal = refusedUnder.get(item.id); /* @@ -3315,10 +3421,18 @@ export function ChatTranscript({ ); }; - const hasConnector = visible.some( - (item) => - item.kind === "tool" && item.toolCall.function.name.startsWith("mcp__"), - ); + /* + * The apps' names and logos, looked up once an app's step is in the conversation, and from the + * moment a turn starts: its line names the app it is using ("Using Google Calendar…") the instant + * the step starts. Looked up only then, the line read "Using Googlecalendar…" beside a letter for + * a beat, and then changed to the name and logo. + */ + const hasConnector = + busy || + visible.some( + (item) => + item.kind === "tool" && item.toolCall.function.name.startsWith("mcp__"), + ); return ( {hasActivities ? ( @@ -3436,7 +3550,8 @@ export function ChatTranscript({ reason={stopped} /> ) - ) : waitingOnTheModel || reconnectingNow ? ( + ) : (waitingOnTheModel || reconnectingNow) && + !lineSaysIt ? ( ) : null} {working} diff --git a/app/src/components/channels/subtask-step.tsx b/app/src/components/channels/subtask-step.tsx index d826b3b93d..0766d268d9 100644 --- a/app/src/components/channels/subtask-step.tsx +++ b/app/src/components/channels/subtask-step.tsx @@ -14,6 +14,7 @@ import { StepOutput, StepRow, stepDetails, + stepOpens, } from "./tool-activity"; type ToolItem = Extract; @@ -134,9 +135,14 @@ export function SubtaskStep({ {handedBack ? : null} {step.output ? : null} {steps.length ? ( -
    - {foldRereads(steps).map((inner) => ( - +
      + {foldRereads(steps).map((inner, _, rows) => ( + ))}
    ) : null} diff --git a/app/src/components/channels/tool-activity.tsx b/app/src/components/channels/tool-activity.tsx index 70caa04ad3..003ae309ae 100644 --- a/app/src/components/channels/tool-activity.tsx +++ b/app/src/components/channels/tool-activity.tsx @@ -50,7 +50,6 @@ import { IconFilePlus, IconFileText, IconFolder, - IconLoader2, IconPlug, IconSearch, IconSend, @@ -65,6 +64,11 @@ import { PluginLogo, } from "@/components/plugins/plugin-logo"; import { settingsToolCardFor } from "@/components/settings-tools/settings-tool-card"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui/tooltip"; import { useOverflows } from "@/hooks/use-overflows"; import { appsQueryOptions } from "@/lib/apps/queries"; import { readOutcome } from "@/lib/computers/activity"; @@ -286,7 +290,10 @@ const NOTHING_DRAWN: readonly { name: string }[] = []; * throws outside a provider and the transcript is drawn without one in places. With no provider * nothing is drawn. A `*` renderer draws every tool it is asked about, so nothing outside MCP folds. */ -export function useDrawnTool(): (name: string) => boolean { +export function useDrawnTool(): ((name: string) => boolean) & { + /** Any renderer is in: until then a card the app draws can't be told from a step it folds. */ + known: boolean; +} { const copilotkit = useContext(CopilotKitContext)?.copilotkit; const subscribe = useCallback( (onChange: () => void) => @@ -302,7 +309,10 @@ export function useDrawnTool(): (name: string) => boolean { ); return useMemo(() => { const names = new Set(renderers.map((renderer) => renderer.name)); - return names.has("*") ? () => true : (name) => names.has(name); + const drawn = names.has("*") + ? () => true + : (name: string) => names.has(name); + return Object.assign(drawn, { known: names.size > 0 }); }, [renderers]); } @@ -541,21 +551,37 @@ export function stepDetails(step: ToolItem): StepDetails { return detailsOf(step, new Map()); } +/** An app's name from its key: as it was added here (`useAppName`), or its key in words. */ +export type AppName = (appId: string) => string; + /** * `stepDetails`, naming a folder step's folder from the conversation's folder names. `live`: the * steps' turn is still going. Once it is over, a command with no answer was stopped under way. + * `appName`: an app step's app, by the name it was added under (`useAppName`). */ export function stepDetailsIn( folders: FolderNames, live = true, + appName: AppName = connectorName, ): (step: ToolItem) => StepDetails { - return (step) => detailsOf(step, folders, live); + return (step) => detailsOf(step, folders, live, appName); +} + +/** + * The words beside an app's action, with the app said by its name: `readToolName` names it from its + * key ("Googlecalendar"), which only the apps added here know as "Google Calendar". + */ +function appDetail(detail: string, appId: string, appName: AppName): string { + return detail === appId || detail === connectorName(appId) + ? appName(appId) + : detail; } function detailsOf( step: ToolItem, folders: FolderNames, live = true, + appName: AppName = connectorName, ): StepDetails { if (cutOffStep(step.result)) { // Read as the step it was while under way, then marked: what the Bot was told is not shown. @@ -565,7 +591,7 @@ function detailsOf( subtask: _subtask, terminal: _terminal, ...details - } = detailsOf(underWay, folders); + } = detailsOf(underWay, folders, true, appName); return { ...details, // A subtask's own row reads its result; a cut-off one has none, so it is an ordinary step. @@ -654,7 +680,8 @@ function detailsOf( if (name === READ_RESULT_PART) { // The app's own answer, read on: its step is the app's, as the app's read is ("Used Fireflies"). const app = appOfRead(args); - const detail = partRead(args, part); + // Its app is its logo (`AppMark`), as on every app step: "List events, part 2 of 3". + const detail = partRead(args, part, appName, false); return { ...outcome, label: readToolName(name, outcome.pending).label, @@ -663,7 +690,7 @@ function detailsOf( inputs: [], pages: 0, ...(app - ? { kind: "connector", connector: connectorName(app), appId: app } + ? { kind: "connector", connector: appName(app), appId: app } : { kind: "tool" }), }; } @@ -738,14 +765,14 @@ function detailsOf( pages: Math.max(urls.length, 1), }; } + // Words beside the action that were only the app's name go: the row's logo says it (`AppMark`). + const shown = detail ? appDetail(detail, server, appName) : undefined; return { ...base, kind: "connector", - ...(detail - ? { detail: detail === server ? connectorName(server) : detail } - : {}), + ...(shown && shown !== appName(server) ? { detail: shown } : {}), pages: 0, - connector: connectorName(server), + connector: appName(server), appId: server, }; } @@ -783,18 +810,27 @@ function appOfRead(args: Record): string | undefined { return prefix === "mcp" && server ? server : undefined; } -/** The words beside a `read_result_part` step: see `readOf`. */ +/** + * The words beside a `read_result_part` step: see `readOf`. `withApp` false leaves the app out, for a + * row whose logo says it: "Get transcript, part 2 of 3". + */ function partRead( args: Record, part: { part?: number; parts?: number } | undefined, + appName: AppName, + withApp = true, ): string | undefined { const whole = readOf(args); const read = whole ? readToolName(whole) : undefined; - const named = read - ? read.detail - ? `${read.label} on ${read.detail}` - : read.label + const app = appOfRead(args); + const said = read?.detail + ? app + ? appDetail(read.detail, app, appName) + : read.detail : undefined; + // `withApp` false: the app is left out where its logo already says it (`AppMark`). + const on = withApp || !app || said !== appName(app) ? said : undefined; + const named = read ? (on ? `${read.label} on ${on}` : read.label) : undefined; const number = part?.part ?? (typeof args.part === "number" @@ -1225,35 +1261,20 @@ const ActivityApps = createContext( undefined, ); -export function LiveConnectorStep({ - appId, - label, -}: { - appId: string; - label: string; -}) { +/** + * An app's name as it was added here ("Google Calendar"), read from the apps the transcript looked + * up for its icons (`ActivityAppMarks`), or its key in words until they are in. + * + * ONE NAME FOR AN APP ON EVERY ROW. An app's step was named from its key, so Google Calendar's + * finished steps read "Googlecalendar", while its step still running, drawn by a component of its + * own, read "Google Calendar". Every step now names its app here, running or done. + */ +export function useAppName(): AppName { const apps = useContext(ActivityApps); - const title = - apps?.find((app) => app.id === appId)?.title ?? connectorName(appId); - return ( - - - - {title} - - · - - {label} - - - In progress - + return useCallback( + (appId: string) => + apps?.find((app) => app.id === appId)?.title ?? connectorName(appId), + [apps], ); } @@ -1273,6 +1294,20 @@ export function ActivityAppMarks({ }, client ?? appQueryClient, ); + /* + * EVERY APP'S LOGO FETCHED ONCE THE LIST IS IN, before a step needs it. A turn's line shows the + * logo of the app it is using the moment the step starts ("Using Google Calendar…"), and a logo + * fetched only then left the mark's square empty for a beat beside the words. + */ + useEffect(() => { + if (typeof Image === "undefined") return; + for (const app of data ?? []) { + if (!app.logo) continue; + const image = new Image(); + image.referrerPolicy = "no-referrer"; + image.src = app.logo; + } + }, [data]); return {children}; } @@ -1283,30 +1318,73 @@ export function ActivityAppMarks({ * and a magnifying glass with its handle cut off reads as the letter C. */ function IconStack({ marks }: { marks: { kind: StepKind; appId?: string }[] }) { + const appName = useAppName(); const icons = Array.from( new Map(marks.map((mark) => [mark.appId ?? mark.kind, mark])).values(), ); + /* + * ONE MARK STYLE: A BARE 16PX ICON OR LOGO. A step on no app was drawn in a gray disc ("Looking + * for a tool"), while the app step after it drew its logo bare, so the same line changed shape + * between one step and the next. One mark is drawn bare, whatever it is; only marks stacked on + * each other sit on a ring of the page, so each is told from the one behind it. + */ if (icons.length === 1) { const [mark] = icons; - if (mark?.appId) return ; + if (mark?.appId) + return ; + if (mark) return ; } + /* + * AN APP'S LOGO NAMES IT WHEREVER IT IS. A step's row named its app on hover (`AppMark`), but the + * folded line above, "Worked through 8 steps" beside Gmail's, Slack's and Google Calendar's logos, + * named none: the same logo told something in one place and nothing in the other. + */ return ( - - {icons.map(({ kind, appId }, index) => ( - 0 ? "-ml-1.5" : "" - }`} - > - - - ))} + + {icons.map(({ kind, appId }, index) => { + const style = { zIndex: icons.length - index }; + const shape = `relative flex size-5 items-center justify-center rounded-full bg-background ring-2 ring-background ${ + index > 0 ? "-ml-1" : "" + }`; + const icon = ( + + ); + return appId ? ( + + + } + > + {icon} + + {appName(appId)} + + ) : ( + + {icon} + + ); + })} ); } +/** The app a call is a step on (`mcp__googlecalendar__list_events`), or none for any other call. */ +export function appOfCall(name: string): string | undefined { + return serverStepKind(name) === "connector" ? name.split("__")[1] : undefined; +} + /** The kind of step a call the server ran is, as `stepDetails` names it: research, an app, or one of ours. */ function serverStepKind(name: string): StepKind { // A part of an attached file read: a file, as the folded row draws it. @@ -1335,9 +1413,53 @@ export function ServerStepIcon({ name }: { name: string }) { ); } +/** Where each of several apps' logos sits in one mark's square: two corner to corner, more in a grid. */ +const CLUSTER = { + 2: ["left-0 top-0 z-10 size-[11px]", "bottom-0 right-0 size-[11px]"], + 4: [ + "left-0 top-0 size-[7px]", + "right-0 top-0 size-[7px]", + "bottom-0 left-0 size-[7px]", + "bottom-0 right-0 size-[7px]", + ], +} as const; + +/** + * The apps a turn's line worked on, as its mark: one app's logo, or several apps' logos in the room + * of one. + * + * THE SAME ROOM HOWEVER MANY APPS. Several apps' logos side by side were wider than the one mark the + * line had while it worked ("Using Gmail…"), so when it ended the words beside them moved over. Two + * logos now sit corner to corner in one mark's square, and three or four in its corners, each named + * on hover; opened, every row draws its own app's logo full size. + */ export function WorkAppIcons({ names }: { names: string[] }) { + const appName = useAppName(); + const apps = [...new Set(names)]; + if (apps.length <= 1) + return ( + ({ kind: "connector", appId }))} /> + ); + const places = apps.length === 2 ? CLUSTER[2] : CLUSTER[4]; return ( - ({ kind: "connector", appId }))} /> + + {apps.slice(0, places.length).map((appId, index) => ( + + + } + > + + + {appName(appId)} + + ))} + ); } @@ -1363,48 +1485,255 @@ export function StepStatus({ return null; } +/** + * The one app a folded line already shows ("Used Google Calendar", or "Google Calendar Worked + * through 2 steps" beside its logo). Its steps on that app don't draw its logo again. + * + * ONE LOGO FOR ONE APP. Opened, "Used Google Calendar" listed three steps, each beside the Google + * Calendar logo the line above them had just drawn: the same mark four times, telling nothing the + * first didn't. Where the steps are on several apps, each still draws its own, since that is how + * they are told apart. + */ +export const LineShowsApp = createContext(undefined); + +/** + * The columns every row inside one turn's line keeps, worked out over all its steps at once + * (`foldGrid`): the chevron's, and whether a row that doesn't open draws its mark in it. + * + * ONE GRID PER LINE. Opened, a turn's line lists the runs of steps the Bot's words had split apart, + * and each run worked out its own columns: "Looked for a tool" drew its wrench where "Find free + * slots" below it drew its chevron, so the two marks, and the two labels, sat a column apart. + */ +export const FoldGrid = createContext(undefined); + +type Grid = { chevronRoom: boolean; markInChevron: boolean }; + +/* + * THE SAME OBJECT FOR THE SAME COLUMNS. Worked out afresh on every render, the grid was a new + * context value each time, and every finished row inside a turn's line drew again on each word of + * the reply streaming under it. + */ +const GRIDS: Record = { + none: { chevronRoom: false, markInChevron: false }, + chevron: { chevronRoom: true, markInChevron: false }, + markInChevron: { chevronRoom: true, markInChevron: true }, +}; + +/** The columns for the rows of one turn's line (`FoldGrid`), from every step in it. */ +export function foldGrid( + items: readonly TranscriptItem[], + folders: FolderNames, + appName: AppName, +): Grid { + const details = stepDetailsIn(folders, false, appName); + const steps = items.flatMap((item) => + item.kind === "tools" ? foldRereads(item.steps.map(details)) : [], + ); + const shown = onlyApp(items); + if (!steps.some(stepOpens)) return GRIDS.none as Grid; + return ( + steps.some((step) => stepOpens(step) && drawsMark(step, shown)) + ? GRIDS.chevron + : GRIDS.markInChevron + ) as Grid; +} + +/** + * The one app the steps in `items` are on, leaving out steps on no app ("Looked for a tool"); none + * if they are on several apps, or on none. + * + * ONE RULE FOR THE LINE AND ITS ROWS. A turn that looked for a tool, then listed events, read + * "Google Calendar Worked through 2 steps", and opened to "List events" beside the Google + * Calendar logo again: the line named the one app among its logos, the rows asked whether every + * step was on it. Both now ask this. + */ +export function onlyApp(items: readonly TranscriptItem[]): string | undefined { + const apps = new Set(); + for (const item of items) { + const onApps = + item.kind === "tool" + ? [appOfCall(item.toolCall.function.name)] + : item.kind === "tools" + ? item.steps + .map(stepDetails) + .map((step) => + step.kind === "connector" ? step.appId : undefined, + ) + : []; + for (const app of onApps) if (app) apps.add(app); + } + const [app] = apps; + return apps.size === 1 ? app : undefined; +} + +/** + * An app's logo on a step's row, which says the app's name when the pointer rests on it, and to a + * screen reader. + * + * THE LOGO SAYS THE APP. Every app step read "List events Google Calendar", "Search messages + * Slack": the app's name again after every action, beside the logo that already said it. The row + * now says what was done, and its logo which app it was done on; the name is there on hover for a + * logo someone doesn't know. + */ +export function AppMark({ appId, name }: { appId: string; name: string }) { + return ( + + } + > + + + {name} + + ); +} + +/** Whether a step's row draws a mark: every step does, but one on the app its line shows (`shown`). */ +export function drawsMark( + step: StepDetails, + shown: string | undefined, +): boolean { + return !(step.kind === "connector" && step.appId && step.appId === shown); +} + +/** + * A step's mark: an app's logo named on hover (`AppMark`), or the icon for its kind of step. None for + * a step on the app the line above it already shows (`LineShowsApp`). + */ +function StepMark({ step }: { step: StepDetails }) { + const shown = useContext(LineShowsApp); + if (!drawsMark(step, shown)) return null; + return ; +} + +/** A step's mark wherever it is drawn: its app's logo, named on hover, or the icon for its kind. */ +export function BareStepMark({ step }: { step: StepDetails }) { + return step.kind === "connector" && step.appId ? ( + + ) : ( + + ); +} + +/** + * What a line says while `steps` are under way: the one app they are on ("Using Google Calendar…"), + * how many subtasks are working, or the step itself ("Looking for a tool…"). The words a folded run + * of steps says while it runs (`ToolActivity`), for a turn's line too. + */ +export function underWayLabel(steps: readonly StepDetails[]): string { + const subtasks = steps.filter((step) => step.kind === "subtask").length; + if (subtasks) + return subtasks === 1 + ? "Working on a subtask…" + : `Working on ${subtasks} subtasks…`; + const apps = [ + ...new Set( + steps.map((step) => (step.kind === "connector" ? step.connector : null)), + ), + ]; + if (apps.length && apps.every(Boolean)) + return apps.length === 1 + ? `Using ${apps[0]}…` + : `Using ${plural(apps.length, "app", "apps")}…`; + return `${steps[0]?.label ?? "Working"}…`; +} + +/** + * Whether a step's row opens (`StepRow`): a subtask to its steps, a command to its terminal, and any + * other step but a browser one to what it was given and what came back, when it has either. + */ +export function stepOpens(step: StepDetails): boolean { + if (step.kind === "subtask" || step.terminal) return true; + return ( + step.kind !== "browser" && (step.inputs.length > 0 || Boolean(step.output)) + ); +} + +/** + * The apps a row of steps starts and ends on: a list of steps by its first and last, an app's call + * on a line of its own by its app. None for any other row, or a step that is no app's. + */ +export function rowApps(item: TranscriptItem): { + first?: string; + last?: string; +} { + const lone = + item.kind === "tool" + ? item + : item.kind === "tools" && item.steps.length === 1 + ? item.steps[0] + : undefined; + if (lone) { + const app = appOfCall(lone.toolCall.function.name); + return { first: app, last: app }; + } + if (item.kind !== "tools") return {}; + const steps = foldRereads(item.steps.map(stepDetails)); + const app = (step: StepDetails | undefined) => + step?.kind === "connector" ? step.appId : undefined; + return { first: app(steps[0]), last: app(steps.at(-1)) }; +} + /** One step, as a folded line opens to it. Also how a subtask's card lists the steps it took. */ export function StepRow({ step, active, - liveConnector, + chevronRoom = false, + markInChevron = false, }: { step: StepDetails; active: boolean; - liveConnector?: boolean; + /** + * Another row in its list opens (`stepOpens`): a row that doesn't keeps the chevron's room, so its + * mark and words line up with theirs. + */ + chevronRoom?: boolean; + /** + * The rows in its list that open draw no mark (their app is the line's): a row that doesn't open + * draws its mark where their chevron is, so its words start where theirs do. + */ + markInChevron?: boolean; }) { + const shown = useContext(LineShowsApp); if (step.kind === "subtask") return ; /* * The step still working shimmers, as the group's own line does while it runs. "In progress" in * muted text beside a label drawn exactly like the finished steps above it read as one more static * row: a person watching four "Fetch emails" lines and a fifth with no result took the Bot for dead. + * + * ONE ROW, RUNNING OR DONE. An app's step still running was drawn as a box of its own, the app + * first and the action after it, where every other row, its own finished steps beside it, says the + * action first and the app after, plain. Nothing on the box said more than the row does: it is the + * row, shimmering, with "In progress" where "Blocked" or "Didn't work" would be. */ const running = active && step.pending; - const line = - running && liveConnector && step.appId ? ( - - ) : ( - - - - {step.label} - - {step.href ? ( - - {step.detail ?? step.href} - - ) : step.detail ? ( - {step.detail} - ) : null} - + const lineWith = (mark: ReactNode) => ( + // Spaced as a line of its own is (`ToolLine`), so a step and a lone call line up in one list. + + {mark} + + {step.label} - ); + {step.href ? ( + + {step.detail ?? step.href} + + ) : step.detail ? ( + {step.detail} + ) : null} + + + ); + const line = lineWith(); const reason = step.failed && step.kind === "browser" ? (

    @@ -1422,13 +1751,28 @@ export function StepRow({ ); // A browser step says everything it has in its line. Anything else opens to what it was given // and what came back, which no other place in the transcript shows. - if (step.kind === "browser" || (!step.inputs.length && !step.output)) + if (!stepOpens(step)) { + /* + * THE MARK IN THE CHEVRON'S COLUMN. Under "Google Calendar Worked through 2 steps", "List + * events" is its chevron and its words, no logo; "Looked for a tool" kept the chevron's room and + * drew its wrench after it, so its words started a mark further in. Where the rows that open + * draw no mark, this one's stands where their chevron does, as wide, and its words start where + * theirs do. + */ + const inChevron = markInChevron && drawsMark(step, shown); return ( -

  1. - {line} +
  2. + {inChevron + ? lineWith( + + + , + ) + : line} {reason}
  3. ); + } return (
  4. @@ -1591,7 +1935,7 @@ export function WorkingNow({ steps }: { steps: readonly StepDetails[] }) { ) : (
  5. - + {step.label} @@ -1609,8 +1953,9 @@ export function WorkingNow({ steps }: { steps: readonly StepDetails[] }) { export function stepsUnderWay( items: readonly TranscriptItem[], folders: FolderNames, + appName?: AppName, ): StepDetails[] { - const details = stepDetailsIn(folders); + const details = stepDetailsIn(folders, true, appName); return items.flatMap((item) => item.kind === "tools" ? foldRereads(item.steps.map(details)).filter( @@ -1625,19 +1970,21 @@ export function stepsUnderWay( export function ToolActivity({ group, active, - conversation = false, expanded, }: { group: ToolGroup; /** This is the newest row of a turn still in flight, so a step without a result is running. */ active: boolean; - conversation?: boolean; expanded?: boolean; }) { const folders = useContext(FolderNamesContext); // A command with no answer runs while its turn does, whichever row it is in. const inFlight = useContext(TurnInFlightContext); - const steps = group.steps.map(stepDetailsIn(folders, active || inFlight)); + const lineShows = useContext(LineShowsApp); + const appName = useAppName(); + const steps = group.steps.map( + stepDetailsIn(folders, active || inFlight, appName), + ); // What the line opens to: a run of rereads is one row. See `foldRereads`. const rows = foldRereads(steps); const running = active && steps.some((step) => step.pending); @@ -1661,32 +2008,68 @@ export function ToolActivity({ * each step under way is a line of its own beneath it: the Bot's own, and each subtask with what it * was asked, the step it is on and how many it has taken. Opened, the group lists everything. */ + /* + * A RUN OF APP STEPS IS ITS APPS' LINE, RUNNING OR DONE. While it ran, a run of Google Calendar + * steps was listed open, one row each, and folded into "Used Google Calendar" only once every step + * had its answer. Now it is that line from the start, "Using Google Calendar…", shimmering while a + * step is under way, and opened, it lists the steps as it does once they are done. + */ + const apps = [ + ...new Set( + rows.map((step) => (step.kind === "connector" ? step.connector : null)), + ), + ]; + const appsOnly = apps.every(Boolean); + const using = + appsOnly && apps.length === 1 + ? `Using ${apps[0]}…` + : `Using ${plural(apps.length, "app", "apps")}…`; const live = running ? rows.filter((step) => step.pending && !step.interrupted) : []; - const showLiveSteps = - conversation && - inFlight && - rows.some((step) => step.pending && !step.interrupted) && - rows.every((step) => step.kind === "connector"); - const list = ( -
      + const oneApp = appsOnly && apps.length === 1 ? rows[0]?.appId : undefined; + // The app the line above these rows shows: their own line's, or, drawn open, the one around them. + const shown = expanded ? lineShows : oneApp; + // Drawn open inside a turn's line, the rows keep the line's columns, worked out over all its steps. + const grid = useContext(FoldGrid); + const chevronRoom = + expanded && grid ? grid.chevronRoom : rows.some(stepOpens); + const markInChevron = + expanded && grid + ? grid.markInChevron + : chevronRoom && + !rows.some((step) => stepOpens(step) && drawsMark(step, shown)); + const rowsList = ( + // One size wherever it is opened: a folded line's own body is drawn smaller, a "Worked for" + // line's isn't, and the same steps read at two sizes in one conversation. + // Inside a turn's line, its rows keep the line's one gap: no room above or below a run of them. +
        {rows.map((step) => ( ))}
      ); + // Folded, its own line shows its app; drawn open, the line it sits under does (`LineShowsApp`). + const list = expanded ? ( + rowsList + ) : ( + {rowsList} + ); const approvals = ( step.toolCall.id)} /> ); - if (expanded || showLiveSteps) { + if (expanded) { return ( <> {list} @@ -1703,15 +2086,19 @@ export function ToolActivity({ drawnWhenOpened icon={} openKey={group.id} - live={live.length ? : undefined} + live={ + live.length && !appsOnly ? : undefined + } label={ running && working ? working === 1 ? "Working on a subtask…" : `Working on ${working} subtasks…` - : running && current - ? `${current.label}…` - : summarise(steps) + : running && appsOnly + ? using + : running && current + ? `${current.label}…` + : summarise(steps) } detail={asides.length ? asides.join(" · ") : undefined} running={running} diff --git a/app/src/components/channels/tool-line.tsx b/app/src/components/channels/tool-line.tsx index 720f464af2..2a326c1da4 100644 --- a/app/src/components/channels/tool-line.tsx +++ b/app/src/components/channels/tool-line.tsx @@ -89,6 +89,7 @@ export function ToolLine({ label, attempted, detail, + lead, running, refused, failed, @@ -101,8 +102,27 @@ export function ToolLine({ openKey, live, drawnWhenOpened, + chevronRoom, + status, + wide, children, }: { + /** + * Its words shimmer across the whole width of the line, as the "Thinking" line under a message + * does (`Thinking` in chat-transcript.tsx): the band is sized to what it sweeps, so on the few + * words alone it crossed them fast and often, and read as another thing from that line. + */ + wide?: boolean; + /** + * Its words are the conversation's progress, said to a screen reader as they change ("Thinking", + * "Using Gmail…"), as the "Thinking" line under a message used to be. + */ + status?: boolean; + /** + * A line with nothing to open yet that will come to open (a turn's line before its first step) + * keeps the chevron's room, so its mark and words don't move when the chevron arrives. + */ + chevronRoom?: boolean; /** * What it opens to is drawn only once it is opened (`useDrawnOnceOpened`), for a line holding * nothing that must be on the page while folded: a group's list of steps, which can run to @@ -128,6 +148,8 @@ export function ToolLine({ * step, where it is the reason and wraps in full. */ detail?: string; + /** What the line is about, said before what was done ("Google Calendar Worked through 2 steps"). */ + lead?: string; running?: boolean; /** A policy or a boundary said no. Final: nothing the Bot does differently will help. */ refused?: boolean; @@ -203,10 +225,11 @@ export function ToolLine({ const text = ( {icon ? {icon} : null} + {lead ? {lead} : null} {/* * Free to shrink, so a long label (a folded run's "Read 1 file, searched for 2 patterns and * listed 1 directory") wraps in a phone-width column instead of running past it. The detail @@ -218,6 +241,8 @@ export function ToolLine({ className={ label.length <= SHORT_LABEL ? "shrink-0 whitespace-nowrap" : "min-w-0" } + // `status` rather than `alert`: progress, not something that interrupts. + {...(status ? { role: "status" } : {})} > {refused ? `Blocked: ${attempted ?? label}` @@ -242,6 +267,11 @@ export function ToolLine({ {detail} ) : null} + {/* + * Said to a screen reader, which hears no shimmer: the same "In progress" a step in a list + * says beside its label (`StepStatus`), on every line still running, whatever it does. + */} + {running ? In progress : null} ); @@ -250,7 +280,15 @@ export function ToolLine({ * is done (a page read, then the pages it read) does not move. As a block, a line with an icon * taller than its words sat two or three pixels lower than the same line opening to something. */ - if (!children) return
      {text}
      ; + if (!children) + return chevronRoom ? ( +
      + + {text} +
      + ) : ( +
      {text}
      + ); const remember = (event: SyntheticEvent) => { const open = event.currentTarget.open; diff --git a/app/src/components/tasks/turn-work.ts b/app/src/components/tasks/turn-work.ts index 5c9a5a6fef..adec5f13a0 100644 --- a/app/src/components/tasks/turn-work.ts +++ b/app/src/components/tasks/turn-work.ts @@ -40,17 +40,30 @@ export type TurnWork = { rows: { item: TranscriptItem; index: number }[]; /** The turn is still under way. */ running: boolean; + /** + * A conversation's turn: the person's row its line is drawn under, from the moment they send to the + * answer and after. A task's fold is drawn where its first row is, and has none. + */ + under?: string; + /** The Bot has said something after the line's last step: its answer, or what may yet be it. */ + answered?: boolean; }; export type TurnWorkFolds = { - /** Each fold, by the id of the first row it holds, which is where it is drawn. */ + /** Each task fold, by the id of the first row it holds, which is where it is drawn. */ at: Map; + /** Each conversation turn's line, by the id of the person's row it is drawn under. */ + under: Map; /** Every row inside a fold, drawn there and not on its own. */ inside: Set; }; /** No folds: a thread that is not a task's. */ -export const NO_TURN_WORK: TurnWorkFolds = { at: new Map(), inside: new Set() }; +export const NO_TURN_WORK: TurnWorkFolds = { + at: new Map(), + under: new Map(), + inside: new Set(), +}; /** * Whether a call drawn on its own is a step of the work: Claude Code's own tools, the Bot computer's @@ -130,8 +143,18 @@ export function foldTurnWork( running: boolean, waiting: ReadonlySet = new Set(), scope: "task" | "conversation" = "task", + /** + * A conversation's words on the way fold into its line. Not while the app can't yet tell a card it + * draws from a step (`useDrawnTool`'s `known`): a picture would read as a step for one render, the + * words before it would fold, and come back out a render later replaying their arrival. + */ + foldWords = true, ): TurnWorkFolds { - const folds: TurnWorkFolds = { at: new Map(), inside: new Set() }; + const folds: TurnWorkFolds = { + at: new Map(), + under: new Map(), + inside: new Set(), + }; // Where each turn starts: just after what the person (or the brief) said. const starts: { askId: string; at: number; from: number }[] = []; items.forEach((item, index) => { @@ -148,6 +171,20 @@ export function foldTurnWork( starts.forEach((start, turn) => { const end = starts[turn + 1]?.at ?? items.length; const inFlight = running && turn === starts.length - 1; + if (scope === "conversation") { + const work = conversationTurn( + items, + start, + end, + inFlight, + waiting, + foldWords, + ); + if (!work) return; + if (work.under !== undefined) folds.under.set(work.under, work); + for (const row of work.rows) folds.inside.add(row.item.id); + return; + } const said: number[] = []; for (let index = start.from; index < end; index += 1) { const item = items[index]; @@ -160,21 +197,16 @@ export function foldTurnWork( ? end - 1 : -1 : (said.at(-1) ?? -1); - // Every piece of a conversation reply stays visible, including text around a chart. - // Leave work visible while the turn is live or when the Bot never produced an answer. - if (scope === "conversation" && (inFlight || answer === -1)) return; const rows: TurnWork["rows"] = []; for (let index = start.from; index < end; index += 1) { const item = items[index]; if (!item || index === answer) continue; // The plan stays in view while its turn runs: it is how the person sees how far along it is. if (inFlight && isPlanStep(item)) continue; - // Keep existing refusal and issue notices at their original place in conversation replies. - if (scope === "conversation" && hasVisibleOutcome(item)) continue; if ( (item.kind === "tools" && !waitsOnThePerson(item, inFlight, waiting)) || (item.kind === "tool" && isWorkStep(item)) || - (scope === "task" && item.kind === "text" && item.role === "assistant") + (item.kind === "text" && item.role === "assistant") ) rows.push({ item, index }); } @@ -189,7 +221,76 @@ export function foldTurnWork( folds.at.set(first.item.id, work); for (const row of rows) folds.inside.add(row.item.id); }); - return folds.at.size ? folds : NO_TURN_WORK; + return folds.at.size || folds.under.size ? folds : NO_TURN_WORK; +} + +/** + * A conversation's turn, as one line under the person's message, from the moment they send. + * + * ONE LINE, MADE AT SEND, NEVER REBUILT. A turn was drawn one way while the Bot worked ("Thinking", + * then a line per step, each styled by where it came from) and rebuilt another way once it ended: + * one "Worked through 2 steps" line that swallowed the steps and moved above what the Bot had said + * on the way. Filmed from a real run, every frame was plausible and every transition jumped. Now the + * line is there from the send ("Thinking"), says what is under way ("Using Google Calendar…"), and + * ends as what was done, in the same place; the answer is drawn under it. + * + * What folds: every step of the work, and what the Bot said before its last step (said on the way, + * not the answer). What the Bot said after its last step stays out, since it is the answer or may yet + * be: while the turn runs, its newest words are the answer until a step starts after them, and then + * they go into the line. What is drawn for the person (a chart, a card, a plan, a question, an + * approval still waiting, a step that went wrong) stays where it is. + * + * A turn that took no step and said nothing yet is still a line while it runs: "Thinking" is that + * line, not an element of its own. Once its answer starts with no step taken, it has no line, and + * its words are drawn where the line was. + */ +function conversationTurn( + items: readonly TranscriptItem[], + start: { askId: string; from: number }, + end: number, + inFlight: boolean, + waiting: ReadonlySet, + foldWords: boolean, +): TurnWork | undefined { + const steps: number[] = []; + const said: number[] = []; + for (let index = start.from; index < end; index += 1) { + const item = items[index]; + if (!item) continue; + if (item.kind === "text" && item.role === "assistant") said.push(index); + // A refusal or an issue keeps its place, said where it happened. + if (hasVisibleOutcome(item)) continue; + /* + * Only runs of steps: a call drawn on its own in a conversation is drawn for the person (a + * card, a chart, a picture, a plan, a change Claude Code made, a command it ran), and stays in + * view, in its place under the line. Folded at the end, the plan was the turn rebuilt again. + */ + if (item.kind === "tools" && !waitsOnThePerson(item, inFlight, waiting)) + steps.push(index); + } + const lastStep = steps.at(-1) ?? -1; + const rows: TurnWork["rows"] = []; + for (let index = start.from; index < end; index += 1) { + const item = items[index]; + if (!item) continue; + if ( + steps.includes(index) || + (foldWords && index < lastStep && said.includes(index)) + ) + rows.push({ item, index }); + } + const answered = said.some((index) => index > lastStep); + // No step and no words yet, while it runs: the line is the turn's "Thinking". + if (!rows.length && !(inFlight && !said.length)) return undefined; + const ask = items[start.from - 1]; + return { + id: `work:${start.askId}`, + askId: start.askId, + rows, + running: inFlight, + under: ask?.id, + answered, + }; } /** How many steps a fold holds: each tool call in it, a run of them counted call by call. */ diff --git a/app/src/components/tasks/worked-for.tsx b/app/src/components/tasks/worked-for.tsx index 492c9799a5..fba8041e0b 100644 --- a/app/src/components/tasks/worked-for.tsx +++ b/app/src/components/tasks/worked-for.tsx @@ -15,8 +15,16 @@ import { useSyncExternalStore, } from "react"; import { + BareStepMark, + FoldGrid, + foldGrid, + foldRereads, + onlyApp, + stepDetailsIn, stepsUnderWay, type TranscriptItem, + underWayLabel, + useAppName, WorkAppIcons, WorkingNow, } from "@/components/channels/tool-activity"; @@ -225,10 +233,12 @@ function WorkLine({ * the step it is on and how many it has taken. Opened, the rows inside say the same and more. */ const folders = useContext(FolderNamesContext); + const appName = useAppName(); const underWay = running ? stepsUnderWay( work.rows.map((row) => row.item), folders, + appName, ) : []; const apps = work.rows.flatMap(({ item }) => { @@ -242,6 +252,8 @@ function WorkLine({ : []; }); }); + // The one app the line's logo shows, if it shows one: named on the line, not again on its rows. + const app = onlyApp(work.rows.map((row) => row.item)); return (
      : undefined} - label={text} + // After the app's name, what was done goes on the sentence: "Google Calendar worked for 2m". + label={app ? text.charAt(0).toLowerCase() + text.slice(1) : text} + /* + * THE ONE APP, NAMED. "Worked through 2 steps" beside Google Calendar's logo said which app + * only to someone who knew the logo; its rows don't name it (`LineShowsApp`). Where the + * line's logo is one app's, the line names it beside the logo, before what was done: + * "Google Calendar Worked through 2 steps". + */ + {...(app ? { lead: appName(app) } : {})} running={running} openKey={work.id} live={underWay.length ? : undefined} @@ -263,3 +283,137 @@ function WorkLine({
      ); } + +/** The apps a turn's steps were on, in the order it first used them, for the line's logos. */ +function appsOf(work: TurnWork): string[] { + return work.rows.flatMap(({ item }) => { + const tools = + item.kind === "tools" ? item.steps : item.kind === "tool" ? [item] : []; + return tools.flatMap(({ toolCall }) => { + const name = toolCall.function.name; + const [namespace, appId, action] = name.split("__"); + return namespace === "mcp" && appId && action && !researchRoleOfCall(name) + ? [appId] + : []; + }); + }); +} + +/** + * A conversation turn's one line, from the moment the person sends to long after the answer + * (`foldTurnWork`'s "conversation" scope draws it under their message). + * + * ONE LINE, AND ONLY ITS WORDS AND MARK CHANGE. Filmed from a real run, the turn used to be a + * "Thinking" paragraph, then a line per step in two styles, then "Thinking" again between steps, then + * a "Worked through 2 steps" line rebuilt above the Bot's words once it ended. Now one line says, in + * one place: "Thinking", "Looking for a tool…", "Using Google Calendar…", and once the answer + * starts, "Google Calendar worked through 2 steps". Its mark is the step's under way, none while + * the Bot thinks, and once it is done, the apps it used. The chevron's + * room is kept from the first frame, so nothing moves when there comes to be something to open. + */ +export function TurnLine({ + work, + busy, + reconnecting = false, + children, +}: { + work: TurnWork; + /** The Bot is working on the conversation now: a stopped turn is in flight but not moving. */ + busy: boolean; + /** The Bot is waiting to try its model again: said in place of "Thinking". */ + reconnecting?: boolean; + /** The folded rows, drawn as they would be on their own. */ + children: ReactNode; +}) { + const folders = useContext(FolderNamesContext); + const appName = useAppName(); + const items = work.rows.map((row) => row.item); + const live = work.running && busy; + const underWay = live ? stepsUnderWay(items, folders, appName) : []; + // The last step taken, for the line's mark while the Bot thinks after it. + const details = stepDetailsIn(folders, live, appName); + const last = items + .flatMap((item) => + item.kind === "tools" + ? foldRereads(item.steps.map(details)) + : item.kind === "tool" + ? [details(item)] + : [], + ) + .at(-1); + const apps = appsOf(work); + const app = onlyApp(items); + const steps = stepsIn(work); + const thinking = live && !underWay.length && !work.answered; + /* + * WHAT IT HAS DONE SO FAR, WHILE THE BOT IS TALKING. Its words after a step may be the answer or + * only a remark before the next step, and nobody knows which until a step starts or the run ends. + * The line says what it has done ("Google Calendar Worked through 2 steps"), shimmering while the + * run goes on: if the words were the answer, the run's end only stills it; if a step follows, the + * line says that step. Said as done and still, it read as finished, and then started again. + */ + const done = !underWay.length && (!live || work.answered); + const said = underWay.length + ? underWayLabel(underWay) + : thinking + ? reconnecting + ? "Reconnecting…" + : "Thinking" + : steps === 0 + ? "Worked on it" + : `Worked through ${steps} ${steps === 1 ? "step" : "steps"}`; + // After the app's name, what was done goes on the sentence: "Google Calendar worked through 2 + // steps". With no app named, it starts it: "Worked through 4 steps". + const lead = done && app ? appName(app) : undefined; + const label = lead ? said.charAt(0).toLowerCase() + said.slice(1) : said; + const grid = foldGrid(items, folders, appName); + /* + * "THINKING" IS THE WORD ALONE, AS IT IS UNDER A MESSAGE. A sparkle beside it, and then the last + * step's logo beside it between steps, put a picture by a state that has none. The mark's room is + * kept, empty, so the words stay where a step's will be and nothing moves when one starts. + */ + const mark = thinking ? ( + + ) : underWay[0] ? ( + + ) : done && apps.length ? ( + + ) : last ? ( + + ) : ( + + ); + // Subtasks run for minutes: each one under way says how far along it is, beneath the line. + const subtasks = underWay.filter((step) => step.kind === "subtask"); + return ( +
      + : undefined} + > + {work.rows.length ? ( + /* + * ONE GAP BETWEEN EVERYTHING IN THE LINE. Rows of one run sat 8px apart, a run and the + * Bot's words between runs 16px, so "Looked for a tool" stood off from the steps under it + * as if it were something else. Every row and every line said on the way is 8px from the + * next. + */ +
      + {children} +
      + ) : undefined} +
      +
      + ); +} diff --git a/app/tests/app-step-rows.test.tsx b/app/tests/app-step-rows.test.tsx new file mode 100644 index 0000000000..e31ac8c8f8 --- /dev/null +++ b/app/tests/app-step-rows.test.tsx @@ -0,0 +1,545 @@ +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; +import type { Message } from "@ag-ui/core"; +import { CopilotKitProvider } from "@copilotkit/react-core/v2"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { + cleanup, + fireEvent, + render, + waitFor, + within, +} from "@testing-library/react"; +import { ChatTranscript } from "@/components/channels/chat-transcript"; +import { forgetOpenedLines } from "@/components/channels/tool-line"; +import { queryClient } from "@/query-client"; +import { approvalInboxResponse } from "./approvals-api"; +import { settleReactWork } from "./settle-react-work"; + +/** + * An app's steps are drawn one way, running or done, and say their app once. + * + * Reported from the web app, on a Bot listing a person's events: three Google Calendar steps in a + * row, drawn three ways. The two finished ones read "List events" beside "Googlecalendar", the app's + * key, while the one still running sat in a box of its own, the app first, "Google Calendar · List + * events", with a spinner. The box said nothing the row does not: the action, the app, and that it + * was still going. + * + * So a run of steps on one app is that app's line, "Using Google Calendar…" while a step runs and + * "Used Google Calendar" once it is done, and opened, each step is one row saying what was done, the + * same row running or done, with no logo the line above already draws. Where the steps are on + * several apps, each row draws its app's logo, which names the app on hover and to a screen reader. + */ + +const originalFetch = globalThis.fetch; + +/** Google Calendar, as the apps added here list it. Its key in words would be "Googlecalendar". */ +const APP = { + id: "googlecalendar", + title: "Google Calendar", + logo: "https://apps.example/google-calendar.svg", +}; + +beforeAll(() => { + GlobalRegistrator.register({ url: "http://localhost/" }); + globalThis.fetch = Object.assign( + async (input: Parameters[0]) => { + const url = new URL( + typeof input === "string" + ? input + : input instanceof URL + ? input.href + : input.url, + "http://localhost", + ); + { + const approvals = approvalInboxResponse(url.pathname, { + enabled: false, + requests: [], + rules: [], + teamRules: [], + questions: [], + }); + if (approvals) return approvals; + } + if (url.pathname === "/api/v2/organizations/default/apps") + return Response.json({ apps: [APP], nextCursor: null }); + return Response.json({ error: "not served" }, { status: 404 }); + }, + { preconnect: originalFetch.preconnect }, + ); +}); + +afterEach(() => { + cleanup(); + forgetOpenedLines(); + queryClient.clear(); +}); + +afterAll(async () => { + await settleReactWork(); + globalThis.fetch = originalFetch; + GlobalRegistrator.unregister(); +}); + +const LIST_EVENTS = "mcp__googlecalendar__list_events"; +const EVENTS = '{"events":[{"summary":"Design review"}]}'; +const NOTE = + '[OpenBot: this answer is 40,000 characters long, in 3 parts. This is part 2 of 3: characters 18,000 to 36,000. To read part 3, call read_result_part with {"tool":"mcp__googlecalendar__list_events","arguments":{},"part":3}.]'; + +/** One call, answered unless `result` is left out. */ +function call( + id: string, + name: string, + args: object, + result?: string, +): Message[] { + return [ + { + id: `a-${id}`, + role: "assistant", + content: "", + toolCalls: [ + { + id, + type: "function", + function: { name, arguments: JSON.stringify(args) }, + }, + ], + }, + ...(result === undefined + ? [] + : [ + { + id: `t-${id}`, + role: "tool" as const, + toolCallId: id, + content: result, + }, + ]), + ]; +} + +const ASKED: Message = { + id: "u1", + role: "user", + content: "What's on my calendar this week?", +}; + +/** The turn from the report: events listed, the next part of that answer read, events listed again. */ +function turn(lastAnswered: boolean): Message[] { + return [ + ASKED, + ...call("list-1", LIST_EVENTS, { timeMin: "2026-12-01" }, EVENTS), + ...call( + "part-2", + "read_result_part", + { tool: LIST_EVENTS, arguments: {}, part: 2 }, + `${EVENTS}\n\n${NOTE}`, + ), + ...call( + "list-2", + LIST_EVENTS, + { timeMin: "2026-12-08" }, + lastAnswered ? EVENTS : undefined, + ), + ]; +} + +function transcript(messages: Message[], busy: boolean) { + return ( + + + + + + ); +} + +/** What a step's line says, in order, and how it is drawn: each part's tag and classes. */ +function shapeOf(line: Element) { + return { + tag: line.tagName, + classes: line.className, + parts: [...line.children].map((part) => part.tagName), + }; +} + +/** What a row says, as read: a logo, or a letter standing in for one, is drawn, not read. */ +function said(line: Element): string { + const copy = line.cloneNode(true) as Element; + for (const hidden of copy.querySelectorAll("[aria-hidden]")) hidden.remove(); + return copy.textContent ?? ""; +} + +/** The app a row's logo names, to a screen reader and on hover (`AppMark`). */ +function markOf(line: Element) { + const mark = line.querySelector('[role="img"]'); + return { + name: mark?.getAttribute("aria-label"), + logo: mark?.querySelector("img")?.getAttribute("src"), + }; +} + +test("a run of one app's steps is that app's line while it runs, and opens to one row per step", async () => { + const view = render(transcript(turn(false), true)); + + // While a step runs, the turn's line says the app it is using, by its name, shimmering, and + // folded (`TurnLine`). + const line = await view.findByText("Using Google Calendar…"); + expect(line.closest(".tool-line-running")).not.toBeNull(); + expect(line.closest("details")?.open).toBe(false); + fireEvent.click(line); + + // Opened, one row a step. + const steps = view.getByRole("list", { name: "Tool steps" }); + const rows = [...steps.querySelectorAll(":scope > li")]; + expect(rows).toHaveLength(3); + const lines = rows.map( + (row) => row.querySelector("summary > span:last-child") as Element, + ); + const [listed, partRead, running] = lines; + if (!listed || !partRead || !running) throw new Error("Expected 3 lines"); + + // What was done, finished or running, and not the app again: the line above says it, and draws its + // logo, so the rows under it don't. + expect(listed.textContent).toBe("List events"); + expect(partRead.textContent).toBe( + "Read the next part of an answerList events, part 2 of 3", + ); + expect(running.textContent).toBe("List eventsIn progress"); + for (const row of lines) expect(markOf(row).name).toBeUndefined(); + + // One shape: no box, no app before the action, the same parts in the same order. + const done = shapeOf(listed); + expect(shapeOf(running)).toEqual({ ...done, parts: [...done.parts, "SPAN"] }); + // Only its running says it is running: the label shimmers, and "In progress" where a status goes. + expect(running.querySelector(".tool-line-running")?.textContent).toBe( + "List events", + ); + expect(listed.querySelector(".tool-line-running")).toBeNull(); + // Opened, its rows are drawn at the size every list of steps is. + expect(steps.className).toContain("text-sm"); + + // The app's key is never shown as its name. + expect(view.container.textContent).not.toContain("Googlecalendar"); + expect(view.container.textContent).not.toContain("googlecalendar"); +}); + +test("answered, the line says what the run did, and its steps stop running and nothing else changes", async () => { + const view = render(transcript(turn(false), true)); + fireEvent.click(await view.findByText("Using Google Calendar…")); + const before = shapeOf( + view + .getByRole("list", { name: "Tool steps" }) + .querySelector( + ":scope > li:last-child summary > span:last-child", + ) as Element, + ); + + // Every step answered, the same line says the Bot is thinking about what came back. + view.rerender(transcript(turn(true), true)); + expect(await view.findByText("Thinking")).toBeTruthy(); + const after = view.getByRole("list", { name: "Tool steps" }); + expect(after.querySelector(".tool-line-running")).toBeNull(); + const last = after.querySelector( + ":scope > li:last-child summary > span:last-child", + ) as Element; + expect(last.textContent).toBe("List events"); + expect(shapeOf(last)).toEqual({ + ...before, + parts: before.parts.slice(0, -1), + }); + expect(view.container.textContent).not.toContain("Googlecalendar"); +}); + +test("steps on several apps each draw their app's logo, which names the app", async () => { + const view = render( + transcript( + [ + ASKED, + ...call("list-1", LIST_EVENTS, { timeMin: "2026-12-01" }, EVENTS), + ...call( + "mail-1", + "mcp__gmail__fetch_emails", + { query: "is:unread" }, + '{"messages":[]}', + ), + ], + true, + ), + ); + fireEvent.click(await view.findByText("Thinking")); + const lines = [ + ...view + .getByRole("list", { name: "Tool steps" }) + .querySelectorAll(":scope > li summary > span:last-child"), + ]; + expect(lines.map(said)).toEqual(["List events", "Fetch emails"]); + expect(lines.map((line) => markOf(line))).toEqual([ + { name: APP.title, logo: APP.logo }, + expect.objectContaining({ name: "Gmail" }), + ]); + // The app's name is the logo's, not written on the row. + expect(view.queryByText("Google Calendar")).toBeNull(); +}); + +test("resting the pointer on an app's logo names the app", async () => { + const view = render( + transcript( + [ASKED, ...call("list-1", LIST_EVENTS, { timeMin: "2026-12-01" })], + true, + ), + ); + const mark = await waitFor(() => { + const found = view.container.querySelector( + '[role="img"][aria-label="Google Calendar"]', + ); + if (!found) throw new Error("Expected the app's logo"); + return found; + }); + expect(view.queryByText("Google Calendar")).toBeNull(); + fireEvent.pointerEnter(mark, { pointerType: "mouse" }); + fireEvent.mouseEnter(mark); + fireEvent.pointerMove(mark, { pointerType: "mouse" }); + fireEvent.mouseMove(mark); + expect( + await view.findByText("Google Calendar", {}, { timeout: 3000 }), + ).toBeTruthy(); +}); + +test("an app's call on its own is its turn's line, which reads the same way running or done", async () => { + const one = (answered: boolean) => [ + ASKED, + ...call( + "list-1", + LIST_EVENTS, + { timeMin: "2026-12-01" }, + answered ? EVENTS : undefined, + ), + ]; + const view = render(transcript(one(false), true)); + const line = (await view.findByText("Using Google Calendar…")) + .parentElement as HTMLElement; + await waitFor(() => expect(markOf(line).logo).toBe(APP.logo)); + // The app's logo, naming the app; what it is doing; and "In progress" for a screen reader, which + // hears no shimmer. + expect(markOf(line).name).toBe(APP.title); + expect(line.classList.contains("tool-line-running")).toBe(true); + expect(line.querySelector(".sr-only")?.textContent).toBe("In progress"); + expect(view.container.textContent).not.toContain("Googlecalendar"); + const whileRunning = [...line.classList]; + + view.rerender(transcript(one(true), false)); + const done = (await view.findByText("worked through 1 step")) + .parentElement as HTMLElement; + // The same logo, and the app named before what was done. + expect(markOf(done)).toEqual({ name: APP.title, logo: APP.logo }); + expect(said(done)).toBe("Google Calendarworked through 1 step"); + // Drawn as it was while running, less the running. + const running = new Set(["tool-line-running", "tabular-nums"]); + expect([...done.classList]).toEqual( + whileRunning.filter((name) => !running.has(name)), + ); +}); + +test("a step that doesn't open keeps the chevron's room in a list where others open, so the rows line up", async () => { + const view = render( + transcript( + [ + ASKED, + ...call("list-1", LIST_EVENTS, { timeMin: "2026-12-01" }, EVENTS), + // Given nothing and answered with nothing: nothing to open to. + ...call("calendars", "mcp__googlecalendar__list_calendars", {}, ""), + ], + true, + ), + ); + fireEvent.click(await view.findByText("Thinking")); + const rows = [ + ...view + .getByRole("list", { name: "Tool steps" }) + .querySelectorAll(":scope > li"), + ]; + expect(rows).toHaveLength(2); + const [opens, doesnt] = rows; + expect(opens?.querySelector("summary")).not.toBeNull(); + expect(doesnt?.querySelector("summary")).toBeNull(); + // The chevron is 14px and 6px from what follows it: the row without one is drawn 20px in. + expect(doesnt?.className).toContain("pl-5"); + expect(opens?.className).not.toContain("pl-5"); +}); + +const BETWEEN = "I found the design review. I'm checking next week too."; + +/** A finished turn: calls on Google Calendar, `before` then `after` of them with the Bot's words between. */ +function splitTurn(before: number, after: number): Message[] { + const list = (n: number) => + call(`list-${n}`, LIST_EVENTS, { timeMin: `2026-12-0${n}` }, EVENTS); + return [ + ASKED, + ...Array.from({ length: before }, (_, n) => list(n + 1)).flat(), + { id: "between", role: "assistant", content: BETWEEN }, + ...Array.from({ length: after }, (_, n) => list(before + n + 1)).flat(), + { + id: "answer", + role: "assistant", + content: "You have a design review on Tuesday.", + }, + ]; +} + +for (const [shape, before, after] of [ + ["a call on a line of its own", 1, 1], + ["a list of calls", 2, 2], +] as const) + test(`app steps the Bot spoke between sit as one list once the turn is folded: ${shape} each side`, async () => { + const view = render(transcript(splitTurn(before, after), false)); + const fold = await waitFor(() => { + const found = view.container.querySelector( + '[data-slot="worked-for"] details', + ); + if (!found) throw new Error("Expected the turn's steps folded"); + return found; + }); + fireEvent.click(fold.querySelector("summary") as HTMLElement); + // The apps added here are in: the line draws Google Calendar's own logo. + await waitFor(() => + expect(fold.querySelector("summary img")?.getAttribute("src")).toBe( + APP.logo, + ), + ); + + // The line names the one app its logo shows, beside the logo and before what was done. + const label = within( + fold.querySelector("summary") as HTMLElement, + ).getByText(`worked through ${before + after} steps`); + const named = label.previousElementSibling; + expect(named?.textContent).toBe(APP.title); + expect( + named?.previousElementSibling?.querySelector("img")?.getAttribute("src"), + ).toBe(APP.logo); + expect(label.nextElementSibling).toBeNull(); + + // Each call is a row of its own, drawn alike, a lone call included: what was done, with no logo, + // since every step in the line is on the one app its line draws. + const lines = within(fold) + .getAllByText("List events") + .map((label) => label.parentElement as Element); + expect(lines).toHaveLength(before + after); + for (const line of lines) { + expect(line.textContent).toBe("List events"); + expect(markOf(line).name).toBeUndefined(); + expect(line.closest('ol[aria-label="Tool steps"]')).not.toBeNull(); + } + + // The gap the words left is closed by the line's one gap (`TurnLine`): every row is 8px from the + // next, nothing is drawn up, and no run's list keeps room of its own above or below. + expect(fold.querySelector("div.space-y-2.py-1")).not.toBeNull(); + for (const line of [lines[before - 1], lines[before]]) { + expect(line?.closest('[class*="-mt-"]')).toBeNull(); + expect(line?.closest("ol")?.className).not.toContain("py-1"); + } + // The Bot's words are said outside the fold, as always. + expect(view.getByText(BETWEEN).closest("details")).toBeNull(); + }); + +test("a turn's line on several apps names none after what it did, and each logo names its app on hover", async () => { + const view = render( + transcript( + [ + ASKED, + ...call("list-1", LIST_EVENTS, { timeMin: "2026-12-01" }, EVENTS), + { id: "between", role: "assistant", content: BETWEEN }, + ...call( + "mail-1", + "mcp__gmail__fetch_emails", + { query: "is:unread" }, + '{"messages":[]}', + ), + { + id: "answer", + role: "assistant", + content: "You have a design review on Tuesday.", + }, + ], + false, + ), + ); + const summary = await waitFor(() => { + const found = view.container.querySelector( + '[data-slot="worked-for"] summary', + ); + if (!found) throw new Error("Expected the turn's steps folded"); + return found; + }); + await waitFor(() => + expect( + [...summary.querySelectorAll('[role="img"]')].map((mark) => + mark.getAttribute("aria-label"), + ), + ).toEqual([APP.title, "Gmail"]), + ); + // Two apps: no one app to name; each logo names its own. + const label = within(summary).getByText("Worked through 2 steps"); + expect( + label.previousElementSibling?.querySelector('[role="img"]'), + ).not.toBeNull(); + expect(label.nextElementSibling).toBeNull(); + expect(view.queryByText("Gmail")).toBeNull(); + const gmail = summary.querySelector( + '[role="img"][aria-label="Gmail"]', + ) as HTMLElement; + fireEvent.pointerEnter(gmail, { pointerType: "mouse" }); + fireEvent.mouseEnter(gmail); + fireEvent.pointerMove(gmail, { pointerType: "mouse" }); + fireEvent.mouseMove(gmail); + expect(await view.findByText("Gmail", {}, { timeout: 3000 })).toBeTruthy(); +}); + +test("a turn that also took a step on no app is still its one app's line, and that app's rows draw no logo", async () => { + const view = render( + transcript( + [ + ASKED, + // Given nothing and answered with nothing: a step that opens to nothing. + ...call("search", "search_tools", {}, ""), + ...call("list-1", LIST_EVENTS, { timeMin: "2026-12-01" }, EVENTS), + { + id: "answer", + role: "assistant", + content: "You have a design review on Tuesday.", + }, + ], + false, + ), + ); + const fold = await waitFor(() => { + const found = view.container.querySelector( + '[data-slot="worked-for"] details', + ); + if (!found) throw new Error("Expected the turn's steps folded"); + return found; + }); + const summary = fold.querySelector("summary") as HTMLElement; + await waitFor(() => + expect( + within(summary).getByText("worked through 2 steps").previousElementSibling + ?.textContent, + ).toBe(APP.title), + ); + fireEvent.click(summary); + const listed = within(fold).getByText("List events").parentElement as Element; + expect(said(listed)).toBe("List events"); + expect(markOf(listed).name).toBeUndefined(); + // "List events" is a chevron and its words: the step that doesn't open draws its wrench in the + // chevron's column, as wide (14px), not after the chevron's room. + const looked = within(fold) + .getByText("Looked for a tool") + .closest("li") as Element; + expect(looked.querySelector("summary")).toBeNull(); + expect(looked.className).not.toContain("pl-5"); + expect(looked.querySelector("svg")?.parentElement?.className).toContain( + "w-3.5", + ); +}); diff --git a/app/tests/approval-carry-on-running.test.tsx b/app/tests/approval-carry-on-running.test.tsx index 25c082c268..70b50f55ba 100644 --- a/app/tests/approval-carry-on-running.test.tsx +++ b/app/tests/approval-carry-on-running.test.tsx @@ -288,7 +288,7 @@ function mounting() { } const STOP = '[data-testid="composer-stop"]'; -const WORKING = '.tool-line-running, [data-slot="live-connector-step"]'; +const WORKING = ".tool-line-running"; test("after Allow once, the conversation shows the Bot working until the server's turn ends", async () => { const view = mounting(); diff --git a/app/tests/approval-left-carry-on.test.tsx b/app/tests/approval-left-carry-on.test.tsx index 7b82d5bb27..645e381eb0 100644 --- a/app/tests/approval-left-carry-on.test.tsx +++ b/app/tests/approval-left-carry-on.test.tsx @@ -263,7 +263,7 @@ function mounting() { ); } -const WORKING = '.tool-line-running, [data-slot="live-connector-step"]'; +const WORKING = ".tool-line-running"; /** The person allows the DM, and the server carries the conversation on: shown as working. */ async function allowed(view: ReturnType) { diff --git a/app/tests/carry-on-carried-turn-browser.test.tsx b/app/tests/carry-on-carried-turn-browser.test.tsx index 65cdabcd6b..a0638e5511 100644 --- a/app/tests/carry-on-carried-turn-browser.test.tsx +++ b/app/tests/carry-on-carried-turn-browser.test.tsx @@ -643,7 +643,7 @@ describe.skipIf(!asked)("Carry on while the server carries a turn on", () => { // Allowed: the server carries the conversation on, and the Bot has the turn. await page.getByRole("button", { name: "Allow once" }).click(); await page - .locator('.tool-line-running, [data-slot="live-connector-step"]') + .locator(".tool-line-running") .first() .waitFor({ timeout: 15_000 }); diff --git a/app/tests/carry-on-while-busy.test.tsx b/app/tests/carry-on-while-busy.test.tsx index 4d2ea27141..025022364a 100644 --- a/app/tests/carry-on-while-busy.test.tsx +++ b/app/tests/carry-on-while-busy.test.tsx @@ -360,7 +360,7 @@ function mounting(idle = false) { ); } -const WORKING = '.tool-line-running, [data-slot="live-connector-step"]'; +const WORKING = ".tool-line-running"; test("Carry on pressed while the server still has the turn waits as a queued message, and is sent once when the turn ends", async () => { const view = mounting(); diff --git a/app/tests/coding-tool-cards.test.tsx b/app/tests/coding-tool-cards.test.tsx index 0fcf9aae1a..9aa43c3c1d 100644 --- a/app/tests/coding-tool-cards.test.tsx +++ b/app/tests/coding-tool-cards.test.tsx @@ -3,7 +3,13 @@ import type { Message } from "@ag-ui/core"; import { CopilotKitProvider } from "@copilotkit/react-core/v2"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; import { QueryClientProvider } from "@tanstack/react-query"; -import { cleanup, fireEvent, render, within } from "@testing-library/react"; +import { + cleanup, + fireEvent, + render, + waitFor, + within, +} from "@testing-library/react"; import { ChatTranscript } from "@/components/channels/chat-transcript"; import { CodingTools } from "@/lib/copilot/coding-tools"; import { queryClient } from "@/query-client"; @@ -13,6 +19,7 @@ import { type RecordedCall, recorded, } from "./coding-tools.fixture"; +import { openWorkedFor } from "./open-folds"; import { settleReactWork } from "./settle-react-work"; /** @@ -92,9 +99,17 @@ function draw(messages: Message[], busy = false) { ); } -/** The one card a call drew, found by what it says it did. */ +/** + * The one card a call drew, found by what it says it did: in view, or inside the turn's line opened + * as a person opens it (`TurnLine`), where a step that folds with others is drawn. + */ async function card(view: ReturnType, label: string) { - return within(await view.findByRole("region", { name: label })); + return within( + await waitFor(() => { + openWorkedFor(view.container); + return view.getByRole("region", { name: label }); + }), + ); } /** The coding cards drawn, by what each says it did. Other regions on the page are left out. */ @@ -270,8 +285,8 @@ test("a run of reads and searches is one line, as Claude Code folds it, that ope ], ), ); - const line = await view.findByText("Read 1 file and searched for 4 patterns"); - // One row for the run, not five. + // In a conversation the run is the turn's one line (`TurnLine`): one row for the run, not five. + const line = await view.findByText("Worked through 5 steps"); expect(cards(view)).toEqual([]); // Opened, as a person clicking it does: its steps are drawn once it is. fireEvent.click(line); @@ -311,23 +326,29 @@ test("a coding turn folds only its reads and searches, and keeps every change an "Edited a file", "Ran a command", ]); - // A lone read keeps its own line; the two listings fold into one, which says both didn't work. + // The read and the two listings are the turn's line (`TurnLine`), which opens to them. + fireEvent.click(await view.findByText("Worked through 3 steps")); + // A lone read is its own row; the two listings are a row each, and each says it didn't work. expect(view.getByText("Read 39 lines")).toBeTruthy(); - expect(view.getByText("Listed 2 directories")).toBeTruthy(); - expect(view.getByText("2 issues")).toBeTruthy(); + const steps = view.getByRole("list", { name: "Tool steps" }); + expect(readableLines(steps, ":scope > li")).toEqual([ + "Listedls /definitely/not/hereDidn't work", + "Listedls /definitely/not/hereDidn't work", + ]); }); test("a tool that shares a Claude Code name but not its arguments is drawn as any other tool", async () => { // Another harness's `Bash`, taking `cmd` where Claude Code's takes `command`. const other = { name: "Bash", arguments: JSON.stringify({ cmd: "ls" }) }; const view = draw(turn([other], ["greet.py"])); + fireEvent.click(await view.findByText("Worked through 1 step")); await view.findByText("Bash"); expect(view.queryByRole("region", { name: "Ran a command" })).toBeNull(); cleanup(); // And folds with its neighbours, as a tool the app has no component for does. const two = draw(turn([other, other], ["greet.py", "greet.py"])); - expect(await two.findByText("Used 2 tools")).toBeTruthy(); + expect(await two.findByText("Worked through 2 steps")).toBeTruthy(); expect(cards(two)).toEqual([]); }); diff --git a/app/tests/long-answer-part-steps.test.tsx b/app/tests/long-answer-part-steps.test.tsx index f4b3c66af3..ad7651f6fb 100644 --- a/app/tests/long-answer-part-steps.test.tsx +++ b/app/tests/long-answer-part-steps.test.tsx @@ -2,7 +2,7 @@ import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; import type { Message } from "@ag-ui/core"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { cleanup, fireEvent, render } from "@testing-library/react"; +import { cleanup, fireEvent, render, within } from "@testing-library/react"; import { toVisibleChatItems } from "../src/components/channels/chat-messages"; import { groupToolSteps, @@ -172,8 +172,16 @@ for (const [who, tool] of [ expect(view.getByText("Used Fireflies")).toBeDefined(); // Each read says, in words, which answer it read on in and which part. expect(lines(view)).toEqual([ - "Get transcriptFireflies", - "Read the next part of an answerGet transcript on Fireflies, part 2 of 3", - "Read the next part of an answerGet transcript on Fireflies, part 3 of 3", + "Get transcript", + "Read the next part of an answerGet transcript, part 2 of 3", + "Read the next part of an answerGet transcript, part 3 of 3", ]); + // The line above already shows Fireflies, its logo naming it, so no row draws that logo again. + expect(view.getAllByRole("img", { name: "Fireflies" })).toHaveLength(1); + expect( + within(view.getByRole("list", { name: "Tool steps" })).queryAllByRole( + "img", + { name: "Fireflies" }, + ), + ).toHaveLength(0); }); diff --git a/app/tests/plan-turns.test.ts b/app/tests/plan-turns.test.ts index cc2d8cb3fb..d12eaf46c0 100644 --- a/app/tests/plan-turns.test.ts +++ b/app/tests/plan-turns.test.ts @@ -227,18 +227,39 @@ describe("the plan in a turn's fold", () => { expect(folds.inside.has("g1")).toBe(true); }); - test("folds with the work once the answer is in, and is not counted as a step", () => { + test("folds with a task's work once the answer is in, and is not counted as a step", () => { const items = latestPlanPerTurn([ asked("u1"), plan("p1", ["completed", "completed"]), gmail("g1"), said("a1", "Four drafts are in Gmail."), ]); - const folds = foldTurnWork(items, false, new Set(), "conversation"); + const folds = foldTurnWork(items, false); expect(folds.inside.has("p1")).toBe(true); const work = folds.at.get("p1"); expect(work && stepsIn(work)).toBe(1); }); + + test("stays in view in a conversation, under the turn's line, which holds its steps", () => { + // In a conversation the turn's line is never rebuilt once it ends (`TurnLine`), so the plan the + // person watched fill in stays where it was, under the line, and the line holds the steps. + const g1 = gmail("g1"); + const items = [ + ...latestPlanPerTurn([ + asked("u1"), + plan("p1", ["completed", "completed"]), + ]), + ...(g1.kind === "tool" + ? [{ kind: "tools" as const, id: "group:g1", steps: [g1] }] + : []), + said("a1", "Four drafts are in Gmail."), + ]; + const folds = foldTurnWork(items, false, new Set(), "conversation"); + expect(folds.inside.has("p1")).toBe(false); + expect(folds.inside.has("group:g1")).toBe(true); + const work = folds.under.get("u1"); + expect(work && stepsIn(work)).toBe(1); + }); }); describe("reading a plan", () => { diff --git a/app/tests/reconnecting-line.test.tsx b/app/tests/reconnecting-line.test.tsx index 773f9f229f..dd598d33a7 100644 --- a/app/tests/reconnecting-line.test.tsx +++ b/app/tests/reconnecting-line.test.tsx @@ -172,9 +172,17 @@ function open(agent: DroppingBot) { const SHIMMER = "tool-line-running"; -/** The turn's live line, the one `role="status"` line that shimmers. */ +/** + * The turn's live line, the one `role="status"` line that shimmers: the turn's own line under the + * person's message while nothing has been said after its last step (`TurnLine`, its words the + * status), and the line under the Bot's words once it has said something. + */ function liveLine(): HTMLElement | null { - return document.querySelector(`[role="status"].${SHIMMER}`); + return ( + [...document.querySelectorAll('[role="status"]')].find( + (status) => status.closest(`.${SHIMMER}`) !== null, + ) ?? null + ); } test("while the Bot waits to reconnect, the live line says Reconnecting…, then Thinking again once it is back", async () => { diff --git a/app/tests/reread-steps.test.tsx b/app/tests/reread-steps.test.tsx index b6815ebe43..2418f80f72 100644 --- a/app/tests/reread-steps.test.tsx +++ b/app/tests/reread-steps.test.tsx @@ -2,7 +2,7 @@ import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; import type { Message } from "@ag-ui/core"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { cleanup, fireEvent, render } from "@testing-library/react"; +import { cleanup, fireEvent, render, within } from "@testing-library/react"; import { toVisibleChatItems } from "../src/components/channels/chat-messages"; import { groupToolSteps, @@ -111,11 +111,11 @@ test("a run of rereads is one row that counts them, and a different step between return line.textContent; }); expect(rows).toEqual([ - "Fetch emailsGmail", + "Fetch emails", "Reread 12 earlier results", - "Fetch emailsGmail", + "Fetch emails", "Reread 3 earlier results", - "Fetch emailsGmail", + "Fetch emails", "Reread an earlier result", ]); }); @@ -134,7 +134,11 @@ test("while the last reread runs, the one row says it is rereading", () => { fireEvent(line, new Event("toggle")); expect(view.queryByRole("list", { name: "Working now" })).toBeNull(); expect(view.getByText("Rereading earlier results")).toBeDefined(); - expect(view.getByText("In progress")).toBeDefined(); + expect( + within(view.getByRole("list", { name: "Tool steps" })).getByText( + "In progress", + ), + ).toBeDefined(); expect(view.queryByText("Reread an earlier result")).toBeNull(); expect(view.container.querySelectorAll("ol > li")).toHaveLength(2); }); diff --git a/app/tests/running-step-shimmer.test.tsx b/app/tests/running-step-shimmer.test.tsx index 1fc52f8aba..4e8480b620 100644 --- a/app/tests/running-step-shimmer.test.tsx +++ b/app/tests/running-step-shimmer.test.tsx @@ -3,7 +3,7 @@ import type { Message } from "@ag-ui/core"; import { CopilotKitProvider } from "@copilotkit/react-core/v2"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; import { QueryClientProvider } from "@tanstack/react-query"; -import { cleanup, fireEvent, render } from "@testing-library/react"; +import { cleanup, fireEvent, render, within } from "@testing-library/react"; import { ChatTranscript } from "@/components/channels/chat-transcript"; import { forgetOpenedLines } from "@/components/channels/tool-line"; import { queryClient } from "@/query-client"; @@ -130,41 +130,63 @@ function transcript(messages: Message[], busy: boolean) { const SHIMMER = "tool-line-running"; -test("the running app step shows one progress indicator until it has an answer", async () => { +/** What a row says, as read: its icon is drawn, not read. */ +function said(row: HTMLElement): string { + const copy = row.cloneNode(true) as HTMLElement; + for (const hidden of copy.querySelectorAll("[aria-hidden]")) hidden.remove(); + return copy.textContent ?? ""; +} + +test("the running app step shimmers, beside the steps already done, until it has an answer", async () => { const view = render(transcript(run(false), true)); + // While it works, the turn is one line saying it is using the app, shimmering, folded until it is + // opened (`TurnLine`). + const line = await view.findByText("Using Gmail…"); + expect(line.closest(`.${SHIMMER}`)).not.toBeNull(); + expect(line.closest("details")?.open).toBe(false); + fireEvent.click(line); + // Named as the app's page names it, not in its stored order ("Fetch message by thread id"). const running = await view.findByText("Fetch thread messages"); - const indicator = running.closest('[data-slot="live-connector-step"]'); - expect(indicator?.textContent).toContain("Gmail"); - expect(indicator?.textContent).toContain("In progress"); + expect(running.classList.contains(SHIMMER)).toBe(true); + // Its row says what the finished rows say, in the same order, and that it is under way. The line + // above already shows Gmail, so the row doesn't draw its logo again. + const row = running.parentElement as HTMLElement; + expect(said(row)).toBe("Fetch thread messagesIn progress"); + expect(row.querySelector('[role="img"]')).toBeNull(); // The steps already answered look as they always have. const finished = view.getAllByText("Fetch emails"); expect(finished).toHaveLength(4); - for (const step of finished) + for (const step of finished) { expect(step.classList.contains(SHIMMER)).toBe(false); + expect(step.parentElement?.className).toBe(row.className); + } - // Answered: the step stays in the group and its progress indicator goes away. + // Answered: the step stays in the list and its progress indicator goes, while the line says the + // Bot is thinking about what came back. view.rerender(transcript(run(true), true)); - // The group folds once every step has its answer: opened, the step is in it, still. - fireEvent.click(await view.findByText("Used Gmail")); + expect(await view.findByText("Thinking")).toBeTruthy(); expect( view.getByText("Fetch thread messages").classList.contains(SHIMMER), ).toBe(false); - expect(view.queryByText("In progress")).toBeNull(); + const steps = view.getByRole("list", { name: "Tool steps" }); + expect(within(steps).queryByText("In progress")).toBeNull(); expect(view.queryByRole("list", { name: "Working now" })).toBeNull(); }); test("once every step has its answer and the model is still going, the transcript says it is thinking", async () => { const view = render(transcript(run(true), true)); - expect(await view.findByText("Used Gmail")).toBeTruthy(); - const thinking = view.getByText("Thinking"); + // The turn's line says it, in its own place: not a second line below it. + const thinking = await view.findByText("Thinking"); expect(thinking.getAttribute("role")).toBe("status"); - expect(thinking.classList.contains(SHIMMER)).toBe(true); + expect(thinking.closest(`.${SHIMMER}`)).not.toBeNull(); + expect(view.getAllByRole("status")).toHaveLength(1); - // The turn ends: nothing says it is still working. + // The turn ends: the line says what it did, and nothing says it is still working. view.rerender(transcript(run(true), false)); + expect(await view.findByText("worked through 5 steps")).toBeTruthy(); expect(view.queryByText("Thinking")).toBeNull(); expect(document.querySelector(`.${SHIMMER}`)).toBeNull(); }); diff --git a/app/tests/step-rows-layout.fixture.tsx b/app/tests/step-rows-layout.fixture.tsx index 5aedbbafa8..1c414e4206 100644 --- a/app/tests/step-rows-layout.fixture.tsx +++ b/app/tests/step-rows-layout.fixture.tsx @@ -4,6 +4,7 @@ import { QueryClientProvider } from "@tanstack/react-query"; import { createRoot } from "react-dom/client"; import { ChatTranscript } from "@/components/channels/chat-transcript"; import { TooltipProvider } from "@/components/ui/tooltip"; +import { ComputerTools } from "@/lib/copilot/computer-tools"; import { setCurrentOrganization } from "@/lib/organizations/current"; import { queryClient } from "@/query-client"; import { approvalInboxResponse } from "./approvals-api"; @@ -19,6 +20,8 @@ setCurrentOrganization("default"); * said a line on the way, as Bots now do on a long job, and then read one more page on its own: a * single "Read web pages" line between the Bot's words. `?state=running`: that page is still being * read, in a turn that is still going. `?state=done`: it was read and the Bot answered. + * `?state=tool-then-app`: another turn, which looked for a tool (a step that opens to nothing) and + * then listed events on Google Calendar, and answered. */ type Call = { id: string; name: string; args: unknown; result?: unknown }; @@ -137,9 +140,26 @@ const before: Message[] = [ ]; const messages: Message[] = - state === "running" - ? [...before, ...call(10, { ...READ_ONE, result: undefined })] - : [...before, ...call(10, READ_ONE), ANSWER]; + state === "tool-then-app" + ? [ + ASKED, + ...call(20, { + id: "search", + name: "search_tools", + args: {}, + result: "", + }), + ...call(21, { + id: "list", + name: "mcp__googlecalendar__list_events", + args: { timeMin: "2026-12-06" }, + result: { events: [{ summary: "Design review" }] }, + }), + ANSWER, + ] + : state === "running" + ? [...before, ...call(10, { ...READ_ONE, result: undefined })] + : [...before, ...call(10, READ_ONE), ANSWER]; /** The server, as far as this conversation asks it anything: no approvals are waiting. */ const realFetch = window.fetch.bind(window); @@ -174,6 +194,8 @@ if (root) + {/* The app's own renderers, so the transcript knows which tools it draws itself. */} +
      { const built = await Bun.build({ @@ -170,16 +162,13 @@ async function open( }); }); await page.goto(`${ORIGIN}/?state=${state}`); - if (state === "running") { - // The single line itself, beside the Bot's narration. - await singleLine(page).waitFor(); - } else { - await page.getByText(COMPLETED, { exact: true }).waitFor(); - } - await page - .getByText("press release", { exact: false }) - .first() - .waitFor({ timeout: 15_000 }); + // The turn's one line (`TurnLine`): running, it says what it is doing; done, what it did. + if (state === "running") + await page.locator('[data-slot="worked-for"]').waitFor(); + else + await page + .getByText(state === "done" ? COMPLETED : ON_ONE_APP, { exact: true }) + .waitFor(); await style(page); await page.evaluate(() => document.fonts.ready); await still(page); @@ -211,78 +200,9 @@ async function style(page: Page) { await page.addStyleTag({ content: await stylesheet([...new Set(classes)]) }); } -/** A step line by its words: where its words start, and the icon drawn before them. */ -function line(page: Page, label: string) { - return page.evaluate((label) => { - // A line's own words, not a row of the same name inside what a folded line opens to. - const words = [...document.querySelectorAll("span")].find( - (span) => - span.childElementCount === 0 && - span.textContent === label && - span.closest("li") === null, - ); - if (!words) throw new Error(`no line reading "${label}"`); - const box = words.getBoundingClientRect(); - // The line's own text: its icon, if it has one, and its words. - const icon = words.parentElement?.querySelector("svg") ?? null; - const tile = icon?.parentElement ?? null; - const rounded = (rect: DOMRect) => [ - Math.round(rect.width), - Math.round(rect.height), - ]; - const look = (element: Element | null) => { - if (!element) return null; - const style = getComputedStyle(element); - return { - size: rounded(element.getBoundingClientRect()), - colour: style.color, - background: style.backgroundColor, - radius: style.borderRadius, - }; - }; - return { - // Where the line's first icon starts: a folded line of two kinds has two, so its words start later. - iconLeft: tile ? Math.round(tile.getBoundingClientRect().left) : null, - top: box.top, - icon: look(icon), - tile: look(tile), - // The icon's centre against the words' centre: lined up on the line. - iconOffCentre: icon - ? Math.round( - icon.getBoundingClientRect().top + - icon.getBoundingClientRect().height / 2 - - (box.top + box.height / 2), - ) - : null, - // From the last of the line's icons (a folded line overlaps one per kind) to its words. - wordsFromIcon: - icon && words.previousElementSibling - ? Math.round( - box.left - - words.previousElementSibling.getBoundingClientRect().right, - ) - : null, - }; - }, label); -} - -/** From the foot of the Bot's line on the way to the top of the single page's line. */ -function gapAboveSingle(page: Page) { - return page.evaluate((label) => { - const said = document.querySelector('[data-message-id="on-the-way"]'); - const lastWords = [...(said?.querySelectorAll("p") ?? [])].at(-1); - const words = [...document.querySelectorAll("span")].find( - (span) => - span.childElementCount === 0 && - span.textContent === label && - span.closest("li") === null, - ); - if (!lastWords || !words) throw new Error("no line on the way, or no step"); - return Math.round( - words.getBoundingClientRect().top - - lastWords.getBoundingClientRect().bottom, - ); - }, SINGLE); +/** What the Bot said on the way, between its steps. */ +function onTheWay(page: Page) { + return page.getByText("I'll read the IMF's press release", { exact: false }); } describe.skipIf(!asked)("a Bot's step lines among its words", () => { @@ -291,7 +211,7 @@ describe.skipIf(!asked)("a Bot's step lines among its words", () => { for (const window of WINDOWS) { const where = `in ${engine}, ${theme}, ${window.width}px`; - test(`the current step sits below the Bot's words and folds when the answer is ready, ${where}`, async () => { + test(`the turn is one line while the page is read and once answered, with the Bot's words on the way inside it, ${where}`, async () => { const running = await open(engine, theme, window, "running"); const done = await open(engine, theme, window, "done"); try { @@ -308,62 +228,88 @@ describe.skipIf(!asked)("a Bot's step lines among its words", () => { ), }); } - const whileRunning = await gapAboveSingle(running); - expect(whileRunning).toBeGreaterThan(0); - expect(whileRunning).toBeLessThanOrEqual(40); + for (const page of [running, done]) { + // One line for the turn, and what the Bot said on the way is behind it, not beside it. + expect( + await page.locator('[data-slot="worked-for"]').count(), + ).toBe(1); + expect(await onTheWay(page).isVisible()).toBe(false); + } + expect(await running.getByText(/…$/).first().isVisible()).toBe( + true, + ); const summary = done .locator('[data-slot="worked-for"] summary') - .filter({ - hasText: COMPLETED, - }); + .filter({ hasText: COMPLETED }); expect(await summary.count()).toBe(1); - expect(await singleLine(done).isVisible()).toBe(false); + // The answer is in view; opened, the line shows the words on the way and the page read. expect( - await done.locator('[data-message-id="on-the-way"]').isVisible(), + await done + .getByText("weaker trade", { exact: false }) + .isVisible(), ).toBe(true); await summary.click(); - expect(await singleLine(done).isVisible()).toBe(true); + await style(done); + await onTheWay(done).waitFor(); + expect(await onTheWay(done).isVisible()).toBe(true); + // Inside the line, not a row of the conversation of its own. + expect( + await onTheWay(done).evaluate( + (words) => words.closest('[data-slot="worked-for"]') !== null, + ), + ).toBe(true); } finally { await running.close(); await done.close(); } }, 60_000); - test(`a single "${SINGLE}" line has the icon the folded line beside it has, ${where}`, async () => { - const running = await open(engine, theme, window, "running"); - const done = await open(engine, theme, window, "done"); + test(`a step that doesn't open draws its mark where the chevrons of the rows that open are, and its words start where theirs do, ${where}`, async () => { + const page = await open(engine, theme, window, "tool-then-app"); try { - // The single line and earlier folded group use the same icon treatment while working. - const { icon, tile, iconOffCentre, wordsFromIcon } = await line( - running, - FOLDED, - ); - const single = await line(running, SINGLE); - expect(single.icon).not.toBeNull(); - expect(single).toMatchObject({ - icon, - tile, - iconOffCentre, - wordsFromIcon, - }); - // Its completed disclosure preserves the treatment when the work is reopened. - await done + await page .locator('[data-slot="worked-for"] summary') - .filter({ - hasText: COMPLETED, - }) + .filter({ hasText: ON_ONE_APP }) .click(); - // A finished turn's rows are drawn once it is opened, so styled once they are. - await style(done); - expect(await line(done, SINGLE)).toMatchObject({ - icon: single.icon, - tile: single.tile, - iconOffCentre: single.iconOffCentre, - wordsFromIcon: single.wordsFromIcon, + await page.getByText("List events", { exact: true }).waitFor(); + await style(page); + await still(page); + const placed = await page.evaluate(() => { + const rows = [ + ...document.querySelectorAll( + '[data-slot="worked-for"] ol[aria-label="Tool steps"] > li', + ), + ]; + const row = (words: string) => { + const li = rows.find((one) => one.textContent?.includes(words)); + const label = [...(li?.querySelectorAll("span") ?? [])].find( + (span) => + span.childElementCount === 0 && span.textContent === words, + ); + return { li, label }; + }; + const looked = row("Looked for a tool"); + const listed = row("List events"); + const mark = looked.li?.querySelector("svg"); + const chevron = listed.li?.querySelector(".tool-line-chevron"); + if (!mark || !chevron || !looked.label || !listed.label) + throw new Error("no wrench, chevron or words"); + const centre = (element: Element) => { + const box = element.getBoundingClientRect(); + return box.left + box.width / 2; + }; + return { + markOffChevron: Math.abs(centre(mark) - centre(chevron)), + wordsApart: Math.abs( + looked.label.getBoundingClientRect().left - + listed.label.getBoundingClientRect().left, + ), + }; }); + expect(placed.markOffChevron).toBeLessThan(1); + expect(placed.wordsApart).toBeLessThan(1); } finally { - await running.close(); - await done.close(); + await page.close(); } }, 60_000); } diff --git a/app/tests/subtask-step.test.tsx b/app/tests/subtask-step.test.tsx index 4caee8fb2b..d4e5794201 100644 --- a/app/tests/subtask-step.test.tsx +++ b/app/tests/subtask-step.test.tsx @@ -182,7 +182,8 @@ async function subtaskRow(view: Awaited>) { test("a subtask is one step of the turn's work line, not a card of its own", async () => { const view = await draw(answered, { settled: true, busy: false }); - expect(await view.findByText("Ran a subtask")).toBeTruthy(); + // A step of the turn's one line (`TurnLine`), which counts it. + expect(await view.findByText("Worked through 1 step")).toBeTruthy(); expect(view.container.querySelector("figure")).toBeNull(); // Opened, its own line says what it was asked and how many steps it took. await openWork(view); diff --git a/app/tests/task-worked-for.test.tsx b/app/tests/task-worked-for.test.tsx index 4fe3049631..0ce76c1e1d 100644 --- a/app/tests/task-worked-for.test.tsx +++ b/app/tests/task-worked-for.test.tsx @@ -174,7 +174,7 @@ test("a finished turn folds its steps and what it said on the way into one Worke const view = draw(); await waitFor(() => - expect(workedFor(view.container)?.textContent).toContain("Worked for 52s"), + expect(workedFor(view.container)?.textContent).toContain("worked for 52s"), ); const row = workedFor(view.container); if (!row) throw new Error("No Worked for row."); @@ -192,7 +192,7 @@ test("a finished turn folds its steps and what it said on the way into one Worke ).toBeTruthy(); // It opens to the steps and the line said on the way, drawn once it is opened. - await userEvent.click(view.getByText("Worked for 52s")); + await userEvent.click(view.getByText("worked for 52s")); expect(fold?.open).toBe(true); await waitFor(() => expect(fold?.textContent).toContain(NARRATION)); }); @@ -202,7 +202,7 @@ test("a turn the server has not listed says how many steps it took", async () => const view = draw(); await waitFor(() => expect(workedFor(view.container)?.textContent).toContain( - "Worked through 1 step", + "worked through 1 step", ), ); expect(view.getByText(ANSWER)).toBeTruthy(); diff --git a/app/tests/tool-line-reduced-motion.test.tsx b/app/tests/tool-line-reduced-motion.test.tsx index 189b9b4fa8..e3368b5d6f 100644 --- a/app/tests/tool-line-reduced-motion.test.tsx +++ b/app/tests/tool-line-reduced-motion.test.tsx @@ -139,8 +139,9 @@ for (const engine of engines) (probe) => getComputedStyle(probe).color, ); const lines = await painted(page); + // A running line also says "In progress" to a screen reader, which sees no shimmer. expect(lines.map((line) => line.text)).toEqual([ - "Asked youWhich city should I search?", + "Asked youWhich city should I search?In progress", "Asking Ana…", ]); for (const line of lines) { diff --git a/app/tests/tool-result-parts.test.tsx b/app/tests/tool-result-parts.test.tsx index 6f524cdb95..1b966aeb7f 100644 --- a/app/tests/tool-result-parts.test.tsx +++ b/app/tests/tool-result-parts.test.tsx @@ -3,7 +3,7 @@ import type { Message } from "@ag-ui/core"; import { CopilotKitProvider } from "@copilotkit/react-core/v2"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; import { QueryClientProvider } from "@tanstack/react-query"; -import { cleanup, fireEvent, render } from "@testing-library/react"; +import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; import { toVisibleChatItems } from "@/components/channels/chat-messages"; import { ChatTranscript } from "@/components/channels/chat-transcript"; import { dropRepeatedAppCards } from "@/components/channels/tool-activity"; @@ -126,7 +126,7 @@ test("a stored Read of a picture opens, and draws the Read step and the reply", const view = draw(read.messages); expect(await view.findByText("It is a ribbon diagram.")).toBeTruthy(); // The finished turn's work is folded; opened, as a person does, it shows the Read step. - fireEvent.click(view.getByText("Worked through 1 step")); + fireEvent.click(view.getByText(/^worked through 1 step$/i)); expect(await view.findByText("model2.png")).toBeTruthy(); expect(view.getByText("Read")).toBeTruthy(); expect(view.getByText("Returned an image.")).toBeTruthy(); @@ -141,8 +141,9 @@ test("a result in several text parts reads as those parts, a paragraph each", as const view = draw(read.messages); expect(await view.findByText("It is a ribbon diagram.")).toBeTruthy(); - fireEvent.click(view.getByText("Worked through 1 step")); - expect(await view.findByText("Search")).toBeTruthy(); + fireEvent.click(view.getByText(/^worked through 1 step$/i)); + // An app's step in the line is a row that opens to its answer, as a person opens it. + fireEvent.click(await view.findByText("Search")); // Each part its own paragraph: run together, they read "Found 2 pages Ribbon diagrams …". expect(view.getByText("Found 2 pages").tagName).toBe("P"); expect(view.getByText("Ribbon diagrams Protein folds").tagName).toBe("P"); @@ -158,9 +159,12 @@ test("a live result that is a JSON object is drawn as JSON", async () => { const view = draw(live); expect(await view.findByText("It is a ribbon diagram.")).toBeTruthy(); - fireEvent.click(view.getByText("Worked through 1 step")); - expect(await view.findByText("Lookup rows")).toBeTruthy(); - expect(view.container.textContent).toContain('"rows": 2'); + fireEvent.click(view.getByText(/^worked through 1 step$/i)); + // A step of the turn's line, which opens to what it was given and what came back (`StepRow`). + fireEvent.click(await view.findByText("Lookup rows")); + await waitFor(() => + expect(view.container.textContent).toContain('"rows": 2'), + ); }); test("the result readers take a list of parts as text", () => { diff --git a/app/tests/transcript-attachments.test.tsx b/app/tests/transcript-attachments.test.tsx index 182b755aa9..b6e08e3fe5 100644 --- a/app/tests/transcript-attachments.test.tsx +++ b/app/tests/transcript-attachments.test.tsx @@ -311,6 +311,7 @@ test("a turn that is only an attachment is still waited on", () => { { busy: true }, ); + // The turn's line, under the attachment, from the moment it is sent (`TurnLine`). expect(getByRole("status").textContent).toBe("Thinking"); }); diff --git a/app/tests/turn-line-layout.fixture.tsx b/app/tests/turn-line-layout.fixture.tsx new file mode 100644 index 0000000000..0294906d15 --- /dev/null +++ b/app/tests/turn-line-layout.fixture.tsx @@ -0,0 +1,199 @@ +import type { Message } from "@ag-ui/core"; +import { CopilotKitProvider } from "@copilotkit/react-core/v2"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { useState } from "react"; +import { createRoot } from "react-dom/client"; +import { ChatTranscript } from "@/components/channels/chat-transcript"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { ComputerTools } from "@/lib/copilot/computer-tools"; +import { setCurrentOrganization } from "@/lib/organizations/current"; +import { queryClient } from "@/query-client"; +import { approvalInboxResponse } from "./approvals-api"; + +// The organization the fake server answers for, as every test starts in (tests/preload.ts). +setCurrentOrganization("default"); + +/** + * One conversation turn from the moment it is sent to its answer, as a page of its own for + * turn-line-layout.test.tsx to bundle and load in a real browser, then step through. + * + * Asked what is on their calendar tomorrow, the Bot looked for a tool, said what day tomorrow is, + * listed events on Google Calendar and answered: the run a person filmed when the turn was drawn one + * way while it ran and rebuilt another way once it ended. `window.__moment(n)` draws the turn as it + * stood at its nth moment; `window.__moments` says how many there are. + */ + +type Call = { id: string; name: string; args: unknown; result?: unknown }; + +function call(index: number, { id, name, args, result }: Call): Message[] { + return [ + { + id: `a-${index}`, + role: "assistant", + content: "", + toolCalls: [ + { + id, + type: "function", + function: { name, arguments: JSON.stringify(args) }, + }, + ], + }, + ...(result === undefined + ? [] + : [ + { + id: `t-${index}`, + role: "tool" as const, + toolCallId: id, + content: + typeof result === "string" ? result : JSON.stringify(result), + }, + ]), + ]; +} + +const ASKED: Message = { + id: "u1", + role: "user", + content: "what's on my calendar tomorrow?", +}; +const SEARCH: Call = { + id: "search", + name: "search_tools", + args: { query: "google calendar find events", limit: 5 }, + result: '[{"name":"GOOGLECALENDAR_EVENTS_LIST"}]', +}; +const ON_THE_WAY: Message = { + id: "on-the-way", + role: "assistant", + content: "Tomorrow is Sunday 2026-12-06 (Pacific, UTC-8).", +}; +const LIST: Call = { + id: "list", + name: "mcp__googlecalendar__list_events", + args: { timeMin: "2026-12-06T00:00:00-08:00" }, + result: { items: [{ summary: "Design review" }, { summary: "Focus block" }] }, +}; +const STARTED: Message = { + id: "answer", + role: "assistant", + content: "Tomorrow", +}; +const ANSWER: Message = { + ...STARTED, + content: + "Tomorrow (Sunday, Dec 6) you have two events: a design review at 9:30 and a focus block at 6.", +}; + +/** The turn at each moment of its run, and whether the Bot was still working on it. */ +const MOMENTS: { busy: boolean; messages: Message[] }[] = [ + // Sent, nothing back yet: "Thinking". + { busy: true, messages: [ASKED] }, + // Looking for a tool. + { + busy: true, + messages: [ASKED, ...call(0, { ...SEARCH, result: undefined })], + }, + // It found one, and the Bot is thinking. + { busy: true, messages: [ASKED, ...call(0, SEARCH)] }, + // It said what day tomorrow is, and is listing events. + { + busy: true, + messages: [ + ASKED, + ...call(0, SEARCH), + ON_THE_WAY, + ...call(1, { ...LIST, result: undefined }), + ], + }, + // The events are in. + { + busy: true, + messages: [ASKED, ...call(0, SEARCH), ON_THE_WAY, ...call(1, LIST)], + }, + // The answer starts. + { + busy: true, + messages: [ + ASKED, + ...call(0, SEARCH), + ON_THE_WAY, + ...call(1, LIST), + STARTED, + ], + }, + // Done. + { + busy: false, + messages: [ASKED, ...call(0, SEARCH), ON_THE_WAY, ...call(1, LIST), ANSWER], + }, +]; + +declare global { + interface Window { + __moment?: (moment: number) => void; + __moments?: number; + } +} +window.__moments = MOMENTS.length; + +/** The server, as far as this conversation asks it anything: no approvals are waiting. */ +const realFetch = window.fetch.bind(window); +window.fetch = (async ( + input: Parameters[0], + init?: RequestInit, +) => { + const url = new URL( + typeof input === "string" + ? input + : input instanceof URL + ? input.href + : input.url, + location.origin, + ); + const approvals = approvalInboxResponse(url.pathname, { + enabled: false, + requests: [], + rules: [], + teamRules: [], + questions: [], + }); + if (approvals) return approvals; + if (url.origin === location.origin) + return Response.json({ error: "not served" }, { status: 404 }); + return realFetch(input, init); +}) as typeof fetch; + +function Turn() { + const [moment, setMoment] = useState(0); + window.__moment = setMoment; + const now = MOMENTS[moment] ?? MOMENTS[0]; + return ( +
      + +
      + ); +} + +const root = document.getElementById("root"); +if (root) + createRoot(root).render( + + + + {/* The app's own renderers, so the transcript knows which tools it draws itself. */} + + + + + , + ); diff --git a/app/tests/turn-line-layout.test.tsx b/app/tests/turn-line-layout.test.tsx new file mode 100644 index 0000000000..017cb886d6 --- /dev/null +++ b/app/tests/turn-line-layout.test.tsx @@ -0,0 +1,338 @@ +import { afterAll, beforeAll, describe, expect } from "bun:test"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import type { Browser, BrowserType, Page } from "playwright-core"; +import { compile } from "tailwindcss"; +import { marksPlugin } from "./marks-plugin"; +import { test } from "./renderer-crash"; + +/** + * A conversation turn is one line under the person's message, from the moment they send it to its + * answer and after, and the line never moves: only its words and its mark change. + * + * Filmed from a real run ("what's on my calendar tomorrow?"), a turn was drawn one way while the + * Bot worked and rebuilt another way once it ended: a "Thinking" paragraph, a line for the tool + * search in a gray disc, "Thinking" again, a line for the app's step with no logo that jumped left + * when its logo came, a chevron that pushed it right when the step was done, and at the end one + * "Worked through 2 steps" line rebuilt in the place of the first step, above what the Bot had said + * on the way. Every frame was plausible; every transition jumped. + * + * The real transcript is drawn in a real browser, bundled from the fixture beside this file, with + * the app's stylesheet, and stepped through the run's moments: sent, looking for a tool, thinking, + * listing events, thinking, answering, done. At each one there is one line, the first thing under + * the person's message, with its mark and its words where they were at the first moment, and the + * message above it where it was. A phone's width and a laptop's, light and dark. + * + * OPENBOT_APP_BROWSER=1 bun test app/tests/turn-line-layout.test.tsx + * + * Chromium by default, as CI has it. OPENBOT_APP_ENGINES=chromium,webkit adds WebKit. With + * OPENBOT_APP_SHOTS= each moment is saved as turn-line----.png. + */ +const asked = process.env.OPENBOT_APP_BROWSER === "1"; +const shots = process.env.OPENBOT_APP_SHOTS; +const engines = (process.env.OPENBOT_APP_ENGINES ?? "chromium") + .split(",") + .map((engine) => engine.trim()) + .filter((engine) => engine === "chromium" || engine === "webkit") as ( + | "chromium" + | "webkit" +)[]; + +const APP = join(import.meta.dir, ".."); +const ORIGIN = "http://openbot.test"; +const THEMES = ["light", "dark"] as const; +const WINDOWS = [ + { width: 400, height: 860 }, + { width: 1440, height: 900 }, +]; +type Theme = (typeof THEMES)[number]; + +/** What the line says at each moment of the run, in order. */ +const SAYS = [ + /^ThinkingIn progress$/, + /^Looking for a tool…/, + /^ThinkingIn progress$/, + /^Using Googlecalendar…|^Using Google Calendar…/, + /^ThinkingIn progress$/, + // The app's name, then what was done, on the sentence. + /^Google ?[Cc]alendarworked through 2 steps/, + /^Google ?[Cc]alendarworked through 2 steps/, +]; + +async function bundle(): Promise { + const built = await Bun.build({ + entrypoints: [join(import.meta.dir, "turn-line-layout.fixture.tsx")], + target: "browser", + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + plugins: [marksPlugin], + }); + if (!built.success) throw new AggregateError(built.logs, "bundle failed"); + const script = built.outputs.find((output) => output.kind === "entry-point"); + if (!script) throw new Error("bundle has no entry point"); + return script.text(); +} + +/** The directory of an installed package, from the app or the repository root. */ +function packageDir(name: string): string { + const dir = [ + join(APP, "node_modules", name), + join(APP, "..", "node_modules", name), + ].find(existsSync); + if (!dir) throw new Error(`no package ${name}`); + return dir; +} + +/** Where `@import "[/]"` lands, by the package's `style` export as Vite reads it. */ +function packageStylesheet(id: string): string { + const parts = id.split("/"); + const name = id.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]; + const dir = packageDir(name); + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + const subpath = `.${id.slice(name.length)}`; + const entry = pkg.exports?.[subpath]; + const file = + typeof entry === "string" + ? entry + : (entry?.style ?? entry?.default ?? pkg.main ?? "index.css"); + return join(dir, file); +} + +/** The app's stylesheet, built by Tailwind for these classes, as the app's build does. */ +async function stylesheet(classes: string[]): Promise { + const tailwind = dirname(Bun.resolveSync("tailwindcss/package.json", APP)); + const entry = join(APP, "src", "styles.css"); + const compiler = await compile(readFileSync(entry, "utf8"), { + base: dirname(entry), + loadStylesheet: async (id, base) => { + const path = + id === "tailwindcss" + ? join(tailwind, "index.css") + : id.startsWith(".") + ? join(base, id) + : packageStylesheet(id); + return { path, base: dirname(path), content: readFileSync(path, "utf8") }; + }, + }); + return compiler.build(classes); +} + +const browsers = new Map(); +let script: string; + +beforeAll(async () => { + if (!asked) return; + script = await bundle(); + const playwright = await import("playwright-core"); + for (const engine of engines) { + const type: BrowserType = playwright[engine]; + browsers.set( + engine, + // The CI job installs full Chromium without the headless shell. + await type.launch(engine === "chromium" ? { channel: "chromium" } : {}), + ); + } +}, 120_000); + +afterAll(async () => { + for (const browser of browsers.values()) await browser.close(); +}); + +async function open( + engine: string, + theme: Theme, + window: { width: number; height: number }, +): Promise { + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage({ + viewport: window, + colorScheme: theme, + reducedMotion: "reduce", + }); + page.on("pageerror", (error) => console.error(error)); + const figtree = join(packageDir("@fontsource-variable/figtree"), "files"); + await page.route(`${ORIGIN}/**`, (route) => { + const path = new URL(route.request().url()).pathname; + if (path === "/turn.js") + return route.fulfill({ contentType: "text/javascript", body: script }); + const font = join(figtree, path.split("/").pop() ?? ""); + if (path.startsWith("/files/") && existsSync(font)) + return route.fulfill({ path: font }); + if (path.startsWith("/api/")) return route.fulfill({ status: 404 }); + return route.fulfill({ + contentType: "text/html", + body: `
      `, + }); + }); + await page.goto(`${ORIGIN}/`); + await page.locator('[data-slot="worked-for"]').waitFor(); + await page.evaluate(() => document.fonts.ready); + return page; +} + +/** Until nothing on the page is moving, endless shimmers aside. */ +async function still(page: Page) { + await page.waitForFunction(() => + document + .getAnimations() + .every( + (animation) => + animation.playState !== "running" || + animation.timeline !== document.timeline || + animation.effect?.getComputedTiming().endTime === + Number.POSITIVE_INFINITY, + ), + ); +} + +/** Styles the classes the page draws now: each moment can draw some the one before did not. */ +async function style(page: Page) { + const classes = await page.evaluate(() => + [...document.querySelectorAll("[class]")].flatMap((element) => [ + ...element.classList, + ]), + ); + await page.addStyleTag({ content: await stylesheet([...new Set(classes)]) }); +} + +/** Draws the turn as it stood at one moment of its run, styled and settled. */ +async function moment(page: Page, n: number) { + await page.evaluate((n) => window.__moment?.(n), n); + await page.locator(`main[data-moment="${n}"]`).waitFor(); + await style(page); + await still(page); +} + +/** Where the person's message, the turn's line, its mark and its words are, and what it says. */ +function measure(page: Page) { + return page.evaluate(() => { + const lines = [...document.querySelectorAll('[data-slot="worked-for"]')]; + const line = lines[0]; + if (!line) throw new Error("no turn line"); + const mark = line.querySelector("span.self-center"); + const words = mark?.nextElementSibling; + if (!mark || !words) throw new Error("the line has no mark or no words"); + const asked = [...document.querySelectorAll("[data-message-id]")].find( + (row) => row.textContent?.includes("what's on my calendar tomorrow?"), + ); + if (!asked) throw new Error("no message"); + // The line is the first thing under the message: no row of the turn is drawn between them. + const row = line.closest("[data-message-id]"); + const rows = [...document.querySelectorAll("[data-message-id]")]; + const round = (value: number) => Math.round(value * 10) / 10; + return { + lines: lines.length, + next: rows.indexOf(row as Element) - rows.indexOf(asked), + // Its words, after its mark (an app with no logo yet draws its initial there). + says: (mark.parentElement?.textContent ?? "") + .slice(mark.textContent?.length ?? 0) + .trim(), + top: round(line.getBoundingClientRect().top), + markLeft: round(mark.getBoundingClientRect().left), + markWidth: round(mark.getBoundingClientRect().width), + wordsLeft: round(words.getBoundingClientRect().left), + askedTop: round(asked.getBoundingClientRect().top), + }; + }); +} + +/** + * While the line says "Thinking": its words look exactly as main's "Thinking" under a message does + * (a `

      `, drawn here beside it to + * compare), with no icon beside them, and the shimmer sweeps the line, not the one word. + */ +function thinkingLook(page: Page) { + return page.evaluate(() => { + const line = document.querySelector('[data-slot="worked-for"]'); + const words = line?.querySelector('[role="status"]'); + const shimmer = words?.closest(".tool-line-running"); + if (!line || !words || !shimmer) throw new Error("no Thinking line"); + const main = document.createElement("p"); + main.className = "tool-line-running text-muted-foreground text-sm"; + main.textContent = "Thinking"; + line.parentElement?.append(main); + const look = (element: Element) => { + const style = getComputedStyle(element); + return [ + style.fontFamily, + style.fontSize, + style.fontWeight, + style.lineHeight, + style.letterSpacing, + style.color, + ]; + }; + const result = { + words: words.textContent, + look: look(words), + main: look(main), + // Nothing in the mark's room: the chevron is the line's, not a mark beside the word. + icons: line.querySelectorAll("span.self-center svg, span.self-center img") + .length, + shimmerShare: + shimmer.getBoundingClientRect().width / + line.getBoundingClientRect().width, + }; + main.remove(); + return result; + }); +} + +describe.skipIf(!asked)("a conversation turn's one line", () => { + for (const engine of engines) + for (const theme of THEMES) + for (const size of WINDOWS) + test(`stays where it was made, from send to done, ${engine}, ${theme}, ${size.width}px`, async () => { + const page = await open(engine, theme, size); + const count = await page.evaluate(() => window.__moments ?? 0); + expect(count).toBe(SAYS.length); + const seen: Awaited>[] = []; + for (let n = 0; n < count; n += 1) { + await moment(page, n); + seen.push(await measure(page)); + if (n === 0 || n === 2 || n === 4) { + const thinking = await thinkingLook(page); + const said = `at moment ${n}`; + expect(thinking.words, said).toBe("Thinking"); + expect(thinking.look, said).toEqual(thinking.main); + expect(thinking.icons, said).toBe(0); + expect(thinking.shimmerShare, said).toBeGreaterThan(0.8); + } + if (shots) { + mkdirSync(shots, { recursive: true }); + await page.screenshot({ + path: join( + shots, + `turn-line-${engine}-${theme}-${size.width}-${n}.png`, + ), + }); + } + } + const [first] = seen; + if (!first) throw new Error("no moments"); + seen.forEach((now, n) => { + const said = `at moment ${n}, "${now.says}"`; + expect(now.says, said).toMatch(SAYS[n] as RegExp); + // One line, right under the message, at every moment. + expect(now.lines, said).toBe(1); + expect(now.next, said).toBe(1); + // Nothing moves: not the message, not the line, not its mark, not its words. + expect(Math.abs(now.askedTop - first.askedTop), said).toBeLessThan( + 1, + ); + expect(Math.abs(now.top - first.top), said).toBeLessThan(1); + expect(Math.abs(now.markLeft - first.markLeft), said).toBeLessThan( + 1, + ); + expect( + Math.abs(now.markWidth - first.markWidth), + said, + ).toBeLessThan(1); + expect( + Math.abs(now.wordsLeft - first.wordsLeft), + said, + ).toBeLessThan(1); + }); + await page.close(); + }, 60_000); +}); diff --git a/app/tests/work-folded.test.tsx b/app/tests/work-folded.test.tsx index 58667d3ece..db6ff1a22a 100644 --- a/app/tests/work-folded.test.tsx +++ b/app/tests/work-folded.test.tsx @@ -169,7 +169,7 @@ function lineOf(fold: HTMLDetailsElement): string { return summary.textContent ?? ""; } -test("regular chat folds finished app calls and keeps all answer text outside", async () => { +test("a conversation turn is one line from the start, which folds its app calls and what was said on the way, and keeps the answer outside", async () => { const [ask, ...steps] = conversation([ { id: "notion-1", @@ -191,25 +191,37 @@ test("regular chat folds finished app calls and keeps all answer text outside", ...steps, { id: "after", role: "assistant", content: "The busiest day was Tuesday." }, ]; - const view = render(transcript([ask, ...steps.slice(0, 1)], true)); - expect(view.container.querySelector('[data-slot="worked-for"]')).toBeNull(); - expect(view.container.querySelector('img[src*="notion.svg"]')).not.toBeNull(); - expect(view.getByText("Notion")).toBeTruthy(); - expect(view.getByText("Search pages")).toBeTruthy(); - expect(view.getByText("In progress")).toBeTruthy(); + // Sent: the turn's line says it is thinking, in its place under the message (`TurnLine`). + const view = render(transcript([ask], true)); + const lines = () => + view.container.querySelectorAll('[data-slot="worked-for"]'); + expect(await view.findByText("Thinking")).toBeTruthy(); + expect(lines()).toHaveLength(1); + // A step runs: the same line says the app it is using, by its logo, which says its name. + view.rerender(transcript([ask, ...steps.slice(0, 1)], true)); + expect(await view.findByText("Using Notion…")).toBeTruthy(); + expect(view.getByRole("img", { name: "Notion" })).toBeTruthy(); + expect(lines()).toHaveLength(1); + + // Two calls on Notion while the turn runs: the line opens to its steps. view.rerender(transcript([ask, ...steps.slice(0, 3)], true)); + fireEvent.click(await view.findByText("Using Notion…")); const liveSteps = view.getByRole("list", { name: "Tool steps" }); expect(liveSteps.textContent).toContain("Get page"); expect(view.getAllByText("Get page")).toHaveLength(1); + fireEvent.click(view.getByText("Using Notion…")); + // Answered: still the one line, saying what was done beside Notion's logo. What the Bot said + // before its steps is inside it, said on the way; its answer, after them, is outside. view.rerender(transcript(messages)); + expect(lines()).toHaveLength(1); const fold = view.container.querySelector( '[data-slot="worked-for"] details', ); expect(fold?.open).toBe(false); expect(fold?.querySelector("summary")?.textContent).toContain( - "Worked through 2 steps", + "Notionworked through 2 steps", ); expect(fold?.querySelector('summary img[src*="notion.svg"]')).not.toBeNull(); fireEvent.click(fold?.querySelector("summary") as HTMLElement); @@ -218,7 +230,7 @@ test("regular chat folds finished app calls and keeps all answer text outside", expect(completedSteps.textContent).toContain("Get page"); expect( (await view.findByText("Here are the figures.")).closest("details"), - ).toBeNull(); + ).toBe(fold); expect( (await view.findByText("The busiest day was Tuesday.")).closest("details"), ).toBeNull(); @@ -267,7 +279,8 @@ test("a command still running shimmers on its line, and goes still when it is do const view = render(transcript(conversation([ranCommand("run-3")]), true)); const running = await foldOf(view, "Ran a command"); expect(running.open).toBe(false); - expect(lineOf(running)).toBe(`Running a command${COMMAND}`); + // A screen reader, which hears no shimmer, is told it is under way. + expect(lineOf(running)).toBe(`Running a command${COMMAND}In progress`); expect( running.querySelector("summary .tool-line-running")?.textContent, ).toContain("Running a command");