diff --git a/docs/app-guidelines.md b/docs/app-guidelines.md index dbc5085063..3c00133726 100644 --- a/docs/app-guidelines.md +++ b/docs/app-guidelines.md @@ -273,7 +273,9 @@ Native's, and builds its own only when neither fits. The development build shows - **A Bot's work shows as it happens, as in the web app.** From the moment a message is sent there is one row under it that says what the Bot is doing and only changes its words: "Thinking…", then each step in the web app's own words while it runs ("Search the web…"), then what the steps - were once they are over ("Took 2 steps"). The reply is written under it as it comes, as markdown, + did once they are over, in one phrase counted by kind as the web app's folded line says it + ("Searched the web and read 2 pages"). Opened, each step is a line after its kind's icon, on a thin + branch from that row, and never what the tool answered (`mobile/src/run-steps.ts`). The reply is written under it as it comes, as markdown, with what is half written closed or held back so no symbols show. Nothing is added to the page and taken away again, and a reply never steps back to a shorter reading of itself: a run that ended stays drawn from what the socket carried until the messages read back hold it in full diff --git a/mobile/app/conversation.tsx b/mobile/app/conversation.tsx index cd804777f2..528849925b 100644 --- a/mobile/app/conversation.tsx +++ b/mobile/app/conversation.tsx @@ -107,6 +107,12 @@ import { } from "../src/live-run"; import { conversationOf, showConversation } from "../src/on-screen"; import { measure, useOrbFlight, type ViewHandle } from "../src/orb-flight"; +import { + type KnownCalls, + knownCalls, + NO_CALLS, + stepLines, +} from "../src/run-steps"; import { connectAiRouteFor } from "../src/setup"; import { shownMessages } from "../src/shown-messages"; import { useLoad } from "../src/use-load"; @@ -128,16 +134,22 @@ type Item = | { kind: "day"; key: string; label: string } | { kind: "message"; key: string; message: ConversationMessage } // `going` is the step of a live run that is still under way, in the present tense: "Searching the web". - | { kind: "steps"; key: string; steps: string[]; going?: string } + | { + kind: "steps"; + key: string; + steps: ConversationMessage[]; + going?: string; + } | { kind: "approval"; key: string; request: Approval }; /** * A step a Bot took rather than something it said: a tool's own line, or a finished reply that only - * called tools. A run of them folds into one line, as the web app's transcript folds them. A reply - * that drew cards is not a step: its cards are drawn. + * called tools. A run of them folds into one line, as the web app's transcript folds them, and is + * said in its words when it is drawn (`stepLines`). A reply that drew cards is not a step: its cards + * are drawn. */ -function stepWords(message: ConversationMessage): string[] | null { - if (message.role === "tool") return [message.text || "Used a tool."]; +function stepsOf(message: ConversationMessage): ConversationMessage[] | null { + if (message.role === "tool") return [message]; if (drawable(message).length > 0) return null; if ( message.role === "bot" && @@ -147,9 +159,7 @@ function stepWords(message: ConversationMessage): string[] | null { message.status !== "waiting" && message.status !== "failed" ) - return message.toolCalls && message.toolCalls > 1 - ? [`Used ${message.toolCalls} tools.`] - : ["Used a tool."]; + return [message]; return null; } @@ -270,6 +280,13 @@ export function Conversation({ const liveNow = useRef(live); liveNow.current = live; const watcher = useRef<{ reconnect(): void } | null>(null); + /* + * Every tool call the socket carried here, the replay's runs that ended included, kept after their runs go: the + * messages read back hold a step as the tool's answer with no name, and it is named from these as the web app + * names it (../src/run-steps.ts). + */ + const [calls, setCalls] = useState(NO_CALLS); + useEffect(() => setCalls((held) => knownCalls(held, live)), [live]); // Whether the socket has gone quiet on a live run: true until it carries an event, and QUIET_MS after its last. const [quiet, setQuiet] = useState(true); // The runs Stop was pressed for: they are ending on the server, and the button waits for them. @@ -284,6 +301,7 @@ export function Conversation({ useEffect(() => { if (!channelId || !person) return; setLive([]); + setCalls(NO_CALLS); setDelivered(null); setAwaiting(null); setStopAsked(new Set()); @@ -325,7 +343,10 @@ export function Conversation({ ended(); }, onCaughtUp(runId) { - setLive(caughtUp(replay ?? liveNow.current, runId)); + const replayed = replay ?? liveNow.current; + // The runs that ended go from what is drawn live, but their steps are still named by what they called. + setCalls((held) => knownCalls(held, replayed)); + setLive(caughtUp(replayed, runId)); replay = null; // Whatever ended while the socket was away is in the messages now. void refreshHistory(); @@ -584,7 +605,7 @@ export function Conversation({ label: dayAndTime(message.createdAt), }); if (!Number.isNaN(at)) previous = at; - const steps = stepWords(message); + const steps = stepsOf(message); // A step of a live run that is still going is said as what the Bot is doing, under the ones that are over. const going = liveStep(message) === "running" ? message.text : undefined; const last = out[out.length - 1]; @@ -751,6 +772,8 @@ export function Conversation({ className="flex-1" inverted data={items} + // A run of steps is said in the words of the calls the socket carried, which can come after its messages. + extraData={calls} keyExtractor={(item) => item.key} keyboardDismissMode="interactive" keyboardShouldPersistTaps="handled" @@ -800,7 +823,7 @@ export function Conversation({ label={`${item.going}…`} /> ) : ( - + ) ) : item.kind === "approval" ? ( = { + search: IconSearch, + fetch: IconFileText, + browser: IconWorld, + connector: IconPlug, + tool: IconTool, + file: IconFileText, + directory: IconFolder, + command: IconTerminal2, + saved: IconFilePlus, + subtask: IconSubtask, +}; + +/** A step as text: what was done, and what it was done to after it, muted. */ +function StepText({ step, quiet }: { step: StepLine; quiet?: boolean }) { + return ( + + {step.label} + {step.detail ? ( + {` ${step.detail}`} + ) : null} + + ); +} + /** * What a Bot did between two things it said, folded into one quiet line, as the web app's transcript - * folds a run of steps: "Took 3 steps", which opens to each one. A single step is its own line. The - * transcript keeps the Bot's words and the person's in front, and the working out behind a tap. + * folds a run of steps: what they did, in one phrase ("Searched the web and read 2 pages"), which opens + * to each one. A single step is its own line. The transcript keeps the Bot's words and the person's in + * front, and the working out behind a tap. + * + * Each step is a line in the web app's words (../run-steps.ts), after its kind's icon: what was done, + * and what it was done to after it, muted, cut short at the end of the line. Never what the tool + * answered. Opened, the steps hang from the line on a thin branch, the last one closing it. */ -export function StepsLine({ steps }: { steps: string[] }) { +export function StepsLine({ steps }: { steps: StepLine[] }) { const [open, setOpen] = useState(false); + const [only] = steps; + if (!only) return null; // As tall as a Bot's working row and set in as far (`MessageWorking`), which this row takes the place of when a // run's steps are over: the words change, and nothing on the page moves. if (steps.length === 1) return ( - + - - {steps[0]} - + ); + const summary = summarise(steps); return ( setOpen((now) => !now)} - className="min-h-6 flex-row items-center gap-2 self-start active:opacity-60" + className="min-h-6 max-w-full flex-row items-center gap-2 self-start active:opacity-60" > - + - - Took {steps.length} steps + + {summary} {open ? ( - - {steps.map((step, index) => ( - - {step} - - ))} + + {steps.map((step, index) => { + const last = index === steps.length - 1; + return ( + + {/* The branch: down past every step but the last, which it turns into and ends at. */} + + + + + + + + + + ); + })} ) : null} diff --git a/mobile/src/icons.ts b/mobile/src/icons.ts index 2e9f90a4ea..19c1c8b8f0 100644 --- a/mobile/src/icons.ts +++ b/mobile/src/icons.ts @@ -8,8 +8,8 @@ export { default as IconAlertCircle } from "@tabler/icons-react-native/IconAlert export { default as IconAlertTriangle } from "@tabler/icons-react-native/IconAlertTriangle"; export { default as IconArchive } from "@tabler/icons-react-native/IconArchive"; export { default as IconArrowLeft } from "@tabler/icons-react-native/IconArrowLeft"; -export { default as IconArrowsExchange } from "@tabler/icons-react-native/IconArrowsExchange"; export { default as IconArrowUp } from "@tabler/icons-react-native/IconArrowUp"; +export { default as IconArrowsExchange } from "@tabler/icons-react-native/IconArrowsExchange"; export { default as IconBell } from "@tabler/icons-react-native/IconBell"; export { default as IconBook } from "@tabler/icons-react-native/IconBook"; export { default as IconBrain } from "@tabler/icons-react-native/IconBrain"; @@ -37,6 +37,9 @@ export { default as IconEdit } from "@tabler/icons-react-native/IconEdit"; export { default as IconEye } from "@tabler/icons-react-native/IconEye"; export { default as IconEyeOff } from "@tabler/icons-react-native/IconEyeOff"; export { default as IconFile } from "@tabler/icons-react-native/IconFile"; +export { default as IconFilePlus } from "@tabler/icons-react-native/IconFilePlus"; +export { default as IconFileText } from "@tabler/icons-react-native/IconFileText"; +export { default as IconFolder } from "@tabler/icons-react-native/IconFolder"; export { default as IconHistory } from "@tabler/icons-react-native/IconHistory"; export { default as IconInfoCircle } from "@tabler/icons-react-native/IconInfoCircle"; export { default as IconKey } from "@tabler/icons-react-native/IconKey"; @@ -63,7 +66,10 @@ export { default as IconSelector } from "@tabler/icons-react-native/IconSelector export { default as IconSettings } from "@tabler/icons-react-native/IconSettings"; export { default as IconShieldLock } from "@tabler/icons-react-native/IconShieldLock"; export { default as IconSparkles } from "@tabler/icons-react-native/IconSparkles"; +export { default as IconSubtask } from "@tabler/icons-react-native/IconSubtask"; +export { default as IconTerminal2 } from "@tabler/icons-react-native/IconTerminal2"; export { default as IconTool } from "@tabler/icons-react-native/IconTool"; export { default as IconTrash } from "@tabler/icons-react-native/IconTrash"; export { default as IconUsersGroup } from "@tabler/icons-react-native/IconUsersGroup"; +export { default as IconWorld } from "@tabler/icons-react-native/IconWorld"; export { default as IconX } from "@tabler/icons-react-native/IconX"; diff --git a/mobile/src/live-run.ts b/mobile/src/live-run.ts index 93b4ad18fa..6ddfb18433 100644 --- a/mobile/src/live-run.ts +++ b/mobile/src/live-run.ts @@ -34,6 +34,8 @@ type LiveTool = { answered: boolean; /** What the call answered, for a question the person was asked. */ result?: string; + /** The message the answer came in: the id the conversation's messages read the answer back by. */ + resultId?: string; }; /** A step's id as a message's, so a row keeps its place from the step's start to its end. */ @@ -266,11 +268,13 @@ export function reduce(runs: LiveRuns, event: LiveEvent): LiveRuns { return withTool(runs, event, (tool) => ({ ...tool, done: true })); case "TOOL_CALL_RESULT": { const content = event.content; + const resultId = messageOf(event); return withTool(runs, event, (tool) => ({ ...tool, done: true, answered: true, ...(typeof content === "string" ? { result: content } : {}), + ...(resultId ? { resultId } : {}), })); } default: @@ -327,6 +331,15 @@ export function liveStep( return message.status === "running" ? "running" : "over"; } +/** The tool call one of a live run's steps stands for, by its id; null for any other message. */ +export function liveStepCall( + message: Pick, +): string | null { + return message.role === "tool" && message.id.startsWith(STEP) + ? message.id.slice(STEP.length) + : null; +} + /** What the person answered the questions a live run asked, by tool call. */ export function liveAnswers(runs: LiveRuns): Map { const out = new Map(); @@ -415,8 +428,9 @@ export function sentAgain(runs: LiveRuns): LiveRuns { * * Each step the Bot takes follows the message it is part of, as a `tool` message in the web app's words for it * (./shared-copy/tool-name.js): `running` while it is going and said as what it is doing, then over and said as what - * it did ({@link liveStep}). The read messages hold a step by the server's words for it and nothing else, so as - * many of the steps that are over are left out as the read messages hold since the person last spoke. After a step that is over, with nothing written yet, the Bot + * it did ({@link liveStep}). The read messages hold a step as the tool's answer and nothing else, which + * ./run-steps.ts says in the same words as here, so as many of the steps that are over are left out as the read + * messages hold since the person last spoke. After a step that is over, with nothing written yet, the Bot * is thinking again, which is said as one more step under way ({@link THINKING}), on the same row. */ export function asMessages( diff --git a/mobile/src/run-steps.ts b/mobile/src/run-steps.ts new file mode 100644 index 0000000000..33fd188976 --- /dev/null +++ b/mobile/src/run-steps.ts @@ -0,0 +1,324 @@ +/** + * What a Bot's steps say in a conversation, as the web app's transcript says them + * (app/src/components/channels/tool-activity.tsx): one line a step, in the web app's words for the tool it called + * (./shared-copy/tool-name.js), with what it was done to beside it: the search, the site a page is on, the app, the + * command, the file. Never what the tool answered. That was written for the Bot, and the web app keeps it behind a + * second tap, cut short. + * + * A step read back over REST is a `tool` message whose text is the tool's answer and nothing else: it has no name. + * Its name is the one the conversation's live socket carried for the same call ({@link knownCalls}), found by the + * message its answer came in, by the call's id, or by the answer itself. A step whose call was never seen says only + * that the Bot used a tool. + */ +import type { ConversationMessage } from "./api/generated/model"; +import { isDrawn } from "./gallery/drawn"; +import { type LiveRuns, liveStep, liveStepCall, stepWords } from "./live-run"; +import { readToolName, researchRoleOfToolName } from "./shared-copy/tool-name"; + +/** + * What kind of step a line is, as the web app sorts its steps (`StepKind` in tool-activity.tsx): it picks the line's + * icon, and how the folded line counts it ({@link summarise}). + */ +export type StepKind = + | "search" + | "fetch" + | "browser" + | "connector" + | "tool" + | "file" + | "directory" + | "command" + | "saved" + | "subtask"; + +/** + * One step as a line: what was done, and what it was done to, muted beside it. `pages` is how many pages a read + * read, and `app` the app a connector step used, which the folded line counts and names. + */ +export type StepLine = { + label: string; + detail?: string; + kind: StepKind; + pages?: number; + app?: string; +}; + +/** A tool call a Bot made: its name, and its arguments as the run sent them (JSON). */ +export type KnownCall = { name: string; args: string }; + +/** + * The tool calls a conversation's runs made, by each id the conversation's messages may read a step back by: the + * call's own, and the message its answer came in. Also by the answer itself, for a step read back under an id of its + * own; null where calls that differ answered the same. + */ +export type KnownCalls = ReadonlyMap; + +export const NO_CALLS: KnownCalls = new Map(); + +/** A step whose call was never seen: all that is known is that the Bot used a tool. */ +const USED_A_TOOL = "Used a tool"; + +/** The browser steps on a Bot's computer, as the web app lists them (`BROWSER_STEPS` in browser-activity.tsx). */ +const BROWSER_STEPS = new Set([ + "computer_navigate", + "computer_read", + "computer_snapshot", + "computer_click", + "computer_type", + "computer_key", + "computer_scroll", +]); + +/** The web app's tool that hands work to a subtask (shared/subagent.ts `SUBAGENT_TOOL`). */ +const SUBTASK_TOOL = "run_subagent"; + +/** What kind of step a call is, as the web app's `detailsOf` sorts it. */ +export function kindOf(name: string): StepKind { + const role = researchRoleOfToolName(name); + if (role) return role; + if (name.startsWith("mcp__")) return "connector"; + if (BROWSER_STEPS.has(name)) return "browser"; + if (name === SUBTASK_TOOL) return "subtask"; + if (name === "computer_run_command") return "command"; + if (name === "computer_write_file") return "saved"; + if (name === "computer_read_file") return "file"; + if (name === "computer_list_files") return "directory"; + return "tool"; +} + +/** The steps on a Bot's computer that name the file or folder they were done to. */ +const FILE_STEPS = new Set([ + "computer_read_file", + "computer_write_file", + "computer_list_files", +]); + +const answerKey = (answer: string) => `answer:${answer.trim()}`; + +const same = (a: KnownCall | null, b: KnownCall | null) => + a === b || + (a !== null && b !== null && a.name === b.name && a.args === b.args); + +/** + * `held`, with the calls of `runs` added: each one whose arguments are whole, or all there will be once its run + * ended. `held` itself when nothing is new, so a screen that keeps them is not drawn again for every word a reply + * streams. + */ +export function knownCalls(held: KnownCalls, runs: LiveRuns): KnownCalls { + let next: Map | null = null; + const put = (key: string, call: KnownCall | null) => { + const now = (next ?? held).get(key); + if (now !== undefined && same(now, call)) return; + next ??= new Map(held); + next.set(key, call); + }; + for (const run of runs) + for (const tool of run.tools) { + if (!tool.done && !run.ended) continue; + const call = { name: tool.name, args: tool.args }; + put(tool.id, call); + if (tool.resultId) put(tool.resultId, call); + const answer = tool.result?.trim(); + if (!answer) continue; + const had = (next ?? held).get(answerKey(answer)); + put( + answerKey(answer), + had === undefined || (had !== null && same(had, call)) ? call : null, + ); + } + return next ?? held; +} + +/** The call a step stands for, when the conversation's runs carried it. */ +function callOf( + message: ConversationMessage, + known: KnownCalls, +): KnownCall | null { + const live = liveStepCall(message); + if (live !== null) return known.get(live) ?? null; + return ( + known.get(message.id) ?? + (message.text.trim() ? known.get(answerKey(message.text)) : null) ?? + null + ); +} + +/** + * A run of steps as lines, oldest first, as the web app's folded line opens to them: a `tool` message for each step + * (one a live run is taking, or one read back), and a Bot's reply that only called tools. Such a reply is said only + * where no step follows it: when the server recorded each step after it, those say what it did. A question the Bot + * drew a card for is answered in a `tool` message too, and is no step: its card is drawn. + */ +export function stepLines( + steps: readonly ConversationMessage[], + known: KnownCalls, +): StepLine[] { + const said: (KnownCall | string)[] = []; + steps.forEach((message, index) => { + if (message.role === "tool") { + const call = callOf(message, known); + if (call && isDrawn(call.name)) return; + // A live step already says what it did in these words. A step read back holds only the tool's answer. + said.push( + call ?? + (liveStep(message) && message.text ? message.text : USED_A_TOOL), + ); + return; + } + if (steps[index + 1]?.role === "tool") return; + said.push( + message.toolCalls && message.toolCalls > 1 + ? `Used ${message.toolCalls} tools` + : USED_A_TOOL, + ); + }); + const alone = said.length === 1; + return said.map((step) => + typeof step === "string" + ? { label: step, kind: "tool" } + : stepLine(step, alone), + ); +} + +/** + * One call as a line, as the web app draws it in the list a folded line opens to: "Search the web" and what was + * searched, "Read web pages" and the site, "Send email" and "Gmail". `alone`, it is the step's own line, as the web + * app's line for one call: a search that is over reads "Searched the web", and research names nothing beside it. + */ +export function stepLine(call: KnownCall, alone = false): StepLine { + const role = researchRoleOfToolName(call.name); + const args = objectOf(call.args); + const kind = kindOf(call.name); + const label = alone + ? stepWords(call.name, false) + : readToolName(call.name).label; + const detail = alone && role ? undefined : detailOf(call.name, args, role); + const app = kind === "connector" ? readToolName(call.name).detail : undefined; + return { + label, + kind, + ...(detail ? { detail } : {}), + ...(kind === "fetch" ? { pages: Math.max(urlsOf(args).length, 1) } : {}), + ...(app ? { app } : {}), + }; +} + +/** + * What a run of steps did, as one phrase on the line they fold into, as the web app says it (`summarise` in + * tool-activity.tsx): "Searched the web and read 2 pages". Counted by kind, because the list is what the line + * opens to. An app is named, because which one was reached is the person's own fact. + */ +export function summarise(lines: readonly StepLine[]): string { + const of = (kind: StepKind) => lines.filter((line) => line.kind === kind); + const phrases: string[] = []; + const files = of("file").length; + if (files) phrases.push(`read ${plural(files, "file", "files")}`); + const directories = of("directory").length; + if (directories) + phrases.push(`listed ${plural(directories, "directory", "directories")}`); + if (of("search").length) phrases.push("searched the web"); + const read = of("fetch").reduce((sum, line) => sum + (line.pages ?? 1), 0); + if (read) phrases.push(`read ${plural(read, "page", "pages")}`); + if (of("browser").length) phrases.push("used the browser"); + const commands = of("command").length; + if (commands) + phrases.push(commands === 1 ? "ran a command" : `ran ${commands} commands`); + const saved = of("saved").length; + if (saved) + phrases.push(saved === 1 ? "saved a file" : `saved ${saved} files`); + const apps = [ + ...new Set(of("connector").map((line) => line.app ?? "")), + ].filter(Boolean); + if (apps.length === 1) phrases.push(`used ${apps[0]}`); + else if (apps.length > 1) + phrases.push(`used ${plural(apps.length, "app", "apps")}`); + const unnamed = of("connector").filter((line) => !line.app).length; + const subtasks = of("subtask").length; + if (subtasks) + phrases.push(subtasks === 1 ? "ran a subtask" : `ran ${subtasks} subtasks`); + const tools = of("tool").length + unnamed; + if (tools) phrases.push(`used ${plural(tools, "tool", "tools")}`); + const sentence = + phrases.length > 1 + ? `${phrases.slice(0, -1).join(", ")} and ${phrases.at(-1)}` + : (phrases[0] ?? `took ${plural(lines.length, "step", "steps")}`); + return sentence.charAt(0).toUpperCase() + sentence.slice(1); +} + +function plural(count: number, one: string, many: string): string { + return count === 1 ? `1 ${one}` : `${count} ${many}`; +} + +/** What a step was done to, as the web app's list says it beside the step (`detailsOf` in tool-activity.tsx). */ +function detailOf( + name: string, + args: Record, + role: "search" | "fetch" | null, +): string | undefined { + if (name === "computer_run_command") return oneLine(args.command); + if (FILE_STEPS.has(name)) return oneLine(args.path); + if (!name.startsWith("mcp__")) return undefined; + if (role === "search") + return oneLine( + firstString( + args.query, + args.objective, + args.search_queries, + args.queries, + ), + ); + if (role === "fetch") { + const [first, ...more] = urlsOf(args); + if (!first) return undefined; + return more.length + ? `${hostOf(first)} and ${more.length} more` + : hostOf(first); + } + return readToolName(name).detail; +} + +function objectOf(value: string): Record { + try { + const parsed: unknown = JSON.parse(value); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) + ? (parsed as Record) + : {}; + } catch { + return {}; + } +} + +/** A value as one line, as the web app's line truncates it: its whitespace run together. */ +function oneLine(value: unknown): string | undefined { + if (typeof value !== "string") return undefined; + return value.replace(/\s+/g, " ").trim() || undefined; +} + +function firstString(...values: unknown[]): string | undefined { + for (const value of values) { + if (typeof value === "string" && value.trim()) return value.trim(); + if (Array.isArray(value)) { + const found = value.find( + (entry): entry is string => typeof entry === "string" && !!entry.trim(), + ); + if (found) return found.trim(); + } + } + return undefined; +} + +function urlsOf(args: Record): string[] { + const urls = Array.isArray(args.urls) ? args.urls : [args.url]; + return urls.filter( + (url): url is string => typeof url === "string" && !!url.trim(), + ); +} + +/** The site an address is on, without `www.`; the address itself where it isn't one. */ +function hostOf(url: string): string { + try { + return new URL(url).hostname.replace(/^www\./, "") || url; + } catch { + return url; + } +} diff --git a/mobile/tests/run-steps.test.ts b/mobile/tests/run-steps.test.ts new file mode 100644 index 0000000000..9a2e6717fc --- /dev/null +++ b/mobile/tests/run-steps.test.ts @@ -0,0 +1,266 @@ +/** + * A Bot's steps say what the web app's transcript says of them: one line a step, in its words for the tool, with what + * the step was done to beside it, and never what the tool answered. + */ +import { expect, test } from "bun:test"; +import type { ConversationMessage } from "../src/api/generated/model"; +import { asMessages, type LiveRuns, reduce } from "../src/live-run"; +import type { LiveEvent } from "../src/live-thread"; +import { + kindOf, + knownCalls, + NO_CALLS, + stepLine, + stepLines, + summarise, +} from "../src/run-steps"; + +const play = (events: LiveEvent[], from: LiveRuns = []) => + events.reduce(reduce, from); +/** One call of run r1, from its start to its answer. */ +const call = ( + id: string, + name: string, + args: unknown, + answer?: { messageId: string; content: string }, +): LiveEvent[] => [ + { type: "TOOL_CALL_START", toolCallId: id, toolCallName: name }, + { type: "TOOL_CALL_ARGS", toolCallId: id, delta: JSON.stringify(args) }, + { type: "TOOL_CALL_END", toolCallId: id }, + ...(answer + ? [{ type: "TOOL_CALL_RESULT", toolCallId: id, ...answer, role: "tool" }] + : []), +]; +const read = ( + id: string, + role: ConversationMessage["role"], + text: string, + more: Partial = {}, +): ConversationMessage => ({ + id, + role, + personId: null, + botId: "b1", + text, + status: "completed", + createdAt: "2026-11-30T10:00:00.000Z", + ...more, +}); + +/** What a fetch tool answers: a whole page, as it was written for the Bot. */ +const ARTICLE = + '{"content":"# The best pizza in Naples\\n\\nNaples is the home of pizza.\\n\\n## Where to go\\n\\n…"}'; +const SEARCHED = + '{"results":[{"title":"Pizza","url":"https://example.com/pizza"}]}'; + +const run = play([ + { type: "RUN_STARTED", runId: "r1" }, + ...call( + "c1", + "mcp__exa__web_search_exa", + { query: "best pizza\nin Naples" }, + { messageId: "t1", content: SEARCHED }, + ), + ...call( + "c2", + "mcp__parallel__web_fetch", + { + urls: ["https://www.example.com/pizza", "https://other.org/a"], + }, + { messageId: "t2", content: ARTICLE }, + ), + { type: "RUN_FINISHED", runId: "r1" }, +]); +const known = knownCalls(NO_CALLS, run); + +test("a step read back never says what the tool answered", () => { + const lines = stepLines( + [read("t9", "tool", ARTICLE), read("t8", "tool", "x".repeat(5000))], + NO_CALLS, + ); + expect(lines).toMatchObject([ + { label: "Used a tool" }, + { label: "Used a tool" }, + ]); + expect(JSON.stringify(lines)).not.toContain("pizza"); +}); + +test("a step read back is named by the call its answer came from, with what it was done to", () => { + expect( + stepLines( + [read("t1", "tool", SEARCHED), read("t2", "tool", ARTICLE)], + known, + ), + ).toMatchObject([ + { label: "Search the web", detail: "best pizza in Naples" }, + { label: "Read web pages", detail: "example.com and 1 more" }, + ]); +}); + +test("on a line of its own, a search that is over reads as done and names nothing beside it", () => { + expect(stepLines([read("t1", "tool", SEARCHED)], known)).toMatchObject([ + { label: "Searched the web" }, + ]); +}); + +test("a step read back under an id of its own is found by its answer, unless calls that differ answered the same", () => { + expect( + stepLines([read("other", "tool", ` ${ARTICLE}\n`)], known), + ).toMatchObject([{ label: "Read web pages" }]); + const twice = knownCalls( + known, + play([ + { type: "RUN_STARTED", runId: "r2" }, + ...call( + "c3", + "computer_click", + {}, + { messageId: "t3", content: ARTICLE }, + ), + ]), + ); + expect(stepLines([read("other", "tool", ARTICLE)], twice)).toMatchObject([ + { label: "Used a tool" }, + ]); + // Its own id still names it. + expect(stepLines([read("t2", "tool", ARTICLE)], twice)).toMatchObject([ + { label: "Read web pages" }, + ]); +}); + +test("a reply that only called tools is said once: by its steps when they follow it, else by itself", () => { + const reply = read("m1", "bot", "", { toolCalls: 2 }); + expect( + stepLines( + [reply, read("t1", "tool", SEARCHED), read("t2", "tool", ARTICLE)], + known, + ), + ).toHaveLength(2); + expect(stepLines([reply], known)).toMatchObject([{ label: "Used 2 tools" }]); + expect( + stepLines([read("m2", "bot", "", { toolCalls: 1 })], known), + ).toMatchObject([{ label: "Used a tool" }]); +}); + +test("a live run's steps keep their words, and say what they were done to once their call is known", () => { + const going = play([ + { type: "RUN_STARTED", runId: "r3" }, + ...call( + "c4", + "computer_run_command", + { command: "ls -la\n /tmp" }, + { messageId: "t4", content: "total 0" }, + ), + ...call( + "c5", + "mcp__composio-gmail__GMAIL_SEND_EMAIL", + { to: "a@b.c" }, + { + messageId: "t5", + content: '{"ok":true}', + }, + ), + ]); + const steps = asMessages(going, []).filter((m) => m.role === "tool"); + // Newest first, as the API lists them: the steps of one row are oldest first. + const row = steps.filter((m) => m.status !== "running").reverse(); + expect(stepLines(row, NO_CALLS).map((line) => line.label)).toEqual([ + "Ran a command", + "Send email", + ]); + expect(stepLines(row, knownCalls(NO_CALLS, going))).toMatchObject([ + { label: "Ran a command", detail: "ls -la /tmp" }, + { label: "Send email", detail: "Gmail" }, + ]); +}); + +test("a question's answer is no step: its card is drawn", () => { + const asked = knownCalls( + NO_CALLS, + play([ + { type: "RUN_STARTED", runId: "r4" }, + ...call( + "q1", + "askChoice", + { question: "Which?" }, + { messageId: "t6", content: '{"choice":"production"}' }, + ), + ]), + ); + expect( + stepLines([read("t6", "tool", '{"choice":"production"}')], asked), + ).toEqual([]); +}); + +test("calls already kept are kept as they are, so nothing is drawn again for a reply's words", () => { + expect(knownCalls(known, run)).toBe(known); + const writing = play( + [ + { type: "TEXT_MESSAGE_START", runId: "r1", messageId: "m9" }, + { type: "TEXT_MESSAGE_CONTENT", messageId: "m9", delta: "Here." }, + ], + run, + ); + expect(knownCalls(known, writing)).toBe(known); + // A call whose arguments are still arriving is not kept yet. + const half = play([ + { type: "RUN_STARTED", runId: "r5" }, + { type: "TOOL_CALL_START", toolCallId: "c6", toolCallName: "x" }, + ]); + expect(knownCalls(NO_CALLS, half)).toBe(NO_CALLS); +}); + +test("a step's line names what it was done to as the web app's list does", () => { + expect( + stepLine({ + name: "computer_write_file", + args: '{"path":"notes.txt"}', + }), + ).toMatchObject({ label: "Saved a file", detail: "notes.txt" }); + expect( + stepLine({ name: "mcp__parallel__web_fetch", args: '{"url":"nope"}' }), + ).toMatchObject({ label: "Read web pages", detail: "nope" }); + expect( + stepLine({ name: "mcp__exa__web_search_exa", args: "{not json" }), + ).toMatchObject({ label: "Search the web" }); + expect( + stepLine({ + name: "mcp__exa__web_search_exa", + args: '{"search_queries":["", "pizza"]}', + }), + ).toMatchObject({ label: "Search the web", detail: "pizza" }); +}); + +test("each step has its kind, which picks its icon as the web app's list does", () => { + expect(kindOf("mcp__exa__web_search_exa")).toBe("search"); + expect(kindOf("computer_run_command")).toBe("command"); + expect(kindOf("computer_write_file")).toBe("saved"); + expect(kindOf("computer_read_file")).toBe("file"); + expect(kindOf("computer_list_files")).toBe("directory"); + expect(kindOf("computer_navigate")).toBe("browser"); + expect(kindOf("run_subagent")).toBe("subtask"); + expect(kindOf("save_memory")).toBe("tool"); +}); + +test("a run of steps is said in one phrase, counted by kind, as the web app's folded line says it", () => { + expect( + summarise([ + { label: "Search the web", kind: "search" }, + { label: "Read web pages", kind: "fetch", pages: 2 }, + { label: "Opened page", kind: "fetch" }, + ]), + ).toBe("Searched the web and read 3 pages"); + expect( + summarise([ + { label: "Ran a command", kind: "command" }, + { label: "Ran a command", kind: "command" }, + { label: "Read a file", kind: "file" }, + ]), + ).toBe("Read 1 file and ran 2 commands"); + expect( + summarise([ + { label: "Send email", kind: "connector", app: "Gmail" }, + { label: "Used a tool", kind: "tool" }, + ]), + ).toBe("Used Gmail and used 1 tool"); +});