TypeScript
feat(clients): live row shows the agent's latest thought (#16284)
Theo Browne95ccbf406626
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex c18874b1cb0..b5f258a0889 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -1628,6 +1628,7 @@ function renderFeedEntry(summaryToolIcon={entry.summaryToolIcon}hasFailure={entry.hasFailure}shimmer={entry.shimmer}+ thought={entry.thought}onToggle={() => props.onToggleWorkGroup(entry.groupId, entry.id)}/>);@@ -2937,6 +2938,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {case "run-fold":return resolveThreadFeedFixedItemSize(entry.type);case "work-toggle":+ // A live thought wraps up to four lines, so that row measures itself.+ return entry.thought ? undefined : WORK_GROUP_TOGGLE_HEIGHT;case "thinking":return WORK_GROUP_TOGGLE_HEIGHT;case "activity-group":diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsxindex 4a906752951..32e6d272b67 100644--- a/apps/mobile/src/features/threads/thread-work-log.tsx+++ b/apps/mobile/src/features/threads/thread-work-log.tsx@@ -1222,11 +1222,11 @@ export function ThreadWorkGroupToggle(props: {readonly toolIcon?: ToolActivityIcon;readonly hasFailure: boolean;readonly shimmer: boolean;+ readonly thought?: string | undefined;readonly onToggle: () => void;}) {- const accessibilityLabel = props.hasFailure- ? `${props.summary}, tool call failed`- : props.summary;+ const statusLabel = props.hasFailure ? `${props.summary}, tool call failed` : props.summary;+ const accessibilityLabel = props.thought ? `${props.thought} ${statusLabel}` : statusLabel;const icon =props.summaryToolIcon ??(props.toolSurface@@ -1235,6 +1235,28 @@ export function ThreadWorkGroupToggle(props: {return (<WorkLogBlock layout="group-header">+ {props.thought ? (+ // The latest thought sits above the status line as an ordinary work-log+ // row, wrapped up to four lines.+ <Pressable+ accessible={false}+ onPress={props.onToggle}+ className="flex-row items-start gap-1.5 rounded-md px-0.5 active:bg-subtle"+ >+ <WorkLogIconSlot>+ <WorkLogIcon icon="brain" color={props.iconSubtleColor} />+ </WorkLogIconSlot>+ <Text+ key={props.rowSizing.textSizeKey}+ selectable={false}+ numberOfLines={4}+ ellipsizeMode="tail"+ className="min-w-0 flex-1 py-0.5 text-sm text-foreground-muted"+ >+ {props.thought}+ </Text>+ </Pressable>+ ) : null}<WorkLogPressableaccessibilityRole="button"accessibilityState={{ expanded: props.expanded }}diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.tsindex 6743876a2fe..d88e840ba40 100644--- a/apps/mobile/src/lib/threadActivity.test.ts+++ b/apps/mobile/src/lib/threadActivity.test.ts@@ -2279,7 +2279,8 @@ it.each(["First paragraph.\n\nSecond paragraph.", ""])();if (text) {expect(rows.find((row) => row.type === "work-toggle")).toMatchObject({- summary: "First paragraph. Second paragraph.",+ summary: "Thinking",+ thought: "First paragraph.",live: true,});} else {@@ -2293,6 +2294,32 @@ it.each(["First paragraph.\n\nSecond paragraph.", ""])(},);+it("keeps the latest thought under the live tool status", () => {+ const at = "2026-06-20T00:00:02.000Z";+ const thought: OrchestrationV2TurnItem = {+ ...base("found-thought", at, 1),+ type: "reasoning",+ status: "completed",+ streaming: false,+ text: "Found the cause: no commits yet. Checking the UI next.",+ };+ const tool = { ...command(at), status: "running" as const, completedAt: null };+ const rows = deriveThreadFeedPresentation(+ buildThreadFeed([projected(userMessage(), 0), projected(thought, 1), projected(tool, 2)]),+ { runId, status: "running", startedAt: at, completedAt: null },+ new Set(),+ new Set(),+ at,+ );+ expect(rows.find((row) => row.type === "work-toggle")).toMatchObject({+ thought: "Found the cause: no commits yet.",+ live: true,+ });+ expect(rows.find((row) => row.type === "work-toggle")).not.toMatchObject({+ summary: "Thinking",+ });+});+it("stops stranded thinking after a steer and follows the next thought or tool", () => {const at = "2026-06-20T00:00:02.000Z";const thought = (id: string): OrchestrationV2TurnItem => ({@@ -2316,7 +2343,8 @@ it("stops stranded thinking after a steer and follows the next thought or tool",at,);expect(rows([first]).find((row) => row.type === "work-toggle")).toMatchObject({- summary: "first-thought",+ summary: "Thinking",+ thought: "first-thought",live: true,shimmer: true,});@@ -2340,9 +2368,11 @@ it("stops stranded thinking after a steer and follows the next thought or tool",]) {const live = rows(items).filter((row) => row.type === "work-toggle" && row.shimmer);expect(live).toHaveLength(1);- expect(live[0]).toMatchObject({- summary: items.at(-1)!.type === "reasoning" ? "next-thought" : "Running vp",- });+ expect(live[0]).toMatchObject(+ items.at(-1)!.type === "reasoning"+ ? { summary: "Thinking", thought: "next-thought" }+ : { summary: "Running vp" },+ );}expect(first.status).toBe("running");});diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.tsindex d88b1dba2ea..2dc513e40f0 100644--- a/apps/mobile/src/lib/threadActivity.ts+++ b/apps/mobile/src/lib/threadActivity.ts@@ -18,6 +18,7 @@ import {} from "@t3tools/client-runtime/work-log/command-label";import {contextCompactionLabel,+ liveThoughtLine,toolItemForDisplay,workEntryDisplayIndicatesToolFailure,liveActivityToolStatus,@@ -213,6 +214,8 @@ type ThreadFeedEntryContent =readonly hasFailure: boolean;readonly live: boolean;readonly shimmer: boolean;+ /** First sentence of the latest thought, shown above the live status line. */+ readonly thought?: string;}| {readonly type: "run-fold";@@ -1496,8 +1499,17 @@ function appendToolGroupRows(const shimmer = activeTail && (active || latestActivity.status === "success");const singleActivity = activities.length === 1 ? latestActivity : null;const groupSummary = summarizeToolGroup(activities.map((activity) => activity.workEntry));+ const latestThought =+ live && !expanded+ ? activities.findLast(+ (activity) =>+ activity.workEntry.itemType === "reasoning" &&+ (activity.workEntry.detail?.trim() ?? "") !== "",+ )?.workEntry.detail+ : undefined;+ const thought = latestThought ? liveThoughtLine(latestThought) : "";const summary = live- ? expanded && latestActivity.workEntry.itemType === "reasoning"+ ? (expanded || thought) && latestActivity.workEntry.itemType === "reasoning"? latestActivity.lifecycleStatus === "inProgress"? "Thinking": "Thought"@@ -1552,6 +1564,7 @@ function appendToolGroupRows(...(groupToolSurface ? { toolSurface: groupToolSurface } : {}),...(groupToolIcon ? { toolIcon: groupToolIcon } : {}),...(summaryToolIcon ? { summaryToolIcon } : {}),+ ...(thought ? { thought } : {}),hasFailure: (() => {const lastToolLike = activities.findLast((activity) => activity.toolLike);return (diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.tsindex e1ce7145d63..98339041f68 100644--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts@@ -2044,6 +2044,60 @@ describe("deriveMessagesTimelineRows", () => {expect(rows.some((row) => row.kind === "thinking")).toBe(false);});+ it("carries the latest thought on the live row while a later tool runs", () => {+ type WorkEntry = Extract<+ Parameters<typeof deriveMessagesTimelineRows>[0]["timelineEntries"][number],+ { kind: "work" }+ >;+ const work = (+ id: string,+ at: string,+ fields: Omit<WorkEntry["entry"], "id" | "createdAt" | "runId" | "label">,+ ): WorkEntry => ({+ id: `${id}-entry`,+ kind: "work",+ createdAt: at,+ entry: { id, createdAt: at, runId: "turn-1" as never, label: id, ...fields },+ });+ const rows = deriveMessagesTimelineRows({+ timelineEntries: [+ work("old-thought", "2026-01-01T00:00:01Z", {+ itemType: "reasoning",+ detail: "First idea.",+ tone: "thinking" as const,+ toolLifecycleStatus: "completed" as const,+ }),+ work("new-thought", "2026-01-01T00:00:02Z", {+ itemType: "reasoning",+ detail: "Found the cause.",+ tone: "thinking" as const,+ toolLifecycleStatus: "completed" as const,+ }),+ work("running-command", "2026-01-01T00:00:03Z", {+ command: "rg cause",+ requestKind: "command",+ tone: "tool" as const,+ toolLifecycleStatus: "inProgress" as const,+ }),+ ],+ latestRun: {+ runId: "turn-1" as never,+ status: "running",+ startedAt: "2026-01-01T00:00:00Z",+ completedAt: null,+ },+ isWorking: true,+ activeTurnStartedAt: "2026-01-01T00:00:00Z",+ turnDiffSummaries: [],+ supportsConversationRollback: false,+ });++ expect(rows.find((row) => row.kind === "work-live")).toMatchObject({+ entry: { id: "running-command" },+ thought: { id: "new-thought" },+ });+ });+it("keeps an actually running tool in the shared activity row", () => {const rows = deriveMessagesTimelineRows({timelineEntries: [diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.tsindex b619a347255..74f3991396e 100644--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts@@ -540,6 +540,8 @@ type MessagesTimelineRowContent =groupId: string;expanded: boolean;active: boolean;+ /** Latest reasoning in the live group, shown above the status line. */+ thought?: WorkLogEntry;}| {kind: "working";@@ -1434,6 +1436,9 @@ export function deriveMessagesTimelineRows(input: {latestVisibleToolEntry.entry.toolLifecycleStatus !== "declined" &&workEntryDisplayIndicatesToolFailure(latestVisibleToolEntry.entry);+ const latestThoughtEntry = visibleActiveToolEntries.findLast(+ (entry) => entry.entry.itemType === "reasoning" && (entry.entry.detail?.trim() ?? "") !== "",+ );const activeWorkPlacementEntryId = latestVisibleToolEntry?.id;const activeWorkRow =activeWorkAnchor && latestVisibleToolEntry && !latestToolFailed@@ -1450,6 +1455,7 @@ export function deriveMessagesTimelineRows(input: {groupId,expanded: input.expandedWorkGroupIds?.has(groupId) ?? false,active: latestToolKeepsActivityLive,+ ...(latestThoughtEntry ? { thought: latestThoughtEntry.entry } : {}),};})(): null;diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex 43f9746a659..6145098f604 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -40,6 +40,7 @@ import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thrimport { notificationChildThreadId } from "@t3tools/client-runtime/state/thread-execution";import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";import {+ liveThoughtLine,resolveWorkEntryToolPresentation,resolveViewedImageAsset,workEntryViewedImagePath,@@ -3780,18 +3781,53 @@ function LiveWorkEntryTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "const threadLabel = threadReadLabel(label, threadTarget);const failed = workEntryDisplayIndicatesToolFailure(row.entry);+ // The expanded group already lists the thought, so the preview steps aside.+ const thoughtLine = row.thought && !row.expanded ? liveThoughtLine(row.thought.detail ?? "") : "";+ // While the thought itself streams, the status line just says Thinking.+ const thoughtIsStatus = thoughtLine !== "" && row.entry === row.thought;return (<buttontype="button"- className="group/live-work flex min-h-6 w-full max-w-full cursor-pointer items-center rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"- aria-label={failed ? `${threadLabel?.text ?? label}, tool call failed` : undefined}+ className={cn(+ "group/live-work flex w-full max-w-full cursor-pointer rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70",+ thoughtLine ? "flex-col items-start" : "min-h-6 items-center",+ )}+ aria-label={+ failed+ ? `${thoughtLine ? `${thoughtLine} ` : ""}${threadLabel?.text ?? label}, tool call failed`+ : undefined+ }aria-expanded={row.expanded}onClick={() => ctx.onToggleWorkGroup(row.groupId, row.id)}>+ {thoughtLine ? (+ // The latest thought's first sentence sits above the status line as an+ // ordinary work-log row, so a finding never hides behind the next tool call.+ <WorkLogRow+ icon={+ <span className="flex size-4 items-center justify-center text-icon-muted">+ <ToolActivityIconView+ icon={undefined}+ fallbackName="brain"+ className="block size-4 shrink-0 stroke-2"+ muted+ />+ </span>+ }+ label={<span className="line-clamp-4">{thoughtLine}</span>}+ wrapLabel+ />+ ) : null}<LiveActivityRowlabel={- row.entry.questionAnswer && hasQuestionAnswer(row.entry.questionAnswer) ? (+ thoughtIsStatus ? (+ row.active ? (+ "Thinking"+ ) : (+ "Thought"+ )+ ) : row.entry.questionAnswer && hasQuestionAnswer(row.entry.questionAnswer) ? (<span className="flex min-w-0 gap-1.5"><span className="min-w-0 truncate">{label}</span><span className="min-w-0 truncate text-foreground">diff --git a/apps/web/src/components/chat/WorkLog.tsx b/apps/web/src/components/chat/WorkLog.tsxindex 4358f30f4de..8ac63e0dae4 100644--- a/apps/web/src/components/chat/WorkLog.tsx+++ b/apps/web/src/components/chat/WorkLog.tsx@@ -46,7 +46,13 @@ type RowContent = {function WorkLogLine({ icon, label, trailing, wrapLabel }: RowContent) {return (- <div className="flex min-h-6 min-w-0 items-center gap-1.5 text-sm leading-relaxed select-none [&_*]:select-none">+ <div+ className={cn(+ "flex min-h-6 min-w-0 gap-1.5 text-sm leading-relaxed select-none [&_*]:select-none",+ // A wrapped label keeps its icon beside the first line.+ wrapLabel ? "items-start" : "items-center",+ )}+ >{icon ? (<span className="relative flex size-6 shrink-0 items-center justify-center">{icon}</span>) : null}diff --git a/packages/client-runtime/src/work-log/presentation.test.ts b/packages/client-runtime/src/work-log/presentation.test.tsindex 8a73dd70fb7..6e41a53478a 100644--- a/packages/client-runtime/src/work-log/presentation.test.ts+++ b/packages/client-runtime/src/work-log/presentation.test.ts@@ -7,6 +7,7 @@ import { T3_MCP_TOOL_NAMES } from "@t3tools/shared/t3McpToolPresentation";import {commandDetailRepeatsCommand,extractCommandOutputText,+ liveThoughtLine,resolveViewedImageAsset,resolveWorkEntryToolPresentation,summarizeToolGroup,@@ -960,3 +961,40 @@ describe("device group summaries", () => {).toBe("Used 1 tool");});});++describe("liveThoughtLine", () => {+ it("keeps the first sentence, including a closing quote", () => {+ expect(+ liveThoughtLine(+ 'Found the cause: the repo has no commits, so `git worktree add` fails with "invalid reference: main." Now checking the UI.',+ ),+ ).toBe(+ 'Found the cause: the repo has no commits, so git worktree add fails with "invalid reference: main."',+ );+ });++ it("does not cut at dots inside file names or long dashes", () => {+ expect(+ liveThoughtLine("I read ThreadLaunchService.ts \u2014 it skips the fetch. Next step."),+ ).toBe("I read ThreadLaunchService.ts \u2014 it skips the fetch.");+ });++ it("uses a bold-only opening line as the whole line", () => {+ expect(+ liveThoughtLine("**Narrowing dispatch files**\n\nI should check the adapter. Then more."),+ ).toBe("Narrowing dispatch files");+ expect(liveThoughtLine("**Narrowing dispatch files**\r\n\r\nI should check the adapter.")).toBe(+ "Narrowing dispatch files",+ );+ });++ it("returns unpunctuated text whole and flattens markdown", () => {+ expect(liveThoughtLine("- Checking [the docs](https://x.dev) for **limits**")).toBe(+ "Checking the docs for limits",+ );+ expect(liveThoughtLine("This is *really* ~~not~~ _fine_ in snake_case_names.")).toBe(+ "This is really not fine in snake_case_names.",+ );+ expect(liveThoughtLine(" ")).toBe("");+ });+});diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.tsindex f5e9daab749..8ef6f58be59 100644--- a/packages/client-runtime/src/work-log/presentation.ts+++ b/packages/client-runtime/src/work-log/presentation.ts@@ -754,3 +754,23 @@ export function toolGroupSummaryKind();return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";}++/**+ * Plain-text line for the latest thought in the live activity row. A+ * bold-only opening line (the Codex summary heading) wins; otherwise this is+ * the first sentence of the reasoning text. Web and mobile both render it.+ */+export function liveThoughtLine(markdown: string): string {+ const heading = /^\s*\*\*([^*\r\n]+)\*\*[ \t]*\r?(?:\n|$)/.exec(markdown)?.[1];+ const text = (heading ?? markdown)+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")+ .replace(/^[ \t]*(?:#{1,6}|[-*+]|\d+\.)[ \t]+/gm, "")+ .replace(/`+|\*\*|~~/g, "")+ .replace(/(^|[^\w*])[*_]([^*_\n]+)[*_](?![\w*])/g, "$1$2")+ .replace(/\s+/g, " ")+ .trim();+ if (heading !== undefined) return text;+ // Cut after the first . ? or ! (plus a closing quote or paren) that a space follows.+ const end = /[.?!]["'”’)]?(?=\s)/.exec(text);+ return end ? text.slice(0, end.index + end[0].length) : text;+}