From fc8cfe53e0d03fb8315f302dff997d355c6c099b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 13 Apr 2026 18:52:21 -0700 Subject: [PATCH] Refactor thread components and improve UI elements - Removed the last conversation line display from the ThreadRow component. - Updated the ThreadDetailScreen to conditionally show an active work indicator based on the active work duration label. - Simplified the ThreadFeed component by removing unused functions and optimizing the activity row building process. - Enhanced the presentation of work log entries by refining the way details and summaries are displayed. - Cleaned up imports and improved code structure across multiple files. --- apps/mobile/src/features/home/HomeScreen.tsx | 8 +- .../features/threads/ThreadDetailScreen.tsx | 19 +- .../src/features/threads/ThreadFeed.tsx | 49 +- .../features/threads/threadPresentation.ts | 9 - apps/mobile/src/lib/threadActivity.test.ts | 171 +++++ apps/mobile/src/lib/threadActivity.ts | 594 ++++++++++++++++-- 6 files changed, 744 insertions(+), 106 deletions(-) create mode 100644 apps/mobile/src/lib/threadActivity.test.ts diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 5388cd7788..e333293431 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -15,7 +15,7 @@ import type { SavedRemoteConnection } from "../../lib/connection"; import { scopedProjectKey } from "../../lib/scopedEntities"; import { relativeTime } from "../../lib/time"; import { useGitStatus } from "../../state/use-git-status"; -import { lastConversationLine, threadStatusTone } from "../threads/threadPresentation"; +import { threadStatusTone } from "../threads/threadPresentation"; /* ─── Types ──────────────────────────────────────────────────────────── */ @@ -121,7 +121,6 @@ function ThreadRow(props: { const separatorColor = useThemeColor("--color-separator"); const { bg, fg } = statusColors(props.thread); const tone = threadStatusTone(props.thread); - const preview = lastConversationLine(props.thread); const timestamp = relativeTime(props.thread.updatedAt ?? props.thread.createdAt); const branch = props.thread.branch; @@ -190,11 +189,6 @@ function ThreadRow(props: { - {/* Message preview */} - - {preview} - - {/* Branch + git info */} {branch ? ( diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 84876f844c..5c057d45b3 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -15,6 +15,7 @@ import { KeyboardAvoidingView, KeyboardStickyView } from "react-native-keyboard- import { useSafeAreaInsets } from "react-native-safe-area-context"; import { runOnJS } from "react-native-reanimated"; +import { AppText as Text } from "../../components/AppText"; import type { StatusTone } from "../../components/StatusPill"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import type { MobileLayoutVariant } from "../../lib/mobileLayout"; @@ -155,6 +156,7 @@ function useStreamingHaptics(threadId: string, feed: ReadonlyArray + {props.activeWorkDurationLabel ? ( + + + + + + + + + Working for {props.activeWorkDurationLabel} + + + + ) : null} + {props.activePendingApproval || props.activePendingUserInput ? ( {props.activePendingApproval ? ( diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 0714f2d2c8..a45c49df44 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -46,10 +46,6 @@ function compactActivityDetail(detail: string | null): string | null { return cleaned.length > 0 ? cleaned : null; } -function normalizeCompactActivityLabel(value: string): string { - return value.replace(/\s+(?:started|complete|completed)\s*$/i, "").trim(); -} - function buildActivityRows( activities: ReadonlyArray<{ readonly id: string; @@ -59,42 +55,19 @@ function buildActivityRows( readonly status: string | null; }>, ) { - const rows: Array<{ + return activities.map<{ id: string; createdAt: string; summary: string; detail: string | null; status: string | null; - }> = []; - - for (const activity of activities) { - const detail = compactActivityDetail(activity.detail); - const previous = rows.at(-1); - - if ( - previous && - normalizeCompactActivityLabel(previous.summary) === - normalizeCompactActivityLabel(activity.summary) - ) { - rows[rows.length - 1] = { - ...previous, - createdAt: activity.createdAt, - detail: detail ?? previous.detail, - status: activity.status ?? previous.status, - }; - continue; - } - - rows.push({ - id: activity.id, - createdAt: activity.createdAt, - summary: activity.summary, - detail, - status: activity.status, - }); - } - - return rows; + }>((activity) => ({ + id: activity.id, + createdAt: activity.createdAt, + summary: activity.summary, + detail: compactActivityDetail(activity.detail), + status: activity.status, + })); } const MAX_VISIBLE_WORK_LOG_ENTRIES = 6; @@ -416,16 +389,14 @@ function renderFeedEntry( { - const copyValue = row.detail ?? normalizeCompactActivityLabel(row.summary); + const copyValue = row.detail ?? row.summary; props.onCopyWorkRow(row.id, copyValue); }} style={{ fontFamily: "ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, monospace", }} > - {row.detail - ? `${normalizeCompactActivityLabel(row.summary)} - ${row.detail}` - : normalizeCompactActivityLabel(row.summary)} + {row.detail ? `${row.summary} - ${row.detail}` : row.summary} {props.copiedRowId === row.id ? ( diff --git a/apps/mobile/src/features/threads/threadPresentation.ts b/apps/mobile/src/features/threads/threadPresentation.ts index 24c4138c8a..01b6415df8 100644 --- a/apps/mobile/src/features/threads/threadPresentation.ts +++ b/apps/mobile/src/features/threads/threadPresentation.ts @@ -53,15 +53,6 @@ export function messageImageUrl(httpBaseUrl: string | null, attachmentId: string return url.toString(); } -export function lastConversationLine(thread: EnvironmentScopedThreadShell): string { - if (!thread.latestUserMessageAt) { - return "No messages yet."; - } - return thread.session?.status === "running" || thread.session?.status === "starting" - ? "Working on latest request..." - : "Open thread to view latest message."; -} - export function screenTitle(config: T3ServerConfig | null, serverUrl: string | null): string { if (config) { const segments = config.cwd.split(/[/\\]/).filter(Boolean); diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts new file mode 100644 index 0000000000..bc235c2ed7 --- /dev/null +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -0,0 +1,171 @@ +import { describe, expect, it } from "vitest"; + +import { + EventId, + ProjectId, + ThreadId, + TurnId, + type OrchestrationThread, + type OrchestrationThreadActivity, +} from "@t3tools/contracts"; + +import { buildThreadFeed } from "./threadActivity"; + +function makeActivity( + input: Partial & + Pick, +): OrchestrationThreadActivity { + return { + tone: "info", + payload: {}, + turnId: null, + ...input, + }; +} + +function makeThread( + input: Partial & Pick, +): OrchestrationThread { + return { + modelSelection: { provider: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + latestTurn: null, + createdAt: "2026-04-01T00:00:00.000Z", + updatedAt: "2026-04-01T00:00:00.000Z", + archivedAt: null, + deletedAt: null, + messages: [], + proposedPlans: [], + activities: [], + checkpoints: [], + session: null, + ...input, + }; +} + +describe("buildThreadFeed", () => { + it("includes runtime warnings from the latest turn", () => { + const thread = makeThread({ + id: ThreadId.make("thread-1"), + projectId: ProjectId.make("project-1"), + title: "Runtime warning thread", + latestTurn: { + turnId: TurnId.make("turn-latest"), + state: "running", + requestedAt: "2026-04-01T00:00:00.000Z", + startedAt: "2026-04-01T00:00:01.000Z", + completedAt: null, + assistantMessageId: null, + }, + activities: [ + makeActivity({ + id: EventId.make("activity-old"), + kind: "runtime.warning", + summary: "Runtime warning", + createdAt: "2026-04-01T00:00:02.000Z", + turnId: TurnId.make("turn-old"), + payload: { + message: "Old warning", + }, + }), + makeActivity({ + id: EventId.make("activity-latest"), + kind: "runtime.warning", + summary: "Runtime warning", + createdAt: "2026-04-01T00:00:03.000Z", + turnId: TurnId.make("turn-latest"), + payload: { + message: "Latest warning", + }, + }), + ], + }); + + const feed = buildThreadFeed(thread, [], null); + const group = feed[0]; + + expect(group).toMatchObject({ + type: "activity-group", + }); + if (!group || group.type !== "activity-group") { + return; + } + + expect(group.activities).toEqual([ + { + id: "activity-latest", + createdAt: "2026-04-01T00:00:03.000Z", + summary: "Runtime warning", + detail: null, + status: null, + }, + ]); + }); + + it("collapses matching tool lifecycle rows like desktop", () => { + const thread = makeThread({ + id: ThreadId.make("thread-2"), + projectId: ProjectId.make("project-1"), + title: "Collapsed tools", + latestTurn: { + turnId: TurnId.make("turn-1"), + state: "completed", + requestedAt: "2026-04-01T00:00:00.000Z", + startedAt: "2026-04-01T00:00:01.000Z", + completedAt: "2026-04-01T00:00:03.000Z", + assistantMessageId: null, + }, + activities: [ + makeActivity({ + id: EventId.make("tool-updated"), + kind: "tool.updated", + tone: "tool", + summary: "Run tests", + createdAt: "2026-04-01T00:00:01.000Z", + turnId: TurnId.make("turn-1"), + payload: { + title: "Run tests", + itemType: "command_execution", + detail: "/bin/zsh -lc 'bun run test'", + }, + }), + makeActivity({ + id: EventId.make("tool-completed"), + kind: "tool.completed", + tone: "tool", + summary: "Run tests completed", + createdAt: "2026-04-01T00:00:02.000Z", + turnId: TurnId.make("turn-1"), + payload: { + title: "Run tests", + itemType: "command_execution", + detail: "/bin/zsh -lc 'bun run test'", + }, + }), + ], + }); + + const feed = buildThreadFeed(thread, [], null); + const group = feed[0]; + + expect(group).toMatchObject({ + type: "activity-group", + }); + if (!group || group.type !== "activity-group") { + return; + } + + expect(group.activities).toEqual([ + { + id: "tool-completed", + createdAt: "2026-04-01T00:00:02.000Z", + summary: "Run tests", + detail: "bun run test", + status: null, + }, + ]); + }); +}); diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index b74e1f7fe1..a5d901e7a8 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -1,3 +1,4 @@ +import { isToolLifecycleItemType } from "@t3tools/contracts"; import type { ApprovalRequestId, CommandId, @@ -5,6 +6,8 @@ import type { MessageId, OrchestrationThread, OrchestrationThreadActivity, + TurnId, + ToolLifecycleItemType, ThreadId, UserInputQuestion, } from "@t3tools/contracts"; @@ -49,6 +52,25 @@ export interface ThreadFeedActivity { readonly status: string | null; } +interface WorkLogEntry { + id: string; + createdAt: string; + label: string; + detail?: string; + command?: string; + rawCommand?: string; + changedFiles?: ReadonlyArray; + tone: "thinking" | "tool" | "info" | "error"; + toolTitle?: string; + itemType?: ToolLifecycleItemType; + requestKind?: PendingApproval["requestKind"]; +} + +interface DerivedWorkLogEntry extends WorkLogEntry { + activityKind: OrchestrationThreadActivity["kind"]; + collapseKey?: string; +} + type RawThreadFeedEntry = | { readonly type: "message"; @@ -149,6 +171,7 @@ function parseUserInputQuestions( header: question.header, question: question.question, options, + multiSelect: question.multiSelect === true, }; }) .filter((question): question is UserInputQuestion => question !== null); @@ -174,48 +197,519 @@ function resolvePendingUserInputAnswer( return normalizeDraftAnswer(draft?.selectedOptionLabel); } -function coercePayloadRecord(payload: unknown): Record | null { - return payload && typeof payload === "object" ? (payload as Record) : null; -} - -function isToolActivity(activity: OrchestrationThreadActivity): boolean { - return ( - activity.kind === "tool.started" || - activity.kind === "tool.updated" || - activity.kind === "tool.completed" +function deriveWorkLogEntries( + activities: ReadonlyArray, + latestTurnId: TurnId | undefined, +): WorkLogEntry[] { + const ordered = Arr.sort(activities, activityOrder); + const entries = ordered + .filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true)) + .filter((activity) => activity.kind !== "tool.started") + .filter((activity) => activity.kind !== "task.started" && activity.kind !== "task.completed") + .filter((activity) => activity.kind !== "context-window.updated") + .filter((activity) => activity.summary !== "Checkpoint captured") + .filter((activity) => !isPlanBoundaryToolActivity(activity)) + .map(toDerivedWorkLogEntry); + return collapseDerivedWorkLogEntries(entries).map( + ({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry, ); } -function activityDetail(activity: OrchestrationThreadActivity): string | null { - const payload = coercePayloadRecord(activity.payload); - const detail = - typeof payload?.detail === "string" - ? payload.detail - : typeof payload?.error === "string" - ? payload.error - : typeof payload?.message === "string" - ? payload.message - : null; - if (detail && detail.trim().length > 0) { - return detail; +function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean { + if (activity.kind !== "tool.updated" && activity.kind !== "tool.completed") { + return false; } - return null; + + const payload = + activity.payload && typeof activity.payload === "object" + ? (activity.payload as Record) + : null; + return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:"); } -function activityStatus(activity: OrchestrationThreadActivity): string | null { - const payload = coercePayloadRecord(activity.payload); - const status = - typeof payload?.status === "string" - ? payload.status - : typeof payload?.state === "string" - ? payload.state - : null; - if (status && status.trim().length > 0) { - return status; +function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry { + const payload = + activity.payload && typeof activity.payload === "object" + ? (activity.payload as Record) + : null; + const commandPreview = extractToolCommand(payload); + const changedFiles = extractChangedFiles(payload); + const title = extractToolTitle(payload); + const entry: DerivedWorkLogEntry = { + id: activity.id, + createdAt: activity.createdAt, + label: activity.summary, + tone: activity.tone === "approval" ? "info" : activity.tone, + activityKind: activity.kind, + }; + const itemType = extractWorkLogItemType(payload); + const requestKind = extractWorkLogRequestKind(payload); + if (payload && typeof payload.detail === "string" && payload.detail.length > 0) { + const detail = stripTrailingExitCode(payload.detail).output; + if (detail) { + entry.detail = detail; + } } - return null; + if (commandPreview.command) { + entry.command = commandPreview.command; + } + if (commandPreview.rawCommand) { + entry.rawCommand = commandPreview.rawCommand; + } + if (changedFiles.length > 0) { + entry.changedFiles = changedFiles; + } + if (title) { + entry.toolTitle = title; + } + if (itemType) { + entry.itemType = itemType; + } + if (requestKind) { + entry.requestKind = requestKind; + } + const collapseKey = deriveToolLifecycleCollapseKey(entry); + if (collapseKey) { + entry.collapseKey = collapseKey; + } + return entry; } +function collapseDerivedWorkLogEntries( + entries: ReadonlyArray, +): DerivedWorkLogEntry[] { + const collapsed: DerivedWorkLogEntry[] = []; + for (const entry of entries) { + const previous = collapsed.at(-1); + if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) { + collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry); + continue; + } + collapsed.push(entry); + } + return collapsed; +} + +function shouldCollapseToolLifecycleEntries( + previous: DerivedWorkLogEntry, + next: DerivedWorkLogEntry, +): boolean { + if (previous.activityKind !== "tool.updated" && previous.activityKind !== "tool.completed") { + return false; + } + if (next.activityKind !== "tool.updated" && next.activityKind !== "tool.completed") { + return false; + } + if (previous.activityKind === "tool.completed") { + return false; + } + return previous.collapseKey !== undefined && previous.collapseKey === next.collapseKey; +} + +function mergeDerivedWorkLogEntries( + previous: DerivedWorkLogEntry, + next: DerivedWorkLogEntry, +): DerivedWorkLogEntry { + const changedFiles = mergeChangedFiles(previous.changedFiles, next.changedFiles); + const detail = next.detail ?? previous.detail; + const command = next.command ?? previous.command; + const rawCommand = next.rawCommand ?? previous.rawCommand; + const toolTitle = next.toolTitle ?? previous.toolTitle; + const itemType = next.itemType ?? previous.itemType; + const requestKind = next.requestKind ?? previous.requestKind; + const collapseKey = next.collapseKey ?? previous.collapseKey; + return { + ...previous, + ...next, + ...(detail ? { detail } : {}), + ...(command ? { command } : {}), + ...(rawCommand ? { rawCommand } : {}), + ...(changedFiles.length > 0 ? { changedFiles } : {}), + ...(toolTitle ? { toolTitle } : {}), + ...(itemType ? { itemType } : {}), + ...(requestKind ? { requestKind } : {}), + ...(collapseKey ? { collapseKey } : {}), + }; +} + +function mergeChangedFiles( + previous: ReadonlyArray | undefined, + next: ReadonlyArray | undefined, +): string[] { + const merged = [...(previous ?? []), ...(next ?? [])]; + if (merged.length === 0) { + return []; + } + return [...new Set(merged)]; +} + +function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | undefined { + if (entry.activityKind !== "tool.updated" && entry.activityKind !== "tool.completed") { + return undefined; + } + const normalizedLabel = normalizeCompactToolLabel(entry.toolTitle ?? entry.label); + const detail = entry.detail?.trim() ?? ""; + const itemType = entry.itemType ?? ""; + if (normalizedLabel.length === 0 && detail.length === 0 && itemType.length === 0) { + return undefined; + } + return [itemType, normalizedLabel, detail].join("\u001f"); +} + +function normalizeCompactToolLabel(value: string): string { + return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim(); +} + +function workEntryPreview( + workEntry: Pick, +): string | null { + if (workEntry.command) return workEntry.command; + if (workEntry.detail) return workEntry.detail; + if ((workEntry.changedFiles?.length ?? 0) === 0) return null; + const [firstPath] = workEntry.changedFiles ?? []; + if (!firstPath) return null; + return workEntry.changedFiles!.length === 1 + ? firstPath + : `${firstPath} +${workEntry.changedFiles!.length - 1} more`; +} + +function capitalizePhrase(value: string): string { + const trimmed = value.trim(); + if (trimmed.length === 0) { + return value; + } + return `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`; +} + +function workEntryHeading(workEntry: WorkLogEntry): string { + if (!workEntry.toolTitle) { + return capitalizePhrase(normalizeCompactToolLabel(workEntry.label)); + } + return capitalizePhrase(normalizeCompactToolLabel(workEntry.toolTitle)); +} + +function asRecord(value: unknown): Record | null { + return value && typeof value === "object" ? (value as Record) : null; +} + +function asTrimmedString(value: unknown): string | null { + if (typeof value !== "string") { + return null; + } + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} + +function trimMatchingOuterQuotes(value: string): string { + const trimmed = value.trim(); + if ( + (trimmed.startsWith("'") && trimmed.endsWith("'")) || + (trimmed.startsWith('"') && trimmed.endsWith('"')) + ) { + const unquoted = trimmed.slice(1, -1).trim(); + return unquoted.length > 0 ? unquoted : trimmed; + } + return trimmed; +} + +function executableBasename(value: string): string | null { + const trimmed = trimMatchingOuterQuotes(value); + if (trimmed.length === 0) { + return null; + } + const normalized = trimmed.replace(/\\/g, "/"); + const segments = normalized.split("/"); + const last = segments.at(-1)?.trim() ?? ""; + return last.length > 0 ? last.toLowerCase() : null; +} + +function splitExecutableAndRest(value: string): { executable: string; rest: string } | null { + const trimmed = value.trim(); + if (trimmed.length === 0) { + return null; + } + + if (trimmed.startsWith('"') || trimmed.startsWith("'")) { + const quote = trimmed.charAt(0); + const closeIndex = trimmed.indexOf(quote, 1); + if (closeIndex <= 0) { + return null; + } + return { + executable: trimmed.slice(0, closeIndex + 1), + rest: trimmed.slice(closeIndex + 1).trim(), + }; + } + + const firstWhitespace = trimmed.search(/\s/); + if (firstWhitespace < 0) { + return { + executable: trimmed, + rest: "", + }; + } + + return { + executable: trimmed.slice(0, firstWhitespace), + rest: trimmed.slice(firstWhitespace).trim(), + }; +} + +const SHELL_WRAPPER_SPECS = [ + { + executables: ["pwsh", "pwsh.exe", "powershell", "powershell.exe"], + wrapperFlagPattern: /(?:^|\s)-command\s+/i, + }, + { + executables: ["cmd", "cmd.exe"], + wrapperFlagPattern: /(?:^|\s)\/c\s+/i, + }, + { + executables: ["bash", "sh", "zsh"], + wrapperFlagPattern: /(?:^|\s)-(?:l)?c\s+/i, + }, +] as const; + +function findShellWrapperSpec(shell: string) { + return SHELL_WRAPPER_SPECS.find((spec) => + (spec.executables as ReadonlyArray).includes(shell), + ); +} + +function unwrapCommandRemainder(value: string, wrapperFlagPattern: RegExp): string | null { + const match = wrapperFlagPattern.exec(value); + if (!match) { + return null; + } + + const command = value.slice(match.index + match[0].length).trim(); + if (command.length === 0) { + return null; + } + + const unwrapped = trimMatchingOuterQuotes(command); + return unwrapped.length > 0 ? unwrapped : null; +} + +function unwrapKnownShellCommandWrapper(value: string): string { + const split = splitExecutableAndRest(value); + if (!split || split.rest.length === 0) { + return value; + } + + const shell = executableBasename(split.executable); + if (!shell) { + return value; + } + + const spec = findShellWrapperSpec(shell); + if (!spec) { + return value; + } + + return unwrapCommandRemainder(split.rest, spec.wrapperFlagPattern) ?? value; +} + +function formatCommandArrayPart(value: string): string { + return /[\s"'`]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value; +} + +function formatCommandValue(value: unknown): string | null { + const direct = asTrimmedString(value); + if (direct) { + return direct; + } + if (!Array.isArray(value)) { + return null; + } + const parts = value + .map((entry) => asTrimmedString(entry)) + .filter((entry): entry is string => entry !== null); + if (parts.length === 0) { + return null; + } + return parts.map((part) => formatCommandArrayPart(part)).join(" "); +} + +function normalizeCommandValue(value: unknown): string | null { + const formatted = formatCommandValue(value); + return formatted ? unwrapKnownShellCommandWrapper(formatted) : null; +} + +function toRawToolCommand(value: unknown, normalizedCommand: string | null): string | null { + const formatted = formatCommandValue(value); + if (!formatted || normalizedCommand === null) { + return null; + } + return formatted === normalizedCommand ? null : formatted; +} + +function extractToolCommand(payload: Record | null): { + command: string | null; + rawCommand: string | null; +} { + const data = asRecord(payload?.data); + const item = asRecord(data?.item); + const itemResult = asRecord(item?.result); + const itemInput = asRecord(item?.input); + const itemType = asTrimmedString(payload?.itemType); + const detail = asTrimmedString(payload?.detail); + const candidates: unknown[] = [ + item?.command, + itemInput?.command, + itemResult?.command, + data?.command, + itemType === "command_execution" && detail ? stripTrailingExitCode(detail).output : null, + ]; + + for (const candidate of candidates) { + const command = normalizeCommandValue(candidate); + if (!command) { + continue; + } + return { + command, + rawCommand: toRawToolCommand(candidate, command), + }; + } + + return { + command: null, + rawCommand: null, + }; +} + +function extractToolTitle(payload: Record | null): string | null { + return asTrimmedString(payload?.title); +} + +function stripTrailingExitCode(value: string): { + output: string | null; + exitCode?: number | undefined; +} { + const trimmed = value.trim(); + const match = /^(?[\s\S]*?)(?:\s*\d+)>)\s*$/i.exec( + trimmed, + ); + if (!match?.groups) { + return { + output: trimmed.length > 0 ? trimmed : null, + }; + } + const exitCode = Number.parseInt(match.groups.code ?? "", 10); + const normalizedOutput = match.groups.output?.trim() ?? ""; + return { + output: normalizedOutput.length > 0 ? normalizedOutput : null, + ...(Number.isInteger(exitCode) ? { exitCode } : {}), + }; +} + +function extractWorkLogItemType( + payload: Record | null, +): WorkLogEntry["itemType"] | undefined { + if (typeof payload?.itemType === "string" && isToolLifecycleItemType(payload.itemType)) { + return payload.itemType; + } + return undefined; +} + +function extractWorkLogRequestKind( + payload: Record | null, +): WorkLogEntry["requestKind"] | undefined { + if ( + payload?.requestKind === "command" || + payload?.requestKind === "file-read" || + payload?.requestKind === "file-change" + ) { + return payload.requestKind; + } + return requestKindFromRequestType(payload?.requestType) ?? undefined; +} + +function pushChangedFile(target: string[], seen: Set, value: unknown) { + const normalized = asTrimmedString(value); + if (!normalized || seen.has(normalized)) { + return; + } + seen.add(normalized); + target.push(normalized); +} + +function collectChangedFiles(value: unknown, target: string[], seen: Set, depth: number) { + if (depth > 4 || target.length >= 12) { + return; + } + if (Array.isArray(value)) { + for (const entry of value) { + collectChangedFiles(entry, target, seen, depth + 1); + if (target.length >= 12) { + return; + } + } + return; + } + + const record = asRecord(value); + if (!record) { + return; + } + + pushChangedFile(target, seen, record.path); + pushChangedFile(target, seen, record.filePath); + pushChangedFile(target, seen, record.relativePath); + pushChangedFile(target, seen, record.filename); + pushChangedFile(target, seen, record.newPath); + pushChangedFile(target, seen, record.oldPath); + + for (const nestedKey of [ + "item", + "result", + "input", + "data", + "changes", + "files", + "edits", + "patch", + "patches", + "operations", + ]) { + if (!(nestedKey in record)) { + continue; + } + collectChangedFiles(record[nestedKey], target, seen, depth + 1); + if (target.length >= 12) { + return; + } + } +} + +function extractChangedFiles(payload: Record | null): string[] { + const changedFiles: string[] = []; + const seen = new Set(); + collectChangedFiles(asRecord(payload?.data), changedFiles, seen, 0); + return changedFiles; +} + +function compareActivityLifecycleRank(kind: string): number { + if (kind.endsWith(".started") || kind === "tool.started") { + return 0; + } + if (kind.endsWith(".progress") || kind.endsWith(".updated")) { + return 1; + } + if (kind.endsWith(".completed") || kind.endsWith(".resolved")) { + return 2; + } + return 1; +} + +const activityOrder = Order.combineAll([ + Order.mapInput(Order.Number, (activity) => activity.sequence ?? Number.MAX_SAFE_INTEGER), + Order.mapInput(Order.String, (activity) => activity.createdAt), + Order.mapInput(Order.Number, (activity) => compareActivityLifecycleRank(activity.kind)), + Order.mapInput(Order.String, (activity) => activity.id), +]); + function isEmptyMessage(entry: RawThreadFeedEntry): boolean { if (entry.type !== "message") { return false; @@ -263,7 +757,7 @@ export function derivePendingApprovals( activities: ReadonlyArray, ): PendingApproval[] { const openByRequestId = new Map(); - const ordered = Arr.sortWith(activities, (s) => new Date(s.createdAt), Order.Date); + const ordered = Arr.sort(activities, activityOrder); for (const activity of ordered) { const payload = @@ -310,7 +804,7 @@ export function derivePendingUserInputs( activities: ReadonlyArray, ): PendingUserInput[] { const openByRequestId = new Map(); - const ordered = Arr.sortWith(activities, (s) => new Date(s.createdAt), Order.Date); + const ordered = Arr.sort(activities, activityOrder); for (const activity of ordered) { const payload = @@ -390,6 +884,10 @@ export function buildThreadFeed( const loadedMessages = options?.loadedMessages ?? thread.messages; const oldestLoadedMessageCreatedAt = options?.loadedMessages !== undefined ? (loadedMessages[0]?.createdAt ?? null) : null; + const workLogEntries = deriveWorkLogEntries( + thread.activities, + thread.latestTurn?.turnId ?? undefined, + ); const entries = Arr.sortWith( [ ...loadedMessages.map((message) => ({ @@ -405,29 +903,25 @@ export function buildThreadFeed( queuedMessage, sending: queuedMessage.messageId === dispatchingQueuedMessageId, })), - ...thread.activities - .filter((activity) => { - if (!isToolActivity(activity)) { - return false; - } + ...workLogEntries + .filter((entry) => { if (options?.loadedMessages === undefined) { return true; } return ( - oldestLoadedMessageCreatedAt === null || - activity.createdAt >= oldestLoadedMessageCreatedAt + oldestLoadedMessageCreatedAt === null || entry.createdAt >= oldestLoadedMessageCreatedAt ); }) - .map((activity) => ({ + .map((entry) => ({ type: "activity", - id: activity.id, - createdAt: activity.createdAt, + id: entry.id, + createdAt: entry.createdAt, activity: { - id: activity.id, - createdAt: activity.createdAt, - summary: activity.summary, - detail: activityDetail(activity), - status: activityStatus(activity), + id: entry.id, + createdAt: entry.createdAt, + summary: workEntryHeading(entry), + detail: workEntryPreview(entry), + status: null, }, })), ],