import { type AssetResource, ProviderDriverKind, type OrchestrationV2ExecutionNode, type OrchestrationV2PlanArtifact, type OrchestrationV2ProjectedTurnItem, type OrchestrationV2RunAttempt, type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, type PlanId, type RunId, type ThreadId, type ToolActivitySurface, type ToolActivityIcon, type ToolActivitySource,} from "@t3tools/contracts";import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";import type { ThreadPendingApproval, ThreadPendingUserInput,} from "@t3tools/client-runtime/state/thread-requests";import type { ThreadRunSummary, ThreadRuntimeSummary } from "@t3tools/client-runtime/state/shell";import { turnItemIsWorkspacePreparation } from "@t3tools/client-runtime/state/turn-item-presentation"; import { isImageAttachment, type ChatAttachment, type ChatMessage, type ProposedPlan, type SessionPhase, type TurnDiffSummary,} from "./types";import * as DateTime from "effect/DateTime";import * as Equal from "effect/Equal";import { shallow } from "zustand/vanilla/shallow"; export { formatDuration, formatElapsed } from "@t3tools/shared/orchestrationTiming"; export type ProviderPickerKind = ProviderDriverKind; export const PROVIDER_OPTIONS: Array<{ value: ProviderPickerKind; label: string; available: boolean; pickerSidebarBadge?: "new" | "soon";}> = [ { value: ProviderDriverKind.make("codex"), label: "Codex", available: true }, { value: ProviderDriverKind.make("claudeAgent"), label: "Claude", available: true }, { value: ProviderDriverKind.make("opencode"), label: "OpenCode", available: true, pickerSidebarBadge: "new", }, { value: ProviderDriverKind.make("cursor"), label: "Cursor", available: true, pickerSidebarBadge: "new", }, { value: ProviderDriverKind.make("grok"), label: "Grok", available: true }, { value: ProviderDriverKind.make("antigravity"), label: "Antigravity", available: true, pickerSidebarBadge: "new", },]; export type WorkLogToolLifecycleStatus = | "idle" | "inProgress" | "completed" | "failed" | "declined" | "stopped"; export interface WorkLogEntry { readonly id: string; readonly createdAt: string; readonly runId?: RunId | null; readonly label: string; readonly detail?: string; readonly command?: string; readonly rawCommand?: string; readonly changedFiles?: ReadonlyArray<string>; readonly tone: "thinking" | "tool" | "info" | "error"; readonly toolTitle?: string; readonly toolCallId?: string; readonly viewedImagePath?: string; readonly toolSurface?: ToolActivitySurface; readonly toolIcon?: ToolActivityIcon; readonly toolSource?: ToolActivitySource; readonly sourceActivityKind?: string; readonly taskId?: string; readonly agentRole?: string; readonly toolData?: unknown; readonly requestKind?: string; readonly itemType?: OrchestrationV2TurnItem["type"]; readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus; readonly structuredPayload?: OrchestrationV2TurnItem; readonly sourceItemType?: OrchestrationV2TurnItem["type"]; readonly projectedItem?: OrchestrationV2ProjectedTurnItem;} export type PendingApproval = ThreadPendingApproval;export type PendingUserInput = ThreadPendingUserInput; export interface ActivePlanState { readonly createdAt: string; readonly runId: RunId | null; readonly explanation?: string | null; readonly steps: Array<{ readonly step: string; readonly status: "pending" | "inProgress" | "completed"; }>;} export interface LatestProposedPlanState { readonly id: PlanId; readonly createdAt: string; readonly updatedAt: string; readonly runId: RunId | null; readonly planMarkdown: string; readonly status: OrchestrationV2PlanArtifact["status"];} export type TimelineAttempt = Pick< OrchestrationV2RunAttempt, "id" | "runId" | "attemptOrdinal" | "rootNodeId" | "status">; export type TimelineEntry = ( | { readonly id: string; readonly kind: "message"; readonly createdAt: string; readonly message: ChatMessage; readonly projectedItem?: OrchestrationV2ProjectedTurnItem; } | { readonly id: string; readonly kind: "proposed-plan"; readonly createdAt: string; readonly proposedPlan: ProposedPlan; } | { readonly id: string; readonly kind: "work"; readonly createdAt: string; readonly entry: WorkLogEntry; } | { readonly id: string; readonly kind: "event"; readonly createdAt: string; readonly projectedItem: OrchestrationV2ProjectedTurnItem; }) & { /** V2 identity resolved from the item's execution node, when locally available. */ readonly attempt?: TimelineAttempt;}; export function workLogEntryIsToolLike(entry: WorkLogEntry): boolean { return ( entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error" || entry.command !== undefined || entry.requestKind !== undefined );} /** Heuristic: providers often emit successful item status while error text lives in `detail` / `command`. */function toolDetailTextLooksLikeFailure(text: string): boolean { const t = text.toLowerCase(); if (t.includes("file not found")) { return true; } if (t.includes("no files found")) { return true; } if ( t.includes("enoent") || t.includes("no such file or directory") || t.includes("no such file") ) { return true; } if (t.includes("cannot find path") && t.includes("because it does not exist")) { return true; } if (t.includes("commandnotfoundexception")) { return true; } if (t.includes("is not recognized as the name of a cmdlet")) { return true; } if (t.includes("is not recognized") && t.includes("the term '")) { return true; } if (t.includes("a parameter cannot be found that matches parameter name")) { return true; } if (t.includes("command not found")) { return true; } if (/<exited with exit code\s+[1-9]\d*\s*>/i.test(text)) { return true; } if (/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text)) { return true; } if (/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)) { return true; } return false;} function workEntryIndicatesToolFailureFromOutput( entry: WorkLogEntry, includeCommand: boolean,): boolean { if (entry.tone === "error") { return true; } const ls = entry.toolLifecycleStatus; if (ls === "failed" || ls === "declined") { return true; } if (!workLogEntryIsToolLike(entry)) { return false; } const parts: string[] = []; if (entry.detail) { parts.push(entry.detail); } if (includeCommand && entry.command) { parts.push(entry.command); } const blob = parts.join("\n"); if (blob.length === 0) { return false; } return toolDetailTextLooksLikeFailure(blob);} /** True when a tool failed, including providers that put error output in `command`. */export function workEntryIndicatesToolFailure(entry: WorkLogEntry): boolean { return workEntryIndicatesToolFailureFromOutput(entry, true);} /** True when the rendered result indicates failure. The command itself is user intent, not output. */export function workEntryDisplayIndicatesToolFailure(entry: WorkLogEntry): boolean { return workEntryIndicatesToolFailureFromOutput(entry, false);} /** Severe failures keep the red treatment ordinary tool failures lost: provider * runtime errors mean the turn or a core side effect broke, not that a * command exited nonzero. */export function workEntrySignalsSevereFailure(entry: WorkLogEntry): boolean { return entry.itemType === "error";} export function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean { if ( !workLogEntryIsToolLike(entry) || workEntryIndicatesToolFailure(entry) || entry.tone === "thinking" ) { return false; } const status = entry.toolLifecycleStatus; return ( status !== "failed" && status !== "declined" && status !== "inProgress" && status !== "stopped" && status !== "idle" );} export function workEntryIndicatesToolNeutralStatus(entry: WorkLogEntry): boolean { return ( workLogEntryIsToolLike(entry) && !workEntryIndicatesToolFailure(entry) && !workEntryIndicatesToolSuccess(entry) );} export function isLatestRunSettled( latestRun: Pick<ThreadRunSummary, "runId" | "startedAt" | "completedAt" | "status"> | null, runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId"> | null,): boolean { if (latestRun === null) return false; if ( latestRun.status === "preparing" || latestRun.status === "queued" || latestRun.status === "starting" || latestRun.status === "running" || latestRun.status === "waiting" ) return false; return runtime?.activeRunId !== latestRun.runId;} export function deriveActiveWorkStartedAt( latestRun: Pick<ThreadRunSummary, "runId" | "startedAt" | "completedAt" | "status"> | null, runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId"> | null, sendStartedAt: string | null,): string | null { if (runtime?.activeRunId !== null && runtime?.activeRunId !== undefined) { return latestRun?.runId === runtime.activeRunId ? (latestRun.startedAt ?? sendStartedAt) : sendStartedAt; } return isLatestRunSettled(latestRun, runtime) ? sendStartedAt : (latestRun?.startedAt ?? sendStartedAt);} export function derivePendingApprovals( approvals: ReadonlyArray<ThreadPendingApproval>,): ThreadPendingApproval[] { return [...approvals].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));} export function derivePendingUserInputs( inputs: ReadonlyArray<ThreadPendingUserInput>,): ThreadPendingUserInput[] { return [...inputs].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));} export function deriveActivePlanState( projection: OrchestrationV2ThreadProjection | null, latestRunId: RunId | undefined,): ActivePlanState | null { if (projection === null) return null; const plans = projection.plans.filter((plan) => plan.kind === "todo_list"); const plan = [...plans].toReversed().find((candidate) => candidate.runId === latestRunId) ?? plans.at(-1) ?? null; if (plan === null || plan.steps.length === 0) return null; return { createdAt: planItemTime(projection, plan.id), runId: plan.runId, explanation: plan.explanation ?? null, steps: plan.steps.map(({ text, status }) => ({ step: text, status: status === "running" ? "inProgress" : status, })), };} function planItemTime(projection: OrchestrationV2ThreadProjection, planId: PlanId): string { const item = projection.turnItems.findLast( (candidate) => (candidate.type === "proposed_plan" || candidate.type === "todo_list") && candidate.planId === planId, ); return DateTime.formatIso(item?.updatedAt ?? projection.updatedAt);} function toLatestProposedPlanState( projection: OrchestrationV2ThreadProjection, plan: Extract<OrchestrationV2PlanArtifact, { readonly kind: "proposed_plan" }>,): LatestProposedPlanState { const updatedAt = planItemTime(projection, plan.id); return { id: plan.id, createdAt: updatedAt, updatedAt, runId: plan.runId, planMarkdown: plan.markdown, status: plan.status, };} export function findLatestProposedPlan( projection: OrchestrationV2ThreadProjection | null, latestRunId: RunId | string | null | undefined,): LatestProposedPlanState | null { if (projection === null) return null; const plans = projection.plans.filter((plan) => plan.kind === "proposed_plan"); const candidates = latestRunId ? plans.filter((plan) => plan.runId === latestRunId) : plans; const plan = [...(candidates.length > 0 ? candidates : plans)] .toSorted( (left, right) => planItemTime(projection, left.id).localeCompare(planItemTime(projection, right.id)) || left.id.localeCompare(right.id), ) .at(-1); return plan === undefined ? null : toLatestProposedPlanState(projection, plan);} export function findSidebarProposedPlan(input: { readonly threads: ReadonlyArray<{ readonly id: ThreadId; readonly projection: OrchestrationV2ThreadProjection; }>; readonly latestRun: Pick<ThreadRunSummary, "runId" | "sourcePlanRef"> | null; readonly latestRunSettled: boolean; readonly threadId: ThreadId | string | null | undefined;}): LatestProposedPlanState | null { if (!input.latestRunSettled && input.latestRun?.sourcePlanRef !== undefined) { const source = input.latestRun.sourcePlanRef; const sourceProjection = input.threads.find( (thread) => thread.id === source.threadId, )?.projection; const plan = sourceProjection?.plans.find( (candidate) => candidate.kind === "proposed_plan" && candidate.id === source.planId, ); if (sourceProjection !== undefined && plan?.kind === "proposed_plan") { return toLatestProposedPlanState(sourceProjection, plan); } } const activeProjection = input.threads.find((thread) => thread.id === input.threadId)?.projection; return findLatestProposedPlan(activeProjection ?? null, input.latestRun?.runId);} export function hasActionableProposedPlan(plan: LatestProposedPlanState | null): boolean { return plan?.status === "active";} const STANDALONE_V2_ITEM_TYPES = new Set<OrchestrationV2ProjectedTurnItem["item"]["type"]>([ "approval_request", "fork", "handoff", "run_interrupt_request", "run_interrupt_result", "subagent", "thread_created", "user_input_request",]); const PERSISTENT_RESOURCE_V2_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([ "fork", "subagent", "thread_created",]); export function timelineEntryIsPersistentResourceCard(entry: TimelineEntry): boolean { return ( entry.kind === "event" && PERSISTENT_RESOURCE_V2_ITEM_TYPES.has(entry.projectedItem.item.type) );} function projectedItemCreatedAt(row: OrchestrationV2ProjectedTurnItem): string { return DateTime.formatIso(row.item.startedAt ?? row.item.updatedAt);} function projectedWorkEntryStatus( item: OrchestrationV2TurnItem,): NonNullable<WorkLogEntry["toolLifecycleStatus"]> { switch (item.status) { case "pending": case "running": case "waiting": return "inProgress"; case "completed": return "completed"; case "idle": return "idle"; case "failed": return "failed"; case "cancelled": case "interrupted": return "stopped"; }} function projectedWorkEntryTone(item: OrchestrationV2TurnItem): WorkLogEntry["tone"] { if (item.type === "error") return "info"; if (item.type === "reasoning") return "thinking"; switch (item.type) { case "command_execution": case "file_change": case "file_search": case "web_search": case "dynamic_tool": case "subagent": return "tool"; default: return "info"; }} export function providerErrorPresentation( item: Extract<OrchestrationV2TurnItem, { readonly type: "error" }>,): { readonly label: string; readonly detail: string } { if (item.retry === undefined) { return { label: item.title?.trim() || "Provider error", detail: item.failure.message, }; } const progress = item.retry.maxAttempts === nullLines 1–500 of 1056. Load more
import { type AssetResource, ProviderDriverKind, type OrchestrationV2ExecutionNode, type OrchestrationV2PlanArtifact, type OrchestrationV2ProjectedTurnItem, type OrchestrationV2RunAttempt, type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, type PlanId, type RunId, type ThreadId, type ToolActivitySurface, type ToolActivityIcon, type ToolActivitySource, } from "@t3tools/contracts"; import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation"; import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; import type { ThreadPendingApproval, ThreadPendingUserInput, } from "@t3tools/client-runtime/state/thread-requests"; import type { ThreadRunSummary, ThreadRuntimeSummary } from "@t3tools/client-runtime/state/shell"; import { turnItemIsWorkspacePreparation } from "@t3tools/client-runtime/state/turn-item-presentation"; import { isImageAttachment, type ChatAttachment, type ChatMessage, type ProposedPlan, type SessionPhase, type TurnDiffSummary, } from "./types"; import * as DateTime from "effect/DateTime"; import * as Equal from "effect/Equal"; import { shallow } from "zustand/vanilla/shallow"; export { formatDuration, formatElapsed } from "@t3tools/shared/orchestrationTiming"; export type ProviderPickerKind = ProviderDriverKind; export const PROVIDER_OPTIONS: Array<{ value: ProviderPickerKind; label: string; available: boolean; pickerSidebarBadge?: "new" | "soon"; }> = [ { value: ProviderDriverKind.make("codex"), label: "Codex", available: true }, { value: ProviderDriverKind.make("claudeAgent"), label: "Claude", available: true }, { value: ProviderDriverKind.make("opencode"), label: "OpenCode", available: true, pickerSidebarBadge: "new", }, { value: ProviderDriverKind.make("cursor"), label: "Cursor", available: true, pickerSidebarBadge: "new", }, { value: ProviderDriverKind.make("grok"), label: "Grok", available: true }, { value: ProviderDriverKind.make("antigravity"), label: "Antigravity", available: true, pickerSidebarBadge: "new", }, ]; export type WorkLogToolLifecycleStatus = | "idle" | "inProgress" | "completed" | "failed" | "declined" | "stopped"; export interface WorkLogEntry { readonly id: string; readonly createdAt: string; readonly runId?: RunId | null; readonly label: string; readonly detail?: string; readonly command?: string; readonly rawCommand?: string; readonly changedFiles?: ReadonlyArray<string>; readonly tone: "thinking" | "tool" | "info" | "error"; readonly toolTitle?: string; readonly toolCallId?: string; readonly viewedImagePath?: string; readonly toolSurface?: ToolActivitySurface; readonly toolIcon?: ToolActivityIcon; readonly toolSource?: ToolActivitySource; readonly sourceActivityKind?: string; readonly taskId?: string; readonly agentRole?: string; readonly toolData?: unknown; readonly requestKind?: string; readonly itemType?: OrchestrationV2TurnItem["type"]; readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus; readonly structuredPayload?: OrchestrationV2TurnItem; readonly sourceItemType?: OrchestrationV2TurnItem["type"]; readonly projectedItem?: OrchestrationV2ProjectedTurnItem; } export type PendingApproval = ThreadPendingApproval; export type PendingUserInput = ThreadPendingUserInput; export interface ActivePlanState { readonly createdAt: string; readonly runId: RunId | null; readonly explanation?: string | null; readonly steps: Array<{ readonly step: string; readonly status: "pending" | "inProgress" | "completed"; }>; } export interface LatestProposedPlanState { readonly id: PlanId; readonly createdAt: string; readonly updatedAt: string; readonly runId: RunId | null; readonly planMarkdown: string; readonly status: OrchestrationV2PlanArtifact["status"]; } export type TimelineAttempt = Pick< OrchestrationV2RunAttempt, "id" | "runId" | "attemptOrdinal" | "rootNodeId" | "status" >; export type TimelineEntry = ( | { readonly id: string; readonly kind: "message"; readonly createdAt: string; readonly message: ChatMessage; readonly projectedItem?: OrchestrationV2ProjectedTurnItem; } | { readonly id: string; readonly kind: "proposed-plan"; readonly createdAt: string; readonly proposedPlan: ProposedPlan; } | { readonly id: string; readonly kind: "work"; readonly createdAt: string; readonly entry: WorkLogEntry; } | { readonly id: string; readonly kind: "event"; readonly createdAt: string; readonly projectedItem: OrchestrationV2ProjectedTurnItem; } ) & { /** V2 identity resolved from the item's execution node, when locally available. */ readonly attempt?: TimelineAttempt; }; export function workLogEntryIsToolLike(entry: WorkLogEntry): boolean { return ( entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error" || entry.command !== undefined || entry.requestKind !== undefined ); } /** Heuristic: providers often emit successful item status while error text lives in `detail` / `command`. */ function toolDetailTextLooksLikeFailure(text: string): boolean { const t = text.toLowerCase(); if (t.includes("file not found")) { return true; } if (t.includes("no files found")) { return true; } if ( t.includes("enoent") || t.includes("no such file or directory") || t.includes("no such file") ) { return true; } if (t.includes("cannot find path") && t.includes("because it does not exist")) { return true; } if (t.includes("commandnotfoundexception")) { return true; } if (t.includes("is not recognized as the name of a cmdlet")) { return true; } if (t.includes("is not recognized") && t.includes("the term '")) { return true; } if (t.includes("a parameter cannot be found that matches parameter name")) { return true; } if (t.includes("command not found")) { return true; } if (/<exited with exit code\s+[1-9]\d*\s*>/i.test(text)) { return true; } if (/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text)) { return true; } if (/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)) { return true; } return false; } function workEntryIndicatesToolFailureFromOutput( entry: WorkLogEntry, includeCommand: boolean, ): boolean { if (entry.tone === "error") { return true; } const ls = entry.toolLifecycleStatus; if (ls === "failed" || ls === "declined") { return true; } if (!workLogEntryIsToolLike(entry)) { return false; } const parts: string[] = []; if (entry.detail) { parts.push(entry.detail); } if (includeCommand && entry.command) { parts.push(entry.command); } const blob = parts.join("\n"); if (blob.length === 0) { return false; } return toolDetailTextLooksLikeFailure(blob); } /** True when a tool failed, including providers that put error output in `command`. */ export function workEntryIndicatesToolFailure(entry: WorkLogEntry): boolean { return workEntryIndicatesToolFailureFromOutput(entry, true); } /** True when the rendered result indicates failure. The command itself is user intent, not output. */ export function workEntryDisplayIndicatesToolFailure(entry: WorkLogEntry): boolean { return workEntryIndicatesToolFailureFromOutput(entry, false); } /** Severe failures keep the red treatment ordinary tool failures lost: provider * runtime errors mean the turn or a core side effect broke, not that a * command exited nonzero. */ export function workEntrySignalsSevereFailure(entry: WorkLogEntry): boolean { return entry.itemType === "error"; } export function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean { if ( !workLogEntryIsToolLike(entry) || workEntryIndicatesToolFailure(entry) || entry.tone === "thinking" ) { return false; } const status = entry.toolLifecycleStatus; return ( status !== "failed" && status !== "declined" && status !== "inProgress" && status !== "stopped" && status !== "idle" ); } export function workEntryIndicatesToolNeutralStatus(entry: WorkLogEntry): boolean { return ( workLogEntryIsToolLike(entry) && !workEntryIndicatesToolFailure(entry) && !workEntryIndicatesToolSuccess(entry) ); } export function isLatestRunSettled( latestRun: Pick<ThreadRunSummary, "runId" | "startedAt" | "completedAt" | "status"> | null, runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId"> | null, ): boolean { if (latestRun === null) return false; if ( latestRun.status === "preparing" || latestRun.status === "queued" || latestRun.status === "starting" || latestRun.status === "running" || latestRun.status === "waiting" ) return false; return runtime?.activeRunId !== latestRun.runId; } export function deriveActiveWorkStartedAt( latestRun: Pick<ThreadRunSummary, "runId" | "startedAt" | "completedAt" | "status"> | null, runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId"> | null, sendStartedAt: string | null, ): string | null { if (runtime?.activeRunId !== null && runtime?.activeRunId !== undefined) { return latestRun?.runId === runtime.activeRunId ? (latestRun.startedAt ?? sendStartedAt) : sendStartedAt; } return isLatestRunSettled(latestRun, runtime) ? sendStartedAt : (latestRun?.startedAt ?? sendStartedAt); } export function derivePendingApprovals( approvals: ReadonlyArray<ThreadPendingApproval>, ): ThreadPendingApproval[] { return [...approvals].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)); } export function derivePendingUserInputs( inputs: ReadonlyArray<ThreadPendingUserInput>, ): ThreadPendingUserInput[] { return [...inputs].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)); } export function deriveActivePlanState( projection: OrchestrationV2ThreadProjection | null, latestRunId: RunId | undefined, ): ActivePlanState | null { if (projection === null) return null; const plans = projection.plans.filter((plan) => plan.kind === "todo_list"); const plan = [...plans].toReversed().find((candidate) => candidate.runId === latestRunId) ?? plans.at(-1) ?? null; if (plan === null || plan.steps.length === 0) return null; return { createdAt: planItemTime(projection, plan.id), runId: plan.runId, explanation: plan.explanation ?? null, steps: plan.steps.map(({ text, status }) => ({ step: text, status: status === "running" ? "inProgress" : status, })), }; } function planItemTime(projection: OrchestrationV2ThreadProjection, planId: PlanId): string { const item = projection.turnItems.findLast( (candidate) => (candidate.type === "proposed_plan" || candidate.type === "todo_list") && candidate.planId === planId, ); return DateTime.formatIso(item?.updatedAt ?? projection.updatedAt); } function toLatestProposedPlanState( projection: OrchestrationV2ThreadProjection, plan: Extract<OrchestrationV2PlanArtifact, { readonly kind: "proposed_plan" }>, ): LatestProposedPlanState { const updatedAt = planItemTime(projection, plan.id); return { id: plan.id, createdAt: updatedAt, updatedAt, runId: plan.runId, planMarkdown: plan.markdown, status: plan.status, }; } export function findLatestProposedPlan( projection: OrchestrationV2ThreadProjection | null, latestRunId: RunId | string | null | undefined, ): LatestProposedPlanState | null { if (projection === null) return null; const plans = projection.plans.filter((plan) => plan.kind === "proposed_plan"); const candidates = latestRunId ? plans.filter((plan) => plan.runId === latestRunId) : plans; const plan = [...(candidates.length > 0 ? candidates : plans)] .toSorted( (left, right) => planItemTime(projection, left.id).localeCompare(planItemTime(projection, right.id)) || left.id.localeCompare(right.id), ) .at(-1); return plan === undefined ? null : toLatestProposedPlanState(projection, plan); } export function findSidebarProposedPlan(input: { readonly threads: ReadonlyArray<{ readonly id: ThreadId; readonly projection: OrchestrationV2ThreadProjection; }>; readonly latestRun: Pick<ThreadRunSummary, "runId" | "sourcePlanRef"> | null; readonly latestRunSettled: boolean; readonly threadId: ThreadId | string | null | undefined; }): LatestProposedPlanState | null { if (!input.latestRunSettled && input.latestRun?.sourcePlanRef !== undefined) { const source = input.latestRun.sourcePlanRef; const sourceProjection = input.threads.find( (thread) => thread.id === source.threadId, )?.projection; const plan = sourceProjection?.plans.find( (candidate) => candidate.kind === "proposed_plan" && candidate.id === source.planId, ); if (sourceProjection !== undefined && plan?.kind === "proposed_plan") { return toLatestProposedPlanState(sourceProjection, plan); } } const activeProjection = input.threads.find((thread) => thread.id === input.threadId)?.projection; return findLatestProposedPlan(activeProjection ?? null, input.latestRun?.runId); } export function hasActionableProposedPlan(plan: LatestProposedPlanState | null): boolean { return plan?.status === "active"; } const STANDALONE_V2_ITEM_TYPES = new Set<OrchestrationV2ProjectedTurnItem["item"]["type"]>([ "approval_request", "fork", "handoff", "run_interrupt_request", "run_interrupt_result", "subagent", "thread_created", "user_input_request", ]); const PERSISTENT_RESOURCE_V2_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([ "fork", "subagent", "thread_created", ]); export function timelineEntryIsPersistentResourceCard(entry: TimelineEntry): boolean { return ( entry.kind === "event" && PERSISTENT_RESOURCE_V2_ITEM_TYPES.has(entry.projectedItem.item.type) ); } function projectedItemCreatedAt(row: OrchestrationV2ProjectedTurnItem): string { return DateTime.formatIso(row.item.startedAt ?? row.item.updatedAt); } function projectedWorkEntryStatus( item: OrchestrationV2TurnItem, ): NonNullable<WorkLogEntry["toolLifecycleStatus"]> { switch (item.status) { case "pending": case "running": case "waiting": return "inProgress"; case "completed": return "completed"; case "idle": return "idle"; case "failed": return "failed"; case "cancelled": case "interrupted": return "stopped"; } } function projectedWorkEntryTone(item: OrchestrationV2TurnItem): WorkLogEntry["tone"] { if (item.type === "error") return "info"; if (item.type === "reasoning") return "thinking"; switch (item.type) { case "command_execution": case "file_change": case "file_search": case "web_search": case "dynamic_tool": case "subagent": return "tool"; default: return "info"; } } export function providerErrorPresentation( item: Extract<OrchestrationV2TurnItem, { readonly type: "error" }>, ): { readonly label: string; readonly detail: string } { if (item.retry === undefined) { return { label: item.title?.trim() || "Provider error", detail: item.failure.message, }; } const progress = item.retry.maxAttempts === null