diff --git a/apps/mobile/src/features/threads/ThreadActivityInspector.tsx b/apps/mobile/src/features/threads/ThreadActivityInspector.tsx new file mode 100644 index 0000000000..2fe661319b --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadActivityInspector.tsx @@ -0,0 +1,199 @@ +import * as Haptics from "expo-haptics"; +import { SymbolView } from "expo-symbols"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { useRouter } from "expo-router"; +import { useMemo, useState } from "react"; +import { Linking, Pressable, ScrollView, type ColorValue, View } from "react-native"; + +import { AppText as Text } from "../../components/AppText"; +import type { ThreadFeedActivity } from "../../lib/threadActivity"; +import { buildThreadActivityInspector } from "../../lib/threadActivityInspector"; +import { buildThreadFilesNavigation } from "../../lib/routes"; +import { resolveWorkspaceRelativeFilePath } from "../files/filePath"; +import { threadEnvironment } from "../../state/threads"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { useV2ItemSupport } from "../../state/v2-item-support"; + +export function ThreadActivityInspector(props: { + readonly activity: ThreadFeedActivity; + readonly environmentId: EnvironmentId; + readonly iconColor: ColorValue; + readonly workspaceRoot?: string | null; +}) { + const router = useRouter(); + const row = props.activity.projectedItem; + const support = useV2ItemSupport({ + environmentId: props.environmentId, + sourceThreadId: row.sourceThreadId, + sourceItemId: row.sourceItemId, + }); + const model = useMemo( + () => buildThreadActivityInspector(props.activity, support), + [props.activity, support], + ); + const revertCheckpoint = useAtomCommand(threadEnvironment.revertCheckpoint, { + label: "checkpoint rollback", + reportFailure: true, + }); + const [rollingBack, setRollingBack] = useState(false); + + return ( + + + {model.fields.map((field) => ( + + + {field.label} + + + {field.value} + + + ))} + + + {model.blocks.map((block) => ( + + + {block.label} + + + + {block.value} + + + + ))} + + {model.fileLinks.length > 0 ? ( + + + Files + + {model.fileLinks.map((link) => { + const relativePath = + resolveWorkspaceRelativeFilePath(props.workspaceRoot, link.path) ?? + (link.path.startsWith("/") ? null : link.path); + return ( + { + if (!relativePath) return; + void Haptics.selectionAsync(); + router.push( + buildThreadFilesNavigation( + { environmentId: props.environmentId, threadId: row.sourceThreadId }, + relativePath, + link.line, + ), + ); + }} + className="min-h-9 flex-row items-center gap-2 rounded-md border border-neutral-300/50 px-2.5 py-1.5 dark:border-white/[0.1]" + > + + + {link.label} + + + ); + })} + + ) : null} + + {model.webLinks.length > 0 ? ( + + + Sources + + {model.webLinks.map((link) => ( + void Linking.openURL(link.url)} + className="min-h-9 flex-row items-center gap-2 rounded-md border border-neutral-300/50 px-2.5 py-1.5 dark:border-white/[0.1]" + > + + + {link.label} + + + ))} + + ) : null} + + {model.rollbackTarget ? ( + { + setRollingBack(true); + void Haptics.selectionAsync(); + void revertCheckpoint({ + environmentId: props.environmentId, + input: { + threadId: model.rollbackTarget!.threadId, + checkpointId: model.rollbackTarget!.checkpointId, + scopeId: model.rollbackTarget!.scopeId, + }, + }).finally(() => setRollingBack(false)); + }} + className="min-h-10 flex-row items-center justify-center gap-2 rounded-lg border border-neutral-300/60 px-3 py-2 dark:border-white/[0.12]" + > + + + {rollingBack ? "Rolling back…" : "Roll back to checkpoint"} + + + ) : null} + + + + Structured details + + + + {model.structuredDetails} + + + + + ); +} diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 40d53b34f6..820fdc7143 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -818,7 +818,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe function renderFeedEntry( info: { item: ThreadFeedEntry; index: number }, - props: Pick & { + props: Pick & { readonly copiedRowId: string | null; readonly expandedWorkRows: Record; readonly terminalAssistantMessageIds: ReadonlySet; @@ -1009,10 +1009,13 @@ function renderFeedEntry( ); } @@ -1742,6 +1745,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { reviewCommentBubbleWidth, userBubbleMaxWidth, skills: props.skills, + workspaceRoot: props.workspaceRoot, }), [ copiedRowId, @@ -1762,6 +1766,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { onToggleWorkRow, props.environmentId, props.skills, + props.workspaceRoot, ], ); diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index 529adac1db..4a634f64df 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -1,13 +1,13 @@ import * as Haptics from "expo-haptics"; -import { type AppSymbolName, SymbolView } from "../../components/AppSymbol"; -import { LayoutAnimation, Pressable, ScrollView, useColorScheme, View } from "react-native"; +import { SymbolView, type SFSymbol } from "expo-symbols"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { LayoutAnimation, Pressable, useColorScheme, View } from "react-native"; import { AppText as Text } from "../../components/AppText"; import { scaledTypographyLineHeight } from "../../lib/appearancePreferences"; import { cn } from "../../lib/cn"; import type { ThreadFeedActivity } from "../../lib/threadActivity"; -import { MOBILE_TYPOGRAPHY } from "../../lib/typography"; -import Animated, { FadeIn } from "react-native-reanimated"; +import { ThreadActivityInspector } from "./ThreadActivityInspector"; const WORK_LOG_LAYOUT_ANIMATION = { duration: 180, @@ -122,17 +122,17 @@ export function collapsedWorkLogHeight( export function ThreadWorkLog(props: { readonly activities: ReadonlyArray; readonly copiedRowId: string | null; + readonly environmentId: EnvironmentId; + readonly expanded: boolean; readonly expandedRows: Readonly>; readonly iconSubtleColor: import("react-native").ColorValue; readonly onCopyRow: (rowId: string, value: string) => void; readonly onToggleRow: (rowId: string) => void; + readonly workspaceRoot?: string | null; }) { const colorScheme = useColorScheme(); const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)"; - const rows = visibleWorkLogActivities(props.activities).map((activity) => ({ - ...activity, - detail: compactActivityDetail(activity.detail), - })); + const rows = props.activities; if (rows.length === 0) { return null; @@ -151,9 +151,9 @@ export function ThreadWorkLog(props: { {rows.map((row) => { const expanded = props.expandedRows[row.id] ?? false; - const canExpand = row.canExpand; - const fullDetail = expanded ? row.getFullDetail() : null; - const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary; + const canExpand = row.fullDetail !== null; + const detail = compactActivityDetail(row.detail); + const displayText = detail ? `${row.summary} ${detail}` : row.summary; const iconIsDestructive = row.icon === "alert" || row.icon === "warning"; return ( @@ -203,8 +203,8 @@ export function ThreadWorkLog(props: { > {row.summary} - {row.detail ? ( - {row.detail} + {detail ? ( + {detail} ) : null} @@ -248,22 +248,14 @@ export function ThreadWorkLog(props: { - {fullDetail ? ( - - - - {fullDetail} - - + {expanded && row.fullDetail ? ( + + ) : null} diff --git a/apps/mobile/src/lib/threadActivityInspector.test.ts b/apps/mobile/src/lib/threadActivityInspector.test.ts new file mode 100644 index 0000000000..2f773a1125 --- /dev/null +++ b/apps/mobile/src/lib/threadActivityInspector.test.ts @@ -0,0 +1,228 @@ +import { EMPTY_V2_ITEM_SUPPORT } from "@t3tools/client-runtime/state/item-support"; +import { + CheckpointId, + CheckpointScopeId, + NodeId, + ProviderDriverKind, + ProviderInstanceId, + RunId, + ThreadId, + TurnItemId, + type OrchestrationV2ProjectedTurnItem, + type OrchestrationV2TurnItem, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; + +import { buildThreadFeed, type ThreadFeedActivity } from "./threadActivity"; +import { buildThreadActivityInspector } from "./threadActivityInspector"; + +const threadId = ThreadId.make("thread-1"); +const sourceThreadId = ThreadId.make("thread-source"); +const runId = RunId.make("run-1"); +const nodeId = NodeId.make("node-1"); +const startedAt = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); +const completedAt = DateTime.makeUnsafe("2026-06-20T00:00:02.000Z"); + +function itemBase(id: string) { + return { + id: TurnItemId.make(id), + threadId, + runId, + nodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed" as const, + title: null, + startedAt, + completedAt, + updatedAt: completedAt, + }; +} + +function activityFor(item: OrchestrationV2TurnItem): ThreadFeedActivity { + const row: OrchestrationV2ProjectedTurnItem = { + position: 0, + visibility: "inherited", + sourceThreadId, + sourceItemId: item.id, + item, + }; + const group = buildThreadFeed([row])[0]; + if (group?.type !== "activity-group" || !group.activities[0]) { + throw new Error("Expected an activity group"); + } + return group.activities[0]; +} + +describe("buildThreadActivityInspector", () => { + it("presents command lifecycle, execution support, output, and exit state", () => { + const item: OrchestrationV2TurnItem = { + ...itemBase("command"), + type: "command_execution", + input: "vp check", + output: "all checks passed", + exitCode: 0, + }; + const support = { + ...EMPTY_V2_ITEM_SUPPORT, + item, + run: { status: "completed" } as never, + attempts: [ + { + id: "attempt-1", + attemptOrdinal: 1, + status: "superseded", + reason: "initial", + }, + { + id: "attempt-2", + attemptOrdinal: 2, + status: "completed", + reason: "steering_restart", + }, + ] as never, + node: { kind: "tool_call", status: "completed" } as never, + providerSession: { + status: "ready", + model: "gpt-5.4", + cwd: "/workspace/project", + } as never, + }; + + const model = buildThreadActivityInspector(activityFor(item), support); + expect(model.fields).toEqual( + expect.arrayContaining([ + { label: "Duration", value: "2.0s" }, + { label: "Run", value: "completed" }, + { label: "Working directory", value: "/workspace/project" }, + { label: "Visibility", value: "inherited" }, + ]), + ); + expect(model.blocks).toEqual( + expect.arrayContaining([ + expect.objectContaining({ label: "Command", value: "vp check" }), + expect.objectContaining({ label: "Output", value: "all checks passed" }), + expect.objectContaining({ label: "Exit", value: "Process exited with code 0" }), + expect.objectContaining({ label: "Attempt history" }), + ]), + ); + }); + + it("exposes file and web result provenance plus dynamic structured data", () => { + const fileSearch: OrchestrationV2TurnItem = { + ...itemBase("file-search"), + type: "file_search", + pattern: "resolveSession", + results: [{ fileName: "src/session.ts", line: 42, preview: "function resolveSession()" }], + }; + const fileModel = buildThreadActivityInspector(activityFor(fileSearch), EMPTY_V2_ITEM_SUPPORT); + expect(fileModel.fileLinks).toEqual([ + { + label: "src/session.ts — function resolveSession()", + path: "src/session.ts", + line: 42, + }, + ]); + + const webSearch: OrchestrationV2TurnItem = { + ...itemBase("web-search"), + type: "web_search", + patterns: ["Effect Schema docs"], + results: [ + { title: "Schema", url: "https://effect.website/docs/schema", snippet: "Typed schemas" }, + ], + }; + const webModel = buildThreadActivityInspector(activityFor(webSearch), EMPTY_V2_ITEM_SUPPORT); + expect(webModel.webLinks).toEqual([ + { label: "Schema", url: "https://effect.website/docs/schema" }, + ]); + expect(webModel.blocks).toEqual( + expect.arrayContaining([ + expect.objectContaining({ label: "Schema", value: "Typed schemas" }), + ]), + ); + + const dynamicTool: OrchestrationV2TurnItem = { + ...itemBase("dynamic"), + type: "dynamic_tool", + toolName: "custom", + input: { nested: { value: 1 } }, + output: { ok: true }, + }; + const dynamicModel = buildThreadActivityInspector( + activityFor(dynamicTool), + EMPTY_V2_ITEM_SUPPORT, + ); + expect(dynamicModel.blocks).toEqual( + expect.arrayContaining([ + expect.objectContaining({ label: "Input", value: expect.stringContaining('"nested"') }), + expect.objectContaining({ label: "Output", value: expect.stringContaining('"ok"') }), + ]), + ); + expect(dynamicModel.structuredDetails).toContain('"type": "dynamic_tool"'); + }); + + it("enables rollback only for the matching ready checkpoint", () => { + const checkpointId = CheckpointId.make("checkpoint-1"); + const scopeId = CheckpointScopeId.make("scope-1"); + const item: OrchestrationV2TurnItem = { + ...itemBase("checkpoint"), + type: "checkpoint", + checkpointId, + scopeId, + files: [{ path: "src/main.ts", kind: "modified", additions: 2, deletions: 1 }], + }; + const checkpoint = { id: checkpointId, scopeId, status: "ready" } as never; + const model = buildThreadActivityInspector(activityFor(item), { + ...EMPTY_V2_ITEM_SUPPORT, + item, + checkpoint, + }); + + expect(model.canRollback).toBe(true); + expect(model.rollbackTarget).toEqual({ + threadId: sourceThreadId, + checkpointId, + scopeId, + }); + }); + + it("prefers live subagent progress from supporting state", () => { + const item: OrchestrationV2TurnItem = { + ...itemBase("subagent"), + type: "subagent", + subagentId: nodeId, + origin: "provider_native", + driver: ProviderDriverKind.make("claude"), + providerInstanceId: ProviderInstanceId.make("claude"), + childThreadId: null, + prompt: "Audit the reducer", + progress: "Starting", + result: null, + }; + const model = buildThreadActivityInspector(activityFor(item), { + ...EMPTY_V2_ITEM_SUPPORT, + item, + subagent: { + origin: "provider_native", + status: "running", + progress: "Reading projection tests", + result: null, + } as never, + }); + + expect(model.fields).toContainEqual({ + label: "Delegated task", + value: "provider native · running", + }); + expect(model.blocks).toContainEqual({ + label: "Progress", + value: "Reading projection tests", + monospaced: false, + }); + }); +}); diff --git a/apps/mobile/src/lib/threadActivityInspector.ts b/apps/mobile/src/lib/threadActivityInspector.ts new file mode 100644 index 0000000000..72d02e3cde --- /dev/null +++ b/apps/mobile/src/lib/threadActivityInspector.ts @@ -0,0 +1,304 @@ +import type { V2ItemSupport } from "@t3tools/client-runtime/state/item-support"; +import type { ThreadId } from "@t3tools/contracts"; +import { formatDuration } from "@t3tools/shared/orchestrationTiming"; +import * as DateTime from "effect/DateTime"; + +import type { ThreadFeedActivity } from "./threadActivity"; + +export interface ThreadActivityInspectorField { + readonly label: string; + readonly value: string; +} + +export interface ThreadActivityInspectorBlock { + readonly label: string; + readonly value: string; + readonly monospaced: boolean; +} + +export interface ThreadActivityFileLink { + readonly label: string; + readonly path: string; + readonly line?: number; +} + +export interface ThreadActivityWebLink { + readonly label: string; + readonly url: string; +} + +export interface ThreadActivityInspectorModel { + readonly fields: ReadonlyArray; + readonly blocks: ReadonlyArray; + readonly fileLinks: ReadonlyArray; + readonly webLinks: ReadonlyArray; + readonly canRollback: boolean; + readonly rollbackTarget: { + readonly threadId: ThreadId; + readonly checkpointId: string; + readonly scopeId: string; + } | null; + readonly structuredDetails: string; +} + +function formatStructured(value: unknown): string { + if (typeof value === "string") return value; + try { + return JSON.stringify(value, null, 2) ?? String(value); + } catch { + return String(value); + } +} + +function durationLabel( + startedAt: DateTime.Utc | null, + completedAt: DateTime.Utc | null, +): string | null { + if (startedAt === null) return null; + const start = DateTime.toEpochMillis(startedAt); + const end = completedAt === null ? Date.now() : DateTime.toEpochMillis(completedAt); + return formatDuration(Math.max(0, end - start)); +} + +function addBlock( + blocks: ThreadActivityInspectorBlock[], + label: string, + value: unknown, + monospaced = true, +): void { + if (value === undefined || value === null || value === "") return; + blocks.push({ label, value: formatStructured(value), monospaced }); +} + +export function buildThreadActivityInspector( + activity: ThreadFeedActivity, + support: V2ItemSupport, +): ThreadActivityInspectorModel { + const row = activity.projectedItem; + const item = row.item; + const fields: ThreadActivityInspectorField[] = [ + { label: "Item", value: item.type.replaceAll("_", " ") }, + { label: "Status", value: item.status.replaceAll("_", " ") }, + ]; + const duration = durationLabel(item.startedAt, item.completedAt); + if (duration) fields.push({ label: "Duration", value: duration }); + if (row.visibility !== "local") fields.push({ label: "Visibility", value: row.visibility }); + if (support.run) fields.push({ label: "Run", value: support.run.status }); + + const latestAttempt = support.attempts.at(-1); + if (latestAttempt) { + fields.push({ + label: "Attempt", + value: `${latestAttempt.attemptOrdinal} · ${latestAttempt.status} · ${latestAttempt.reason.replaceAll("_", " ")}`, + }); + } + if (support.node) { + fields.push({ + label: "Node", + value: `${support.node.kind.replaceAll("_", " ")} · ${support.node.status}`, + }); + } + if (support.providerThread) { + fields.push({ + label: "Provider thread", + value: `${support.providerThread.providerInstanceId} · ${support.providerThread.status}`, + }); + } + if (support.providerTurn) { + fields.push({ label: "Provider turn", value: support.providerTurn.status }); + } + if (support.providerSession) { + fields.push({ + label: "Session", + value: `${support.providerSession.status} · ${support.providerSession.model ?? "default model"}`, + }); + fields.push({ label: "Working directory", value: support.providerSession.cwd }); + } + if (support.runtimeRequest) { + fields.push({ + label: "Request", + value: `${support.runtimeRequest.status} · ${support.runtimeRequest.responseCapability.type.replaceAll("_", " ")}`, + }); + } + + const blocks: ThreadActivityInspectorBlock[] = []; + const fileLinks: ThreadActivityFileLink[] = []; + const webLinks: ThreadActivityWebLink[] = []; + + if (support.attempts.length > 1) { + addBlock( + blocks, + "Attempt history", + support.attempts + .map( + (attempt) => + `Attempt ${attempt.attemptOrdinal} · ${attempt.status} · ${attempt.reason.replaceAll("_", " ")}`, + ) + .join("\n"), + ); + } + + switch (item.type) { + case "reasoning": + addBlock(blocks, "Reasoning", item.text, false); + break; + case "command_execution": + addBlock(blocks, "Command", item.input); + addBlock(blocks, "Output", item.output); + if (item.exitCode !== undefined) { + addBlock(blocks, "Exit", `Process exited with code ${item.exitCode}`); + } + break; + case "file_change": + fileLinks.push({ label: item.fileName, path: item.fileName }); + if (item.additions !== undefined || item.deletions !== undefined) { + fields.push({ + label: "Changes", + value: `+${item.additions ?? 0} −${item.deletions ?? 0}`, + }); + } + addBlock(blocks, "Patch", item.diffStr); + addBlock(blocks, "Before", item.oldStr); + addBlock(blocks, "After", item.newStr); + break; + case "file_search": + addBlock(blocks, "Query", item.pattern); + for (const result of item.results ?? []) { + fileLinks.push({ + label: result.preview ? `${result.fileName} — ${result.preview}` : result.fileName, + path: result.fileName, + ...(result.line === undefined ? {} : { line: result.line }), + }); + } + break; + case "web_search": + addBlock(blocks, "Queries", item.patterns?.join("\n")); + for (const result of item.results ?? []) { + if (result.url) { + webLinks.push({ + label: result.title ?? result.url, + url: result.url, + }); + } + if (result.snippet) + addBlock(blocks, result.title ?? "Search result", result.snippet, false); + } + break; + case "dynamic_tool": + addBlock(blocks, "Input", item.input); + addBlock(blocks, "Output", item.output); + break; + case "approval_request": + addBlock(blocks, "Prompt", item.prompt, false); + break; + case "user_input_request": + addBlock( + blocks, + "Questions", + item.questions.map((question) => question.question).join("\n"), + false, + ); + break; + case "checkpoint": + addBlock( + blocks, + "Files", + item.files + .map((file) => `${file.path} +${file.additions} −${file.deletions} ${file.kind}`) + .join("\n"), + ); + break; + case "subagent": + addBlock(blocks, "Prompt", item.prompt, false); + addBlock(blocks, "Progress", support.subagent?.progress ?? item.progress, false); + addBlock(blocks, "Result", support.subagent?.result ?? item.result, false); + if (support.subagent) { + fields.push({ + label: "Delegated task", + value: `${support.subagent.origin.replaceAll("_", " ")} · ${support.subagent.status}`, + }); + } + break; + case "handoff": + addBlock(blocks, "Summary", item.summary, false); + fields.push({ + label: "Handoff", + value: `${item.strategy.replaceAll("_", " ")} · ${support.contextHandoff?.status ?? item.status}`, + }); + if (support.contextTransfer) { + fields.push({ + label: "Transfer", + value: `${support.contextTransfer.type.replaceAll("_", " ")} · ${support.contextTransfer.status}`, + }); + if (support.contextTransfer.resolution) { + fields.push({ + label: "Context", + value: support.contextTransfer.resolution.strategy.replaceAll("_", " "), + }); + } + } + break; + case "error": + addBlock(blocks, "Error", item.failure.message, false); + if (item.failure.code) fields.push({ label: "Code", value: item.failure.code }); + if (item.failure.retryable !== null) { + fields.push({ label: "Retryable", value: item.failure.retryable ? "yes" : "no" }); + } + break; + case "proposed_plan": + addBlock(blocks, "Plan", item.markdown, false); + break; + case "todo_list": + addBlock( + blocks, + "Tasks", + item.steps + .map((step) => `${step.status === "completed" ? "✓" : "○"} ${step.text}`) + .join("\n"), + false, + ); + addBlock(blocks, "Explanation", item.explanation, false); + break; + case "compaction": + addBlock(blocks, "Summary", item.summary, false); + if (item.beforeTokenCount !== undefined || item.afterTokenCount !== undefined) { + fields.push({ + label: "Context tokens", + value: `${item.beforeTokenCount ?? "?"} → ${item.afterTokenCount ?? "?"}`, + }); + } + break; + case "run_interrupt_request": + case "run_interrupt_result": + addBlock(blocks, "Message", item.message, false); + break; + case "fork": + case "thread_created": + case "user_message": + case "assistant_message": + break; + } + + const checkpoint = item.type === "checkpoint" ? support.checkpoint : null; + return { + fields, + blocks, + fileLinks, + webLinks, + canRollback: checkpoint?.status === "ready", + rollbackTarget: + checkpoint?.status === "ready" + ? { + threadId: row.sourceThreadId, + checkpointId: checkpoint.id, + scopeId: checkpoint.scopeId, + } + : null, + structuredDetails: formatStructured({ + visibility: row.visibility, + sourceThreadId: row.sourceThreadId, + sourceItemId: row.sourceItemId, + item, + }), + }; +} diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index d52a2b989f..d9bc15d33b 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -40,7 +40,7 @@ import { import { setPendingConnectionError } from "../state/use-remote-environment-registry"; import { useSelectedThreadDetail, - useSelectedThreadProjection, + useSelectedThreadVisibleTurnItems, } from "../state/use-thread-detail"; import { useThreadSelection } from "../state/use-thread-selection"; import { enqueueThreadOutboxMessage } from "./thread-outbox"; @@ -80,7 +80,7 @@ export function useThreadDraftForThread(input: { export function useThreadComposerState() { const { selectedThread: selectedThreadShell } = useThreadSelection(); const selectedThreadDetail = useSelectedThreadDetail(); - const selectedThreadProjection = useSelectedThreadProjection(); + const selectedThreadVisibleTurnItems = useSelectedThreadVisibleTurnItems(); const composerDrafts = useAtomValue(composerDraftsAtom); const queuedMessagesByThreadKey = useThreadOutboxMessages(); @@ -96,8 +96,8 @@ export function useThreadComposerState() { [queuedMessagesByThreadKey, selectedThreadKey], ); const selectedThreadFeed = useMemo( - () => buildThreadFeed(selectedThreadProjection?.projection.visibleTurnItems ?? []), - [selectedThreadProjection?.projection.visibleTurnItems], + () => buildThreadFeed(selectedThreadVisibleTurnItems), + [selectedThreadVisibleTurnItems], ); const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null; diff --git a/apps/mobile/src/state/use-thread-detail.ts b/apps/mobile/src/state/use-thread-detail.ts index 0460126d75..9e3bac3ae6 100644 --- a/apps/mobile/src/state/use-thread-detail.ts +++ b/apps/mobile/src/state/use-thread-detail.ts @@ -1,6 +1,6 @@ import { useAtomValue } from "@effect/atom-react"; import type { ScopedThreadProjection } from "@t3tools/client-runtime/state/shell"; -import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import type { EnvironmentId, OrchestrationV2ThreadProjection, ThreadId } from "@t3tools/contracts"; import * as Option from "effect/Option"; import { Atom } from "effect/unstable/reactivity"; @@ -10,6 +10,9 @@ import { useThreadSelection } from "./use-thread-selection"; const EMPTY_THREAD_PROJECTION_ATOM = Atom.make(null).pipe( Atom.withLabel("mobile-thread-projection:empty"), ); +const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make< + OrchestrationV2ThreadProjection["visibleTurnItems"] +>(Object.freeze([])).pipe(Atom.withLabel("mobile-thread-visible-turn-items:empty")); export interface ThreadDetailTarget { readonly environmentId: EnvironmentId | null; @@ -50,3 +53,24 @@ export function useSelectedThreadProjection(): ScopedThreadProjection | null { threadId: selectedThread?.id ?? null, }); } + +export function useThreadVisibleTurnItems( + target: ThreadDetailTarget, +): OrchestrationV2ThreadProjection["visibleTurnItems"] { + return useAtomValue( + target.environmentId === null || target.threadId === null + ? EMPTY_VISIBLE_TURN_ITEMS_ATOM + : environmentThreadDetails.visibleTurnItemsAtom({ + environmentId: target.environmentId, + threadId: target.threadId, + }), + ); +} + +export function useSelectedThreadVisibleTurnItems(): OrchestrationV2ThreadProjection["visibleTurnItems"] { + const { selectedThread } = useThreadSelection(); + return useThreadVisibleTurnItems({ + environmentId: selectedThread?.environmentId ?? null, + threadId: selectedThread?.id ?? null, + }); +} diff --git a/apps/mobile/src/state/v2-item-support.ts b/apps/mobile/src/state/v2-item-support.ts new file mode 100644 index 0000000000..f9fa51dc75 --- /dev/null +++ b/apps/mobile/src/state/v2-item-support.ts @@ -0,0 +1,56 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + EMPTY_V2_ITEM_SUPPORT, + resolveV2ItemSupport, + v2ItemSupportEqual, + type V2ItemSupport, +} from "@t3tools/client-runtime/state/item-support"; +import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts"; +import { Atom } from "effect/unstable/reactivity"; + +import { environmentThreadDetails } from "./threads"; + +interface ItemSupportTarget { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly itemId: TurnItemId; +} + +function supportKey(target: ItemSupportTarget): string { + return JSON.stringify(target); +} + +function parseSupportKey(key: string): ItemSupportTarget { + return JSON.parse(key) as ItemSupportTarget; +} + +const itemSupportAtomFamily = Atom.family((key: string) => { + const target = parseSupportKey(key); + const ref = scopeThreadRef(target.environmentId, target.threadId); + let previous = EMPTY_V2_ITEM_SUPPORT; + return Atom.make((get): V2ItemSupport => { + const scoped = get(environmentThreadDetails.threadAtom(ref)); + if (scoped === null) return EMPTY_V2_ITEM_SUPPORT; + const next = resolveV2ItemSupport(scoped.projection, target.itemId); + if (v2ItemSupportEqual(previous, next)) return previous; + previous = next; + return next; + }).pipe(Atom.withLabel(`mobile-v2-item-support:${key}`)); +}); + +export function useV2ItemSupport(target: { + readonly environmentId: EnvironmentId; + readonly sourceThreadId: ThreadId; + readonly sourceItemId: TurnItemId; +}): V2ItemSupport { + return useAtomValue( + itemSupportAtomFamily( + supportKey({ + environmentId: target.environmentId, + threadId: target.sourceThreadId, + itemId: target.sourceItemId, + }), + ), + ); +} diff --git a/apps/web/src/state/v2ItemSupport.ts b/apps/web/src/state/v2ItemSupport.ts index 1c985bdfd6..269baab331 100644 --- a/apps/web/src/state/v2ItemSupport.ts +++ b/apps/web/src/state/v2ItemSupport.ts @@ -1,47 +1,16 @@ import { useAtomValue } from "@effect/atom-react"; -import type { - EnvironmentId, - OrchestrationV2ThreadProjection, - ThreadId, - TurnItemId, -} from "@t3tools/contracts"; +import { + EMPTY_V2_ITEM_SUPPORT, + resolveV2ItemSupport, + v2ItemSupportEqual, + type V2ItemSupport, +} from "@t3tools/client-runtime/state/item-support"; +import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { Atom } from "effect/unstable/reactivity"; import { environmentThreadDetails } from "./threads"; -type Projection = OrchestrationV2ThreadProjection; - -export interface V2ItemSupport { - readonly item: Projection["turnItems"][number] | null; - readonly run: Projection["runs"][number] | null; - readonly attempts: ReadonlyArray; - readonly node: Projection["nodes"][number] | null; - readonly providerSession: Projection["providerSessions"][number] | null; - readonly providerThread: Projection["providerThreads"][number] | null; - readonly providerTurn: Projection["providerTurns"][number] | null; - readonly runtimeRequest: Projection["runtimeRequests"][number] | null; - readonly checkpoint: Projection["checkpoints"][number] | null; - readonly subagent: Projection["subagents"][number] | null; - readonly contextHandoff: Projection["contextHandoffs"][number] | null; - readonly contextTransfer: Projection["contextTransfers"][number] | null; -} - -const EMPTY_SUPPORT: V2ItemSupport = Object.freeze({ - item: null, - run: null, - attempts: Object.freeze([]), - node: null, - providerSession: null, - providerThread: null, - providerTurn: null, - runtimeRequest: null, - checkpoint: null, - subagent: null, - contextHandoff: null, - contextTransfer: null, -}); - function supportKey(input: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId; @@ -62,111 +31,15 @@ function parseSupportKey(key: string): { }; } -function sameEntities(left: ReadonlyArray, right: ReadonlyArray): boolean { - return left.length === right.length && left.every((value, index) => value === right[index]); -} - -function sameSupport(left: V2ItemSupport, right: V2ItemSupport): boolean { - return ( - left.item === right.item && - left.run === right.run && - sameEntities(left.attempts, right.attempts) && - left.node === right.node && - left.providerSession === right.providerSession && - left.providerThread === right.providerThread && - left.providerTurn === right.providerTurn && - left.runtimeRequest === right.runtimeRequest && - left.checkpoint === right.checkpoint && - left.subagent === right.subagent && - left.contextHandoff === right.contextHandoff && - left.contextTransfer === right.contextTransfer - ); -} - const itemSupportAtomFamily = Atom.family((key: string) => { const target = parseSupportKey(key); const ref = scopeThreadRef(target.environmentId, target.threadId); - let previous = EMPTY_SUPPORT; + let previous = EMPTY_V2_ITEM_SUPPORT; return Atom.make((get): V2ItemSupport => { const scoped = get(environmentThreadDetails.threadAtom(ref)); - if (scoped === null) return EMPTY_SUPPORT; - const projection = scoped.projection; - const item = - projection.turnItems.find((candidate) => candidate.id === target.itemId) ?? - projection.visibleTurnItems.find((candidate) => candidate.sourceItemId === target.itemId) - ?.item ?? - null; - if (item === null) return EMPTY_SUPPORT; - const run = - item.runId === null - ? null - : (projection.runs.find((candidate) => candidate.id === item.runId) ?? null); - const attempts = - item.runId === null - ? EMPTY_SUPPORT.attempts - : projection.attempts.filter((candidate) => candidate.runId === item.runId); - const node = - item.nodeId === null - ? null - : (projection.nodes.find((candidate) => candidate.id === item.nodeId) ?? null); - const providerThread = - item.providerThreadId === null - ? null - : (projection.providerThreads.find((candidate) => candidate.id === item.providerThreadId) ?? - null); - const providerSession = - providerThread?.providerSessionId == null - ? null - : (projection.providerSessions.find( - (candidate) => candidate.id === providerThread.providerSessionId, - ) ?? null); - const providerTurn = - item.providerTurnId === null - ? null - : (projection.providerTurns.find((candidate) => candidate.id === item.providerTurnId) ?? - null); - const requestId = - item.type === "approval_request" || item.type === "user_input_request" - ? item.requestId - : node?.runtimeRequestId; - const runtimeRequest = - requestId == null - ? null - : (projection.runtimeRequests.find((candidate) => candidate.id === requestId) ?? null); - const checkpoint = - item.type === "checkpoint" - ? (projection.checkpoints.find((candidate) => candidate.id === item.checkpointId) ?? null) - : null; - const subagent = - item.type === "subagent" - ? (projection.subagents.find((candidate) => candidate.id === item.subagentId) ?? null) - : null; - const contextHandoff = - item.type === "handoff" - ? (projection.contextHandoffs.find((candidate) => candidate.id === item.contextHandoffId) ?? - null) - : null; - const contextTransfer = - contextHandoff?.transferId == null - ? null - : (projection.contextTransfers.find( - (candidate) => candidate.id === contextHandoff.transferId, - ) ?? null); - const next: V2ItemSupport = { - item, - run, - attempts, - node, - providerSession, - providerThread, - providerTurn, - runtimeRequest, - checkpoint, - subagent, - contextHandoff, - contextTransfer, - }; - if (sameSupport(previous, next)) return previous; + if (scoped === null) return EMPTY_V2_ITEM_SUPPORT; + const next = resolveV2ItemSupport(scoped.projection, target.itemId); + if (v2ItemSupportEqual(previous, next)) return previous; previous = next; return next; }).pipe(Atom.withLabel(`web-v2-item-support:${key}`)); diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 6435146421..6afbc87748 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -63,6 +63,10 @@ "types": "./src/state/git.ts", "default": "./src/state/git.ts" }, + "./state/item-support": { + "types": "./src/state/itemSupport.ts", + "default": "./src/state/itemSupport.ts" + }, "./state/models": { "types": "./src/state/models.ts", "default": "./src/state/models.ts" diff --git a/packages/client-runtime/src/state/itemSupport.test.ts b/packages/client-runtime/src/state/itemSupport.test.ts new file mode 100644 index 0000000000..552230746e --- /dev/null +++ b/packages/client-runtime/src/state/itemSupport.test.ts @@ -0,0 +1,205 @@ +import { + NodeId, + ProviderDriverKind, + ProviderInstanceId, + ProviderSessionId, + ProviderThreadId, + ProviderTurnId, + RunAttemptId, + RunId, + RuntimeRequestId, + TurnItemId, + type OrchestrationV2TurnItem, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; + +import { v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; +import { EMPTY_V2_ITEM_SUPPORT, resolveV2ItemSupport, v2ItemSupportEqual } from "./itemSupport.ts"; + +const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); +const runId = RunId.make("run-1"); +const nodeId = NodeId.make("node-1"); +const itemId = TurnItemId.make("item-1"); +const requestId = RuntimeRequestId.make("request-1"); +const providerInstanceId = ProviderInstanceId.make("codex"); +const providerThreadId = ProviderThreadId.make("provider-thread-1"); +const providerTurnId = ProviderTurnId.make("provider-turn-1"); + +const commandItem: OrchestrationV2TurnItem = { + id: itemId, + threadId: v2ThreadId, + runId, + nodeId, + providerThreadId, + providerTurnId, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "running", + title: null, + startedAt: now, + completedAt: null, + updatedAt: now, + type: "command_execution", + input: "vp check", +}; + +describe("resolveV2ItemSupport", () => { + it("retains identity while linking a turn item to its execution and provider entities", () => { + const run = { + id: runId, + threadId: v2ThreadId, + ordinal: 1, + providerInstanceId, + modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" }, + providerThreadId, + userMessageId: "message-1" as never, + rootNodeId: nodeId, + activeAttemptId: RunAttemptId.make("attempt-2"), + status: "running" as const, + requestedAt: now, + startedAt: now, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }; + const attempts = [ + { + id: RunAttemptId.make("attempt-1"), + runId, + attemptOrdinal: 1, + rootNodeId: nodeId, + providerInstanceId, + providerThreadId, + providerTurnId, + reason: "initial" as const, + status: "superseded" as const, + startedAt: now, + completedAt: now, + }, + { + id: RunAttemptId.make("attempt-2"), + runId, + attemptOrdinal: 2, + rootNodeId: nodeId, + providerInstanceId, + providerThreadId, + providerTurnId, + reason: "steering_restart" as const, + status: "running" as const, + startedAt: now, + completedAt: null, + }, + ]; + const node = { + id: nodeId, + threadId: v2ThreadId, + runId, + parentNodeId: null, + rootNodeId: nodeId, + kind: "tool_call" as const, + status: "running" as const, + countsForRun: true, + providerThreadId, + providerTurnId, + nativeItemRef: null, + runtimeRequestId: requestId, + checkpointScopeId: null, + startedAt: now, + completedAt: null, + }; + const providerThread = { + id: providerThreadId, + driver: ProviderDriverKind.make("codex"), + providerInstanceId, + providerSessionId: null, + appThreadId: v2ThreadId, + ownerNodeId: nodeId, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "active" as const, + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }; + const providerTurn = { + id: providerTurnId, + providerThreadId, + nodeId, + runAttemptId: attempts[1]!.id, + nativeTurnRef: null, + ordinal: 1, + status: "running" as const, + startedAt: now, + completedAt: null, + }; + const runtimeRequest = { + id: requestId, + nodeId, + providerTurnId, + nativeRequestRef: null, + kind: "dynamic_tool_call" as const, + status: "pending" as const, + responseCapability: { + type: "live" as const, + providerSessionId: ProviderSessionId.make("session-1"), + }, + createdAt: now, + resolvedAt: null, + }; + const projection = { + ...v2Projection, + runs: [run], + attempts, + nodes: [node], + providerThreads: [providerThread], + providerTurns: [providerTurn], + runtimeRequests: [runtimeRequest], + turnItems: [commandItem], + }; + + const support = resolveV2ItemSupport(projection, itemId); + expect(support.item).toBe(commandItem); + expect(support.run).toBe(run); + expect(support.attempts).toEqual(attempts); + expect(support.attempts[0]).toBe(attempts[0]); + expect(support.node).toBe(node); + expect(support.providerThread).toBe(providerThread); + expect(support.providerTurn).toBe(providerTurn); + expect(support.runtimeRequest).toBe(runtimeRequest); + }); + + it("resolves synthetic items from the authoritative visible sequence", () => { + const projection = { + ...v2Projection, + visibleTurnItems: [ + { + position: 0, + visibility: "synthetic" as const, + sourceThreadId: v2ThreadId, + sourceItemId: itemId, + item: commandItem, + }, + ], + }; + expect(resolveV2ItemSupport(projection, itemId).item).toBe(commandItem); + }); + + it("returns the stable empty support for unknown items", () => { + expect(resolveV2ItemSupport(v2Projection, itemId)).toBe(EMPTY_V2_ITEM_SUPPORT); + }); + + it("compares support structurally while retaining entity identity semantics", () => { + expect(v2ItemSupportEqual(EMPTY_V2_ITEM_SUPPORT, { ...EMPTY_V2_ITEM_SUPPORT })).toBe(true); + expect( + v2ItemSupportEqual(EMPTY_V2_ITEM_SUPPORT, { + ...EMPTY_V2_ITEM_SUPPORT, + attempts: [{ id: "attempt" } as never], + }), + ).toBe(false); + }); +}); diff --git a/packages/client-runtime/src/state/itemSupport.ts b/packages/client-runtime/src/state/itemSupport.ts new file mode 100644 index 0000000000..936ac4d9c4 --- /dev/null +++ b/packages/client-runtime/src/state/itemSupport.ts @@ -0,0 +1,138 @@ +import type { OrchestrationV2ThreadProjection, TurnItemId } from "@t3tools/contracts"; + +type Projection = OrchestrationV2ThreadProjection; + +export interface V2ItemSupport { + readonly item: Projection["turnItems"][number] | null; + readonly run: Projection["runs"][number] | null; + readonly attempts: ReadonlyArray; + readonly node: Projection["nodes"][number] | null; + readonly providerSession: Projection["providerSessions"][number] | null; + readonly providerThread: Projection["providerThreads"][number] | null; + readonly providerTurn: Projection["providerTurns"][number] | null; + readonly runtimeRequest: Projection["runtimeRequests"][number] | null; + readonly checkpoint: Projection["checkpoints"][number] | null; + readonly subagent: Projection["subagents"][number] | null; + readonly contextHandoff: Projection["contextHandoffs"][number] | null; + readonly contextTransfer: Projection["contextTransfers"][number] | null; +} + +export const EMPTY_V2_ITEM_SUPPORT: V2ItemSupport = Object.freeze({ + item: null, + run: null, + attempts: Object.freeze([]), + node: null, + providerSession: null, + providerThread: null, + providerTurn: null, + runtimeRequest: null, + checkpoint: null, + subagent: null, + contextHandoff: null, + contextTransfer: null, +}); + +/** + * Resolves the relational V2 entities that enrich one projected item. The + * caller supplies the item's source-thread projection, including for inherited + * rows, so every returned entity retains its original projection identity. + */ +export function resolveV2ItemSupport(projection: Projection, itemId: TurnItemId): V2ItemSupport { + const item = + projection.turnItems.find((candidate) => candidate.id === itemId) ?? + projection.visibleTurnItems.find((candidate) => candidate.sourceItemId === itemId)?.item ?? + null; + if (item === null) return EMPTY_V2_ITEM_SUPPORT; + + const run = + item.runId === null + ? null + : (projection.runs.find((candidate) => candidate.id === item.runId) ?? null); + const attempts = + item.runId === null + ? EMPTY_V2_ITEM_SUPPORT.attempts + : projection.attempts.filter((candidate) => candidate.runId === item.runId); + const node = + item.nodeId === null + ? null + : (projection.nodes.find((candidate) => candidate.id === item.nodeId) ?? null); + const providerThread = + item.providerThreadId === null || item.providerThreadId === undefined + ? null + : (projection.providerThreads.find((candidate) => candidate.id === item.providerThreadId) ?? + null); + const providerSession = + providerThread?.providerSessionId == null + ? null + : (projection.providerSessions.find( + (candidate) => candidate.id === providerThread.providerSessionId, + ) ?? null); + const providerTurn = + item.providerTurnId === null + ? null + : (projection.providerTurns.find((candidate) => candidate.id === item.providerTurnId) ?? + null); + const requestId = + item.type === "approval_request" || item.type === "user_input_request" + ? item.requestId + : node?.runtimeRequestId; + const runtimeRequest = + requestId == null + ? null + : (projection.runtimeRequests.find((candidate) => candidate.id === requestId) ?? null); + const checkpoint = + item.type === "checkpoint" + ? (projection.checkpoints.find((candidate) => candidate.id === item.checkpointId) ?? null) + : null; + const subagent = + item.type === "subagent" + ? (projection.subagents.find((candidate) => candidate.id === item.subagentId) ?? null) + : null; + const contextHandoff = + item.type === "handoff" + ? (projection.contextHandoffs.find((candidate) => candidate.id === item.contextHandoffId) ?? + null) + : null; + const contextTransfer = + contextHandoff?.transferId == null + ? null + : (projection.contextTransfers.find( + (candidate) => candidate.id === contextHandoff.transferId, + ) ?? null); + + return { + item, + run, + attempts, + node, + providerSession, + providerThread, + providerTurn, + runtimeRequest, + checkpoint, + subagent, + contextHandoff, + contextTransfer, + }; +} + +function sameEntities(left: ReadonlyArray, right: ReadonlyArray): boolean { + return left.length === right.length && left.every((value, index) => value === right[index]); +} + +export function v2ItemSupportEqual(left: V2ItemSupport, right: V2ItemSupport): boolean { + return ( + left.item === right.item && + left.run === right.run && + sameEntities(left.attempts, right.attempts) && + left.node === right.node && + left.providerSession === right.providerSession && + left.providerThread === right.providerThread && + left.providerTurn === right.providerTurn && + left.runtimeRequest === right.runtimeRequest && + left.checkpoint === right.checkpoint && + left.subagent === right.subagent && + left.contextHandoff === right.contextHandoff && + left.contextTransfer === right.contextTransfer + ); +}