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 = /^(?