Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8308: feat(mobile): open historical run transcripts (#9613)

Ryan Yu002b2dcbcabf
diff --git a/apps/mobile/app/(app)/[workspace]/_layout.tsx b/apps/mobile/app/(app)/[workspace]/_layout.tsx
index 2b34cf6337..1f23b5774d 100644
--- a/apps/mobile/app/(app)/[workspace]/_layout.tsx
+++ b/apps/mobile/app/(app)/[workspace]/_layout.tsx
@@ -222,6 +222,15 @@ export default function WorkspaceLayout() {
options={SHEET_OPTIONS}
/>
<Stack.Screen name="issue/[id]/runs" options={SHEET_OPTIONS} />
+ <Stack.Screen
+ name="issue/[id]/run/[taskId]"
+ options={{
+ title: t("navigation:routes.execution_record"),
+ // Opened above the runs formSheet; dismiss back to that sheet.
+ presentation: "modal",
+ headerLeft: () => <ModalCloseButton />,
+ }}
+ />
{/* Full emoji picker for a comment reaction. Pushed from the "+"
button inside the comment long-press tapback row — see
components/issue/comment-context-menu.tsx. */}
diff --git a/apps/mobile/app/(app)/[workspace]/issue/[id]/run/[taskId].tsx b/apps/mobile/app/(app)/[workspace]/issue/[id]/run/[taskId].tsx
new file mode 100644
index 0000000000..5a0242d848
--- /dev/null
+++ b/apps/mobile/app/(app)/[workspace]/issue/[id]/run/[taskId].tsx
@@ -0,0 +1,107 @@
+import { ActivityIndicator, View } from "react-native";
+import { useLocalSearchParams } from "expo-router";
+import { useQuery } from "@tanstack/react-query";
+import { Text } from "@/components/ui/text";
+import { Button } from "@/components/ui/button";
+import { ActorAvatar } from "@/components/ui/actor-avatar";
+import { RunTranscript } from "@/components/issue/run-transcript";
+import { issueTasksOptions } from "@/data/queries/issues";
+import { runTranscriptMessagesOptions } from "@/data/queries/chat";
+import { useRunTranscriptRealtime } from "@/data/realtime/use-run-transcript-realtime";
+import { useActorLookup } from "@/data/use-actor-name";
+import { useWorkspaceStore } from "@/data/workspace-store";
+import { useT } from "@/lib/i18n";
+import { isRunTranscriptTaskId } from "@/lib/run-transcript";
+
+export default function RunTranscriptRoute() {
+ const params = useLocalSearchParams<{ id?: string; taskId?: string }>();
+ const issueId = typeof params.id === "string" ? params.id : "";
+ const taskId = isRunTranscriptTaskId(params.taskId) ? params.taskId : null;
+ const wsId = useWorkspaceStore((s) => s.currentWorkspaceId);
+ const { getName } = useActorLookup();
+ const { t } = useT("issues");
+
+ const tasksQuery = useQuery(issueTasksOptions(wsId, issueId));
+ const task = taskId
+ ? tasksQuery.data?.find((candidate) => candidate.id === taskId)
+ : undefined;
+ const transcriptQuery = useQuery(runTranscriptMessagesOptions(task?.id));
+ useRunTranscriptRealtime(issueId, task?.id);
+
+ const retry = () => {
+ void tasksQuery.refetch();
+ if (task) void transcriptQuery.refetch();
+ };
+
+ if (tasksQuery.isLoading || (task && transcriptQuery.isLoading)) {
+ return (
+ <View className="flex-1 items-center justify-center gap-3">
+ <ActivityIndicator />
+ <Text className="text-sm text-muted-foreground">
+ {t("runs.transcript.loading")}
+ </Text>
+ </View>
+ );
+ }
+
+ if (
+ (tasksQuery.error && !tasksQuery.data) ||
+ (transcriptQuery.error && !transcriptQuery.data)
+ ) {
+ return (
+ <StateMessage text={t("runs.transcript.load_error")}>
+ <Button variant="outline" onPress={retry}>
+ <Text>{t("runs.transcript.retry")}</Text>
+ </Button>
+ </StateMessage>
+ );
+ }
+
+ if (!taskId || !task) {
+ return <StateMessage text={t("runs.transcript.missing")} />;
+ }
+
+ const summary =
+ task.trigger_summary?.trim() || t("summary.direct");
+
+ return (
+ <RunTranscript
+ task={task}
+ items={transcriptQuery.data ?? []}
+ header={
+ <View className="flex-row items-start gap-3 rounded-lg bg-muted/40 px-3 py-3">
+ <ActorAvatar type="agent" id={task.agent_id} size={32} showPresence />
+ <View className="min-w-0 flex-1 gap-1">
+ <Text className="text-sm font-semibold text-foreground">
+ {getName("agent", task.agent_id)}
+ </Text>
+ <Text className="text-sm text-muted-foreground">{summary}</Text>
+ <Text className={statusClass(task.status)}>
+ {t(`runs.status.${task.status}`)}
+ </Text>
+ </View>
+ </View>
+ }
+ />
+ );
+}
+
+function StateMessage({
+ text,
+ children,
+}: {
+ text: string;
+ children?: React.ReactNode;
+}) {
+ return (
+ <View className="flex-1 items-center justify-center gap-4 px-8">
+ <Text className="text-center text-sm text-muted-foreground">{text}</Text>
+ {children}
+ </View>
+ );
+}
+
+function statusClass(status: string): string {
+ if (status === "failed") return "text-xs text-destructive";
+ return "text-xs text-muted-foreground";
+}
diff --git a/apps/mobile/app/(app)/[workspace]/issue/[id]/runs.tsx b/apps/mobile/app/(app)/[workspace]/issue/[id]/runs.tsx
index 340358463b..2da872b615 100644
--- a/apps/mobile/app/(app)/[workspace]/issue/[id]/runs.tsx
+++ b/apps/mobile/app/(app)/[workspace]/issue/[id]/runs.tsx
@@ -9,7 +9,8 @@
* the legacy `useRunsSheetStore` is gone since the route system is the
* single source of truth for what's open.
*
- * Past-row tap is a no-op in v1 — transcript drilldown is deferred.
+ * Past rows push a task-id-addressed execution-record screen. Keeping the
+ * identifier in the route makes deep links and cache misses deterministic.
*/
import { useMemo } from "react";
import { ScrollView, View } from "react-native";
diff --git a/apps/mobile/components/issue/run-row.tsx b/apps/mobile/components/issue/run-row.tsx
index f11bc1e328..81b9bc64a2 100644
--- a/apps/mobile/components/issue/run-row.tsx
+++ b/apps/mobile/components/issue/run-row.tsx
@@ -2,15 +2,16 @@
* Single row inside the agent-runs formSheet route
* (`app/(app)/[workspace]/issue/[id]/runs.tsx`). Same component for active
* and past tasks —
- * the trailing Cancel button is conditional on `status in {queued,
- * dispatched, running}`, and the status badge / colour swaps based on the
- * AgentTask.status enum.
+ * the trailing Cancel button is available for every cancellable status,
+ * and the status badge / colour swaps based on the AgentTask.status enum.
*
- * Tapping a past row is a no-op in v1 — the transcript-detail screen is
- * explicitly out of scope per /Users/qingnaiyuan/.claude/plans/
- * ok-plan-linked-taco.md.
+ * Terminal runs open their persisted execution record. Active rows keep the
+ * cancel affordance and are not links: this route is for historical records.
*/
import { Alert, Pressable, View } from "react-native";
+import { Ionicons } from "@expo/vector-icons";
+import { useColorScheme } from "nativewind";
+import { router } from "expo-router";
import type { AgentTask } from "@multica/core/types";
import { Text } from "@/components/ui/text";
import { ActorAvatar } from "@/components/ui/actor-avatar";
@@ -19,22 +20,29 @@ import { useActorLookup } from "@/data/use-actor-name";
import { runFailureBadgeLabel } from "@/lib/run-failure-badge";
import { timeAgo } from "@/lib/time-ago";
import { useT } from "@/lib/i18n";
+import { isCancellableRunStatus, runTranscriptRoute } from "@/lib/run-transcript";
+import { useWorkspaceStore } from "@/data/workspace-store";
+import { THEME } from "@/lib/theme";
interface Props {
task: AgentTask;
issueId: string;
}
-const ACTIVE_STATUSES: readonly AgentTask["status"][] = [
- "queued",
- "dispatched",
- "running",
+const TERMINAL_STATUSES: readonly AgentTask["status"][] = [
+ "completed",
+ "failed",
+ "cancelled",
];
export function RunRow({ task, issueId }: Props) {
const { getName } = useActorLookup();
const { t } = useT("issues");
- const isActive = ACTIVE_STATUSES.includes(task.status);
+ const { colorScheme } = useColorScheme();
+ const theme = THEME[colorScheme === "dark" ? "dark" : "light"];
+ const workspace = useWorkspaceStore((s) => s.currentWorkspaceSlug);
+ const isActive = isCancellableRunStatus(task.status);
+ const isTerminal = TERMINAL_STATUSES.includes(task.status);
const summary =
task.trigger_summary?.trim() || fallbackSummary(task, t);
// Past tasks use completed_at when present (server fills it for terminal
@@ -42,8 +50,8 @@ export function RunRow({ task, issueId }: Props) {
// long it's been waiting.
const timestamp = task.completed_at || task.created_at;
- return (
- <View className="flex-row items-start gap-3 py-2">
+ const content = (
+ <>
<ActorAvatar type="agent" id={task.agent_id} size={28} showPresence />
<View className="flex-1 gap-1">
<Text
@@ -61,7 +69,29 @@ export function RunRow({ task, issueId }: Props) {
</View>
</View>
{isActive ? <CancelButton taskId={task.id} issueId={issueId} /> : null}
- </View>
+ {isTerminal ? (
+ <Ionicons
+ name="chevron-forward"
+ size={16}
+ color={theme.mutedForeground}
+ />
+ ) : null}
+ </>
+ );
+
+ if (!isTerminal || !workspace) {
+ return <View className="flex-row items-start gap-3 py-2">{content}</View>;
+ }
+
+ return (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={t("runs.open_transcript", { summary })}
+ onPress={() => router.push(runTranscriptRoute(workspace, issueId, task.id))}
+ className="flex-row items-start gap-3 py-2 active:opacity-60"
+ >
+ {content}
+ </Pressable>
);
}
diff --git a/apps/mobile/components/issue/run-transcript.tsx b/apps/mobile/components/issue/run-transcript.tsx
new file mode 100644
index 0000000000..0287e7b422
--- /dev/null
+++ b/apps/mobile/components/issue/run-transcript.tsx
@@ -0,0 +1,241 @@
+import { useMemo, useState } from "react";
+import { FlatList, Pressable, View } from "react-native";
+import { Ionicons } from "@expo/vector-icons";
+import { useColorScheme } from "nativewind";
+import type { AgentTask, TaskMessagePayload } from "@multica/core/types";
+import { redactSecrets } from "@multica/core/security/redact-secrets";
+import { Text } from "@/components/ui/text";
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from "@/components/ui/collapsible";
+import { Markdown } from "@/lib/markdown";
+import { useT } from "@/lib/i18n";
+import { buildRunTranscriptEntries, getRunDiagnostics, runToolContext } from "@/lib/run-transcript";
+import type { RunTranscriptEntry } from "@/lib/run-transcript";
+import { THEME } from "@/lib/theme";
+
+const DISPLAY_CLIP_CHARS = 8_000;
+
+export function RunTranscript({
+ items,
+ task,
+ header,
+}: {
+ items: readonly TaskMessagePayload[];
+ task: AgentTask;
+ header: React.ReactElement;
+}) {
+ const { t } = useT("issues");
+ const timeline = useMemo(() => buildRunTranscriptEntries(items), [items]);
+ const diagnostics = getRunDiagnostics(task);
+
+ return (
+ <FlatList
+ className="flex-1"
+ contentContainerClassName="px-4 py-4"
+ data={timeline}
+ keyExtractor={(item, index) => `${item.task_id}-${item.seq}-${index}`}
+ renderItem={({ item }) => <TranscriptEntry item={item} />}
+ ItemSeparatorComponent={EntrySeparator}
+ ListHeaderComponent={
+ <View className="mb-4 gap-4">
+ {header}
+ {diagnostics ? (
+ <View className={`gap-2 rounded-lg border px-3 py-3 ${
+ task.status === "failed" ? "border-destructive/30 bg-destructive/5" : "border-border bg-card"
+ }`}>
+ {diagnostics.reasonKey ? (
+ <Text className="text-sm font-medium text-destructive">
+ {t(`chat:${diagnostics.reasonKey}`)}
+ </Text>
+ ) : null}
+ {diagnostics.error ? (
+ <View className="gap-1">
+ <Text className="text-xs font-medium text-muted-foreground">
+ {t("runs.transcript.diagnostics")}
+ </Text>
+ <Text selectable className="font-mono text-xs text-foreground">
+ {diagnostics.error}
+ </Text>
+ </View>
+ ) : null}
+ </View>
+ ) : null}
+ </View>
+ }
+ ListEmptyComponent={
+ diagnostics ? null : (
+ <View className="items-center rounded-lg border border-dashed border-border px-4 py-8">
+ <Text className="text-sm text-muted-foreground">
+ {t("runs.transcript.empty")}
+ </Text>
+ </View>
+ )
+ }
+ />
+ );
+}
+
+function EntrySeparator() {
+ return <View className="h-2" />;
+}
+
+function TranscriptEntry({ item: entry }: { item: RunTranscriptEntry }) {
+ if (entry.kind === "tool") return <ToolEntry call={entry.call} result={entry.result} />;
+ const item = entry.message;
+ switch (item.type) {
+ case "thinking":
+ return (
+ <EntryCard icon="bulb-outline" labelKey="thinking" collapsible>
+ <Text selectable className="text-sm italic text-muted-foreground">
+ {item.content || "—"}
+ </Text>
+ </EntryCard>
+ );
+ case "error":
+ return (
+ <EntryCard icon="alert-circle-outline" labelKey="error" destructive>
+ <Text selectable className="text-sm text-destructive">
+ {item.content || "—"}
+ </Text>
+ </EntryCard>
+ );
+ case "text":
+ default:
+ return (
+ <EntryCard icon="chatbubble-ellipses-outline" labelKey="output">
+ {item.content ? (
+ <Markdown content={item.content} />
+ ) : (
+ <Text className="text-sm text-muted-foreground">—</Text>
+ )}
+ </EntryCard>
+ );
+ }
+}
+
+function ToolEntry({ call, result }: { call?: TaskMessagePayload; result?: TaskMessagePayload }) {
+ const { t } = useT("issues");
+ const input =
+ call?.input && Object.keys(call.input).length > 0
+ ? redactSecrets(JSON.stringify(call.input, null, 2))
+ : "—";
+ const detail = [call?.tool || result?.tool || t("runs.transcript.unknown_tool"), runToolContext(call)]
+ .filter(Boolean).join(" · ");
+
+ return (
+ <EntryCard
+ icon={call ? "construct-outline" : "terminal-outline"}
+ labelKey={call ? "tool_call" : "tool_output"}
+ detail={detail}
+ collapsible
+ >
+ <View className="gap-2">
+ {call ? (
+ <View className="rounded-md bg-muted px-3 py-2">
+ <Text selectable className="font-mono text-xs text-muted-foreground">
+ {input}
+ </Text>
+ </View>
+ ) : null}
+ {result ? <ToolResultContent item={result} /> : null}
+ </View>
+ </EntryCard>
+ );
+}
+
+function ToolResultContent({ item }: { item: TaskMessagePayload }) {
+ const { t } = useT("issues");
+ const [showFullOutput, setShowFullOutput] = useState(false);
+ const output = item.output ?? "";
+ const clipped = output.length > DISPLAY_CLIP_CHARS;
+ const shown = clipped && !showFullOutput
+ ? `${output.slice(0, DISPLAY_CLIP_CHARS)}...`
+ : output;
+
+ return (
+ <View className="gap-2">
+ <Text className="text-xs font-medium text-muted-foreground">
+ {t("runs.transcript.tool_output")}
+ </Text>
+ <View className="rounded-md bg-muted px-3 py-2">
+ <Text selectable className="font-mono text-xs text-muted-foreground">
+ {shown || "—"}
+ </Text>
+ </View>
+ {clipped ? (
+ <Pressable
+ accessibilityRole="button"
+ onPress={() => setShowFullOutput(!showFullOutput)}
+ className="mt-2 py-1"
+ >
+ <Text className="text-sm text-brand">
+ {t(showFullOutput ? "runs.transcript.show_less" : "runs.transcript.show_full_output")}
+ </Text>
+ </Pressable>
+ ) : null}
+ {item.output_truncated === true ? (
+ <Text className="mt-2 text-xs text-muted-foreground">
+ {t("runs.transcript.truncated")}
+ </Text>
+ ) : null}
+ </View>
+ );
+}
+
+function EntryCard({
+ icon,
+ labelKey,
+ detail,
+ destructive = false,
+ collapsible = false,
+ children,
+}: {
+ icon: React.ComponentProps<typeof Ionicons>["name"];
+ labelKey: "thinking" | "error" | "output" | "tool_call" | "tool_output";
+ detail?: string;
+ destructive?: boolean;
+ collapsible?: boolean;
+ children: React.ReactNode;
+}) {
+ const { t } = useT("issues");
+ const [open, setOpen] = useState(false);
+ const { colorScheme } = useColorScheme();
+ const theme = THEME[colorScheme === "dark" ? "dark" : "light"];
+ const className = `rounded-lg border px-3 py-3 ${
+ destructive ? "border-destructive/30 bg-destructive/5" : "border-border bg-card"
+ }`;
+ const heading = (
+ <>
+ <Ionicons name={icon} size={14} color={destructive ? theme.destructive : theme.mutedForeground} />
+ <Text numberOfLines={2} className={`flex-1 text-xs font-medium ${destructive ? "text-destructive" : "text-muted-foreground"}`}>
+ {t(`runs.transcript.${labelKey}`)}{detail ? ` · ${detail}` : ""}
+ </Text>
+ </>
+ );
+
+ if (collapsible) {
+ return (
+ <Collapsible open={open} onOpenChange={setOpen} className={className}>
+ <CollapsibleTrigger className="flex-row items-center gap-2">
+ {heading}
+ <Ionicons
+ name={open ? "chevron-down" : "chevron-forward"}
+ size={14}
+ color={theme.mutedForeground}
+ />
+ </CollapsibleTrigger>
+ <CollapsibleContent className="pt-2">{children}</CollapsibleContent>
+ </Collapsible>
+ );
+ }
+
+ return (
+ <View className={className}>
+ <View className="mb-2 flex-row items-center gap-2">{heading}</View>
+ {children}
+ </View>
+ );
+}
diff --git a/apps/mobile/data/queries/chat.ts b/apps/mobile/data/queries/chat.ts
index a1b8f07432..b6919fbae6 100644
--- a/apps/mobile/data/queries/chat.ts
+++ b/apps/mobile/data/queries/chat.ts
@@ -10,12 +10,12 @@
* Same shape as web's `chatKeys` in packages/core/chat/queries.ts (mobile
* owns its own copy per the "mirror, don't import" rule in apps/mobile/CLAUDE.md).
*
- * `staleTime: Infinity` everywhere — caches are kept fresh by WS event
- * handlers, not by background refetch. Foreground / reconnect invalidates
- * are scoped to each owning hook (see use-chat-sessions-realtime.ts and
- * use-chat-session-realtime.ts).
+ * Base caches use `staleTime: Infinity` and WS updates. The run detail
+ * overrides freshness to backfill whenever its selected task becomes active.
+ * Reconnect invalidates are scoped to each owning realtime hook.
*/
import { queryOptions } from "@tanstack/react-query";
+import type { TaskMessagePayload } from "@multica/core/types";
import { api } from "@/data/api";
export const chatKeys = {
@@ -78,4 +78,27 @@ export const taskMessagesOptions = (taskId: string | null | undefined) =>
queryFn: ({ signal }) => api.listTaskMessages(taskId!, { signal }),
enabled: isTaskMessageTaskId(taskId),
staleTime: Infinity,
+ // A backfill can snapshot before a live frame is persisted. Keep both
+ // sets of seqs so its later response cannot erase the realtime tail.
+ structuralSharing: (previous, incoming) => {
+ const existing = previous as TaskMessagePayload[] | undefined;
+ const bySeq = new Map(
+ (existing ?? []).map((m) => [m.seq, m]),
+ );
+ let changed = !existing;
+ for (const message of incoming as TaskMessagePayload[]) {
+ if (bySeq.get(message.seq) !== message) changed = true;
+ bySeq.set(message.seq, message);
+ }
+ if (!changed) return existing!;
+ return [...bySeq.values()].sort((a, b) => a.seq - b.seq);
+ },
+ });
+
+export const runTranscriptMessagesOptions = (taskId: string | null | undefined) =>
+ queryOptions({
+ ...taskMessagesOptions(taskId),
+ // A cached cancelled run may predate the final flush. Also backfill when
+ // the initial issue/task lookup resolves after this observer mounted.
+ staleTime: 0,
});
diff --git a/apps/mobile/data/realtime/chat-ws-updaters.ts b/apps/mobile/data/realtime/chat-ws-updaters.ts
index 4038cffe83..cc1efb60c3 100644
--- a/apps/mobile/data/realtime/chat-ws-updaters.ts
+++ b/apps/mobile/data/realtime/chat-ws-updaters.ts
@@ -319,3 +319,11 @@ export function appendTaskMessage(
},
);
}
+
+export async function refreshTaskMessages(qc: QueryClient, taskId: string) {
+ const queryKey = chatKeys.taskMessages(taskId);
+ // Invalidation alone reuses an unfinished first load. Cancel it first,
+ // retaining any WS rows received since it began instead of reverting them.
+ await qc.cancelQueries({ queryKey }, { revert: false, silent: true });
+ await qc.invalidateQueries({ queryKey });
+}
diff --git a/apps/mobile/data/realtime/use-run-transcript-realtime.test.ts b/apps/mobile/data/realtime/use-run-transcript-realtime.test.ts
new file mode 100644
index 0000000000..7fb6c1d456
--- /dev/null
+++ b/apps/mobile/data/realtime/use-run-transcript-realtime.test.ts
@@ -0,0 +1,193 @@
+// @vitest-environment node
+import { QueryClient, QueryObserver } from "@tanstack/react-query";
+import type { TaskMessagePayload } from "@multica/core/types";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { api } from "@/data/api";
+import { chatKeys, runTranscriptMessagesOptions } from "@/data/queries/chat";
+import { issueKeys } from "@/data/queries/issue-keys";
+import type { WSSubscriptionSetup } from "@/lib/use-ws-subscriptions";
+import type { WSClient } from "./ws-client";
+import { useRunTranscriptRealtime } from "./use-run-transcript-realtime";
+
+const state = vi.hoisted(() => ({
+ qc: undefined as unknown as QueryClient,
+ setup: undefined as WSSubscriptionSetup | undefined,
+}));
+vi.mock("@/data/api", () => ({ api: { listTaskMessages: vi.fn() } }));
+vi.mock("@tanstack/react-query", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),
+ useQueryClient: () => state.qc,
+}));
+vi.mock("@/lib/use-ws-subscriptions", () => ({
+ useWSSubscriptions: (setup: WSSubscriptionSetup) => { state.setup = setup; },
+}));
+
+const wsId = "workspace-1";
+const issueId = "issue-1";
+const taskId = "123e4567-e89b-12d3-a456-426614174000";
+const key = chatKeys.taskMessages(taskId);
+const tasksKey = issueKeys.tasks(wsId, issueId);
+const cleanups: (() => void)[] = [];
+
+function message(seq: number): TaskMessagePayload {
+ return { task_id: taskId, issue_id: issueId, seq, type: "text", content: `row ${seq}` };
+}
+
+function connect() {
+ useRunTranscriptRealtime(issueId, taskId);
+ const handlers = new Map<string, (payload: unknown) => void>();
+ let reconnect = () => {};
+ const ws = {
+ on: (event: string, handler: (payload: unknown) => void) => {
+ handlers.set(event, handler);
+ return () => { handlers.delete(event); };
+ },
+ onReconnect: (handler: () => void) => {
+ reconnect = handler;
+ return () => { reconnect = () => {}; };
+ },
+ };
+ const cleanup = () => { for (const unsubscribe of unsubscribes) unsubscribe(); };
+ const unsubscribes = state.setup!(ws as unknown as WSClient, wsId) ?? [];
+ cleanups.push(cleanup);
+ return {
+ emit: (event: string, payload: unknown) => { handlers.get(event)?.(payload); },
+ reconnect: () => reconnect(),
+ cleanup,
+ };
+}
+
+function open() {
+ const observer = new QueryObserver(state.qc, runTranscriptMessagesOptions(taskId));
+ cleanups.push(observer.subscribe(() => {}));
+ return observer;
+}
+
+async function expectRows(seqs: number[]) {
+ await vi.waitFor(() => {
+ expect(state.qc.getQueryState(key)?.fetchStatus).toBe("idle");
+ expect(state.qc.getQueryData<TaskMessagePayload[]>(key)?.map((m) => m.seq)).toEqual(seqs);
+ });
+}
+
+describe("run transcript cache lifecycle", () => {
+ beforeEach(() => {
+ state.qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } });
+ state.setup = undefined;
+ vi.mocked(api.listTaskMessages).mockReset().mockResolvedValue([message(1)]);
+ state.qc.setQueryData(tasksKey, []);
+ });
+ afterEach(() => {
+ for (const cleanup of cleanups.splice(0)) cleanup();
+ state.qc.clear();
+ });
+
+ it("backfills every open even when a cancelled run has an Infinity-fresh cache", async () => {
+ state.qc.setQueryData(key, [message(1)]);
+ vi.mocked(api.listTaskMessages).mockResolvedValue([message(1), message(2)]);
+ open();
+ await expectRows([1, 2]);
+ expect(api.listTaskMessages).toHaveBeenCalledWith(taskId, { signal: expect.any(AbortSignal) });
+ });
+
+ it("backfills a warm cache when the task lookup resolves after the screen mounts", async () => {
+ state.qc.setQueryData(key, [message(1)]);
+ vi.mocked(api.listTaskMessages).mockResolvedValue([message(1), message(2)]);
+ const observer = new QueryObserver(state.qc, runTranscriptMessagesOptions(undefined));
+ cleanups.push(observer.subscribe(() => {}));
+ expect(api.listTaskMessages).not.toHaveBeenCalled();
+ observer.setOptions(runTranscriptMessagesOptions(taskId));
+ await expectRows([1, 2]);
+ });
+
+ it("accepts the final flush after cancellation, in order and without duplicates", async () => {
+ const ws = connect();
+ open();
+ await expectRows([1]);
+ ws.emit("task:cancelled", { task_id: taskId, issue_id: issueId });
+ await expectRows([1]);
+ ws.emit("task:message", message(3));
+ ws.emit("task:message", message(2));
+ ws.emit("task:message", message(2));
+ await expectRows([1, 2, 3]);
+ });
+
+ it.each(["task:completed", "task:failed", "task:cancelled", "reconnect"])(
+ "backfills messages and run metadata on %s", async (event) => {
+ const ws = connect();
+ open();
+ await expectRows([1]);
+ vi.mocked(api.listTaskMessages).mockResolvedValue([message(1), message(2)]);
+ if (event === "reconnect") ws.reconnect();
+ else ws.emit(event, { task_id: taskId, issue_id: issueId });
+ await expectRows([1, 2]);
+ expect(state.qc.getQueryState(tasksKey)?.isInvalidated).toBe(true);
+ },
+ );
+
+ it("keeps live rows when an older HTTP snapshot finishes afterward", async () => {
+ let resolve!: (rows: TaskMessagePayload[]) => void;
+ vi.mocked(api.listTaskMessages).mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
+ const ws = connect();
+ open();
+ ws.emit("task:message", message(2));
+ resolve([message(1)]);
+ await expectRows([1, 2]);
+
+ // Persisted data wins for an existing seq, while absent seqs survive.
+ const persisted = { ...message(2), content: "persisted correction" };
+ vi.mocked(api.listTaskMessages).mockResolvedValue([persisted]);
+ ws.reconnect();
+ await vi.waitFor(() => expect(state.qc.getQueryData<TaskMessagePayload[]>(key)?.[1]).toEqual(persisted));
+ await expectRows([1, 2]);
+ });
+
+ it("starts a fresh request if a terminal event arrives during the first load", async () => {
+ let resolveOld!: (rows: TaskMessagePayload[]) => void;
+ vi.mocked(api.listTaskMessages)
+ .mockImplementationOnce(() => new Promise((done) => { resolveOld = done; }))
+ .mockResolvedValue([message(1), message(2)]);
+ const ws = connect();
+ open();
+ ws.emit("task:completed", { task_id: taskId, issue_id: issueId });
+ resolveOld([message(1)]);
+ await expectRows([1, 2]);
+ expect(api.listTaskMessages).toHaveBeenCalledTimes(2);
+ });
+
+ it("preserves realtime rows and avoids an error flash when cancelling an old fetch", async () => {
+ vi.mocked(api.listTaskMessages)
+ .mockImplementationOnce(() => new Promise(() => {}))
+ .mockResolvedValue([message(1)]);
+ const ws = connect();
+ const observer = open();
+ const statuses: string[] = [];
+ cleanups.push(observer.subscribe((result) => { statuses.push(result.status); }));
+ ws.emit("task:message", message(2));
+ ws.emit("task:completed", { task_id: taskId, issue_id: issueId });
+ await expectRows([1, 2]);
+ expect(statuses).not.toContain("error");
+ expect(api.listTaskMessages).toHaveBeenCalledTimes(2);
+ });
+
+ it("ignores other runs/issues and stops responding after cleanup", async () => {
+ const ws = connect();
+ open();
+ await expectRows([1]);
+ for (const payload of [
+ { ...message(2), task_id: "other-task" },
+ { ...message(2), issue_id: "other-issue" },
+ ]) {
+ ws.emit("task:message", payload);
+ ws.emit("task:cancelled", payload);
+ }
+ expect(api.listTaskMessages).toHaveBeenCalledTimes(1);
+ expect(state.qc.getQueryState(tasksKey)?.isInvalidated).toBe(false);
+ ws.cleanup();
+ ws.emit("task:message", message(2));
+ ws.emit("task:completed", message(2));
+ ws.reconnect();
+ await expectRows([1]);
+ expect(api.listTaskMessages).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/mobile/data/realtime/use-run-transcript-realtime.ts b/apps/mobile/data/realtime/use-run-transcript-realtime.ts
new file mode 100644
index 0000000000..75091c9369
--- /dev/null
+++ b/apps/mobile/data/realtime/use-run-transcript-realtime.ts
@@ -0,0 +1,35 @@
+import { useQueryClient } from "@tanstack/react-query";
+import { issueKeys } from "@/data/queries/issue-keys";
+import { useWSSubscriptions } from "@/lib/use-ws-subscriptions";
+import { appendTaskMessage, refreshTaskMessages } from "./chat-ws-updaters";
+
+/** Own the selected run's stream for the lifetime of its detail screen. */
+export function useRunTranscriptRealtime(issueId: string, taskId: string | undefined) {
+ const qc = useQueryClient();
+
+ useWSSubscriptions((ws, wsId) => {
+ if (!issueId || !taskId) return;
+
+ const isMine = (payload: { issue_id?: string; task_id: string }) =>
+ payload.issue_id === issueId && payload.task_id === taskId;
+ const refresh = () => {
+ void refreshTaskMessages(qc, taskId);
+ void qc.invalidateQueries({ queryKey: issueKeys.tasks(wsId, issueId) });
+ };
+ const onTerminal = (payload: { issue_id?: string; task_id: string }) => {
+ if (isMine(payload)) refresh();
+ };
+
+ return [
+ ws.on("task:message", (payload) => {
+ if (isMine(payload)) appendTaskMessage(qc, payload);
+ }),
+ ws.on("task:completed", onTerminal),
+ ws.on("task:failed", onTerminal),
+ // Cancellation precedes the final flush. Continue accepting messages
+ // afterward, and backfill again on the daemon's cancellation ack.
+ ws.on("task:cancelled", onTerminal),
+ ws.onReconnect(refresh),
+ ];
+ }, [issueId, taskId, qc]);
+}
diff --git a/apps/mobile/data/schemas.test.ts b/apps/mobile/data/schemas.test.ts
new file mode 100644
index 0000000000..18eb79b33a
--- /dev/null
+++ b/apps/mobile/data/schemas.test.ts
@@ -0,0 +1,48 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { parseWithFallback } from "@/lib/parse-response";
+import {
+ EMPTY_TASK_MESSAGE_LIST,
+ TaskMessageListSchema,
+} from "./schemas";
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("TaskMessageListSchema", () => {
+ it("keeps an incomplete row renderable with safe defaults", () => {
+ const parsed = TaskMessageListSchema.parse([
+ {
+ type: "future_event",
+ task_id: 42,
+ seq: "first",
+ content: { malformed: true },
+ input: "not-an-object",
+ },
+ ]);
+
+ expect(parsed).toEqual([
+ expect.objectContaining({
+ type: "text",
+ task_id: "",
+ seq: 0,
+ content: undefined,
+ input: undefined,
+ }),
+ ]);
+ });
+
+ it("falls back to an empty transcript for a malformed response root", () => {
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+
+ expect(
+ parseWithFallback(
+ { messages: "not-an-array" },
+ TaskMessageListSchema,
+ EMPTY_TASK_MESSAGE_LIST,
+ { endpoint: "GET /api/tasks/:id/messages" },
+ ),
+ ).toEqual([]);
+ });
+});
diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.ts
index afbe16baa4..8f914d86e4 100644
--- a/apps/mobile/data/schemas.ts
+++ b/apps/mobile/data/schemas.ts
@@ -336,25 +336,26 @@ export const SendChatMessageResponseSchema: z.ZodType<SendChatMessageResponse> =
// error). Mirrors web's TaskMessagePayload type and the WS `task:message`
// payload so the mobile cache shape stays interchangeable with web's.
export const TaskMessagePayloadSchema: z.ZodType<TaskMessagePayload> = z.object({
- task_id: z.string(),
- issue_id: z.string().default(""),
- chat_session_id: z.string().optional(),
- seq: z.number().default(0),
+ call_id: z.string().optional().catch(undefined),
+ task_id: z.string().default("").catch(""),
+ issue_id: z.string().default("").catch(""),
+ chat_session_id: z.string().optional().catch(undefined),
+ seq: z.number().default(0).catch(0),
// Enum drift defense: unknown server-side types fall back to "text" so
// the row still renders (as a plain markdown chunk) instead of crashing
// the timeline. Matches root CLAUDE.md "Enum drift downgrades, not crashes".
type: z
.enum(["text", "thinking", "tool_use", "tool_result", "error"])
.catch("text"),
- tool: z.string().optional(),
- content: z.string().optional(),
- input: z.record(z.string(), z.unknown()).optional(),
- output: z.string().optional(),
+ tool: z.string().optional().catch(undefined),
+ content: z.string().optional().catch(undefined),
+ input: z.record(z.string(), z.unknown()).optional().catch(undefined),
+ output: z.string().optional().catch(undefined),
// Optional with no default: absent means no daemon measured this record's
// completeness, which is not the same as measured-and-complete. `.catch`
// keeps a malformed value from failing the row and emptying the transcript.
output_truncated: z.boolean().optional().catch(undefined),
- created_at: z.string().optional(),
+ created_at: z.string().optional().catch(undefined),
}).loose();
export const TaskMessageListSchema = z.array(TaskMessagePayloadSchema).default([]);
@@ -413,7 +414,16 @@ export const AgentTaskSchema: z.ZodType<AgentTask> = z.object({
runtime_id: z.string().default(""),
issue_id: z.string().default(""),
status: z
- .enum(["queued", "dispatched", "running", "completed", "failed", "cancelled"])
+ .enum([
+ "queued",
+ "deferred",
+ "dispatched",
+ "waiting_local_directory",
+ "running",
+ "completed",
+ "failed",
+ "cancelled",
+ ])
.catch("queued"),
priority: z.number().default(0),
dispatched_at: z.string().nullable().default(null),
diff --git a/apps/mobile/lib/run-transcript.test.ts b/apps/mobile/lib/run-transcript.test.ts
new file mode 100644
index 0000000000..6162bddf83
--- /dev/null
+++ b/apps/mobile/lib/run-transcript.test.ts
@@ -0,0 +1,160 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { TaskMessagePayload } from "@multica/core/types";
+import { AgentTaskSchema } from "@/data/schemas";
+import {
+ buildRunTranscript,
+ buildRunTranscriptEntries,
+ getRunDiagnostics,
+ isCancellableRunStatus,
+ isRunTranscriptTaskId,
+ RUN_TRANSCRIPT_PATHNAME,
+ runTranscriptRoute,
+ runToolContext,
+} from "./run-transcript";
+
+describe("run transcript route", () => {
+ it("keeps the issue and task identifiers in the route", () => {
+ expect(runTranscriptRoute("acme", "issue-7", "task-9")).toEqual({
+ pathname: "/[workspace]/issue/[id]/run/[taskId]",
+ params: {
+ workspace: "acme",
+ id: "issue-7",
+ taskId: "task-9",
+ },
+ });
+ expect(RUN_TRANSCRIPT_PATHNAME).toContain("[taskId]");
+ });
+
+ it("accepts only backend task UUIDs for transcript requests", () => {
+ expect(
+ isRunTranscriptTaskId("123e4567-e89b-12d3-a456-426614174000"),
+ ).toBe(true);
+ expect(isRunTranscriptTaskId("optimistic-task")).toBe(false);
+ expect(isRunTranscriptTaskId(undefined)).toBe(false);
+ });
+});
+
+function message(seq: number, type: TaskMessagePayload["type"], content?: string): TaskMessagePayload {
+ return { task_id: "task-1", issue_id: "issue-1", seq, type, content };
+}
+
+describe("historical run transcript", () => {
+ it("pairs parallel same-name calls by ID when results finish in reverse order", () => {
+ const callA = { ...message(1, "tool_use"), tool: "Bash", call_id: "A", input: { command: "test A" } };
+ const callB = { ...message(2, "tool_use"), tool: "Bash", call_id: "B", input: { command: "test B" } };
+ const resultB = { ...message(3, "tool_result"), tool: "Bash", call_id: "B", output: "B failed" };
+ const resultA = { ...message(4, "tool_result"), tool: "Bash", call_id: "A", output: "A passed" };
+ const source = [callA, callB, resultB, resultA];
+ const original = structuredClone(source);
+
+ expect(buildRunTranscriptEntries(source)).toEqual([
+ { kind: "tool", task_id: "task-1", seq: 1, call: callA, result: resultA },
+ { kind: "tool", task_id: "task-1", seq: 2, call: callB, result: resultB },
+ ]);
+ expect(source).toEqual(original);
+ expect(runToolContext(callA)).toBe("test A");
+ expect(runToolContext(callB)).toBe("test B");
+ });
+
+ it("keeps unmatched and unidentified tool output without guessing a call", () => {
+ const call = { ...message(1, "tool_use"), tool: "Read", call_id: "known" };
+ const orphan = { ...message(2, "tool_result"), tool: "Read", call_id: "missing", output: "orphan" };
+ const noId = { ...message(3, "tool_result"), tool: "Read", output: "legacy" };
+ expect(buildRunTranscriptEntries([call, orphan, noId, message(4, "text", "done")])).toEqual([
+ { kind: "tool", task_id: "task-1", seq: 1, call },
+ { kind: "tool", task_id: "task-1", seq: 2, result: orphan },
+ { kind: "tool", task_id: "task-1", seq: 3, result: noId },
+ { kind: "message", task_id: "task-1", seq: 4, message: message(4, "text", "done") },
+ ]);
+ });
+
+ it("does not pair identical call IDs from different tasks", () => {
+ const call = { ...message(1, "tool_use"), call_id: "shared" };
+ const result = { ...message(2, "tool_result"), task_id: "another-task", call_id: "shared" };
+ expect(buildRunTranscriptEntries([call, result])).toHaveLength(2);
+ });
+
+ it("redacts tool context and retains file paths in the collapsed heading", () => {
+ expect(runToolContext({ ...message(1, "tool_use"), input: { file_path: "src/main.ts" } })).toBe("src/main.ts");
+ expect(runToolContext({ ...message(1, "tool_use"), input: { command: "echo Authorization: Bearer fake-value" } }))
+ .toBe("echo Authorization: Bearer [REDACTED]");
+ expect(runToolContext(undefined)).toBeUndefined();
+ });
+
+ it("sorts and joins streamed Markdown without changing the source messages", () => {
+ const messages = [
+ message(3, "text", "\n```"),
+ message(1, "text", "```ts\n"),
+ message(2, "text", "const answer = 42;"),
+ ];
+ const original = structuredClone(messages);
+
+ expect(buildRunTranscript(messages)).toEqual([
+ expect.objectContaining({ seq: 1, content: "```ts\nconst answer = 42;\n```" }),
+ ]);
+ expect(messages).toEqual(original);
+ });
+
+ it("merges adjacent thinking but keeps tool calls, results, and errors in order", () => {
+ const messages = [
+ message(1, "thinking", "First "),
+ { ...message(2, "thinking", "check"), created_at: "2026-10-28T00:00:02Z" },
+ { ...message(3, "tool_use"), tool: "Read", input: { file_path: "README.md" }, call_id: "read-1" },
+ { ...message(4, "tool_result"), output: "contents", output_truncated: true, call_id: "read-1" },
+ message(5, "thinking", "Then"),
+ message(6, "error", "Failed"),
+ message(7, "text", "Result"),
+ ];
+
+ expect(buildRunTranscript(messages)).toEqual([
+ { ...messages[0], content: "First check", created_at: messages[1].created_at },
+ ...messages.slice(2),
+ ]);
+ expect(buildRunTranscript([])).toEqual([]);
+ });
+
+ it("redacts secrets after joining fragments, including tool output", () => {
+ const token = ["ghp_", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn"].join("");
+ const result = buildRunTranscript([
+ message(1, "text", token.slice(0, 12)),
+ message(2, "text", token.slice(12)),
+ { ...message(3, "tool_result"), output: `found ${token}` },
+ ]);
+
+ expect(result[0].content).toBe("[REDACTED GITHUB TOKEN]");
+ expect(result[1].output).toBe("found [REDACTED GITHUB TOKEN]");
+ });
+
+ it("preserves startup diagnostics even when no execution messages exist", () => {
+ const task = AgentTaskSchema.parse({
+ id: "task-1", status: "failed", failure_reason: "environment_prepare_failed",
+ error: "prepare execution environment: permission denied",
+ });
+
+ expect(buildRunTranscript([])).toEqual([]);
+ expect(getRunDiagnostics(task)).toEqual({
+ reasonKey: "failure_reason.environment_prepare_failed",
+ error: "prepare execution environment: permission denied",
+ });
+ });
+
+ it("redacts raw diagnostics and safely labels unknown failure reasons", () => {
+ expect(getRunDiagnostics(AgentTaskSchema.parse({
+ id: "task-1", status: "failed", failure_reason: "future_reason",
+ error: "Authorization: Bearer fake-value",
+ }))).toEqual({ reasonKey: "failure_reason.default", error: "Authorization: Bearer [REDACTED]" });
+ expect(getRunDiagnostics(AgentTaskSchema.parse({ id: "task-1", status: "completed" }))).toBeNull();
+ });
+});
+
+describe("run cancellation after schema parsing", () => {
+ it.each(["queued", "deferred", "dispatched", "waiting_local_directory", "running"])(
+ "keeps %s cancellable", (status) => {
+ expect(isCancellableRunStatus(AgentTaskSchema.parse({ id: "task-1", status }).status)).toBe(true);
+ },
+ );
+ it.each(["completed", "failed", "cancelled"])("does not cancel %s runs", (status) => {
+ expect(isCancellableRunStatus(AgentTaskSchema.parse({ id: "task-1", status }).status)).toBe(false);
+ });
+});
diff --git a/apps/mobile/lib/run-transcript.ts b/apps/mobile/lib/run-transcript.ts
new file mode 100644
index 0000000000..2092f23f58
--- /dev/null
+++ b/apps/mobile/lib/run-transcript.ts
@@ -0,0 +1,106 @@
+import type { AgentTask, TaskMessagePayload } from "@multica/core/types";
+import { redactSecrets } from "@multica/core/security/redact-secrets";
+import { failureReasonKey } from "./failure-reason-label";
+
+const UUID_PATTERN =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+export const RUN_TRANSCRIPT_PATHNAME =
+ "/[workspace]/issue/[id]/run/[taskId]" as const;
+
+export function runTranscriptRoute(
+ workspace: string,
+ issueId: string,
+ taskId: string,
+) {
+ return {
+ pathname: RUN_TRANSCRIPT_PATHNAME,
+ params: { workspace, id: issueId, taskId },
+ } as const;
+}
+
+export function isRunTranscriptTaskId(taskId: unknown): taskId is string {
+ return typeof taskId === "string" && UUID_PATTERN.test(taskId);
+}
+
+export function isCancellableRunStatus(status: AgentTask["status"]): boolean {
+ return (
+ status === "queued" ||
+ status === "deferred" ||
+ status === "dispatched" ||
+ status === "waiting_local_directory" ||
+ status === "running"
+ );
+}
+
+/** Match web transcript semantics without importing its UI or query layer. */
+export function buildRunTranscript(
+ messages: readonly TaskMessagePayload[],
+): TaskMessagePayload[] {
+ const items: TaskMessagePayload[] = [];
+ for (const message of [...messages].sort((a, b) => a.seq - b.seq)) {
+ const previous = items[items.length - 1];
+ if (
+ previous &&
+ (message.type === "text" || message.type === "thinking") &&
+ previous.type === message.type
+ ) {
+ previous.content = `${previous.content ?? ""}${message.content ?? ""}`;
+ previous.created_at = message.created_at ?? previous.created_at;
+ } else {
+ items.push({ ...message });
+ }
+ }
+ // Redact after coalescing: a credential may span two daemon flushes.
+ return items.map((item) => ({
+ ...item,
+ content: item.content ? redactSecrets(item.content) : item.content,
+ output: item.output ? redactSecrets(item.output) : item.output,
+ }));
+}
+
+export type RunTranscriptEntry =
+ | { kind: "message"; task_id: string; seq: number; message: TaskMessagePayload }
+ | { kind: "tool"; task_id: string; seq: number; call?: TaskMessagePayload; result?: TaskMessagePayload };
+
+/** Pair by opaque identity, never by completion order or a shared tool name. */
+export function buildRunTranscriptEntries(messages: readonly TaskMessagePayload[]): RunTranscriptEntry[] {
+ const entries: RunTranscriptEntry[] = [];
+ const pending = new Map<string, Extract<RunTranscriptEntry, { kind: "tool" }>>();
+
+ for (const message of buildRunTranscript(messages)) {
+ // Missing IDs stay unpaired rather than guessing which parallel call won.
+ const key = message.call_id ? `${message.task_id}:${message.call_id}` : null;
+ if (message.type === "tool_use") {
+ const entry = { kind: "tool" as const, task_id: message.task_id, seq: message.seq, call: message };
+ entries.push(entry);
+ if (key) pending.set(key, entry);
+ } else if (message.type === "tool_result") {
+ const call = key ? pending.get(key) : undefined;
+ if (call && key) {
+ call.result = message;
+ pending.delete(key);
+ } else {
+ entries.push({ kind: "tool", task_id: message.task_id, seq: message.seq, result: message });
+ }
+ } else {
+ entries.push({ kind: "message", task_id: message.task_id, seq: message.seq, message });
+ }
+ }
+ return entries;
+}
+
+export function runToolContext(call: TaskMessagePayload | undefined): string | undefined {
+ const input = call?.input;
+ const context = [input?.command, input?.file_path, input?.path, input?.pattern, input?.query]
+ .find((value): value is string => typeof value === "string" && value.length > 0);
+ return context ? redactSecrets(context) : undefined;
+}
+
+export function getRunDiagnostics(
+ task: Pick<AgentTask, "status" | "failure_reason" | "error">,
+) {
+ const reasonKey = task.status === "failed" ? failureReasonKey(task.failure_reason) : null;
+ const error = task.error?.trim() ? redactSecrets(task.error) : null;
+ return reasonKey || error ? { reasonKey, error } : null;
+}
diff --git a/apps/mobile/locales/en/issues.json b/apps/mobile/locales/en/issues.json
index b557a22c88..81cf811823 100644
--- a/apps/mobile/locales/en/issues.json
+++ b/apps/mobile/locales/en/issues.json
@@ -241,6 +241,25 @@
"active": "Active",
"past": "Past",
"title": "Agent Runs",
+ "open_transcript": "Open execution record for {{summary}}",
+ "transcript": {
+ "title": "Execution record",
+ "loading": "Loading execution record...",
+ "load_error": "Couldn't load this execution record.",
+ "retry": "Try again",
+ "missing": "This run is unavailable or no longer exists.",
+ "empty": "No execution record was saved for this run.",
+ "thinking": "Thinking",
+ "tool_call": "Tool call",
+ "tool_output": "Tool output",
+ "output": "Output",
+ "error": "Error",
+ "unknown_tool": "Unknown tool",
+ "truncated": "This output was truncated when saved.",
+ "diagnostics": "Technical details",
+ "show_full_output": "Show full output",
+ "show_less": "Show less"
+ },
"status": {
"queued": "Queued",
"deferred": "Deferred",
diff --git a/apps/mobile/locales/en/navigation.json b/apps/mobile/locales/en/navigation.json
index 8efe99f692..4c582d3acd 100644
--- a/apps/mobile/locales/en/navigation.json
+++ b/apps/mobile/locales/en/navigation.json
@@ -31,6 +31,7 @@
"edit_issue": "Edit issue",
"edit_project": "Edit project",
"runs": "Runs",
+ "execution_record": "Execution record",
"add_resource": "Add resource",
"recent": "Recent"
}
diff --git a/apps/mobile/locales/zh-Hans/issues.json b/apps/mobile/locales/zh-Hans/issues.json
index 9c95b11931..950e793557 100644
--- a/apps/mobile/locales/zh-Hans/issues.json
+++ b/apps/mobile/locales/zh-Hans/issues.json
@@ -237,6 +237,25 @@
"active": "进行中",
"past": "历史",
"title": "智能体运行",
+ "open_transcript": "打开{{summary}}的执行记录",
+ "transcript": {
+ "title": "执行记录",
+ "loading": "正在加载执行记录...",
+ "load_error": "无法加载此执行记录。",
+ "retry": "重试",
+ "missing": "此运行不可用或已不存在。",
+ "empty": "此运行没有保存执行记录。",
+ "thinking": "思考",
+ "tool_call": "工具调用",
+ "tool_output": "工具输出",
+ "output": "输出",
+ "error": "错误",
+ "unknown_tool": "未知工具",
+ "truncated": "此输出在保存时已截断。",
+ "diagnostics": "技术详情",
+ "show_full_output": "展开完整输出",
+ "show_less": "收起"
+ },
"status": {
"queued": "排队中",
"deferred": "已延后",
diff --git a/apps/mobile/locales/zh-Hans/navigation.json b/apps/mobile/locales/zh-Hans/navigation.json
index 43b70daf05..0259dc8f7f 100644
--- a/apps/mobile/locales/zh-Hans/navigation.json
+++ b/apps/mobile/locales/zh-Hans/navigation.json
@@ -31,6 +31,7 @@
"edit_issue": "编辑任务",
"edit_project": "编辑项目",
"runs": "运行",
+ "execution_record": "执行记录",
"add_resource": "添加资源",
"recent": "最近"
}
diff --git a/apps/mobile/locales/zh-Hant/issues.json b/apps/mobile/locales/zh-Hant/issues.json
index 05c20535e3..aa56e8d3f9 100644
--- a/apps/mobile/locales/zh-Hant/issues.json
+++ b/apps/mobile/locales/zh-Hant/issues.json
@@ -237,6 +237,25 @@
"active": "進行中",
"past": "歷史",
"title": "智慧體執行",
+ "open_transcript": "開啟{{summary}}的執行記錄",
+ "transcript": {
+ "title": "執行記錄",
+ "loading": "正在載入執行記錄...",
+ "load_error": "無法載入此執行記錄。",
+ "retry": "重試",
+ "missing": "此執行不可用或已不存在。",
+ "empty": "此執行沒有儲存執行記錄。",
+ "thinking": "思考",
+ "tool_call": "工具呼叫",
+ "tool_output": "工具輸出",
+ "output": "輸出",
+ "error": "錯誤",
+ "unknown_tool": "未知工具",
+ "truncated": "此輸出在儲存時已截斷。",
+ "diagnostics": "技術詳情",
+ "show_full_output": "展開完整輸出",
+ "show_less": "收起"
+ },
"status": {
"queued": "排隊中",
"deferred": "已延後",
diff --git a/apps/mobile/locales/zh-Hant/navigation.json b/apps/mobile/locales/zh-Hant/navigation.json
index db1e9e6120..5f610247a6 100644
--- a/apps/mobile/locales/zh-Hant/navigation.json
+++ b/apps/mobile/locales/zh-Hant/navigation.json
@@ -31,6 +31,7 @@
"edit_issue": "編輯任務",
"edit_project": "編輯專案",
"runs": "執行",
+ "execution_record": "執行記錄",
"add_resource": "新增資源",
"recent": "最近"
}
diff --git a/packages/core/package.json b/packages/core/package.json
index 736e4d5e09..b0e5b35483 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -152,6 +152,7 @@
"./provider": "./provider.tsx",
"./logger": "./logger.ts",
"./utils": "./utils.ts",
+ "./security/redact-secrets": "./security/redact-secrets.ts",
"./constants/*": "./constants/*.ts",
"./feature-flags": "./feature-flags/index.ts",
"./platform": "./platform/index.ts",
diff --git a/packages/views/common/task-transcript/redact.test.ts b/packages/core/security/redact-secrets.test.ts
similarity index 98%
rename from packages/views/common/task-transcript/redact.test.ts
rename to packages/core/security/redact-secrets.test.ts
index 9f7a9a63ce..0d5ff8e718 100644
--- a/packages/views/common/task-transcript/redact.test.ts
+++ b/packages/core/security/redact-secrets.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { describe, it, expect } from "vitest";
-import { redactSecrets } from "./redact";
+import { redactSecrets } from "./redact-secrets";
describe("redactSecrets", () => {
it("redacts AWS access key", () => {
diff --git a/packages/core/security/redact-secrets.ts b/packages/core/security/redact-secrets.ts
new file mode 100644
index 0000000000..0011f45291
--- /dev/null
+++ b/packages/core/security/redact-secrets.ts
@@ -0,0 +1,41 @@
+/**
+ * Client-side fallback for redacting sensitive information in agent output.
+ * The server performs primary redaction; this is a safety net for display.
+ */
+
+const patterns: { re: RegExp; replacement: string }[] = [
+ // AWS access key IDs
+ { re: /\bAKIA[0-9A-Z]{16}\b/g, replacement: "[REDACTED AWS KEY]" },
+ // AWS secret access keys
+ { re: /(?:aws_secret_access_key|secret_?access_?key)\s*[=:]\s*[A-Za-z0-9/+=]{40}/gi, replacement: "[REDACTED AWS SECRET]" },
+ // PEM private keys
+ { re: /-----BEGIN[A-Z\s]*PRIVATE KEY-----[\s\S]*?-----END[A-Z\s]*PRIVATE KEY-----/g, replacement: "[REDACTED PRIVATE KEY]" },
+ // GitHub OAuth / classic tokens (ghp_/gho_/ghu_/ghs_/ghr_)
+ { re: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,255}\b/g, replacement: "[REDACTED GITHUB TOKEN]" },
+ // GitHub fine-grained PATs (github_pat_…, recommended since 2022)
+ { re: /\bgithub_pat_[A-Za-z0-9_]{20,255}\b/g, replacement: "[REDACTED GITHUB TOKEN]" },
+ // Google API keys (AIza…, e.g. Gemini / Maps / Firebase)
+ { re: /\bAIza[0-9A-Za-z_-]{35}([^0-9A-Za-z_-]|$)/g, replacement: "[REDACTED GOOGLE API KEY]$1" },
+ // GitLab personal access tokens
+ { re: /\bglpat-[A-Za-z0-9_-]{20,}\b/g, replacement: "[REDACTED GITLAB TOKEN]" },
+ // OpenAI / Anthropic API keys
+ { re: /\bsk-[A-Za-z0-9_-]{20,}\b/g, replacement: "[REDACTED API KEY]" },
+ // Slack tokens
+ { re: /\bxox[bporas]-[A-Za-z0-9-]{10,}\b/g, replacement: "[REDACTED SLACK TOKEN]" },
+ // JWT tokens
+ { re: /\bey[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, replacement: "[REDACTED JWT]" },
+ // Bearer tokens
+ { re: /\bBearer\s+[A-Za-z0-9\-._~+/]+=*/gi, replacement: "Bearer [REDACTED]" },
+ // Connection strings with embedded passwords
+ { re: /(?:postgres|mysql|mongodb|redis|amqp)(?:ql)?:\/\/[^:\s]+:[^@\s]+@/gi, replacement: "[REDACTED CONNECTION STRING]@" },
+ // Generic key=value secret env vars
+ { re: /(?:API_KEY|API_SECRET|SECRET_KEY|SECRET|ACCESS_TOKEN|AUTH_TOKEN|PRIVATE_KEY|DATABASE_URL|DB_PASSWORD|DB_URL|REDIS_URL|PASSWORD|TOKEN)\s*[=:]\s*\S+/gi, replacement: "[REDACTED CREDENTIAL]" },
+];
+
+export function redactSecrets(text: string): string {
+ let result = text;
+ for (const { re, replacement } of patterns) {
+ result = result.replace(re, replacement);
+ }
+ return result;
+}
diff --git a/packages/views/common/task-transcript/redact.ts b/packages/views/common/task-transcript/redact.ts
index 0011f45291..4e2334040d 100644
--- a/packages/views/common/task-transcript/redact.ts
+++ b/packages/views/common/task-transcript/redact.ts
@@ -1,41 +1 @@
-/**
- * Client-side fallback for redacting sensitive information in agent output.
- * The server performs primary redaction; this is a safety net for display.
- */
-
-const patterns: { re: RegExp; replacement: string }[] = [
- // AWS access key IDs
- { re: /\bAKIA[0-9A-Z]{16}\b/g, replacement: "[REDACTED AWS KEY]" },
- // AWS secret access keys
- { re: /(?:aws_secret_access_key|secret_?access_?key)\s*[=:]\s*[A-Za-z0-9/+=]{40}/gi, replacement: "[REDACTED AWS SECRET]" },
- // PEM private keys
- { re: /-----BEGIN[A-Z\s]*PRIVATE KEY-----[\s\S]*?-----END[A-Z\s]*PRIVATE KEY-----/g, replacement: "[REDACTED PRIVATE KEY]" },
- // GitHub OAuth / classic tokens (ghp_/gho_/ghu_/ghs_/ghr_)
- { re: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,255}\b/g, replacement: "[REDACTED GITHUB TOKEN]" },
- // GitHub fine-grained PATs (github_pat_…, recommended since 2022)
- { re: /\bgithub_pat_[A-Za-z0-9_]{20,255}\b/g, replacement: "[REDACTED GITHUB TOKEN]" },
- // Google API keys (AIza…, e.g. Gemini / Maps / Firebase)
- { re: /\bAIza[0-9A-Za-z_-]{35}([^0-9A-Za-z_-]|$)/g, replacement: "[REDACTED GOOGLE API KEY]$1" },
- // GitLab personal access tokens
- { re: /\bglpat-[A-Za-z0-9_-]{20,}\b/g, replacement: "[REDACTED GITLAB TOKEN]" },
- // OpenAI / Anthropic API keys
- { re: /\bsk-[A-Za-z0-9_-]{20,}\b/g, replacement: "[REDACTED API KEY]" },
- // Slack tokens
- { re: /\bxox[bporas]-[A-Za-z0-9-]{10,}\b/g, replacement: "[REDACTED SLACK TOKEN]" },
- // JWT tokens
- { re: /\bey[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, replacement: "[REDACTED JWT]" },
- // Bearer tokens
- { re: /\bBearer\s+[A-Za-z0-9\-._~+/]+=*/gi, replacement: "Bearer [REDACTED]" },
- // Connection strings with embedded passwords
- { re: /(?:postgres|mysql|mongodb|redis|amqp)(?:ql)?:\/\/[^:\s]+:[^@\s]+@/gi, replacement: "[REDACTED CONNECTION STRING]@" },
- // Generic key=value secret env vars
- { re: /(?:API_KEY|API_SECRET|SECRET_KEY|SECRET|ACCESS_TOKEN|AUTH_TOKEN|PRIVATE_KEY|DATABASE_URL|DB_PASSWORD|DB_URL|REDIS_URL|PASSWORD|TOKEN)\s*[=:]\s*\S+/gi, replacement: "[REDACTED CREDENTIAL]" },
-];
-
-export function redactSecrets(text: string): string {
- let result = text;
- for (const { re, replacement } of patterns) {
- result = result.replace(re, replacement);
- }
- return result;
-}
+export { redactSecrets } from "@multica/core/security/redact-secrets";