diff --git a/app/src/components/channels/chat-transcript.tsx b/app/src/components/channels/chat-transcript.tsx index 73d48f1f55..5d40e18203 100644 --- a/app/src/components/channels/chat-transcript.tsx +++ b/app/src/components/channels/chat-transcript.tsx @@ -28,7 +28,7 @@ import { ownToolSubject, readToolName, } from "@openbot/shared/tool-name"; -import { SEARCH_TOOLS, toolsFound } from "@openbot/shared/tool-search"; +import { SEARCH_TOOLS } from "@openbot/shared/tool-search"; import { QueryClientContext, useQuery } from "@tanstack/react-query"; import { motion, useReducedMotion } from "motion/react"; import { @@ -202,16 +202,24 @@ import { } from "./telemetry-assistant-message"; import { ActivityAppMarks, + AppMark, + appOfCall, attachmentReadName, dropRepeatedAppCards, + foundToolsInWords, groupToolSteps, - LiveConnectorStep, + isSubtaskCall, + LineWaiting, + rowApps, ServerStepIcon, + SubtaskRows, ToolActivity, type ToolGroup, type TranscriptItem, + useAppName, useDrawnTool, useReportsDesktopActivity, + type Waiting, } from "./tool-activity"; import { ToolRenderBoundary, toolCallFinal } from "./tool-boundary"; import { DrawnWhenOpened, ToolLine } from "./tool-line"; @@ -1949,7 +1957,6 @@ const ToolCallBody = memo(function ToolCallBody({ result, latest, spokeAfter, - liveConnector, }: { toolCallId: string; name: string; @@ -1959,7 +1966,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 +2035,6 @@ const ToolCallBody = memo(function ToolCallBody({ ) : ( { const other = b.steps[index]; @@ -2123,6 +2135,35 @@ export function sameToolRow(a: ToolRowProps, b: ToolRowProps): boolean { ); } +/** + * Whether a row of calls is drawn as steps (`ToolActivity`), not as a lone call's own line or card + * (`ToolCallBody`). A run is steps, and so is a lone browser step, and a subtask, which is drawn as + * work even alone, so a second call joining it does not change its shape. + * + * A LONE STEP ON AN APP IS ITS APP'S LINE FROM ITS FIRST FRAME (`folds`). "Fetch emails", alone, was + * a line of its own; when the Bot fetched again, the two were a run, and a run is its app's line, so + * the same row read "Fetch emails", then "Using Gmail…". Now it is "Using Gmail…" from the first + * call, "Used Gmail" once answered, and opens to "Fetch emails": a second call joins it and only the + * list under it grows. + * + * `openAmongRows`: drawn open among a conversation's "Worked for" line's rows, where a lone call the + * server ran is a step as theirs are. "Looked for a tool" was a muted line in a gray circle, a gap + * above "Find free slots"; it is one more entry in the list, with its own mark. A call the app draws + * itself (a command and its terminal) keeps its own card there. + */ +function drawnAsSteps( + steps: ToolGroup["steps"], + isDrawn: (name: string) => boolean, + { folds, openAmongRows }: { folds: boolean; openAmongRows: boolean }, +): boolean { + const [only] = steps; + if (steps.length !== 1 || !only || isBrowserStep(only)) return true; + const name = only.toolCall.function.name; + if (name === SUBAGENT_TOOL) return true; + if (folds && appOfCall(name)) return true; + return openAmongRows && (name.startsWith("mcp__") || !isDrawn(name)); +} + const ToolRow = memo(function ToolRow({ id, steps, @@ -2130,38 +2171,44 @@ const ToolRow = memo(function ToolRow({ inFlight, latest, spokeAfter, - conversation, expanded, + folds, workAlone, + thinking, }: ToolRowProps) { const [only] = steps; + const isDrawn = useDrawnTool(); useReportsDesktopActivity(steps, active); return ( - {steps.length === 1 && - only && + {only && !workAlone && - !isBrowserStep(only) && - // 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 ? ( + !drawnAsSteps(steps, isDrawn, { + folds: Boolean(folds), + openAmongRows: Boolean(expanded && folds), + }) ? ( - + + + + ) : !expanded && steps.every(isSubtaskCall) ? ( + // Subtasks are rows of their own, each opened to its steps (`SubtaskRows`). + ) : ( )} @@ -2182,7 +2229,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,9 +2236,10 @@ 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; + // Answered, and the Bot is working out its next move: this line says so (`LineWaiting`). + const waiting = useContext(LineWaiting); // Cut off with its outcome unknown: named as it is while under way, since nobody knows it was done. const interrupted = cutOffStep(result); const named = readToolName(name, running || interrupted); @@ -2200,10 +2247,14 @@ export function ServerToolLine({ const appId = !role && name.startsWith("mcp__") ? name.split("__")[1] : undefined; const folders = useContext(FolderNamesContext); + const appName = useAppName(); // 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 +2313,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 @@ -2308,14 +2353,22 @@ export function ServerToolLine({ role && shown && !refused && !failed && !interrupted ? readResearchSources(shown) : null; + // While the Bot thinks after this step, the line says "Thinking", its icon kept, and no detail. + const saying = + waiting === "reconnecting" + ? "Reconnecting…" + : waiting === "thinking" + ? "Thinking" + : undefined; if (role && sources) return ( } - label={label} - running={running} + label={saying ?? label} + running={running || saying !== undefined} + announce={saying !== undefined} > } - label={label} + icon={ + appId ? ( + + ) : ( + + ) + } + label={saying ?? label} refused={refused} failed={failed} interrupted={interrupted} - running={running} + running={running || saying !== undefined} + announce={saying !== undefined} > {shown ? ( @@ -2350,22 +2410,6 @@ export function ServerToolLine({ ); } -/** - * The tools a search found, one to a line by the name a step gives each ("Send email on Gmail"). The - * search answers the model, naming each tool by the id it is offered under - * (`mcp__composio-gmail__GMAIL_SEND_EMAIL`), and the step opened to that answer as it was. - */ -function foundToolsInWords(answer: string | undefined): string | undefined { - const names = answer ? toolsFound(answer) : []; - if (names.length === 0) return undefined; - return names - .map((name) => { - const { label, detail } = readToolName(name); - return `- ${detail ? `${label} on ${detail}` : label}`; - }) - .join("\n"); -} - /* * Moved beside the turns it also decides; re-exported for the callers that read it from here. And * the lightbox's picture, now in attachment-view.tsx, where the transcript's tests import it from. @@ -2671,6 +2715,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, @@ -2734,6 +2793,43 @@ export function ChatTranscript({ folds, lastAskId: [...folds.at.values()].at(-1)?.askId, }; + /* + * A TURN'S SUBTASKS ARE ONE LIST. A Bot starts subtasks a few at a time, saying something between, + * and with what it said gone into the turn's line each batch was a block of its own, a gap between + * one subtask and the next. In a conversation every subtask a turn has in view is drawn as one list + * where the first is (`SubtaskRows`), the rest left out of their own places. + */ + const subtaskLists = new Map(); + const inSubtaskList = new Set(); + if (!taskThread) { + let list: Extract[] = []; + const close = () => { + const [first, ...rest] = list; + if (first && rest.length) { + subtaskLists.set(first.id, { + kind: "tools", + id: first.id, + steps: list.flatMap((group) => group.steps), + }); + for (const group of rest) inSubtaskList.add(group.id); + } + list = []; + }; + for (const item of items) { + if ( + (item.kind === "text" && isPersonSentMessage(item.role, item.text)) || + item.kind === "attachments" + ) + close(); + else if ( + item.kind === "tools" && + item.steps.every(isSubtaskCall) && + !folds.inside.has(item.id) + ) + list.push(item); + } + close(); + } /* * Each finished reply's words, under its last line. A task's folded working is not what it said * back, and a steer note is the person's words, not the Bot's. @@ -2854,6 +2950,36 @@ 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; + /* + * THINKING BETWEEN STEPS IS THE LINE'S OWN. With every step of the last line answered and the Bot + * working out what to do next, "Thinking" was drawn as a line of its own under "Used Gmail": a + * second thing under the turn that came and went between steps. The line itself says it, its + * icons kept, and turns back into "Using Gmail…" when the next step starts, or "Used Gmail" when + * the Bot speaks. A lone call's line the server ran says it too ("Looked for a tool" becomes + * "Thinking"); a card the app draws itself, and a task's "Worked for" line, keep it under them. + */ + const thinkingInLine: Waiting | undefined = + (waitingOnTheModel || reconnectingNow) && + !stopped && + lastItem?.kind === "tools" && + lastItem.steps.every((step) => step.result !== undefined) && + // Subtasks' rows can't say it; "Thinking" stands under them. + !lastItem.steps.every(isSubtaskCall) && + (drawnAsSteps(lastItem.steps, isDrawn, { + folds: true, + openAmongRows: false, + }) || + // A lone call drawn as the server's line (`ServerToolLine`): "Looked for a tool". + lastItem.steps.every( + ({ toolCall: { function: call } }) => + call.name.startsWith("mcp__") || !isDrawn(call.name), + )) && + !taskWork.folds.inside.has(lastItem.id) && + !taskWork.folds.at.has(lastItem.id) + ? reconnectingNow + ? "reconnecting" + : "thinking" + : undefined; const viewportRef = useRef(null); const newestUserMessageId = @@ -3187,8 +3313,8 @@ export function ChatTranscript({ > = turnStart} latest={index >= latestIndex} @@ -3197,6 +3323,9 @@ export function ChatTranscript({ workAlone={mended.has( item.kind === "tools" ? (item.steps[0]?.id ?? "") : item.id, )} + {...(thinkingInLine && index === items.length - 1 + ? { thinking: thinkingInLine } + : {})} /> ) : item.kind === "activity" ? ( @@ -3245,19 +3374,57 @@ export function ChatTranscript({ {...rowGuard} > - {work.rows.map((row) => ( - - {rowContent(row.item, row.index, !taskThread)} - - ))} + {work.rows.map((row, at) => { + // 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 card is not a step. In a conversation every run of steps is drawn + // open, as a list (`drawnAsSteps`); in a task's thread, only an app's are joined. + const above = work.rows[at - 1]; + const listOfSteps = (item: TranscriptItem) => + item.kind === "tools" && + drawnAsSteps(item.steps, isDrawn, { + folds: true, + openAmongRows: true, + }); + const shape = taskThread ? stepsShape(row.item) : "list"; + const joins = + above !== undefined && + (taskThread + ? stepsShape(above.item) === shape && + rowApps(above.item).last !== undefined && + rowApps(row.item).first !== undefined + : listOfSteps(above.item) && listOfSteps(row.item)); + const content = rowContent(row.item, row.index, !taskThread); + /* + * What the Bot said on the way, among its steps in a conversation's line: its own + * words, quieter than its answer, as the steps' rows are. + */ + const drawn = + !taskThread && + row.item.kind === "text" && + row.item.role === "assistant" ? ( +
+ {content} +
+ ) : ( + content + ); + return ( + + {joins ?
{drawn}
: drawn} +
+ ); + })}
); if (taskWork.folds.inside.has(item.id)) return null; + if (inSubtaskList.has(item.id)) return null; // A refused turn's notice, under the last row of the person's message it answered. const refusal = refusedUnder.get(item.id); /* @@ -3285,7 +3452,7 @@ export function ChatTranscript({ : {})} {...rowGuard} > - {rowContent(item, index)} + {rowContent(subtaskLists.get(item.id) ?? item, index)} {/* * Beside the drawn answer, never around it: wrapping the row once its turn ended would mount * the interface again, and an interface drawn in a frame would load again. @@ -3436,7 +3603,14 @@ export function ChatTranscript({ reason={stopped} /> ) - ) : waitingOnTheModel || reconnectingNow ? ( + ) : (waitingOnTheModel || reconnectingNow) && + !thinkingInLine && + // A conversation's turn whose line is running says it on that line. + !( + !taskThread && + lastItem !== undefined && + taskWork.folds.inside.has(lastItem.id) + ) ? ( ) : null} {working} diff --git a/app/src/components/channels/subtask-step.tsx b/app/src/components/channels/subtask-step.tsx index d826b3b93d..a5235f150c 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; @@ -122,6 +123,7 @@ export function SubtaskStep({ } running={running} step={step} + doing={running ? steps.at(-1)?.label : undefined} /> @@ -134,9 +136,14 @@ export function SubtaskStep({ {handedBack ? : null} {step.output ? : null} {steps.length ? ( -
    - {foldRereads(steps).map((inner) => ( - +
      + {foldRereads(steps).map((inner, _, rows) => ( + ))}
    ) : null} @@ -201,9 +208,15 @@ function SubtaskStatus({ count, model, bot, + doing, }: { step: StepDetails; running: boolean; + /** + * The step it is on while it works ("Running a command"), from its own thread: said on its row, + * closed, as the line under the turn's folded line said it before subtasks were rows of their own. + */ + doing?: string | undefined; handedBack: boolean; /** It finished with an answer. */ answered: boolean; @@ -218,7 +231,7 @@ function SubtaskStatus({ if (running) return ( - {by(steps ? `Working · ${steps}` : "Working")} + {by([doing ?? "Working", steps].filter(Boolean).join(" · "))} ); if (step.pending) diff --git a/app/src/components/channels/tool-activity.tsx b/app/src/components/channels/tool-activity.tsx index 70caa04ad3..4442dd00f0 100644 --- a/app/src/components/channels/tool-activity.tsx +++ b/app/src/components/channels/tool-activity.tsx @@ -26,6 +26,7 @@ import { ownToolLabel, readToolName, } from "@openbot/shared/tool-name"; +import { SEARCH_TOOLS, toolsFound } from "@openbot/shared/tool-search"; import { QueryClientContext, useQuery } from "@tanstack/react-query"; import { createContext, @@ -50,7 +51,6 @@ import { IconFilePlus, IconFileText, IconFolder, - IconLoader2, IconPlug, IconSearch, IconSend, @@ -65,6 +65,18 @@ import { PluginLogo, } from "@/components/plugins/plugin-logo"; import { settingsToolCardFor } from "@/components/settings-tools/settings-tool-card"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +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"; @@ -134,8 +146,9 @@ export type TranscriptItem = VisibleChatItem | ToolGroup; * A coding harness's reads and searches fold too, though the app draws them, because Claude Code * folds them: a run of Read, Grep, Glob and plain `ls`, `cat` or `grep` commands is one line saying * "Read 3 files and searched for 2 patterns" (its changelog, 2.1.0 to 2.1.89). Its edits, writes, - * other commands and plan keep their own rows, as they do there. A single call on its own keeps its own line; one browser step is still a group, as it - * always was, so the row does not change shape when the second step arrives. + * other commands and plan keep their own rows, as they do there. A single call on its own keeps its + * own line, but one browser step, or one step on an app, is drawn as a group from the start, so the + * row does not change shape when the second step arrives (`drawnAsSteps`, chat-transcript.tsx). * * `isDrawn` says which tools the app draws itself; the transcript reads it from `useDrawnTool`. * @@ -163,6 +176,14 @@ export function groupToolSteps( // Nothing happened, and the Bot looks and goes again: not a step to show (`awaitingFreshLook`). if (item.kind === "tool" && awaitingFreshLook(item)) continue; if (item.kind === "tool" && foldable(item, isDrawn)) { + /* + * SUBTASKS RUN IN A ROW OF THEIR OWN. A subtask works for minutes, with steps of its own, and + * the person follows it and steps into it; folded into a run's line with a search and two app + * calls it was a line of progress under that line that couldn't be opened. Subtasks the Bot + * starts together are one row of their own (`SubtaskRows`); its other steps are another. + */ + const [head] = run; + if (head && isSubtaskCall(head) !== isSubtaskCall(item)) close(); run.push(item); continue; } @@ -277,6 +298,11 @@ function foldable(item: ToolItem, isDrawn: (name: string) => boolean): boolean { const NOTHING_DRAWN: readonly { name: string }[] = []; +/** Whether a call is a subtask the Bot handed to a subagent. */ +export function isSubtaskCall(item: ToolItem): boolean { + return item.toolCall.function.name === SUBAGENT_TOOL; +} + /** * Whether the app draws a tool itself, read from CopilotKit's own renderer registry. * @@ -541,21 +567,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 +607,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 +696,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 +706,7 @@ function detailsOf( inputs: [], pages: 0, ...(app - ? { kind: "connector", connector: connectorName(app), appId: app } + ? { kind: "connector", connector: appName(app), appId: app } : { kind: "tool" }), }; } @@ -683,9 +726,13 @@ function detailsOf( pages: 0, }; } - if (!name.startsWith("mcp__")) + if (!name.startsWith("mcp__")) { + // A tool search opens to the tools it found, in words, as its line of its own does. + const found = + name === SEARCH_TOOLS && !refused ? foundToolsInWords(answer) : undefined; return { ...outcome, + ...(found ? { output: found } : {}), kind: "tool", // Beside "Blocked", what was tried: "Save a file", not "Saved a file", which did not happen. // So too beside "Didn't work", for a step that then did not happen: "Draw an interface". @@ -697,6 +744,7 @@ function detailsOf( ...(name === RECALL_EARLIER_RESULTS ? { rereads: 1 } : {}), pages: 0, }; + } const [, server = "", ...rest] = name.split("__"); const role = researchRoleOfTool(server, rest.join("__")); @@ -738,18 +786,37 @@ 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, }; } +/** + * The tools a search found, one to a line by the name a step gives each ("Send email on Gmail"). The + * search answers the model, naming each tool by the id it is offered under + * (`mcp__composio-gmail__GMAIL_SEND_EMAIL`), and the step opened to that answer as it was. Its line + * of its own (`ServerToolLine`) and its row in a list open to the same words. + */ +export function foundToolsInWords( + answer: string | undefined, +): string | undefined { + const names = answer ? toolsFound(answer) : []; + if (names.length === 0) return undefined; + return names + .map((name) => { + const { label, detail } = readToolName(name); + return `- ${detail ? `${label} on ${detail}` : label}`; + }) + .join("\n"); +} + /** * The name of the attached file a `read_attachment` step read part of, from the server's answer * (`{ attachment_id, name, offset, text, next_offset, total_length }`), or undefined while it runs or @@ -783,18 +850,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 +1301,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], ); } @@ -1283,30 +1344,72 @@ 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 IS BARE. A lone "Looked for a tool" drew its wrench in a gray circle, and the app steps + * beside it their logos bare: two kinds of row for one kind of thing. A single mark is drawn as a + * step's row draws it (`StepMark`); only marks that overlap need the circle that parts them. + */ 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-6 items-center justify-center rounded-full bg-muted text-muted-foreground ring-2 ring-background ${ + index > 0 ? "-ml-1.5" : "" + }`; + 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,6 +1438,21 @@ export function ServerStepIcon({ name }: { name: string }) { ); } +/** + * The kinds of step a turn's work holds, for its line where it used no app: the wrench of a tool + * search, the magnifier of a web search. One mark each, as a folded line draws them. + */ +export function WorkStepIcons({ items }: { items: readonly TranscriptItem[] }) { + const marks = items.flatMap((item) => + item.kind === "tools" + ? item.steps.map(stepDetails) + : item.kind === "tool" + ? [stepDetails(item)] + : [], + ); + return marks.length ? : null; +} + export function WorkAppIcons({ names }: { names: string[] }) { return ( ({ kind: "connector", appId }))} /> @@ -1363,15 +1481,119 @@ export function StepStatus({ return null; } +/** + * 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. A turn's folded line names it: "Google Calendar Worked + * through 2 steps". + */ +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} + + ); +} + +/** + * A step's mark: an app's logo named on hover (`AppMark`), or the icon for its kind of step. + * + * EVERY ROW DRAWS ITS OWN. Under "Google Calendar Worked through 2 steps", "List events" drew no + * logo (the line had just shown it) while "Looked for a tool" drew its wrench, so one list held two + * shapes of row. Every step is one more entry in the list, with its own mark. + */ +function StepMark({ step }: { step: StepDetails }) { + return step.kind === "connector" && step.appId ? ( + + ) : ( + + ); +} + +/** + * 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, }: { step: StepDetails; active: boolean; - liveConnector?: boolean; + /** + * A row that doesn't open keeps the chevron's room, so its mark and words line up with the rows + * that do, in its list and in the lists beside it. + */ + chevronRoom?: boolean; }) { if (step.kind === "subtask") return ; @@ -1379,32 +1601,35 @@ export function StepRow({ * 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 line = ( + // Spaced as a line of its own is (`ToolLine`), so a step and a lone call line up in one list. + + + + {step.label} - ); + {step.href ? ( + + {step.detail ?? step.href} + + ) : step.detail ? ( + {step.detail} + ) : null} + + + ); const reason = step.failed && step.kind === "browser" ? (

    @@ -1422,9 +1647,9 @@ 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)) return ( -

  1. +
  2. {line} {reason}
  3. @@ -1591,7 +1816,7 @@ export function WorkingNow({ steps }: { steps: readonly StepDetails[] }) { ) : (
  4. - + {step.label} @@ -1609,8 +1834,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( @@ -1622,22 +1848,103 @@ export function stepsUnderWay( ); } +/** How many subtasks a conversation lists before the rest are behind "See all". */ +const SUBTASKS_SHOWN = 3; + +/** + * Subtasks the Bot started, each a row of its own in the conversation: what it was asked, the step + * it is on and how many it has taken, opened to the steps it took (`SubtaskStep`). + * + * A BOT THAT STARTS THIRTY-FIVE OF THEM LISTS THREE. The rest are behind "See all (35)", which opens + * a view of every one, each opened as it is here; the conversation keeps its shape however many + * the Bot starts. + */ +export function SubtaskRows({ + group, + active, +}: { + group: ToolGroup; + active: boolean; +}) { + const folders = useContext(FolderNamesContext); + const inFlight = useContext(TurnInFlightContext); + const appName = useAppName(); + const [all, setAll] = useState(false); + const steps = group.steps.map( + stepDetailsIn(folders, active || inFlight, appName), + ); + const shown = steps.slice(0, SUBTASKS_SHOWN); + const rows = (list: readonly StepDetails[]) => + list.map((step) => ( + + )); + return ( + <> +
      + {rows(shown)} +
    + {steps.length > shown.length ? ( + + {/* Under the rows, where their words start. */} +
    + +
    + + + {steps.length} subtasks + +
      + {rows(steps)} +
    +
    +
    + ) : null} + step.toolCall.id)} + /> + + ); +} + +/** What a line whose steps are all answered says while the Bot works out its next move. */ +export type Waiting = "thinking" | "reconnecting"; + +/** The same, for a lone call's own line (`ServerToolLine`), which its row draws through a card's path. */ +export const LineWaiting = createContext(undefined); + export function ToolActivity({ group, active, - conversation = false, expanded, + thinking, }: { 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; + /** + * Every step has its answer and the Bot is working out its next move: the line says "Thinking" + * (or "Reconnecting…"), shimmering, its icons kept, in place of a line of its own under it. + */ + thinking?: Waiting; }) { 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 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,23 +1968,45 @@ 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")}…`; + /* + * ONLY WHAT THE LINE CAN'T SAY IS DRAWN UNDER IT WHILE IT RUNS: a subtask's progress, and the + * command running now. A Bot that called Gmail, Fireflies and Google Calendar at once drew each + * of them, icon and words, under the folded line, two or three or four rows that came and went + * beneath a line that was meant to be folded; and a read of an answer's next part was named on + * the line and again under it. The line names the steps; opened, it lists them. + */ const live = running - ? rows.filter((step) => step.pending && !step.interrupted) + ? rows.filter( + (step) => + step.pending && + !step.interrupted && + (step.kind === "subtask" || step.terminal !== undefined), + ) : []; - const showLiveSteps = - conversation && - inFlight && - rows.some((step) => step.pending && !step.interrupted) && - rows.every((step) => step.kind === "connector"); const list = ( -
      + // 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. +
        {rows.map((step) => ( - + // The chevron's room is kept whether or not any row here opens: a list of one step that + // doesn't sits beside lists whose steps do, and their marks and words line up. + ))}
      ); @@ -1686,7 +2015,7 @@ export function ToolActivity({ toolCallIds={group.steps.map((step) => step.toolCall.id)} /> ); - if (expanded || showLiveSteps) { + if (expanded) { return ( <> {list} @@ -1703,18 +2032,27 @@ 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) + thinking === "reconnecting" + ? "Reconnecting…" + : thinking + ? "Thinking" + : running && working + ? working === 1 + ? "Working on a subtask…" + : `Working on ${working} subtasks…` + : running && appsOnly + ? using + : running && current + ? `${current.label}…` + : summarise(steps) } detail={asides.length ? asides.join(" · ") : undefined} - running={running} + running={running || thinking !== undefined} + announce={thinking !== undefined} > {list} diff --git a/app/src/components/channels/tool-line.tsx b/app/src/components/channels/tool-line.tsx index 720f464af2..1ebec582f1 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,20 @@ export function ToolLine({ openKey, live, drawnWhenOpened, + announce, + wraps, children, }: { + /** + * The label is the Bot's words, not a few of the line's own: it wraps, up to three lines, and the + * icon stands at its first line. + */ + wraps?: boolean; + /** + * The label is said to a screen reader as it changes (`role="status"`): a line that says + * "Thinking" while the Bot works out its next move, as the "Thinking" line it stands in for did. + */ + announce?: 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 +141,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; @@ -206,7 +221,18 @@ export function ToolLine({ running ? "tool-line-running tabular-nums" : "" } ${saysWhy ? "flex-wrap" : ""}`} > - {icon ? {icon} : null} + {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 @@ -216,8 +242,13 @@ export function ToolLine({ */} {refused ? `Blocked: ${attempted ?? label}` @@ -242,6 +273,14 @@ 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. Not on + * a line that announces its label ("Thinking"), which already says it. + */} + {running && !announce ? ( + In progress + ) : null} ); @@ -272,14 +311,18 @@ export function ToolLine({ * Native
      owns expansion because SDK tool renderers can be re-invoked independently * of this component's React state. */} + {/* + * A label of several lines (`wraps`): the chevron, the icons and the first line of words share + * one row, 24 pixels tall, each centred in it, and the rest of the words run on under it. + */} {/* biome-ignore lint/a11y/noStaticElementInteractions: a summary is its details' own control; the press only draws what it opens to (`useDrawnOnceOpened`). */} @@ -303,12 +346,20 @@ export function ToolLine({ )}
      ); - if (!live) return line; - // Only while folded: opened, the line's own rows say the same, and nothing is said twice. + /* + * ONE TREE, WITH OR WITHOUT WHAT IS UNDER WAY. The line was its
      alone, and wrapped in a + *
      only while something under way was drawn beneath it, so each time a step began or ended + * beside another React drew the line anew: an app's logo under the pointer was replaced before + * its name could show, and hovering a running line never named the app. The wrapper is always + * there; without anything under way it has no margin of its own, so the line sits where it did. + * + * What is under way is shown only while folded: opened, the line's own rows say the same, and + * nothing is said twice. + */ return ( -
      +
      {line} - {folded ?
      {live}
      : null} + {live && folded ?
      {live}
      : null}
      ); } diff --git a/app/src/components/tasks/turn-work.ts b/app/src/components/tasks/turn-work.ts index 5c9a5a6fef..eb9d714833 100644 --- a/app/src/components/tasks/turn-work.ts +++ b/app/src/components/tasks/turn-work.ts @@ -154,15 +154,17 @@ export function foldTurnWork( if (item?.kind === "text" && item.role === "assistant") said.push(index); } // What it came back with: its last line, once the turn is over; while it runs, the newest line - // only when it is the newest row, since that may be the answer arriving. + // only when it is the newest row, since that may be the answer arriving. A conversation's turn + // still running has no answer yet: what the Bot says is its thinking, drawn on its line. const answer = inFlight - ? said.at(-1) === end - 1 - ? end - 1 - : -1 + ? scope === "conversation" + ? -1 + : said.at(-1) === end - 1 + ? 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; + // A finished conversation turn with no last words of its own leaves its work in view. + if (scope === "conversation" && !inFlight && answer === -1) return; const rows: TurnWork["rows"] = []; for (let index = start.from; index < end; index += 1) { const item = items[index]; @@ -171,6 +173,16 @@ export function foldTurnWork( if (inFlight && isPlanStep(item)) continue; // Keep existing refusal and issue notices at their original place in conversation replies. if (scope === "conversation" && hasVisibleOutcome(item)) continue; + // A conversation's subtasks stay rows of their own while its turn runs: the person follows them. + if ( + scope === "conversation" && + inFlight && + item.kind === "tools" && + item.steps.every( + (step) => step.toolCall.function.name === SUBAGENT_TOOL, + ) + ) + continue; if ( (item.kind === "tools" && !waitsOnThePerson(item, inFlight, waiting)) || (item.kind === "tool" && isWorkStep(item)) || @@ -178,6 +190,46 @@ export function foldTurnWork( ) rows.push({ item, index }); } + /* + * WHAT THE BOT SAYS ON THE WAY IS PART OF ITS WORK, IN ONE GROUP WITH ITS STEPS. Its words between + * steps were paragraphs of their own, each splitting the steps into another line: a long job read + * as a wall of half-thoughts and lines. Now, once a turn has taken a step, what the Bot says on + * the way goes into the turn's one line with its steps, in order: while it works, the line reads + * its latest thought (`WorkLine`); once it has answered, the line says what it did and the answer + * stands under it. Words before anything left out of the line (a chart, a card, a refusal) stay + * beside it, in view. + */ + if (scope === "conversation") { + // Nothing done yet but words: they stand as words until the Bot takes a step. + if (inFlight && rows.length === 0) return; + const folded = new Set(rows.map((row) => row.index)); + for (const index of said) { + if (index === answer) continue; + let next = index + 1; + while ( + next < end && + items[next]?.kind === "text" && + (items[next] as { role?: string }).role === "assistant" + ) + next += 1; + const item = items[index]; + const nextItem = items[next]; + // The newest words of a turn still running are its thinking now, and so are words that + // start its subtasks, which run as rows of their own beside its line. + const startsSubtasks = + inFlight && + nextItem?.kind === "tools" && + nextItem.steps.every( + (step) => step.toolCall.function.name === SUBAGENT_TOOL, + ); + if ( + item && + (folded.has(next) || (inFlight && next >= end) || startsSubtasks) + ) + rows.push({ item, index }); + } + rows.sort((a, b) => a.index - b.index); + } const first = rows[0]; if (!first) return; const work: TurnWork = { diff --git a/app/src/components/tasks/worked-for.tsx b/app/src/components/tasks/worked-for.tsx index 492c9799a5..a5bce2f1dc 100644 --- a/app/src/components/tasks/worked-for.tsx +++ b/app/src/components/tasks/worked-for.tsx @@ -15,10 +15,13 @@ import { useSyncExternalStore, } from "react"; import { + onlyApp, stepsUnderWay, type TranscriptItem, + useAppName, WorkAppIcons, WorkingNow, + WorkStepIcons, } from "@/components/channels/tool-activity"; import { ToolLine } from "@/components/channels/tool-line"; import { type ApprovalQueueData, approvalQueueOptions } from "@/lib/approvals"; @@ -124,12 +127,18 @@ export function WorkedFor({ threadId, work, last, + conversation = false, children, }: { threadId: string | undefined; work: TurnWork; /** This is the thread's newest turn, the one a task that reads Working is working on. */ last: boolean; + /** + * A conversation's turn, not a task's: while it runs, its line reads the Bot's latest thought, or + * what its steps are doing, not how long it has been working. + */ + conversation?: boolean; /** The folded rows, drawn as they would be on their own. */ children: ReactNode; }) { @@ -140,6 +149,7 @@ export function WorkedFor({ ) : ( = 0; at -= 1) { + const item = work.rows[at]?.item; + if (item?.kind !== "text" || item.role !== "assistant") continue; + const paragraph = item.text + .split(/\n\s*\n/) + .map((part) => part.trim()) + .filter(Boolean) + .at(-1); + if (!paragraph) continue; + return paragraph + .replace(/^#+\s+|^\s*[-*+]\s+|^\s*\d+\.\s+/gm, "") + .replace(/\*\*|__|`/g, "") + .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1") + .replace(/\s+/g, " ") + .trim(); + } + return undefined; +} + function TimedWork({ threadId, work, @@ -210,11 +244,13 @@ function WorkLine({ text, work, running, + conversation = false, children, }: { text: string; work: TurnWork; running: boolean; + conversation?: boolean; children: ReactNode; }) { /* @@ -225,12 +261,37 @@ 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 underWay = running - ? stepsUnderWay( - work.rows.map((row) => row.item), - folders, - ) - : []; + const appName = useAppName(); + /* + * In a conversation, nothing is drawn under the line: it says what the Bot is thinking or doing, + * and a subtask is one of its rows, opened to see the steps it is taking. A line of a subtask's + * progress under it read as one more thing to look at and could not be opened. + */ + const underWay = + running && !conversation + ? stepsUnderWay( + work.rows.map((row) => row.item), + folders, + appName, + ) + : []; + /* + * WHILE A CONVERSATION'S TURN RUNS, ITS LINE READS WHAT THE BOT IS THINKING. Its latest words, as + * it says them, shimmering, over as many lines as they take (up to three), beside the logos of the + * apps it has used; before it has said anything, what its steps are doing ("Using Gmail…"), or + * "Thinking" between them. Once it has answered, the line says what it did. + */ + const thought = conversation && running ? latestThought(work) : undefined; + const doing = + conversation && running && !thought + ? stepsDoing( + stepsUnderWay( + work.rows.map((row) => row.item), + folders, + appName, + ), + ) + : undefined; const apps = work.rows.flatMap(({ item }) => { const tools = item.kind === "tools" ? item.steps : item.kind === "tool" ? [item] : []; @@ -242,6 +303,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} + icon={ + apps.length ? ( + + ) : ( + row.item)} /> + ) + } + /* + * THE ONE APP, NAMED. "Worked through 2 steps" beside Google Calendar's logo said which app + * only to someone who knew the logo, and its rows don't name it in words (`AppMark`). Where + * the line's logo is one app's, the line names it beside the logo, before what was done, and + * what was done carries on from the name, in lower case: "Google Calendar worked through 2 + * steps". Every word the line can start with ("Worked", "Working") is an ordinary word. + */ + label={ + thought ?? + doing ?? + (app ? text.charAt(0).toLowerCase() + text.slice(1) : text) + } + {...(app && !thought && !doing ? { lead: appName(app) } : {})} + {...(thought ? { wraps: true } : {})} + // Its thoughts and "Thinking" are said to a screen reader as they change. + announce={conversation && running} running={running} openKey={work.id} live={underWay.length ? : undefined} @@ -263,3 +347,26 @@ function WorkLine({
      ); } + +/** + * What a running turn's steps are doing, said on its line before the Bot has said anything: its app's + * name ("Using Gmail…"), how many apps ("Using 3 apps…"), or the step itself; "Thinking" when none is + * under way. + */ +function stepsDoing( + underWay: readonly ReturnType[number][], +): string { + const [first] = underWay; + if (!first) return "Thinking"; + const subtasks = underWay.filter((step) => step.kind === "subtask").length; + if (subtasks) + return subtasks === 1 + ? "Working on a subtask…" + : `Working on ${subtasks} subtasks…`; + const apps = [...new Set(underWay.map((step) => step.connector))]; + if (underWay.every((step) => step.kind === "connector")) + return apps.length === 1 + ? `Using ${apps[0]}…` + : `Using ${apps.length} apps…`; + return `${first.label}…`; +} diff --git a/app/tests/app-step-rows.test.tsx b/app/tests/app-step-rows.test.tsx new file mode 100644 index 0000000000..da1d9ea7c7 --- /dev/null +++ b/app/tests/app-step-rows.test.tsx @@ -0,0 +1,654 @@ +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, ToolLine } 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, beside its app's logo, which names the app on hover and to a screen + * reader. Every step is one more entry in the list, a step on no app included, with its own mark. + */ + +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 Bot's answer starting after its steps. Until it does, a line whose steps are all answered says + * "Thinking" (`thinkingInLine`); once it speaks, the line says what was done. + */ +const SAID: Message = { + id: "said", + role: "assistant", + content: "Here's your 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 run is its app's line, by the app's name, shimmering, and folded. + const line = await view.findByText("Using Google Calendar…"); + expect(line.closest(".tool-line-running")).not.toBeNull(); + // The turn's one line, closed: its steps are inside it, out of sight until it is opened. + expect((line.closest("details") as HTMLDetailsElement).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's name again: its logo says it, on every row. + 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).toBe(APP.title); + + // 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 and the Bot speaking: the same line reads its words, and opened, its steps + // have stopped running. + view.rerender(transcript([...turn(true), SAID], true)); + expect(await view.findByText(SAID.content as string)).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":[]}', + ), + SAID, + ], + false, + ), + ); + // The turn over, its line says what it did, and opened, lists each step beside its app's logo. + fireEvent.click(await view.findByText("Worked through 2 steps")); + 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("a lone call on an app is its app's line from the first call, and a second call joins it without a rename", async () => { + const turnOf = (...calls: Message[][]) => [ASKED, ...calls.flat()]; + const first = (answered: boolean) => + call( + "list-1", + LIST_EVENTS, + { timeMin: "2026-12-01" }, + answered ? EVENTS : undefined, + ); + const second = (answered: boolean) => + call( + "list-2", + LIST_EVENTS, + { timeMin: "2026-12-08" }, + answered ? EVENTS : undefined, + ); + + // One call, running: its app's line, shimmering, folded. Not a line of the action's own that a + // second call would rename. + const view = render(transcript(turnOf(first(false)), true)); + const running = await view.findByText("Using Google Calendar…"); + expect(running.closest(".tool-line-running")).not.toBeNull(); + expect((running.closest("details") as HTMLDetailsElement).open).toBe(false); + const row = running.closest("details"); + expect(row).not.toBeNull(); + await waitFor(() => + expect(row?.querySelector("summary img")?.getAttribute("src")).toBe( + APP.logo, + ), + ); + expect(view.container.textContent).not.toContain("Googlecalendar"); + + // Answered, the Bot working out its next move: the same line says "Thinking". + view.rerender(transcript(turnOf(first(true)), true)); + expect(await view.findByText("Thinking")).toBeTruthy(); + expect(view.getByText("Thinking").closest("details")).toBe(row); + + // A second call on the app joins it: the same line, running again, and nothing renamed. + view.rerender(transcript(turnOf(first(true), second(false)), true)); + expect(await view.findByText("Using Google Calendar…")).toBeTruthy(); + expect(view.getByText("Using Google Calendar…").closest("details")).toBe(row); + + // Opened, it lists both calls. + fireEvent.click(view.getByText("Using Google Calendar…")); + const steps = view.getByRole("list", { name: "Tool steps" }); + expect(within(steps).getAllByText("List events")).toHaveLength(2); +}); + +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", {}, ""), + SAID, + ], + false, + ), + ); + fireEvent.click(await view.findByText("worked through 2 steps")); + 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(`once the turn is folded, what the Bot said between app steps is inside the line, between them, in order: ${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, which + // carries on from the name in lower case: "Google Calendar worked through 2 steps". + 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, beside its + // app's logo. + 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).toBe(APP.title); + expect(line.closest('ol[aria-label="Tool steps"]')).not.toBeNull(); + } + + // The Bot's words fold with the steps they came between, and still split them: the rows before + // the words, the words, then the rows after, none drawn up across them. + const words = within(fold).getByText(BETWEEN); + expect(words.closest('[data-slot="worked-for"]')).not.toBeNull(); + const follows = (a: Node, b: Node) => + Boolean(a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING); + const lastBefore = lines[before - 1]; + const firstAfter = lines[before]; + if (!lastBefore || !firstAfter) throw new Error("Expected rows each side"); + expect(follows(lastBefore, words)).toBe(true); + expect(follows(words, firstAfter)).toBe(true); + expect(firstAfter.closest('[class*="-mt-"]')).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 the step on no app is one more row in its list", 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).toBe(APP.title); + // "Looked for a tool" is one more entry in the same list as "List events", not a line of its own + // in a gray circle: its wrench bare, where the logo is, and the chevron's room kept, since it + // opens to nothing. + const looked = within(fold) + .getByText("Looked for a tool") + .closest("li") as Element; + const list = listed.closest('ol[aria-label="Tool steps"]'); + expect(list).not.toBeNull(); + expect(looked.closest('ol[aria-label="Tool steps"]')).toBe(list); + expect(looked.querySelector("summary")).toBeNull(); + expect(looked.className).toContain("pl-5"); + expect(looked.querySelector(".rounded-full")).toBeNull(); +}); + +test("a line that names the step under way doesn't name it again under itself", async () => { + const view = render( + transcript( + [ + ASKED, + ...call("list-1", LIST_EVENTS, { timeMin: "2026-12-01" }, EVENTS), + // Still running, and on no app: the line names it, so nothing under the line repeats it. + ...call("search", "search_tools", { query: "calendar" }), + ], + true, + ), + ); + const line = await view.findByText("Looking for a tool…"); + expect(line.closest(".tool-line-running")).not.toBeNull(); + // Said on the line, and not again under it: its step is inside the closed line, out of sight. + expect(view.queryByRole("list", { name: "Working now" })).toBeNull(); + expect((line.closest("details") as HTMLDetailsElement).open).toBe(false); +}); + +for (const [what, steps, mark] of [ + [ + "a step on an app", + call("list-1", LIST_EVENTS, { timeMin: "2026-12-01" }, EVENTS), + APP.title, + ], + [ + "a step on no app", + call("search", "search_tools", { query: "calendar" }, "[]"), + undefined, + ], +] as const) + test(`between steps, the last line says "Thinking" itself, with no line of its own under it: ${what}`, async () => { + const view = render(transcript([ASKED, ...steps], true)); + const thinking = await view.findByText("Thinking"); + // One "Thinking", and it is the line's: its mark kept beside it, shimmering. + expect(view.getAllByText("Thinking")).toHaveLength(1); + expect(thinking.closest(".tool-line-running")).not.toBeNull(); + const row = thinking.parentElement as HTMLElement; + if (mark) expect(markOf(row).name).toBe(mark); + else expect(row.querySelector("svg")).not.toBeNull(); + // Once the Bot speaks, the line says what was done again. + view.rerender( + transcript( + [ASKED, ...steps, { id: "said", role: "assistant", content: "Done." }], + true, + ), + ); + await waitFor(() => expect(view.queryByText("Thinking")).toBeNull()); + }); + +test("a running line is not drawn anew when what is under way beneath it comes and goes, so its logos keep their hover", async () => { + const line = (live: boolean) => ( + } + label="Running a command…" + live={live ? python3 save_csv.py : undefined} + running + > + rows + + ); + const view = render(line(true)); + const summary = view.getByText("Running a command…").closest("summary"); + const logo = summary?.querySelector('[role="img"]'); + expect(view.getByText("python3 save_csv.py")).toBeTruthy(); + + // Nothing under way beneath it any more: the same line, the same logo, not drawn anew. + view.rerender(line(false)); + expect(view.queryByText("python3 save_csv.py")).toBeNull(); + expect(view.getByText("Running a command…").closest("summary")).toBe(summary); + expect(logo?.isConnected).toBe(true); + + // And back again. + view.rerender(line(true)); + expect(view.getByText("Running a command…").closest("summary")).toBe(summary); +}); diff --git a/app/tests/approval-answer-carries-on-browser.test.tsx b/app/tests/approval-answer-carries-on-browser.test.tsx index bfccd4af87..6865b9904a 100644 --- a/app/tests/approval-answer-carries-on-browser.test.tsx +++ b/app/tests/approval-answer-carries-on-browser.test.tsx @@ -723,7 +723,8 @@ describe.skipIf(!asked)("An approval answered in a long conversation", () => { * The server carries the conversation on. Its words stream into this tab while the turn * goes on: the first answer is not finished, and the thread's history doesn't hold them. */ - await page.getByText(POSTED).waitFor({ timeout: 10_000 }); + // On the turn's line, the Bot's latest words, and among its steps inside it. + await page.getByText(POSTED).first().waitFor({ timeout: 10_000 }); await shoot(page, shot("live", "2-carrying-on")); expect( scene.requests.find((request) => request.id === "approval-launch") diff --git a/app/tests/approval-answered-layout.test.tsx b/app/tests/approval-answered-layout.test.tsx index 65e6524202..8b30c6d8ba 100644 --- a/app/tests/approval-answered-layout.test.tsx +++ b/app/tests/approval-answered-layout.test.tsx @@ -394,8 +394,9 @@ const answerLine = (page: Page, said: string) => const workLine = (page: Page) => page .locator("details.tool-line > summary", { - // After the app's mark (Google's "G" here), so not anchored to the start. - hasText: /Worked through \d+ steps?/, + // After the app's mark and name ("Google Calendar worked through 1 step"), so not anchored to + // the start, and in lower case there. + hasText: /[Ww]orked through \d+ steps?/, }) .locator(".."); 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..eb920fe37c 100644 --- a/app/tests/carry-on-carried-turn-browser.test.tsx +++ b/app/tests/carry-on-carried-turn-browser.test.tsx @@ -562,7 +562,8 @@ describe.skipIf(!asked)("Carry on while the server carries a turn on", () => { }, ]; scene.going = "carried-on"; - await page.getByText(DONE).waitFor({ timeout: 15_000 }); + // The Bot's words on its turn's line while it runs, and among its steps inside it. + await page.getByText(DONE).first().waitFor({ timeout: 15_000 }); // Once the server is done, the page asks how its last run here ended before it says // anything about the cut-off turn: that answer is what this step waits for. const ended = page.waitForResponse( @@ -643,7 +644,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/channel-failed-run-restore.test.tsx b/app/tests/channel-failed-run-restore.test.tsx index 27861250ba..cd2461b805 100644 --- a/app/tests/channel-failed-run-restore.test.tsx +++ b/app/tests/channel-failed-run-restore.test.tsx @@ -858,7 +858,7 @@ test("Carry on after an interrupted turn sends the Bot what the turn already did const stopped = await live.findByTestId("transcript-stopped"); expect(within(stopped).getByRole("alert").textContent).toBe(TURN_INTERRUPTED); // What it saved stays on screen. - await live.findByText("Reading the first meeting."); + await live.findAllByText("Reading the first meeting."); const user = userEvent.setup({ document: live.container.ownerDocument }); await user.click(within(stopped).getByRole("button", { name: "Carry on" })); @@ -905,12 +905,14 @@ test.each(["Dismiss", "Escape"])( expect(live.queryByTestId("transcript-stopped")).toBeNull(), ); // What it saved stays on screen. - await live.findByText("Reading the first meeting."); + // Said on the turn's line while it runs, and among its steps inside it. + await live.findAllByText("Reading the first meeting."); live.unmount(); const back = open(); await settled(back, "Summarise last week's customer meetings"); - await back.findByText("Reading the first meeting."); + // Said on the turn's line while it runs, and among its steps inside it. + await back.findAllByText("Reading the first meeting."); // The replay says how the run ended again; the notice stays down. await new Promise((resolve) => setTimeout(resolve, 300)); expect(back.queryByTestId("transcript-stopped")).toBeNull(); diff --git a/app/tests/channel-join-replay.test.tsx b/app/tests/channel-join-replay.test.tsx index 019719e084..576259a6cf 100644 --- a/app/tests/channel-join-replay.test.tsx +++ b/app/tests/channel-join-replay.test.tsx @@ -37,6 +37,7 @@ import { botGrantsPath, botGrantsResponse } from "./bot-grants-api"; import { answerBotsList, botPath } from "./bots-api"; import { botComponentsPath, botComponentsResponse } from "./components-api"; import { conversationOf, conversationPath } from "./conversations-api"; +import { openWorkedFor } from "./open-folds"; import { ANSWER_TEXT, ANSWERED_EARLY, @@ -403,6 +404,9 @@ test("a reply is shown once when the roster announces its turn while the convers ?.messages.filter((message) => message.role === "assistant") .map((message) => message.content), ).toEqual([ASKING_TEXT, ASKED_TEXT]); + // Said on the way to the question, it folds with the turn's steps once the turn is over; opened, + // it is there once. + await act(async () => openWorkedFor(view.container)); expect(shown(view.container, ASKING_TEXT)).toBe(1); expect(shown(view.container, ASKED_TEXT)).toBe(1); expect(historyReads).toBeGreaterThan(0); @@ -433,6 +437,9 @@ test("a reply still being written when the conversation is opened arrives whole" const view = opened(); await view.findByText(ASKED_SO_FAR, undefined, { timeout: 4000 }); await view.findByText(ASKED_TEXT, undefined, { timeout: 6000 }); + // Said on the way to the question, it folds with the turn's steps once the turn is over; opened, + // it is there once. + await act(async () => openWorkedFor(view.container)); expect(shown(view.container, ASKING_TEXT)).toBe(1); expect(shown(view.container, ASKED_TEXT)).toBe(1); }, 15_000); @@ -579,6 +586,9 @@ test("a reply is shown once and whole after leaving its conversation and coming ?.messages.filter((message) => message.role === "assistant") .map((message) => message.content), ).toEqual([ASKING_TEXT, ASKED_TEXT]); + // Said on the way to the question, it folds with the turn's steps once the turn is over; opened, + // it is there once. + await act(async () => openWorkedFor(view.container)); expect(shown(view.container, ASKING_TEXT)).toBe(1); expect(shown(view.container, ASKED_TEXT)).toBe(1); }, 20_000); diff --git a/app/tests/channel-opens-history-first.test.tsx b/app/tests/channel-opens-history-first.test.tsx index 82a7e2958e..9e65617800 100644 --- a/app/tests/channel-opens-history-first.test.tsx +++ b/app/tests/channel-opens-history-first.test.tsx @@ -35,6 +35,8 @@ import { } from "./ask-person-replay.fixture"; import { botGrantsPath, botGrantsResponse } from "./bot-grants-api"; import { answerBotsList, botPath } from "./bots-api"; +import { botComponentsPath, botComponentsResponse } from "./components-api"; +import { openWorkedFor } from "./open-folds"; import { ANSWER_TEXT, ANSWERED_EARLY, @@ -42,7 +44,6 @@ import { lookupsReplayStart, lookupsStored, } from "./parallel-lookups.fixture"; -import { botComponentsPath, botComponentsResponse } from "./components-api"; /* * Opening a conversation shows what it already holds without waiting for the join's replay. @@ -433,6 +434,9 @@ for (const turn of turns) { await sleep(500); expect(shown(view.container, turn.user)).toBe(1); + // What the Bot said on the way folds with its steps once the turn is over; opened, each line is + // there once, as the answer is. + await act(async () => openWorkedFor(view.container)); for (const reply of turn.replies) expect(shown(view.container, reply)).toBe(1); expect(historyReads).toBeGreaterThan(0); @@ -576,6 +580,8 @@ test("a turn that ended just before opening is kept", async () => { await sleep(500); expect(shown(view.container, ASKED_TEXT)).toBe(1); + // Said on the way to the question, it folds with the turn's steps; opened, it is there once. + await act(async () => openWorkedFor(view.container)); expect(shown(view.container, ASKING_TEXT)).toBe(1); expect(historyReads).toBeGreaterThan(0); }, 10_000); diff --git a/app/tests/connector-approval-in-chat.test.tsx b/app/tests/connector-approval-in-chat.test.tsx index 5b9e38e975..1e58090608 100644 --- a/app/tests/connector-approval-in-chat.test.tsx +++ b/app/tests/connector-approval-in-chat.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, render, within } from "@testing-library/react"; +import { cleanup, fireEvent, render, within } from "@testing-library/react"; import { ChatTranscript } from "@/components/channels/chat-transcript"; import { queryClient } from "@/query-client"; import { approvalInboxResponse } from "./approvals-api"; @@ -178,8 +178,10 @@ test("a send the admin set to ask every time offers Allow once and Deny only", a expect(card.queryByRole("radio", { name: "Always allow here" })).toBeNull(); }); -test("with nothing waiting, the call is the line it always was", async () => { +test("with nothing waiting, the call is its app's line, as any step on an app is", async () => { const view = draw(); + // Not yet answered, in a turn no longer running: its app's line, which opens to "Create event". + fireEvent.click(await view.findByText(/Google ?Calendar/)); expect(await view.findByText("Create event")).toBeTruthy(); expect( view.queryByRole("region", { name: "Waiting for your approval" }), diff --git a/app/tests/conversation-reply-copy.test.tsx b/app/tests/conversation-reply-copy.test.tsx index e39e8e1121..59003009af 100644 --- a/app/tests/conversation-reply-copy.test.tsx +++ b/app/tests/conversation-reply-copy.test.tsx @@ -149,9 +149,9 @@ test("a finished reply in a conversation has one Copy, which copies the reply's fireEvent.click(copy); await flush(); - expect(copied).toEqual([ - "Let me look at your calendar.\n\nYou have **nothing** booked today.", - ]); + // The reply as it reads once the turn is over: what the Bot said on the way ("Let me look at your + // calendar.") folds with its steps, so Copy takes the answer. + expect(copied).toEqual(["You have **nothing** booked today."]); expect(events).toEqual([ { kind: "result_copied", diff --git a/app/tests/long-answer-part-steps.test.tsx b/app/tests/long-answer-part-steps.test.tsx index f4b3c66af3..789ea4e7ef 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, @@ -98,7 +98,13 @@ function drawRow(messages: Message[]) { ...messages, ]); const rows = groupToolSteps(items, nothingDrawn); - const group = rows.find((row) => row.kind === "tools") as ToolGroup; + // Every step in one line's list, as a turn's folded line opens to them: a subtask is a run of its + // own (`SubtaskRows`), and opened among a turn's steps it is one more row. + const group: ToolGroup = { + kind: "tools", + id: "steps", + steps: rows.flatMap((row) => (row.kind === "tools" ? row.steps : [])), + }; const view = render( @@ -172,8 +178,15 @@ 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", ]); + // Each row draws its app's logo, as every step's row does, and the logo names it. + expect( + within(view.getByRole("list", { name: "Tool steps" })).queryAllByRole( + "img", + { name: "Fireflies" }, + ), + ).toHaveLength(3); }); 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/run-ended-unheard-layout.test.tsx b/app/tests/run-ended-unheard-layout.test.tsx index be58af5059..db582781e1 100644 --- a/app/tests/run-ended-unheard-layout.test.tsx +++ b/app/tests/run-ended-unheard-layout.test.tsx @@ -691,7 +691,11 @@ describe.skipIf(!asked)("a run whose end never reached this browser", () => { scene = { ends: "onStep", stored: [], endings: new Map() }; const page = await sent(engine, theme, window); try { - await page.getByText(FINISHED_REPORT).waitFor({ timeout: 30_000 }); + // The Bot's words on its turn's line while it runs, and among its steps inside it. + await page + .getByText(FINISHED_REPORT) + .first() + .waitFor({ timeout: 30_000 }); await page .getByRole("button", { name: "Stop the Bot" }) .waitFor({ state: "detached", timeout: 15_000 }); @@ -744,7 +748,11 @@ describe.skipIf(!asked)("a run whose end never reached this browser", () => { scene = { ends: "carried", stored: [], endings: new Map() }; const page = await sent(engine, theme, window); try { - await page.getByText(FINISHED_REPORT).waitFor({ timeout: 30_000 }); + // The Bot's words on its turn's line while it runs, and among its steps inside it. + await page + .getByText(FINISHED_REPORT) + .first() + .waitFor({ timeout: 30_000 }); await page .getByRole("button", { name: "Stop the Bot" }) .waitFor({ state: "detached", timeout: 15_000 }); diff --git a/app/tests/running-step-shimmer.test.tsx b/app/tests/running-step-shimmer.test.tsx index 1fc52f8aba..bfc188a070 100644 --- a/app/tests/running-step-shimmer.test.tsx +++ b/app/tests/running-step-shimmer.test.tsx @@ -130,38 +130,72 @@ 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 group is its app's line, shimmering, folded until it is opened. + const line = await view.findByText("Using Gmail…"); + expect(line.closest(`.${SHIMMER}`)).not.toBeNull(); + expect((line.closest("details") as HTMLDetailsElement).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, beside + // its app's logo, as every step's row is. + const row = running.parentElement as HTMLElement; + expect(said(row)).toBe("Fetch thread messagesIn progress"); + expect(row.querySelector('[role="img"]')?.getAttribute("aria-label")).toBe( + "Gmail", + ); // 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 Bot working out its next move: the step stays in the group, its progress + // indicator goes, and the group's line says "Thinking". Once the Bot speaks, it reads its words. 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(); expect(view.queryByRole("list", { name: "Working now" })).toBeNull(); + view.rerender( + transcript( + [...run(true), { id: "said", role: "assistant", content: "Here." }], + true, + ), + ); + expect(await view.findByText("Here.")).toBeTruthy(); }); 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 run's own line says it, in place of "Used Gmail", beside Gmail's logo: not a line of its own. + const thinking = await view.findByText("Thinking"); + expect(view.getAllByText("Thinking")).toHaveLength(1); expect(thinking.getAttribute("role")).toBe("status"); - expect(thinking.classList.contains(SHIMMER)).toBe(true); + expect(thinking.closest(`.${SHIMMER}`)).not.toBeNull(); + expect( + thinking + .closest("summary") + ?.querySelector('[role="img"]') + ?.getAttribute("aria-label"), + ).toBe("Gmail"); // The turn ends: nothing says it is still working. view.rerender(transcript(run(true), false)); diff --git a/app/tests/step-rows-layout.fixture.tsx b/app/tests/step-rows-layout.fixture.tsx index 5aedbbafa8..14de596c2e 100644 --- a/app/tests/step-rows-layout.fixture.tsx +++ b/app/tests/step-rows-layout.fixture.tsx @@ -19,6 +19,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 +139,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); diff --git a/app/tests/step-rows-layout.test.tsx b/app/tests/step-rows-layout.test.tsx index 0ffca7fc0e..40013e3c25 100644 --- a/app/tests/step-rows-layout.test.tsx +++ b/app/tests/step-rows-layout.test.tsx @@ -47,13 +47,17 @@ const WINDOWS = [ { width: 1440, height: 900 }, ]; type Theme = (typeof THEMES)[number]; -type State = "running" | "done"; +type State = "running" | "done" | "tool-then-app"; /** The folded line of the search and the two pages read beside it. */ -const FOLDED = "Searched the web and read 2 pages"; const COMPLETED = "Worked through 3 steps"; /** The page read on its own. */ const SINGLE = "Read web pages"; +/** + * The turn that looked for a tool, then listed events on Google Calendar. Said after the app's + * name, so in lower case: "Google Calendar worked through 2 steps". + */ +const ON_ONE_APP = "worked through 2 steps"; function singleLine(page: Page) { return page @@ -171,15 +175,15 @@ 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(); + // The turn's one line, reading what the Bot said last. + await page + .locator('[data-slot="worked-for"] summary', { hasText: "press release" }) + .waitFor({ timeout: 15_000 }); } else { - await page.getByText(COMPLETED, { exact: true }).waitFor(); + await page + .getByText(state === "done" ? COMPLETED : ON_ONE_APP, { exact: true }) + .waitFor(); } - await page - .getByText("press release", { exact: false }) - .first() - .waitFor({ timeout: 15_000 }); await style(page); await page.evaluate(() => document.fonts.ready); await still(page); @@ -211,78 +215,64 @@ 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, +/** + * A step line by its words: where its words start, and the icon drawn before them. A line of its + * own by default; `inList`, a row of the same name inside what a folded line opens to. + */ +function line(page: Page, label: string, inList = false) { + return page.evaluate( + ([label, inList]) => { + const words = [...document.querySelectorAll("span")].find( + (span) => + span.childElementCount === 0 && + span.textContent === label && + (span.closest("li") !== null) === inList, + ); + 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 + 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( - box.left - - words.previousElementSibling.getBoundingClientRect().right, + icon.getBoundingClientRect().top + + icon.getBoundingClientRect().height / 2 - + (box.top + box.height / 2), ) : 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); + // 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, inList] as const, + ); } describe.skipIf(!asked)("a Bot's step lines among its words", () => { @@ -291,7 +281,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(`while it works, the turn is one line reading the Bot's words; done, it folds, the answer under it, ${where}`, async () => { const running = await open(engine, theme, window, "running"); const done = await open(engine, theme, window, "done"); try { @@ -308,45 +298,87 @@ describe.skipIf(!asked)("a Bot's step lines among its words", () => { ), }); } - const whileRunning = await gapAboveSingle(running); - expect(whileRunning).toBeGreaterThan(0); - expect(whileRunning).toBeLessThanOrEqual(40); + // Running: one line, shimmering, reading what the Bot said last over two lines or three, + // and nothing of the turn's steps or words beside it. + const placed = await running.evaluate(() => { + const summary = document.querySelector( + '[data-slot="worked-for"] summary', + ); + const chevron = summary?.querySelector(".tool-line-chevron"); + const icons = summary?.querySelector(".tool-line-running > span"); + const words = summary?.querySelector('[role="status"]'); + if (!summary || !chevron || !icons || !words) + throw new Error("no line, chevron, icons or words"); + const centre = (element: Element) => { + const box = element.getBoundingClientRect(); + return box.top + box.height / 2; + }; + const lineHeight = Number.parseFloat( + getComputedStyle(words).lineHeight, + ); + return { + running: summary.querySelector(".tool-line-running") !== null, + lines: Math.round( + words.getBoundingClientRect().height / lineHeight, + ), + // The chevron, the icons and the words' first line share one row. + chevronOffIcons: Math.abs(centre(chevron) - centre(icons)), + firstLineOffIcons: Math.abs( + words.getBoundingClientRect().top + + lineHeight / 2 - + centre(icons), + ), + }; + }); + expect(placed.running).toBe(true); + expect(placed.lines).toBeGreaterThanOrEqual(1); + expect(placed.lines).toBeLessThanOrEqual(3); + expect(placed.chevronOffIcons).toBeLessThan(1); + expect(placed.firstLineOffIcons).toBeLessThan(1.5); + expect( + await running + .locator('[data-message-id="on-the-way"]') + .isVisible(), + ).toBe(false); + expect(await singleLine(running).isVisible()).toBe(false); + + // Done: the line says what it did, the answer is under it, and what the Bot said on the + // way is inside it with its steps, in order, once it is opened. const summary = done .locator('[data-slot="worked-for"] summary') .filter({ hasText: COMPLETED, }); expect(await summary.count()).toBe(1); - expect(await singleLine(done).isVisible()).toBe(false); expect( await done.locator('[data-message-id="on-the-way"]').isVisible(), - ).toBe(true); + ).toBe(false); await summary.click(); - expect(await singleLine(done).isVisible()).toBe(true); + expect( + await done + .locator('[data-slot="worked-for"]') + .getByText("press release", { exact: false }) + .isVisible(), + ).toBe(true); + expect( + await done + .locator( + '[data-slot="worked-for"] ol[aria-label="Tool steps"] li', + { hasText: SINGLE }, + ) + // The folded search's list reads a page too; the single one is the turn's last. + .last() + .isVisible(), + ).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"); + test(`opened, a page read on its own is a row whose icon is bare, as every step's is, ${where}`, async () => { const done = await open(engine, theme, window, "done"); 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 .locator('[data-slot="worked-for"] summary') .filter({ @@ -355,16 +387,85 @@ describe.skipIf(!asked)("a Bot's step lines among its words", () => { .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, - }); + const row = await line(done, SINGLE, true); + expect(row.icon?.size).toEqual([16, 16]); + expect(row.tile?.background).toBe("rgba(0, 0, 0, 0)"); } finally { - await running.close(); await done.close(); } }, 60_000); + + test(`a step on no app is one more row of the list: its mark where the logos are, its words where theirs start, ${where}`, async () => { + const page = await open(engine, theme, window, "tool-then-app"); + try { + await page + .locator('[data-slot="worked-for"] summary') + .filter({ hasText: ON_ONE_APP }) + .click(); + 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 wrench = looked.li?.querySelector("svg"); + const logo = listed.li?.querySelector('[role="img"]'); + if (!wrench || !logo || !looked.label || !listed.label) + throw new Error("no wrench, logo or words"); + const centre = (element: Element) => { + const box = element.getBoundingClientRect(); + return box.left + box.width / 2; + }; + // No tile behind the wrench: bare, as the logo beside it is. + const tiled = [ + wrench.parentElement, + wrench.parentElement?.parentElement, + ] + .filter((element): element is HTMLElement => Boolean(element)) + .some( + (element) => + getComputedStyle(element).backgroundColor !== + "rgba(0, 0, 0, 0)", + ); + const lookedBox = looked.li?.getBoundingClientRect(); + const listedBox = listed.li?.getBoundingClientRect(); + return { + markApart: Math.abs(centre(wrench) - centre(logo)), + wordsApart: Math.abs( + looked.label.getBoundingClientRect().left - + listed.label.getBoundingClientRect().left, + ), + tiled, + heights: [lookedBox?.height, listedBox?.height], + // The rows sit one under the other, a row's gap apart (`space-y-2`), no wider. + gap: + lookedBox && listedBox + ? listedBox.top - lookedBox.bottom + : -1, + }; + }); + expect(placed.markApart).toBeLessThan(1); + expect(placed.wordsApart).toBeLessThan(1); + expect(placed.tiled).toBe(false); + expect(placed.heights[0]).toBe(placed.heights[1]); + expect(placed.gap).toBeGreaterThanOrEqual(0); + expect(placed.gap).toBeLessThanOrEqual(8); + } finally { + await page.close(); + } + }, 60_000); } }); diff --git a/app/tests/stopped-command-layout.test.tsx b/app/tests/stopped-command-layout.test.tsx index a5bc551a3f..be994d9197 100644 --- a/app/tests/stopped-command-layout.test.tsx +++ b/app/tests/stopped-command-layout.test.tsx @@ -463,12 +463,15 @@ describe.skipIf(!asked)("a command the person stopped", () => { await page.keyboard.type(ASKED); await page.getByRole("button", { name: "Send message" }).click(); - // Under way: the line says so and shimmers, and Stop is offered. - await page - .getByText("Running a command") - .first() - .waitFor({ timeout: 30_000 }); - expect((await readLine(page)).shimmers).toBe(1); + // Under way: the turn's one line shimmers, reading what the Bot said ("I'll build the + // report now."), and Stop is offered. The command's own line is inside it. + const turnLine = page + .locator('[data-slot="worked-for"][data-running] summary') + .first(); + await turnLine.waitFor({ timeout: 30_000 }); + expect(await turnLine.locator(".tool-line-running").count()).toBe( + 1, + ); await shoot(page, name("running")); const stop = page.getByRole("button", { name: "Stop the Bot" }); diff --git a/app/tests/stopped-turn-return-browser.test.tsx b/app/tests/stopped-turn-return-browser.test.tsx index edc2427ba9..b0b6206ba8 100644 --- a/app/tests/stopped-turn-return-browser.test.tsx +++ b/app/tests/stopped-turn-return-browser.test.tsx @@ -511,7 +511,7 @@ const go = (page: Page, to: string) => */ async function settled(page: Page) { await composer(page); - await page.getByText(PROMISE).waitFor({ timeout: 15_000 }); + await page.getByText(PROMISE).first().waitFor({ timeout: 15_000 }); // Past the join's deadline, its replay, the history read and the server's answer on the run. await sleep(4_000); } @@ -555,7 +555,7 @@ describe.skipIf(!asked)("a turn that ended in an error", () => { try { await page.goto(`${origin}${HERE}?quietMs=400&theme=${theme}`); await send(page, ASKED); - await page.getByText(PROMISE).waitFor({ timeout: 15_000 }); + await page.getByText(PROMISE).first().waitFor({ timeout: 15_000 }); // The person goes to start another conversation while the Bot works. await go(page, "/channel/new"); @@ -644,7 +644,7 @@ describe.skipIf(!asked)("a turn that ended in an error", () => { try { await page.goto(`${origin}${HERE}?quietMs=400&theme=light`); await send(page, ASKED); - await page.getByText(PROMISE).waitFor({ timeout: 15_000 }); + await page.getByText(PROMISE).first().waitFor({ timeout: 15_000 }); await go(page, "/channel/new"); await page.getByText("Somewhere else in OpenBot").waitFor(); await sleep(4_500); diff --git a/app/tests/subtask-step.test.tsx b/app/tests/subtask-step.test.tsx index 4caee8fb2b..03b53bfd85 100644 --- a/app/tests/subtask-step.test.tsx +++ b/app/tests/subtask-step.test.tsx @@ -166,13 +166,16 @@ async function openWork(view: Awaited>) { for (const fold of view.container.querySelectorAll("details:not([open])")) if (fold.parentElement?.localName !== "li") open(fold.querySelector("summary") as HTMLElement); + // A turn's steps are a list in its line; its subtasks are a list of their own (`SubtaskRows`). expect( - view.container.querySelector('[aria-label="Tool steps"]'), + view.container.querySelector( + '[aria-label="Tool steps"], [aria-label="Subtasks"]', + ), ).not.toBeNull(); }); } -/** The subtask's own row, opened, from inside the turn's folded work line. */ +/** The subtask's own row, opened: a row of its own in the conversation, or in a folded line's list. */ async function subtaskRow(view: Awaited>) { await openWork(view); const row = (await view.findByText("Subtask")).closest("li") as HTMLElement; @@ -180,9 +183,11 @@ async function subtaskRow(view: Awaited>) { return within(row); } -test("a subtask is one step of the turn's work line, not a card of its own", async () => { +test("a subtask is a row of its own that opens to its steps, not a card", async () => { const view = await draw(answered, { settled: true, busy: false }); - expect(await view.findByText("Ran a subtask")).toBeTruthy(); + // A row of its own in the conversation, with its own chevron: no card, and no line around it. + const subtasks = await view.findByRole("list", { name: "Subtasks" }); + expect(within(subtasks).getByText("Subtask")).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); @@ -276,7 +281,9 @@ test("a subtask given to another Bot names that Bot on its line, while it works answered.subagent.slice(0, 2), ); const row = await subtaskRow(working); - expect(await row.findByText("Designer · Working · 2 steps")).toBeTruthy(); + expect( + await row.findByText("Designer · List open tickets · 2 steps"), + ).toBeTruthy(); cleanup(); const done = await draw( @@ -306,9 +313,9 @@ test("while it works, the line says so, and the row opens to each step as the su const view = await draw(answered, { settled: false, busy: true }, [ ...answered.subagent.slice(0, 2), ]); - expect(await view.findByText("Working on a subtask…")).toBeTruthy(); + // Its row says it is working, the step it is on and how many it has taken, closed. const row = await subtaskRow(view); - expect(await row.findByText("Working · 2 steps")).toBeTruthy(); + expect(await row.findByText("List open tickets · 2 steps")).toBeTruthy(); expect(await row.findByText("Get account")).toBeTruthy(); expect(row.getByText("List open tickets")).toBeTruthy(); expect(row.getAllByText("In progress")).toHaveLength(2); @@ -359,7 +366,7 @@ test("a subtask its turn left behind says it never finished, and one the server expect(await refused.findByText("Blocked")).toBeTruthy(); }); -test("subtasks started together share one line that counts them while their turn runs", async () => { +test("subtasks started together are one list of rows while their turn runs, each with its own chevron", async () => { // Two calls in one step, neither answered yet: the second row is drawn under the first. const first = answered; const second = { ...handedBack, parentThreadId: answered.parentThreadId }; @@ -393,19 +400,24 @@ test("subtasks started together share one line that counts them while their turn />, ), ); - expect(await view.findByText("Working on 2 subtasks…")).toBeTruthy(); - await openWork(view); - expect(view.getAllByText("Subtask")).toHaveLength(2); - expect(view.getAllByText(/^Working( · \d+ steps?)?$/)).toHaveLength(2); + // One list, a row each, each opening on its own: no line over them that counts them. + const subtasks = await view.findByRole("list", { name: "Subtasks" }); + await waitFor(() => + expect(within(subtasks).getAllByText("Subtask")).toHaveLength(2), + ); + expect( + subtasks.querySelectorAll(":scope > li > details > summary"), + ).toHaveLength(2); + expect(view.queryByText(/Working on \d+ subtasks/)).toBeNull(); expect(view.queryByText("Not completed")).toBeNull(); }); /* * FOUND ON OPENBOT CLOUD, in a phone's browser: a Bot gave each row of a table to a subtask, and for - * minutes each line said only "Working", which reads the same as a Bot that has stopped. Its line, - * closed, now says how many steps it has taken and what it is doing, and keeps up as it works. + * minutes each line said only "Working", which reads the same as a Bot that has stopped. Its row, + * closed, says what it was asked, the step it is on and how many it has taken, and keeps up. */ -test("while it works, the folded line shows the subtask under way: what it was asked, the step it is on and how many it has taken", async () => { +test("while it works, its row shows what it was asked, the step it is on and how many it has taken", async () => { const threadId = await subagentThreadId( answered.parentThreadId, answered.call.id, @@ -413,18 +425,18 @@ test("while it works, the folded line shows the subtask under way: what it was a const view = await draw(answered, { settled: false, busy: true }, [ ...answered.subagent.slice(0, 2), ]); - expect(await view.findByText("Working on a subtask…")).toBeTruthy(); - // Nothing opened: the turn's line is folded, and what is under way shows beneath it. - const group = view - .getByText("Working on a subtask…") - .closest("details") as HTMLDetailsElement; - expect(group.open).toBe(false); - const line = () => within(view.getByRole("list", { name: "Working now" })); - expect(line().getByText(/For customer account Birch Labs/)).toBeTruthy(); - expect(await line().findByText("2 steps")).toBeTruthy(); - expect(line().getByText("List open tickets")).toBeTruthy(); + // Nothing opened: the row is closed, and says all of it. + const subtasks = await view.findByRole("list", { name: "Subtasks" }); + const row = () => + within(subtasks.querySelector(":scope > li summary") as HTMLElement); + expect(row().getByText(/For customer account Birch Labs/)).toBeTruthy(); + expect(await row().findByText("List open tickets · 2 steps")).toBeTruthy(); + expect( + (subtasks.querySelector(":scope > li > details") as HTMLDetailsElement) + .open, + ).toBe(false); - // The subagent takes another step: the line catches up without being opened. + // The subagent takes another step: the row catches up without being opened. served.set(threadId, [ ...answered.subagent.slice(0, 2), { @@ -441,17 +453,20 @@ test("while it works, the folded line shows the subtask under way: what it was a }, ]); /* - * The line's next read. In the browser it comes every few seconds on its own; under this test's + * The row's next read. In the browser it comes every few seconds on its own; under this test's * DOM the query library loaded before the window existed and keeps no timers, so the read is asked * for here, as its timer would, once a poll's interval has gone by. */ setSystemTime(new Date(Date.now() + SUBAGENT_POLL_MS)); await queryClient.refetchQueries({ queryKey: ["subagents"] }); setSystemTime(); - expect(await line().findByText("3 steps")).toBeTruthy(); - expect(line().getByText("Get account notes")).toBeTruthy(); + expect( + await row().findByText( + /^(Get account notes|Getting account notes) · 3 steps$/, + ), + ).toBeTruthy(); - // Done: nothing is under way, so nothing shows beneath the line. + // Done: it says how many steps it took, and nothing says it is working. view.rerender( wrap( answered.parentThreadId, @@ -462,7 +477,8 @@ test("while it works, the folded line shows the subtask under way: what it was a />, ), ); - expect(view.queryByRole("list", { name: "Working now" })).toBeNull(); + expect(await view.findByText(/\d+ steps?$/)).toBeTruthy(); + expect(view.queryByText(/^Working/)).toBeNull(); }, 30_000); /** A subagent deep into its work: hundreds of steps, each a call and its answer. */ @@ -510,9 +526,9 @@ test("a working subagent with hundreds of steps, whose thread takes seconds to r { settled: false, busy: true }, longThread(300), ); - const line = () => within(view.getByRole("list", { name: "Working now" })); + const subtasks = await view.findByRole("list", { name: "Subtasks" }); expect( - await line().findByText("300 steps", {}, { timeout: 6_000 }), + await within(subtasks).findByText(/ · 300 steps$/, {}, { timeout: 6_000 }), ).toBeTruthy(); }, 15_000); @@ -521,7 +537,7 @@ test("a working subagent with hundreds of steps, whose thread takes seconds to r * line in the folded turn every 5 s on a timer of its own: about fifty builds of the whole thread a * minute while a person watched one subagent work. */ -test("a working subagent shown opened and in the folded line is read once every five seconds, not fifty times a minute", async () => { +test("a working subagent shown opened and closed is read once every five seconds, not fifty times a minute", async () => { const clock = queryClock({ moveDate: true }); try { const view = await draw( @@ -542,3 +558,63 @@ test("a working subagent shown opened and in the folded line is read once every clock.stop(); } }, 15_000); + +test("a subtask started beside a search is a row of its own while the turn runs, the search in the turn's line", async () => { + served.set( + await subagentThreadId(answered.parentThreadId, answered.call.id), + answered.subagent.slice(0, 2), + ); + const view = render( + wrap( + answered.parentThreadId, + , + ), + ); + // The subtask: a row of its own, out of the turn's line, with nothing of the search in it. + const subtasks = await view.findByRole("list", { name: "Subtasks" }); + expect(within(subtasks).getAllByText("Subtask")).toHaveLength(1); + expect(subtasks.textContent).not.toMatch(/for a tool/); + // The search: in the turn's one line, which says it and has no subtask in it. + const line = view.container.querySelector( + '[data-slot="worked-for"][data-running] summary', + ); + expect(line?.textContent).toContain("Looking for a tool"); + expect( + view.container + .querySelector('[data-slot="worked-for"]') + ?.querySelector('[aria-label="Subtasks"]'), + ).toBeNull(); +}); diff --git a/app/tests/task-worked-for.test.tsx b/app/tests/task-worked-for.test.tsx index 4fe3049631..e09177aeb4 100644 --- a/app/tests/task-worked-for.test.tsx +++ b/app/tests/task-worked-for.test.tsx @@ -174,7 +174,8 @@ 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"), + // Its one app named first, and what was done carrying on from the name, in lower case. + 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 +193,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 +203,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-activity.test.tsx b/app/tests/tool-activity.test.tsx index 2c47c48c29..76358578d8 100644 --- a/app/tests/tool-activity.test.tsx +++ b/app/tests/tool-activity.test.tsx @@ -9,9 +9,9 @@ import { dropRepeatedAppCards, groupToolSteps, type StepDetails, + StepOutput, stepDetails, summarise, - StepOutput, ToolActivity, type ToolGroup, useDrawnTool, @@ -75,7 +75,7 @@ test("adjacent connector calls fold into one row named after the first", () => { }); }); -test("a subtask folds into the same line as the searches beside it, even though the app draws it", () => { +test("a subtask reads as one of the turn's steps beside the searches, even though the app draws it", () => { const subtask = call( "subtask", "run_subagent", @@ -90,8 +90,6 @@ test("a subtask folds into the same line as the searches beside it, even though fetch(["https://a.example/1"]), text("answer"), ]; - const grouped = groupToolSteps(items, () => true); - expect(grouped.map((item) => item.kind)).toEqual(["tools", "text"]); const steps = items.slice(0, 3).map((item) => stepDetails(item as ToolItem)); expect(steps[0]).toMatchObject({ kind: "subtask", 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..2d4c907a70 100644 --- a/app/tests/tool-result-parts.test.tsx +++ b/app/tests/tool-result-parts.test.tsx @@ -141,8 +141,10 @@ 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(); + // Said after its app's name, so in lower case. + fireEvent.click(view.getByText("worked through 1 step")); + // 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"); @@ -159,7 +161,8 @@ 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(); + fireEvent.click(await view.findByText("Lookup rows")); + await view.findByText(/"rows": 2/); expect(view.container.textContent).toContain('"rows": 2'); }); diff --git a/app/tests/work-folded-layout.test.tsx b/app/tests/work-folded-layout.test.tsx index e62e9d2b89..9d457ad0ee 100644 --- a/app/tests/work-folded-layout.test.tsx +++ b/app/tests/work-folded-layout.test.tsx @@ -387,26 +387,40 @@ describe.skipIf(!asked)("a Bot's work in a conversation", () => { name: "Conversation", }); - // One line for the run, shimmering, saying a command is running. - const line = conversation.locator("summary .tool-line-running", { - hasText: "Running a command…", - }); - expect(await line.count()).toBe(1); + // One line for the turn, shimmering: what the Bot said last, or what its step is doing. + const summary = conversation + .locator('[data-slot="worked-for"][data-running] summary') + .first(); + const line = summary.locator(".tool-line-running").first(); expect(await line.isVisible()).toBe(true); expect( await line.evaluate( (element) => getComputedStyle(element).animationName, ), ).toBe("tool-line-shimmer"); - // Under it, the command running now, shimmering too. - const now = conversation.getByRole("list", { name: "Working now" }); - expect(await now.isVisible()).toBe(true); - expect(await now.textContent()).toContain( - "python3 save_csv.py top-articles.csv", - ); + // Nothing is drawn under it: the line says it, and opened, it lists it. + expect( + await conversation + .getByRole("list", { name: "Working now" }) + .count(), + ).toBe(0); + // Opened, the command running now is one of its rows, named by what runs, shimmering. + await summary.click(); + const work = conversation + .locator('[data-slot="worked-for"]') + .first(); + expect( + await work + .getByText("python3 save_csv.py top-articles.csv", { + exact: false, + }) + .first() + .isVisible(), + ).toBe(true); expect( - await now + await work .locator(".tool-line-running", { hasText: "Running a command" }) + .first() .isVisible(), ).toBe(true); // What the commands printed stays behind the fold in the conversation. diff --git a/app/tests/work-folded.test.tsx b/app/tests/work-folded.test.tsx index 58667d3ece..ea7ba9e6a7 100644 --- a/app/tests/work-folded.test.tsx +++ b/app/tests/work-folded.test.tsx @@ -4,7 +4,13 @@ import { CopilotKitProvider } from "@copilotkit/react-core/v2"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; import { SEND_FILE_TOOL } from "@openbot/shared/send-file"; import { QueryClientProvider } from "@tanstack/react-query"; -import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; +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 { CodingTools } from "@/lib/copilot/coding-tools"; @@ -169,7 +175,7 @@ function lineOf(fold: HTMLDetailsElement): string { return summary.textContent ?? ""; } -test("regular chat folds finished app calls and keeps all answer text outside", async () => { +test("regular chat folds finished app calls with what was said on the way, and keeps the answer outside", async () => { const [ask, ...steps] = conversation([ { id: "notion-1", @@ -192,13 +198,30 @@ test("regular chat folds finished app calls and keeps all answer text outside", { 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(); + // While the turn runs, its one line says what its steps are doing, closed, and a screen reader + // hears it as it changes. + expect( + view.container + .querySelector('[data-slot="worked-for"]') + ?.getAttribute("data-running"), + ).toBe("true"); 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(); + const label = view.getByText("Using Notion…"); + // The app is its logo on the line, which says its name (to a screen reader, and on hover). + expect( + within(label.closest("summary") as HTMLElement).getByRole("img", { + name: "Notion", + }), + ).toBeTruthy(); + expect(label.getAttribute("role")).toBe("status"); + const line = label.closest("details"); + expect(line?.open).toBe(false); view.rerender(transcript([ask, ...steps.slice(0, 3)], true)); + // Two calls on Notion while the turn runs: the same line, shimmering, which opens to its steps. + const using = await view.findByText("Using Notion…"); + expect(using.closest("details")).toBe(line); + fireEvent.click(using); const liveSteps = view.getByRole("list", { name: "Tool steps" }); expect(liveSteps.textContent).toContain("Get page"); expect(view.getAllByText("Get page")).toHaveLength(1); @@ -208,17 +231,21 @@ test("regular chat folds finished app calls and keeps all answer text outside", '[data-slot="worked-for"] details', ); expect(fold?.open).toBe(false); + // After the one app's name, so in lower case: "Notion worked through 2 steps". 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); const completedSteps = view.getByRole("list", { name: "Tool steps" }); expect(completedSteps.textContent).toContain("Search pages"); expect(completedSteps.textContent).toContain("Get page"); + // Said before the steps, it folds with them once the turn is over, in order; the answer stays out. expect( - (await view.findByText("Here are the figures.")).closest("details"), - ).toBeNull(); + (await view.findByText("Here are the figures.")).closest( + '[data-slot="worked-for"]', + ), + ).not.toBeNull(); expect( (await view.findByText("The busiest day was Tuesday.")).closest("details"), ).toBeNull(); @@ -267,7 +294,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");