Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(web): read Codex, Claude Code and Pi trajectories, refetched per step
LeoXing8bc6988e3bf1
diff --git a/apps/web/src/features/rooms/task-sidebar/adapters/runtime-history-view.tsx b/apps/web/src/features/rooms/task-sidebar/adapters/runtime-history-view.tsxindex 2ceabb1c..69a8f8e6 100644--- a/apps/web/src/features/rooms/task-sidebar/adapters/runtime-history-view.tsx+++ b/apps/web/src/features/rooms/task-sidebar/adapters/runtime-history-view.tsx@@ -79,7 +79,7 @@ function activityTimelineItems(const thinkingTitles = new Set<string>();// Later steps name a Task only by id; reuse the name it was created with.const taskNames = new Map<string, string>();- for (const source of records.flatMap(claudeActivityRecords)) {+ for (const source of records.flatMap(contentBlockRecords)) {let record = source;if (record.native_type === "event_msg.mcp_tool_call_end") {const invocation = asObject(nativePayload(record)?.invocation);@@ -237,7 +237,11 @@ export function nativeCommand(record: TeamHubMessageActivityRecord) {const payload = nativePayload(record);const block = nativeContentBlock(record, payload);const input =- asObject(block?.input) ?? parseObject(payload?.arguments) ?? payload;+ asObject(block?.input) ??+ asObject(block?.arguments) ??+ parseObject(payload?.arguments) ??+ asObject(payload?.action) ??+ payload;const command = input?.cmd ?? input?.command;if (typeof command === "string") return command;if (Array.isArray(command)) return command.filter(isString).join(" ");@@ -286,7 +290,7 @@ export function nativePayload(record: TeamHubMessageActivityRecord) {);}-function claudeBlockCategory(type: unknown): HistoryCategory | undefined {+function contentBlockCategory(type: unknown): HistoryCategory | undefined {switch (type) {case "text":return "message";@@ -295,6 +299,7 @@ function claudeBlockCategory(type: unknown): HistoryCategory | undefined {return "reasoning";case "tool_use":case "server_tool_use":+ case "toolCall":return "tool_call";case "tool_result":return "tool_result";@@ -303,15 +308,15 @@ function claudeBlockCategory(type: unknown): HistoryCategory | undefined {}}-export function claudeActivityRecords(+export function contentBlockRecords(record: TeamHubMessageActivityRecord,): TeamHubMessageActivityRecord[] {- const blocks = claudeMessageBlocks(record);+ const blocks = messageContentBlocks(record);if (!blocks) return [record];const native = asObject(record.native_record)!;const message = asObject(native.message)!;return blocks.flatMap((block) => {- const category = claudeBlockCategory(block.type);+ const category = contentBlockCategory(block.type);if (!category) return [];return [{@@ -332,8 +337,7 @@ export function reasoningText(const block = nativeContentBlock(record, payload);if (block?.type === "thinking" || block?.type === "redacted_thinking") {return (- claudeThinkingSummary(block) ??- "Thinking recorded · private content hidden"+ thinkingSummary(block) ?? "Thinking recorded · private content hidden");}return stringValue(payload?.text) ?? textContent(payload?.summary);@@ -352,7 +356,7 @@ export function nativeContentBlock(case "tool_call":return blocks.find((block) =>- (block.type === "tool_use" || block.type === "server_tool_use") &&+ contentBlockCategory(block.type) === "tool_call" &&(!record.tool_call_id || block.id === record.tool_call_id),);case "tool_result":@@ -408,10 +412,10 @@ export function indexToolCalls(records: TeamHubMessageActivityRecord[]) {}>();for (const record of records) {- const blocks = claudeMessageBlocks(record);+ const blocks = messageContentBlocks(record);if (blocks) {for (const block of blocks) {- const category = claudeBlockCategory(block.type);+ const category = contentBlockCategory(block.type);const id = stringValue(category === "tool_result" ? block.tool_use_id : block.id,);@@ -454,12 +458,20 @@ export interface ToolCallPair {readonly result?: TeamHubMessageActivityRecord;}-function claudeMessageBlocks(+/**+ * The content blocks of a Runtime that records a whole message per line:+ * Claude Code's user and assistant lines, and Pi's assistant messages. A Pi+ * tool result is its own line, already a tool_result record.+ */+function messageContentBlocks(record: TeamHubMessageActivityRecord,): JsonObject[] | undefined {const native = asObject(record.native_record);- if (native?.type !== "user" && native?.type !== "assistant") return undefined;- const message = asObject(native.message);+ const message = asObject(native?.message);+ const claudeLine = native?.type === "user" || native?.type === "assistant";+ const piAssistant =+ native?.type === "message" && message?.role === "assistant";+ if (!claudeLine && !piAssistant) return undefined;if (typeof message?.content === "string")return [{ type: "text", text: message.content }];return Array.isArray(message?.content)@@ -470,7 +482,7 @@ function claudeMessageBlocks(: undefined;}-function claudeThinkingSummary(block: JsonObject): string | undefined {+export function thinkingSummary(block: JsonObject): string | undefined {if (typeof block.summary === "string") return block.summary;if (!Array.isArray(block.summary)) return undefined;return (diff --git a/apps/web/src/features/rooms/task-sidebar/adapters/runtime-trajectory-view.test.tsx b/apps/web/src/features/rooms/task-sidebar/adapters/runtime-trajectory-view.test.tsxnew file mode 100644index 00000000..0f9c0424--- /dev/null+++ b/apps/web/src/features/rooms/task-sidebar/adapters/runtime-trajectory-view.test.tsx@@ -0,0 +1,221 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";++import type { TeamHubMessageActivityRecord } from "@/features/teamhub/teamhub-types";++import { RuntimeTrajectoryView } from "./runtime-trajectory-view";++describe("RuntimeTrajectoryView", () => {+ it("shows each Codex call with what it acted on and opens to its output", () => {+ const records = [+ codex(0, "reasoning", "response_item.reasoning", {+ summary: [{ text: "**Checking the tests**", type: "summary_text" }],+ type: "reasoning",+ }),+ codex(1, "tool_call", "response_item.function_call", {+ arguments: JSON.stringify({ cmd: "pnpm test" }),+ call_id: "c1",+ name: "exec_command",+ type: "function_call",+ }),+ codex(2, "tool_result", "response_item.function_call_output", {+ call_id: "c1",+ output: "12 passed",+ type: "function_call_output",+ }),+ codex(3, "tool_call", "response_item.custom_tool_call", {+ call_id: "c2",+ input:+ "*** Begin Patch\n*** Update File: notes.md\n@@\n-old line\n+new line\n*** End Patch",+ name: "apply_patch",+ type: "custom_tool_call",+ }),+ codex(4, "tool_result", "response_item.custom_tool_call_output", {+ call_id: "c2",+ output: "Success",+ type: "custom_tool_call_output",+ }),+ codex(5, "tool_call", "response_item.web_search_call", {+ action: { query: "vitest docs", type: "search" },+ status: "completed",+ type: "web_search_call",+ }),+ codex(6, "message", "response_item.message", {+ content: [{ text: "All **green**.", type: "output_text" }],+ role: "assistant",+ type: "message",+ }),+ ];++ render(<RuntimeTrajectoryView live records={records} />);++ expect(screen.getByText("Checking the tests")).toBeVisible();+ const ran = screen.getByTitle("Ran pnpm test");+ fireEvent.click(ran);+ expect(ran.closest("details")).toHaveAttribute("open");+ expect(screen.getByText("12 passed")).toBeVisible();+ const edited = screen.getByTitle("Edited notes.md");+ fireEvent.click(edited);+ expect(screen.getByText("-old line")).toHaveClass("text-app-danger");+ expect(screen.getByText("+new line")).toHaveClass("text-app-success");+ expect(screen.queryByText("*** Begin Patch")).not.toBeInTheDocument();+ // A hosted search has no result record; its own status settles it.+ expect(screen.getByTitle("Searched vitest docs")).not.toHaveClass(+ "town-shimmer-text",+ );+ expect(screen.getByText("green").tagName).toBe("STRONG");+ fireEvent.click(ran);+ expect(ran.closest("details")).not.toHaveAttribute("open");+ });++ it("splits Claude Code messages into calls and leaves private thinking out", () => {+ const records = [+ claude(0, "assistant", [+ { signature: "s", thinking: "private", type: "thinking" },+ {+ id: "t1",+ input: { command: "ls docs" },+ name: "Bash",+ type: "tool_use",+ },+ {+ id: "t2",+ input: {+ file_path: "docs/a.md",+ new_string: "Hello",+ old_string: "Hi",+ },+ name: "Edit",+ type: "tool_use",+ },+ {+ id: "t3",+ input: { path: "src", pattern: "TODO" },+ name: "Grep",+ type: "tool_use",+ },+ ]),+ claude(1, "user", [+ { content: "a.md\nb.md", tool_use_id: "t1", type: "tool_result" },+ ]),+ claude(2, "assistant", [{ text: "Updated a.md.", type: "text" }]),+ ];++ render(<RuntimeTrajectoryView live={false} records={records} />);++ expect(screen.queryByText(/private/)).not.toBeInTheDocument();+ expect(screen.queryByText(/Thinking recorded/)).not.toBeInTheDocument();+ fireEvent.click(screen.getByTitle("Ran ls docs"));+ expect(screen.getByText(/a\.md\s+b\.md/)).toBeVisible();+ fireEvent.click(screen.getByTitle("Edited docs/a.md"));+ expect(screen.getByText("-Hi")).toBeVisible();+ expect(screen.getByText("+Hello")).toBeVisible();+ expect(screen.getByTitle("Searched TODO in src")).toBeVisible();+ expect(screen.getByText("Updated a.md.")).toBeVisible();+ });++ it("reads Pi tool calls and marks a call without a result pending only while live", () => {+ const records = [+ pi(0, "message", "assistant", {+ content: [+ { text: "Looking first.", type: "text" },+ {+ arguments: { command: "ls" },+ id: "p1",+ name: "bash",+ type: "toolCall",+ },+ {+ arguments: { newText: "two", oldText: "one", path: "notes.md" },+ id: "p2",+ name: "edit",+ type: "toolCall",+ },+ ],+ role: "assistant",+ }),+ pi(1, "tool_result", "toolResult", {+ content: [{ text: "readme.txt", type: "text" }],+ role: "toolResult",+ toolCallId: "p1",+ toolName: "bash",+ }),+ ];++ const { rerender } = render(+ <RuntimeTrajectoryView live records={records} />,+ );++ expect(screen.getByText("Looking first.")).toBeVisible();+ fireEvent.click(screen.getByTitle("Ran ls"));+ expect(screen.getByText("readme.txt")).toBeVisible();+ expect(screen.getByTitle("Ran ls")).not.toHaveClass("town-shimmer-text");+ expect(screen.getByTitle("Edited notes.md")).toHaveClass(+ "town-shimmer-text",+ );+ rerender(<RuntimeTrajectoryView live={false} records={records} />);+ expect(screen.getByTitle("Edited notes.md")).not.toHaveClass(+ "town-shimmer-text",+ );+ });+});++function codex(+ ordinal: number,+ category: TeamHubMessageActivityRecord["category"],+ nativeType: string,+ payload: Record<string, unknown>,+): TeamHubMessageActivityRecord {+ return {+ category,+ native_record: { payload, type: nativeType.split(".")[0] },+ native_type: nativeType,+ ordinal,+ redacted_fields: [],+ turn_id: "turn-codex",+ ...(payload.role ? { role: payload.role as string } : {}),+ ...(typeof payload.call_id === "string"+ ? { tool_call_id: payload.call_id }+ : {}),+ ...(typeof payload.name === "string" ? { tool_name: payload.name } : {}),+ };+}++function claude(+ ordinal: number,+ role: "assistant" | "user",+ content: Record<string, unknown>[],+): TeamHubMessageActivityRecord {+ return {+ category: "message",+ native_record: { message: { content, role }, type: role },+ native_type: role,+ ordinal,+ redacted_fields: [],+ role,+ turn_id: "turn-claude",+ };+}++function pi(+ ordinal: number,+ category: TeamHubMessageActivityRecord["category"],+ role: string,+ message: Record<string, unknown>,+): TeamHubMessageActivityRecord {+ return {+ category,+ native_record: { id: `pi-${ordinal}`, message, type: "message" },+ native_type: "message",+ ordinal,+ redacted_fields: [],+ role,+ turn_id: `pi-${ordinal}`,+ ...(typeof message.toolCallId === "string"+ ? {+ tool_call_id: message.toolCallId,+ tool_name: message.toolName as string,+ }+ : {}),+ };+}diff --git a/apps/web/src/features/rooms/task-sidebar/adapters/runtime-trajectory-view.tsx b/apps/web/src/features/rooms/task-sidebar/adapters/runtime-trajectory-view.tsxindex b83f31ab..e976747a 100644--- a/apps/web/src/features/rooms/task-sidebar/adapters/runtime-trajectory-view.tsx+++ b/apps/web/src/features/rooms/task-sidebar/adapters/runtime-trajectory-view.tsx@@ -1,15 +1,19 @@-import { ChevronRight, Sparkles } from "lucide-react";+import { ArrowRight01Icon, SparklesIcon } from "@hugeicons/core-free-icons";import { useMemo } from "react";-import { toolPresentation } from "@/features/rooms/runtime-status/runtime-tool-presentation";-+import { Icon } from "@/components/ui/icon";+import { cn } from "@/lib/cn";+import {+ toolNameLabel,+ toolPresentation,+} from "@/features/rooms/runtime-status/runtime-tool-presentation";import type { TeamHubMessageActivityRecord } from "@/features/teamhub/teamhub-types";import { MessageMarkdown } from "../../chat/message-markdown";import {activityMessageText,asObject,- claudeActivityRecords,+ contentBlockRecords,indexToolCalls,isAssistantMessage,isEventRecord,@@ -20,6 +24,7 @@ import {parseObject,reasoningText,stringValue,+ thinkingSummary,type ToolCallPair,} from "./runtime-history-view";@@ -31,13 +36,13 @@ type TrajectoryItem =interface TrajectoryCall {/** What the call acted on: a command, a path, a query. */detail: string;+ /** Lines added and removed, shown as a diff in place of the output. */+ diff?: string;/** The full input, when it says more than the detail. */input?: string;/** The Runtime-neutral tool kind that picks the row's icon. */kind: string;output?: string;- /** A patch's lines, coloured as a diff. */- patch?: string;pending: boolean;verb: string;}@@ -45,14 +50,17 @@ interface TrajectoryCall {/*** A Runtime's native turn, one row per step: what it thought, each command* or tool call with what it acted on, and what it replied. A call opens to- * its full input and output.+ * its full input and output. Reads Codex, Claude Code and Pi records.*/export function RuntimeTrajectoryView({+ live,records,}: {+ /** Whether the turn is still running, so a call without a result is pending. */+ live: boolean;records: TeamHubMessageActivityRecord[];}) {- const items = useMemo(() => trajectoryItems(records), [records]);+ const items = useMemo(() => trajectoryItems(records, live), [records, live]);return (<olaria-label="Activity log"@@ -64,11 +72,7 @@ export function RuntimeTrajectoryView({className="flex min-h-8 items-start gap-2 py-1.5 text-app-muted"key={item.key}>- <Sparkles- aria-hidden="true"- className="mt-0.5 shrink-0"- size={15}- />+ <Icon className="mt-0.5 shrink-0" icon={SparklesIcon} size={14} /><p className="min-w-0 flex-1">{item.text}</p></li>) : item.kind === "reply" ? (@@ -86,11 +90,14 @@ export function RuntimeTrajectoryView({}function TrajectoryCallRow({ call }: { call: TrajectoryCall }) {- const { icon: ToolIcon } = toolPresentation(call.kind);- const output = call.patch ?? call.output;+ const { glyph } = toolPresentation(call.kind);+ const output = call.diff ?? call.output;const label = (<span- className={`min-w-0 flex-1 truncate ${call.pending ? "town-shimmer-text" : ""}`}+ className={cn(+ "min-w-0 flex-1 truncate",+ call.pending && "town-shimmer-text",+ )}title={`${call.verb} ${call.detail}`}>{call.verb} <span className="text-app-body">{call.detail}</span>@@ -99,7 +106,7 @@ function TrajectoryCallRow({ call }: { call: TrajectoryCall }) {if (!output && !call.input)return (<li className="flex min-h-8 items-center gap-2 py-1.5 text-app-muted">- <ToolIcon aria-hidden="true" className="shrink-0" size={15} />+ <Icon className="shrink-0" icon={glyph} size={14} />{label}</li>);@@ -107,28 +114,24 @@ function TrajectoryCallRow({ call }: { call: TrajectoryCall }) {<li><details className="group"><summary className="flex min-h-8 cursor-pointer list-none items-center gap-2 py-1.5 text-app-muted hover:text-app-body focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-app-focus [&::-webkit-details-marker]:hidden">- <span className="relative inline-flex size-[15px] shrink-0 items-center justify-center">- <ToolIcon- aria-hidden="true"- className="absolute inset-0 m-auto group-hover:hidden group-focus-within:hidden group-open:hidden"- size={15}- />- <ChevronRight- aria-hidden="true"- className="absolute inset-0 m-auto hidden group-hover:block group-focus-within:block group-open:block group-open:rotate-90 motion-reduce:transition-none"- size={15}- />+ <span className="relative inline-flex size-[14px] shrink-0 items-center justify-center">+ <span className="absolute inset-0 group-hover:hidden group-focus-within:hidden group-open:hidden">+ <Icon icon={glyph} size={14} />+ </span>+ <span className="absolute inset-0 hidden group-hover:block group-focus-within:block group-open:block group-open:rotate-90 motion-reduce:transition-none">+ <Icon icon={ArrowRight01Icon} size={14} />+ </span></span>{label}</summary>- <div className="space-y-2 pb-2 pl-[1.45rem]">+ <div className="space-y-2 pb-2 pl-[1.4rem]">{call.input ? (<TrajectoryText label="Input" text={call.input} />) : null}{output ? (<TrajectoryText- diff={Boolean(call.patch)}- label={call.patch ? "Changes" : "Output"}+ diff={Boolean(call.diff)}+ label={call.diff ? "Changes" : "Output"}text={output}/>) : null}@@ -150,10 +153,10 @@ function TrajectoryText({return (<section aria-label={label}><p className="pb-1 text-app-muted">{label}</p>- <pre className="workspace-scrollbar max-h-72 overflow-auto rounded-md bg-app-surface-soft px-3 py-2 font-mono text-[11px] leading-[17px] whitespace-pre-wrap break-words text-app-body">+ <pre className="workspace-scrollbar max-h-72 overflow-auto rounded-md bg-app-surface-soft px-3 py-2 font-mono text-[11px] leading-[17px] break-words whitespace-pre-wrap text-app-body">{diff? text.split("\n").map((line, index) => (- <span className={`block ${diffTone(line)}`} key={index}>+ <span className={cn("block", diffTone(line))} key={index}>{line || " "}</span>))@@ -167,24 +170,23 @@ function diffTone(line: string) {if (line.startsWith("+") && !line.startsWith("+++"))return "text-app-success";if (line.startsWith("-") && !line.startsWith("---")) return "text-app-danger";- return "";+ return undefined;}function trajectoryItems(records: TeamHubMessageActivityRecord[],+ live: boolean,): TrajectoryItem[] {const ordered = [...records].sort((left, right) => left.ordinal - right.ordinal)- .flatMap(claudeActivityRecords);+ .flatMap(contentBlockRecords);const pairs = indexToolCalls(ordered);const items: TrajectoryItem[] = [];const seenReasoning = new Set<string>();for (const record of ordered) {const key = `${record.ordinal}:${items.length}`;if (record.category === "reasoning") {- const text = reasoningText(record)- ?.replace(/^\*\*([\s\S]+)\*\*$/, "$1")- .trim();+ const text = reasoningSummary(record);if (!text || seenReasoning.has(text)) continue;seenReasoning.add(text);items.push({ key, kind: "reasoning", text });@@ -198,71 +200,128 @@ function trajectoryItems(const pair = record.tool_call_id? pairs.get(record.tool_call_id): undefined;- items.push({ call: trajectoryCall(record, pair), key, kind: "call" });+ items.push({+ call: trajectoryCall(record, pair, live),+ key,+ kind: "call",+ });}}return items;}-/** Names a call by what its tool does, from the tool's own name and input. */+/**+ * The readable summary of a reasoning step. Private thinking without a+ * summary says nothing to show, so it is left out.+ */+function reasoningSummary(record: TeamHubMessageActivityRecord) {+ const block = nativeContentBlock(record, nativePayload(record));+ const text = block ? thinkingSummary(block) : reasoningText(record);+ return text?.replace(/^\*\*([\s\S]+)\*\*$/, "$1").trim();+}++/**+ * Names a call by what its tool does. Each Runtime names its tools its own+ * way: Codex `exec_command` and `apply_patch`, Claude Code `Bash`, `Read` and+ * `Edit`, Pi `bash`, `read` and `edit`; MCP tools keep their own names.+ */function trajectoryCall(record: TeamHubMessageActivityRecord,pair: ToolCallPair | undefined,+ live: boolean,): TrajectoryCall {const payload = nativePayload(record);const block = nativeContentBlock(record, payload);+ const nativeKind = record.native_type.split(".").pop() ?? "";const name =- record.tool_name ?? stringValue(block?.name) ?? stringValue(payload?.name);+ record.tool_name ??+ stringValue(block?.name) ??+ stringValue(payload?.name) ??+ nativeKind;const rawInput =stringValue(payload?.input) ?? stringValue(payload?.arguments);const args =- asObject(block?.input) ?? parseObject(payload?.arguments) ?? undefined;- const output = pair?.result ? nativeOutput(pair.result) : undefined;- const base = { output, pending: !pair?.result };- const tool = (name ?? "tool").toLowerCase();+ asObject(block?.input) ??+ asObject(block?.arguments) ??+ parseObject(payload?.arguments) ??+ asObject(payload?.action);+ // A hosted search reports its own completion and has no result record.+ const settled = Boolean(pair?.result) || payload?.status === "completed";+ const base = {+ output: pair?.result ? nativeOutput(pair.result) : undefined,+ pending: live && !settled,+ };+ const tool = name.toLowerCase();const command = nativeCommand(record);- if (command && /^(exec_command|shell|local_shell|bash)$/.test(tool))+ if (+ command &&+ [+ "exec_command",+ "shell",+ "local_shell",+ "local_shell_call",+ "bash",+ ].includes(tool)+ )return { ...base, detail: command, kind: "command", verb: "Ran" };const path = stringValue(args?.path ?? args?.file_path ?? args?.filePath);- if (/^(read_file|read|view)$/.test(tool) && path)+ if (["read", "read_file", "view"].includes(tool) && path)return { ...base, detail: path, kind: "read", verb: "Read" };- const patch =- tool === "apply_patch" ? (stringValue(args?.input) ?? rawInput) : undefined;- if (patch !== undefined)+ if (tool === "apply_patch") {+ const patch = stringValue(args?.input) ?? rawInput ?? "";return {...base,detail: patchFiles(patch) || "files",- // The envelope only repeats the file names the row already shows.- patch: patch- .split("\n")- .filter(- (line) =>- !/^\*\*\* (Begin Patch|End Patch|Add File:|Update File:|Delete File:)|^@@$/.test(- line,- ),- )- .join("\n"),+ diff: patchLines(patch),kind: "file_change",verb: "Edited",};- if (/^(edit|write|multiedit|str_replace_based_edit_tool)$/.test(tool) && path)+ }+ if (+ ["edit", "multiedit", "write", "str_replace_based_edit_tool"].includes(+ tool,+ ) &&+ path+ )return {...base,detail: path,- input: JSON.stringify(args, null, 2),+ diff: editLines(args) || undefined,kind: "file_change",- verb: "Edited",+ verb: tool === "write" ? "Wrote" : "Edited",};- const query = stringValue(args?.query);- if (/^(web_search|websearch)$/.test(tool) && query)- return { ...base, detail: query, kind: "search", verb: "Searched" };+ const query = stringValue(args?.query ?? args?.pattern);+ if (+ [+ "web_search",+ "web_search_call",+ "websearch",+ "grep",+ "glob",+ "find",+ ].includes(tool) &&+ query+ ) {+ const scope = stringValue(args?.path);+ return {+ ...base,+ detail: scope ? `${query} in ${scope}` : query,+ kind: "search",+ verb: "Searched",+ };+ }+ if (tool === "ls")+ return { ...base, detail: path ?? ".", kind: "read", verb: "Listed" };const url = stringValue(args?.url);- if (/^(web_fetch|webfetch)$/.test(tool) && url)+ if (["web_fetch", "webfetch"].includes(tool) && url)return { ...base, detail: url, kind: "browse", verb: "Fetched" };+ const task = stringValue(args?.description);+ if (["task", "agent"].includes(tool) && task)+ return { ...base, detail: task, kind: "delegation", verb: "Delegated" };const input = args ? JSON.stringify(args, null, 2) : rawInput;return {...base,- detail: name ?? "tool",+ detail: toolNameLabel(name),...(input ? { input } : {}),kind: "tool",verb: "Called",@@ -274,3 +333,40 @@ function patchFiles(patch: string) {.map((match) => match[1]!.trim()).join(", ");}++/** A Codex patch's lines; its envelope only repeats the files the row names. */+function patchLines(patch: string) {+ return patch+ .split("\n")+ .filter(+ (line) =>+ !/^\*\*\* (Begin Patch|End Patch|Add File:|Update File:|Delete File:)|^@@$/.test(+ line,+ ),+ )+ .join("\n");+}++/**+ * An edit tool's input as removed and added lines: Claude Code's+ * `old_string`/`new_string` (or `edits` of them, or `content` to write) and+ * Pi's `oldText`/`newText`.+ */+function editLines(args: Record<string, unknown> | undefined) {+ const prefix = (text: unknown, mark: string) =>+ typeof text === "string" ? text.split("\n").map((line) => mark + line) : [];+ const content = args?.content;+ if (typeof content === "string") return prefix(content, "+").join("\n");+ const listed = args?.edits;+ const edits = Array.isArray(listed) ? listed : [args];+ return edits+ .map((value) => {+ const edit = asObject(value);+ return [+ ...prefix(edit?.old_string ?? edit?.oldText, "-"),+ ...prefix(edit?.new_string ?? edit?.newText, "+"),+ ].join("\n");+ })+ .filter(Boolean)+ .join("\n\n");+}diff --git a/apps/web/src/features/rooms/task-sidebar/adapters/task-activities-panel-tab.tsx b/apps/web/src/features/rooms/task-sidebar/adapters/task-activities-panel-tab.tsxindex 6e4e2405..15b650d9 100644--- a/apps/web/src/features/rooms/task-sidebar/adapters/task-activities-panel-tab.tsx+++ b/apps/web/src/features/rooms/task-sidebar/adapters/task-activities-panel-tab.tsx@@ -1,6 +1,11 @@import { dateTimeFormat } from "@/lib/date-format";+import { useState } from "react";import { useInfiniteQuery } from "@tanstack/react-query";-import { ArrowLeft01Icon, RefreshIcon } from "@hugeicons/core-free-icons";+import {+ Activity01Icon,+ ArrowRight01Icon,+ RefreshIcon,+} from "@hugeicons/core-free-icons";import { Button } from "@/components/ui/button";import { Icon } from "@/components/ui/icon";import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";@@ -15,80 +20,23 @@ import {useTaskActivities,} from "@/features/work-items/use-task-activities";import { roomMessagesInfiniteQueryOptions } from "../../room-queries";+import { ActorAvatar } from "../../members/actor-avatar";+import { MessageMarkdown } from "../../chat/message-markdown";import { RuntimeActivityPath } from "../../runtime-status/runtime-activity-path-view";import { useTaskActivityEvents } from "../../runtime-status/use-task-activity-events";+import { RunningDots } from "../running-dots";import { PanelLoading } from "../panel-loading";const stageLabels: Record<TeamHubTaskExecution["status"], string> = {running: "Running",waiting_for_approval: "Waiting for approval",- idle: "Reported",+ idle: "Idle",failed: "Failed",canceled: "Stopped",};+const tabs = ["Activity", "Details"] as const;-/** One Task's activity: each of its runs, newest last, and nothing else. */export function TaskActivitiesPanelTab({- hidden,- onBack,- taskId,- tenantId,- title,-}: {- hidden: boolean;- onBack?: () => void;- taskId: string;- tenantId: string;- title?: string;-}) {- const view = useTaskActivityView({ hidden, taskId, tenantId });- const { data, execution, refresh } = view;- return (- <section- className={hidden ? "hidden" : "flex h-full min-h-0 flex-col bg-card"}- hidden={hidden || undefined}- inert={hidden || undefined}- data-testid="task-activities-panel"- aria-label="Task activities"- >- <header className="flex min-h-14 shrink-0 items-center gap-2.5 border-b border-app-border px-4 py-2">- {onBack ? (- <button- aria-label="Back to activity"- className="flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-app-focus"- onClick={onBack}- title="Back to activity"- type="button"- >- <Icon icon={ArrowLeft01Icon} size={16} />- </button>- ) : null}- <div className="min-w-0 flex-1">- <h2 className="truncate text-sm font-semibold text-foreground">- {title ?? data.item.data?.title ?? "Task"}- </h2>- <p className="truncate text-xs text-app-muted">- {execution ? stageLabels[execution.status] : "Task"}- </p>- </div>- <button- type="button"- aria-label="Refresh task"- onClick={refresh}- title="Refresh"- className="flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"- >- <Icon icon={RefreshIcon} size={16} />- </button>- </header>- <div className="workspace-scrollbar min-h-0 flex-1 overflow-y-auto">- <TaskActivityRuns hidden={hidden} tenantId={tenantId} view={view} />- </div>- </section>- );-}--export function useTaskActivityView({hidden,taskId,tenantId,@@ -97,6 +45,7 @@ export function useTaskActivityView({taskId: string;tenantId: string;}) {+ const [tab, setTab] = useState<(typeof tabs)[number]>("Activity");const data = useTaskActivities({ tenantId, taskId, enabled: !hidden });const { client } = useTeamHubRuntime();const messages = useInfiniteQuery({@@ -107,77 +56,222 @@ export function useTaskActivityView({? 2_000: false,});+ const publicMessages =+ messages.data?.pages.flatMap((page) => page.items) ?? [];+ const execution = data.execution.data;+ const item = data.item.data;+ const stopped = taskExecutionStopped(execution);+ const status = execution+ ? stageLabels[execution.status]+ : (item?.state.replaceAll("_", " ") ?? "");const refresh = () => {void data.item.refetch();void data.execution.refetch();void data.activities.refetch();if (data.roomId) void messages.refetch();};- return {- data,- execution: data.execution.data,- messages: messages.data?.pages.flatMap((page) => page.items) ?? [],- refresh,- };-}--function TaskActivityRuns({- hidden,- tenantId,- view: { data, execution, messages },-}: {- hidden: boolean;- tenantId: string;- view: ReturnType<typeof useTaskActivityView>;-}) {- const stopped = taskExecutionStopped(execution);- if (data.activities.error)- return (- <State>- {isTaskActivityNotFound(data.activities.error)- ? "You do not have access to this task’s work room activity."- : "Activity could not be loaded. Try refreshing."}- </State>- );- if (data.activities.isPending) return <State busy>Loading activity…</State>;return (- <>- {data.roomId && !data.connected ? (- <State>Reconnecting to live activity…</State>- ) : null}- {!data.runStatuses.length ? <State>No activity yet.</State> : null}- {data.roomId- ? data.runStatuses.map((runStatus) => (- <TaskActivityGroup- key={runStatus.id}- runStatus={runStatus}- tenantId={tenantId}- roomId={data.roomId!}- visible={!hidden}- stopped={stopped}- paused={execution?.status === "waiting_for_approval"}- messages={messages}- labeled={data.runStatuses.length > 1}- />- ))- : null}- {data.activities.hasNextPage ? (- <div className="px-4 py-3">- <Button- size="compact"- tone="ghost"- disabled={data.activities.isFetchingNextPage}- onClick={() => void data.activities.fetchNextPage()}+ <section+ className={hidden ? "hidden" : "flex h-full min-h-0 flex-col bg-card"}+ hidden={hidden || undefined}+ inert={hidden || undefined}+ data-testid="task-activities-panel"+ aria-label="Task activities"+ >+ <header className="shrink-0 border-b border-app-border px-4 pb-3 pt-4">+ <div className="flex items-center gap-2 text-xs text-app-muted">+ <Icon icon={Activity01Icon} size={14} />+ <span>Task {item ? `#${item.number}` : ""}</span>+ <button+ type="button"+ aria-label="Refresh task"+ onClick={refresh}+ className="ml-auto rounded-lg p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground">- Load earlier activity- </Button>+ <Icon icon={RefreshIcon} size={14} />+ </button></div>- ) : null}- </>+ <h2 className="mt-2 break-words text-sm font-semibold text-app-ink">+ {item?.title ?? "Task activity"}+ </h2>+ <div className="mt-3 flex flex-wrap items-center gap-2 text-xs">+ <span className="rounded-full bg-muted px-2 py-0.5 capitalize text-muted-foreground">+ {status}+ </span>+ {execution?.current_attempt ? (+ <span className="text-app-muted">+ Attempt {execution.current_attempt.attempt_number}+ </span>+ ) : null}+ </div>+ {execution ? (+ <p className="mt-2 text-2xs text-app-muted">+ Updated {formatTime(execution.execution_updated_at)}+ </p>+ ) : null}+ </header>+ <nav+ aria-label="Task sections"+ className="flex shrink-0 gap-1 border-b border-border px-3 py-2"+ >+ {tabs.map((value) => (+ <button+ type="button"+ aria-current={tab === value ? "page" : undefined}+ key={value}+ onClick={() => setTab(value)}+ className={`rounded-full px-3 py-1 text-sm font-medium transition-colors duration-150 ${tab === value ? "bg-muted text-foreground" : "text-muted-foreground hover:bg-muted/50 hover:text-foreground"}`}+ >+ {value}+ </button>+ ))}+ </nav>+ <div className="workspace-scrollbar min-h-0 flex-1 overflow-y-auto">+ {data.item.error ? (+ <State>Task could not be loaded.</State>+ ) : data.item.isPending ? (+ <State busy>Loading task…</State>+ ) : (+ <>+ {data.execution.error ? (+ <State>Execution status could not be loaded.</State>+ ) : null}+ {tab === "Activity" ? (+ <>+ {data.activities.error ? (+ <State>+ {isTaskActivityNotFound(data.activities.error)+ ? "You do not have access to this task’s work room activity."+ : "Activity could not be loaded. Try refreshing."}+ </State>+ ) : data.activities.isPending ? (+ <State busy>Loading activity…</State>+ ) : (+ <>+ {data.roomId && !data.connected ? (+ <State>Reconnecting to live activity…</State>+ ) : null}+ {!data.runStatuses.length ? (+ <State>+ No published activity yet. Earlier runs may not have an+ activity history.+ </State>+ ) : null}+ {data.roomId+ ? data.runStatuses.map((runStatus) => (+ <TaskActivityGroup+ key={runStatus.id}+ runStatus={runStatus}+ tenantId={tenantId}+ roomId={data.roomId!}+ visible={!hidden}+ stopped={stopped}+ paused={+ execution?.status === "waiting_for_approval"+ }+ messages={publicMessages}+ />+ ))+ : null}+ {data.activities.hasNextPage ? (+ <div className="px-4 py-3">+ <Button+ size="compact"+ tone="ghost"+ disabled={data.activities.isFetchingNextPage}+ onClick={() => void data.activities.fetchNextPage()}+ >+ Load earlier activity+ </Button>+ </div>+ ) : null}+ </>+ )}+ {data.roomId ? (+ <div className="border-t border-app-border px-4 py-4">+ <h3 className="mb-3 text-xs font-medium text-app-body">+ Task messages+ </h3>+ {messages.error ? (+ <p className="text-xs text-app-muted">+ Messages could not be loaded.+ </p>+ ) : !publicMessages.length ? (+ <p className="text-xs text-app-muted">+ No task messages yet.+ </p>+ ) : (+ [...publicMessages].reverse().map((message) => (+ <article key={message.id} className="mb-4">+ <div className="mb-1 flex gap-2 text-2xs text-app-muted">+ <span>{message.author.display_name}</span>+ <time dateTime={message.created_at}>+ {formatTime(message.created_at)}+ </time>+ </div>+ <MessageMarkdown+ body={message.raw_message}+ authorKind={message.author.kind}+ />+ </article>+ ))+ )}+ {messages.hasNextPage ? (+ <Button+ size="compact"+ tone="ghost"+ disabled={messages.isFetchingNextPage}+ onClick={() => void messages.fetchNextPage()}+ >+ Load earlier messages+ </Button>+ ) : null}+ </div>+ ) : null}+ </>+ ) : null}+ {tab === "Details" && item ? (+ <div className="space-y-5 p-4 text-xs text-app-body">+ <dl className="space-y-3">+ <Field+ label="Assignees"+ value={+ item.assignees+ .map((assignment) => assignment.actor.display_name)+ .join(", ") || "Unassigned"+ }+ />+ <Field label="Priority" value={item.priority} />+ <Field+ label="Execution"+ value={+ execution+ ? stageLabels[execution.status]+ : "Execution is not enabled"+ }+ />+ {execution?.reason_code ? (+ <Field label="Reason" value={execution.reason_code} />+ ) : null}+ </dl>+ {item.description ? (+ <div>+ <h3 className="mb-2 font-medium">Description</h3>+ <MessageMarkdown+ body={item.description}+ authorKind="human"+ />+ </div>+ ) : null}+ </div>+ ) : null}+ </>+ )}+ </div>+ </section>);}-/** One run of the Task; a Task resumed more than once labels each run. */function TaskActivityGroup({runStatus,tenantId,@@ -186,7 +280,6 @@ function TaskActivityGroup({stopped,paused: taskPaused,messages,- labeled,}: {runStatus: TeamHubRunStatus;tenantId: string;@@ -195,16 +288,17 @@ function TaskActivityGroup({stopped: boolean;paused: boolean;messages: TeamHubMessage[];- labeled: boolean;}) {const active = runStatus.status === "active" && !stopped;const paused = runStatus.status === "active" && taskPaused;+ const [opened, setOpened] = useState<boolean>();+ const expanded = opened ?? active;const events = useTaskActivityEvents({tenantId,roomId,runStatusId: runStatus.id,revision: runStatus.revision,- enabled: visible,+ enabled: visible && expanded,});const interrupted =(runStatus.status === "aborted" &&@@ -218,24 +312,64 @@ function TaskActivityGroup({? "interrupted": "ended";return (- <div>- {labeled ? (- <p className="px-4 pt-3 text-2xs text-app-muted">- {formatTime(runStatus.created_at)}- </p>- ) : null}- {events.error ? (- <State>Activity could not be loaded.</State>- ) : !events.data ? (- <State busy>Loading activity…</State>- ) : (- <RuntimeActivityPath- records={events.data.items}- messages={messages}- lifecycle={lifecycle}- embedded+ <div className="border-b border-app-border">+ <button+ type="button"+ aria-expanded={expanded}+ onClick={() => setOpened(!expanded)}+ className="flex w-full items-center gap-2.5 px-4 py-3 text-left transition-colors duration-300 hover:bg-muted/70"+ >+ <ActorAvatar+ actorId={runStatus.agent.id}+ kind="agent"+ name={runStatus.agent.display_name}+ size="xs"/>- )}+ <span className="min-w-0 flex-1">+ <span className="block truncate text-xs font-medium text-app-body">+ {runStatus.agent.display_name}+ </span>+ <span className="text-2xs text-app-muted">+ {formatTime(runStatus.created_at)} ·{" "}+ {active+ ? "Working"+ : paused+ ? "Paused"+ : interrupted+ ? "Interrupted"+ : "Ended"}+ </span>+ </span>+ {active ? (+ <span+ aria-label="Agent working"+ className="flex h-3.5 items-center text-app-info"+ role="img"+ >+ <RunningDots />+ </span>+ ) : (+ <Icon+ className={expanded ? "rotate-90 text-app-muted" : "text-app-muted"}+ icon={ArrowRight01Icon}+ size={14}+ />+ )}+ </button>+ {expanded ? (+ events.error ? (+ <State>Activity could not be loaded.</State>+ ) : !events.data ? (+ <State busy>Loading activity…</State>+ ) : (+ <RuntimeActivityPath+ records={events.data.items}+ messages={messages}+ lifecycle={lifecycle}+ embedded+ />+ )+ ) : null}</div>);}@@ -253,6 +387,14 @@ function State({</p>);}+function Field({ label, value }: { label: string; value: string }) {+ return (+ <div className="flex gap-3">+ <dt className="w-24 shrink-0 text-app-muted">{label}</dt>+ <dd className="min-w-0 break-words capitalize">{value}</dd>+ </div>+ );+}function formatTime(value: string) {return dateTimeFormat({month: "short",diff --git a/apps/web/src/features/rooms/task-sidebar/adapters/task-conversation-dialog.tsx b/apps/web/src/features/rooms/task-sidebar/adapters/task-conversation-dialog.tsxindex 1dbc7c59..c21db7b6 100644--- a/apps/web/src/features/rooms/task-sidebar/adapters/task-conversation-dialog.tsx+++ b/apps/web/src/features/rooms/task-sidebar/adapters/task-conversation-dialog.tsx@@ -1,9 +1,14 @@-import { useQuery, useQueryClient } from "@tanstack/react-query";+import {+ keepPreviousData,+ useQuery,+ useQueryClient,+} from "@tanstack/react-query";import { useMemo, useState, type ReactNode } from "react";import { ModalDialog } from "@/components/ui/modal-dialog";import { StatusPill } from "@/components/ui/status-pill";import { teamHubData } from "@/features/teamhub/teamhub-api";+import { useTaskActivities } from "@/features/work-items/use-task-activities";import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";import type {TeamHubRunStatus,@@ -25,7 +30,6 @@ import { TaskActivityLinksProvider } from "../../runtime-status/task-activity-blimport { useTaskActivityEvents } from "../../runtime-status/use-task-activity-events";import { PanelLoading } from "../panel-loading";import { RuntimeTrajectoryView } from "./runtime-trajectory-view";-import { useTaskActivityView } from "./task-activities-panel-tab";/** Lets the task blocks in an activity log open their Task's conversation. */export function TaskConversationProvider({@@ -83,11 +87,8 @@ export function TaskConversationDialog({roomId: originRoomId,tenantId,});- const { data, execution, refresh } = useTaskActivityView({- hidden: false,- taskId,- tenantId,- });+ const data = useTaskActivities({ enabled: true, taskId, tenantId });+ const execution = data.execution.data;const live =execution?.status === "running" ||execution?.status === "waiting_for_approval";@@ -138,7 +139,7 @@ export function TaskConversationDialog({<CancelTaskButtoncancel={async () => {await cancel(taskId);- refresh();+ await data.execution.refetch();}}title={title}/>@@ -222,8 +223,12 @@ function TaskConversationRun({}) {const { client } = useTeamHubRuntime();const active = runStatus.status === "active" && !stopped;+ // Native history is read from the Runtime's session file on the Computer,+ // so it is read again only when the Run publishes a new step, which bumps+ // its revision, never on a timer.const history = useQuery({enabled: Boolean(roomId),+ placeholderData: keepPreviousData,queryKey: ["teamhub",tenantId,@@ -232,6 +237,7 @@ function TaskConversationRun({"runs",runStatus.id,"activities",+ runStatus.revision,],queryFn: () =>teamHubData(@@ -240,7 +246,6 @@ function TaskConversationRun({}),),retry: false,- refetchInterval: active ? 1_500 : false,});// Native history may lag a live turn; its published steps stand in.const native = history.data?.status === "available" && history.data.records;@@ -268,7 +273,7 @@ function TaskConversationRun({{runStatus.agent.display_name}</p>{native ? (- <RuntimeTrajectoryView records={native} />+ <RuntimeTrajectoryView live={active} records={native} />) : events.data ? (<div className="[&_ol]:px-0 [&_ol]:py-1"><RuntimeActivityPath