The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
feat(ui): complete the task workspace (#12640)
Dotta39206c009637
diff --git a/ui/src/api/activity.ts b/ui/src/api/activity.tsindex b4d9d2baf8..9f23c8954f 100644--- a/ui/src/api/activity.ts+++ b/ui/src/api/activity.ts@@ -28,6 +28,9 @@ export interface RunForIssue {continuationAttempt?: number;lastUsefulActionAt?: string | null;nextAction?: string | null;+ wakeCommentIds?: string[] | null;+ wakeCommentId?: string | null;+ contextCommentId?: string | null;contextSnapshot?: Record<string, unknown> | null;environment?: {id: string;diff --git a/ui/src/api/heartbeats.ts b/ui/src/api/heartbeats.tsindex 80b4fcb429..3351459d4b 100644--- a/ui/src/api/heartbeats.ts+++ b/ui/src/api/heartbeats.ts@@ -2,6 +2,8 @@ import type {HeartbeatRun,HeartbeatRunEvent,WorkspaceOperation,+ ProviderTraceFrame,+ ProviderTraceMetadata,} from "@paperclipai/shared";import { api } from "./client";@@ -81,18 +83,44 @@ export interface WatchdogDecisionInput {snoozedUntil?: string | null;}+export type RuntimeRequestKind =+ | "runtime"+ | "command_approval"+ | "file_approval"+ | "permission_approval"+ | "user_input"+ | "elicitation";++export type RuntimeRequestResolution =+ | { action: "accept" | "accept_for_session" | "decline" | "cancel" }+ | { action: "submit"; answers: Record<string, { answers: string[] }> }+ | { action: "submit"; content: Record<string, unknown> }+ | { action: "submit"; response: import("@paperclipai/adapter-utils").PaperclipQuestionResponse };+export interface HeartbeatRunListOptions {summary?: boolean;}+export interface ProviderTraceInspection {+ trace: ProviderTraceMetadata | null;+ entries: Array<Record<string, unknown>>;+}+export const heartbeatsApi = {- list: (companyId: string, agentId?: string, limit?: number, options: HeartbeatRunListOptions = {}) => {+ list: (+ companyId: string,+ agentId?: string,+ limit?: number,+ options: HeartbeatRunListOptions = {},+ ) => {const searchParams = new URLSearchParams();if (agentId) searchParams.set("agentId", agentId);if (limit) searchParams.set("limit", String(limit));if (options.summary) searchParams.set("summary", "true");const qs = searchParams.toString();- return api.get<HeartbeatRun[]>(`/companies/${companyId}/heartbeat-runs${qs ? `?${qs}` : ""}`);+ return api.get<HeartbeatRun[]>(+ `/companies/${companyId}/heartbeat-runs${qs ? `?${qs}` : ""}`,+ );},get: (runId: string) => api.get<HeartbeatRun>(`/heartbeat-runs/${runId}`),events: (runId: string, afterSeq = 0, limit = 200) =>@@ -100,16 +128,83 @@ export const heartbeatsApi = {`/heartbeat-runs/${runId}/events?afterSeq=${encodeURIComponent(String(afterSeq))}&limit=${encodeURIComponent(String(limit))}`,),log: (runId: string, offset = 0, limitBytes = 256000) =>- api.get<{ runId: string; store: string; logRef: string; content: string; nextOffset?: number }>(+ api.get<{+ runId: string;+ store: string;+ logRef: string;+ content: string;+ nextOffset?: number;+ }>(`/heartbeat-runs/${runId}/log?offset=${encodeURIComponent(String(offset))}&limitBytes=${encodeURIComponent(String(limitBytes))}`,),workspaceOperations: (runId: string) =>- api.get<WorkspaceOperation[]>(`/heartbeat-runs/${runId}/workspace-operations`),- workspaceOperationLog: (operationId: string, offset = 0, limitBytes = 256000) =>- api.get<{ operationId: string; store: string; logRef: string; content: string; nextOffset?: number }>(+ api.get<WorkspaceOperation[]>(+ `/heartbeat-runs/${runId}/workspace-operations`,+ ),+ providerTrace: (runId: string) =>+ api.get<ProviderTraceInspection>(`/heartbeat-runs/${runId}/provider-trace`),+ providerTraceMetadata: (companyId: string, runIds: string[]) => {+ const params = new URLSearchParams({ runIds: runIds.slice(0, 100).join(",") });+ return api.get<ProviderTraceMetadata[]>(+ `/companies/${companyId}/provider-traces?${params.toString()}`,+ );+ },+ revealProviderTraceFrame: (runId: string, frameId: number) =>+ api.post<ProviderTraceFrame>(+ `/heartbeat-runs/${runId}/provider-trace/frames/${frameId}/reveal`,+ {},+ ),+ deleteProviderTrace: (runId: string) =>+ api.delete<{ ok: true }>(`/heartbeat-runs/${runId}/provider-trace`),+ downloadProviderTrace: async (runId: string): Promise<Blob> => {+ const response = await fetch(+ `/api/heartbeat-runs/${runId}/provider-trace/download`,+ {+ credentials: "include",+ headers: { Accept: "application/x-ndjson" },+ },+ );+ if (!response.ok) {+ const body = (await response.json().catch(() => null)) as {+ error?: string;+ } | null;+ throw new Error(+ body?.error ?? `Trace download failed: ${response.status}`,+ );+ }+ return response.blob();+ },+ workspaceOperationLog: (+ operationId: string,+ offset = 0,+ limitBytes = 256000,+ ) =>+ api.get<{+ operationId: string;+ store: string;+ logRef: string;+ content: string;+ nextOffset?: number;+ }>(`/workspace-operations/${operationId}/log?offset=${encodeURIComponent(String(offset))}&limitBytes=${encodeURIComponent(String(limitBytes))}`,),- cancel: (runId: string) => api.post<void>(`/heartbeat-runs/${runId}/cancel`, {}),+ cancel: (runId: string) =>+ api.post<void>(`/heartbeat-runs/${runId}/cancel`, {}),+ resolveRuntimeRequest: (input: {+ runId: string;+ requestId: string;+ turnId: string;+ requestKind: RuntimeRequestKind;+ resolution: RuntimeRequestResolution;+ }) =>+ api.post<{ accepted: true; commandId: string }>(+ `/heartbeat-runs/${input.runId}/runtime-requests/${encodeURIComponent(input.requestId)}/resolve`,+ {+ turnId: input.turnId,+ requestKind: input.requestKind,+ resolution: input.resolution,+ },+ ),recordWatchdogDecision: (input: WatchdogDecisionInput) =>api.post(`/heartbeat-runs/${input.runId}/watchdog-decisions`, {decision: input.decision,@@ -129,10 +224,13 @@ export const heartbeatsApi = {if (typeof options === "number") {searchParams.set("minCount", String(options));} else if (options) {- if (options.minCount) searchParams.set("minCount", String(options.minCount));+ if (options.minCount)+ searchParams.set("minCount", String(options.minCount));if (options.limit) searchParams.set("limit", String(options.limit));}const qs = searchParams.toString();- return api.get<LiveRunForIssue[]>(`/companies/${companyId}/live-runs${qs ? `?${qs}` : ""}`);+ return api.get<LiveRunForIssue[]>(+ `/companies/${companyId}/live-runs${qs ? `?${qs}` : ""}`,+ );},};diff --git a/ui/src/api/issues.ts b/ui/src/api/issues.tsindex 4f00784fd7..e412614d75 100644--- a/ui/src/api/issues.ts+++ b/ui/src/api/issues.ts@@ -13,6 +13,7 @@ import type {IssueAttachment,IssueCostSummary,IssueComment,+ IssueQueuedCommentQueue,IssueDocument,IssueLabel,IssueRecoveryAction,@@ -237,6 +238,39 @@ export const issuesApi = {const qs = params.toString();return api.get<IssueComment[]>(`/issues/${id}/comments${qs ? `?${qs}` : ""}`);},+ getQueuedComments: (id: string) =>+ api.get<IssueQueuedCommentQueue>(`/issues/${id}/queued-comments`),+ editQueuedComment: (+ id: string,+ commentId: string,+ data: { body: string; queueId: string; revision: string },+ ) =>+ api.patch<IssueQueuedCommentQueue>(+ `/issues/${id}/queued-comments/${commentId}`,+ data,+ ),+ reorderQueuedComments: (+ id: string,+ data: { orderedCommentIds: string[]; queueId: string; revision: string },+ ) => api.put<IssueQueuedCommentQueue>(`/issues/${id}/queued-comments/order`, data),+ steerQueuedComment: (+ id: string,+ commentId: string,+ data: { queueId: string; targetRunId: string; revision: string },+ ) =>+ api.post<IssueQueuedCommentQueue>(+ `/issues/${id}/queued-comments/${commentId}/steer`,+ data,+ ),+ discardQueuedComment: (+ id: string,+ commentId: string,+ data: { queueId: string; revision: string },+ ) =>+ api.delete<IssueQueuedCommentQueue>(+ `/issues/${id}/queued-comments/${commentId}`,+ data,+ ),listInteractions: (id: string) =>api.get<IssueThreadInteraction[]>(`/issues/${id}/interactions`),listAcceptedPlanDecompositions: (id: string) =>@@ -253,6 +287,8 @@ export const issuesApi = {api.post<IssueThreadInteraction>(`/issues/${id}/interactions/${interactionId}/reject`, reason ? { reason } : {}),cancelInteraction: (id: string, interactionId: string, reason?: string) =>api.post<IssueThreadInteraction>(`/issues/${id}/interactions/${interactionId}/cancel`, reason ? { reason } : {}),+ skipInteraction: (id: string, interactionId: string, reason?: string) =>+ api.post<IssueThreadInteraction>(`/issues/${id}/interactions/${interactionId}/skip`, reason ? { reason } : {}),respondToInteraction: (id: string,interactionId: string,diff --git a/ui/src/components/BreadcrumbBar.test.tsx b/ui/src/components/BreadcrumbBar.test.tsxnew file mode 100644index 0000000000..373f742905--- /dev/null+++ b/ui/src/components/BreadcrumbBar.test.tsx@@ -0,0 +1,86 @@+// @vitest-environment jsdom++import { act, useEffect, type ReactNode } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { BreadcrumbProvider, useBreadcrumbs } from "../context/BreadcrumbContext";+import { BreadcrumbBar } from "./BreadcrumbBar";++vi.mock("@/lib/router", () => ({+ Link: ({ children, to }: { children: ReactNode; to: string }) => (+ <a href={to}>{children}</a>+ ),+}));++vi.mock("../context/SidebarContext", () => ({+ useSidebar: () => ({ isMobile: false, toggleSidebar: vi.fn() }),+}));++vi.mock("../context/CompanyContext", () => ({+ useCompany: () => ({ selectedCompanyId: "company-1", selectedCompany: { issuePrefix: "PAP" } }),+}));++vi.mock("@/plugins/slots", () => ({+ usePluginSlots: () => ({ slots: [] }),+ PluginSlotOutlet: () => null,+}));++vi.mock("@/plugins/launchers", () => ({+ usePluginLaunchers: () => ({ launchers: [] }),+ PluginLauncherOutlet: () => null,+}));++function TaskBreadcrumbs({ onOpen }: { onOpen: () => void }) {+ const { setBreadcrumbs, setBreadcrumbToolbar } = useBreadcrumbs();++ useEffect(() => {+ setBreadcrumbs([+ { label: "Tasks", href: "/tasks" },+ { label: "Keep the panel launcher available", identifier: "PAP-16679" },+ ]);+ setBreadcrumbToolbar(+ <button type="button" aria-label="Show task side panel" onClick={onOpen}>+ Show panel+ </button>,+ );+ return () => setBreadcrumbToolbar(null);+ }, [onOpen, setBreadcrumbToolbar, setBreadcrumbs]);++ return <BreadcrumbBar />;+}++describe("BreadcrumbBar", () => {+ let container: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ });++ afterEach(() => {+ act(() => root.unmount());+ container.remove();+ });++ it("renders a page toolbar in the same persistent row as the task breadcrumb", async () => {+ const onOpen = vi.fn();+ await act(async () => {+ root.render(+ <BreadcrumbProvider>+ <TaskBreadcrumbs onOpen={onOpen} />+ </BreadcrumbProvider>,+ );+ });++ const launcher = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Show task side panel"]',+ );+ expect(launcher).not.toBeNull();+ expect(launcher?.closest(".h-12")?.textContent).toContain("PAP-16679");++ act(() => launcher?.click());+ expect(onOpen).toHaveBeenCalledOnce();+ });+});diff --git a/ui/src/components/BreadcrumbBar.tsx b/ui/src/components/BreadcrumbBar.tsxindex 3bb3407efe..b29d24cc89 100644--- a/ui/src/components/BreadcrumbBar.tsx+++ b/ui/src/components/BreadcrumbBar.tsx@@ -12,7 +12,7 @@ import {BreadcrumbPage,BreadcrumbSeparator,} from "@/components/ui/breadcrumb";-import { Fragment, useMemo } from "react";+import { Fragment, useMemo, type ReactNode } from "react";import { PluginSlotOutlet, usePluginSlots } from "@/plugins/slots";import { PluginLauncherOutlet, usePluginLaunchers } from "@/plugins/launchers";@@ -24,11 +24,18 @@ function CrumbIdentifier({ identifier }: { identifier?: string }) {return <span className="shrink-0 font-mono text-muted-foreground">{identifier}</span>;}-function GlobalToolbar({ context }: { context: GlobalToolbarContext }) {+function GlobalToolbar({+ context,+ pageToolbar,+}: {+ context: GlobalToolbarContext;+ pageToolbar?: ReactNode;+}) {const { slots } = usePluginSlots({ slotTypes: ["globalToolbarButton"], companyId: context.companyId });const { launchers } = usePluginLaunchers({ placementZones: ["globalToolbarButton"], companyId: context.companyId, enabled: !!context.companyId });return (<div className="ml-auto flex shrink-0 items-center gap-1 pl-2 empty:hidden">+ {pageToolbar}{slots.length > 0 ? (<PluginSlotOutlet slotTypes={["globalToolbarButton"]} context={context} className="flex items-center gap-1" />) : null}@@ -40,7 +47,7 @@ function GlobalToolbar({ context }: { context: GlobalToolbarContext }) {}export function BreadcrumbBar() {- const { breadcrumbs, mobileToolbar } = useBreadcrumbs();+ const { breadcrumbs, breadcrumbToolbar, mobileToolbar } = useBreadcrumbs();const { toggleSidebar, isMobile } = useSidebar();const { selectedCompanyId, selectedCompany } = useCompany();@@ -52,7 +59,12 @@ export function BreadcrumbBar() {[selectedCompanyId, selectedCompany?.issuePrefix],);- const globalToolbarSlots = <GlobalToolbar context={globalToolbarSlotContext} />;+ const globalToolbarSlots = (+ <GlobalToolbar+ context={globalToolbarSlotContext}+ pageToolbar={isMobile ? null : breadcrumbToolbar}+ />+ );if (isMobile && mobileToolbar) {return (diff --git a/ui/src/components/DocumentAnnotationLayer.test.tsx b/ui/src/components/DocumentAnnotationLayer.test.tsxindex 80c6a010d9..e03dd75a61 100644--- a/ui/src/components/DocumentAnnotationLayer.test.tsx+++ b/ui/src/components/DocumentAnnotationLayer.test.tsx@@ -66,7 +66,7 @@ describe("DocumentAnnotationLayer", () => {vi.clearAllMocks();});- it("uses solid yellow backgrounds for annotation highlights in light and dark themes", async () => {+ it("uses borderless token-driven overlay boxes for annotation highlight states", async () => {const body = document.createElement("div");body.textContent = "Annotated body text.";root = createRoot(container);@@ -97,14 +97,16 @@ describe("DocumentAnnotationLayer", () => {expect(highlights).toHaveLength(4);for (const highlight of highlights) {- const backgroundClasses = Array.from(highlight.classList).filter((className) =>- /^(dark:|hover:|dark:hover:)?bg-yellow-\d+$/.test(className)- || /^(dark:|hover:|dark:hover:)?bg-yellow-\d+\//.test(className),- );- expect(backgroundClasses.some((className) => className.includes("/"))).toBe(false);- expect(backgroundClasses.some((className) => className.startsWith("bg-yellow-"))).toBe(true);- expect(backgroundClasses.some((className) => className.startsWith("dark:bg-yellow-"))).toBe(true);+ expect(highlight.className).toBe("paperclip-doc-annotation-highlight absolute");+ expect(highlight.className).not.toContain("outline");+ expect(highlight.className).not.toContain("shadow");}+ expect(highlights.find((highlight) => highlight.getAttribute("data-thread-id") === "focused")+ ?.getAttribute("data-focused")).toBe("true");+ expect(highlights.find((highlight) => highlight.getAttribute("data-thread-id") === "stale")+ ?.getAttribute("data-anchor-state")).toBe("stale");+ expect(highlights.find((highlight) => highlight.getAttribute("data-thread-id") === "resolved")+ ?.getAttribute("data-status")).toBe("resolved");});it("does not render highlights for text clipped by folded document content", async () => {@@ -241,7 +243,7 @@ describe("DocumentAnnotationLayer", () => {}});- it("uses native CSS highlights for visual paint when the browser supports them", async () => {+ it("keeps native CSS highlight ranges synchronized while using the overlay for visual paint", async () => {const originalCss = globalThis.CSS;const originalHighlight = (globalThis as { Highlight?: unknown }).Highlight;const setHighlight = vi.fn();@@ -284,7 +286,7 @@ describe("DocumentAnnotationLayer", () => {await new Promise((resolve) => window.requestAnimationFrame(resolve));});- expect(container.querySelector(".paperclip-doc-annotation-highlight")).toBeNull();+ expect(container.querySelector(".paperclip-doc-annotation-highlight")).not.toBeNull();expect(container.querySelector(".paperclip-doc-annotation-hit-target")).not.toBeNull();const openHighlightCall = setHighlight.mock.calls.find(([name]) => name === "paperclip-doc-annotation-open");expect(openHighlightCall).toBeTruthy();diff --git a/ui/src/components/DocumentAnnotationLayer.tsx b/ui/src/components/DocumentAnnotationLayer.tsxindex c149f7e013..45f384dbea 100644--- a/ui/src/components/DocumentAnnotationLayer.tsx+++ b/ui/src/components/DocumentAnnotationLayer.tsx@@ -263,7 +263,6 @@ export function DocumentAnnotationLayer({() => `document-annotation-${reactId.replace(/[^a-zA-Z0-9_-]/g, "")}`,[reactId],);- const nativeHighlightsSupported = getNativeHighlightApi() !== null;const selectionDebugEnabled = isSelectionDebugEnabled();if (selectionDebugEnabled) initializeSelectionDebug();@@ -503,43 +502,31 @@ export function DocumentAnnotationLayer({const content = (<>- {!nativeHighlightsSupported ? (- <div className="paperclip-doc-annotation-visual-layer pointer-events-none absolute inset-0 z-0" aria-hidden="true">- <div className="relative h-full w-full">- {highlightRects.map((rect, index) => {- const isFocused = rect.focused;- const isStale = rect.anchorState === "stale";- const isResolved = rect.status === "resolved";- return (- <span- key={`visual-${rect.threadId}-${index}`}- data-thread-id={rect.threadId}- data-anchor-state={rect.anchorState}- data-status={rect.status}- data-focused={isFocused || undefined}- className={cn(- "paperclip-doc-annotation-highlight absolute rounded-none transition-colors",- // base box treatment (replaces the previous baseline border)- isResolved- ? "bg-yellow-100 outline outline-1 outline-dashed outline-offset-0 outline-yellow-700/45 dark:bg-yellow-700 dark:outline-yellow-200/45"- : isStale- ? "bg-yellow-200 outline outline-2 outline-dashed outline-offset-0 outline-yellow-700/65 dark:bg-yellow-600 dark:outline-yellow-200/70"- : isFocused- ? "bg-yellow-300 outline outline-2 outline-offset-0 outline-yellow-700/85 shadow-(--shadow-extract-6) dark:bg-yellow-500 dark:outline-yellow-200/85"- : "bg-yellow-200 dark:bg-yellow-600",- )}- style={{- top: rect.top,- left: rect.left,- width: rect.width,- height: rect.height,- }}- />- );- })}- </div>+ <div className="paperclip-doc-annotation-visual-layer pointer-events-none absolute inset-0 z-0" aria-hidden="true">+ <div className="relative h-full w-full">+ {highlightRects.map((rect, index) => {+ const isFocused = rect.focused;+ const isHovered = rect.threadId === hoveredThreadId;+ return (+ <span+ key={`visual-${rect.threadId}-${index}`}+ data-thread-id={rect.threadId}+ data-anchor-state={rect.anchorState}+ data-status={rect.status}+ data-focused={isFocused || undefined}+ data-hovered={isHovered || undefined}+ className="paperclip-doc-annotation-highlight absolute"+ style={{+ top: rect.top,+ left: rect.left,+ width: rect.width,+ height: rect.height,+ }}+ />+ );+ })}</div>- ) : null}+ </div><divclassName="paperclip-doc-annotation-layer pointer-events-none absolute inset-0 z-(--z-2)"aria-hidden="true"@@ -561,8 +548,6 @@ export function DocumentAnnotationLayer({aria-label="Open annotation thread"className={cn("paperclip-doc-annotation-hit-target pointer-events-auto absolute cursor-pointer rounded-none bg-transparent transition-colors",- // Tint the run on hover so it's obvious which highlight you're over.- isHovered && "bg-amber-400/40 dark:bg-amber-300/30",isFocused && "ring-1 ring-transparent",)}style={{diff --git a/ui/src/components/FileViewerSheet.tsx b/ui/src/components/FileViewerSheet.tsxindex 79a6d64200..3d742ad013 100644--- a/ui/src/components/FileViewerSheet.tsx+++ b/ui/src/components/FileViewerSheet.tsx@@ -936,7 +936,7 @@ interface FileViewerBodyProps {onFallbackToProject: null | (() => void);}-function FileViewerBody({+export function FileViewerBody({resolveQuery,contentQuery,elapsedMs,diff --git a/ui/src/components/IssueChatThread.tsx b/ui/src/components/IssueChatThread.tsxindex cf4b0baf8e..50a9e492fb 100644--- a/ui/src/components/IssueChatThread.tsx+++ b/ui/src/components/IssueChatThread.tsx@@ -36,12 +36,15 @@ import type {FeedbackVote,FeedbackVoteValue,IssueAttachment,+ IssueDocumentSummary,IssueBlockerAttention,IssueRecoveryAction,+ IssueQueuedCommentQueue,IssueRelationIssueSummary,IssueScheduledRetry,SuccessfulRunHandoffState,IssueWorkMode,+ IssueWorkProduct,} from "@paperclipai/shared";import type { ActiveRunForIssue, LiveRunForIssue } from "../api/heartbeats";import { findUIAdapter } from "../adapters/registry";@@ -234,6 +237,8 @@ interface IssueChatMessageContext {onCancelInteraction?: (interaction: AskUserQuestionsInteraction,) => Promise<void> | void;+ /** New task-view composer takeover action. The classic thread does not render it. */+ onSkipInteraction?: (interaction: IssueThreadInteraction) => Promise<void> | void;onSubmitInteractionVerdicts?: (interaction: RequestItemVerdictsInteraction,verdicts: { id: string; verdict: RequestItemVerdictValue; reason?: string }[],@@ -435,6 +440,10 @@ interface IssueChatComposerProps {interface IssueChatThreadProps {comments: IssueChatComment[];interactions?: IssueThreadInteraction[];+ /** App-authoritative resources interleaved by the default task thread. */+ documents?: IssueDocumentSummary[];+ workProducts?: IssueWorkProduct[];+ attachments?: IssueAttachment[];feedbackVotes?: FeedbackVote[];feedbackDataSharingPreference?: FeedbackDataSharingPreference;feedbackTermsUrl?: string | null;@@ -480,6 +489,9 @@ interface IssueChatThreadProps {/** Resume a paused assignee agent so runs can start again. */onResumeAssignee?: () => Promise<void> | void;resumeAssigneePending?: boolean;+ /** Requeues a blocked task after its no-live-execution-path recovery notice. */+ onTryAgainNoLiveExecutionPath?: () => Promise<void> | void;+ tryAgainNoLiveExecutionPathPending?: boolean;companyId?: string | null;projectId?: string | null;issueStatus?: string;@@ -536,6 +548,12 @@ interface IssueChatThreadProps {includeSucceededRunsWithoutOutput?: boolean;onInterruptQueued?: (runId: string) => Promise<void>;onCancelQueued?: (commentId: string) => void;+ /** Authoritative PRP queue. The classic thread intentionally ignores it. */+ queuedCommentQueue?: IssueQueuedCommentQueue | null;+ onEditQueuedComment?: (commentId: string, body: string, revision: string) => Promise<void>;+ onReorderQueuedComments?: (orderedCommentIds: string[], revision: string) => Promise<void>;+ onSteerQueuedComment?: (commentId: string, revision: string) => Promise<void>;+ onDiscardQueuedComment?: (commentId: string, revision: string) => Promise<void>;onDeleteComment?: (commentId: string) => Promise<void> | void;interruptingQueuedRunId?: string | null;stoppingRunId?: string | null;@@ -562,6 +580,8 @@ interface IssueChatThreadProps {onCancelInteraction?: (interaction: AskUserQuestionsInteraction,) => Promise<void> | void;+ /** New task-view composer takeover action. The classic thread does not render it. */+ onSkipInteraction?: (interaction: IssueThreadInteraction) => Promise<void> | void;onSubmitInteractionVerdicts?: (interaction: RequestItemVerdictsInteraction,verdicts: { id: string; verdict: RequestItemVerdictValue; reason?: string }[],@@ -1343,7 +1363,7 @@ function CopyablePreBlock({ children, className }: { children: string; className}const TOOL_ICON_MAP: Record<string, React.ComponentType<{ className?: string }>> = {- // Extend with specific tool icons as they become known+ paperclip_provider_activity: ClipboardList,};function getToolIcon(toolName: string): React.ComponentType<{ className?: string }> {@@ -1364,6 +1384,9 @@ function IssueChatToolPart({isError?: boolean;}) {const [open, setOpen] = useState(false);+ if (toolName === "paperclip_provider_activity") {+ return <IssueChatProviderActivity args={args} running={result === undefined} open={open} onToggle={() => setOpen((current) => !current)} />;+ }const rawArgsText = argsText ?? "";const parsedArgs = args ?? parseToolPayload(rawArgsText);const resultText =@@ -1452,6 +1475,51 @@ function IssueChatToolPart({);}+function IssueChatProviderActivity({+ args,+ running,+ open,+ onToggle,+}: {+ args: unknown;+ running: boolean;+ open: boolean;+ onToggle: () => void;+}) {+ const value = typeof args === "object" && args !== null && !Array.isArray(args) ? args as Record<string, unknown> : {};+ const payload = typeof value.payload === "object" && value.payload !== null && !Array.isArray(value.payload) ? value.payload as Record<string, unknown> : {};+ const title = typeof value.title === "string" ? value.title : "Provider activity";+ const summary = typeof value.summary === "string" ? value.summary : "";+ const steps = Array.isArray(payload.steps) ? payload.steps.slice(0, 256) : [];+ const children = Array.isArray(payload.children) ? payload.children.slice(0, 64) : [];+ const sources = Array.isArray(payload.sources) ? payload.sources.slice(0, 64) : [];+ const output = typeof payload.output === "string" ? payload.output.slice(-(8 * 1024)) : "";+ const effectiveModel = typeof payload.effectiveModel === "string" ? payload.effectiveModel : null;+ const requestedModel = typeof payload.requestedModel === "string" ? payload.requestedModel : null;+ const hasDetails = steps.length > 0 || children.length > 0 || sources.length > 0 || output.length > 0 || effectiveModel !== null;+ return (+ <div className="flex gap-2 px-1" data-provider-family={String(value.family ?? "unknown")}>+ <div className="pt-1"><ClipboardList className="h-3.5 w-3.5 text-muted-foreground/50" /></div>+ <div className="min-w-0 flex-1">+ <button type="button" className="flex w-full items-center gap-2 rounded-md py-0.5 text-left hover:bg-accent/5" onClick={onToggle} aria-expanded={open}>+ <span className="min-w-0 flex-1 truncate text-(length:--text-compact) text-muted-foreground/80">{title}{summary ? <span className="ml-1.5 text-muted-foreground/50">{summary}</span> : null}</span>+ {running ? <Loader2 className="h-3 w-3 animate-spin text-muted-foreground/50" /> : null}+ {hasDetails ? <ChevronDown className={cn("h-3.5 w-3.5 text-muted-foreground/40 transition-transform", open && "rotate-180")} /> : null}+ </button>+ {open && hasDetails ? (+ <div className="mt-1 space-y-2 rounded-md border border-border/50 bg-accent/15 p-2 text-xs">+ {steps.map((entry, index) => { const step = typeof entry === "object" && entry !== null ? entry as Record<string, unknown> : {}; return <div key={String(step.stepId ?? index)} className="flex gap-2"><span aria-hidden>{step.status === "completed" ? "✓" : step.status === "blocked" ? "!" : "○"}</span><span>{String(step.body ?? "")}</span></div>; })}+ {children.map((entry, index) => { const child = typeof entry === "object" && entry !== null ? entry as Record<string, unknown> : {}; return <div key={String(child.childId ?? index)}><span className="font-medium">{String(child.role ?? "Child agent")}</span> · {String(child.status ?? "unknown")}{child.summary ? ` — ${String(child.summary)}` : ""}</div>; })}+ {sources.map((entry, index) => { const source = typeof entry === "object" && entry !== null ? entry as Record<string, unknown> : {}; const href = typeof source.url === "string" && /^https?:\/\//.test(source.url) ? source.url : null; return <div key={String(source.sourceId ?? index)}>{href ? <a href={href} target="_blank" rel="noreferrer" className="underline">{String(source.title ?? href)}</a> : <span>{String(source.title ?? "Unavailable source")}</span>} <span className="text-muted-foreground">(provider-reported)</span></div>; })}+ {effectiveModel ? <div><span className="text-muted-foreground">Model</span> {requestedModel && requestedModel !== effectiveModel ? `${requestedModel} → ` : ""}{effectiveModel}</div> : null}+ {output ? <CopyablePreBlock className="max-h-56 overflow-auto whitespace-pre-wrap rounded bg-background/70 p-2 font-mono text-(length:--text-micro)">{output}</CopyablePreBlock> : null}+ </div>+ ) : null}+ </div>+ </div>+ );+}+function getThreadMessageCopyText(message: ThreadMessage) {return message.content.filter((part): part is TextMessagePart => part.type === "text")@@ -4525,6 +4593,8 @@ export function IssueChatThread({resumeFromBacklogPending = false,onResumeAssignee,resumeAssigneePending = false,+ onTryAgainNoLiveExecutionPath: _onTryAgainNoLiveExecutionPath,+ tryAgainNoLiveExecutionPathPending: _tryAgainNoLiveExecutionPathPending,externalReferences,linkCaseReferences = false,}: IssueChatThreadProps) {diff --git a/ui/src/components/IssueProperties.test.tsx b/ui/src/components/IssueProperties.test.tsxindex 702154a54c..bacdee29f3 100644--- a/ui/src/components/IssueProperties.test.tsx+++ b/ui/src/components/IssueProperties.test.tsx@@ -505,18 +505,11 @@ describe("IssueProperties", () => {document.body.innerHTML = "";});- it("keeps the Plan tab visible for a planning-mode issue without a plan document", async () => {+ it("does not show a Plan tab for a planning-mode issue without a plan document", async () => {mockInstanceSettingsApi.getExperimental.mockResolvedValue({enableTaskWatchdogs: false,enableClassicTaskInterface: false,});- mockIssuesApi.listInteractions.mockResolvedValue([- {- kind: "request_confirmation",- status: "pending",- payload: { target: { type: "issue_document", key: "plan" } },- },- ]);const root = renderProperties(container, {issue: createIssue({ workMode: "planning" }),childIssues: [],@@ -525,18 +518,8 @@ describe("IssueProperties", () => {});await waitForAssertion(() => {- expect(Array.from(container.querySelectorAll("button")).some((button) => button.textContent === "Plan")).toBe(true);- });-- const planTab = Array.from(container.querySelectorAll("button")).find((button) => button.textContent === "Plan");- await act(async () => {- // Radix Tabs triggers select on mousedown (button 0), not on click.- planTab!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));- });-- await waitForAssertion(() => {- expect(container.textContent).toContain("This task is in plan mode but no plan document has been written yet.");- expect(container.textContent).toContain("A plan confirmation is pending, but the plan document it should confirm is missing.");+ expect(Array.from(container.querySelectorAll("button")).some((button) => button.textContent === "Plan")).toBe(false);+ expect(container.textContent).not.toContain("This task is in plan mode but no plan document has been written yet.");});act(() => root.unmount());diff --git a/ui/src/components/PropertiesPanel.test.tsx b/ui/src/components/PropertiesPanel.test.tsxindex 7a85b1b27a..ca24f9cd4d 100644--- a/ui/src/components/PropertiesPanel.test.tsx+++ b/ui/src/components/PropertiesPanel.test.tsx@@ -4,6 +4,7 @@ import { flushSync } from "react-dom";import { createRoot, type Root } from "react-dom/client";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { TooltipProvider } from "@/components/ui/tooltip";import { PropertiesPanel } from "./PropertiesPanel";const mockInstanceSettingsApi = vi.hoisted(() => ({@@ -16,16 +17,19 @@ vi.mock("@/api/instanceSettings", () => ({const mockPanelState = vi.hoisted(() => ({panelContent: null as unknown,+ panelContentMode: "padded" as const,panelVisible: true,}));+const mockSetPanelVisible = vi.hoisted(() => vi.fn());vi.mock("../context/PanelContext", () => ({usePanel: () => ({panelContent: mockPanelState.panelContent,+ panelContentMode: mockPanelState.panelContentMode,panelVisible: mockPanelState.panelVisible,openPanel: vi.fn(),closePanel: vi.fn(),- setPanelVisible: vi.fn(),+ setPanelVisible: mockSetPanelVisible,togglePanelVisible: vi.fn(),}),}));@@ -50,7 +54,9 @@ describe("PropertiesPanel", () => {flushSync(() => {root!.render(<QueryClientProvider client={queryClient}>- <PropertiesPanel />+ <TooltipProvider>+ <PropertiesPanel />+ </TooltipProvider></QueryClientProvider>,);});@@ -61,6 +67,7 @@ describe("PropertiesPanel", () => {container = document.createElement("div");document.body.appendChild(container);window.localStorage.clear();+ mockSetPanelVisible.mockClear();});afterEach(() => {@@ -85,7 +92,7 @@ describe("PropertiesPanel", () => {expect(aside).not.toBeNull();expect(aside!.style.width).toBe("320px");expect(aside!.querySelector('[role="separator"]')).toBeNull();- expect(container.querySelector('[aria-label="Maximize panel"]')).toBeNull();+ expect(container.querySelector('[aria-label="Maximize side panel"]')).toBeNull();// Inner wrapper keeps the hardcoded width classes exactly as today.expect(aside!.querySelector(".w-80")).not.toBeNull();});@@ -111,12 +118,24 @@ describe("PropertiesPanel", () => {expect(aside).not.toBeNull();expect(aside!.style.width).toBe("322px");expect(aside!.querySelector('[role="separator"][aria-label="Resize panel"]')).not.toBeNull();- expect(container.querySelector('[aria-label="Maximize panel"]')).not.toBeNull();+ expect(container.querySelector('[aria-label="Maximize side panel"]')).not.toBeNull();const inner = aside!.querySelector<HTMLDivElement>(":scope > div:not([role])");expect(inner!.style.width).toBe("322px");expect(inner!.style.minWidth).toBe("322px");});+ it("uses the pressed side-panel toggle instead of an X to hide the open pane", async () => {+ await renderPanel();+ const toggle = container.querySelector<HTMLButtonElement>('[aria-label="Toggle side panel"]');+ expect(toggle).not.toBeNull();+ expect(toggle!.getAttribute("aria-pressed")).toBe("true");+ expect(toggle!.querySelector(".lucide-panel-right-close")).not.toBeNull();+ expect(container.querySelector('[aria-label="Hide side panel"]')).toBeNull();++ toggle!.click();+ expect(mockSetPanelVisible).toHaveBeenCalledWith(false);+ });+it("restores a remembered width from localStorage (clamped to the minimum)", async () => {window.localStorage.setItem("taskChatRedesign.propertiesPaneWidth", "300");await renderPanel();diff --git a/ui/src/components/PropertiesPanel.tsx b/ui/src/components/PropertiesPanel.tsxindex 6a0e684a44..777d2d9174 100644--- a/ui/src/components/PropertiesPanel.tsx+++ b/ui/src/components/PropertiesPanel.tsx@@ -1,13 +1,14 @@import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";-import { Maximize2, Minimize2, X } from "lucide-react";+import { X } from "lucide-react";import { usePanel } from "../context/PanelContext";import { useClassicTaskInterfaceEnabled } from "../hooks/useClassicTaskInterfaceEnabled";import { cn } from "../lib/utils";import { Button } from "@/components/ui/button";import { ScrollArea } from "@/components/ui/scroll-area";+import { SidePanelFrame, SidePanelWindowControls } from "@/components/side-panel";export function PropertiesPanel() {- const { panelContent, panelVisible, setPanelVisible } = usePanel();+ const { panelContent, panelContentMode, panelVisible, setPanelVisible } = usePanel();const { enabled: classicTaskInterfaceEnabled } = useClassicTaskInterfaceEnabled();if (!panelContent) return null;@@ -36,6 +37,7 @@ export function PropertiesPanel() {return (<ResizablePropertiesPanelpanelContent={panelContent}+ panelContentMode={panelContentMode}panelVisible={panelVisible}setPanelVisible={setPanelVisible}/>@@ -129,12 +131,14 @@ interface FixedPane {interface ResizablePropertiesPanelProps {panelContent: ReactNode;+ panelContentMode: "padded" | "prose" | "full-bleed";panelVisible: boolean;setPanelVisible: (visible: boolean) => void;}function ResizablePropertiesPanel({panelContent,+ panelContentMode,panelVisible,setPanelVisible,}: ResizablePropertiesPanelProps) {@@ -353,45 +357,40 @@ function ResizablePropertiesPanel({className={cn("flex-1 flex flex-col min-h-0", isFixed && "w-full")}style={isFixed ? undefined : { width, minWidth: width }}>- {/* The slot hosts whatever IssueProperties portals in — the tab strip- when Plan/Artifacts have content, else a plain "Properties" title;- window controls sit right. Vertical padding lives on the controls- cluster, not the bar, so the tab strip can stretch to the border- and its active underline hugs the header's bottom line. */}- <div className="flex items-center justify-between gap-2 px-4 border-b border-border">- <div- id={PROPERTIES_PANE_HEADER_SLOT_ID}- className="flex min-w-0 flex-1 items-center self-stretch"- />- <div className="flex items-center gap-1 py-2">- <Button- variant="ghost"- size="icon-xs"- className="size-7"- title={maximized ? "Restore panel" : "Maximize panel"}- aria-label={maximized ? "Restore panel" : "Maximize panel"}- onClick={maximized ? handleRestore : handleMaximize}- >- {maximized ? (- <Minimize2 className="h-3.5 w-3.5" />- ) : (- <Maximize2 className="h-3.5 w-3.5" />- )}- </Button>- <Button variant="ghost" size="icon-xs" onClick={() => setPanelVisible(false)}>- <X className="h-4 w-4" />- </Button>- </div>- </div>- <ScrollArea className="flex-1">- <div- className={cn("p-4", maximized && "mx-auto w-full px-9")}- style={maximized ? { maxWidth: MAXIMIZED_CONTENT_MAX_WIDTH } : undefined}- >- {panelContent}- </div>- </ScrollArea>- <div id={PROPERTIES_PANE_FOOTER_SLOT_ID} className="shrink-0" />+ <SidePanelFrame+ presentation="docked"+ maximized={maximized}+ contentMode="full-bleed"+ className="flex-1 border-l-0"+ header={(+ <div+ id={PROPERTIES_PANE_HEADER_SLOT_ID}+ className="flex min-w-0 flex-1 items-center self-stretch"+ />+ )}+ trailingControls={(+ <SidePanelWindowControls+ maximized={maximized}+ onMaximizedChange={(next) => {+ if (next) handleMaximize();+ else handleRestore();+ }}+ onToggle={() => setPanelVisible(false)}+ />+ )}+ footer={<div id={PROPERTIES_PANE_FOOTER_SLOT_ID} />}+ >+ {panelContentMode === "full-bleed" ? panelContent : (+ <ScrollArea className="h-full">+ <div+ className={cn("p-4", maximized && "mx-auto w-full px-9")}+ style={maximized ? { maxWidth: MAXIMIZED_CONTENT_MAX_WIDTH } : undefined}+ >+ {panelContent}+ </div>+ </ScrollArea>+ )}+ </SidePanelFrame></div></aside></>diff --git a/ui/src/components/TaskChatThread.test.tsx b/ui/src/components/TaskChatThread.test.tsxindex 9bf7a13e97..0d37f90ca7 100644--- a/ui/src/components/TaskChatThread.test.tsx+++ b/ui/src/components/TaskChatThread.test.tsx@@ -1,17 +1,32 @@// @vitest-environment jsdomimport type { ReactElement } from "react";-import { forwardRef, useImperativeHandle, type ForwardedRef } from "react";+import { act, forwardRef, useImperativeHandle, type ForwardedRef } from "react";import { flushSync } from "react-dom";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { ThemeProvider } from "@/context/ThemeContext";import { TaskChatThread } from "./TaskChatThread";+import type {+ IssueDocument,+ IssueQueuedCommentQueue,+ IssueThreadInteraction,+} from "@paperclipai/shared";+import { heartbeatsApi } from "@/api/heartbeats";const transcriptState = vi.hoisted(() => ({ transcriptByRun: new Map() }));const nativeTranscriptState = vi.hoisted(() => ({ transcriptByRun: new Map() }));const transcriptHookRuns = vi.hoisted(() => ({ legacy: [] as unknown[][], native: [] as unknown[][] }));const sidebarState = vi.hoisted(() => ({ isMobile: false }));+const planState = vi.hoisted(() => ({ data: null as IssueDocument | null }));+const DIRECT_ADAPTER_TYPES = [+ "codex_local",+ "claude_local",+ "opencode_local",+ "process",+ "http",+ "custom_plugin",+] as const;vi.mock("@/components/transcript/useLiveRunTranscripts", () => ({useLiveRunTranscripts: ({ runs }: { runs: unknown[] }) => {@@ -29,11 +44,20 @@ vi.mock("@/context/SidebarContext", () => ({useSidebar: () => ({ isMobile: sidebarState.isMobile }),}));vi.mock("@/hooks/useIssuePlanDocument", () => ({- useIssuePlanDocument: () => ({ data: null }),+ useIssuePlanDocument: () => planState,}));vi.mock("@/lib/router", () => ({- Link: ({ to, children, ...props }: { to: string; children: React.ReactNode }) => (- <a href={to} {...props}>{children}</a>+ Link: ({+ to,+ children,+ ...props+ }: {+ to: string;+ children: React.ReactNode;+ }) => (+ <a href={to} {...props}>+ {children}+ </a>),}));vi.mock("@/components/MarkdownEditor", () => ({@@ -41,7 +65,10 @@ vi.mock("@/components/MarkdownEditor", () => ({{ value }: { value: string },ref: ForwardedRef<unknown>,) {- useImperativeHandle(ref, () => ({ insertMarkdown: () => {}, focus: () => {} }));+ useImperativeHandle(ref, () => ({+ insertMarkdown: () => {},+ focus: () => {},+ }));return <div data-testid="mock-editor">{value}</div>;}),}));@@ -56,6 +83,7 @@ beforeEach(() => {transcriptHookRuns.legacy.length = 0;transcriptHookRuns.native.length = 0;sidebarState.isMobile = false;+ planState.data = null;container = document.createElement("div");document.body.appendChild(container);root = createRoot(container);@@ -66,6 +94,7 @@ afterEach(() => {root = null;container.remove();localStorage.clear();+ vi.restoreAllMocks();});function render(ui: ReactElement) {@@ -77,8 +106,14 @@ function fakeScrollGeometry({ scrollHeight = 1000, clientHeight = 400, scrollTop = 600 } = {},) {let currentScrollTop = scrollTop;- Object.defineProperty(element, "scrollHeight", { value: scrollHeight, configurable: true });- Object.defineProperty(element, "clientHeight", { value: clientHeight, configurable: true });+ Object.defineProperty(element, "scrollHeight", {+ value: scrollHeight,+ configurable: true,+ });+ Object.defineProperty(element, "clientHeight", {+ value: clientHeight,+ configurable: true,+ });Object.defineProperty(element, "scrollTop", {get: () => currentScrollTop,set: (value: number) => {@@ -88,28 +123,189 @@ function fakeScrollGeometry(});}+function planDocument(overrides: Partial<IssueDocument> = {}): IssueDocument {+ return {+ id: "document-plan",+ companyId: "company-1",+ issueId: "issue-1",+ key: "plan",+ title: "Plan",+ format: "markdown",+ body: "# Preview the Plan\n- Reuse the review card.\n- Stream live steps.\n- Reconcile the revision.",+ latestRevisionId: "revision-3",+ latestRevisionNumber: 3,+ createdByAgentId: "agent-1",+ createdByUserId: null,+ updatedByAgentId: "agent-1",+ updatedByUserId: null,+ lockedAt: null,+ lockedByAgentId: null,+ lockedByUserId: null,+ createdAt: new Date("2026-08-23T10:00:00.000Z"),+ updatedAt: new Date("2026-08-23T10:01:00.000Z"),+ ...overrides,+ };+}++function planReviewInteraction(+ status: "pending" | "accepted" | "expired" = "pending",+ revisionId = "revision-3",+ sourceRunId: string | null = "run-plan",+): IssueThreadInteraction {+ const isResolved = status !== "pending";+ return {+ id: "plan-review",+ companyId: "company-1",+ issueId: "issue-1",+ kind: "request_confirmation",+ title: "Review the Plan",+ summary: null,+ status,+ continuationPolicy: "wake_assignee",+ resolverPolicy: "anyone",+ requestedResolverPolicy: "anyone",+ effectiveResolverPolicy: "anyone",+ resolverPolicyProvenance: "inherited",+ effectiveResolverPolicySource: "requested",+ legacyResolverPolicyAliases: {+ requested: "board_or_agents",+ effective: "board_or_agents",+ },+ createdByAgentId: "agent-1",+ createdByUserId: null,+ sourceRunId,+ resolvedByAgentId: null,+ resolvedByUserId: isResolved ? "user-1" : null,+ createdAt: new Date("2026-08-23T10:01:01.000Z"),+ updatedAt: new Date("2026-08-23T10:01:01.000Z"),+ resolvedAt: isResolved ? new Date("2026-08-23T10:02:00.000Z") : null,+ payload: {+ version: 1,+ prompt: "Approve this Plan?",+ target: {+ type: "issue_document",+ issueId: "issue-1",+ documentId: "document-plan",+ key: "plan",+ revisionId,+ revisionNumber: 3,+ label: "Plan revision 3",+ },+ },+ result:+ status === "accepted"+ ? { outcome: "accepted" }+ : status === "expired"+ ? {+ outcome: "superseded_by_comment",+ commentId: "follow-up-comment",+ }+ : null,+ } as IssueThreadInteraction;+}++function questionInteraction(+ id: string,+ prompt: string,+ createdAt: string,+): IssueThreadInteraction {+ return {+ id,+ companyId: "company-1",+ issueId: "issue-1",+ kind: "ask_user_questions",+ title: prompt,+ status: "pending",+ continuationPolicy: "wake_assignee",+ resolverPolicy: "anyone",+ requestedResolverPolicy: "anyone",+ effectiveResolverPolicy: "anyone",+ resolverPolicyProvenance: "inherited",+ effectiveResolverPolicySource: "requested",+ legacyResolverPolicyAliases: {+ requested: "board_or_agents",+ effective: "board_or_agents",+ },+ createdByAgentId: "agent-1",+ createdByUserId: null,+ resolvedByAgentId: null,+ resolvedByUserId: null,+ createdAt: new Date(createdAt),+ updatedAt: new Date(createdAt),+ resolvedAt: null,+ payload: {+ version: 1,+ questions: [+ {+ id: `${id}-question`,+ prompt,+ selectionMode: "single",+ required: true,+ options: [+ { id: "yes", label: "Yes" },+ { id: "no", label: "No" },+ ],+ },+ ],+ },+ result: null,+ } as IssueThreadInteraction;+}+describe("TaskChatThread draft pass-through", () => {+ it("aligns the desktop thread header with the side-panel tab row", () => {+ render(+ <TaskChatThread+ comments={[+ {+ id: "comment-1",+ companyId: "company-1",+ issueId: "issue-1",+ authorType: "user",+ authorAgentId: null,+ authorUserId: "user-1",+ body: "Header alignment fixture.",+ presentation: null,+ metadata: null,+ createdAt: new Date("2026-08-15T12:00:00.000Z"),+ updatedAt: new Date("2026-08-15T12:00:00.000Z"),+ },+ ]}+ onAdd={async () => {}}+ />,+ );++ const scroller = container.querySelector(+ '[data-testid="task-chat-scroller"]',+ );+ expect(scroller?.firstElementChild?.classList).toContain("pt-3");+ });+it("keeps the composer dock aligned with the thread's horizontal padding", () => {render(<TaskChatThread- comments={[{- id: "comment-1",- companyId: "company-1",- issueId: "issue-1",- authorType: "user",- authorAgentId: null,- authorUserId: "user-1",- body: "Waiting for the dependency.",- presentation: null,- metadata: null,- createdAt: new Date("2026-08-15T12:00:00.000Z"),- updatedAt: new Date("2026-08-15T12:00:00.000Z"),- }]}+ comments={[+ {+ id: "comment-1",+ companyId: "company-1",+ issueId: "issue-1",+ authorType: "user",+ authorAgentId: null,+ authorUserId: "user-1",+ body: "Waiting for the dependency.",+ presentation: null,+ metadata: null,+ createdAt: new Date("2026-08-15T12:00:00.000Z"),+ updatedAt: new Date("2026-08-15T12:00:00.000Z"),+ },+ ]}onAdd={async () => {}}/>,);- const dock = container.querySelector('[data-testid="task-chat-composer-dock"]');+ const dock = container.querySelector(+ '[data-testid="task-chat-composer-dock"]',+ );expect(dock?.classList).toContain("px-4");expect(dock?.classList).not.toContain("px-1");});@@ -125,8 +321,30 @@ describe("TaskChatThread draft pass-through", () => {/>,);- expect(container.querySelector('[data-testid="mock-editor"]')?.textContent)- .toBe("half-written thought");+ expect(+ container.querySelector('[data-testid="mock-editor"]')?.textContent,+ ).toBe("half-written thought");+ });++ it("forwards human profiles to the selected composer assignee", () => {+ render(+ <TaskChatThread+ comments={[]}+ onAdd={async () => {}}+ enableReassign+ reassignOptions={[{ id: "user:user-1", label: "Riley Board" }]}+ currentAssigneeValue="user:user-1"+ userProfileMap={+ new Map([+ ["user-1", { label: "Riley Board", image: "/riley-avatar.png" }],+ ])+ }+ />,+ );++ expect(+ container.querySelector('[data-assignee-trigger-avatar="user-1"]'),+ ).not.toBeNull();});});@@ -146,22 +364,24 @@ describe("TaskChatThread runtime transcript selection", () => {createdAt: "2026-08-25T18:00:00.000Z",startedAt: "2026-08-25T18:00:00.000Z",},- {- runId: "legacy-run",- runtimeMode: "legacy",+ ...DIRECT_ADAPTER_TYPES.map((adapterType, index) => ({+ runId: `legacy-run-${index}`,+ runtimeMode: "legacy" as const,status: "succeeded",- agentId: "agent-2",- adapterType: "codex_local",- createdAt: "2026-08-25T18:01:00.000Z",- startedAt: "2026-08-25T18:01:00.000Z",- },+ agentId: `agent-${index + 2}`,+ adapterType,+ createdAt: `2026-08-25T18:0${index + 1}:00.000Z`,+ startedAt: `2026-08-25T18:0${index + 1}:00.000Z`,+ })),]}/>,);const legacyRuns = transcriptHookRuns.legacy.at(-1) as Array<{ id: string }>;const nativeRuns = transcriptHookRuns.native.at(-1) as Array<{ id: string }>;- expect(legacyRuns.map((run) => run.id)).toEqual(["legacy-run"]);+ expect(legacyRuns.map((run) => run.id)).toEqual(+ DIRECT_ADAPTER_TYPES.map((_, index) => `legacy-run-${index}`),+ );expect(nativeRuns.map((run) => run.id)).toEqual(["native-run"]);});@@ -264,7 +484,7 @@ describe("TaskChatThread runtime transcript selection", () => {/>,);- expect(container.querySelector('[data-testid="task-chat-progress-update"]')?.textContent)+ expect(container.querySelector('[data-testid="task-chat-phase-interstitial"]')?.textContent).toContain("Persisted before message channels existed.");expect(container.querySelector('[data-testid="task-chat-final-response"]')).toBeNull();@@ -277,7 +497,7 @@ describe("TaskChatThread runtime transcript selection", () => {/>,);- expect(container.querySelector('[data-testid="task-chat-progress-update"]')).toBeNull();+ expect(container.querySelector('[data-testid="task-chat-phase-interstitial"]')).toBeNull();expect(container.querySelector('[data-testid="task-chat-final-response"]')?.textContent).toContain("Persisted before message channels existed.");});@@ -312,7 +532,7 @@ describe("TaskChatThread runtime transcript selection", () => {channel: "progress",}]);renderRun();- expect(container.querySelector('[data-testid="task-chat-progress-update"]')?.textContent)+ expect(container.querySelector('[data-testid="task-chat-phase-interstitial"]')?.textContent).toContain("Same text.");expect(container.querySelector('[data-testid="task-chat-final-response"]')).toBeNull();@@ -323,7 +543,7 @@ describe("TaskChatThread runtime transcript selection", () => {channel: "final",}]);renderRun();- expect(container.querySelector('[data-testid="task-chat-progress-update"]')).toBeNull();+ expect(container.querySelector('[data-testid="task-chat-phase-interstitial"]')).toBeNull();expect(container.querySelector('[data-testid="task-chat-final-response"]')?.textContent).toContain("Same text.");});@@ -383,6 +603,195 @@ describe("TaskChatThread runtime transcript selection", () => {expect(container.textContent).toContain("↑20");expect(container.textContent).not.toContain("↑10");});+ it.each(DIRECT_ADAPTER_TYPES)(+ "keeps active %s output on the legacy live-tail surface",+ (adapterType) => {+ const runId = `active-${adapterType}`;+ transcriptState.transcriptByRun.set(runId, [+ {+ kind: "assistant",+ ts: "2026-08-25T18:00:01.000Z",+ text: `Active ${adapterType} output`,+ },+ ]);++ render(+ <TaskChatThread+ comments={[]}+ onAdd={async () => {}}+ issueStatus="in_progress"+ activeRun={{+ id: runId,+ runtimeMode: "legacy",+ status: "running",+ invocationSource: "issue",+ triggerDetail: null,+ startedAt: "2026-08-25T18:00:00.000Z",+ finishedAt: null,+ createdAt: "2026-08-25T18:00:00.000Z",+ agentId: "agent-1",+ agentName: "Direct agent",+ adapterType,+ }}+ />,+ );++ expect(+ container.querySelector('[data-testid="task-chat-live-run-pill"]'),+ ).not.toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-phase-interstitial"]')+ ?.textContent,+ ).toContain(`Active ${adapterType} output`);+ expect(+ container.querySelector('[data-testid="task-chat-runner-turn"]'),+ ).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-queued-messages"]'),+ ).toBeNull();+ },+ );++ it.each(DIRECT_ADAPTER_TYPES)(+ "keeps settled %s activity in the shared legacy turn",+ (adapterType) => {+ const runId = `settled-${adapterType}`;+ transcriptState.transcriptByRun.set(runId, [+ {+ kind: "tool_call",+ ts: "2026-08-25T18:00:01.000Z",+ name: "Read",+ toolUseId: `${runId}-tool`,+ input: { file_path: "src/legacy.ts" },+ },+ {+ kind: "tool_result",+ ts: "2026-08-25T18:00:02.000Z",+ toolUseId: `${runId}-tool`,+ toolName: "Read",+ content: "legacy contents",+ isError: false,+ },+ ]);++ render(+ <TaskChatThread+ comments={[]}+ onAdd={async () => {}}+ linkedRuns={[+ {+ runId,+ runtimeMode: "legacy",+ status: "succeeded",+ agentId: "agent-1",+ agentName: "Direct agent",+ adapterType,+ createdAt: "2026-08-25T18:00:00.000Z",+ startedAt: "2026-08-25T18:00:00.000Z",+ finishedAt: "2026-08-25T18:00:03.000Z",+ },+ ]}+ />,+ );++ expect(+ container.querySelector('[data-testid="task-chat-turn"]'),+ ).not.toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-turn-summary"]')+ ?.textContent,+ ).toContain("Worked");+ expect(+ container.querySelector('[data-testid="task-chat-runner-turn"]'),+ ).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-final-response"]'),+ ).toBeNull();+ },+ );++ it.each(DIRECT_ADAPTER_TYPES)(+ "keeps an empty active %s run on the legacy status surface",+ (adapterType) => {+ render(+ <TaskChatThread+ comments={[]}+ onAdd={async () => {}}+ issueStatus="in_progress"+ activeRun={{+ id: `empty-${adapterType}`,+ runtimeMode: "legacy",+ status: "running",+ invocationSource: "issue",+ triggerDetail: null,+ currentStatusMessage: "Preparing direct runtime",+ startedAt: "2026-08-25T18:00:00.000Z",+ finishedAt: null,+ createdAt: "2026-08-25T18:00:00.000Z",+ agentId: "agent-1",+ agentName: "Direct agent",+ adapterType,+ }}+ />,+ );++ const tail = container.querySelector(+ '[data-testid="task-chat-live-transcript"]',+ );+ expect(tail?.textContent).toContain("Preparing direct runtime");+ expect(+ container.querySelector('[data-testid="task-chat-runner-turn"]'),+ ).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-composer-takeover"]'),+ ).toBeNull();+ },+ );++ it.each(DIRECT_ADAPTER_TYPES)(+ "keeps durable questions usable for an active %s run without runner controls",+ (adapterType) => {+ render(+ <TaskChatThread+ comments={[]}+ interactions={[+ questionInteraction(+ `question-${adapterType}`,+ "Which legacy path should continue?",+ "2026-08-25T18:00:01.000Z",+ ),+ ]}+ onAdd={async () => {}}+ onSubmitInteractionAnswers={async () => {}}+ issueStatus="in_progress"+ activeRun={{+ id: `question-run-${adapterType}`,+ runtimeMode: "legacy",+ status: "running",+ invocationSource: "issue",+ triggerDetail: null,+ startedAt: "2026-08-25T18:00:00.000Z",+ finishedAt: null,+ createdAt: "2026-08-25T18:00:00.000Z",+ agentId: "agent-1",+ agentName: "Direct agent",+ adapterType,+ }}+ />,+ );++ expect(+ container.querySelector('[data-testid="task-chat-composer-takeover"]')+ ?.textContent,+ ).toContain("Which legacy path should continue?");+ expect(+ container.querySelector('[data-testid="task-chat-runner-turn"]'),+ ).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-queued-messages"]'),+ ).toBeNull();+ },+ );});describe("TaskChatThread composer alignment", () => {@@ -399,6 +808,50 @@ describe("TaskChatThread composer alignment", () => {});});+describe("TaskChatThread no-live-execution-path recovery", () => {+ const noLivePathComment = {+ id: "comment-no-live-path",+ companyId: "company-1",+ issueId: "issue-1",+ authorType: "system" as const,+ authorAgentId: null,+ authorUserId: null,+ body: "Paperclip retried continuation, but it still has no live execution path.",+ presentation: {+ kind: "system_notice" as const,+ tone: "danger" as const,+ title: "No live execution path",+ detailsDefaultOpen: false,+ },+ metadata: null,+ createdAt: new Date("2026-08-26T12:00:00.000Z"),+ updatedAt: new Date("2026-08-26T12:00:00.000Z"),+ };++ it("offers Try again only while the task is blocked", async () => {+ const onTryAgain = vi.fn();+ const props = {+ comments: [noLivePathComment],+ onAdd: async () => {},+ onTryAgainNoLiveExecutionPath: onTryAgain,+ showComposer: false,+ };++ render(<TaskChatThread {...props} issueStatus="blocked" />);+ const tryAgain = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-no-live-path-try-again"]',+ );+ expect(tryAgain).not.toBeNull();++ flushSync(() => tryAgain!.click());+ await Promise.resolve();+ expect(onTryAgain).toHaveBeenCalledTimes(1);++ render(<TaskChatThread {...props} issueStatus="todo" />);+ expect(container.querySelector('[data-testid="task-chat-no-live-path-try-again"]')).toBeNull();+ });+});+describe("TaskChatThread blocker links", () => {it("shows the direct and server-selected terminal blocker at the top and bottom", () => {const terminalBlocker = {@@ -452,18 +905,26 @@ describe("TaskChatThread blocker links", () => {/>,);- const notices = container.querySelectorAll('[data-testid="task-chat-blocker-links"]');+ const notices = container.querySelectorAll(+ '[data-testid="task-chat-blocker-links"]',+ );expect(notices).toHaveLength(2);expect(notices[0]?.getAttribute("data-placement")).toBe("top");expect(notices[1]?.getAttribute("data-placement")).toBe("bottom");for (const notice of notices) {- expect(notice.textContent).toContain("Blocked byPAP-600Waiting in review");- expect(notice.textContent).toContain("Ultimately blocked byPAP-777Actual work");+ expect(notice.textContent).toContain(+ "Blocked byPAP-600Waiting in review",+ );+ expect(notice.textContent).toContain(+ "Ultimately blocked byPAP-777Actual work",+ );expect(notice.querySelector('a[href="/issues/PAP-600"]')).not.toBeNull();expect(notice.querySelector('a[href="/issues/PAP-777"]')).not.toBeNull();}expect(container.textContent).not.toContain("Different dependency");- expect(container.textContent).not.toContain("This task resumes automatically");+ expect(container.textContent).not.toContain(+ "This task resumes automatically",+ );});it("shows the ordered live-work queue at the top and bottom", () => {@@ -530,23 +991,34 @@ describe("TaskChatThread blocker links", () => {/>,);- const notices = container.querySelectorAll('[data-testid="task-chat-live-work-links"]');+ const notices = container.querySelectorAll(+ '[data-testid="task-chat-live-work-links"]',+ );expect(notices).toHaveLength(2);expect(notices[0]?.getAttribute("data-placement")).toBe("top");expect(notices[1]?.getAttribute("data-placement")).toBe("bottom");for (const notice of notices) {expect(notice.textContent).toContain("Waiting on live work");- const orderedLinks = [...notice.querySelectorAll('[data-testid="task-chat-live-work-step"] a')]- .map((link) => link.textContent);+ const orderedLinks = [+ ...notice.querySelectorAll(+ '[data-testid="task-chat-live-work-step"] a',+ ),+ ].map((link) => link.textContent);expect(orderedLinks).toEqual(["PAP-17424Run the guarded cutover","PAP-17425Verify the live projection","PAP-17427Verify the completed projection",]);- expect(notice.textContent).toContain("Now runningPAP-17426Restore live alias projection");- expect(notice.querySelector('a[href="/issues/PAP-17426"]')).not.toBeNull();+ expect(notice.textContent).toContain(+ "Now runningPAP-17426Restore live alias projection",+ );+ expect(+ notice.querySelector('a[href="/issues/PAP-17426"]'),+ ).not.toBeNull();}- expect(container.querySelector('[data-testid="task-chat-blocker-links"]')).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-blocker-links"]'),+ ).toBeNull();});it("keeps the compact blocker rows when covered work is no longer live", () => {@@ -567,20 +1039,26 @@ describe("TaskChatThread blocker links", () => {sampleStalledBlockerIdentifier: null,blockingTreeLive: false,}}- blockedBy={[{- id: "direct-1",- identifier: "PAP-500",- title: "Direct dependency",- status: "todo",- priority: "medium",- assigneeAgentId: "agent-1",- assigneeUserId: null,- }]}+ blockedBy={[+ {+ id: "direct-1",+ identifier: "PAP-500",+ title: "Direct dependency",+ status: "todo",+ priority: "medium",+ assigneeAgentId: "agent-1",+ assigneeUserId: null,+ },+ ]}/>,);- expect(container.querySelector('[data-testid="task-chat-live-work-links"]')).toBeNull();- expect(container.querySelectorAll('[data-testid="task-chat-blocker-links"]')).toHaveLength(2);+ expect(+ container.querySelector('[data-testid="task-chat-live-work-links"]'),+ ).toBeNull();+ expect(+ container.querySelectorAll('[data-testid="task-chat-blocker-links"]'),+ ).toHaveLength(2);});it("shows only the direct row when the blocker has no deeper unresolved leaf", () => {@@ -589,20 +1067,26 @@ describe("TaskChatThread blocker links", () => {comments={[]}onAdd={async () => {}}issueStatus="blocked"- blockedBy={[{- id: "direct-1",- identifier: "PAP-500",- title: "Direct dependency",- status: "in_progress",- priority: "medium",- assigneeAgentId: "agent-1",- assigneeUserId: null,- }]}+ blockedBy={[+ {+ id: "direct-1",+ identifier: "PAP-500",+ title: "Direct dependency",+ status: "in_progress",+ priority: "medium",+ assigneeAgentId: "agent-1",+ assigneeUserId: null,+ },+ ]}/>,);- expect(container.querySelectorAll('[data-testid="task-chat-blocker-links"]')).toHaveLength(2);- expect(container.textContent).toContain("Blocked byPAP-500Direct dependency");+ expect(+ container.querySelectorAll('[data-testid="task-chat-blocker-links"]'),+ ).toHaveLength(2);+ expect(container.textContent).toContain(+ "Blocked byPAP-500Direct dependency",+ );expect(container.textContent).not.toContain("Ultimately blocked by");});@@ -620,15 +1104,17 @@ describe("TaskChatThread blocker links", () => {priority: "medium" as const,assigneeAgentId: "agent-1",assigneeUserId: null,- terminalBlockers: [{- id: "leaf-2",- identifier: "PAP-700",- title: "Deeper structural leaf",- status: "todo" as const,- priority: "medium" as const,- assigneeAgentId: "agent-2",- assigneeUserId: null,- }],+ terminalBlockers: [+ {+ id: "leaf-2",+ identifier: "PAP-700",+ title: "Deeper structural leaf",+ status: "todo" as const,+ priority: "medium" as const,+ assigneeAgentId: "agent-2",+ assigneeUserId: null,+ },+ ],};render(@@ -664,9 +1150,15 @@ describe("TaskChatThread blocker links", () => {/>,);- for (const notice of container.querySelectorAll('[data-testid="task-chat-blocker-links"]')) {- expect(notice.textContent).toContain("Blocked byPAP-600Selected dependency");- expect(notice.textContent).toContain("Ultimately blocked byPAP-650Stalled intermediate review");+ for (const notice of container.querySelectorAll(+ '[data-testid="task-chat-blocker-links"]',+ )) {+ expect(notice.textContent).toContain(+ "Blocked byPAP-600Selected dependency",+ );+ expect(notice.textContent).toContain(+ "Ultimately blocked byPAP-650Stalled intermediate review",+ );}expect(container.textContent).not.toContain("Unrelated dependency");expect(container.textContent).not.toContain("Deeper structural leaf");@@ -702,7 +1194,9 @@ describe("TaskChatThread blocker links", () => {};render(<TaskChatThread {...baseProps} issueStatus="in_progress" />);- const scroller = container.querySelector<HTMLElement>('[data-testid="task-chat-scroller"]')!;+ const scroller = container.querySelector<HTMLElement>(+ '[data-testid="task-chat-scroller"]',+ )!;fakeScrollGeometry(scroller);render(<TaskChatThread {...baseProps} issueStatus="blocked" />);@@ -716,19 +1210,23 @@ describe("TaskChatThread blocker links", () => {comments={[]}onAdd={async () => {}}issueStatus="in_progress"- blockedBy={[{- id: "direct-1",- identifier: "PAP-500",- title: "Direct dependency",- status: "in_progress",- priority: "medium",- assigneeAgentId: "agent-1",- assigneeUserId: null,- }]}+ blockedBy={[+ {+ id: "direct-1",+ identifier: "PAP-500",+ title: "Direct dependency",+ status: "in_progress",+ priority: "medium",+ assigneeAgentId: "agent-1",+ assigneeUserId: null,+ },+ ]}/>,);- expect(container.querySelector('[data-testid="task-chat-blocker-links"]')).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-blocker-links"]'),+ ).toBeNull();});});@@ -773,21 +1271,23 @@ describe("TaskChatThread queued message actions", () => {it("disables the action while the queued run is being interrupted", () => {render(<TaskChatThread- comments={[{- id: "comment-queued",- companyId: "company-1",- issueId: "issue-1",- authorType: "user",- authorAgentId: null,- authorUserId: "user-1",- body: "Use the latest requirements instead.",- presentation: null,- metadata: null,- clientStatus: "queued",- queueTargetRunId: "run-active",- createdAt: new Date("2026-08-14T12:00:00.000Z"),- updatedAt: new Date("2026-08-14T12:00:00.000Z"),- }]}+ comments={[+ {+ id: "comment-queued",+ companyId: "company-1",+ issueId: "issue-1",+ authorType: "user",+ authorAgentId: null,+ authorUserId: "user-1",+ body: "Use the latest requirements instead.",+ presentation: null,+ metadata: null,+ clientStatus: "queued",+ queueTargetRunId: "run-active",+ createdAt: new Date("2026-08-14T12:00:00.000Z"),+ updatedAt: new Date("2026-08-14T12:00:00.000Z"),+ },+ ]}onAdd={async () => {}}onInterruptQueued={async () => {}}interruptingQueuedRunId="run-active"@@ -802,11 +1302,94 @@ describe("TaskChatThread queued message actions", () => {});});+describe("TaskChatThread Paperclip Runner queue", () => {+ const queuedComment = {+ id: "queued-prp-1",+ companyId: "company-1",+ issueId: "issue-1",+ authorType: "user" as const,+ authorAgentId: null,+ authorUserId: "user-1",+ body: "Render this queued message exactly once.",+ presentation: null,+ metadata: null,+ createdAt: new Date("2026-08-22T15:00:00.000Z"),+ updatedAt: new Date("2026-08-22T15:00:00.000Z"),+ };+ const queue: IssueQueuedCommentQueue = {+ issueId: "issue-1",+ queueId: "wake-1",+ state: "deferred",+ targetRunId: "run-1",+ revision: "revision-1",+ protocol: "paperclip_runner_v1",+ steeringDisposition: "available",+ entries: [+ { comment: queuedComment, position: 0, canEdit: true, canDiscard: true },+ ],+ };++ function occurrenceCount(text: string) {+ return container.textContent?.split(text).length! - 1;+ }++ it("suppresses the transcript echo until the queued entry is consumed", async () => {+ const props = {+ comments: [queuedComment],+ onAdd: async () => {},+ queuedCommentQueue: queue,+ onEditQueuedComment: async () => {},+ onReorderQueuedComments: async () => {},+ onSteerQueuedComment: async () => {},+ onDiscardQueuedComment: async () => {},+ };+ render(<TaskChatThread {...props} />);++ const stack = container.querySelector(+ '[data-testid="task-chat-composer-stack"]',+ );+ const queuePane = container.querySelector(+ '[data-testid="task-chat-queued-messages"]',+ );+ expect(queuePane?.parentElement).toBe(stack);+ expect(stack?.classList).not.toContain("gap-2");+ expect(+ container.querySelector(+ '[data-testid="task-chat-queued-message-queued-prp-1"]',+ ),+ ).not.toBeNull();+ expect(occurrenceCount(queuedComment.body)).toBe(1);++ await act(async () => {+ render(+ <TaskChatThread+ {...props}+ queuedCommentQueue={{ ...queue, revision: "revision-2", entries: [] }}+ />,+ );+ await Promise.resolve();+ });++ expect(+ container.querySelector(+ '[data-testid="task-chat-queued-message-queued-prp-1"]',+ ),+ ).toBeNull();+ expect(occurrenceCount(queuedComment.body)).toBe(1);+ });+});+describe("TaskChatThread mobile composer dock (PAP-495)", () => {it("pins the composer to the nav-aware bottom offset so its action row clears the auto-hiding bottom nav", () => {sidebarState.isMobile = true;- render(<TaskChatThread comments={[]} onAdd={async () => {}} draftKey="task-chat-draft:issue-mobile" />);+ render(+ <TaskChatThread+ comments={[]}+ onAdd={async () => {}}+ draftKey="task-chat-draft:issue-mobile"+ />,+ );const dock = container.querySelector('[data-testid="mock-editor"]')@@ -822,6 +1405,165 @@ describe("TaskChatThread mobile composer dock (PAP-495)", () => {});describe("TaskChatThread live transcript", () => {+ it("places the turn status island below composer accessories and hides it when the turn is terminal", () => {+ nativeTranscriptState.transcriptByRun.set("run-status", [+ {+ kind: "provider_activity",+ ts: "2026-08-24T12:00:01.000Z",+ family: "plan",+ eventType: "plan.updated",+ status: "running",+ title: "Plan",+ payload: {+ planId: "turn-1",+ steps: [+ { stepId: "one", body: "Inspect", status: "completed" },+ { stepId: "two", body: "Build", status: "in_progress" },+ ],+ },+ },+ {+ kind: "workspace_change",+ ts: "2026-08-24T12:00:02.000Z",+ changeSetId: "turn-1:workspace",+ revision: 1,+ source: "harness_reported",+ complete: false,+ files: [+ {+ path: "ui/src/App.tsx",+ operation: "modify",+ previousPath: null,+ additions: 4,+ deletions: 1,+ binary: false,+ diff: null,+ },+ ],+ totals: { files: 1, additions: 4, deletions: 1 },+ patchArtifactRef: null,+ },+ ]);+ const activeRun = {+ id: "run-status",+ status: "running" as const,+ invocationSource: "issue" as const,+ triggerDetail: null,+ startedAt: "2026-08-24T12:00:00.000Z",+ finishedAt: null,+ createdAt: "2026-08-24T12:00:00.000Z",+ agentId: "agent-1",+ agentName: "Codex",+ adapterType: "paperclip_runner",+ runtimeMode: "native" as const,+ };++ render(+ <TaskChatThread+ comments={[]}+ onAdd={async () => {}}+ issueStatus="in_progress"+ activeRun={activeRun}+ composerAccessory={<div data-testid="composer-accessory">Monitor</div>}+ />,+ );++ const dock = container.querySelector(+ '[data-testid="task-chat-composer-dock"]',+ )!;+ const accessory = container.querySelector(+ '[data-testid="composer-accessory"]',+ )!;+ const island = container.querySelector(+ '[data-testid="task-chat-turn-status-island"]',+ )!;+ const stack = container.querySelector(+ '[data-testid="task-chat-composer-stack"]',+ )!;+ expect(island.textContent).toContain("Step 2 / 2");+ expect(island.textContent).toContain("1 file changed");+ expect(accessory.compareDocumentPosition(island)).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ expect(island.compareDocumentPosition(stack)).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ expect(dock.contains(island)).toBe(true);++ render(+ <TaskChatThread+ comments={[]}+ onAdd={async () => {}}+ issueStatus="in_progress"+ activeRun={{+ ...activeRun,+ status: "succeeded",+ finishedAt: "2026-08-24T12:01:00.000Z",+ }}+ />,+ );+ expect(+ container.querySelector('[data-testid="task-chat-turn-status-island"]'),+ ).toBeNull();+ });++ it("keeps an unlinked persisted runner reply hidden while the live turn still owns that response", () => {+ nativeTranscriptState.transcriptByRun.set("run-runner", [+ {+ kind: "assistant",+ ts: "2026-08-21T15:44:20.000Z",+ text: "Completed the requested streaming test.",+ channel: "final",+ delta: true,+ },+ ]);+ const comment = {+ id: "comment-runner",+ companyId: "company-1",+ issueId: "issue-1",+ authorType: "agent" as const,+ authorAgentId: "agent-1",+ authorUserId: null,+ body: "Completed the requested streaming test.",+ presentation: null,+ metadata: null,+ runId: null,+ createdAt: new Date("2026-08-21T15:44:22.000Z"),+ updatedAt: new Date("2026-08-21T15:44:22.000Z"),+ };++ render(+ <TaskChatThread+ comments={[comment]}+ onAdd={async () => {}}+ issueStatus="in_progress"+ activeRun={{+ id: "run-runner",+ status: "running",+ invocationSource: "issue",+ triggerDetail: null,+ startedAt: "2026-08-21T15:44:00.000Z",+ finishedAt: null,+ createdAt: "2026-08-21T15:44:00.000Z",+ agentId: "agent-1",+ agentName: "Runner",+ adapterType: "paperclip_runner",+ runtimeMode: "native",+ }}+ />,+ );++ expect(+ container.textContent?.match(/Completed the requested streaming test\./g),+ ).toHaveLength(1);+ expect(+ container.querySelectorAll('[data-testid="task-chat-agent-bubble"]'),+ ).toHaveLength(1);+ expect(+ container.querySelector('[data-testid="task-chat-live-transcript"]'),+ ).not.toBeNull();+ });+it("surfaces the live runtime status while no transcript has streamed yet", () => {// Sandbox runs spend their first minutes in preparation phases (config// seed, workspace sync) with zero transcript entries. The tail must show@@ -844,11 +1586,16 @@ describe("TaskChatThread live transcript", () => {comments={[]}onAdd={async () => {}}issueStatus="in_progress"- activeRun={{ ...baseRun, currentStatusMessage: "Syncing workspace to environment" }}+ activeRun={{+ ...baseRun,+ currentStatusMessage: "Syncing workspace to environment",+ }}/>,);- const tail = container.querySelector('[data-testid="task-chat-live-transcript"]');+ const tail = container.querySelector(+ '[data-testid="task-chat-live-transcript"]',+ );expect(tail).not.toBeNull();expect(tail!.textContent).toContain("Syncing workspace to environment");expect(tail!.textContent).not.toContain("Waiting for transcript...");@@ -862,7 +1609,9 @@ describe("TaskChatThread live transcript", () => {activeRun={{ ...baseRun, id: "run-prep-2" }}/>,);- const tail2 = container.querySelector('[data-testid="task-chat-live-transcript"]');+ const tail2 = container.querySelector(+ '[data-testid="task-chat-live-transcript"]',+ );expect(tail2!.textContent).toContain("Waiting for transcript...");});@@ -871,16 +1620,39 @@ describe("TaskChatThread live transcript", () => {// row, stdout/stderr/system dumps) with real content. Only the streamed// reply markdown and the tool row may reach the thread.transcriptState.transcriptByRun.set("run-1", [- { kind: "init", ts: "2026-08-07T00:00:00.000Z", model: "claude", sessionId: "sess-INITMARKER" },- { kind: "system", ts: "2026-08-07T00:00:00.000Z", text: "SYSTEMNOISE environment hint" },- { kind: "stdout", ts: "2026-08-07T00:00:00.000Z", text: "STDOUTNOISE raw json dump" },- { kind: "stderr", ts: "2026-08-07T00:00:00.000Z", text: "STDERRNOISE adapter timeout note" },+ {+ kind: "init",+ ts: "2026-08-07T00:00:00.000Z",+ model: "claude",+ sessionId: "sess-INITMARKER",+ },+ {+ kind: "system",+ ts: "2026-08-07T00:00:00.000Z",+ text: "SYSTEMNOISE environment hint",+ },+ {+ kind: "stdout",+ ts: "2026-08-07T00:00:00.000Z",+ text: "STDOUTNOISE raw json dump",+ },+ {+ kind: "stderr",+ ts: "2026-08-07T00:00:00.000Z",+ text: "STDERRNOISE adapter timeout note",+ },{kind: "assistant",ts: "2026-08-07T00:00:00.000Z",text: "Streaming through the shared renderer",},- { kind: "tool_call", ts: "2026-08-07T00:00:00.000Z", name: "Read", toolUseId: "t1", input: { file_path: "src/app.ts" } },+ {+ kind: "tool_call",+ ts: "2026-08-07T00:00:00.000Z",+ name: "Read",+ toolUseId: "t1",+ input: { file_path: "src/app.ts" },+ },]);render(@@ -903,20 +1675,109 @@ describe("TaskChatThread live transcript", () => {/>,);- const tail = container.querySelector('[data-testid="task-chat-live-transcript"]');+ const tail = container.querySelector(+ '[data-testid="task-chat-live-transcript"]',+ );expect(tail).not.toBeNull();// Clean content survives: streamed reply markdown + compact phase summary.- expect(tail!.textContent).toContain("Streaming through the shared renderer");- const phaseSummary = tail!.querySelector<HTMLButtonElement>('[data-testid="task-chat-phase-summary"]');- expect(phaseSummary?.getAttribute("aria-expanded")).toBe("false");- flushSync(() => phaseSummary!.click());+ expect(tail!.textContent).toContain(+ "Streaming through the shared renderer",+ );+ const phaseSummary = tail!.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-phase-summary"]',+ );+ expect(phaseSummary?.getAttribute("aria-expanded")).toBe("true");expect(tail!.textContent).toContain("src/app.ts");// None of the debug plumbing reaches the thread.- for (const noise of ["INITMARKER", "SYSTEMNOISE", "STDOUTNOISE", "STDERRNOISE"]) {+ for (const noise of [+ "INITMARKER",+ "SYSTEMNOISE",+ "STDOUTNOISE",+ "STDERRNOISE",+ ]) {expect(container.textContent).not.toContain(noise);}});+ it("resolves a visible canonical input even while run adapter metadata is stale", async () => {+ transcriptState.transcriptByRun.set("run-input", [+ {+ kind: "runtime_request",+ ts: "2026-08-23T20:00:00.000Z",+ requestId: "question-1",+ requestKind: "runtime",+ turnId: "turn-1",+ requestType: "input",+ status: "pending",+ prompt: "Codex needs your input.",+ choices: [],+ fields: [],+ questionSet: {+ schema: "paperclip.question_set.v1",+ questions: [+ {+ id: "goal",+ prompt: "What should the server do?",+ required: true,+ answerMode: "single_select",+ options: [{ id: "api", label: "Starter API" }],+ },+ ],+ },+ },+ ]);+ const resolveRuntimeRequest = vi+ .spyOn(heartbeatsApi, "resolveRuntimeRequest")+ .mockResolvedValue({} as never);++ render(+ <TaskChatThread+ comments={[]}+ onAdd={async () => {}}+ issueStatus="in_progress"+ activeRun={{+ id: "run-input",+ status: "running",+ invocationSource: "issue",+ triggerDetail: null,+ startedAt: "2026-08-23T20:00:00.000Z",+ finishedAt: null,+ createdAt: "2026-08-23T20:00:00.000Z",+ agentId: "agent-1",+ agentName: "Runner",+ // Reproduces the lag that caused DOT-202: the transcript already has+ // a Paperclip request while the linked-run adapter classification is+ // still stale.+ adapterType: "codex_local",+ }}+ />,+ );++ const option = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.includes("Starter API"),+ );+ await act(async () => option?.click());+ const submit = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.trim() === "Submit answers",+ );+ await act(async () => submit?.click());++ expect(resolveRuntimeRequest).toHaveBeenCalledWith({+ runId: "run-input",+ requestId: "question-1",+ turnId: "turn-1",+ requestKind: "runtime",+ resolution: {+ action: "submit",+ response: {+ schema: "paperclip.question_response.v1",+ answers: { goal: { selectedOptionIds: ["api"] } },+ },+ },+ });+ expect(container.textContent).not.toContain("no longer attached");+ });+it("keeps the transcript mounted through run settle until the settled turn renders (PAP-462 B4)", () => {transcriptState.transcriptByRun.set("run-1", [{diff --git a/ui/src/components/TaskChatThread.tsx b/ui/src/components/TaskChatThread.tsxindex 86c82b65cd..25f27dcfef 100644--- a/ui/src/components/TaskChatThread.tsx+++ b/ui/src/components/TaskChatThread.tsx@@ -1,5 +1,16 @@-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps } from "react";-import { IssueChatThread, IssueAssigneePausedNotice } from "@/components/IssueChatThread";+import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+ type ComponentProps,+} from "react";+import {+ IssueAssigneePausedNotice,+ IssueChatThread,+} from "@/components/IssueChatThread";import {useLiveRunTranscripts,type RunTranscriptSource,@@ -7,6 +18,10 @@ import {import { useNativeRunTranscripts } from "@/components/transcript/useNativeRunTranscripts";import { TaskChatLiveTail } from "@/components/task-chat/TaskChatLiveTail";import { TaskChatRunnerTurn } from "@/components/task-chat/TaskChatRunnerTurn";+import {+ TaskChatTurnStatusIsland,+ taskChatTurnStatusModel,+} from "@/components/task-chat/TaskChatTurnStatusIsland";import { commentsToTaskChatItems } from "@/components/task-chat/task-chat-adapter";import {assembleThreadItems,@@ -14,8 +29,12 @@ import {buildTurnSummary,coalesceSettledTurns,isTerminalRunStatus,+ embedPlanDocumentAtWriteBoundary,+ paperclipRunnerFinalResponse,+ paperclipRunnerTimelineItems,prependIssueBrief,settledRunChildren,+ splitTranscriptAtAnchors,transcriptToTaskChatItems,type SettledTurnMergeMeta,} from "@/components/task-chat/transcript-adapter";@@ -28,18 +47,37 @@ import type {TaskChatInteractionItem,TaskChatItem,TaskChatMessageItem,+ TaskChatPlanDocumentItem,+ TaskChatRuntimeRequestDecision,+ TaskChatRuntimeRequestItem,TaskChatTurnItem,} from "@/components/task-chat/task-chat-model";+import {+ latestPendingRuntimeRequest,+ runtimeRequestReplacesComposerSkip,+} from "@/components/task-chat/task-chat-model";import { TaskChatInteractionCard } from "@/components/task-chat/TaskChatInteractionCard";+import { TaskChatProtocolCard } from "@/components/task-chat/TaskChatProtocolCard";import {interactionThreadAnchorMs,isSuppressedThreadInteraction,} from "@/components/task-chat/interaction-thread-order";-import { shouldHideInteractionCard } from "@/lib/issue-thread-interactions";+import {+ interactionReplacesComposerSkip,+ shouldHideInteractionCard,+} from "@/lib/issue-thread-interactions";import { TaskChatBubbleActions } from "@/components/task-chat/TaskChatBubbleActions";-import type { FeedbackVoteValue } from "@paperclipai/shared";-import { TaskChatThreadView, taskChatContentKey } from "@/components/task-chat/TaskChatThreadView";+import type {+ FeedbackVoteValue,+ IssueDocument,+ IssueThreadInteraction,+} from "@paperclipai/shared";+import {+ TaskChatThreadView,+ taskChatContentKey,+} from "@/components/task-chat/TaskChatThreadView";import { TaskChatComposer } from "@/components/task-chat/TaskChatComposer";+import { TaskChatQueuedMessages } from "@/components/task-chat/TaskChatQueuedMessages";import { useWindowAutoFollow } from "@/components/task-chat/useWindowAutoFollow";import { useSidebar } from "@/context/SidebarContext";import { cn } from "@/lib/utils";@@ -53,6 +91,13 @@ import {TaskChatBlockerLinks,TaskChatLiveWorkLinks,} from "@/components/task-chat/TaskChatBlockerLinks";+import { buildDocumentAnnotationHash } from "@/lib/document-annotation-hash";+import {+ documentDisplayTitle,+ selectAgentArtifactAttachments,+ workProductHref,+} from "@/lib/issue-artifacts";+import { heartbeatsApi, type RuntimeRequestResolution } from "@/api/heartbeats";function toMs(value: Date | string | null | undefined): number {if (!value) return 0;@@ -60,6 +105,104 @@ function toMs(value: Date | string | null | undefined): number {return Number.isNaN(ms) ? 0 : ms;}+function normalizedMessageText(value: string | null | undefined): string {+ return (value ?? "").trim().replace(/\s+/g, " ");+}++function safeResourceHref(value: string | null | undefined): string | null {+ if (!value) return null;+ if (value.startsWith("/") || value.startsWith("#")) return value;+ try {+ const url = new URL(value);+ return url.protocol === "http:" || url.protocol === "https:" ? value : null;+ } catch {+ return null;+ }+}++function formatResourceBytes(value: number): string {+ if (value < 1024) return `${value} B`;+ if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`;+ return `${(value / (1024 * 1024)).toFixed(1)} MB`;+}++function interactionTargetsPlanRevision(+ interaction: IssueThreadInteraction,+ planDocument: IssueDocument,+): boolean {+ if (interaction.kind !== "request_confirmation") return false;+ const target = interaction.payload.target;+ if (target?.type !== "issue_document" || target.key !== "plan") return false;+ if (target.issueId && target.issueId !== planDocument.issueId) return false;+ if (planDocument.latestRevisionId) {+ return target.revisionId === planDocument.latestRevisionId;+ }+ return target.revisionNumber === planDocument.latestRevisionNumber;+}++function isResolvedPlanConfirmation(interaction: IssueThreadInteraction) {+ return (+ interaction.kind === "request_confirmation" &&+ (interaction.status === "accepted" || interaction.status === "rejected") &&+ interaction.payload.target?.type === "issue_document" &&+ interaction.payload.target.key === "plan"+ );+}++// A runner-authored plan review is only the lifecycle receipt. Its full plan+// preview already belongs to the source turn's write_document boundary, so+// resolving or expiring the review must not insert a second large block there.+function runnerTurnOwnsPlanPreview(+ interaction: IssueThreadInteraction,+ renderedRunIds: ReadonlySet<string>,+ tailRunId: string | null,+): boolean {+ if (!interaction.sourceRunId || interaction.kind !== "request_confirmation")+ return false;+ const target = interaction.payload.target;+ return (+ target?.type === "issue_document" &&+ target.key === "plan" &&+ (renderedRunIds.has(interaction.sourceRunId) ||+ tailRunId === interaction.sourceRunId)+ );+}++function threadOwnsPlanPreview(+ interaction: IssueThreadInteraction,+ planDocument: IssueDocument | null | undefined,+ planDocumentSourceRunId: string | null,+ renderedRunIds: ReadonlySet<string>,+ tailRunId: string | null,+): boolean {+ if (!planDocument || !interactionTargetsPlanRevision(interaction, planDocument))+ return false;+ // Plans without a native-run owner are canonical chronological thread+ // entries. In particular, legacy adapters write them through shell/API+ // tools rather than a semantic write_document boundary, so the pending+ // confirmation must not replace that durable timeline position.+ if (!planDocumentSourceRunId) return true;+ return runnerTurnOwnsPlanPreview(interaction, renderedRunIds, tailRunId);+}++function isRunnerResponseComment(params: {+ comment: TaskChatThreadProps["comments"][number];+ runId: string;+ runStartedAtMs: number | null;+ finalText: string | null;+}): boolean {+ const { comment, runId, runStartedAtMs, finalText } = params;+ if (comment.deletedAt || comment.authorType === "user") return false;+ if (comment.runId === runId) return true;+ if (comment.runId || !finalText) return false;+ const commentAtMs = toMs(comment.createdAt);+ if (runStartedAtMs != null && commentAtMs < runStartedAtMs - 5_000)+ return false;+ return (+ normalizedMessageText(comment.body) === normalizedMessageText(finalText)+ );+}+// PAP-462 B4: backstop for how long the just-settled run's transcript stays// mounted when neither a settled turn nor a reply comment ever arrives to hand// off to (e.g. a stopped run with no tool activity). Normal completions hand off@@ -67,8 +210,158 @@ function toMs(value: Date | string | null | undefined): number {const SETTLING_TAIL_MAX_MS = 15_000;const EMPTY_LIVE_ISSUE_IDS: ReadonlySet<string> = new Set<string>();+function isNativePaperclipRunnerRun(+ run:+ | {+ adapterType?: string | null;+ runtimeMode?: string | null;+ }+ | null+ | undefined,+): boolean {+ return (+ run?.runtimeMode === "native" && run.adapterType === "paperclip_runner"+ );+}+const LEGACY_WITHHELD_RUN_COMMENT =+ "Run completed. Agent did not post a summary comment this run (transcript withheld — see run log).";++function acceptedSemanticResult(+ value: unknown,+): Record<string, unknown> | null {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const resultJson = value as Record<string, unknown>;+ const semanticResult = resultJson.semanticResult;+ const candidates = [+ resultJson.nativeResult,+ resultJson.acceptedResult,+ semanticResult &&+ typeof semanticResult === "object" &&+ !Array.isArray(semanticResult)+ ? (semanticResult as Record<string, unknown>).result+ : null,+ ];+ for (const candidate of candidates) {+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate))+ continue;+ const result = candidate as Record<string, unknown>;+ if (result.schema !== "paperclip.run_result.v1") continue;+ return result;+ }+ return null;+}++function acceptedSemanticResultSummary(value: unknown): string | null {+ const result = acceptedSemanticResult(value);+ return typeof result?.summary === "string" && result.summary.trim()+ ? result.summary+ : null;+}++function acceptedSemanticResultVerificationCaveats(value: unknown) {+ const runResult =+ value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+ const finalizedCaveats = Array.isArray(runResult.verificationCaveats)+ ? runResult.verificationCaveats+ : [];+ if (finalizedCaveats.length > 0) {+ return finalizedCaveats.flatMap((candidate) => {+ if (+ !candidate ||+ typeof candidate !== "object" ||+ Array.isArray(candidate)+ )+ return [];+ const caveat = candidate as Record<string, unknown>;+ if (typeof caveat.commandOrCheck !== "string") return [];+ return [+ {+ commandOrCheck: caveat.commandOrCheck,+ reasonCode:+ typeof caveat.reasonCode === "string" ? caveat.reasonCode : null,+ detail: typeof caveat.detail === "string" ? caveat.detail : null,+ },+ ];+ });+ }+ const result = acceptedSemanticResult(value);+ const verification = Array.isArray(result?.verification)+ ? result.verification+ : [];+ return verification.flatMap((candidate) => {+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate))+ return [];+ const check = candidate as Record<string, unknown>;+ if (check.status !== "not_run" || typeof check.commandOrCheck !== "string")+ return [];+ return [+ {+ commandOrCheck: check.commandOrCheck,+ reasonCode:+ typeof check.reasonCode === "string" ? check.reasonCode : null,+ detail: typeof check.detail === "string" ? check.detail : null,+ },+ ];+ });+}++function resolvedWithoutUserFacingResponse(value: unknown): boolean {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;+ const decision = (value as Record<string, unknown>).presentationDecision;+ return Boolean(+ decision &&+ typeof decision === "object" &&+ !Array.isArray(decision) &&+ (decision as Record<string, unknown>).schema ===+ "paperclip.run_presentation_decision.v1" &&+ (decision as Record<string, unknown>).chosenSource === "none",+ );+}+export type TaskChatThreadProps = ComponentProps<typeof IssueChatThread>;+type PendingComposerInput =+ | {+ key: string;+ kind: "runtime";+ item: TaskChatRuntimeRequestItem;+ label: string;+ }+ | {+ key: string;+ kind: "durable";+ interaction: TaskChatInteractionItem["interaction"];+ label: string;+ };++function durableInputLabel(+ interaction: TaskChatInteractionItem["interaction"],+): string {+ if (interaction.kind === "ask_user_questions")+ return interaction.title ?? "Questions";+ if (interaction.kind === "suggest_tasks")+ return interaction.title ?? "Suggested tasks";+ if (interaction.kind === "request_checkbox_confirmation")+ return interaction.title ?? "Choose options";+ if (interaction.kind === "request_item_verdicts")+ return interaction.title ?? "Review items";+ if (interaction.kind === "connection_intent")+ return interaction.title ?? "Connect service";+ if (+ interaction.payload.target?.type === "issue_document" &&+ interaction.payload.target.key === "plan"+ ) {+ return interaction.title ?? "Review plan";+ }+ if (interaction.payload.toolAction)+ return interaction.title ?? "Approve tool action";+ if (interaction.payload.secretProposal)+ return interaction.title ?? "Review secret proposal";+ return interaction.title ?? "Confirmation";+}+/*** Chat-style task thread — the default task detail experience.*@@ -95,10 +388,14 @@ export function TaskChatThread(props: TaskChatThreadProps) {const {comments,interactions,+ documents = [],+ workProducts = [],+ attachments = [],timelineEvents,issueId = null,agentMap,userLabelMap,+ userProfileMap,currentUserId,onAdd,issueWorkMode = "standard",@@ -124,6 +421,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {onRejectInteraction,onSubmitInteractionAnswers,onCancelInteraction,+ onSkipInteraction,onSubmitInteractionVerdicts,externalReferences,threadHeader,@@ -135,6 +433,13 @@ export function TaskChatThread(props: TaskChatThreadProps) {draftKey,onInterruptQueued,interruptingQueuedRunId,+ onTryAgainNoLiveExecutionPath,+ tryAgainNoLiveExecutionPathPending = false,+ queuedCommentQueue,+ onEditQueuedComment,+ onReorderQueuedComments,+ onSteerQueuedComment,+ onDiscardQueuedComment,blockedBy = [],blockerAttention,liveIssueIds,@@ -142,22 +447,136 @@ export function TaskChatThread(props: TaskChatThreadProps) {resumeAssigneePending = false,} = props;+ const paperclipQueue =+ queuedCommentQueue?.protocol === "paperclip_runner_v1"+ ? queuedCommentQueue+ : null;+ const queuedCommentIds = useMemo(+ () =>+ new Set(paperclipQueue?.entries.map((entry) => entry.comment.id) ?? []),+ [paperclipQueue],+ );+ const [queuedEdit, setQueuedEdit] = useState<{+ commentId: string;+ body: string;+ revision: string;+ stale?: boolean;+ } | null>(null);++ const beginQueuedEdit = useCallback(+ (commentId: string) => {+ const entry = paperclipQueue?.entries.find(+ (candidate) => candidate.comment.id === commentId,+ );+ if (!entry?.canEdit || !paperclipQueue) return;+ setQueuedEdit({+ commentId,+ body: entry.comment.body,+ revision: paperclipQueue.revision,+ });+ },+ [paperclipQueue],+ );++ const saveQueuedEdit = useCallback(+ async (commentId: string, body: string) => {+ if (!queuedEdit || queuedEdit.commentId !== commentId) {+ throw new Error("This queued message is no longer editable.");+ }+ if (queuedEdit.stale) {+ await onAdd(body);+ return;+ }+ if (!onEditQueuedComment)+ throw new Error("This queued message is no longer editable.");+ try {+ await onEditQueuedComment(commentId, body, queuedEdit.revision);+ } catch (error) {+ const payload =+ typeof error === "object" && error !== null+ ? (error as { status?: unknown; body?: unknown; message?: unknown })+ : null;+ const responseBody =+ typeof payload?.body === "object" && payload.body !== null+ ? (payload.body as { code?: unknown; details?: unknown })+ : null;+ const details =+ typeof responseBody?.details === "object" &&+ responseBody.details !== null+ ? (responseBody.details as { code?: unknown })+ : null;+ const code =+ typeof details?.code === "string"+ ? details.code+ : typeof responseBody?.code === "string"+ ? responseBody.code+ : null;+ const stale =+ payload?.status === 409 &&+ (code === "queued_comment_stale_target" ||+ code === "queued_comment_not_pending");+ if (stale) {+ setQueuedEdit((current) =>+ current?.commentId === commentId+ ? { ...current, stale: true }+ : current,+ );+ }+ throw error;+ }+ },+ [onAdd, onEditQueuedComment, queuedEdit],+ );++ useEffect(() => {+ if (!queuedEdit || queuedEdit.stale) return;+ const targetStillQueued = paperclipQueue?.entries.some(+ (entry) => entry.comment.id === queuedEdit.commentId,+ );+ if (!targetStillQueued) {+ setQueuedEdit((current) =>+ current ? { ...current, stale: true } : current,+ );+ } else if (+ paperclipQueue &&+ queuedEdit.revision !== paperclipQueue.revision+ ) {+ // A concurrent reorder/edit refreshes the optimistic-lock token without+ // replacing the Markdown currently in the editor.+ setQueuedEdit((current) =>+ current ? { ...current, revision: paperclipQueue.revision } : current,+ );+ }+ }, [paperclipQueue, queuedEdit]);+const liveWorkLinks = useMemo(- () => issueStatus === "blocked" && blockerAttention?.state === "covered"- ? resolveTaskChatLiveWork(blockedBy, liveIssueIds ?? EMPTY_LIVE_ISSUE_IDS, blockerAttention.terminalBlocker)- : null,- [blockedBy, blockerAttention?.state, blockerAttention?.terminalBlocker, issueStatus, liveIssueIds],+ () =>+ issueStatus === "blocked" && blockerAttention?.state === "covered"+ ? resolveTaskChatLiveWork(+ blockedBy,+ liveIssueIds ?? EMPTY_LIVE_ISSUE_IDS,+ blockerAttention.terminalBlocker,+ )+ : null,+ [+ blockedBy,+ blockerAttention?.state,+ blockerAttention?.terminalBlocker,+ issueStatus,+ liveIssueIds,+ ],);const blockerLinks = useMemo(- () => issueStatus === "blocked" && !liveWorkLinks- ? resolveTaskChatBlockers(- blockedBy,- blockerAttention?.terminalBlockerIssueId,- blockerAttention?.directBlockerIssueId,- blockerAttention?.terminalBlocker,- )- : null,+ () =>+ issueStatus === "blocked" && !liveWorkLinks+ ? resolveTaskChatBlockers(+ blockedBy,+ blockerAttention?.terminalBlockerIssueId,+ blockerAttention?.directBlockerIssueId,+ blockerAttention?.terminalBlocker,+ )+ : null,[blockedBy,blockerAttention?.directBlockerIssueId,@@ -168,20 +587,21 @@ export function TaskChatThread(props: TaskChatThreadProps) {],);- const threadHeaderWithBlockers = threadHeader || blockerLinks || liveWorkLinks ? (- <>- {threadHeader}- {liveWorkLinks ? (- <TaskChatLiveWorkLinks liveWork={liveWorkLinks} placement="top" />- ) : blockerLinks ? (- <TaskChatBlockerLinks- directBlocker={blockerLinks.directBlocker}- ultimateBlocker={blockerLinks.ultimateBlocker}- placement="top"- />- ) : null}- </>- ) : undefined;+ const threadHeaderWithBlockers =+ threadHeader || blockerLinks || liveWorkLinks ? (+ <>+ {threadHeader}+ {liveWorkLinks ? (+ <TaskChatLiveWorkLinks liveWork={liveWorkLinks} placement="top" />+ ) : blockerLinks ? (+ <TaskChatBlockerLinks+ directBlocker={blockerLinks.directBlocker}+ ultimateBlocker={blockerLinks.ultimateBlocker}+ placement="top"+ />+ ) : null}+ </>+ ) : undefined;const bottomBlockerLinks = liveWorkLinks ? (<TaskChatLiveWorkLinks liveWork={liveWorkLinks} placement="bottom" />@@ -194,19 +614,59 @@ export function TaskChatThread(props: TaskChatThreadProps) {) : null;const linkedRunMetaById = useMemo(() => {- const map = new Map<string, NonNullable<TaskChatThreadProps["linkedRuns"]>[number]>();+ const map = new Map<+ string,+ NonNullable<TaskChatThreadProps["linkedRuns"]>[number]+ >();for (const run of linkedRuns ?? []) map.set(run.runId, run);return map;}, [linkedRuns]);+ const verificationCaveatsByRunId = useMemo(() => {+ const map = new Map<+ string,+ ReturnType<typeof acceptedSemanticResultVerificationCaveats>+ >();+ for (const run of linkedRuns ?? []) {+ const caveats = acceptedSemanticResultVerificationCaveats(run.resultJson);+ if (caveats.length > 0) map.set(run.runId, caveats);+ }+ return map;+ }, [linkedRuns]);++ // Historical placeholder comments remain untouched in storage. Projection+ // prefers the accepted semantic result so runs such as DOT-20 recover their+ // real upstream response without a data migration.+ const projectedComments = useMemo(+ () =>+ comments.map((comment) => {+ if (comment.body !== LEGACY_WITHHELD_RUN_COMMENT || !comment.runId)+ return comment;+ const summary = acceptedSemanticResultSummary(+ linkedRunMetaById.get(comment.runId)?.resultJson,+ );+ return summary ? { ...comment, body: summary } : comment;+ }),+ [comments, linkedRunMetaById],+ );+const commentItems = useMemo(- () => commentsToTaskChatItems(comments, {+ () =>+ commentsToTaskChatItems(projectedComments, {+ agentMap,+ userLabelMap,+ currentUserId,+ issueAssigneeAgentId,+ verificationCaveatsByRunId,+ }),+ [+ projectedComments,agentMap,userLabelMap,currentUserId,issueAssigneeAgentId,- }),- [comments, agentMap, userLabelMap, currentUserId, issueAssigneeAgentId],+ verificationCaveatsByRunId,+ ],);// Every run we might need a transcript for (history + live), deduped by id.@@ -271,6 +731,63 @@ export function TaskChatThread(props: TaskChatThreadProps) {return (liveRuns ?? []).find((r) => isLiveIssueRun(r, issueStatus)) ?? null;}, [activeRun, issueStatus, liveRuns]);+ // The live runner turn remains the sole owner of its response until the+ // canonical comment and settled activity are both ready. This state is+ // established in a layout effect so the live lane never disappears for a+ // paint between `liveRun` ending and the persistence handoff beginning.+ const [settlingRun, setSettlingRun] = useState<{+ id: string;+ startedAtMs: number | null;+ } | null>(null);+ const prevLiveRunRef = useRef<typeof liveRun>(null);+ useLayoutEffect(() => {+ if (liveRun) {+ prevLiveRunRef.current = liveRun;+ setSettlingRun((current) =>+ current && current.id !== liveRun.id ? null : current,+ );+ return;+ }+ const prev = prevLiveRunRef.current;+ prevLiveRunRef.current = null;+ if (!prev) return;+ setSettlingRun({+ id: prev.id,+ startedAtMs:+ (prev.startedAt ? toMs(prev.startedAt) : null) ?? toMs(prev.createdAt),+ });+ }, [liveRun]);++ const heldPaperclipRunnerRunId =+ liveRun && isNativePaperclipRunnerRun(liveRun)+ ? liveRun.id+ : settlingRun &&+ isNativePaperclipRunnerRun(+ runs.find((run) => run.id === settlingRun.id),+ )+ ? settlingRun.id+ : null;+ const heldPaperclipRunnerStartedAtMs =+ liveRun && heldPaperclipRunnerRunId === liveRun.id+ ? ((liveRun.startedAt ? toMs(liveRun.startedAt) : null) ??+ toMs(liveRun.createdAt))+ : (settlingRun?.startedAtMs ?? null);+ const heldPaperclipRunnerFinalText = useMemo(() => {+ if (!heldPaperclipRunnerRunId) return null;+ const entries = transcriptByRun.get(heldPaperclipRunnerRunId) ?? [];+ for (let index = entries.length - 1; index >= 0; index -= 1) {+ const entry = entries[index];+ if (+ entry.kind === "assistant" &&+ entry.channel === "final" &&+ entry.text.trim()+ ) {+ return entry.text;+ }+ }+ return null;+ }, [heldPaperclipRunnerRunId, transcriptByRun]);+// Runs observed non-terminal while mounted: their turns ANIMATE the fold when// they settle. Runs already terminal at mount collapse instantly.const liveSeenRef = useRef<Set<string>>(new Set());@@ -289,35 +806,188 @@ export function TaskChatThread(props: TaskChatThreadProps) {if (comment.deletedAt || !comment.runId || !comment.id) continue;map.set(comment.runId, comment.id);}+ // A settled Paperclip turn normally attaches to its durable final reply.+ // Same-turn steering splits that causal interval into timestamped segments,+ // so each segment must stay unanchored and interleave around the injected+ // human bubble through the chronological assembler.+ for (const comment of comments) {+ const runId = comment.steeredIntoRunId;+ if (!comment.deletedAt && runId && comment.conversationAnchorAt) {+ map.delete(runId);+ }+ }+ return map;+ }, [comments]);++ const steeringAnchorsByRun = useMemo(() => {+ const map = new Map<string, number[]>();+ for (const comment of comments) {+ const runId = comment.steeredIntoRunId;+ if (comment.deletedAt || !runId || !comment.conversationAnchorAt)+ continue;+ const anchorMs = toMs(comment.conversationAnchorAt);+ if (!Number.isFinite(anchorMs)) continue;+ const anchors = map.get(runId) ?? [];+ if (!anchors.includes(anchorMs)) anchors.push(anchorMs);+ map.set(runId, anchors);+ }+ for (const anchors of map.values()) anchors.sort((a, b) => a - b);return map;}, [comments]);const { data: planDocument } = useIssuePlanDocument(issueId);+ // A native-runner Plan is part of the turn that wrote its current revision.+ // Legacy adapters do not expose the semantic write_document boundary needed+ // for stable embedding, so their Plans remain chronological thread entries.+ // Prefer a native review request's explicit run binding; while that request+ // is still being created, infer the native owner from the document timestamp.+ const planDocumentSourceRunId = useMemo(() => {+ if (!planDocument) return null;+ const candidates = new Map<+ string,+ {+ id: string;+ adapterType: string;+ runtimeMode?: string | null;+ agentId?: string | null;+ createdAt?: Date | string | null;+ startedAt?: Date | string | null;+ finishedAt?: Date | string | null;+ }+ >();+ for (const run of linkedRuns ?? []) {+ candidates.set(run.runId, {+ ...run,+ id: run.runId,+ adapterType: run.adapterType ?? "",+ });+ }+ for (const run of liveRuns ?? []) candidates.set(run.id, run);+ if (activeRun) candidates.set(activeRun.id, activeRun);++ const linkedReview = (interactions ?? []).find(+ (interaction) => {+ if (!interaction.sourceRunId) return false;+ const sourceRun = candidates.get(interaction.sourceRunId);+ return (+ isNativePaperclipRunnerRun(sourceRun) &&+ interactionTargetsPlanRevision(interaction, planDocument)+ );+ },+ );+ if (linkedReview?.sourceRunId) return linkedReview.sourceRunId;++ const documentAtMs = toMs(planDocument.updatedAt);+ const matchingRuns = [...candidates.values()].filter((run) => {+ if (!isNativePaperclipRunnerRun(run)) return false;+ if (+ planDocument.updatedByAgentId &&+ run.agentId &&+ planDocument.updatedByAgentId !== run.agentId+ ) {+ return false;+ }+ const startedAtMs = toMs(run.startedAt ?? run.createdAt);+ const finishedAtMs = run.finishedAt+ ? toMs(run.finishedAt)+ : Number.POSITIVE_INFINITY;+ return (+ startedAtMs <= documentAtMs + 1_000 &&+ documentAtMs <= finishedAtMs + 1_000+ );+ });+ matchingRuns.sort(+ (a, b) =>+ toMs(b.startedAt ?? b.createdAt) - toMs(a.startedAt ?? a.createdAt),+ );+ return matchingRuns[0]?.id ?? null;+ }, [activeRun, interactions, linkedRuns, liveRuns, planDocument]);++ const planTurnItem = useMemo<TaskChatPlanDocumentItem | null>(() => {+ if (!planDocument || !planDocumentSourceRunId) return null;+ return {+ id: `plan-doc:${planDocument.latestRevisionId ?? planDocument.id}`,+ kind: "plan_document",+ document: planDocument,+ };+ }, [planDocument, planDocumentSourceRunId]);+// Comments, interactions, and the plan-doc marker merged into one// chronological backbone (same sort keys and same-run handoff shift as the// legacy buildIssueChatMessages), so plan-mode confirmation/question cards// land where they happened in the conversation.const orderedEntries = useMemo(() => {- const entries: { ms: number; order: number; id: string; item: TaskChatItem }[] = [];+ const entries: {+ ms: number;+ order: number;+ id: string;+ item: TaskChatItem;+ }[] = [];// commentsToTaskChatItems skips deleted comments — mirror its filter so the// two lists stay index-aligned.- const visibleComments = comments.filter((comment) => !comment.deletedAt);+ const visibleComments = projectedComments.filter(+ (comment) => !comment.deletedAt,+ );visibleComments.forEach((comment, index) => {+ if (queuedCommentIds.has(comment.id)) return;+ // The live/settling runner lane already renders this run's final answer.+ // Keep a just-persisted duplicate out of the backbone until the complete+ // canonical bubble + Worked header can replace that lane atomically.+ if (+ heldPaperclipRunnerRunId &&+ isRunnerResponseComment({+ comment,+ runId: heldPaperclipRunnerRunId,+ runStartedAtMs: heldPaperclipRunnerStartedAtMs,+ finalText: heldPaperclipRunnerFinalText,+ })+ )+ return;const item = commentItems[index];if (!item) return;- entries.push({ ms: toMs(comment.createdAt), order: 1, id: item.id, item });+ entries.push({+ // A held/queued input belongs where the runner actually consumes it,+ // not where the user first submitted it while another turn was live.+ ms: comment.conversationAnchorAt+ ? toMs(comment.conversationAnchorAt)+ : toMs(comment.createdAt),+ order:+ 1 + Math.min(comment.conversationAnchorSequence ?? 0, 999) / 1000,+ id: item.id,+ item,+ });});for (const interaction of interactions ?? []) {// Withdrawn/superseded confirmations are retracted calls to action — drop- // them so a dead card never stacks above the one that replaced it- // (PAP-416).+ // them so a dead card never stacks above the one that replaced it.if (isSuppressedThreadInteraction(interaction)) continue;// A never-rendered card — a degenerate `ask_user_questions` (e.g. the// onboarding `Test / A` placeholder) or a stale sibling superseded by a// newer question (PAP-437) — is filtered here so it leaves no empty slot// or gap in the ordered backbone (PAP-424, plan from PAP-420).- if (shouldHideInteractionCard(interaction)) continue;+ const isSupersededQuestionReceipt =+ interaction.kind === "ask_user_questions" &&+ interaction.status !== "pending" &&+ interaction.result?.expirationReason ===+ "superseded_by_newer_interaction";+ if (+ shouldHideInteractionCard(interaction) &&+ !isSupersededQuestionReceipt+ )+ continue;+ // The plan preview is already embedded at this run's write_document+ // boundary. Pending controls live in the composer takeover, so mounting+ // the interaction's second preview here would make the plan jump and+ // duplicate during the live-to-settled handoff.+ if (+ interaction.status === "pending" &&+ planDocument &&+ planDocumentSourceRunId === interaction.sourceRunId &&+ interactionTargetsPlanRevision(interaction, planDocument)+ ) {+ continue;+ }const createdAtMs = toMs(interaction.createdAt);const handoffAtMs =interaction.kind === "request_confirmation" && interaction.sourceRunId@@ -332,17 +1002,92 @@ export function TaskChatThread(props: TaskChatThreadProps) {: null;const id = `interaction:${interaction.id}`;entries.push({- // A resolved card settles at its resolution time so it never reads- // above a message written before the user answered (PAP-416); pending- // cards keep the request-time (handoff/createdAt) slot.- ms: interactionThreadAnchorMs(interaction, handoffAtMs ?? createdAtMs),+ // Question forms and plan previews remain where they were asked. Their+ // separately projected human responses stay at resolvedAt.+ ms: isResolvedPlanConfirmation(interaction)+ ? (handoffAtMs ?? createdAtMs)+ : interactionThreadAnchorMs(+ interaction,+ handoffAtMs ?? createdAtMs,+ ),order: 2,id,item: { id, kind: "interaction", interaction },});}- if (planDocument) {- const revision = planDocument.latestRevisionNumber ?? 1;+ for (const document of documents) {+ if (document.key === "plan") continue;+ const id = `resource:document:${document.id}`;+ entries.push({+ ms: toMs(document.updatedAt),+ order: 3,+ id,+ item: {+ id,+ kind: "protocol",+ surface: "resource",+ resourceKind: "document",+ title: documentDisplayTitle(document),+ subtitle: `Document · rev ${document.latestRevisionNumber}`,+ href: buildDocumentAnnotationHash({+ documentKey: document.key,+ threadId: null,+ commentId: null,+ }),+ timestamp: new Date(document.updatedAt).toISOString(),+ document,+ },+ });+ }+ for (const workProduct of workProducts) {+ const id = `resource:deliverable:${workProduct.id}`;+ const href = workProductHref(workProduct);+ entries.push({+ ms: toMs(workProduct.createdAt),+ order: 3,+ id,+ item: {+ id,+ kind: "protocol",+ surface: "resource",+ resourceKind: "deliverable",+ title: workProduct.title,+ subtitle: [+ workProduct.type.replaceAll("_", " "),+ workProduct.status,+ workProduct.reviewState !== "none" ? workProduct.reviewState : null,+ ]+ .filter(Boolean)+ .join(" · "),+ href: safeResourceHref(href),+ timestamp: new Date(workProduct.createdAt).toISOString(),+ workProduct,+ },+ });+ }+ for (const attachment of selectAgentArtifactAttachments(+ attachments,+ workProducts,+ )) {+ const id = `resource:attachment:${attachment.id}`;+ entries.push({+ ms: toMs(attachment.createdAt),+ order: 3,+ id,+ item: {+ id,+ kind: "protocol",+ surface: "resource",+ resourceKind: "attachment",+ title: attachment.originalFilename ?? "Agent attachment",+ subtitle: `${attachment.contentType} · ${formatResourceBytes(attachment.byteSize)}`,+ href: safeResourceHref(attachment.openPath ?? attachment.contentPath),+ timestamp: new Date(attachment.createdAt).toISOString(),+ attachment,+ },+ });+ }+ if (planDocument && !planDocumentSourceRunId) {const id = `plan-doc:${planDocument.latestRevisionId ?? planDocument.id}`;entries.push({ms: toMs(planDocument.updatedAt),@@ -350,34 +1095,121 @@ export function TaskChatThread(props: TaskChatThreadProps) {id,item: {id,- kind: "marker",- variant: "turn_boundary",- label: revision > 1 ? "Plan updated" : "Plan created",- detail: `rev ${revision} — see the Plan tab`,+ kind: "plan_document",+ document: planDocument,},});}return entries.sort((a, b) => a.ms - b.ms || a.order - b.order || a.id.localeCompare(b.id),);- }, [comments, commentItems, interactions, timelineEvents, linkedRuns, liveRuns, planDocument]);+ }, [+ comments,+ projectedComments,+ commentItems,+ interactions,+ documents,+ workProducts,+ attachments,+ timelineEvents,+ linkedRuns,+ liveRuns,+ planDocument,+ planDocumentSourceRunId,+ heldPaperclipRunnerRunId,+ heldPaperclipRunnerStartedAtMs,+ heldPaperclipRunnerFinalText,+ queuedCommentIds,+ ]);++ const legacyTimelineAnchorsByRun = useMemo(() => {+ const windows = new Map<+ string,+ {+ adapterType: string;+ runtimeMode?: string | null;+ startMs: number;+ endMs: number;+ }+ >();+ for (const run of linkedRuns ?? []) {+ windows.set(run.runId, {+ adapterType: run.adapterType ?? "",+ runtimeMode: run.runtimeMode,+ startMs: toMs(run.startedAt ?? run.createdAt),+ endMs: run.finishedAt+ ? toMs(run.finishedAt)+ : Number.POSITIVE_INFINITY,+ });+ }+ for (const run of liveRuns ?? []) {+ windows.set(run.id, {+ adapterType: run.adapterType,+ runtimeMode: run.runtimeMode,+ startMs: toMs(run.startedAt ?? run.createdAt),+ endMs: run.finishedAt+ ? toMs(run.finishedAt)+ : Number.POSITIVE_INFINITY,+ });+ }+ if (activeRun) {+ windows.set(activeRun.id, {+ adapterType: activeRun.adapterType,+ runtimeMode: activeRun.runtimeMode,+ startMs: toMs(activeRun.startedAt ?? activeRun.createdAt),+ endMs: activeRun.finishedAt+ ? toMs(activeRun.finishedAt)+ : Number.POSITIVE_INFINITY,+ });+ }++ const anchorsByRun = new Map<string, number[]>();+ for (const [runId, window] of windows) {+ if (+ isNativePaperclipRunnerRun(window) ||+ !Number.isFinite(window.startMs)+ ) {+ continue;+ }+ const anchors = orderedEntries+ .map((entry) => entry.ms)+ .filter(+ (entryMs) =>+ Number.isFinite(entryMs) &&+ entryMs > window.startMs &&+ entryMs <= window.endMs,+ );+ if (anchors.length > 0) {+ anchorsByRun.set(runId, [...new Set(anchors)].sort((a, b) => a - b));+ }+ }+ return anchorsByRun;+ }, [activeRun, linkedRuns, liveRuns, orderedEntries]);// Boolean gate (stable across the host's per-render brief objects) so the// heavy assembly memo doesn't recompute on every parent render.const hasBrief = Boolean(issueBrief);- const { items, settledRunIds } = useMemo<{ items: TaskChatItem[]; settledRunIds: Set<string> }>(() => {+ const { items, settledRunIds } = useMemo<{+ items: TaskChatItem[];+ settledRunIds: Set<string>;+ }>(() => {// Runs whose settled turn made it into the assembled thread — the live tail// hands off to this as its "the settled turn has rendered" signal (PAP-462// B4), so the transcript stays mounted through the settle gap without ever// double-rendering beside its own settled turn.const settledRunIds = new Set<string>();- // Settled turns for every terminal run whose transcript we have. Messages- // and thinking are excluded entirely (PAP-361): the final reply already- // landed as the run's comment bubble, interstitial updates are ephemeral- // (live-line only), and thinking stays in the run log / classic- // transcript — "Worked · N tools" expands to exactly the tool rows.- const settledTurns: { turn: TaskChatTurnItem; anchorCommentId: string | null; startMs: number }[] = [];+ const entriesWithFailures = [...orderedEntries];+ // Settled turns for every terminal run whose transcript we have. Provider+ // commentary, grouped activity (including reasoning summaries), and+ // terminal request receipts remain in transcript order. Final text is+ // owned by a posted comment when one exists; yielded interaction runs keep+ // the accepted summary in the turn's durable response slot instead.+ const settledTurns: {+ turn: TaskChatTurnItem;+ anchorCommentId: string | null;+ startMs: number;+ }[] = [];// Raw summary inputs per turn id, so back-to-back same-agent runs can// coalesce into one "Worked" row in the final pass (PAP-362).const turnMergeMetaById = new Map<string, SettledTurnMergeMeta>();@@ -385,47 +1217,315 @@ export function TaskChatThread(props: TaskChatThreadProps) {if (!isTerminalRunStatus(source.status)) continue;if (liveRun && source.id === liveRun.id) continue;const entries = transcriptByRun.get(source.id) ?? [];- if (entries.length === 0) continue;const meta = linkedRunMetaById.get(source.id);- const started = meta?.startedAt ? new Date(meta.startedAt).getTime() : NaN;- const finished = meta?.finishedAt ? new Date(meta.finishedAt).getTime() : NaN;+ const acceptedSummary = acceptedSemanticResultSummary(meta?.resultJson);+ if (entries.length === 0) {+ if (+ isNativePaperclipRunnerRun(source) &&+ acceptedSummary &&+ !lastCommentIdByRun.has(source.id)+ ) {+ const startedAtMs = toMs(meta?.startedAt ?? meta?.createdAt);+ const finishedAtMs = toMs(meta?.finishedAt);+ const durationMs =+ startedAtMs > 0 && finishedAtMs > 0+ ? Math.max(0, finishedAtMs - startedAtMs)+ : undefined;+ const failed = source.status !== "succeeded";+ const turnId = `${source.id}:turn`;+ turnMergeMetaById.set(turnId, {+ agentKey: meta?.agentId ?? "",+ agentName: meta?.agentName,+ parts: [{ entries, durationMs, failed }],+ });+ settledTurns.push({+ turn: {+ id: turnId,+ kind: "turn",+ settled: true,+ agentName:+ meta?.agentName ??+ (meta?.agentId ? agentMap?.get(meta.agentId)?.name : undefined),+ agentIcon: meta?.agentId+ ? agentMap?.get(meta.agentId)?.icon+ : undefined,+ standaloneHeader: true,+ animateFold: liveSeenRef.current.has(source.id),+ items: [],+ finalResponse: paperclipRunnerFinalResponse([], {+ runId: source.id,+ agentName: meta?.agentName,+ fallbackSummary: acceptedSummary,+ }),+ summary: buildTurnSummary(entries, { durationMs, failed }),+ },+ anchorCommentId: null,+ startMs: startedAtMs > 0 ? startedAtMs : Number.POSITIVE_INFINITY,+ });+ settledRunIds.add(source.id);+ } else if (+ source.status === "failed" ||+ source.status === "timed_out"+ ) {+ settledRunIds.add(source.id);+ const code = meta?.errorCode ?? "native_runner_process_exited";+ const retryDetail = meta?.scheduledRetryAt+ ? "Retry scheduled automatically."+ : "You can retry this message now.";+ const detail =+ code === "provider_frame_too_large"+ ? `Provider output exceeded the safe limit. ${retryDetail}`+ : `The runner stopped before returning an answer (${code}). ${retryDetail}`;+ const id = `${source.id}:failure`;+ entriesWithFailures.push({+ ms: toMs(meta?.finishedAt ?? meta?.startedAt ?? meta?.createdAt),+ order: 3,+ id,+ item: {+ id,+ kind: "marker",+ variant: "interrupted",+ label: "Run failed",+ detail,+ },+ });+ } else if (!lastCommentIdByRun.has(source.id)) {+ settledRunIds.add(source.id);+ const id = `${source.id}:terminal-notice`;+ entriesWithFailures.push({+ ms: toMs(meta?.finishedAt ?? meta?.startedAt ?? meta?.createdAt),+ order: 3,+ id,+ item: {+ id,+ kind: "marker",+ variant: "turn_boundary",+ label: "Run completed",+ detail: "The runner returned no user-facing response.",+ },+ });+ }+ continue;+ }+ const started = meta?.startedAt+ ? new Date(meta.startedAt).getTime()+ : NaN;+ const finished = meta?.finishedAt+ ? new Date(meta.finishedAt).getTime()+ : NaN;const durationMs =Number.isFinite(started) && Number.isFinite(finished)? Math.max(0, finished - started): undefined;- const parsed = transcriptToTaskChatItems(entries, {- runId: source.id,- agentName: meta?.agentName,- running: false,- });- const children = settledRunChildren(parsed);- if (children.length === 0) continue;- settledRunIds.add(source.id);+ const sourceIsPaperclipRunner = isNativePaperclipRunnerRun(source);+ const hasPaperclipRunnerResponse =+ sourceIsPaperclipRunner &&+ Boolean(+ acceptedSummary ||+ entries.some(+ (entry) =>+ (entry.kind === "assistant" &&+ entry.channel === "final" &&+ Boolean(entry.text.trim())) ||+ (entry.kind === "run_result" && Boolean(entry.summary.trim())),+ ),+ );+ if (+ source.status === "succeeded" &&+ !lastCommentIdByRun.has(source.id) &&+ resolvedWithoutUserFacingResponse(meta?.resultJson) &&+ !hasPaperclipRunnerResponse+ ) {+ const id = `${source.id}:terminal-notice`;+ entriesWithFailures.push({+ ms: toMs(meta?.finishedAt ?? meta?.startedAt ?? meta?.createdAt),+ order: 3,+ id,+ item: {+ id,+ kind: "marker",+ variant: "turn_boundary",+ label: "Run completed",+ detail: "The runner returned no user-facing response.",+ },+ });+ }const failed = source.status !== "succeeded";const startSlotRaw = meta?.startedAt ?? meta?.createdAt;- turnMergeMetaById.set(`${source.id}:turn`, {- agentKey: meta?.agentId ?? "",- agentName: meta?.agentName,- parts: [{ entries, durationMs, failed }],- });- settledTurns.push({- turn: {- id: `${source.id}:turn`,- kind: "turn",- settled: true,- animateFold: liveSeenRef.current.has(source.id),- items: children,- summary: buildTurnSummary(entries, { durationMs, failed }),- },- anchorCommentId: lastCommentIdByRun.get(source.id) ?? null,- // Chronological slot for a turn with no reply comment to anchor to- // (PAP-367): the run's start time. A run with no linked meta yet- // (just-settled, list not refetched) sits at the thread tail —- // where it last rendered as the live turn — until meta arrives.- startMs: startSlotRaw ? toMs(startSlotRaw) : Number.POSITIVE_INFINITY,- });+ const startSlotMs = startSlotRaw+ ? toMs(startSlotRaw)+ : Number.POSITIVE_INFINITY;+ const timelineAnchors =+ sourceIsPaperclipRunner+ ? (steeringAnchorsByRun.get(source.id) ?? [])+ : (legacyTimelineAnchorsByRun.get(source.id) ?? []);+ const segments = splitTranscriptAtAnchors(+ entries,+ startSlotMs,+ timelineAnchors,+ );+ for (const [segmentIndex, segment] of segments.entries()) {+ if (segment.entries.length === 0) continue;+ const parsedTranscript = transcriptToTaskChatItems(segment.entries, {+ runId: source.id,+ agentName: meta?.agentName,+ running: false,+ });+ const parsed =+ source.id === planDocumentSourceRunId && planTurnItem+ ? embedPlanDocumentAtWriteBoundary(parsedTranscript, planTurnItem)+ : parsedTranscript;+ const children = settledRunChildren(+ sourceIsPaperclipRunner+ ? paperclipRunnerTimelineItems(parsed)+ : parsed,+ );+ const finalResponse =+ sourceIsPaperclipRunner &&+ !lastCommentIdByRun.has(source.id)+ ? paperclipRunnerFinalResponse(parsed, {+ runId: source.id,+ agentName: meta?.agentName,+ fallbackSummary: acceptedSummary,+ })+ : undefined;+ if (+ children.length === 0 &&+ !finalResponse &&+ !sourceIsPaperclipRunner+ )+ continue;+ settledRunIds.add(source.id);+ const segmented = timelineAnchors.length > 0;+ const turnId = segmented+ ? `${source.id}:turn:${segmentIndex}`+ : `${source.id}:turn`;+ const segmentFinishedMs = Number.isFinite(segment.endMs)+ ? segment.endMs+ : finished;+ const segmentDurationMs =+ Number.isFinite(segment.startMs) && Number.isFinite(segmentFinishedMs)+ ? Math.max(0, segmentFinishedMs - segment.startMs)+ : durationMs;+ turnMergeMetaById.set(turnId, {+ agentKey: meta?.agentId ?? "",+ agentName: meta?.agentName,+ parts: [+ { entries: segment.entries, durationMs: segmentDurationMs, failed },+ ],+ });+ settledTurns.push({+ turn: {+ id: turnId,+ kind: "turn",+ settled: true,+ agentName:+ meta?.agentName ??+ (meta?.agentId ? agentMap?.get(meta.agentId)?.name : undefined),+ agentIcon: meta?.agentId+ ? agentMap?.get(meta.agentId)?.icon+ : undefined,+ standaloneHeader: sourceIsPaperclipRunner,+ animateFold: liveSeenRef.current.has(source.id),+ items: children,+ finalResponse,+ summary: buildTurnSummary(segment.entries, {+ durationMs: segmentDurationMs,+ failed,+ }),+ },+ anchorCommentId: segmented+ ? null+ : (lastCommentIdByRun.get(source.id) ?? null),+ // A post-steering segment ties the acknowledgement-backed human+ // bubble and is therefore inserted immediately after it. The first+ // segment retains the normal run-start slot.+ startMs: segment.startMs,+ });+ }}- settledTurns.sort((a, b) => (a.startMs < b.startMs ? -1 : a.startMs > b.startMs ? 1 : 0));++ // Same-turn steering is visible before a live run settles. Freeze every+ // completed pre-steer interval into the main chronology immediately, then+ // leave only the last interval to the streaming tail below. Reusing the+ // settled ids and projection makes the terminal handoff structurally+ // identical instead of moving one unsplit live turn around the steer.+ if (liveRun) {+ const timelineAnchors =+ isNativePaperclipRunnerRun(liveRun)+ ? (steeringAnchorsByRun.get(liveRun.id) ?? [])+ : (legacyTimelineAnchorsByRun.get(liveRun.id) ?? []);+ if (timelineAnchors.length > 0) {+ const entries = transcriptByRun.get(liveRun.id) ?? [];+ const startSlotMs =+ (liveRun.startedAt ? toMs(liveRun.startedAt) : null) ??+ toMs(liveRun.createdAt);+ const segments = splitTranscriptAtAnchors(+ entries,+ startSlotMs,+ timelineAnchors,+ );+ for (const [segmentIndex, segment] of segments.slice(0, -1).entries()) {+ if (segment.entries.length === 0) continue;+ const parsedTranscript = transcriptToTaskChatItems(segment.entries, {+ runId: liveRun.id,+ agentName: liveRun.agentName,+ running: false,+ });+ const parsed =+ liveRun.id === planDocumentSourceRunId && planTurnItem+ ? embedPlanDocumentAtWriteBoundary(parsedTranscript, planTurnItem)+ : parsedTranscript;+ const children = settledRunChildren(+ isNativePaperclipRunnerRun(liveRun)+ ? paperclipRunnerTimelineItems(parsed)+ : parsed,+ );+ if (children.length === 0) continue;+ const turnId = `${liveRun.id}:turn:${segmentIndex}`;+ const segmentDurationMs =+ Number.isFinite(segment.startMs) && Number.isFinite(segment.endMs)+ ? Math.max(0, segment.endMs - segment.startMs)+ : undefined;+ turnMergeMetaById.set(turnId, {+ agentKey: liveRun.agentId ?? "",+ agentName: liveRun.agentName,+ parts: [+ {+ entries: segment.entries,+ durationMs: segmentDurationMs,+ failed: false,+ },+ ],+ });+ settledTurns.push({+ turn: {+ id: turnId,+ kind: "turn",+ settled: true,+ agentName:+ liveRun.agentName ??+ (liveRun.agentId+ ? agentMap?.get(liveRun.agentId)?.name+ : undefined),+ agentIcon: liveRun.agentId+ ? agentMap?.get(liveRun.agentId)?.icon+ : undefined,+ standaloneHeader: isNativePaperclipRunnerRun(liveRun),+ items: children,+ summary: buildTurnSummary(segment.entries, {+ durationMs: segmentDurationMs,+ }),+ },+ anchorCommentId: null,+ startMs: segment.startMs,+ });+ }+ }+ }+ settledTurns.sort((a, b) =>+ a.startMs < b.startMs ? -1 : a.startMs > b.startMs ? 1 : 0,+ );const turnsByAnchor = new Map<string, TaskChatTurnItem[]>();const unanchored: { turn: TaskChatTurnItem; startMs: number }[] = [];@@ -443,7 +1543,14 @@ export function TaskChatThread(props: TaskChatThreadProps) {// (stopped runs, or a reply not yet fetched) interleave chronologically at// their run's start time instead of piling up under the newest message// (PAP-367).- const out = assembleThreadItems(orderedEntries, turnsByAnchor, unanchored);+ entriesWithFailures.sort(+ (a, b) => a.ms - b.ms || a.order - b.order || a.id.localeCompare(b.id),+ );+ const out = assembleThreadItems(+ entriesWithFailures,+ turnsByAnchor,+ unanchored,+ );// PAP-362: two runs replying back-to-back (same agent, nothing but the// agent's own bubbles between) fold into ONE "Worked" row below the last@@ -455,53 +1562,73 @@ export function TaskChatThread(props: TaskChatThreadProps) {// every assembly/merge pass, so nothing can ever sort above it.return {items: prependIssueBrief(- attachSettledTurns(coalesceSettledTurns(out, turnMergeMetaById), turnMergeMetaById),+ attachSettledTurns(+ coalesceSettledTurns(out, turnMergeMetaById),+ turnMergeMetaById,+ ),hasBrief,),settledRunIds,};- }, [orderedEntries, runs, liveRun, transcriptByRun, linkedRunMetaById, lastCommentIdByRun, hasBrief]);-- // PAP-462 B4: the moment a run settles, `liveRun` flips to null — but its- // settled turn (or reply comment) can take seconds to arrive on the next- // comment refetch. Without a handoff the whole transcript unmounts that frame,- // blinking out already-streamed output before its settled form renders. Snapshot- // the just-settled run so its now-static transcript stays mounted through the gap.- const [settlingRun, setSettlingRun] = useState<{ id: string; startedAtMs: number | null } | null>(null);- const prevLiveRunRef = useRef<typeof liveRun>(null);- // Layout effect (not passive): snapshot the settled run before the browser- // paints the `liveRun === null` frame, so the tail never blinks empty for a- // frame between the run stopping and this snapshot committing.- useLayoutEffect(() => {- if (liveRun) {- prevLiveRunRef.current = liveRun;- // A fresh live run supersedes any lingering settled remnant.- setSettlingRun((current) => (current && current.id !== liveRun.id ? null : current));- return;- }- const prev = prevLiveRunRef.current;- prevLiveRunRef.current = null;- if (!prev) return;- setSettlingRun({- id: prev.id,- startedAtMs: (prev.startedAt ? toMs(prev.startedAt) : null) ?? toMs(prev.createdAt),- });- }, [liveRun]);+ }, [+ orderedEntries,+ runs,+ liveRun,+ transcriptByRun,+ linkedRunMetaById,+ lastCommentIdByRun,+ steeringAnchorsByRun,+ legacyTimelineAnchorsByRun,+ hasBrief,+ planDocumentSourceRunId,+ planTurnItem,+ agentMap,+ ]);// Hand off once the settled turn or its reply comment is in the thread; a// stopped run that yields neither is released by the backstop timeout so the// tail never lingers indefinitely.+ const settlingIsPaperclipRunner =+ settlingRun != null &&+ isNativePaperclipRunnerRun(+ runs.find((run) => run.id === settlingRun.id),+ );+ const settlingHasComment =+ settlingRun != null &&+ comments.some((comment) =>+ settlingIsPaperclipRunner+ ? isRunnerResponseComment({+ comment,+ runId: settlingRun.id,+ runStartedAtMs: settlingRun.startedAtMs,+ finalText: heldPaperclipRunnerFinalText,+ })+ : comment.runId === settlingRun.id && !comment.deletedAt,+ );+ const settlingHasDurableInteraction =+ settlingRun != null &&+ (interactions ?? []).some(+ (interaction) =>+ interaction.sourceRunId === settlingRun.id &&+ !isSuppressedThreadInteraction(interaction) &&+ !shouldHideInteractionCard(interaction),+ );const settledRunRendered =settlingRun != null &&- (settledRunIds.has(settlingRun.id) ||- comments.some((comment) => comment.runId === settlingRun.id && !comment.deletedAt));+ (settlingIsPaperclipRunner+ ? settledRunIds.has(settlingRun.id) &&+ (settlingHasComment || settlingHasDurableInteraction)+ : settlingHasComment || settledRunIds.has(settlingRun.id));useEffect(() => {if (!settlingRun) return;if (settledRunRendered) {setSettlingRun(null);return;}- const timer = window.setTimeout(() => setSettlingRun(null), SETTLING_TAIL_MAX_MS);+ const timer = window.setTimeout(+ () => setSettlingRun(null),+ SETTLING_TAIL_MAX_MS,+ );return () => window.clearTimeout(timer);}, [settlingRun, settledRunRendered]);@@ -512,34 +1639,60 @@ export function TaskChatThread(props: TaskChatThreadProps) {settlingRun != null &&!settledRunRendered &&(transcriptByRun.get(settlingRun.id)?.length ?? 0) > 0;- const tailRunId = liveRun ? liveRun.id : showSettlingTail ? settlingRun!.id : null;+ const tailRunId = liveRun+ ? liveRun.id+ : showSettlingTail+ ? settlingRun!.id+ : null;const tailStreaming = Boolean(liveRun);- const tailEntries = tailRunId ? (transcriptByRun.get(tailRunId) ?? []) : [];const tailRunSource = tailRunId? runs.find((run) => run.id === tailRunId): undefined;- const paperclipRunnerTail =- tailRunSource?.runtimeMode === "native" &&- tailRunSource.adapterType === "paperclip_runner";- const tailContentKey = tailEntries.reduce((key, entry) => {+ const paperclipRunnerTail = isNativePaperclipRunnerRun(tailRunSource);+ const tailAllEntries = tailRunId+ ? (transcriptByRun.get(tailRunId) ?? [])+ : [];+ const tailTimelineAnchors = tailRunId+ ? paperclipRunnerTail+ ? (steeringAnchorsByRun.get(tailRunId) ?? [])+ : (legacyTimelineAnchorsByRun.get(tailRunId) ?? [])+ : [];+ const tailSegmentStartMs =+ tailTimelineAnchors.length > 0+ ? tailTimelineAnchors[tailTimelineAnchors.length - 1]+ : null;+ const tailEntries =+ tailSegmentStartMs == null+ ? tailAllEntries+ : tailAllEntries.filter((entry) => toMs(entry.ts) >= tailSegmentStartMs);+ const tailPlanItem =+ tailRunId === planDocumentSourceRunId ? planTurnItem : null;+ // A fresh array is produced on every render. Track every presentation field+ // that can change without changing the entry count or text length so channel,+ // lifecycle, result status, and usage-only updates invalidate the projection.+ const tailEntryContentKey = tailEntries.reduce((key, entry) => {const textIdentity = "text" in entry ? entry.text : "";const contentIdentity = "content" in entry ? entry.content : "";const channelIdentity = "channel" in entry ? entry.channel ?? "" : "";const lifecycleIdentity = "lifecycle" in entry ? entry.lifecycle ?? "" : "";- const statusIdentity = "isError" in entry- ? entry.isError ? "error" : "ok"- : "";- const usageIdentity = entry.kind === "result"- ? `${entry.subtype}:${entry.inputTokens}:${entry.outputTokens}:${entry.cachedTokens}:${entry.costUsd}`- : "";+ const statusIdentity =+ "isError" in entry ? (entry.isError ? "error" : "ok") : "";+ const usageIdentity =+ entry.kind === "result"+ ? `${entry.subtype}:${entry.inputTokens}:${entry.outputTokens}:${entry.cachedTokens}:${entry.costUsd}`+ : "";return `${key}|${entry.kind}:${channelIdentity}:${lifecycleIdentity}:${statusIdentity}:${usageIdentity}:${textIdentity}:${contentIdentity}`;}, String(tailEntries.length));+ const tailContentKey = `${tailSegmentStartMs ?? "run-start"}:${tailEntryContentKey}`;const blockerContentKey = blockerLinks? `${blockerLinks.directBlocker.id}:${blockerLinks.ultimateBlocker?.id ?? ""}`: liveWorkLinks? `live:${liveWorkLinks.steps.map((step) => `${step.blocker.id}:${step.status}`).join(",")}:${liveWorkLinks.nowRunning.map((blocker) => blocker.id).join(",")}`: "";- const threadContentKey = `${taskChatContentKey(items)}:${tailContentKey}:${blockerContentKey}`;+ const tailPlanContentKey = tailPlanItem+ ? `${tailPlanItem.id}:${tailPlanItem.document.body.length}`+ : "";+ const threadContentKey = `${taskChatContentKey(items)}:${tailContentKey}:${tailPlanContentKey}:${blockerContentKey}`;// Status-pill inputs for the tail (PAP-461, A1): the run's start, its finish// (once terminal), and the "called N tools" summary. Memoized on the@@ -547,13 +1700,17 @@ export function TaskChatThread(props: TaskChatThreadProps) {// while the pill's own second-tick keeps the elapsed readout moving. Through// the settle gap the run reads terminal, so the pill lands on its "Worked"// state instead of flipping back to a spinner.- const settlingFinishedAt = settlingRun ? linkedRunMetaById.get(settlingRun.id)?.finishedAt : undefined;+ const settlingFinishedAt = settlingRun+ ? linkedRunMetaById.get(settlingRun.id)?.finishedAt+ : undefined;const tailStatus = liveRun? liveRun.status- : runs.find((run) => run.id === settlingRun?.id)?.status ?? "succeeded";+ : (runs.find((run) => run.id === settlingRun?.id)?.status ?? "succeeded");const tailStartedAtMs = liveRun- ? (liveRun.startedAt ? toMs(liveRun.startedAt) : null) ?? toMs(liveRun.createdAt)- : settlingRun?.startedAtMs ?? null;+ ? (tailSegmentStartMs ??+ (liveRun.startedAt ? toMs(liveRun.startedAt) : null) ??+ toMs(liveRun.createdAt))+ : (settlingRun?.startedAtMs ?? null);const tailFinishedAtMs = liveRun? liveRun.finishedAt? toMs(liveRun.finishedAt)@@ -576,20 +1733,221 @@ export function TaskChatThread(props: TaskChatThreadProps) {// pill's own second-tick keeps the elapsed readout moving. `running` follows// tailStreaming: true while live, false through the settle gap — so the tail// renders identically either side of the run finishing.- const tailAgentName = liveRun?.agentName ?? linkedRunMetaById.get(tailRunId ?? "")?.agentName;+ const tailAgentName =+ liveRun?.agentName ?? linkedRunMetaById.get(tailRunId ?? "")?.agentName;+ const tailAgentId =+ liveRun?.agentId ??+ linkedRunMetaById.get(tailRunId ?? "")?.agentId ??+ issueAssigneeAgentId;+ const tailAgent = tailAgentId ? agentMap?.get(tailAgentId) : undefined;+ const visibleTailAgentName = tailAgentName ?? tailAgent?.name ?? null;+ const visibleTailAgentIcon = tailAgent?.icon ?? null;const tailItems = useMemo(- () =>- tailRunId- ? transcriptToTaskChatItems(tailEntries, {- runId: tailRunId,- agentName: tailAgentName,- running: tailStreaming,- })- : [],+ () => {+ if (!tailRunId) return [];+ const parsed = transcriptToTaskChatItems(tailEntries, {+ runId: tailRunId,+ agentName: tailAgentName,+ running: tailStreaming,+ });+ return tailPlanItem+ ? embedPlanDocumentAtWriteBoundary(parsed, tailPlanItem)+ : parsed;+ },// tailEntries is a fresh array each render; tailContentKey tracks its content.// eslint-disable-next-line react-hooks/exhaustive-deps- [tailRunId, tailContentKey, tailStreaming, tailAgentName],+ [+ tailRunId,+ tailContentKey,+ tailStreaming,+ tailAgentName,+ tailPlanContentKey,+ ],+ );+ const tailTurnStatus = useMemo(+ () =>+ isTerminalRunStatus(tailStatus)+ ? null+ : taskChatTurnStatusModel(tailItems),+ [tailItems, tailStatus],+ );+ const pendingRuntimeRequest = latestPendingRuntimeRequest(tailItems);+ const handleRuntimeRequestDecision = useCallback(+ async (+ item: TaskChatRuntimeRequestItem,+ decision: TaskChatRuntimeRequestDecision,+ ) => {+ if (!item.turnId || !item.requestKind) {+ throw new Error(+ "This runtime request is missing the provider turn identity needed to resolve it.",+ );+ }+ let resolution: RuntimeRequestResolution;+ if (decision.action !== "submit") {+ resolution = decision;+ } else if ("response" in decision) {+ resolution = { action: "submit", response: decision.response };+ } else if (item.requestKind === "user_input") {+ resolution = {+ action: "submit",+ answers: Object.fromEntries(+ Object.entries(decision.values).map(([field, value]) => [+ field,+ { answers: [value] },+ ]),+ ),+ };+ } else if (item.requestKind === "elicitation") {+ resolution = { action: "submit", content: decision.values };+ } else {+ throw new Error(+ "This runtime permission does not accept submitted form data.",+ );+ }+ await heartbeatsApi.resolveRuntimeRequest({+ runId: item.runId,+ requestId: item.requestId,+ turnId: item.turnId,+ requestKind: item.requestKind,+ resolution,+ });+ },+ [],+ );+ const pendingComposerInputs = useMemo<PendingComposerInput[]>(() => {+ const result: PendingComposerInput[] = [];+ const runtimeKey = pendingRuntimeRequest+ ? `runtime:${pendingRuntimeRequest.runId}:${pendingRuntimeRequest.requestId}`+ : null;+ if (pendingRuntimeRequest && runtimeKey) {+ result.push({+ key: runtimeKey,+ kind: "runtime",+ item: pendingRuntimeRequest,+ label:+ pendingRuntimeRequest.questionSet?.title ??+ (pendingRuntimeRequest.requestType === "permission"+ ? "Runtime permission"+ : "Runtime input"),+ });+ }+ const durable = (interactions ?? [])+ .filter(+ (interaction) =>+ interaction.status === "pending" &&+ !shouldHideInteractionCard(interaction),+ )+ .sort((left, right) => toMs(right.createdAt) - toMs(left.createdAt));+ for (const interaction of durable) {+ const recoveredRuntimeKey =+ interaction.kind === "ask_user_questions" &&+ interaction.sourceRunId &&+ interaction.payload.runtimeRequestId+ ? `runtime:${interaction.sourceRunId}:${interaction.payload.runtimeRequestId}`+ : null;+ const key = recoveredRuntimeKey ?? `interaction:${interaction.id}`;+ if (key === runtimeKey) continue;+ result.push({+ key,+ kind: "durable",+ interaction,+ label: durableInputLabel(interaction),+ });+ }+ return result;+ }, [interactions, pendingRuntimeRequest]);+ const [takeoverMode, setTakeoverMode] = useState<"open" | "normal">("open");+ const [selectedPendingKey, setSelectedPendingKey] = useState<string | null>(+ null,+ );+ const knownPendingKeysRef = useRef<Set<string>>(new Set());+ useEffect(() => {+ const currentKeys = new Set(+ pendingComposerInputs.map((input) => input.key),+ );+ const hasNewInput = pendingComposerInputs.some(+ (input) => !knownPendingKeysRef.current.has(input.key),+ );+ knownPendingKeysRef.current = currentKeys;+ setSelectedPendingKey((current) =>+ current && currentKeys.has(current)+ ? current+ : (pendingComposerInputs[0]?.key ?? null),+ );+ if (hasNewInput) setTakeoverMode("open");+ }, [pendingComposerInputs]);+ const selectedPendingInput =+ pendingComposerInputs.find((input) => input.key === selectedPendingKey) ??+ pendingComposerInputs[0] ??+ null;+ const interactionDraftKey = selectedPendingInput+ ? `paperclip:task-input:${issueId ?? "unknown"}:${selectedPendingInput.key}`+ : undefined;+ const openPendingTakeover = useCallback(() => {+ setTakeoverMode("open");+ }, []);+ const showNextPendingInput = useCallback(() => {+ if (pendingComposerInputs.length < 2) return;+ const currentIndex = pendingComposerInputs.findIndex(+ (input) => input.key === selectedPendingInput?.key,+ );+ setSelectedPendingKey(+ pendingComposerInputs[(currentIndex + 1) % pendingComposerInputs.length]+ ?.key ?? null,+ );+ }, [pendingComposerInputs, selectedPendingInput?.key]);+ const skipPendingInput = useCallback(+ async (input: PendingComposerInput) => {+ if (input.kind === "runtime") {+ await handleRuntimeRequestDecision(input.item, { action: "cancel" });+ } else {+ if (!onSkipInteraction)+ throw new Error("Skipping this interaction is unavailable.");+ await onSkipInteraction(input.interaction);+ }+ setTakeoverMode("normal");+ },+ [handleRuntimeRequestDecision, onSkipInteraction],+ );+ const runtimeComposerDisabledReason = composerDisabledReason ?? undefined;+ const assigneeUsesPaperclipRunner = Boolean(+ issueAssigneeAgentId &&+ agentMap?.get(issueAssigneeAgentId)?.adapterType === "paperclip_runner",+ );+ const [runnerSubmissionPending, setRunnerSubmissionPending] = useState(false);+ useEffect(() => {+ if (tailRunId) setRunnerSubmissionPending(false);+ }, [tailRunId]);+ useEffect(() => {+ if (!runnerSubmissionPending || tailRunId) return;+ const timeout = window.setTimeout(+ () => setRunnerSubmissionPending(false),+ 10_000,+ );+ return () => window.clearTimeout(timeout);+ }, [runnerSubmissionPending, tailRunId]);+ const handleThreadAdd = useCallback(+ async (...args: Parameters<typeof onAdd>) => {+ if (assigneeUsesPaperclipRunner) setRunnerSubmissionPending(true);+ try {+ await onAdd(...args);+ } catch (error) {+ setRunnerSubmissionPending(false);+ throw error;+ }+ },+ [assigneeUsesPaperclipRunner, onAdd],);+ const optimisticRunnerStartup =+ assigneeUsesPaperclipRunner &&+ !tailRunId &&+ (runnerSubmissionPending ||+ commentItems.some(+ (item) =>+ item.kind === "message" &&+ item.author === "human" &&+ item.optimistic === "pending",+ ));// Feedback votes keyed by the comment they target (targetType// "issue_comment"), mirroring IssueChatThread — the redesign attaches the@@ -625,13 +1983,20 @@ export function TaskChatThread(props: TaskChatThreadProps) {/>);},- [onVote, feedbackVoteByTargetId, feedbackDataSharingPreference, feedbackTermsUrl],+ [+ onVote,+ feedbackVoteByTargetId,+ feedbackDataSharingPreference,+ feedbackTermsUrl,+ ],);const renderQueuedAction = useCallback((item: TaskChatMessageItem) => {+ if (paperclipQueue) return null;const runId = item.queueTargetRunId;- if (item.optimistic !== "queued" || !runId || !onInterruptQueued) return null;+ if (item.optimistic !== "queued" || !runId || !onInterruptQueued)+ return null;const isInterrupting = interruptingQueuedRunId === runId;return (@@ -646,13 +2011,23 @@ export function TaskChatThread(props: TaskChatThreadProps) {</Button>);},- [interruptingQueuedRunId, onInterruptQueued],+ [interruptingQueuedRunId, onInterruptQueued, paperclipQueue],);const renderInteraction = useCallback((item: TaskChatInteractionItem) => (<TaskChatInteractionCarditem={item}+ planDocument={planDocument}+ showPlanPreview={+ !threadOwnsPlanPreview(+ item.interaction,+ planDocument,+ planDocumentSourceRunId,+ settledRunIds,+ tailRunId,+ )+ }agentMap={agentMap}currentUserId={currentUserId}userLabelMap={userLabelMap}@@ -662,6 +2037,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {onCancelInteraction={onCancelInteraction}onSubmitInteractionVerdicts={onSubmitInteractionVerdicts}onUploadImage={imageUploadHandler}+ mentions={mentions}externalReferences={externalReferences}/>),@@ -675,7 +2051,12 @@ export function TaskChatThread(props: TaskChatThreadProps) {onCancelInteraction,onSubmitInteractionVerdicts,imageUploadHandler,+ mentions,externalReferences,+ planDocument,+ planDocumentSourceRunId,+ settledRunIds,+ tailRunId,],);@@ -685,31 +2066,103 @@ export function TaskChatThread(props: TaskChatThreadProps) {return agentMap?.get(assigneeAgentId) ?? null;}, [agentMap, currentAssigneeValue]);+ const takeoverContent = selectedPendingInput ? (+ selectedPendingInput.kind === "runtime" ? (+ <TaskChatProtocolCard+ item={selectedPendingInput.item}+ presentation="takeover"+ draftKey={interactionDraftKey}+ imageUploadHandler={imageUploadHandler}+ mentions={mentions}+ onRuntimeRequestDecision={handleRuntimeRequestDecision}+ />+ ) : (+ <TaskChatInteractionCard+ item={{+ id: `interaction:${selectedPendingInput.interaction.id}`,+ kind: "interaction",+ interaction: selectedPendingInput.interaction,+ }}+ presentation="takeover"+ draftKey={interactionDraftKey}+ planDocument={planDocument}+ agentMap={agentMap}+ currentUserId={currentUserId}+ userLabelMap={userLabelMap}+ onAcceptInteraction={onAcceptInteraction}+ onRejectInteraction={onRejectInteraction}+ onSubmitInteractionAnswers={onSubmitInteractionAnswers}+ onSubmitInteractionVerdicts={onSubmitInteractionVerdicts}+ onUploadImage={imageUploadHandler}+ mentions={mentions}+ externalReferences={externalReferences}+ />+ )+ ) : null;+ const composerTakeover =+ takeoverMode === "open" && selectedPendingInput && takeoverContent+ ? {+ id: selectedPendingInput.key,+ label: selectedPendingInput.label,+ pendingCount: pendingComposerInputs.length,+ content: takeoverContent,+ onDismiss: () => setTakeoverMode("normal"),+ onSkip: () => skipPendingInput(selectedPendingInput),+ onShowNext: showNextPendingInput,+ inlineSkip:+ selectedPendingInput.kind === "durable"+ ? selectedPendingInput.interaction.kind ===+ "ask_user_questions" ||+ selectedPendingInput.interaction.kind ===+ "request_item_verdicts"+ : selectedPendingInput.item.requestType === "input" &&+ Boolean(selectedPendingInput.item.questionSet),+ hideSkip:+ selectedPendingInput.kind === "durable"+ ? interactionReplacesComposerSkip(+ selectedPendingInput.interaction,+ )+ : runtimeRequestReplacesComposerSkip(selectedPendingInput.item),+ }+ : null;+ const autoFollowContentKey = `${threadContentKey}:${composerTakeover?.id ?? "composer"}`;+// Mobile (PAP-360): the app shell scrolls the DOCUMENT (Layout's main is// overflow-visible with auto height), so the desktop bounded h-dvh chain// collapses the absolute-inset transcript viewport to 0px. Render the thread// in document flow instead (the same scroll={false} path the previews use)- // and track auto-follow against window scroll. Desktop stays byte-identical.+ // and track auto-follow against window scroll. Both paths include takeover+ // state so opening or closing composer input preserves bottom pinning.const { isMobile } = useSidebar();- useWindowAutoFollow(isMobile ? threadContentKey : 0, isMobile);+ useWindowAutoFollow(isMobile ? autoFollowContentKey : 0, isMobile);return (<div- className={cn("flex flex-col", !isMobile && "h-(--tc-thread-max-h) min-h-0 flex-1")}+ className={cn(+ "flex flex-col",+ !isMobile && "h-(--tc-thread-max-h) min-h-0 flex-1",+ )}data-testid="task-chat-thread"><div className={cn("flex flex-col", !isMobile && "min-h-0 flex-1")}>{items.length === 0 && !tailRunId ? (- <div className={isMobile ? undefined : "min-h-0 flex-1 overflow-y-auto"}>+ <div+ className={isMobile ? undefined : "min-h-0 flex-1 overflow-y-auto"}+ >{threadHeaderWithBlockers ? (<div- className="mx-auto flex w-full max-w-(--tc-shell-max-w) flex-col gap-6 px-4 pt-4"+ className={cn(+ "mx-auto flex w-full max-w-(--tc-shell-max-w) flex-col gap-6 px-4",+ isMobile ? "pt-4" : "pt-3",+ )}data-testid="task-chat-thread-header">{threadHeaderWithBlockers}</div>) : null}- <div className="px-3 py-10 text-center text-sm text-muted-foreground">{emptyMessage}</div>+ <div className="px-3 py-10 text-center text-sm text-muted-foreground">+ {emptyMessage}+ </div>{bottomBlockerLinks ? (<div className="mx-auto w-full max-w-(--tc-shell-max-w) px-4 pb-4">{bottomBlockerLinks}@@ -721,51 +2174,69 @@ export function TaskChatThread(props: TaskChatThreadProps) {items={items}header={threadHeaderWithBlockers}renderInteraction={renderInteraction}- renderBrief={issueBrief ? () => <TaskChatDescriptionBubble brief={issueBrief} /> : undefined}+ renderBrief={+ issueBrief+ ? () => <TaskChatDescriptionBubble brief={issueBrief} />+ : undefined+ }renderMessageActions={renderMessageActions}renderQueuedAction={renderQueuedAction}- tail={tailRunId || bottomBlockerLinks ? (- <>- {tailRunId ? (- <div data-testid="task-chat-live-transcript">- {paperclipRunnerTail ? (- <TaskChatRunnerTurn- items={tailItems}- status={tailStatus}- startedAtMs={tailStartedAtMs}- finishedAtMs={tailFinishedAtMs}- toolSummary={tailToolSummary}- />- ) : (- <>- <TaskChatLiveRunPill- status={tailStatus}+ onTryAgainNoLiveExecutionPath={+ issueStatus === "blocked"+ ? onTryAgainNoLiveExecutionPath+ : undefined+ }+ tryAgainNoLiveExecutionPathPending={+ tryAgainNoLiveExecutionPathPending+ }+ tail={+ tailRunId || optimisticRunnerStartup || bottomBlockerLinks ? (+ <>+ {tailRunId || optimisticRunnerStartup ? (+ <div data-testid="task-chat-live-transcript">+ {paperclipRunnerTail || optimisticRunnerStartup ? (+ <TaskChatRunnerTurn+ runId={tailRunId}+ agentName={visibleTailAgentName}+ agentIcon={visibleTailAgentIcon}+ items={tailItems}+ status={+ optimisticRunnerStartup ? "queued" : tailStatus+ }startedAtMs={tailStartedAtMs}finishedAtMs={tailFinishedAtMs}- toolSummary={tailToolSummary}- />- <TaskChatLiveTail- items={tailItems}- emptyMessage={- tailStatus === "queued"- ? "Waiting to start..."- : // Before the first transcript token, surface the run's- // live runtime status (sandbox preparation phases like- // "Syncing workspace to environment" emitted via- // onRuntimeProgress) instead of an opaque wait message.- (liveRun && liveRun.id === tailRunId- ? liveRun.currentStatusMessage- : null) || "Waiting for transcript..."+ onRuntimeRequestDecision={+ handleRuntimeRequestDecision}/>- </>- )}- </div>- ) : null}- {bottomBlockerLinks}- </>- ) : null}- contentKey={threadContentKey}+ ) : (+ <>+ <TaskChatLiveRunPill+ status={tailStatus}+ startedAtMs={tailStartedAtMs}+ finishedAtMs={tailFinishedAtMs}+ toolSummary={tailToolSummary}+ />+ <TaskChatLiveTail+ items={tailItems}+ emptyMessage={+ tailStatus === "queued"+ ? "Waiting to start..."+ : (liveRun && liveRun.id === tailRunId+ ? liveRun.currentStatusMessage+ : null) || "Waiting for transcript..."+ }+ />+ </>+ )}+ </div>+ ) : null}+ {bottomBlockerLinks}+ </>+ ) : null+ }+ contentKey={autoFollowContentKey}+ className={isMobile ? undefined : "pt-3"}scroll={!isMobile}/>)}@@ -800,22 +2271,69 @@ export function TaskChatThread(props: TaskChatThreadProps) {)}>{composerAccessory}- <TaskChatComposer- onAdd={onAdd}- workMode={issueWorkMode}- onWorkModeChange={onWorkModeChange}- disabled={Boolean(composerDisabledReason)}- disabledReason={composerDisabledReason}- onAttachImage={onAttachImage}- onImageUpload={imageUploadHandler}- mentions={mentions}- enableReassign={enableReassign}- reassignOptions={reassignOptions}- currentAssigneeValue={currentAssigneeValue}- issueStatus={issueStatus}- mobile={isMobile}- draftKey={draftKey}- />+ {tailTurnStatus ? (+ <TaskChatTurnStatusIsland model={tailTurnStatus} />+ ) : null}+ <div+ className="relative isolate flex flex-col"+ data-testid="task-chat-composer-stack"+ >+ {paperclipQueue && paperclipQueue.entries.length > 0 ? (+ <TaskChatQueuedMessages+ queue={paperclipQueue}+ onEdit={beginQueuedEdit}+ onReorder={async (orderedCommentIds, revision) => {+ if (!onReorderQueuedComments)+ throw new Error("Queue reordering is unavailable.");+ await onReorderQueuedComments(orderedCommentIds, revision);+ }}+ onSteer={async (commentId, revision) => {+ if (!onSteerQueuedComment)+ throw new Error("Steering is unavailable.");+ await onSteerQueuedComment(commentId, revision);+ }}+ onDiscard={async (commentId, revision) => {+ if (!onDiscardQueuedComment)+ throw new Error("Discard is unavailable.");+ await onDiscardQueuedComment(commentId, revision);+ if (queuedEdit?.commentId === commentId) setQueuedEdit(null);+ }}+ />+ ) : null}+ <div className="relative z-10">+ <TaskChatComposer+ onAdd={handleThreadAdd}+ workMode={issueWorkMode}+ onWorkModeChange={onWorkModeChange}+ disabled={Boolean(runtimeComposerDisabledReason)}+ disabledReason={runtimeComposerDisabledReason}+ onAttachImage={onAttachImage}+ onImageUpload={imageUploadHandler}+ mentions={mentions}+ enableReassign={enableReassign}+ reassignOptions={reassignOptions}+ agentMap={agentMap}+ userProfileMap={userProfileMap}+ currentAssigneeValue={currentAssigneeValue}+ issueStatus={issueStatus}+ mobile={isMobile}+ draftKey={draftKey}+ queuedEdit={queuedEdit}+ onSaveQueuedEdit={saveQueuedEdit}+ onCancelQueuedEdit={() => setQueuedEdit(null)}+ takeover={composerTakeover}+ pendingTakeover={+ pendingComposerInputs.length > 0+ ? {+ count: pendingComposerInputs.length,+ label: `${pendingComposerInputs.length} pending input${pendingComposerInputs.length === 1 ? "" : "s"}`,+ onOpen: openPendingTakeover,+ }+ : null+ }+ />+ </div>+ </div>{footer}</div>) : null}diff --git a/ui/src/components/issue-properties/IssueProperties.tsx b/ui/src/components/issue-properties/IssueProperties.tsxindex abb9d85d71..229bda51c9 100644--- a/ui/src/components/issue-properties/IssueProperties.tsx+++ b/ui/src/components/issue-properties/IssueProperties.tsx@@ -154,11 +154,13 @@ interface IssuePropertiesProps {onCheckMonitorNow?: () => void;checkingMonitorNow?: boolean;documentDeepLink?: IssuePropertiesDocumentDeepLink | null;+ /** Render only the Properties body when a parent owns the side-panel tabs. */+ sidePanelContentOnly?: boolean;}export interface IssuePropertiesDocumentDeepLink {requestId: number;- tab: "plans" | "artifacts";+ tab: "plans" | "artifacts" | "document";documentKey: string;}@@ -179,6 +181,7 @@ export function IssueProperties({onCheckMonitorNow,checkingMonitorNow = false,documentDeepLink,+ sidePanelContentOnly = false,}: IssuePropertiesProps) {const { selectedCompanyId } = useCompany();const { isMobile } = useSidebar();@@ -214,9 +217,7 @@ export function IssueProperties({}setPaneHeaderSlot(document.getElementById(PROPERTIES_PANE_HEADER_SLOT_ID));}, [taskChatShellEnabled, inline]);- // Plan earns a tab as soon as an issue is in planning mode, even before the- // plan document arrives. This keeps an expected plan surface visible and- // lets its diagnostic empty state explain what is missing.+ // A Plan tab represents materialized plan content, not merely planning mode.// Same query keys as the tab bodies, so these share their cached fetches.const { data: paneTabPlanDocument } = useIssuePlanDocument(taskChatShellEnabled ? issue.id : null,@@ -245,8 +246,7 @@ export function IssueProperties({const hasPlanTab =Boolean(paneTabPlanDocument)|| (paneTabAcceptedPlans?.length ?? 0) > 0- || paneTabStandaloneDocuments.length > 0- || issue.workMode === "planning";+ || paneTabStandaloneDocuments.length > 0;// Artifacts covers the same three sources the tab body composes: work// products, documents (redundant with the Plan tab, intentionally), and// agent-created attachments. User comment uploads stay thread-only and@@ -272,6 +272,7 @@ export function IssueProperties({}, [hasPlanTab]);useEffect(() => {if (!documentDeepLink) return;+ if (documentDeepLink.tab === "document") return;paneTabUserChosenRef.current = true;setPaneTab(documentDeepLink.tab);}, [documentDeepLink]);@@ -2608,7 +2609,7 @@ export function IssueProperties({);// Classic Task Interface ON: the legacy stacked pane, byte-for-byte.- if (!taskChatShellEnabled) return propertiesBody;+ if (!taskChatShellEnabled || sidePanelContentOnly) return propertiesBody;// Chat-style with nothing to switch between: no tab strip — the header bar// shows a plain title and the pane body is just the properties stack.diff --git a/ui/src/components/issue-properties/IssuePropertiesArtifactsTab.tsx b/ui/src/components/issue-properties/IssuePropertiesArtifactsTab.tsxindex dea4ed8a2c..4809567fe6 100644--- a/ui/src/components/issue-properties/IssuePropertiesArtifactsTab.tsx+++ b/ui/src/components/issue-properties/IssuePropertiesArtifactsTab.tsx@@ -44,6 +44,7 @@ import { useLocation } from "@/lib/router";interface IssuePropertiesArtifactsTabProps {issue: Issue;+ onOpenDocument?: (document: IssueDocument) => void;documentDeepLink?: {requestId: number;documentKey: string;@@ -319,10 +320,12 @@ function DocumentRow({issueId,doc,openRequestId,+ onOpen,}: {issueId: string;doc: IssueDocument;openRequestId?: number;+ onOpen?: () => void;}) {const [expanded, setExpanded] = useState(false);const [annotationPanelOpen, setAnnotationPanelOpen] = useState(false);@@ -330,13 +333,29 @@ function DocumentRow({const location = useLocation();const Chevron = expanded ? ChevronDown : ChevronRight;useEffect(() => {- if (openRequestId === undefined) return;+ if (onOpen || openRequestId === undefined) return;setExpanded(true);- }, [openRequestId]);+ }, [onOpen, openRequestId]);useEffect(() => {- if (openRequestId === undefined || !expanded) return;+ if (onOpen || openRequestId === undefined || !expanded) return;headerRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });- }, [expanded, openRequestId]);+ }, [expanded, onOpen, openRequestId]);+ if (onOpen) {+ return (+ <button+ type="button"+ onClick={onOpen}+ className={cn(ROW_CLASS, "w-full text-left hover:bg-accent/50")}+ >+ <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate">{documentDisplayTitle(doc)}</span>+ <span className="shrink-0 text-(length:--text-micro) text-muted-foreground">+ {`Rev ${doc.latestRevisionNumber ?? 1}`}+ </span>+ <ChevronRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ </button>+ );+ }return (<div className="rounded-md border border-border bg-card/50"><div ref={headerRef} className="flex items-center hover:bg-accent/50">@@ -396,7 +415,7 @@ function DocumentRow({* user uploads are excluded — those stay first-class in the conversation* thread.*/-export function IssuePropertiesArtifactsTab({ issue, documentDeepLink }: IssuePropertiesArtifactsTabProps) {+export function IssuePropertiesArtifactsTab({ issue, documentDeepLink, onOpenDocument }: IssuePropertiesArtifactsTabProps) {const { data: attachments } = useQuery({queryKey: queryKeys.issues.attachments(issue.id),queryFn: () => issuesApi.listAttachments(issue.id),@@ -464,6 +483,7 @@ export function IssuePropertiesArtifactsTab({ issue, documentDeepLink }: IssuePr<DocumentRowissueId={issue.id}doc={doc}+ onOpen={onOpenDocument ? () => onOpenDocument(doc) : undefined}openRequestId={documentDeepLink?.documentKey === doc.key? documentDeepLink.requestId: undefined}diff --git a/ui/src/components/issue-properties/IssuePropertiesDocumentAnnotations.test.tsx b/ui/src/components/issue-properties/IssuePropertiesDocumentAnnotations.test.tsxindex 25b3235499..38bfee19be 100644--- a/ui/src/components/issue-properties/IssuePropertiesDocumentAnnotations.test.tsx+++ b/ui/src/components/issue-properties/IssuePropertiesDocumentAnnotations.test.tsx@@ -31,15 +31,20 @@ const issueDocument: IssueDocument = {const issue = { id: "issue-1", identifier: "PAP-522", workMode: "standard" } as Issue;vi.mock("@tanstack/react-query", () => ({ useQuery: () => ({ data: [] }) }));-vi.mock("@/hooks/useIssuePlanDocument", () => ({ useIssuePlanDocument: () => ({ data: null, isLoading: false }) }));+vi.mock("@/hooks/useIssuePlanDocument", () => ({+ useIssuePlanDocument: () => ({ data: { ...issueDocument, key: "plan" }, isLoading: false }),+}));vi.mock("@/hooks/useIssueDocuments", () => ({ useIssueDocuments: () => ({ data: [issueDocument] }) }));vi.mock("@/lib/router", () => ({ useLocation: () => ({ hash: "" }) }));vi.mock("@/components/IssuePlanDecompositionsSection", () => ({ IssuePlanDecompositionsSection: () => null }));vi.mock("@/components/MarkdownBody", () => ({ MarkdownBody: ({ children }: { children: string }) => <div>{children}</div> }));vi.mock("@/components/IssueDocumentAnnotations", () => ({DocumentAnnotationsCountChip: ({ docKey }: { docKey: string }) => <span data-testid={`annotation-count-${docKey}`} />,- IssueDocumentAnnotations: ({ doc, children }: { doc: IssueDocument; children: React.ReactNode }) => (- <div data-testid={`annotation-surface-${doc.key}`} data-document-id={doc.id}>{children}</div>+ IssueDocumentAnnotations: ({ doc, children }: {+ doc: Pick<IssueDocument, "key" | "latestRevisionId">;+ children: React.ReactNode;+ }) => (+ <div data-testid={`annotation-surface-${doc.key}`} data-revision-id={doc.latestRevisionId}>{children}</div>),}));@@ -59,8 +64,8 @@ describe("issue properties document annotation mounting", () => {it("uses the issue document key on the Plan tab", async () => {const root = createRoot(container);await act(async () => root.render(<IssuePropertiesPlansTab issue={issue} />));- expect(container.querySelector('[data-testid="annotation-surface-qa-evidence"]')?.getAttribute("data-document-id"))- .toBe("document-1");+ expect(container.querySelector('[data-testid="annotation-surface-plan"]')?.getAttribute("data-revision-id"))+ .toBe("revision-1");await act(async () => root.unmount());});@@ -71,8 +76,8 @@ describe("issue properties document annotation mounting", () => {expect(container.querySelector('[data-testid="annotation-surface-qa-evidence"]')).toBeNull();const expand = container.querySelector('button[aria-expanded="false"]') as HTMLButtonElement;await act(async () => expand.click());- expect(container.querySelector('[data-testid="annotation-surface-qa-evidence"]')?.getAttribute("data-document-id"))- .toBe("document-1");+ expect(container.querySelector('[data-testid="annotation-surface-qa-evidence"]')?.getAttribute("data-revision-id"))+ .toBe("revision-1");await act(async () => root.unmount());});diff --git a/ui/src/components/issue-properties/IssuePropertiesPlansTab.tsx b/ui/src/components/issue-properties/IssuePropertiesPlansTab.tsxindex b3458fbaa4..b35a422d06 100644--- a/ui/src/components/issue-properties/IssuePropertiesPlansTab.tsx+++ b/ui/src/components/issue-properties/IssuePropertiesPlansTab.tsx@@ -1,15 +1,12 @@import { useState } from "react";import { useQuery } from "@tanstack/react-query";-import type { Issue, IssueDocument, IssueThreadInteraction } from "@paperclipai/shared";-import { isArtifactReviewDocumentKey } from "@paperclipai/shared";+import type { Issue, IssueThreadInteraction } from "@paperclipai/shared";import { issuesApi } from "@/api/issues";import { queryKeys } from "@/lib/queryKeys";import { IssuePlanDecompositionsSection } from "@/components/IssuePlanDecompositionsSection";import { MarkdownBody } from "@/components/MarkdownBody";import { DocumentAnnotationsCountChip, IssueDocumentAnnotations } from "@/components/IssueDocumentAnnotations";import { useIssuePlanDocument } from "@/hooks/useIssuePlanDocument";-import { useIssueDocuments } from "@/hooks/useIssueDocuments";-import { documentDisplayTitle } from "@/lib/issue-artifacts";import { useLocation } from "@/lib/router";interface IssuePropertiesPlansTabProps {@@ -29,45 +26,6 @@ function hasPendingPlanConfirmation(interactions: IssueThreadInteraction[] | und);}-function OtherDocumentSection({ issueId, doc, locationHash }: { issueId: string; doc: IssueDocument; locationHash: string }) {- const [annotationPanelOpen, setAnnotationPanelOpen] = useState(false);- return (- <section data-testid="issue-other-document" className="space-y-2 border-t border-border pt-4 first:border-t-0 first:pt-0">- <div className="flex items-baseline justify-between gap-2">- <h3 className="text-sm font-semibold">{documentDisplayTitle(doc)}</h3>- <div className="flex shrink-0 items-center gap-1 text-xs text-muted-foreground">- {`Revision ${doc.latestRevisionNumber ?? 1} · updated ${new Date(doc.updatedAt).toLocaleString([], {- month: "short",- day: "numeric",- hour: "numeric",- minute: "2-digit",- })}`}- <DocumentAnnotationsCountChip- issueId={issueId}- docKey={doc.key}- panelOpen={annotationPanelOpen}- onToggle={() => setAnnotationPanelOpen((open) => !open)}- />- </div>- </div>- <IssueDocumentAnnotations- issueId={issueId}- doc={doc}- bodyMarkdown={doc.body}- draftDirty={false}- draftConflicted={false}- historicalPreview={false}- locationHash={locationHash}- panelOpen={annotationPanelOpen}- onPanelOpenChange={setAnnotationPanelOpen}- panelPlacement="popover"- >- <MarkdownBody>{doc.body}</MarkdownBody>- </IssueDocumentAnnotations>- </section>- );-}-/*** Plans tab of the properties pane.*@@ -89,17 +47,10 @@ export function IssuePropertiesPlansTab({ issue }: IssuePropertiesPlansTabProps)queryKey: queryKeys.issues.interactions(issue.id),queryFn: () => issuesApi.listInteractions(issue.id),});- const { data: documents } = useIssueDocuments(issue.id);const hasPlans = (data?.length ?? 0) > 0;const pendingPlanConfirmation = hasPendingPlanConfirmation(interactions);- // Every other non-system document (e.g. `synthesis`) renders below the plan;- // the `plan` doc itself stays on its dedicated annotated surface above, and- // proxy `artifact-review-*` documents surface only through their Work product.- const otherDocuments = (documents ?? []).filter(- (doc) => doc.key !== "plan" && !isArtifactReviewDocumentKey(doc.key),- );- if (!planDocument && !hasPlans && otherDocuments.length === 0) {+ if (!planDocument && !hasPlans) {return (<div className="px-1 py-6 text-sm text-muted-foreground">{planDocumentLoading ? (@@ -162,9 +113,6 @@ export function IssuePropertiesPlansTab({ issue }: IssuePropertiesPlansTabProps)</IssueDocumentAnnotations></section>) : null}- {otherDocuments.map((doc) => (- <OtherDocumentSection key={doc.key} issueId={issue.id} doc={doc} locationHash={location.hash} />- ))}{hasPlans ? (<IssuePlanDecompositionsSection issueId={issue.id} issueIdentifier={issue.identifier} />) : null}diff --git a/ui/src/components/side-panel/README.md b/ui/src/components/side-panel/README.mdnew file mode 100644index 0000000000..54974cf9db--- /dev/null+++ b/ui/src/components/side-panel/README.md@@ -0,0 +1,28 @@+# Portable side panel++The components exported by `@/components/side-panel` are controlled, domain-free navigation primitives. They do not import task data, APIs, routing, feature flags, or persistence.++## Composition boundary++- `SidePanelFrame` renders docked, sheet, or embedded chrome and applies the selected content layout.+- `SidePanelTabs` and `SidePanelTab` render projected visual tab data and own keyboard navigation, close focus recovery, overflow visibility, and pointer/keyboard reordering.+- `SidePanelLauncher` renders caller-provided sections from the same model as either a plus-button popover or the empty panel body.+- `useSidePanelTabs<TPayload>` owns serializable open/select/close/reorder/reset state. Its optional `onStateChange` callback is the persistence boundary; it never reads storage itself.+- The host adapter owns payload validation, data queries, URL synchronization, content rendering, and persistence scope.++Never put React nodes or fetched content in a persisted `SidePanelTabRecord`. Project icons and live status into `SidePanelTabItem` at render time.++## Registering another page++1. Define a serializable payload union for that page, such as `details | activity | history`.+2. Build stable `SidePanelTabRecord<PagePayload>` descriptors and initialize `useSidePanelTabs` with validated state.+3. Project descriptors into `SidePanelTabItem` values for the tab strip.+4. Render active content in the page adapter by switching on `payload.kind`.+5. Supply the same launcher sections to the plus popover and empty panel.+6. If state is persisted, version and scope it in the adapter and pass writes through `onStateChange`.++## Accessibility and review++The tab strip uses the tabs pattern with roving focus, Arrow/Home/End navigation, named close actions, middle-click close, and live reorder/close announcements. Closing the active tab chooses the right neighbor, then the left; closing the final tab sends focus to the launcher. Reduced-motion preferences disable component transitions and smooth overflow scrolling.++Review `Navigation/Side Panel` in Storybook before changing production adapters. Compare light/dark, minimum/default/wide/maximized, mobile, overflow, empty, launcher, unavailable-resource, and task-composition stories. Tune spacing, radius, contrast, icon size, and motion centrally through the side-panel tokens in `ui/src/index.css`.diff --git a/ui/src/components/side-panel/SidePanelFrame.test.tsx b/ui/src/components/side-panel/SidePanelFrame.test.tsxnew file mode 100644index 0000000000..40354cc397--- /dev/null+++ b/ui/src/components/side-panel/SidePanelFrame.test.tsx@@ -0,0 +1,100 @@+// @vitest-environment jsdom++import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { TooltipProvider } from "@/components/ui/tooltip";+import { SidePanelFrame, SidePanelToggleButton, SidePanelWindowControls } from "./SidePanelFrame";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++describe("side-panel shell controls", () => {+ let root: Root;+ let container: HTMLDivElement;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ });++ afterEach(() => {+ act(() => root.unmount());+ container.remove();+ document.documentElement.style.removeProperty("--motion-scrollbar-idle-delay");+ vi.useRealTimers();+ });++ it("exposes controlled presentation, visibility, maximize, and content layout state", async () => {+ await act(async () => root.render(+ <SidePanelFrame presentation="sheet" open={false} maximized resizing contentMode="full-bleed">+ Body+ </SidePanelFrame>,+ ));+ const frame = container.querySelector("section")!;+ expect(frame.getAttribute("data-presentation")).toBe("sheet");+ expect(frame.getAttribute("data-maximized")).toBe("true");+ expect(frame.getAttribute("data-resizing")).toBe("true");+ expect(frame.getAttribute("aria-hidden")).toBe("true");+ expect(frame.className).toContain("bg-(--side-panel-bg)");+ expect(frame.className).toContain("text-(--side-panel-fg)");+ expect(frame.firstElementChild?.className).toContain("overflow-hidden");+ });++ it("reports toggle, maximize, restore, and panel-toggle actions", async () => {+ const onToggle = vi.fn();+ const onMaximizedChange = vi.fn();+ const onWindowToggle = vi.fn();+ await act(async () => root.render(+ <TooltipProvider>+ <SidePanelToggleButton open={false} onToggle={onToggle} shortcut="]" />+ <SidePanelWindowControls maximized={false} onMaximizedChange={onMaximizedChange} onToggle={onWindowToggle} />+ </TooltipProvider>,+ ));+ const toggleButtons = container.querySelectorAll<HTMLButtonElement>('[aria-label="Toggle side panel"]');+ expect(toggleButtons).toHaveLength(2);+ expect(toggleButtons[0]?.getAttribute("aria-pressed")).toBe("false");+ expect(toggleButtons[1]?.getAttribute("aria-pressed")).toBe("true");+ expect(toggleButtons[0]?.className).toContain("h-(--side-panel-tab-height)");+ await act(async () => toggleButtons[0]?.click());+ const maximizeButton = container.querySelector<HTMLButtonElement>('[aria-label="Maximize side panel"]');+ expect(maximizeButton?.className).toContain("text-muted-foreground");+ expect(maximizeButton?.className).toContain("h-(--side-panel-tab-height)");+ await act(async () => maximizeButton?.click());+ await act(async () => toggleButtons[1]?.click());+ expect(onToggle).toHaveBeenCalledOnce();+ expect(onMaximizedChange).toHaveBeenCalledWith(true);+ expect(onWindowToggle).toHaveBeenCalledOnce();+ });++ it("keeps the prose scrollbar on the full-width viewport while centering its content", async () => {+ await act(async () => root.render(+ <SidePanelFrame contentMode="prose">Document body</SidePanelFrame>,+ ));+ const viewport = container.querySelector<HTMLElement>('[data-side-panel-content-viewport="true"]')!;+ const prose = container.querySelector<HTMLElement>('[data-side-panel-prose-content="true"]')!;+ expect(viewport.className).toContain("overflow-auto");+ expect(viewport.className).not.toContain("max-w-4xl");+ expect(viewport.className).not.toContain("mx-auto");+ expect(prose.className).toContain("mx-auto");+ expect(prose.className).toContain("max-w-4xl");+ });++ it("shows the prose scrollbar only while scroll activity is recent", async () => {+ vi.useFakeTimers();+ document.documentElement.style.setProperty("--motion-scrollbar-idle-delay", "600ms");+ await act(async () => root.render(+ <SidePanelFrame contentMode="prose">Document body</SidePanelFrame>,+ ));+ const viewport = container.querySelector<HTMLElement>('[data-side-panel-content-viewport="true"]')!;+ expect(viewport.className).toContain("scrollbar-while-scrolling");+ expect(viewport.getAttribute("data-scroll-active")).toBeNull();++ act(() => viewport.dispatchEvent(new Event("scroll", { bubbles: true })));+ expect(viewport.getAttribute("data-scroll-active")).toBe("true");+ act(() => vi.advanceTimersByTime(599));+ expect(viewport.getAttribute("data-scroll-active")).toBe("true");+ act(() => vi.advanceTimersByTime(1));+ expect(viewport.getAttribute("data-scroll-active")).toBeNull();+ });+});diff --git a/ui/src/components/side-panel/SidePanelFrame.tsx b/ui/src/components/side-panel/SidePanelFrame.tsxnew file mode 100644index 0000000000..e38d4f92a9--- /dev/null+++ b/ui/src/components/side-panel/SidePanelFrame.tsx@@ -0,0 +1,152 @@+import type { CSSProperties, ReactNode } from "react";+import { Maximize2, Minimize2, PanelRightClose, PanelRightOpen } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";+import type { SidePanelContentMode, SidePanelPresentation } from "./types";+import { useScrollbarWhileScrolling } from "./use-scrollbar-while-scrolling";++export interface SidePanelFrameProps {+ children: ReactNode;+ header?: ReactNode;+ footer?: ReactNode;+ trailingControls?: ReactNode;+ presentation?: SidePanelPresentation;+ contentMode?: SidePanelContentMode;+ open?: boolean;+ maximized?: boolean;+ resizing?: boolean;+ label?: string;+ className?: string;+ bodyClassName?: string;+ style?: CSSProperties;+}++export function SidePanelFrame({+ children,+ header,+ footer,+ trailingControls,+ presentation = "docked",+ contentMode = "padded",+ open = true,+ maximized = false,+ resizing = false,+ label = "Side panel",+ className,+ bodyClassName,+ style,+}: SidePanelFrameProps) {+ const handleScroll = useScrollbarWhileScrolling();+ return (+ <section+ aria-label={label}+ aria-hidden={!open}+ data-presentation={presentation}+ data-open={open ? "true" : "false"}+ data-maximized={maximized ? "true" : "false"}+ data-resizing={resizing ? "true" : "false"}+ className={cn(+ "flex min-h-0 min-w-0 flex-col overflow-hidden bg-(--side-panel-bg) text-(--side-panel-fg)",+ presentation === "docked" && "h-full border-l border-border",+ presentation === "sheet" && "h-full w-full",+ presentation === "embedded" && "h-full rounded-xl border border-border",+ !open && "pointer-events-none opacity-0",+ className,+ )}+ style={style}+ >+ {(header || trailingControls) ? (+ <header className="flex h-(--side-panel-header-height) min-w-0 shrink-0 items-center gap-1 px-2">+ <div className="flex min-w-0 flex-1 self-stretch">{header}</div>+ {trailingControls ? (+ <div className="flex shrink-0 items-center gap-1">{trailingControls}</div>+ ) : null}+ </header>+ ) : null}+ <div+ data-side-panel-content-viewport="true"+ onScroll={handleScroll}+ className={cn(+ "min-h-0 flex-1",+ contentMode === "full-bleed" ? "overflow-hidden" : "overflow-auto",+ contentMode !== "full-bleed" && "scrollbar-while-scrolling",+ contentMode === "padded" && "p-4",+ bodyClassName,+ )}+ >+ {contentMode === "prose" ? (+ <div data-side-panel-prose-content="true" className="mx-auto w-full max-w-4xl px-6 py-4">+ {children}+ </div>+ ) : children}+ </div>+ {footer ? <footer className="shrink-0 border-t border-border">{footer}</footer> : null}+ </section>+ );+}++export function SidePanelToggleButton({+ open,+ onToggle,+ shortcut,+ className,+}: {+ open: boolean;+ onToggle: () => void;+ shortcut?: string;+ className?: string;+}) {+ const label = "Toggle side panel";+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label={label}+ aria-pressed={open}+ onClick={onToggle}+ className={cn(+ "h-(--side-panel-tab-height) w-(--side-panel-tab-height)",+ open && "bg-accent text-accent-foreground",+ className,+ )}+ >+ {open ? <PanelRightClose aria-hidden /> : <PanelRightOpen aria-hidden />}+ </Button>+ </TooltipTrigger>+ <TooltipContent side="bottom">+ {shortcut ? `${label} (${shortcut})` : label}+ </TooltipContent>+ </Tooltip>+ );+}++export function SidePanelWindowControls({+ maximized,+ onMaximizedChange,+ onToggle,+}: {+ maximized: boolean;+ onMaximizedChange: (maximized: boolean) => void;+ onToggle: () => void;+}) {+ return (+ <>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ className="h-(--side-panel-tab-height) w-(--side-panel-tab-height) text-muted-foreground hover:text-foreground focus-visible:text-foreground"+ onClick={() => onMaximizedChange(!maximized)}+ aria-label={maximized ? "Restore side panel" : "Maximize side panel"}+ title={maximized ? "Restore side panel" : "Maximize side panel"}+ >+ {maximized ? <Minimize2 aria-hidden /> : <Maximize2 aria-hidden />}+ </Button>+ <SidePanelToggleButton open onToggle={onToggle} />+ </>+ );+}diff --git a/ui/src/components/side-panel/SidePanelLauncher.test.tsx b/ui/src/components/side-panel/SidePanelLauncher.test.tsxnew file mode 100644index 0000000000..9c626776c0--- /dev/null+++ b/ui/src/components/side-panel/SidePanelLauncher.test.tsx@@ -0,0 +1,65 @@+// @vitest-environment jsdom++import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { FileText } from "lucide-react";+import { SidePanelLauncher } from "./SidePanelLauncher";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++class ResizeObserverStub {+ observe() {}+ unobserve() {}+ disconnect() {}+}++(globalThis as { ResizeObserver?: typeof ResizeObserver }).ResizeObserver = ResizeObserverStub as unknown as typeof ResizeObserver;++describe("SidePanelLauncher", () => {+ let root: Root;+ let container: HTMLDivElement;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ });++ afterEach(() => {+ act(() => root.unmount());+ container.remove();+ });++ it("renders grouped loading, failure, disabled, and already-open states", async () => {+ await act(async () => root.render(+ <SidePanelLauncher+ sections={[+ { id: "open", label: "Open", items: [{ id: "plan", label: "Plan", icon: <FileText />, alreadyOpen: true }] },+ { id: "loading", label: "Recent", items: [], loading: true },+ { id: "failed", label: "Remote", items: [], error: "Recent files unavailable." },+ { id: "disabled", items: [{ id: "files", label: "Files", disabled: true, disabledReason: "No workspace." }] },+ ]}+ onSelect={() => {}}+ />,+ ));+ expect(container.textContent).toContain("Loading…");+ expect(container.textContent).toContain("Recent files unavailable.");+ expect(container.textContent).toContain("No workspace.");+ expect(container.querySelector('[aria-label="Already open"]')).not.toBeNull();+ expect(container.querySelector('[aria-disabled="true"]')).not.toBeNull();+ });++ it("selects enabled caller-provided items", async () => {+ const onSelect = vi.fn();+ await act(async () => root.render(+ <SidePanelLauncher+ sections={[{ id: "docs", items: [{ id: "plan", label: "Plan" }] }]}+ onSelect={onSelect}+ />,+ ));+ const option = container.querySelector<HTMLElement>('[role="option"]')!;+ await act(async () => option.click());+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ id: "plan" }));+ });+});diff --git a/ui/src/components/side-panel/SidePanelLauncher.tsx b/ui/src/components/side-panel/SidePanelLauncher.tsxnew file mode 100644index 0000000000..f1082f49d6--- /dev/null+++ b/ui/src/components/side-panel/SidePanelLauncher.tsx@@ -0,0 +1,143 @@+import { useState, type ReactNode } from "react";+import { AlertCircle, Check, Loader2 } from "lucide-react";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+ CommandSeparator,+ CommandShortcut,+} from "@/components/ui/command";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { cn } from "@/lib/utils";+import type { SidePanelLauncherItem, SidePanelLauncherSection } from "./types";++export interface SidePanelLauncherProps {+ sections: SidePanelLauncherSection[];+ onSelect: (item: SidePanelLauncherItem) => void;+ presentation?: "panel" | "popover";+ trigger?: ReactNode;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+ title?: string;+ description?: string;+ placeholder?: string;+ emptyMessage?: string;+ className?: string;+}++function LauncherContent({+ sections,+ onSelect,+ placeholder,+ emptyMessage,+ panel,+}: Pick<SidePanelLauncherProps, "sections" | "onSelect" | "placeholder" | "emptyMessage"> & { panel: boolean }) {+ return (+ <Command className={cn(panel && "border border-border shadow-sm")}>+ <CommandInput placeholder={placeholder} aria-label={placeholder} />+ <CommandList className={cn(panel && "max-h-none flex-1")}>+ <CommandEmpty>{emptyMessage}</CommandEmpty>+ {sections.map((section, sectionIndex) => (+ <div key={section.id}>+ {sectionIndex > 0 ? <CommandSeparator /> : null}+ <CommandGroup heading={section.label}>+ {section.loading ? (+ <div className="flex items-center gap-2 px-2 py-3 text-sm text-muted-foreground" role="status">+ <Loader2 className="size-4 animate-spin" aria-hidden />+ Loading…+ </div>+ ) : null}+ {section.error ? (+ <div className="flex items-start gap-2 px-2 py-3 text-sm text-muted-foreground" role="status">+ <AlertCircle className="mt-0.5 size-4 shrink-0" aria-hidden />+ <span>{section.error}</span>+ </div>+ ) : null}+ {section.items.map((item) => (+ <CommandItem+ key={item.id}+ value={`${item.label} ${item.description ?? ""} ${item.searchText ?? ""}`}+ disabled={item.disabled}+ title={item.disabledReason}+ onSelect={() => onSelect(item)}+ className="min-h-10"+ >+ {item.icon ? <span className="flex size-4 shrink-0 items-center justify-center">{item.icon}</span> : null}+ <span className="min-w-0 flex-1">+ <span className="block truncate">{item.label}</span>+ {(item.description || item.disabledReason) ? (+ <span className="block truncate text-xs text-muted-foreground">+ {item.disabledReason ?? item.description}+ </span>+ ) : null}+ </span>+ {item.alreadyOpen ? <Check className="size-4 text-muted-foreground" aria-label="Already open" /> : null}+ {item.shortcut ? <CommandShortcut>{item.shortcut}</CommandShortcut> : null}+ </CommandItem>+ ))}+ </CommandGroup>+ </div>+ ))}+ </CommandList>+ </Command>+ );+}++export function SidePanelLauncher({+ sections,+ onSelect,+ presentation = "panel",+ trigger,+ open: controlledOpen,+ onOpenChange,+ title = "Open a side panel tab",+ description = "Choose a view or resource to open.",+ placeholder = "Search tabs and resources…",+ emptyMessage = "No matching tabs or resources.",+ className,+}: SidePanelLauncherProps) {+ const [uncontrolledOpen, setUncontrolledOpen] = useState(false);+ const open = controlledOpen ?? uncontrolledOpen;+ const setOpen = onOpenChange ?? setUncontrolledOpen;+ const content = (+ <LauncherContent+ sections={sections}+ onSelect={(item) => {+ onSelect(item);+ if (presentation === "popover") setOpen(false);+ }}+ placeholder={placeholder}+ emptyMessage={emptyMessage}+ panel={presentation === "panel"}+ />+ );++ if (presentation === "popover") {+ if (!trigger) return null;+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>{trigger}</PopoverTrigger>+ <PopoverContent align="start" className={cn("w-(--side-panel-launcher-width) overflow-hidden p-0", className)}>+ <div className="sr-only">+ <h2>{title}</h2>+ <p>{description}</p>+ </div>+ {content}+ </PopoverContent>+ </Popover>+ );+ }++ return (+ <div className={cn("mx-auto flex h-full w-full max-w-xl flex-col justify-center gap-4 p-4", className)}>+ <div className="space-y-1 text-center">+ <h2 className="text-sm font-semibold">{title}</h2>+ <p className="text-sm text-muted-foreground">{description}</p>+ </div>+ {content}+ </div>+ );+}diff --git a/ui/src/components/side-panel/SidePanelTab.tsx b/ui/src/components/side-panel/SidePanelTab.tsxnew file mode 100644index 0000000000..9726f7a357--- /dev/null+++ b/ui/src/components/side-panel/SidePanelTab.tsx@@ -0,0 +1,144 @@+import { useEffect, useLayoutEffect, useRef, useState, type ButtonHTMLAttributes, type MouseEvent, type ReactNode, type Ref } from "react";+import { X } from "lucide-react";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";++export interface SidePanelTabProps {+ id: string;+ label: string;+ ariaLabel?: string;+ icon?: ReactNode;+ status?: ReactNode;+ active: boolean;+ closable?: boolean;+ disabled?: boolean;+ tabRef?: Ref<HTMLButtonElement>;+ dragHandleProps?: ButtonHTMLAttributes<HTMLButtonElement>;+ onSelect: () => void;+ onClose?: () => void;+ onAuxClick?: (event: MouseEvent<HTMLButtonElement>) => void;+ onKeyDown?: ButtonHTMLAttributes<HTMLButtonElement>["onKeyDown"];+ className?: string;+}++export function SidePanelTab({+ id,+ label,+ ariaLabel,+ icon,+ status,+ active,+ closable = true,+ disabled = false,+ tabRef,+ dragHandleProps,+ onSelect,+ onClose,+ onAuxClick,+ onKeyDown,+ className,+}: SidePanelTabProps) {+ const closeLabel = `Close ${label}`;+ const wrapperRef = useRef<HTMLDivElement>(null);+ const labelRef = useRef<HTMLSpanElement>(null);+ const [labelIsTruncated, setLabelIsTruncated] = useState(false);+ const sizingKey = `${label}:${icon ? "icon" : "no-icon"}:${status ? "status" : "no-status"}:${closable ? "closable" : "fixed"}`;+ const [stableWidth, setStableWidth] = useState<{ key: string; width: number } | null>(null);+ const hasStableWidth = stableWidth?.key === sizingKey;++ useLayoutEffect(() => {+ if (hasStableWidth) return;+ const measuredWidth = wrapperRef.current?.getBoundingClientRect().width ?? 0;+ if (measuredWidth <= 0) return;+ setStableWidth({ key: sizingKey, width: Math.ceil(measuredWidth) });+ }, [hasStableWidth, sizingKey]);++ useEffect(() => {+ const labelElement = labelRef.current;+ if (!labelElement) return;+ const updateTruncation = () => {+ setLabelIsTruncated(labelElement.scrollWidth > labelElement.clientWidth);+ };+ updateTruncation();+ if (typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(updateTruncation);+ observer.observe(labelElement);+ return () => observer.disconnect();+ }, [label]);++ return (+ <div+ ref={wrapperRef}+ data-side-panel-tab-wrapper={id}+ data-active={active ? "true" : "false"}+ style={hasStableWidth ? { width: stableWidth.width } : undefined}+ className={cn(+ "group/side-panel-tab relative flex h-(--side-panel-tab-height) min-w-0 shrink-0 items-center rounded-(--side-panel-tab-radius) border border-transparent",+ "side-panel-tab-motion",+ active+ ? "bg-(--side-panel-tab-active-bg) text-accent-foreground"+ : "text-muted-foreground hover:bg-(--side-panel-tab-hover-bg) hover:text-foreground",+ disabled && "opacity-50",+ className,+ )}+ >+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ {...dragHandleProps}+ ref={tabRef}+ type="button"+ role="tab"+ data-side-panel-tab-target={id}+ id={`side-panel-tab-${id}`}+ aria-controls={`side-panel-content-${id}`}+ aria-selected={active}+ aria-label={ariaLabel ?? label}+ tabIndex={active ? 0 : -1}+ disabled={disabled}+ onClick={onSelect}+ onAuxClick={onAuxClick}+ onKeyDown={onKeyDown}+ className={cn(+ "flex h-full w-full min-w-0 items-center gap-1.5 rounded-(--side-panel-tab-radius) py-1.5 pl-2 text-xs font-medium outline-none",+ closable && (!hasStableWidth || active) ? "pr-7" : "pr-2.5",+ "focus-visible:ring-2 focus-visible:ring-ring/60",+ dragHandleProps?.className,+ )}+ >+ {icon ? <span className="flex size-3.5 shrink-0 items-center justify-center [&_svg]:size-3.5">{icon}</span> : null}+ <span+ ref={labelRef}+ data-truncated={labelIsTruncated ? "true" : undefined}+ className={cn(+ "overflow-hidden whitespace-nowrap",+ closable && hasStableWidth && !active+ ? "max-w-(--side-panel-tab-label-expanded-max-width)"+ : "max-w-(--side-panel-tab-label-max-width)",+ labelIsTruncated && "side-panel-tab-label-fade",+ )}+ >+ {label}+ </span>+ {status ? <span className="flex shrink-0 items-center">{status}</span> : null}+ </button>+ </TooltipTrigger>+ <TooltipContent side="bottom">{label}</TooltipContent>+ </Tooltip>+ {closable && onClose && active ? (+ <button+ type="button"+ aria-label={closeLabel}+ title={closeLabel}+ onClick={(event) => {+ event.stopPropagation();+ onClose();+ }}+ className="side-panel-tab-motion absolute right-1 flex size-6 items-center justify-center rounded-lg text-muted-foreground outline-none hover:bg-background/70 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ <X className="size-3" aria-hidden />+ </button>+ ) : null}+ </div>+ );+}diff --git a/ui/src/components/side-panel/SidePanelTabs.test.tsx b/ui/src/components/side-panel/SidePanelTabs.test.tsxnew file mode 100644index 0000000000..0321837641--- /dev/null+++ b/ui/src/components/side-panel/SidePanelTabs.test.tsx@@ -0,0 +1,179 @@+// @vitest-environment jsdom++import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { FileText, SlidersHorizontal } from "lucide-react";+import { TooltipProvider } from "@/components/ui/tooltip";+import { SidePanelTabs } from "./SidePanelTabs";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++class ResizeObserverStub {+ observe() {}+ unobserve() {}+ disconnect() {}+}++(globalThis as { ResizeObserver?: typeof ResizeObserver }).ResizeObserver = ResizeObserverStub as unknown as typeof ResizeObserver;++describe("SidePanelTabs", () => {+ let container: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ Element.prototype.scrollIntoView = vi.fn();+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {+ callback(0);+ return 1;+ });+ });++ afterEach(() => {+ act(() => root.unmount());+ container.remove();+ vi.restoreAllMocks();+ });++ function renderTabs(+ activeTabId = "properties",+ onCloseTab = vi.fn(),+ onActiveTabChange = vi.fn(),+ onReorderTabs = vi.fn(),+ ) {+ const tabs = [+ { id: "properties", type: "view", label: "Properties", icon: <SlidersHorizontal />, closable: true },+ { id: "document:plan", type: "document", label: "Plan", icon: <FileText />, closable: true },+ ];+ act(() => {+ root.render(+ <TooltipProvider>+ <SidePanelTabs+ tabs={tabs}+ activeTabId={activeTabId}+ onActiveTabChange={onActiveTabChange}+ onCloseTab={onCloseTab}+ onReorderTabs={onReorderTabs}+ onAddTab={vi.fn()}+ />+ </TooltipProvider>,+ );+ });+ return { tabs, onCloseTab, onActiveTabChange, onReorderTabs };+ }++ it("renders accessible tabs and the anchored add action", () => {+ renderTabs();+ expect(container.querySelector('[role="tablist"]')).not.toBeNull();+ const activeTab = container.querySelector<HTMLButtonElement>('[role="tab"][aria-selected="true"]');+ expect(activeTab?.textContent).toContain("Properties");+ expect(activeTab?.className).toContain("text-xs");+ expect(activeTab?.querySelector("span")?.className).toContain("size-3.5");+ expect(container.querySelector('button[aria-label="Close Properties"]')).not.toBeNull();+ expect(container.querySelector('button[aria-label="Close Plan"]')).toBeNull();+ const addButton = container.querySelector<HTMLButtonElement>('button[aria-label="Open a new tab"]');+ expect(addButton?.className).toContain("text-muted-foreground");+ expect(addButton?.className).toContain("h-(--side-panel-tab-height)");+ });++ it("separates only adjacent inactive tabs", () => {+ act(() => {+ root.render(+ <TooltipProvider>+ <SidePanelTabs+ tabs={[+ { id: "active", type: "view", label: "Active", closable: true },+ { id: "inactive-one", type: "view", label: "Inactive one", closable: true },+ { id: "inactive-two", type: "view", label: "Inactive two", closable: true },+ ]}+ activeTabId="active"+ onActiveTabChange={vi.fn()}+ onCloseTab={vi.fn()}+ />+ </TooltipProvider>,+ );+ });+ const separators = container.querySelectorAll('[data-side-panel-tab-separator="true"]');+ expect(separators).toHaveLength(1);+ expect(separators[0]?.parentElement?.querySelector('[data-side-panel-tab-target="inactive-two"]')).not.toBeNull();+ });++ it("keeps intrinsic tab width stable while giving inactive labels the close-button space", () => {+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue({+ x: 0,+ y: 0,+ top: 0,+ right: 128,+ bottom: 30,+ left: 0,+ width: 128,+ height: 30,+ toJSON: () => ({}),+ });+ renderTabs("properties");+ const planWrapper = container.querySelector<HTMLElement>('[data-side-panel-tab-wrapper="document:plan"]')!;+ const planButton = container.querySelector<HTMLElement>('[data-side-panel-tab-target="document:plan"]')!;+ expect(planWrapper.style.width).toBe("128px");+ expect(planButton.className).toContain("pr-2.5");+ expect(planButton.querySelector('[data-truncated]')?.className ?? planButton.querySelector("span:nth-child(2)")?.className)+ .toContain("max-w-(--side-panel-tab-label-expanded-max-width)");++ renderTabs("document:plan");+ const selectedPlanWrapper = container.querySelector<HTMLElement>('[data-side-panel-tab-wrapper="document:plan"]')!;+ const selectedPlanButton = container.querySelector<HTMLElement>('[data-side-panel-tab-target="document:plan"]')!;+ expect(selectedPlanWrapper.style.width).toBe("128px");+ expect(selectedPlanButton.className).toContain("pr-7");+ });++ it("closes a tab with its named close action", () => {+ const onCloseTab = vi.fn();+ renderTabs("properties", onCloseTab);+ const close = container.querySelector<HTMLButtonElement>('button[aria-label="Close Properties"]');+ act(() => close?.click());+ expect(onCloseTab).toHaveBeenCalledWith("properties");+ });++ it("supports middle-click close", () => {+ const onCloseTab = vi.fn();+ renderTabs("properties", onCloseTab);+ const tab = container.querySelector<HTMLButtonElement>('#side-panel-tab-document\\:plan');+ act(() => tab?.dispatchEvent(new MouseEvent("auxclick", { bubbles: true, button: 1 })));+ expect(onCloseTab).toHaveBeenCalledWith("document:plan");+ });++ it("navigates with Arrow, Home, and End keys", () => {+ const onActiveTabChange = vi.fn();+ renderTabs("properties", vi.fn(), onActiveTabChange);+ const properties = container.querySelector<HTMLButtonElement>('[data-side-panel-tab-target="properties"]')!;+ act(() => properties.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "ArrowRight" })));+ expect(onActiveTabChange).toHaveBeenCalledWith("document:plan");++ const plan = container.querySelector<HTMLButtonElement>('[data-side-panel-tab-target="document:plan"]')!;+ act(() => plan.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Home" })));+ expect(onActiveTabChange).toHaveBeenLastCalledWith("properties");+ });++ it("announces and performs keyboard reordering", () => {+ const onReorderTabs = vi.fn();+ renderTabs("document:plan", vi.fn(), vi.fn(), onReorderTabs);+ const plan = container.querySelector<HTMLButtonElement>('[data-side-panel-tab-target="document:plan"]')!;+ act(() => plan.dispatchEvent(new KeyboardEvent("keydown", {+ bubbles: true,+ key: "ArrowLeft",+ altKey: true,+ shiftKey: true,+ })));+ expect(onReorderTabs).toHaveBeenCalledWith(["document:plan", "properties"]);+ expect(container.querySelector('[aria-live="polite"]')?.textContent).toContain("Moved Plan to position 1 of 2");+ });++ it("recovers focus to the right neighbor after close", () => {+ renderTabs("properties");+ const close = container.querySelector<HTMLButtonElement>('button[aria-label="Close Properties"]')!;+ act(() => close.click());+ expect(document.activeElement).toBe(container.querySelector('[data-side-panel-tab-target="document:plan"]'));+ });+});diff --git a/ui/src/components/side-panel/SidePanelTabs.tsx b/ui/src/components/side-panel/SidePanelTabs.tsxnew file mode 100644index 0000000000..4e8a9ce7cb--- /dev/null+++ b/ui/src/components/side-panel/SidePanelTabs.tsx@@ -0,0 +1,252 @@+import {+ useEffect,+ useMemo,+ useRef,+ useState,+ type ButtonHTMLAttributes,+ type KeyboardEvent,+ type MouseEvent,+ type ReactNode,+} from "react";+import {+ DndContext,+ KeyboardSensor,+ PointerSensor,+ closestCenter,+ useSensor,+ useSensors,+ type DragEndEvent,+} from "@dnd-kit/core";+import {+ SortableContext,+ horizontalListSortingStrategy,+ sortableKeyboardCoordinates,+ useSortable,+} from "@dnd-kit/sortable";+import { CSS as DndCSS } from "@dnd-kit/utilities";+import { Plus } from "lucide-react";+import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";+import { SidePanelTab } from "./SidePanelTab";+import type { SidePanelTabItem } from "./types";++interface SortableSidePanelTabProps {+ tab: SidePanelTabItem;+ active: boolean;+ showLeadingSeparator: boolean;+ onSelect: () => void;+ onClose: () => void;+ onAuxClick: (event: MouseEvent<HTMLButtonElement>) => void;+ onKeyDown: (event: KeyboardEvent<HTMLButtonElement>) => void;+}++function SortableSidePanelTab({ tab, active, showLeadingSeparator, onSelect, onClose, onAuxClick, onKeyDown }: SortableSidePanelTabProps) {+ const sortable = useSortable({ id: tab.id, disabled: tab.disabled });+ return (+ <div+ ref={sortable.setNodeRef}+ style={{+ transform: DndCSS.Transform.toString(sortable.transform),+ transition: sortable.transition,+ }}+ className={cn("relative", sortable.isDragging && "z-20 opacity-80")}+ >+ {showLeadingSeparator ? (+ <span+ aria-hidden+ data-side-panel-tab-separator="true"+ className="pointer-events-none absolute inset-y-2 -left-0.5 w-px bg-border/60"+ />+ ) : null}+ <SidePanelTab+ id={tab.id}+ label={tab.label}+ ariaLabel={tab.ariaLabel}+ icon={tab.icon}+ status={tab.status}+ active={active}+ closable={tab.closable}+ disabled={tab.disabled}+ tabRef={sortable.setActivatorNodeRef}+ dragHandleProps={{+ ...sortable.attributes,+ ...sortable.listeners,+ } as ButtonHTMLAttributes<HTMLButtonElement>}+ onSelect={onSelect}+ onClose={onClose}+ onAuxClick={onAuxClick}+ onKeyDown={onKeyDown}+ />+ </div>+ );+}++export interface SidePanelTabsProps {+ tabs: SidePanelTabItem[];+ activeTabId: string | null;+ onActiveTabChange: (tabId: string) => void;+ onCloseTab: (tabId: string) => void;+ onReorderTabs?: (orderedTabIds: string[]) => void;+ onAddTab?: () => void;+ addControl?: ReactNode;+ addLabel?: string;+ className?: string;+}++export function SidePanelTabs({+ tabs,+ activeTabId,+ onActiveTabChange,+ onCloseTab,+ onReorderTabs,+ onAddTab,+ addControl,+ addLabel = "Open a new tab",+ className,+}: SidePanelTabsProps) {+ const [announcement, setAnnouncement] = useState("");+ const scrollRef = useRef<HTMLDivElement>(null);+ const addButtonRef = useRef<HTMLButtonElement>(null);+ const addControlRef = useRef<HTMLDivElement>(null);+ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),+ );+ const tabIds = useMemo(() => tabs.map((tab) => tab.id), [tabs]);++ function findTabElement(tabId: string, selector: "wrapper" | "target") {+ const attribute = selector === "wrapper"+ ? "data-side-panel-tab-wrapper"+ : "data-side-panel-tab-target";+ return Array.from(+ scrollRef.current?.querySelectorAll<HTMLElement>(`[${attribute}]`) ?? [],+ ).find((element) => element.getAttribute(attribute) === tabId) ?? null;+ }++ useEffect(() => {+ if (!activeTabId) return;+ const element = findTabElement(activeTabId, "wrapper");+ const reducedMotion = typeof window.matchMedia === "function"+ && window.matchMedia("(prefers-reduced-motion: reduce)").matches;+ element?.scrollIntoView({ behavior: reducedMotion ? "auto" : "smooth", block: "nearest", inline: "nearest" });+ // `findTabElement` only reads the committed tab DOM for this active id.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [activeTabId]);++ function focusTab(tabId: string | null) {+ window.requestAnimationFrame(() => {+ if (!tabId) {+ addButtonRef.current?.focus();+ addControlRef.current?.querySelector<HTMLElement>("button, [href], input, [tabindex]:not([tabindex='-1'])")?.focus();+ return;+ }+ const tab = findTabElement(tabId, "target") as HTMLButtonElement | null;+ tab?.focus();+ });+ }++ function closeTab(tabId: string) {+ const index = tabIds.indexOf(tabId);+ const nextFocus = tabIds[index + 1] ?? tabIds[index - 1] ?? null;+ onCloseTab(tabId);+ setAnnouncement(nextFocus ? "Tab closed." : "Last tab closed. Choose something to open.");+ focusTab(nextFocus);+ }++ function handleKeyDown(event: KeyboardEvent<HTMLButtonElement>, tabId: string) {+ const index = tabIds.indexOf(tabId);+ if (index < 0) return;+ if (event.altKey && event.shiftKey && (event.key === "ArrowLeft" || event.key === "ArrowRight")) {+ if (!onReorderTabs) return;+ event.preventDefault();+ const target = event.key === "ArrowLeft" ? index - 1 : index + 1;+ if (target < 0 || target >= tabIds.length) return;+ const ordered = [...tabIds];+ const [moved] = ordered.splice(index, 1);+ ordered.splice(target, 0, moved!);+ onReorderTabs(ordered);+ setAnnouncement(`Moved ${tabs[index]?.label ?? "tab"} to position ${target + 1} of ${tabs.length}.`);+ focusTab(tabId);+ return;+ }+ const targetIndex = event.key === "ArrowLeft"+ ? Math.max(0, index - 1)+ : event.key === "ArrowRight"+ ? Math.min(tabIds.length - 1, index + 1)+ : event.key === "Home"+ ? 0+ : event.key === "End"+ ? tabIds.length - 1+ : -1;+ if (targetIndex < 0 || targetIndex === index) return;+ event.preventDefault();+ const targetId = tabIds[targetIndex]!;+ onActiveTabChange(targetId);+ focusTab(targetId);+ }++ function handleDragEnd(event: DragEndEvent) {+ if (!onReorderTabs || !event.over || event.active.id === event.over.id) return;+ const from = tabIds.indexOf(String(event.active.id));+ const to = tabIds.indexOf(String(event.over.id));+ if (from < 0 || to < 0) return;+ const ordered = [...tabIds];+ const [moved] = ordered.splice(from, 1);+ ordered.splice(to, 0, moved!);+ onReorderTabs(ordered);+ setAnnouncement(`Moved ${tabs[from]?.label ?? "tab"} to position ${to + 1} of ${tabs.length}.`);+ }++ return (+ <div className={cn("flex min-w-0 flex-1 items-center gap-1", className)}>+ <div+ ref={scrollRef}+ role="tablist"+ aria-orientation="horizontal"+ className="min-w-0 flex-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"+ >+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>+ <SortableContext items={tabIds} strategy={horizontalListSortingStrategy}>+ <div className="flex min-w-max items-center gap-1 py-1">+ {tabs.map((tab, index) => (+ <SortableSidePanelTab+ key={tab.id}+ tab={tab}+ active={tab.id === activeTabId}+ showLeadingSeparator={+ index > 0+ && tab.id !== activeTabId+ && tabs[index - 1]?.id !== activeTabId+ }+ onSelect={() => onActiveTabChange(tab.id)}+ onClose={() => closeTab(tab.id)}+ onAuxClick={(event) => {+ if (event.button !== 1 || tab.closable === false) return;+ event.preventDefault();+ closeTab(tab.id);+ }}+ onKeyDown={(event) => handleKeyDown(event, tab.id)}+ />+ ))}+ </div>+ </SortableContext>+ </DndContext>+ </div>+ {addControl ? <div ref={addControlRef} className="shrink-0">{addControl}</div> : (onAddTab ? (+ <Button+ ref={addButtonRef}+ type="button"+ variant="ghost"+ size="icon-sm"+ onClick={onAddTab}+ aria-label={addLabel}+ title={addLabel}+ className="h-(--side-panel-tab-height) w-(--side-panel-tab-height) shrink-0 rounded-(--side-panel-control-radius) text-muted-foreground hover:text-foreground focus-visible:text-foreground"+ >+ <Plus aria-hidden />+ </Button>+ ) : null)}+ <div className="sr-only" aria-live="polite" aria-atomic="true">{announcement}</div>+ </div>+ );+}diff --git a/ui/src/components/side-panel/index.ts b/ui/src/components/side-panel/index.tsnew file mode 100644index 0000000000..ea78e901bd--- /dev/null+++ b/ui/src/components/side-panel/index.ts@@ -0,0 +1,20 @@+export { SidePanelFrame, SidePanelToggleButton, SidePanelWindowControls } from "./SidePanelFrame";+export { SidePanelLauncher } from "./SidePanelLauncher";+export { SidePanelTab } from "./SidePanelTab";+export { SidePanelTabs } from "./SidePanelTabs";+export { useScrollbarWhileScrolling } from "./use-scrollbar-while-scrolling";+export {+ normalizeSidePanelTabsState,+ sidePanelTabsReducer,+ useSidePanelTabs,+ type SidePanelTabsAction,+} from "./use-side-panel-tabs";+export type {+ SidePanelContentMode,+ SidePanelLauncherItem,+ SidePanelLauncherSection,+ SidePanelPresentation,+ SidePanelTabItem,+ SidePanelTabRecord,+ SidePanelTabsState,+} from "./types";diff --git a/ui/src/components/side-panel/types.ts b/ui/src/components/side-panel/types.tsnew file mode 100644index 0000000000..51972f0b0c--- /dev/null+++ b/ui/src/components/side-panel/types.ts@@ -0,0 +1,51 @@+import type { ReactNode } from "react";++export type SidePanelContentMode = "padded" | "prose" | "full-bleed";+export type SidePanelPresentation = "docked" | "sheet" | "embedded";++/**+ * Serializable state owned by a side-panel host. Icons and live status are+ * deliberately projected separately into SidePanelTabItem so stored state+ * never contains React nodes.+ */+export interface SidePanelTabRecord<TPayload = unknown> {+ id: string;+ type: string;+ label: string;+ ariaLabel?: string;+ closable?: boolean;+ payload: TPayload;+ contentMode?: SidePanelContentMode;+}++/** Visual projection consumed by the domain-free tab strip. */+export interface SidePanelTabItem extends Omit<SidePanelTabRecord<unknown>, "payload"> {+ icon?: ReactNode;+ status?: ReactNode;+ disabled?: boolean;+}++export interface SidePanelTabsState<TPayload = unknown> {+ tabs: SidePanelTabRecord<TPayload>[];+ activeTabId: string | null;+}++export interface SidePanelLauncherItem {+ id: string;+ label: string;+ description?: string;+ searchText?: string;+ icon?: ReactNode;+ shortcut?: string;+ alreadyOpen?: boolean;+ disabled?: boolean;+ disabledReason?: string;+}++export interface SidePanelLauncherSection {+ id: string;+ label?: string;+ items: SidePanelLauncherItem[];+ loading?: boolean;+ error?: string | null;+}diff --git a/ui/src/components/side-panel/use-scrollbar-while-scrolling.ts b/ui/src/components/side-panel/use-scrollbar-while-scrolling.tsnew file mode 100644index 0000000000..013caf90be--- /dev/null+++ b/ui/src/components/side-panel/use-scrollbar-while-scrolling.ts@@ -0,0 +1,39 @@+import { useCallback, useEffect, useRef, type UIEventHandler } from "react";++const DEFAULT_IDLE_DELAY_MS = 600;++function parseCssTimeMs(value: string): number | null {+ const trimmed = value.trim();+ if (!trimmed) return null;+ const parsed = Number.parseFloat(trimmed);+ if (!Number.isFinite(parsed)) return null;+ return trimmed.endsWith("s") && !trimmed.endsWith("ms") ? parsed * 1000 : parsed;+}++/** Marks a scroll viewport active only while scroll events are arriving. */+export function useScrollbarWhileScrolling(): UIEventHandler<HTMLDivElement> {+ const idleTimerRef = useRef<number | null>(null);+ const activeElementRef = useRef<HTMLDivElement | null>(null);++ const handleScroll = useCallback<UIEventHandler<HTMLDivElement>>((event) => {+ const element = event.currentTarget;+ activeElementRef.current = element;+ element.dataset.scrollActive = "true";+ if (idleTimerRef.current !== null) window.clearTimeout(idleTimerRef.current);++ const configuredDelay = parseCssTimeMs(+ getComputedStyle(document.documentElement).getPropertyValue("--motion-scrollbar-idle-delay"),+ );+ idleTimerRef.current = window.setTimeout(() => {+ delete element.dataset.scrollActive;+ idleTimerRef.current = null;+ }, configuredDelay ?? DEFAULT_IDLE_DELAY_MS);+ }, []);++ useEffect(() => () => {+ if (idleTimerRef.current !== null) window.clearTimeout(idleTimerRef.current);+ if (activeElementRef.current) delete activeElementRef.current.dataset.scrollActive;+ }, []);++ return handleScroll;+}diff --git a/ui/src/components/side-panel/use-side-panel-tabs-hook.test.tsx b/ui/src/components/side-panel/use-side-panel-tabs-hook.test.tsxnew file mode 100644index 0000000000..d8ffc7111a--- /dev/null+++ b/ui/src/components/side-panel/use-side-panel-tabs-hook.test.tsx@@ -0,0 +1,57 @@+// @vitest-environment jsdom++import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useSidePanelTabs } from "./use-side-panel-tabs";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++describe("useSidePanelTabs", () => {+ const mounted: Array<ReturnType<typeof createRoot>> = [];++ afterEach(() => {+ for (const root of mounted) act(() => root.unmount());+ mounted.length = 0;+ });++ it("reports initial and updated serializable state to the persistence boundary", async () => {+ const onStateChange = vi.fn();+ function Harness() {+ const controller = useSidePanelTabs({+ initialState: {+ tabs: [{ id: "details", type: "details", label: "Details", payload: { source: "fixture" } }],+ activeTabId: "details",+ },+ onStateChange,+ });+ return (+ <button+ type="button"+ onClick={() => controller.openTab({+ id: "history",+ type: "history",+ label: "History",+ payload: { source: "fixture" },+ })}+ >+ Open history+ </button>+ );+ }++ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ mounted.push(root);+ await act(async () => root.render(<Harness />));+ expect(onStateChange).toHaveBeenLastCalledWith(expect.objectContaining({ activeTabId: "details" }));++ await act(async () => container.querySelector("button")?.click());+ expect(onStateChange).toHaveBeenLastCalledWith(expect.objectContaining({+ activeTabId: "history",+ tabs: expect.arrayContaining([expect.objectContaining({ id: "history" })]),+ }));+ container.remove();+ });+});diff --git a/ui/src/components/side-panel/use-side-panel-tabs.test.ts b/ui/src/components/side-panel/use-side-panel-tabs.test.tsnew file mode 100644index 0000000000..8165769612--- /dev/null+++ b/ui/src/components/side-panel/use-side-panel-tabs.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it } from "vitest";+import {+ normalizeSidePanelTabsState,+ sidePanelTabsReducer,+} from "./use-side-panel-tabs";+import type { SidePanelTabRecord, SidePanelTabsState } from "./types";++type Payload = { value: string };++function tab(id: string): SidePanelTabRecord<Payload> {+ return { id, type: "example", label: id.toUpperCase(), payload: { value: id } };+}++function state(ids: string[], activeTabId: string | null = ids[0] ?? null): SidePanelTabsState<Payload> {+ return { tabs: ids.map(tab), activeTabId };+}++describe("sidePanelTabsReducer", () => {+ it("opens a new tab and focuses an already-open tab without duplicating it", () => {+ const opened = sidePanelTabsReducer(state(["a"]), { type: "open", tab: tab("b") });+ expect(opened.tabs.map((entry) => entry.id)).toEqual(["a", "b"]);+ expect(opened.activeTabId).toBe("b");++ const focused = sidePanelTabsReducer(opened, { type: "open", tab: tab("a") });+ expect(focused.tabs.map((entry) => entry.id)).toEqual(["a", "b"]);+ expect(focused.activeTabId).toBe("a");+ });++ it("preserves state identity when the requested tab is already active", () => {+ const initial = state(["a", "b"], "b");++ expect(sidePanelTabsReducer(initial, { type: "open", tab: tab("b") })).toBe(initial);+ expect(sidePanelTabsReducer(initial, { type: "select", tabId: "b" })).toBe(initial);+ });++ it("selects the right neighbor, then the left, when closing the active tab", () => {+ const right = sidePanelTabsReducer(state(["a", "b", "c"], "b"), { type: "close", tabId: "b" });+ expect(right.activeTabId).toBe("c");++ const left = sidePanelTabsReducer(state(["a", "b"], "b"), { type: "close", tabId: "b" });+ expect(left.activeTabId).toBe("a");+ });++ it("preserves an intentionally empty state", () => {+ expect(sidePanelTabsReducer(state(["a"]), { type: "close", tabId: "a" })).toEqual({+ tabs: [],+ activeTabId: null,+ });+ });++ it("reorders only complete, unique tab orders", () => {+ const initial = state(["a", "b", "c"], "b");+ expect(sidePanelTabsReducer(initial, {+ type: "reorder",+ orderedTabIds: ["c", "a", "b"],+ })).toEqual({ tabs: [tab("c"), tab("a"), tab("b")], activeTabId: "b" });+ expect(sidePanelTabsReducer(initial, {+ type: "reorder",+ orderedTabIds: ["a", "a", "b"],+ })).toBe(initial);+ });++ it("normalizes duplicates and invalid active ids", () => {+ expect(normalizeSidePanelTabsState({+ tabs: [tab("a"), tab("a"), tab("b")],+ activeTabId: "missing",+ })).toEqual({ tabs: [tab("a"), tab("b")], activeTabId: "a" });+ });++ it("closes other tabs and preserves the selected tab", () => {+ expect(sidePanelTabsReducer(state(["a", "b", "c"], "a"), {+ type: "close-others",+ tabId: "b",+ })).toEqual({ tabs: [tab("b")], activeTabId: "b" });+ });++ it("updates serializable metadata without allowing the stable id to change", () => {+ expect(sidePanelTabsReducer(state(["a"]), {+ type: "update",+ tabId: "a",+ patch: { id: "changed", label: "Renamed", payload: { value: "updated" } },+ })).toEqual({+ tabs: [{ ...tab("a"), label: "Renamed", payload: { value: "updated" } }],+ activeTabId: "a",+ });+ });++ it("normalizes reset state", () => {+ expect(sidePanelTabsReducer(state(["a"]), {+ type: "reset",+ state: { tabs: [tab("b"), tab("b")], activeTabId: "missing" },+ })).toEqual({ tabs: [tab("b")], activeTabId: "b" });+ });+});diff --git a/ui/src/components/side-panel/use-side-panel-tabs.ts b/ui/src/components/side-panel/use-side-panel-tabs.tsnew file mode 100644index 0000000000..09ae27a264--- /dev/null+++ b/ui/src/components/side-panel/use-side-panel-tabs.ts@@ -0,0 +1,140 @@+import { useCallback, useEffect, useReducer } from "react";+import type { SidePanelTabRecord, SidePanelTabsState } from "./types";++export type SidePanelTabsAction<TPayload> =+ | { type: "open"; tab: SidePanelTabRecord<TPayload>; activate?: boolean }+ | { type: "select"; tabId: string }+ | { type: "close"; tabId: string }+ | { type: "close-others"; tabId: string }+ | { type: "reorder"; orderedTabIds: string[] }+ | { type: "update"; tabId: string; patch: Partial<SidePanelTabRecord<TPayload>> }+ | { type: "reset"; state: SidePanelTabsState<TPayload> };++export function normalizeSidePanelTabsState<TPayload>(+ state: SidePanelTabsState<TPayload>,+): SidePanelTabsState<TPayload> {+ const seen = new Set<string>();+ const tabs = state.tabs.filter((tab) => {+ if (!tab.id || !tab.type || seen.has(tab.id)) return false;+ seen.add(tab.id);+ return true;+ });+ const activeTabId = state.activeTabId && seen.has(state.activeTabId)+ ? state.activeTabId+ : tabs[0]?.id ?? null;+ return { tabs, activeTabId };+}++export function sidePanelTabsReducer<TPayload>(+ state: SidePanelTabsState<TPayload>,+ action: SidePanelTabsAction<TPayload>,+): SidePanelTabsState<TPayload> {+ switch (action.type) {+ case "open": {+ const existing = state.tabs.find((tab) => tab.id === action.tab.id);+ if (existing) {+ return action.activate === false || state.activeTabId === existing.id+ ? state+ : { ...state, activeTabId: existing.id };+ }+ return {+ tabs: [...state.tabs, action.tab],+ activeTabId: action.activate === false ? state.activeTabId : action.tab.id,+ };+ }+ case "select":+ return state.activeTabId === action.tabId+ ? state+ : state.tabs.some((tab) => tab.id === action.tabId)+ ? { ...state, activeTabId: action.tabId }+ : state;+ case "close": {+ const index = state.tabs.findIndex((tab) => tab.id === action.tabId);+ if (index < 0) return state;+ const tabs = state.tabs.filter((tab) => tab.id !== action.tabId);+ if (state.activeTabId !== action.tabId) return { ...state, tabs };+ return {+ tabs,+ activeTabId: tabs[index]?.id ?? tabs[index - 1]?.id ?? null,+ };+ }+ case "close-others": {+ const tab = state.tabs.find((candidate) => candidate.id === action.tabId);+ return tab ? { tabs: [tab], activeTabId: tab.id } : state;+ }+ case "reorder": {+ if (action.orderedTabIds.length !== state.tabs.length) return state;+ const byId = new Map(state.tabs.map((tab) => [tab.id, tab]));+ const tabs = action.orderedTabIds.map((id) => byId.get(id));+ if (tabs.some((tab) => !tab) || new Set(action.orderedTabIds).size !== state.tabs.length) {+ return state;+ }+ return { ...state, tabs: tabs as SidePanelTabRecord<TPayload>[] };+ }+ case "update": {+ let changed = false;+ const tabs = state.tabs.map((tab) => {+ if (tab.id !== action.tabId) return tab;+ changed = true;+ return { ...tab, ...action.patch, id: tab.id };+ });+ return changed ? { ...state, tabs } : state;+ }+ case "reset":+ return normalizeSidePanelTabsState(action.state);+ }+}++interface UseSidePanelTabsOptions<TPayload> {+ initialState: SidePanelTabsState<TPayload>;+ onStateChange?: (state: SidePanelTabsState<TPayload>) => void;+}++export function useSidePanelTabs<TPayload>({+ initialState,+ onStateChange,+}: UseSidePanelTabsOptions<TPayload>) {+ const [state, dispatch] = useReducer(+ sidePanelTabsReducer<TPayload>,+ initialState,+ normalizeSidePanelTabsState,+ );++ useEffect(() => {+ onStateChange?.(state);+ }, [onStateChange, state]);++ const openTab = useCallback((tab: SidePanelTabRecord<TPayload>, activate = true) => {+ dispatch({ type: "open", tab, activate });+ }, []);+ const selectTab = useCallback((tabId: string) => dispatch({ type: "select", tabId }), []);+ const closeTab = useCallback((tabId: string) => dispatch({ type: "close", tabId }), []);+ const closeOtherTabs = useCallback(+ (tabId: string) => dispatch({ type: "close-others", tabId }),+ [],+ );+ const reorderTabs = useCallback(+ (orderedTabIds: string[]) => dispatch({ type: "reorder", orderedTabIds }),+ [],+ );+ const updateTab = useCallback(+ (tabId: string, patch: Partial<SidePanelTabRecord<TPayload>>) =>+ dispatch({ type: "update", tabId, patch }),+ [],+ );+ const resetTabs = useCallback(+ (next: SidePanelTabsState<TPayload>) => dispatch({ type: "reset", state: next }),+ [],+ );++ return {+ ...state,+ openTab,+ selectTab,+ closeTab,+ closeOtherTabs,+ reorderTabs,+ updateTab,+ resetTabs,+ };+}diff --git a/ui/src/components/task-chat/QuestionForm.tsx b/ui/src/components/task-chat/QuestionForm.tsxnew file mode 100644index 0000000000..e7bee42572--- /dev/null+++ b/ui/src/components/task-chat/QuestionForm.tsx@@ -0,0 +1,641 @@+import { useEffect, useMemo, useState } from "react";+import {+ Check,+ ChevronLeft,+ ChevronRight,+ Loader2,+ Search,+} from "lucide-react";+import type {+ PaperclipQuestionResponse,+ PaperclipQuestionSet,+} from "@paperclipai/adapter-utils";+import type { MentionOption } from "@/components/MarkdownEditor";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import {+ clearDraft,+ loadStructuredDraft,+ saveStructuredDraft,+} from "@/lib/composer-draft";+import { cn } from "@/lib/utils";+import {+ TaskChatComposerTakeoverControls,+ useTaskChatComposerTakeoverActions,+} from "./TaskChatComposerTakeoverContext";+import { TaskChatRichInput } from "./TaskChatRichInput";+import { matchSafeQuestionValidationPattern } from "./question-validation-pattern";++type Question = PaperclipQuestionSet["questions"][number];+type Answer = PaperclipQuestionResponse["answers"][string];++export interface QuestionFormProps {+ id: string;+ questionSet: PaperclipQuestionSet;+ initialResponse?: PaperclipQuestionResponse | null;+ implicitCustomAnswer?: boolean;+ draftKey?: string;+ disabled?: boolean;+ imageUploadHandler?: (file: File) => Promise<string>;+ mentions?: MentionOption[];+ onSubmit: (response: PaperclipQuestionResponse) => void | Promise<void>;+ onCancel?: () => void | Promise<void>;+}++function answerHasValue(answer: Answer | undefined): boolean {+ return Boolean(+ answer?.text?.trim() ||+ answer?.customText?.trim() ||+ answer?.selectedOptionIds?.length,+ );+}++function answerError(+ question: Question,+ answer: Answer | undefined,+): string | null {+ if (question.required && !answerHasValue(answer))+ return "This question is required.";+ if (+ question.answerMode !== "text" &&+ answer?.customText !== undefined &&+ !answer.customText.trim()+ ) {+ return "Enter a custom answer.";+ }+ const value =+ question.answerMode === "text" ? answer?.text : answer?.customText;+ if (value == null || value.length === 0) return null;+ const validation = question.textValidation;+ if (validation?.minLength != null && value.length < validation.minLength)+ return `Enter at least ${validation.minLength} characters.`;+ if (validation?.maxLength != null && value.length > validation.maxLength)+ return `Enter no more than ${validation.maxLength} characters.`;+ if (validation?.pattern) {+ const result = matchSafeQuestionValidationPattern(validation.pattern, value);+ if (result === "unsupported")+ return "This question has an unsupported validation pattern.";+ if (result === "no_match") return "Use the requested format.";+ }+ if (+ validation?.inputType === "number" ||+ validation?.inputType === "integer"+ ) {+ const numeric = Number(value);+ if (+ !Number.isFinite(numeric) ||+ (validation.inputType === "integer" && !Number.isInteger(numeric))+ ) {+ return `Enter a valid ${validation.inputType}.`;+ }+ if (validation.minimum != null && numeric < validation.minimum)+ return `Enter a value of at least ${validation.minimum}.`;+ if (validation.maximum != null && numeric > validation.maximum)+ return `Enter a value no greater than ${validation.maximum}.`;+ }+ return null;+}++function SelectOption({+ id,+ label,+ description,+ recommended,+ selected,+ multiple,+ disabled,+ onClick,+}: {+ id: string;+ label: string;+ description?: string;+ recommended?: boolean;+ selected: boolean;+ multiple: boolean;+ disabled: boolean;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ id={id}+ role={multiple ? "checkbox" : "radio"}+ aria-checked={selected}+ disabled={disabled}+ className={cn(+ "flex w-full items-start gap-2 rounded-md px-2.5 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60",+ selected+ ? "bg-muted/80"+ : recommended+ ? "bg-muted/50"+ : "hover:bg-muted/40",+ )}+ data-selected={selected ? "true" : "false"}+ data-recommended={recommended ? "true" : "false"}+ onClick={onClick}+ >+ <span+ aria-hidden+ className={cn(+ "mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center border",+ multiple ? "rounded-sm" : "rounded-full",+ selected+ ? "border-primary bg-primary text-primary-foreground"+ : "border-muted-foreground/50",+ )}+ >+ {selected ? (+ multiple ? (+ <Check className="h-3 w-3" />+ ) : (+ <span className="h-1.5 w-1.5 rounded-full bg-current" />+ )+ ) : null}+ </span>+ <span className="min-w-0 flex-1">+ <span className="flex flex-wrap items-center gap-1.5 text-sm font-medium leading-5 text-foreground">+ <span>{label}</span>+ {recommended ? (+ <span className="rounded-sm bg-background/70 px-1.5 py-0.5 text-(length:--text-micro) font-medium text-muted-foreground">+ Recommended+ </span>+ ) : null}+ </span>+ {description ? (+ <span className="block text-xs leading-4 text-muted-foreground">+ {description}+ </span>+ ) : null}+ </span>+ </button>+ );+}++export function QuestionResponseSummary({+ questionSet,+ response,+}: {+ questionSet: PaperclipQuestionSet;+ response: PaperclipQuestionResponse;+}) {+ return (+ <dl className="grid gap-2 text-sm">+ {questionSet.questions.map((question) => {+ const answer = response.answers[question.id];+ const selectedLabels = (answer?.selectedOptionIds ?? []).map(+ (optionId) =>+ question.options?.find((option) => option.id === optionId)?.label ??+ optionId,+ );+ const values = [+ ...selectedLabels,+ answer?.text,+ answer?.customText,+ ].filter((value): value is string => Boolean(value));+ return (+ <div key={question.id}>+ <dt>+ {question.header ? (+ <span className="block text-xs font-medium text-muted-foreground">+ {question.header}+ </span>+ ) : null}+ <span className="block text-sm text-foreground">+ {question.prompt}+ </span>+ </dt>+ <dd className="mt-0.5 text-foreground">+ {values.length > 0 ? values.join(", ") : "No answer"}+ </dd>+ </div>+ );+ })}+ </dl>+ );+}++export function QuestionForm({+ id,+ questionSet,+ initialResponse,+ implicitCustomAnswer = false,+ draftKey,+ disabled = false,+ imageUploadHandler,+ mentions,+ onSubmit,+ onCancel,+}: QuestionFormProps) {+ const takeoverActions = useTaskChatComposerTakeoverActions();+ const initialDraft = draftKey+ ? loadStructuredDraft<{+ page: number;+ answers: Record<string, Answer>;+ customActive: Record<string, boolean>;+ }>(draftKey, {+ page: 0,+ answers: structuredClone(initialResponse?.answers ?? {}),+ customActive: Object.fromEntries(+ Object.entries(initialResponse?.answers ?? {})+ .filter(([, answer]) => Boolean(answer.customText))+ .map(([questionId]) => [questionId, true]),+ ),+ })+ : null;+ const [page, setPage] = useState(initialDraft?.page ?? 0);+ const [answers, setAnswers] = useState<Record<string, Answer>>(+ () =>+ initialDraft?.answers ?? structuredClone(initialResponse?.answers ?? {}),+ );+ const [customActive, setCustomActive] = useState<Record<string, boolean>>(+ () =>+ initialDraft?.customActive ??+ Object.fromEntries(+ Object.entries(initialResponse?.answers ?? {})+ .filter(([, answer]) => Boolean(answer.customText))+ .map(([questionId]) => [questionId, true]),+ ),+ );+ const [working, setWorking] = useState<"submit" | "cancel" | null>(null);+ const [inputUploading, setInputUploading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [filters, setFilters] = useState<Record<string, string>>({});++ useEffect(() => {+ setPage((current) =>+ Math.min(current, Math.max(questionSet.questions.length - 1, 0)),+ );+ }, [questionSet.questions.length]);+ useEffect(() => {+ if (draftKey)+ saveStructuredDraft(draftKey, { page, answers, customActive });+ }, [answers, customActive, draftKey, page]);++ const question = questionSet.questions[page];+ const validationErrors = useMemo(+ () =>+ Object.fromEntries(+ questionSet.questions.map((candidate) => [+ candidate.id,+ answerError(candidate, answers[candidate.id]),+ ]),+ ),+ [answers, questionSet.questions],+ );+ const allValid = Object.values(validationErrors).every(+ (value) => value == null,+ );+ if (!question)+ return (+ <p className="text-sm text-muted-foreground">+ No answerable questions were provided.+ </p>+ );+ const answer = answers[question.id] ?? {};+ const selected = answer.selectedOptionIds ?? [];+ const multiple = question.answerMode === "multi_select";+ const allowsCustom =+ question.answerMode !== "text" &&+ (question.customAnswer?.enabled === true || implicitCustomAnswer);+ const isCustomActive = customActive[question.id] === true;+ const optionFilter = filters[question.id]?.trim().toLowerCase() ?? "";+ const visibleOptions = (question.options ?? []).filter(+ (option) =>+ !optionFilter ||+ option.label.toLowerCase().includes(optionFilter) ||+ option.description?.toLowerCase().includes(optionFilter),+ );++ function updateAnswer(next: Answer) {+ setAnswers((current) => ({ ...current, [question.id]: next }));+ }++ function toggleOption(optionId: string) {+ const optionIds = multiple+ ? selected.includes(optionId)+ ? selected.filter((candidate) => candidate !== optionId)+ : [...selected, optionId]+ : [optionId];+ const nextAnswer = {+ ...answer,+ selectedOptionIds: optionIds,+ ...(!multiple ? { customText: undefined } : {}),+ };+ const nextAnswers = { ...answers, [question.id]: nextAnswer };+ setAnswers(nextAnswers);+ if (!multiple) {+ setCustomActive((current) => ({ ...current, [question.id]: false }));+ if (page < questionSet.questions.length - 1) setPage(page + 1);+ else void submit(nextAnswers);+ }+ }++ function toggleCustom() {+ const active = !isCustomActive;+ setCustomActive((current) => ({ ...current, [question.id]: active }));+ updateAnswer({+ ...answer,+ ...(!multiple && active ? { selectedOptionIds: [] } : {}),+ ...(active+ ? { customText: answer.customText ?? "" }+ : { customText: undefined }),+ });+ }++ async function submit(responseAnswers: Record<string, Answer> = answers) {+ const responseIsValid = questionSet.questions.every(+ (candidate) =>+ answerError(candidate, responseAnswers[candidate.id]) == null,+ );+ if (!responseIsValid || disabled || working || inputUploading) return;+ setWorking("submit");+ setError(null);+ try {+ await onSubmit({+ schema: "paperclip.question_response.v1",+ answers: structuredClone(responseAnswers),+ });+ if (draftKey) clearDraft(draftKey);+ } catch (cause) {+ setError(+ cause instanceof Error+ ? cause.message+ : "The answers could not be submitted.",+ );+ } finally {+ setWorking(null);+ }+ }++ async function cancel() {+ if (!onCancel || disabled || working || inputUploading) return;+ setWorking("cancel");+ setError(null);+ try {+ await onCancel();+ if (draftKey) clearDraft(draftKey);+ } catch (cause) {+ setError(+ cause instanceof Error+ ? cause.message+ : "The questions could not be cancelled.",+ );+ } finally {+ setWorking(null);+ }+ }++ const currentError = validationErrors[question.id];+ const isLastPage = page === questionSet.questions.length - 1;+ const showQuestionActionButton =+ multiple ||+ (isLastPage && (question.answerMode !== "single_select" || isCustomActive));+ const showActionRow = Boolean(+ takeoverActions?.skipButton || onCancel || showQuestionActionButton,+ );+ const pagination =+ questionSet.questions.length > 1 ? (+ <nav+ className="flex shrink-0 items-center gap-1"+ aria-label="Question pagination"+ >+ <Button+ type="button"+ size="icon-xs"+ variant="ghost"+ aria-label="Previous question"+ disabled={disabled || working != null || page === 0}+ onClick={() => setPage((current) => current - 1)}+ >+ <ChevronLeft aria-hidden />+ </Button>+ <span className="min-w-10 text-center tabular-nums">+ {page + 1} of {questionSet.questions.length}+ </span>+ <Button+ type="button"+ size="icon-xs"+ variant="ghost"+ aria-label="Next question"+ disabled={disabled || working != null || isLastPage}+ onClick={() => setPage((current) => current + 1)}+ >+ <ChevronRight aria-hidden />+ </Button>+ </nav>+ ) : null;++ function progressOrSubmit() {+ if (!isLastPage) {+ setPage((current) =>+ Math.min(current + 1, questionSet.questions.length - 1),+ );+ return;+ }+ void submit();+ }+ return (+ <div+ onKeyDown={(event) => {+ if (+ disabled ||+ working ||+ question.answerMode === "text" ||+ event.metaKey ||+ event.ctrlKey ||+ event.altKey+ )+ return;+ const target = event.target as HTMLElement;+ if (target.matches("input, textarea, [contenteditable='true']")) return;+ const optionIndex = Number.parseInt(event.key, 10) - 1;+ const option = visibleOptions[optionIndex];+ if (!option || optionIndex < 0 || optionIndex > 8) return;+ event.preventDefault();+ toggleOption(option.id);+ }}+ >+ {questionSet.description ? (+ <p className="mb-3 text-sm text-muted-foreground">+ {questionSet.description}+ </p>+ ) : null}+ {question.answerMode === "text" ? (+ <div className="mb-2 flex items-center gap-3 text-xs text-muted-foreground">+ {question.answerMode === "text" ? <span>Write an answer</span> : null}+ </div>+ ) : null}+ {pagination ? (+ takeoverActions ? (+ <TaskChatComposerTakeoverControls>+ {pagination}+ </TaskChatComposerTakeoverControls>+ ) : (+ <div className="mb-2 flex justify-end text-xs text-muted-foreground">+ {pagination}+ </div>+ )+ ) : null}+ <div>+ {question.header ? (+ <p className="mb-1 text-xs font-medium text-muted-foreground">+ {question.header}+ </p>+ ) : null}+ <p+ id={`${id}-${question.id}-prompt`}+ className="text-sm font-medium leading-5 text-foreground"+ >+ {question.prompt}+ </p>+ {question.helpText ? (+ <p className="mt-1 text-xs leading-4 text-muted-foreground">+ {question.helpText}+ </p>+ ) : null}+ </div>+ {question.answerMode === "text" ? (+ <div className="mt-3">+ <TaskChatRichInput+ ariaLabelledBy={`${id}-${question.id}-prompt`}+ testId="question-text-answer-composer"+ value={answer.text ?? ""}+ disabled={disabled || working != null}+ onChange={(value) => updateAnswer({ text: value })}+ placeholder="Write your answer"+ imageUploadHandler={imageUploadHandler}+ mentions={mentions}+ autoFocus+ onUploadingChange={setInputUploading}+ onSubmit={() => {+ if (!inputUploading && currentError == null) progressOrSubmit();+ }}+ attachAriaLabel={`Attach image to answer for ${question.prompt}`}+ />+ </div>+ ) : (+ <div+ className="mt-3 grid gap-1.5"+ role={multiple ? "group" : "radiogroup"}+ aria-labelledby={`${id}-${question.id}-prompt`}+ >+ {(question.options?.length ?? 0) > 8 ? (+ <label className="relative mb-1 block">+ <Search+ className="pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"+ aria-hidden+ />+ <Input+ value={filters[question.id] ?? ""}+ onChange={(event) =>+ setFilters((current) => ({+ ...current,+ [question.id]: event.target.value,+ }))+ }+ placeholder="Filter choices"+ aria-label={`Filter choices for ${question.prompt}`}+ className="pl-8"+ />+ </label>+ ) : null}+ {visibleOptions.map((option) => (+ <SelectOption+ key={option.id}+ id={`${id}-${question.id}-${option.id}`}+ label={option.label}+ description={option.description}+ recommended={option.recommended}+ selected={selected.includes(option.id)}+ multiple={multiple}+ disabled={disabled || working != null}+ onClick={() => toggleOption(option.id)}+ />+ ))}+ {allowsCustom ? (+ <div className="space-y-1.5">+ <SelectOption+ id={`${id}-${question.id}-custom`}+ label={question.customAnswer?.label ?? "Other"}+ selected={isCustomActive}+ multiple={multiple}+ disabled={disabled || working != null}+ onClick={toggleCustom}+ />+ {isCustomActive ? (+ <TaskChatRichInput+ ariaLabelledBy={`${id}-${question.id}-prompt`}+ testId="question-other-answer-composer"+ value={answer.customText ?? ""}+ placeholder={+ question.customAnswer?.placeholder ?? "Type your answer"+ }+ disabled={disabled || working != null}+ onChange={(value) =>+ updateAnswer({ ...answer, customText: value })+ }+ autoFocus+ imageUploadHandler={imageUploadHandler}+ mentions={mentions}+ onUploadingChange={setInputUploading}+ onSubmit={() => {+ if (!inputUploading && currentError == null)+ progressOrSubmit();+ }}+ attachAriaLabel={`Attach image to other answer for ${question.prompt}`}+ />+ ) : null}+ </div>+ ) : null}+ </div>+ )}+ {currentError && answerHasValue(answer) ? (+ <p className="mt-2 text-xs text-destructive">{currentError}</p>+ ) : null}+ <div aria-live="assertive">+ {error ? (+ <div className="mt-2 rounded-sm border border-destructive/60 bg-destructive/10 px-2.5 py-2 text-sm text-destructive">+ {error}+ </div>+ ) : null}+ </div>+ {showActionRow ? (+ <div className="mt-3 flex flex-wrap items-center justify-end gap-2">+ {takeoverActions?.skipButton}+ {onCancel ? (+ <Button+ type="button"+ size="sm"+ variant="ghost"+ disabled={disabled || working != null || inputUploading}+ onClick={() => void cancel()}+ >+ {working === "cancel" ? (+ <Loader2 aria-hidden className="h-4 w-4 animate-spin" />+ ) : null}{" "}+ Cancel+ </Button>+ ) : null}+ {showQuestionActionButton ? (+ <Button+ type="button"+ size="sm"+ disabled={+ disabled ||+ working != null ||+ inputUploading ||+ (isLastPage ? !allValid : currentError != null)+ }+ onClick={progressOrSubmit}+ >+ {working === "submit" ? (+ <Loader2 aria-hidden className="h-4 w-4 animate-spin" />+ ) : null}+ {questionSet.submitLabel ?? "Submit answers"}+ </Button>+ ) : null}+ </div>+ ) : null}+ </div>+ );+}diff --git a/ui/src/components/task-chat/TaskChatActivityPhase.test.tsx b/ui/src/components/task-chat/TaskChatActivityPhase.test.tsxindex 260b784747..bdcc4ae5d7 100644--- a/ui/src/components/task-chat/TaskChatActivityPhase.test.tsx+++ b/ui/src/components/task-chat/TaskChatActivityPhase.test.tsx@@ -5,16 +5,32 @@ import { afterEach, describe, expect, it } from "vitest";import { TaskChatActivityPhase } from "./TaskChatActivityPhase";describe("TaskChatActivityPhase", () => {- afterEach(() => { document.body.innerHTML = ""; });+ afterEach(() => {+ document.body.innerHTML = "";+ });it("defaults collapsed, exposes aria state, and unmounts collapsed children", () => {const container = document.createElement("div");document.body.appendChild(container);const root = createRoot(container);- flushSync(() => root.render(<TaskChatActivityPhase item={{- id: "phase-1", kind: "activity_phase", active: false, summary: "Read 1 file",- items: [{ id: "tool-1", kind: "tool", name: "Read", status: "completed" }],- }} renderChild={(child) => <button>{child.id}</button>} />));- const summary = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-phase-summary"]')!;+ flushSync(() =>+ root.render(+ <TaskChatActivityPhase+ item={{+ id: "phase-1",+ kind: "activity_phase",+ active: false,+ summary: "Read 1 file",+ items: [+ { id: "tool-1", kind: "tool", name: "Read", status: "completed" },+ ],+ }}+ renderChild={(child) => <button>{child.id}</button>}+ />,+ ),+ );+ const summary = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-phase-summary"]',+ )!;expect(summary.firstElementChild?.tagName).toBe("svg");expect(summary.getAttribute("aria-expanded")).toBe("false");expect(container.textContent).not.toContain("tool-1");@@ -22,7 +38,71 @@ describe("TaskChatActivityPhase", () => {expect(summary.getAttribute("aria-expanded")).toBe("true");expect(container.textContent).toContain("tool-1");flushSync(() => summary.click());- expect(container.querySelector('[data-testid="task-chat-phase-children"]')).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-phase-children"]'),+ ).toBeNull();+ flushSync(() => root.unmount());+ });++ it("uses a representative icon and hover-only right caret in the runner appearance", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ flushSync(() =>+ root.render(+ <TaskChatActivityPhase+ item={{+ id: "phase-runner",+ kind: "activity_phase",+ active: false,+ summary: "Read a file, ran a command",+ items: [+ {+ id: "tool-read",+ kind: "tool",+ name: "Read",+ rawName: "read_file",+ status: "completed",+ },+ {+ id: "tool-command",+ kind: "tool",+ name: "Bash",+ rawName: "bash",+ status: "completed",+ },+ ],+ }}+ appearance="runner"+ renderChild={(child) => <button>{child.id}</button>}+ />,+ ),+ );++ const summary = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-phase-summary"]',+ )!;+ const icon = summary.querySelector(+ '[data-testid="task-chat-phase-summary-icon"]',+ );+ const iconSlot = summary.querySelector(+ '[data-testid="task-chat-phase-summary-icon-slot"]',+ );+ const caret = summary.querySelector(+ '[data-testid="task-chat-phase-summary-caret"]',+ );+ expect(summary.firstElementChild).toBe(iconSlot);+ expect(iconSlot?.firstElementChild).toBe(icon);+ expect(iconSlot?.classList.contains("w-6")).toBe(true);+ expect(iconSlot?.classList.contains("justify-center")).toBe(true);+ expect(summary.lastElementChild).toBe(caret);+ expect(summary.querySelectorAll("svg")).toHaveLength(2);+ expect(summary.className).toContain("min-h-8");+ expect(summary.className).toContain("py-1.5");+ expect(summary.className).toContain("text-muted-foreground");+ expect(caret?.classList.contains("ml-auto")).toBe(true);+ expect(caret?.classList.contains("opacity-0")).toBe(true);+flushSync(() => root.unmount());});});diff --git a/ui/src/components/task-chat/TaskChatActivityPhase.tsx b/ui/src/components/task-chat/TaskChatActivityPhase.tsxindex aad8cec53b..837cef2638 100644--- a/ui/src/components/task-chat/TaskChatActivityPhase.tsx+++ b/ui/src/components/task-chat/TaskChatActivityPhase.tsx@@ -1,23 +1,90 @@-import { useState, type ReactNode } from "react";-import { ChevronRight } from "lucide-react";+import { useEffect, useState, type ReactNode } from "react";+import { Brain, ChevronRight, CircleEllipsis } from "lucide-react";import { cn } from "@/lib/utils";import { MarkdownBody } from "@/components/MarkdownBody";import type { TaskChatActivityPhaseItem } from "./task-chat-model";+import { protocolActivityPresentation } from "./task-chat-activity-presentation";+import { toolTaxonomy, type ToolIcon } from "./tool-taxonomy";++function representativeIcon(item: TaskChatActivityPhaseItem): ToolIcon {+ // Prefer a concrete operation over bookkeeping/reasoning. A phase can own+ // many different rows, but its collapsed summary needs one calm visual cue.+ for (const child of item.items) {+ if (child.kind === "tool") {+ return toolTaxonomy(child.rawName ?? child.name).icon;+ }+ if (child.kind === "protocol") {+ const presentation = protocolActivityPresentation(child);+ if (presentation) return presentation.icon;+ }+ }+ if (item.items.some((child) => child.kind === "thinking")) return Brain;+ return CircleEllipsis;+}export function TaskChatActivityPhase({item,renderChild,+ renderChildren,+ autoOpen = true,+ defaultOpen = false,+ childrenClassName,+ showChildRail = false,+ appearance = "classic",}: {item: TaskChatActivityPhaseItem;renderChild: (child: TaskChatActivityPhaseItem["items"][number]) => ReactNode;+ renderChildren?: (children: TaskChatActivityPhaseItem["items"]) => ReactNode;+ autoOpen?: boolean;+ /** Keep useful historical content visible in an in-flight transcript. */+ defaultOpen?: boolean;+ childrenClassName?: string;+ /** Draws a nested-activity rail aligned beneath the summary disclosure. */+ showChildRail?: boolean;+ /** Codex-style summary treatment used only by the new Paperclip task UI. */+ appearance?: "classic" | "runner";}) {- const [open, setOpen] = useState(false);+ const shouldAutoOpen =+ defaultOpen ||+ (autoOpen &&+ (item.active ||+ item.items.some(+ (child) =>+ (child.kind === "thinking" && child.streaming) ||+ (child.kind === "tool" && child.status === "in_progress") ||+ (child.kind === "protocol" &&+ child.surface === "provider_activity" &&+ child.status === "running") ||+ (child.kind === "protocol" &&+ child.surface === "workspace_change" &&+ !child.complete) ||+ (child.kind === "protocol" &&+ child.surface === "runtime_request" &&+ child.status === "pending"),+ )));+ const [open, setOpen] = useState(shouldAutoOpen);+ useEffect(() => {+ if (shouldAutoOpen) setOpen(true);+ }, [shouldAutoOpen]);const expandable = item.items.length > 0;+ const runnerAppearance = appearance === "runner";+ const SummaryIcon = runnerAppearance ? representativeIcon(item) : null;return (- <div className="flex min-w-0 flex-col gap-1" data-testid="task-chat-activity-phase">+ <div+ className={cn(+ "flex min-w-0 flex-col",+ runnerAppearance ? "gap-2" : "gap-1",+ )}+ data-testid="task-chat-activity-phase"+ >{item.interstitial ? (- <div className="min-w-0 px-1 text-sm text-foreground/90" data-testid="task-chat-phase-interstitial">- <MarkdownBody softBreaks linkIssueReferences>{item.interstitial.text}</MarkdownBody>+ <div+ className="min-w-0 px-1 text-sm text-foreground/90"+ data-testid="task-chat-phase-interstitial"+ >+ <MarkdownBody softBreaks linkIssueReferences>+ {item.interstitial.text}+ </MarkdownBody></div>) : null}{expandable ? (@@ -27,18 +94,65 @@ export function TaskChatActivityPhase({aria-label={`${open ? "Collapse" : "Expand"} activity: ${item.summary}`}onClick={() => setOpen((value) => !value)}className={cn(- "group flex min-w-0 items-center gap-1.5 rounded-sm px-1 py-0.5 text-left text-xs transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- item.active ? "text-foreground" : "text-muted-foreground",+ runnerAppearance+ ? "group/activity-phase flex min-h-8 w-full min-w-0 items-center gap-2 rounded-sm px-1 py-1.5 text-left text-sm leading-5 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ : "group flex min-w-0 items-center gap-1.5 rounded-sm px-1 py-0.5 text-left text-xs transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ item.active ? "text-foreground/80" : "text-muted-foreground",)}data-testid="task-chat-phase-summary">- <ChevronRight className={cn("h-3 w-3 shrink-0 transition-transform", open && "rotate-90")} aria-hidden />+ {SummaryIcon ? (+ <span+ className="flex w-6 shrink-0 items-center justify-center"+ data-testid="task-chat-phase-summary-icon-slot"+ >+ <SummaryIcon+ className="h-3.5 w-3.5 shrink-0"+ aria-hidden+ data-testid="task-chat-phase-summary-icon"+ />+ </span>+ ) : (+ <ChevronRight+ className={cn(+ "h-3 w-3 shrink-0 transition-transform",+ open && "rotate-90",+ )}+ aria-hidden+ />+ )}<span className="min-w-0 break-words">{item.summary}</span>+ {runnerAppearance ? (+ <ChevronRight+ className={cn(+ "ml-auto h-3 w-3 shrink-0 opacity-0 transition-[opacity,transform] group-hover/activity-phase:opacity-70 group-focus-visible/activity-phase:opacity-70",+ open && "rotate-90",+ )}+ aria-hidden+ data-testid="task-chat-phase-summary-caret"+ />+ ) : null}</button>) : null}{open ? (- <div className="flex min-w-0 flex-col gap-2 pl-2" data-testid="task-chat-phase-children">- {item.items.map((child) => <div className="min-w-0" key={child.id}>{renderChild(child)}</div>)}+ <div+ className={cn("flex min-w-0 flex-col gap-2 pl-2", childrenClassName)}+ data-testid="task-chat-phase-children"+ >+ {showChildRail ? (+ <span+ className="absolute inset-y-1 left-0 w-px bg-border/70"+ aria-hidden+ data-testid="task-chat-phase-child-rail"+ />+ ) : null}+ {renderChildren+ ? renderChildren(item.items)+ : item.items.map((child) => (+ <div className="min-w-0" key={child.id}>+ {renderChild(child)}+ </div>+ ))}</div>) : null}</div>diff --git a/ui/src/components/task-chat/TaskChatBubble.test.tsx b/ui/src/components/task-chat/TaskChatBubble.test.tsxindex f5b6c6818a..58480c5a9f 100644--- a/ui/src/components/task-chat/TaskChatBubble.test.tsx+++ b/ui/src/components/task-chat/TaskChatBubble.test.tsx@@ -138,6 +138,40 @@ describe("TaskChatBubble agent page-surface treatment", () => {});});+describe("TaskChatBubble verification caveats", () => {+ it("renders non-blocking not-run verification beneath the durable agent reply", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);++ flushSync(() => root.render(+ <ThemeProvider>+ <TaskChatBubble item={{+ id: "agent-message",+ kind: "message",+ author: "agent",+ authorName: "Runner",+ text: "The implementation is complete.",+ verificationCaveats: [{+ commandOrCheck: "Run npm test",+ reasonCode: "tool_unavailable",+ detail: "Node and npm are unavailable in this environment.",+ }],+ }} />+ </ThemeProvider>,+ ));++ const caveat = container.querySelector('[data-testid="task-chat-verification-caveats"]');+ expect(caveat?.textContent).toContain("Verification caveat");+ expect(caveat?.textContent).toContain("Run npm test");+ expect(caveat?.textContent).toContain("tool unavailable");+ expect(caveat?.textContent).toContain("Node and npm are unavailable");++ flushSync(() => root.unmount());+ container.remove();+ });+});+describe("TaskChatBubble interstitial self-talk (PAP-357)", () => {let container: HTMLDivElement;let root: Root | null = null;diff --git a/ui/src/components/task-chat/TaskChatBubble.tsx b/ui/src/components/task-chat/TaskChatBubble.tsxindex 45268b7309..3d38a0ce0a 100644--- a/ui/src/components/task-chat/TaskChatBubble.tsx+++ b/ui/src/components/task-chat/TaskChatBubble.tsx@@ -1,7 +1,10 @@import { useState, type ReactNode } from "react";import { cn } from "@/lib/utils";import { MarkdownBody } from "@/components/MarkdownBody";-import { ImageGalleryModal, type GalleryMediaItem } from "@/components/ImageGalleryModal";+import {+ ImageGalleryModal,+ type GalleryMediaItem,+} from "@/components/ImageGalleryModal";import { Avatar, AvatarFallback } from "@/components/ui/avatar";import { AgentIcon } from "@/components/AgentIconPicker";import { CommentAttributionChip } from "@/components/CommentAttributionChip";@@ -14,12 +17,21 @@ import {AttachmentTitle,AttachmentTrigger,} from "@/components/ui/attachment";-import { extractAttachmentRefs, extractImageRefs, fileKindForName } from "./task-chat-attachments";+import {+ extractAttachmentRefs,+ extractImageRefs,+ fileKindForName,+} from "./task-chat-attachments";import { TaskChatSystemNotice } from "./TaskChatSystemNotice";import type { TaskChatMessageItem } from "./task-chat-model";interface TaskChatBubbleProps {item: TaskChatMessageItem;+ /** Requeues a blocked task after a no-live-execution-path recovery notice. */+ onTryAgainNoLiveExecutionPath?: () => Promise<void> | void;+ tryAgainNoLiveExecutionPathPending?: boolean;+ /** Disable the entrance animation when replacing an already-visible live response. */+ animateEntry?: boolean;/** Action shown beside the queued state for an interruptible message. */queuedAction?: ReactNode;/**@@ -29,6 +41,10 @@ interface TaskChatBubbleProps {* Supplied by TaskChatThreadView when `item.attachedTurn` is set.*/attachedTurn?: ReactNode;+ /** New-runner Worked header, rendered above the durable final response. */+ beforeTurn?: ReactNode;+ /** The durable runner turn already owns the shared agent identity row. */+ hideAgentIdentity?: boolean;/*** copy · 👍 · 👎 controls for an agent bubble's footer line (PAP-413).* Rendered here only for a runless reply (leading the bare timestamp); when@@ -46,6 +62,44 @@ function initialsForName(name: string) {return name.slice(0, 2).toUpperCase();}+export function TaskChatAgentIdentity({+ agentName,+ agentIcon,+ onBehalfOfUserName,+}: {+ agentName: string;+ agentIcon?: string | null;+ onBehalfOfUserName?: string;+}) {+ return (+ <span+ className="flex items-center gap-2 px-1"+ data-testid="task-chat-agent-identity"+ >+ <Avatar+ size="sm"+ className="shrink-0"+ data-testid="task-chat-agent-avatar"+ >+ {agentIcon ? (+ <AvatarFallback>+ <AgentIcon icon={agentIcon} className="h-3.5 w-3.5" />+ </AvatarFallback>+ ) : (+ <AvatarFallback>{initialsForName(agentName)}</AvatarFallback>+ )}+ </Avatar>+ <span className="text-sm font-semibold text-foreground">{agentName}</span>+ {onBehalfOfUserName ? (+ <CommentAttributionChip+ agentName={agentName}+ userName={onBehalfOfUserName}+ />+ ) : null}+ </span>+ );+}+/*** Author-typed message row — the primary legibility signal. Human messages sit* right in a solid accent bubble; agent messages sit directly on the page@@ -63,7 +117,17 @@ function galleryItemForImage(src: string, name?: string): GalleryMediaItem {};}-export function TaskChatBubble({ item, queuedAction, attachedTurn, actions }: TaskChatBubbleProps) {+export function TaskChatBubble({+ item,+ animateEntry = true,+ queuedAction,+ attachedTurn,+ beforeTurn,+ hideAgentIdentity = false,+ actions,+ onTryAgainNoLiveExecutionPath,+ tryAgainNoLiveExecutionPathPending,+}: TaskChatBubbleProps) {// Clicking an embedded image opens the full-screen lightbox (with download);// arrow keys walk across the other images in the same bubble.const [lightboxSrc, setLightboxSrc] = useState<string | null>(null);@@ -77,57 +141,66 @@ export function TaskChatBubble({ item, queuedAction, attachedTurn, actions }: Taif (item.author === "system") {// Collapsed humanized one-liner, expandable to the full detail (PAP-443).- return <TaskChatSystemNotice item={item} />;+ return (+ <TaskChatSystemNotice+ item={item}+ onTryAgainNoLiveExecutionPath={onTryAgainNoLiveExecutionPath}+ tryAgainNoLiveExecutionPathPending={tryAgainNoLiveExecutionPathPending}+ />+ );}const isHuman = item.author === "human";// Non-image file references ("[name](/api/attachments/…/content)") render as// attachment chips under the bubble; link-only lines leave the body text.- const { refs: attachmentRefs, text: bodyText } = extractAttachmentRefs(item.text);+ const { refs: attachmentRefs, text: bodyText } = extractAttachmentRefs(+ item.text,+ );const imageRefs = extractImageRefs(bodyText);const galleryItems: GalleryMediaItem[] =lightboxSrc !== null && !imageRefs.some((ref) => ref.url === lightboxSrc)- // A clicked image the extractor missed (e.g. inline HTML) still gets a- // single-item lightbox rather than nothing.- ? [galleryItemForImage(lightboxSrc)]+ ? // A clicked image the extractor missed (e.g. inline HTML) still gets a+ // single-item lightbox rather than nothing.+ [galleryItemForImage(lightboxSrc)]: imageRefs.map((ref) => galleryItemForImage(ref.url, ref.name));- const lightboxIndex = lightboxSrc === null- ? -1- : Math.max(0, galleryItems.findIndex((galleryItem) => galleryItem.contentPath === lightboxSrc));+ const lightboxIndex =+ lightboxSrc === null+ ? -1+ : Math.max(+ 0,+ galleryItems.findIndex(+ (galleryItem) => galleryItem.contentPath === lightboxSrc,+ ),+ );return (- <div className={cn("tc-enter-bubble flex w-full flex-col gap-1", isHuman ? "items-end" : "items-start")}>- {!isHuman && item.authorName ? (- <span className="flex items-center gap-2 px-1">- <Avatar size="sm" className="shrink-0" data-testid="task-chat-agent-avatar">- {item.agentIcon ? (- <AvatarFallback>- <AgentIcon icon={item.agentIcon} className="h-3.5 w-3.5" />- </AvatarFallback>- ) : (- <AvatarFallback>{initialsForName(item.authorName)}</AvatarFallback>- )}- </Avatar>- <span className="text-sm font-semibold text-foreground">{item.authorName}</span>- {item.onBehalfOfUserName ? (- <CommentAttributionChip- agentName={item.authorName}- userName={item.onBehalfOfUserName}- />- ) : null}- </span>+ <div+ className={cn(+ "flex w-full flex-col gap-1",+ animateEntry && "tc-enter-bubble",+ isHuman ? "items-end" : "items-start",+ )}+ >+ {beforeTurn ? <div className="w-full pb-1">{beforeTurn}</div> : null}+ {!isHuman && item.authorName && !hideAgentIdentity ? (+ <TaskChatAgentIdentity+ agentName={item.authorName}+ agentIcon={item.agentIcon}+ onBehalfOfUserName={item.onBehalfOfUserName}+ />) : null}{bodyText.length > 0 ? (<div// Stable hook so the TaskChatLab bubble-treatment explorations// (PAP-501) can scope background/border overrides to the agent// bubble body without touching the live thread.- data-testid={isHuman ? "task-chat-human-bubble" : "task-chat-agent-bubble"}+ data-testid={+ isHuman ? "task-chat-human-bubble" : "task-chat-agent-bubble"+ }className={cn("break-words py-2 text-sm",isHuman? "max-w-(--pct-85) rounded-2xl rounded-br-sm bg-(--liveness-blue) px-3.5 text-white": "w-full bg-transparent px-1 text-foreground",- item.optimistic ? "opacity-80" : null,)}><MarkdownBody@@ -155,13 +228,17 @@ export function TaskChatBubble({ item, queuedAction, attachedTurn, actions }: Taconst kind = fileKindForName(ref.name);const KindIcon = kind.icon;return (- <Attachment key={ref.url} size="sm" className={cn(item.optimistic && "opacity-80")}>+ <Attachment key={ref.url} size="sm"><AttachmentMedia><KindIcon aria-hidden /></AttachmentMedia><AttachmentContent>- <AttachmentTitle className="max-w-48">{ref.name}</AttachmentTitle>- <AttachmentDescription className="max-w-48">{kind.label}</AttachmentDescription>+ <AttachmentTitle className="max-w-48">+ {ref.name}+ </AttachmentTitle>+ <AttachmentDescription className="max-w-48">+ {kind.label}+ </AttachmentDescription></AttachmentContent><AttachmentTriggeraria-label={`Open ${ref.name}`}@@ -172,6 +249,31 @@ export function TaskChatBubble({ item, queuedAction, attachedTurn, actions }: Ta})}</AttachmentGroup>) : null}+ {!isHuman && item.verificationCaveats?.length ? (+ <div+ className="mx-1 w-(--sz-calc-7) rounded-md border border-amber-500/25 bg-amber-500/5 px-3 py-2 text-xs"+ data-testid="task-chat-verification-caveats"+ >+ <p className="font-medium text-amber-800 dark:text-amber-200">+ Verification caveat+ </p>+ <ul className="mt-1 space-y-1 text-muted-foreground">+ {item.verificationCaveats.map((caveat, index) => (+ <li key={`${caveat.commandOrCheck}:${index}`}>+ <span className="font-mono text-foreground">+ {caveat.commandOrCheck}+ </span>+ {caveat.reasonCode+ ? ` · ${caveat.reasonCode.replaceAll("_", " ")}`+ : ""}+ {caveat.detail ? (+ <span className="block">{caveat.detail}</span>+ ) : null}+ </li>+ ))}+ </ul>+ </div>+ ) : null}{item.optimistic ? (<span className="flex items-center gap-1 px-1 text-(length:--text-micro) text-muted-foreground"><span>{item.optimistic === "queued" ? "Queued" : "Sending…"}</span>@@ -183,7 +285,10 @@ export function TaskChatBubble({ item, queuedAction, attachedTurn, actions }: Ta// copy/👍/👎 actions (PAP-413) ride the turn's summary row via its// `leading` slot — not this wrapper — so they stay anchored to the// summary line when the tool history expands beneath it.- <div className="self-stretch" data-testid="task-chat-bubble-attached-turn">+ <div+ className="self-stretch"+ data-testid="task-chat-bubble-attached-turn"+ >{attachedTurn}</div>) : actions ? (diff --git a/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsx b/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsxnew file mode 100644index 0000000000..ca73136699--- /dev/null+++ b/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsx@@ -0,0 +1,2022 @@+import {+ useEffect,+ useMemo,+ useState,+ type ComponentProps,+ type ReactNode,+} from "react";+import {+ Check,+ CheckCircle2,+ ChevronDown,+ ChevronLeft,+ ChevronRight,+ Circle,+ CircleHelp,+ GitBranch,+ ListChecks,+ Loader2,+ MessageSquareQuote,+ Plug,+ Search,+ X,+} from "lucide-react";+import type { IssueDocument } from "@paperclipai/shared";+import type {+ PaperclipQuestionResponse,+ PaperclipQuestionSet,+} from "@paperclipai/adapter-utils";+import { IssueThreadInteractionCard } from "@/components/IssueThreadInteractionCard";+import { ConnectionIntentInteractionBody } from "@/features/connections/ConnectionIntentInteractionBody";+import { MarkdownBody } from "@/components/MarkdownBody";+import type { MentionOption } from "@/components/MarkdownEditor";+import { Button } from "@/components/ui/button";+import { Checkbox } from "@/components/ui/checkbox";+import { Textarea } from "@/components/ui/textarea";+import { Input } from "@/components/ui/input";+import { describeInteractionAudience } from "@/lib/interaction-audience";+import { interactionResolutionErrorMessage } from "@/lib/interaction-resolution-error";+import {+ clearDraft,+ loadStructuredDraft,+ saveStructuredDraft,+} from "@/lib/composer-draft";+import {+ buildIssueThreadInteractionSummary,+ buildSuggestedTaskTree,+ collectSuggestedTaskClientKeys,+ normalizeRequestConfirmationTargetHref,+ type AskUserQuestionsAnswer,+ type AskUserQuestionsInteraction,+ type IssueThreadInteraction,+ type RequestCheckboxConfirmationInteraction,+ type RequestConfirmationInteraction,+ type RequestItemVerdictsInteraction,+ type RequestItemVerdictValue,+ type SuggestTasksInteraction,+ type SuggestedTaskTreeNode,+} from "@/lib/issue-thread-interactions";+import { cn } from "@/lib/utils";+import { QuestionForm } from "./QuestionForm";+import {+ TaskChatComposerTakeoverControls,+ TaskChatComposerTakeoverHeader,+ useTaskChatComposerTakeoverActions,+} from "./TaskChatComposerTakeoverContext";+import { TaskChatPlanPreviewCard } from "./TaskChatPlanPreviewCard";+import { TaskChatRichInput } from "./TaskChatRichInput";++const TAKEOVER_TEXTAREA_CLASS =+ "min-h-16 resize-y border-0 bg-muted/35 text-sm shadow-none focus-visible:ring-0 focus-visible:ring-offset-0";++type SharedInteractionProps = Omit<+ ComponentProps<typeof IssueThreadInteractionCard>,+ "interaction" | "primaryActionOnRight"+>;++export interface TaskChatCompactInteractionCardProps extends SharedInteractionProps {+ interaction: IssueThreadInteraction;+ planDocument?: IssueDocument | null;+ showPlanPreview?: boolean;+ presentation?: "timeline" | "takeover";+ draftKey?: string;+ mentions?: MentionOption[];+}++const KIND_COPY = {+ suggest_tasks: {+ fallbackTitle: "Suggested tasks",+ label: "Tasks",+ icon: GitBranch,+ },+ ask_user_questions: {+ fallbackTitle: "Questions",+ label: "Questions",+ icon: CircleHelp,+ },+ request_confirmation: {+ fallbackTitle: "Confirmation",+ label: "Confirmation",+ icon: CheckCircle2,+ },+ request_checkbox_confirmation: {+ fallbackTitle: "Choose options",+ label: "Selection",+ icon: ListChecks,+ },+ request_item_verdicts: {+ fallbackTitle: "Review items",+ label: "Review",+ icon: MessageSquareQuote,+ },+ connection_intent: {+ fallbackTitle: "Connect service",+ label: "Connection",+ icon: Plug,+ },+} as const;++function statusLabel(status: IssueThreadInteraction["status"]): string {+ return status.replaceAll("_", " ");+}++function statusTone(status: IssueThreadInteraction["status"]): string {+ if (status === "pending") return "text-(--status-agent-running)";+ if (status === "accepted" || status === "answered")+ return "text-(--status-task-icon-done)";+ if (status === "rejected" || status === "failed") return "text-destructive";+ return "text-muted-foreground";+}++function StatusIcon({ status }: { status: IssueThreadInteraction["status"] }) {+ if (status === "pending") {+ return (+ <Circle+ aria-hidden+ className={cn("h-3.5 w-3.5 fill-current", statusTone(status))}+ />+ );+ }+ if (status === "accepted" || status === "answered") {+ return (+ <Check aria-hidden className={cn("h-3.5 w-3.5", statusTone(status))} />+ );+ }+ if (status === "rejected" || status === "failed") {+ return <X aria-hidden className={cn("h-3.5 w-3.5", statusTone(status))} />;+ }+ return (+ <Circle aria-hidden className={cn("h-3.5 w-3.5", statusTone(status))} />+ );+}++function InteractionShell({+ interaction,+ audienceLabel,+ presentation,+ children,+}: {+ interaction: IssueThreadInteraction;+ audienceLabel?: string | null;+ presentation: "timeline" | "takeover";+ children: ReactNode;+}) {+ const kind = KIND_COPY[interaction.kind];+ const Icon = kind.icon;+ const title = (+ <div className="flex min-w-0 items-center gap-2">+ <Icon aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />+ <strong className="min-w-0 truncate text-sm font-medium text-foreground">+ {interaction.title ?? kind.fallbackTitle}+ </strong>+ {interaction.kind === "request_confirmation" &&+ interaction.payload.target?.type === "issue_document" &&+ interaction.payload.target.key === "plan" ? (+ <CompactTarget interaction={interaction} />+ ) : null}+ {interaction.status !== "pending" ? (+ <span+ className="inline-flex shrink-0 items-center gap-1 text-xs capitalize text-muted-foreground"+ data-testid="interaction-status-badge"+ >+ <StatusIcon status={interaction.status} />+ {statusLabel(interaction.status)}+ </span>+ ) : null}+ </div>+ );+ return (+ <article+ className={cn(+ "overflow-hidden",+ presentation === "timeline" &&+ "rounded-md border border-border bg-card/60",+ )}+ >+ {presentation === "takeover" ? (+ <TaskChatComposerTakeoverHeader>{title}</TaskChatComposerTakeoverHeader>+ ) : (+ <header className="flex min-w-0 items-start gap-2 px-3 py-2.5">+ <div className="min-w-0 flex-1">+ {title}+ {audienceLabel ? (+ <p className="mt-0.5 pl-6 text-xs text-muted-foreground">+ {audienceLabel}+ </p>+ ) : null}+ </div>+ </header>+ )}+ <div+ className={+ presentation === "timeline"+ ? "border-t border-border/70 px-3 py-3"+ : undefined+ }+ >+ {children}+ </div>+ </article>+ );+}++function InteractionActionError({ message }: { message: string | null }) {+ return (+ <div aria-live="assertive" data-testid="interaction-action-error">+ {message ? (+ <div className="mt-2 rounded-sm border border-destructive/60 bg-destructive/10 px-2.5 py-2 text-sm text-destructive">+ {message}+ </div>+ ) : null}+ </div>+ );+}++function Details({ children }: { children?: ReactNode }) {+ if (!children) return null;+ return (+ <details className="mt-2">+ <summary className="flex cursor-pointer list-none items-center gap-1 text-xs font-medium text-muted-foreground">+ <ChevronDown aria-hidden className="h-3.5 w-3.5" /> Details+ </summary>+ <div className="mt-2 rounded-sm bg-muted/40 px-2.5 py-2 text-sm text-muted-foreground">+ {children}+ </div>+ </details>+ );+}++function ActionRow({+ children,+ hint,+}: {+ children: ReactNode;+ hint?: string | null;+}) {+ return (+ <div className="mt-3 flex flex-wrap items-center gap-2">+ {hint ? (+ <span className="mr-auto text-xs text-muted-foreground">{hint}</span>+ ) : (+ <span className="mr-auto" />+ )}+ {children}+ </div>+ );+}++function targetLabel(+ interaction:+ | RequestConfirmationInteraction+ | RequestCheckboxConfirmationInteraction+ | RequestItemVerdictsInteraction,+) {+ const target = interaction.payload.target;+ if (!target) return null;+ const label =+ target.label ??+ (target.type === "issue_document" ? target.key : target.key);+ const revision =+ target.revisionNumber == null ? null : `v${target.revisionNumber}`;+ return [label, revision].filter(Boolean).join(" · ");+}++function CompactTarget({+ interaction,+}: {+ interaction:+ | RequestConfirmationInteraction+ | RequestCheckboxConfirmationInteraction+ | RequestItemVerdictsInteraction;+}) {+ const target = interaction.payload.target;+ const label = targetLabel(interaction);+ if (!target || !label) return null;+ const href = target.href+ ? normalizeRequestConfirmationTargetHref(target.href)+ : null;+ if (href) {+ return (+ <a+ href={href}+ className="inline-flex rounded-sm border border-border px-2 py-0.5 font-mono text-xs text-foreground hover:bg-muted/60"+ >+ {label}+ </a>+ );+ }+ return (+ <span className="inline-flex rounded-sm border border-border px-2 py-0.5 font-mono text-xs text-muted-foreground">+ {label}+ </span>+ );+}++function PlanReviewPreview({+ interaction,+ planDocument,+}: {+ interaction: RequestConfirmationInteraction;+ planDocument?: IssueDocument | null;+}) {+ const target = interaction.payload.target;+ if (target?.type !== "issue_document" || target.key !== "plan") return null;++ const targetRevisionId = target.revisionId ?? null;+ const targetRevision = target.revisionNumber ?? null;+ const documentMatchesTarget = Boolean(+ planDocument &&+ (targetRevisionId != null+ ? planDocument.latestRevisionId === targetRevisionId+ : targetRevision == null ||+ planDocument.latestRevisionNumber === targetRevision),+ );++ return (+ <TaskChatPlanPreviewCard+ source={{+ kind: "saved",+ document: documentMatchesTarget ? planDocument : null,+ revision: targetRevision,+ fallbackTitle: target.label,+ }}+ href="#document-plan"+ testId="plan-review-preview"+ ariaLabel={`Open ${target.label ?? (targetRevision == null ? "plan" : `plan revision ${targetRevision}`)}`}+ />+ );+}++function receiptReason(interaction: IssueThreadInteraction): string | null {+ const result = interaction.result;+ if (!result) return null;+ if ("reason" in result && typeof result.reason === "string")+ return result.reason;+ if (interaction.kind === "ask_user_questions") {+ return (+ interaction.result?.cancellationReason ??+ interaction.result?.expirationReason?.replaceAll("_", " ") ??+ null+ );+ }+ return null;+}++function ReceiptDisclosure({+ interaction,+ externalReferences,+ compact = false,+}: {+ interaction: IssueThreadInteraction;+ externalReferences?: SharedInteractionProps["externalReferences"];+ compact?: boolean;+}) {+ const reason = receiptReason(interaction);+ const answerReason =+ reason ??+ (interaction.kind === "suggest_tasks"+ ? (interaction.result?.rejectionReason ?? null)+ : null);+ let request: ReactNode;++ if (interaction.kind === "ask_user_questions") {+ const questionSet = questionSetForInteraction(interaction);+ const response = questionResponseForInteraction(interaction, questionSet);+ request = (+ <div className="grid gap-3">+ {questionSet.description ? (+ <p className="text-sm text-muted-foreground">+ {questionSet.description}+ </p>+ ) : null}+ {questionSet.questions.map((question) => {+ const answer = response?.answers[question.id];+ const selected = (answer?.selectedOptionIds ?? []).map(+ (optionId) =>+ question.options?.find((option) => option.id === optionId)+ ?.label ?? optionId,+ );+ const values = [...selected, answer?.text, answer?.customText].filter(+ (value): value is string => Boolean(value),+ );+ return (+ <div key={question.id}>+ {question.header ? (+ <p className="text-xs font-medium text-muted-foreground">+ {question.header}+ </p>+ ) : null}+ <p className="text-sm text-foreground">{question.prompt}</p>+ {question.helpText ? (+ <p className="mt-0.5 text-xs text-muted-foreground">+ {question.helpText}+ </p>+ ) : null}+ <p className="mt-1 text-sm font-medium text-foreground">+ Answer: {values.length > 0 ? values.join(", ") : "No answer"}+ </p>+ </div>+ );+ })}+ </div>+ );+ } else if (interaction.kind === "request_checkbox_confirmation") {+ const selected = new Set(interaction.result?.selectedOptionIds ?? []);+ const selectedLabels = interaction.payload.options+ .filter((option) => selected.has(option.id))+ .map((option) => option.label);+ request = (+ <div>+ <p className="text-sm text-foreground">{interaction.payload.prompt}</p>+ {interaction.status === "accepted" ? (+ <p className="mt-1 text-sm font-medium text-foreground">+ Answer:{" "}+ {selectedLabels.length > 0+ ? selectedLabels.join(", ")+ : "No options selected"}+ </p>+ ) : null}+ {interaction.payload.detailsMarkdown ? (+ <div className="mt-2 text-sm">+ <MarkdownBody externalReferences={externalReferences}>+ {interaction.payload.detailsMarkdown}+ </MarkdownBody>+ </div>+ ) : null}+ </div>+ );+ } else if (interaction.kind === "request_item_verdicts") {+ const verdicts = new Map(+ (interaction.result?.items ?? []).map((item) => [item.id, item]),+ );+ const decidedItems = interaction.payload.items.filter((item) =>+ verdicts.has(item.id),+ );+ request = (+ <div>+ <p className="text-sm text-foreground">{interaction.payload.prompt}</p>+ {decidedItems.length > 0 ? (+ <ul className="mt-2 grid gap-1 text-sm">+ {decidedItems.map((item) => {+ const verdict = verdicts.get(item.id);+ return (+ <li key={item.id}>+ <span className="font-medium">{item.label}</span> ·{" "}+ {verdict?.verdict}+ {verdict?.reason ? ` — ${verdict.reason}` : ""}+ </li>+ );+ })}+ </ul>+ ) : (+ <p className="mt-1 text-sm font-medium text-foreground">+ No verdicts submitted+ </p>+ )}+ {interaction.payload.detailsMarkdown ? (+ <div className="mt-2 text-sm">+ <MarkdownBody externalReferences={externalReferences}>+ {interaction.payload.detailsMarkdown}+ </MarkdownBody>+ </div>+ ) : null}+ </div>+ );+ } else if (interaction.kind === "suggest_tasks") {+ const created = new Set(+ interaction.result?.createdTasks?.map((task) => task.clientKey) ?? [],+ );+ const createdTasks = interaction.payload.tasks.filter((task) =>+ created.has(task.clientKey),+ );+ request = (+ <div>+ {createdTasks.length > 0 ? (+ <ul className="grid gap-1 text-sm">+ {createdTasks.map((task) => (+ <li key={task.clientKey} className="font-medium">+ {task.title}+ </li>+ ))}+ </ul>+ ) : interaction.status === "accepted" ? (+ <p className="text-sm font-medium text-foreground">+ No tasks created+ </p>+ ) : null}+ </div>+ );+ } else if (interaction.kind === "connection_intent") {+ request = (+ <p className="text-sm text-foreground">+ {interaction.payload.requestingAgentName} requested access to{" "}+ {interaction.payload.serviceName}.+ </p>+ );+ } else {+ request = (+ <div className="grid gap-2">+ <p className="text-sm text-foreground">{interaction.payload.prompt}</p>+ {interaction.payload.detailsMarkdown ? (+ <div className="text-sm">+ <MarkdownBody externalReferences={externalReferences}>+ {interaction.payload.detailsMarkdown}+ </MarkdownBody>+ </div>+ ) : null}+ {interaction.payload.toolAction ? (+ <div className="rounded-sm bg-muted/45 px-3 py-2.5 text-sm">+ <p>+ <strong>{interaction.payload.toolAction.toolDisplayName}</strong>{" "}+ · {interaction.payload.toolAction.risk} risk+ </p>+ <p className="mt-1">+ Expires{" "}+ {new Date(+ interaction.payload.toolAction.expiresAt,+ ).toLocaleString()}+ </p>+ <div className="mt-2">+ <MarkdownBody externalReferences={externalReferences}>+ {interaction.payload.toolAction.previewMarkdown}+ </MarkdownBody>+ </div>+ <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs">+ {interaction.payload.toolAction.argumentsSummaryJson}+ </pre>+ <p className="mt-1 break-all font-mono text-xs text-muted-foreground">+ {interaction.payload.toolAction.argumentsHash}+ </p>+ </div>+ ) : null}+ {interaction.payload.secretProposal ? (+ <dl className="grid gap-1 rounded-sm bg-muted/45 px-3 py-2.5 text-sm">+ <div>+ <dt className="text-xs text-muted-foreground">Secret</dt>+ <dd>{interaction.payload.secretProposal.sourceSecretLabel}</dd>+ </div>+ <div>+ <dt className="text-xs text-muted-foreground">Binding</dt>+ <dd className="font-mono text-xs">+ {interaction.payload.secretProposal.configPath} →{" "}+ {interaction.payload.secretProposal.targetAgentName}+ </dd>+ </div>+ <div>+ <dt className="text-xs text-muted-foreground">Why</dt>+ <dd>{interaction.payload.secretProposal.justification}</dd>+ </div>+ <div>+ <dt className="text-xs text-muted-foreground">Expires</dt>+ <dd>+ {new Date(+ interaction.payload.secretProposal.expiresAt,+ ).toLocaleString()}+ </dd>+ </div>+ </dl>+ ) : null}+ </div>+ );+ }++ const detail = (+ <div+ className={+ compact+ ? "space-y-3 pb-3 pl-7 pr-1"+ : "mt-2 space-y-3 border-t border-border/60 pt-3"+ }+ >+ {request}+ {answerReason ? (+ <p className="text-sm text-muted-foreground">+ <span className="font-medium">Reason:</span> {answerReason}+ </p>+ ) : null}+ </div>+ );++ if (compact) {+ const Icon = KIND_COPY[interaction.kind].icon;+ const summary =+ interaction.kind === "ask_user_questions" &&+ interaction.status === "answered"+ ? "Questions answered"+ : buildIssueThreadInteractionSummary(interaction);+ return (+ <details+ className="group"+ data-testid={+ interaction.kind === "ask_user_questions" &&+ interaction.status === "answered"+ ? "task-chat-answered-questions-receipt"+ : "task-chat-interaction-receipt"+ }+ >+ <summary className="flex min-h-8 cursor-pointer list-none items-center gap-2 rounded-sm px-1 py-1.5 text-sm leading-5 text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <span+ className="flex w-6 shrink-0 items-center justify-center"+ data-testid="task-chat-interaction-receipt-icon-slot"+ >+ <Icon+ aria-hidden+ className="h-3.5 w-3.5 shrink-0 text-muted-foreground"+ data-testid="task-chat-interaction-receipt-icon"+ />+ </span>+ <span>{summary}</span>+ <ChevronRight+ aria-hidden+ className="ml-auto h-3 w-3 shrink-0 text-muted-foreground opacity-0 transition-[opacity,transform] group-hover:opacity-70 group-focus-visible:opacity-70 group-open:rotate-90"+ data-testid="task-chat-interaction-receipt-caret"+ />+ </summary>+ {detail}+ </details>+ );+ }++ return (+ <details className="mt-2">+ <summary className="cursor-pointer text-xs font-medium text-muted-foreground">+ View original request and resolution+ </summary>+ {detail}+ </details>+ );+}++function questionSetForInteraction(+ interaction: AskUserQuestionsInteraction,+): PaperclipQuestionSet {+ if (interaction.payload.questionSet) return interaction.payload.questionSet;+ return {+ schema: "paperclip.question_set.v1",+ ...(interaction.title ? { title: interaction.title } : {}),+ ...(interaction.payload.submitLabel+ ? { submitLabel: interaction.payload.submitLabel }+ : {}),+ questions: interaction.payload.questions.map((question) => {+ const freeText = question.options.find(+ (option) => option.freeText === true,+ );+ return {+ id: question.id,+ prompt: question.prompt,+ ...(question.helpText ? { helpText: question.helpText } : {}),+ required: question.required === true,+ answerMode:+ question.selectionMode === "multi"+ ? ("multi_select" as const)+ : ("single_select" as const),+ options: question.options+ .filter((option) => option.freeText !== true)+ .map((option) => ({+ id: option.id,+ label: option.label,+ ...(option.description ? { description: option.description } : {}),+ })),+ ...(freeText+ ? {+ customAnswer: {+ enabled: true as const,+ label: freeText.label,+ ...(freeText.description+ ? { placeholder: freeText.description }+ : {}),+ },+ }+ : {}),+ };+ }),+ };+}++function questionResponseForInteraction(+ interaction: AskUserQuestionsInteraction,+ questionSet: PaperclipQuestionSet,+): PaperclipQuestionResponse | null {+ if (!interaction.result?.answers) return null;+ return {+ schema: "paperclip.question_response.v1",+ answers: Object.fromEntries(+ interaction.result.answers.map((answer) => {+ const question = questionSet.questions.find(+ (candidate) => candidate.id === answer.questionId,+ );+ return [+ answer.questionId,+ question?.answerMode === "text"+ ? { ...(answer.otherText ? { text: answer.otherText } : {}) }+ : {+ selectedOptionIds: answer.optionIds,+ ...(answer.otherText ? { customText: answer.otherText } : {}),+ },+ ];+ }),+ ),+ };+}++function AskUserQuestionsCard({+ interaction,+ onSubmitInteractionAnswers,+ onCancelInteraction,+ errorMessage,+ draftKey,+ onUploadImage,+ mentions,+}: {+ interaction: AskUserQuestionsInteraction;+ onSubmitInteractionAnswers?: SharedInteractionProps["onSubmitInteractionAnswers"];+ onCancelInteraction?: SharedInteractionProps["onCancelInteraction"];+ errorMessage: (error: unknown) => string;+ draftKey?: string;+ onUploadImage?: SharedInteractionProps["onUploadImage"];+ mentions?: MentionOption[];+}) {+ const questionSet = questionSetForInteraction(interaction);+ const initialResponse = questionResponseForInteraction(+ interaction,+ questionSet,+ );+ return (+ <QuestionForm+ id={interaction.id}+ questionSet={questionSet}+ initialResponse={initialResponse}+ implicitCustomAnswer={interaction.payload.questionSet === undefined}+ draftKey={draftKey}+ disabled={!onSubmitInteractionAnswers}+ imageUploadHandler={onUploadImage}+ mentions={mentions}+ onSubmit={async (response) => {+ const answers: AskUserQuestionsAnswer[] = questionSet.questions.map(+ (question) => {+ const answer = response.answers[question.id];+ const otherText =+ question.answerMode === "text"+ ? answer?.text?.trim()+ : answer?.customText?.trim();+ return {+ questionId: question.id,+ optionIds:+ question.answerMode === "text"+ ? []+ : (answer?.selectedOptionIds ?? []),+ ...(otherText ? { otherText } : {}),+ };+ },+ );+ try {+ await onSubmitInteractionAnswers?.(interaction, answers);+ } catch (error) {+ throw new Error(errorMessage(error));+ }+ }}+ onCancel={+ onCancelInteraction+ ? async () => {+ try {+ await onCancelInteraction(interaction);+ } catch (error) {+ throw new Error(errorMessage(error));+ }+ }+ : undefined+ }+ />+ );+}++function ConfirmationCard({+ interaction,+ planDocument,+ onAcceptInteraction,+ onRejectInteraction,+ externalReferences,+ errorMessage,+ draftKey,+ showPlanPreview,+ onUploadImage,+ mentions,+}: {+ interaction: RequestConfirmationInteraction;+ planDocument?: IssueDocument | null;+ onAcceptInteraction?: SharedInteractionProps["onAcceptInteraction"];+ onRejectInteraction?: SharedInteractionProps["onRejectInteraction"];+ externalReferences?: SharedInteractionProps["externalReferences"];+ errorMessage: (error: unknown) => string;+ draftKey?: string;+ showPlanPreview: boolean;+ onUploadImage?: SharedInteractionProps["onUploadImage"];+ mentions?: MentionOption[];+}) {+ const [rejecting, setRejecting] = useState(false);+ const [reason, setReason] = useState(() =>+ draftKey ? loadStructuredDraft(draftKey, "") : "",+ );+ const [working, setWorking] = useState<"accept" | "reject" | null>(null);+ const [actionError, setActionError] = useState<string | null>(null);+ const [revisionUploading, setRevisionUploading] = useState(false);+ const collectsRejectReason = Boolean(+ interaction.payload.rejectRequiresReason ||+ interaction.payload.allowDeclineReason ||+ interaction.payload.declineReasonPlaceholder,+ );+ const isPlanConfirmation =+ interaction.payload.target?.type === "issue_document" &&+ interaction.payload.target.key === "plan";+ useEffect(() => {+ if (draftKey) saveStructuredDraft(draftKey, reason);+ }, [draftKey, reason]);+ async function resolve(action: "accept" | "reject") {+ if (+ action === "reject" &&+ interaction.payload.rejectRequiresReason &&+ !reason.trim()+ )+ return;+ setWorking(action);+ setActionError(null);+ try {+ if (action === "accept") await onAcceptInteraction?.(interaction);+ else await onRejectInteraction?.(interaction, reason.trim() || undefined);+ if (draftKey) clearDraft(draftKey);+ } catch (error) {+ setActionError(errorMessage(error));+ } finally {+ setWorking(null);+ }+ }++ return (+ <div>+ {isPlanConfirmation && showPlanPreview ? (+ <PlanReviewPreview+ interaction={interaction}+ planDocument={planDocument}+ />+ ) : isPlanConfirmation && rejecting ? null : (+ <div className="flex flex-wrap items-start justify-between gap-2">+ <p className="min-w-0 flex-1 text-sm leading-5 text-foreground">+ {isPlanConfirmation+ ? "Do you accept this plan?"+ : interaction.payload.prompt}+ </p>+ {!isPlanConfirmation ? (+ <CompactTarget interaction={interaction} />+ ) : null}+ </div>+ )}+ {!isPlanConfirmation && interaction.payload.detailsMarkdown ? (+ <Details>+ <MarkdownBody externalReferences={externalReferences}>+ {interaction.payload.detailsMarkdown}+ </MarkdownBody>+ </Details>+ ) : null}+ {interaction.payload.toolAction ? (+ <div className="mt-3 space-y-2 rounded-sm bg-muted/45 px-3 py-2.5 text-sm">+ <div className="flex flex-wrap items-center gap-2">+ <strong>{interaction.payload.toolAction.toolDisplayName}</strong>+ <span+ className={cn(+ "text-xs font-medium capitalize",+ interaction.payload.toolAction.risk === "destructive"+ ? "text-destructive"+ : "text-muted-foreground",+ )}+ >+ {interaction.payload.toolAction.risk} risk+ </span>+ <span className="ml-auto text-xs text-muted-foreground">+ Expires{" "}+ {new Date(+ interaction.payload.toolAction.expiresAt,+ ).toLocaleString()}+ </span>+ </div>+ <MarkdownBody externalReferences={externalReferences}>+ {interaction.payload.toolAction.previewMarkdown}+ </MarkdownBody>+ <details>+ <summary className="cursor-pointer text-xs font-medium text-muted-foreground">+ Arguments and audit hash+ </summary>+ <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs text-foreground">+ {interaction.payload.toolAction.argumentsSummaryJson}+ </pre>+ <p className="mt-1 break-all font-mono text-xs text-muted-foreground">+ {interaction.payload.toolAction.argumentsHash}+ </p>+ </details>+ </div>+ ) : null}+ {interaction.payload.secretProposal ? (+ <dl className="mt-3 grid gap-2 rounded-sm bg-muted/45 px-3 py-2.5 text-sm">+ <div>+ <dt className="text-xs text-muted-foreground">Secret</dt>+ <dd>{interaction.payload.secretProposal.sourceSecretLabel}</dd>+ </div>+ <div>+ <dt className="text-xs text-muted-foreground">Binding</dt>+ <dd className="font-mono text-xs">+ {interaction.payload.secretProposal.configPath} →{" "}+ {interaction.payload.secretProposal.targetAgentName}+ </dd>+ </div>+ <div>+ <dt className="text-xs text-muted-foreground">Why</dt>+ <dd>{interaction.payload.secretProposal.justification}</dd>+ </div>+ <div>+ <dt className="text-xs text-muted-foreground">Expires</dt>+ <dd>+ {new Date(+ interaction.payload.secretProposal.expiresAt,+ ).toLocaleString()}+ </dd>+ </div>+ </dl>+ ) : null}+ {rejecting ? (+ <div className={cn("space-y-2", !isPlanConfirmation && "mt-3")}>+ <p+ id={`${interaction.id}-reject-reason-label`}+ className="text-xs font-medium leading-4 text-foreground"+ >+ {interaction.payload.rejectReasonLabel ?? "What should change?"}+ {interaction.payload.rejectRequiresReason ? "" : " (optional)"}+ </p>+ {isPlanConfirmation ? (+ <TaskChatRichInput+ value={reason}+ onChange={setReason}+ placeholder={+ interaction.payload.declineReasonPlaceholder ??+ "Describe what should change"+ }+ imageUploadHandler={onUploadImage}+ mentions={mentions}+ disabled={working !== null}+ autoFocus+ onUploadingChange={setRevisionUploading}+ onSubmit={() => {+ if (!revisionUploading) void resolve("reject");+ }}+ ariaLabelledBy={`${interaction.id}-reject-reason-label`}+ testId="plan-revision-composer"+ attachAriaLabel="Attach image to revision"+ />+ ) : (+ <Textarea+ id={`${interaction.id}-reject-reason`}+ value={reason}+ onChange={(event) => setReason(event.target.value)}+ placeholder={+ interaction.payload.declineReasonPlaceholder ??+ "Add a short note"+ }+ className={TAKEOVER_TEXTAREA_CLASS}+ autoFocus+ />+ )}+ </div>+ ) : null}+ <InteractionActionError message={actionError} />+ <ActionRow>+ {rejecting ? (+ <>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ disabled={working !== null}+ onClick={() => {+ setRejecting(false);+ }}+ >+ Back+ </Button>+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={+ working !== null ||+ revisionUploading ||+ (Boolean(interaction.payload.rejectRequiresReason) &&+ !reason.trim()) ||+ !onRejectInteraction+ }+ onClick={() => void resolve("reject")}+ >+ {working === "reject" ? (+ <Loader2 aria-hidden className="h-4 w-4 animate-spin" />+ ) : null}+ {interaction.payload.rejectLabel ?? "Reject"}+ </Button>+ </>+ ) : (+ <>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ disabled={working !== null || !onRejectInteraction}+ onClick={() =>+ collectsRejectReason+ ? setRejecting(true)+ : void resolve("reject")+ }+ >+ {interaction.payload.rejectLabel ?? "Reject"}+ </Button>+ <Button+ type="button"+ size="sm"+ disabled={working !== null || !onAcceptInteraction}+ onClick={() => void resolve("accept")}+ >+ {working === "accept" ? (+ <Loader2 aria-hidden className="h-4 w-4 animate-spin" />+ ) : null}+ {interaction.payload.acceptLabel ?? "Approve"}+ </Button>+ </>+ )}+ </ActionRow>+ </div>+ );+}++function CheckboxConfirmationCard({+ interaction,+ onAcceptInteraction,+ onRejectInteraction,+ externalReferences,+ errorMessage,+ draftKey,+}: {+ interaction: RequestCheckboxConfirmationInteraction;+ onAcceptInteraction?: SharedInteractionProps["onAcceptInteraction"];+ onRejectInteraction?: SharedInteractionProps["onRejectInteraction"];+ externalReferences?: SharedInteractionProps["externalReferences"];+ errorMessage: (error: unknown) => string;+ draftKey?: string;+}) {+ const restored = draftKey+ ? loadStructuredDraft<{ selected: string[]; reason: string }>(draftKey, {+ selected: interaction.payload.defaultSelectedOptionIds ?? [],+ reason: "",+ })+ : null;+ const [selected, setSelected] = useState(+ () =>+ new Set(+ restored?.selected ??+ interaction.payload.defaultSelectedOptionIds ??+ [],+ ),+ );+ const [rejecting, setRejecting] = useState(false);+ const [reason, setReason] = useState(restored?.reason ?? "");+ const [filter, setFilter] = useState("");+ const [working, setWorking] = useState<"accept" | "reject" | null>(null);+ const [actionError, setActionError] = useState<string | null>(null);+ const collectsRejectReason = Boolean(+ interaction.payload.rejectRequiresReason ||+ interaction.payload.allowDeclineReason ||+ interaction.payload.declineReasonPlaceholder,+ );+ const minimum = interaction.payload.minSelected ?? 0;+ const maximum = interaction.payload.maxSelected ?? Number.POSITIVE_INFINITY;+ const validCount = selected.size >= minimum && selected.size <= maximum;+ const visibleOptions = interaction.payload.options.filter((option) => {+ const query = filter.trim().toLowerCase();+ return (+ !query ||+ option.label.toLowerCase().includes(query) ||+ option.description?.toLowerCase().includes(query)+ );+ });+ useEffect(() => {+ if (draftKey)+ saveStructuredDraft(draftKey, { selected: [...selected], reason });+ }, [draftKey, reason, selected]);++ function toggle(id: string) {+ setSelected((current) => {+ const next = new Set(current);+ if (next.has(id)) next.delete(id);+ else if (next.size < maximum) next.add(id);+ return next;+ });+ }++ async function resolve(action: "accept" | "reject") {+ if (action === "accept" && !validCount) return;+ if (+ action === "reject" &&+ interaction.payload.rejectRequiresReason &&+ !reason.trim()+ )+ return;+ setWorking(action);+ setActionError(null);+ try {+ if (action === "accept")+ await onAcceptInteraction?.(interaction, undefined, [...selected]);+ else await onRejectInteraction?.(interaction, reason.trim() || undefined);+ if (draftKey) clearDraft(draftKey);+ } catch (error) {+ setActionError(errorMessage(error));+ } finally {+ setWorking(null);+ }+ }++ const countHint =+ maximum < Number.POSITIVE_INFINITY+ ? `${selected.size} selected · choose ${minimum}–${maximum}`+ : minimum > 0+ ? `${selected.size} selected · at least ${minimum}`+ : `${selected.size} selected`;++ return (+ <div>+ <div className="flex flex-wrap items-start justify-between gap-2">+ <p className="min-w-0 flex-1 text-sm leading-5 text-foreground">+ {interaction.payload.prompt}+ </p>+ <CompactTarget interaction={interaction} />+ </div>+ <div+ className="mt-3 grid gap-1"+ role="group"+ aria-label={interaction.payload.prompt}+ >+ {interaction.payload.options.length > 10 ? (+ <label className="relative mb-1 block">+ <Search+ className="pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"+ aria-hidden+ />+ <Input+ value={filter}+ onChange={(event) => setFilter(event.target.value)}+ placeholder="Filter options"+ aria-label="Filter options"+ className="pl-8"+ />+ </label>+ ) : null}+ {visibleOptions.map((option) => (+ <label+ key={option.id}+ className="flex cursor-pointer items-start gap-2 rounded-sm px-2 py-1.5 hover:bg-muted/50"+ >+ <Checkbox+ checked={selected.has(option.id)}+ onCheckedChange={() => toggle(option.id)}+ className="mt-0.5"+ />+ <span className="min-w-0">+ <span className="block text-sm leading-5 text-foreground">+ {option.label}+ </span>+ {option.description ? (+ <span className="block text-xs leading-4 text-muted-foreground">+ {option.description}+ </span>+ ) : null}+ </span>+ </label>+ ))}+ </div>+ {interaction.payload.detailsMarkdown ? (+ <Details>+ <MarkdownBody externalReferences={externalReferences}>+ {interaction.payload.detailsMarkdown}+ </MarkdownBody>+ </Details>+ ) : null}+ {rejecting ? (+ <div className="mt-3 space-y-1.5">+ <label+ htmlFor={`${interaction.id}-reject-reason`}+ className="text-xs font-medium text-foreground"+ >+ {interaction.payload.rejectReasonLabel ?? "What should change?"}+ {interaction.payload.rejectRequiresReason ? "" : " (optional)"}+ </label>+ <Textarea+ id={`${interaction.id}-reject-reason`}+ value={reason}+ onChange={(event) => setReason(event.target.value)}+ placeholder={+ interaction.payload.declineReasonPlaceholder ?? "Add a short note"+ }+ className={TAKEOVER_TEXTAREA_CLASS}+ autoFocus+ />+ </div>+ ) : null}+ <InteractionActionError message={actionError} />+ <ActionRow hint={countHint}>+ {rejecting ? (+ <>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ disabled={working !== null}+ onClick={() => setRejecting(false)}+ >+ Back+ </Button>+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={+ working !== null ||+ (Boolean(interaction.payload.rejectRequiresReason) &&+ !reason.trim()) ||+ !onRejectInteraction+ }+ onClick={() => void resolve("reject")}+ >+ {working === "reject" ? (+ <Loader2 aria-hidden className="h-4 w-4 animate-spin" />+ ) : null}+ {interaction.payload.rejectLabel ?? "Decline"}+ </Button>+ </>+ ) : (+ <>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ disabled={working !== null || !onRejectInteraction}+ onClick={() =>+ collectsRejectReason+ ? setRejecting(true)+ : void resolve("reject")+ }+ >+ {interaction.payload.rejectLabel ?? "Decline"}+ </Button>+ <Button+ type="button"+ size="sm"+ disabled={working !== null || !validCount || !onAcceptInteraction}+ onClick={() => void resolve("accept")}+ >+ {working === "accept" ? (+ <Loader2 aria-hidden className="h-4 w-4 animate-spin" />+ ) : null}+ {interaction.payload.acceptLabel ?? "Confirm selection"}+ </Button>+ </>+ )}+ </ActionRow>+ </div>+ );+}++function SuggestedTaskRow({+ node,+ selected,+ onToggle,+}: {+ node: SuggestedTaskTreeNode;+ selected: Set<string>;+ onToggle: (node: SuggestedTaskTreeNode) => void;+}) {+ if (node.task.hiddenInPreview) return null;+ const hiddenCount = collectSuggestedTaskClientKeys(node).filter(+ (key) =>+ key !== node.task.clientKey &&+ node.children.some(+ (child) => child.task.clientKey === key && child.task.hiddenInPreview,+ ),+ ).length;+ return (+ <li>+ <label className="flex cursor-pointer items-start gap-2 rounded-sm px-2 py-1.5 hover:bg-muted/50">+ <Checkbox+ checked={selected.has(node.task.clientKey)}+ onCheckedChange={() => onToggle(node)}+ className="mt-0.5"+ />+ <span className="min-w-0 flex-1">+ <span className="block text-sm leading-5 text-foreground">+ {node.task.title}+ </span>+ {hiddenCount > 0 ? (+ <span className="block text-xs text-muted-foreground">+ + {hiddenCount} hidden follow-up+ </span>+ ) : null}+ </span>+ </label>+ {node.children.length > 0 ? (+ <ul className="ml-4 border-l border-border/80 pl-2">+ {node.children.map((child) => (+ <SuggestedTaskRow+ key={child.task.clientKey}+ node={child}+ selected={selected}+ onToggle={onToggle}+ />+ ))}+ </ul>+ ) : null}+ </li>+ );+}++function SuggestedTasksCard({+ interaction,+ onAcceptInteraction,+ onRejectInteraction,+ errorMessage,+ draftKey,+}: {+ interaction: SuggestTasksInteraction;+ onAcceptInteraction?: SharedInteractionProps["onAcceptInteraction"];+ onRejectInteraction?: SharedInteractionProps["onRejectInteraction"];+ errorMessage: (error: unknown) => string;+ draftKey?: string;+}) {+ const roots = useMemo(+ () => buildSuggestedTaskTree(interaction.payload.tasks),+ [interaction.payload.tasks],+ );+ const taskByKey = useMemo(+ () =>+ new Map(interaction.payload.tasks.map((task) => [task.clientKey, task])),+ [interaction.payload.tasks],+ );+ const restored = draftKey+ ? loadStructuredDraft<{ selected: string[]; reason: string }>(draftKey, {+ selected: interaction.payload.tasks.map((task) => task.clientKey),+ reason: "",+ })+ : null;+ const [selected, setSelected] = useState(+ () =>+ new Set(+ restored?.selected ??+ interaction.payload.tasks.map((task) => task.clientKey),+ ),+ );+ const [rejecting, setRejecting] = useState(false);+ const [reason, setReason] = useState(restored?.reason ?? "");+ const [filter, setFilter] = useState("");+ const [working, setWorking] = useState<"accept" | "reject" | null>(null);+ const [actionError, setActionError] = useState<string | null>(null);+ useEffect(() => {+ if (draftKey)+ saveStructuredDraft(draftKey, { selected: [...selected], reason });+ }, [draftKey, reason, selected]);+ const visibleRoots = useMemo(() => {+ const query = filter.trim().toLowerCase();+ if (!query) return roots;+ function retain(node: SuggestedTaskTreeNode): SuggestedTaskTreeNode | null {+ const children = node.children+ .map(retain)+ .filter((child): child is SuggestedTaskTreeNode => child !== null);+ const matches =+ node.task.title.toLowerCase().includes(query) ||+ node.task.description?.toLowerCase().includes(query);+ return matches || children.length > 0 ? { ...node, children } : null;+ }+ return roots+ .map(retain)+ .filter((node): node is SuggestedTaskTreeNode => node !== null);+ }, [filter, roots]);++ function toggle(node: SuggestedTaskTreeNode) {+ setSelected((current) => {+ const next = new Set(current);+ const subtree = collectSuggestedTaskClientKeys(node);+ if (next.has(node.task.clientKey))+ subtree.forEach((key) => next.delete(key));+ else {+ subtree.forEach((key) => next.add(key));+ let parentKey = node.task.parentClientKey;+ while (parentKey) {+ next.add(parentKey);+ parentKey = taskByKey.get(parentKey)?.parentClientKey;+ }+ }+ return next;+ });+ }++ async function resolve(action: "accept" | "reject") {+ setWorking(action);+ setActionError(null);+ try {+ if (action === "accept")+ await onAcceptInteraction?.(interaction, [...selected]);+ else await onRejectInteraction?.(interaction, reason.trim() || undefined);+ if (draftKey) clearDraft(draftKey);+ } catch (error) {+ setActionError(errorMessage(error));+ } finally {+ setWorking(null);+ }+ }++ return (+ <div>+ <p className="text-sm leading-5 text-foreground">+ Select the tasks to create.+ </p>+ {interaction.payload.tasks.length > 10 ? (+ <label className="relative mt-3 block">+ <Search+ className="pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"+ aria-hidden+ />+ <Input+ value={filter}+ onChange={(event) => setFilter(event.target.value)}+ placeholder="Filter suggested tasks"+ aria-label="Filter suggested tasks"+ className="pl-8"+ />+ </label>+ ) : null}+ <ul+ className="mt-2 max-h-(--sz-28dvh) overflow-y-auto scrollbar-auto-hide"+ aria-label="Suggested tasks"+ >+ {visibleRoots.map((node) => (+ <SuggestedTaskRow+ key={node.task.clientKey}+ node={node}+ selected={selected}+ onToggle={toggle}+ />+ ))}+ </ul>+ {rejecting ? (+ <div className="mt-3 space-y-1.5">+ <label+ htmlFor={`${interaction.id}-reject-reason`}+ className="text-xs font-medium text-foreground"+ >+ Why should these tasks change? (optional)+ </label>+ <Textarea+ id={`${interaction.id}-reject-reason`}+ value={reason}+ onChange={(event) => setReason(event.target.value)}+ placeholder="Add a short note"+ className={TAKEOVER_TEXTAREA_CLASS}+ autoFocus+ />+ </div>+ ) : null}+ <InteractionActionError message={actionError} />+ <ActionRow+ hint={`${selected.size} of ${interaction.payload.tasks.length} selected`}+ >+ {rejecting ? (+ <>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ disabled={working !== null}+ onClick={() => setRejecting(false)}+ >+ Back+ </Button>+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={working !== null || !onRejectInteraction}+ onClick={() => void resolve("reject")}+ >+ {working === "reject" ? (+ <Loader2 aria-hidden className="h-4 w-4 animate-spin" />+ ) : null}+ Send back+ </Button>+ </>+ ) : (+ <>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ disabled={working !== null || !onRejectInteraction}+ onClick={() => setRejecting(true)}+ >+ Revise+ </Button>+ <Button+ type="button"+ size="sm"+ disabled={+ working !== null || selected.size === 0 || !onAcceptInteraction+ }+ onClick={() => void resolve("accept")}+ >+ {working === "accept" ? (+ <Loader2 aria-hidden className="h-4 w-4 animate-spin" />+ ) : null}+ Create selected+ </Button>+ </>+ )}+ </ActionRow>+ </div>+ );+}++type VerdictDraft = {+ verdict: RequestItemVerdictValue;+ reason: string;+ confirmed?: boolean;+};++function ItemVerdictsCard({+ interaction,+ onSubmitInteractionVerdicts,+ externalReferences,+ errorMessage,+ draftKey,+}: {+ interaction: RequestItemVerdictsInteraction;+ onSubmitInteractionVerdicts?: SharedInteractionProps["onSubmitInteractionVerdicts"];+ externalReferences?: SharedInteractionProps["externalReferences"];+ errorMessage: (error: unknown) => string;+ draftKey?: string;+}) {+ const takeoverActions = useTaskChatComposerTakeoverActions();+ const items = interaction.payload.items;+ const resolvedById = useMemo(+ () =>+ new Map((interaction.result?.items ?? []).map((item) => [item.id, item])),+ [interaction.result],+ );+ const firstPendingIndex = Math.max(+ items.findIndex((item) => !resolvedById.has(item.id)),+ 0,+ );+ const restored = draftKey+ ? loadStructuredDraft<{+ page: number;+ drafts: Array<[string, VerdictDraft]>;+ }>(draftKey, { page: firstPendingIndex, drafts: [] })+ : null;+ const [page, setPage] = useState(restored?.page ?? firstPendingIndex);+ const [drafts, setDrafts] = useState<Map<string, VerdictDraft>>(+ () => new Map(restored?.drafts ?? []),+ );+ const [working, setWorking] = useState(false);+ const [actionError, setActionError] = useState<string | null>(null);+ const enabledVerdicts = interaction.payload.verdicts ?? ["approve", "reject"];+ const requireReasonOn = new Set(+ interaction.payload.requireReasonOn ?? ["reject"],+ );++ useEffect(+ () =>+ setPage((current) => Math.min(current, Math.max(items.length - 1, 0))),+ [items.length],+ );+ useEffect(() => {+ setDrafts((current) => {+ const next = new Map(current);+ let changed = false;+ for (const id of resolvedById.keys()) {+ if (next.delete(id)) changed = true;+ }+ return changed ? next : current;+ });+ const nextPending = items.findIndex(+ (candidate) => !resolvedById.has(candidate.id),+ );+ if (nextPending >= 0) setPage(nextPending);+ }, [items, resolvedById]);+ useEffect(() => {+ if (draftKey) saveStructuredDraft(draftKey, { page, drafts: [...drafts] });+ }, [draftKey, drafts, page]);+ const item = items[page];+ if (!item)+ return (+ <p className="text-sm text-muted-foreground">+ No review items were provided.+ </p>+ );+ const resolved = resolvedById.get(item.id);+ const draft = drafts.get(item.id);+ const itemHref = item.href+ ? normalizeRequestConfirmationTargetHref(item.href)+ : null;+ const rejectionNeedsConfirmation = Boolean(+ !resolved &&+ draft &&+ requireReasonOn.has(draft.verdict) &&+ (!draft.reason.trim() || draft.confirmed === false),+ );++ function advance() {+ setPage((current) => Math.min(current + 1, items.length - 1));+ }++ function setVerdict(verdict: RequestItemVerdictValue) {+ setDrafts((current) => {+ const next = new Map(current);+ const existing = next.get(item.id);+ next.set(item.id, {+ verdict,+ reason: existing?.verdict === verdict ? existing.reason : "",+ confirmed: !requireReasonOn.has(verdict),+ });+ return next;+ });+ if (!requireReasonOn.has(verdict)) advance();+ }++ function setReason(reason: string) {+ setDrafts((current) => {+ const next = new Map(current);+ const existing = next.get(item.id);+ if (existing)+ next.set(item.id, { ...existing, reason, confirmed: false });+ return next;+ });+ }++ function confirmRejectionReason() {+ if (!draft?.reason.trim()) return;+ setDrafts((current) => {+ const next = new Map(current);+ const existing = next.get(item.id);+ if (existing) next.set(item.id, { ...existing, confirmed: true });+ return next;+ });+ advance();+ }++ async function submit() {+ if (!onSubmitInteractionVerdicts) return;+ const verdicts = [...drafts].map(([id, value]) => ({+ id,+ verdict: value.verdict,+ ...(value.reason.trim() ? { reason: value.reason.trim() } : {}),+ }));+ if (+ verdicts.length === 0 ||+ verdicts.some(+ (entry) => requireReasonOn.has(entry.verdict) && !entry.reason,+ )+ )+ return;+ setWorking(true);+ setActionError(null);+ try {+ await onSubmitInteractionVerdicts(interaction, verdicts);+ if (draftKey) clearDraft(draftKey);+ } catch (error) {+ setActionError(errorMessage(error));+ } finally {+ setWorking(false);+ }+ }++ const allDraftsValid =+ drafts.size > 0 &&+ [...drafts.values()].every(+ (candidate) =>+ !requireReasonOn.has(candidate.verdict) ||+ Boolean(candidate.reason.trim() && candidate.confirmed !== false),+ );++ return (+ <div>+ <div className="mb-2 flex items-center text-xs text-muted-foreground">+ <span>{drafts.size + resolvedById.size} decided</span>+ <TaskChatComposerTakeoverControls>+ <nav+ className="flex shrink-0 items-center gap-1"+ aria-label="Item pagination"+ >+ <Button+ type="button"+ size="icon-xs"+ variant="ghost"+ aria-label="Previous item"+ disabled={working || page === 0}+ onClick={() => setPage((current) => current - 1)}+ >+ <ChevronLeft aria-hidden />+ </Button>+ <span className="min-w-10 text-center tabular-nums">+ {page + 1} of {items.length}+ </span>+ <Button+ type="button"+ size="icon-xs"+ variant="ghost"+ aria-label="Next item"+ disabled={+ working ||+ page === items.length - 1 ||+ rejectionNeedsConfirmation+ }+ onClick={() => setPage((current) => current + 1)}+ >+ <ChevronRight aria-hidden />+ </Button>+ </nav>+ </TaskChatComposerTakeoverControls>+ </div>+ <div className="flex flex-wrap items-start justify-between gap-2">+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium leading-5 text-foreground">+ {item.label}+ </p>+ {item.description ? (+ <p className="text-xs leading-4 text-muted-foreground">+ {item.description}+ </p>+ ) : null}+ </div>+ {itemHref ? (+ <a+ href={itemHref}+ className="text-xs font-medium text-primary hover:underline"+ >+ Open+ </a>+ ) : null}+ </div>+ {item.previewMarkdown ? (+ <div className="mt-2 rounded-sm bg-muted/40 px-2.5 py-2 text-xs">+ <MarkdownBody externalReferences={externalReferences}>+ {item.previewMarkdown}+ </MarkdownBody>+ </div>+ ) : null}+ {resolved ? (+ <p className="mt-3 inline-flex rounded-sm border border-border px-2 py-1 text-xs capitalize text-muted-foreground">+ {resolved.verdict}+ {resolved.reason ? ` · ${resolved.reason}` : ""}+ </p>+ ) : (+ <div+ className="mt-3 flex flex-wrap gap-1.5"+ role="group"+ aria-label={`Verdict for ${item.label}`}+ >+ {enabledVerdicts.map((verdict) => (+ <Button+ key={verdict}+ type="button"+ size="sm"+ variant="outline"+ aria-pressed={draft?.verdict === verdict}+ onClick={() => setVerdict(verdict)}+ className={cn(+ "min-w-24 justify-center capitalize",+ verdict === "approve" &&+ (draft?.verdict === verdict+ ? "border-emerald-500/60 bg-emerald-500/15 text-emerald-700 hover:bg-emerald-500/20 dark:text-emerald-300"+ : "border-emerald-500/35 text-emerald-700 hover:bg-emerald-500/10 dark:text-emerald-300"),+ verdict === "reject" &&+ (draft?.verdict === verdict+ ? "border-destructive/60 bg-destructive/15 text-destructive hover:bg-destructive/20"+ : "border-destructive/35 text-destructive hover:bg-destructive/10"),+ )}+ >+ {verdict === "approve" ? (+ <Check aria-hidden className="h-4 w-4" />+ ) : null}+ {verdict === "reject" ? (+ <X aria-hidden className="h-4 w-4" />+ ) : null}+ {verdict}+ </Button>+ ))}+ </div>+ )}+ {!resolved && draft && requireReasonOn.has(draft.verdict) ? (+ <div className="mt-2 space-y-1.5">+ <label+ htmlFor={`${interaction.id}-${item.id}-reason`}+ className="text-xs font-medium text-foreground"+ >+ {interaction.payload.reasonLabel ?? "Reason"}+ </label>+ <Textarea+ id={`${interaction.id}-${item.id}-reason`}+ value={draft.reason}+ onChange={(event) => setReason(event.target.value)}+ placeholder="Add a short reason"+ className={TAKEOVER_TEXTAREA_CLASS}+ autoFocus+ />+ <div className="flex justify-end">+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={!draft.reason.trim() || working}+ onClick={confirmRejectionReason}+ >+ Submit rejection reason+ </Button>+ </div>+ </div>+ ) : null}+ {interaction.payload.detailsMarkdown ? (+ <Details>+ <MarkdownBody externalReferences={externalReferences}>+ {interaction.payload.detailsMarkdown}+ </MarkdownBody>+ </Details>+ ) : null}+ <InteractionActionError message={actionError} />+ <ActionRow>+ {takeoverActions?.skipButton}+ <Button+ type="button"+ size="sm"+ disabled={!allDraftsValid || working || !onSubmitInteractionVerdicts}+ onClick={() => void submit()}+ >+ {working ? (+ <Loader2 aria-hidden className="h-4 w-4 animate-spin" />+ ) : null}+ {drafts.size > 0 ? `Apply ${drafts.size}` : "Apply decisions"}+ </Button>+ </ActionRow>+ </div>+ );+}++export function TaskChatCompactInteractionCard({+ interaction,+ planDocument,+ showPlanPreview = true,+ agentMap,+ currentUserId,+ userLabelMap,+ onAcceptInteraction,+ onRejectInteraction,+ onSubmitInteractionAnswers,+ onCancelInteraction,+ onSubmitInteractionVerdicts,+ onUploadImage,+ externalReferences,+ presentation = "timeline",+ draftKey,+ mentions,+}: TaskChatCompactInteractionCardProps) {+ const creatorLabel = interaction.createdByAgentId+ ? agentMap?.get(interaction.createdByAgentId)?.name+ : interaction.createdByUserId+ ? interaction.createdByUserId === currentUserId+ ? "You"+ : userLabelMap?.get(interaction.createdByUserId)+ : null;+ const addresseeLabel = interaction.addresseeAgentId+ ? agentMap?.get(interaction.addresseeAgentId)?.name+ : interaction.addresseeUserId+ ? interaction.addresseeUserId === currentUserId+ ? "You"+ : (userLabelMap?.get(interaction.addresseeUserId) ??+ interaction.addresseeUserId)+ : null;+ const audience = describeInteractionAudience({+ interaction,+ creatorLabel,+ addresseeLabel,+ });+ const errorMessage = (error: unknown) =>+ interactionResolutionErrorMessage(error, audience);+ const audienceLabel =+ interaction.status === "pending" && !audience.isOpen+ ? audience.shortSummary+ : null;+ const isResolvedPlanReview =+ showPlanPreview &&+ interaction.status !== "pending" &&+ interaction.kind === "request_confirmation" &&+ interaction.payload.target?.type === "issue_document" &&+ interaction.payload.target.key === "plan";++ if (interaction.kind === "connection_intent") {+ return (+ <InteractionShell+ interaction={interaction}+ audienceLabel={audienceLabel}+ presentation={presentation}+ >+ <ConnectionIntentInteractionBody+ interaction={interaction}+ currentUserId={currentUserId}+ addresseeLabel={addresseeLabel ?? "the addressed user"}+ />+ </InteractionShell>+ );+ }++ if (presentation === "timeline" && interaction.status !== "pending") {+ return (+ <>+ {isResolvedPlanReview ? (+ <div className="mb-2">+ <PlanReviewPreview+ interaction={interaction}+ planDocument={planDocument}+ />+ </div>+ ) : null}+ <ReceiptDisclosure+ interaction={interaction}+ externalReferences={externalReferences}+ compact+ />+ </>+ );+ }++ return (+ <InteractionShell+ interaction={interaction}+ audienceLabel={audienceLabel}+ presentation={presentation}+ >+ {interaction.status !== "pending" ? (+ <ReceiptDisclosure+ interaction={interaction}+ externalReferences={externalReferences}+ />+ ) : interaction.kind === "ask_user_questions" ? (+ <AskUserQuestionsCard+ interaction={interaction}+ onSubmitInteractionAnswers={onSubmitInteractionAnswers}+ onCancelInteraction={+ presentation === "timeline" ? onCancelInteraction : undefined+ }+ errorMessage={errorMessage}+ draftKey={draftKey}+ onUploadImage={onUploadImage}+ mentions={mentions}+ />+ ) : interaction.kind === "request_confirmation" ? (+ <ConfirmationCard+ interaction={interaction}+ planDocument={planDocument}+ onAcceptInteraction={onAcceptInteraction}+ onRejectInteraction={onRejectInteraction}+ externalReferences={externalReferences}+ errorMessage={errorMessage}+ draftKey={draftKey}+ showPlanPreview={showPlanPreview && presentation === "timeline"}+ onUploadImage={onUploadImage}+ mentions={mentions}+ />+ ) : interaction.kind === "request_checkbox_confirmation" ? (+ <CheckboxConfirmationCard+ interaction={interaction}+ onAcceptInteraction={onAcceptInteraction}+ onRejectInteraction={onRejectInteraction}+ externalReferences={externalReferences}+ errorMessage={errorMessage}+ draftKey={draftKey}+ />+ ) : interaction.kind === "suggest_tasks" ? (+ <SuggestedTasksCard+ interaction={interaction}+ onAcceptInteraction={onAcceptInteraction}+ onRejectInteraction={onRejectInteraction}+ errorMessage={errorMessage}+ draftKey={draftKey}+ />+ ) : (+ <ItemVerdictsCard+ interaction={interaction}+ onSubmitInteractionVerdicts={onSubmitInteractionVerdicts}+ externalReferences={externalReferences}+ errorMessage={errorMessage}+ draftKey={draftKey}+ />+ )}+ </InteractionShell>+ );+}diff --git a/ui/src/components/task-chat/TaskChatComposer.test.tsx b/ui/src/components/task-chat/TaskChatComposer.test.tsxindex e904a8c45a..653dd16a82 100644--- a/ui/src/components/task-chat/TaskChatComposer.test.tsx+++ b/ui/src/components/task-chat/TaskChatComposer.test.tsx@@ -1,11 +1,15 @@// @vitest-environment jsdom-import { StrictMode, type ReactElement } from "react";+import { StrictMode, useState, type ReactElement } from "react";import { flushSync } from "react-dom";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { buildAgentMentionHref, buildSkillMentionHref } from "@paperclipai/shared";+import {+ buildAgentMentionHref,+ buildSkillMentionHref,+} from "@paperclipai/shared";import { TaskChatComposer } from "./TaskChatComposer";+import { QuestionForm } from "./QuestionForm";import { DRAFT_DEBOUNCE_MS } from "../../lib/composer-draft";/**@@ -16,13 +20,18 @@ import { DRAFT_DEBOUNCE_MS } from "../../lib/composer-draft";* so the inline upload handler can be exercised directly.*/const mdxEditorMockState = vi.hoisted(() => ({- imagePluginOptions: null as { imageUploadHandler?: (file: File) => Promise<string> } | null,+ imagePluginOptions: null as {+ imageUploadHandler?: (file: File) => Promise<string>;+ } | null,}));vi.mock("@mdxeditor/editor", async () => {const React = await import("react");- function setForwardedRef<T>(ref: React.ForwardedRef<T | null>, value: T | null) {+ function setForwardedRef<T>(+ ref: React.ForwardedRef<T | null>,+ value: T | null,+ ) {if (typeof ref === "function") {ref(value);return;@@ -57,22 +66,27 @@ vi.mock("@mdxeditor/editor", async () => {const onChangeRef = React.useRef(onChange);onChangeRef.current = onChange;- const handle = React.useMemo<MockHandle>(() => ({- setMarkdown: (value: string) => {- contentRef.current = value;- if (editableRef.current) editableRef.current.textContent = value;- },- insertMarkdown: (value: string) => {- const next = contentRef.current ? `${contentRef.current}${value}` : value;- contentRef.current = next;- if (editableRef.current) editableRef.current.textContent = next;- onChangeRef.current?.(next);- },- focus: (callback?: () => void) => {- editableRef.current?.focus();- callback?.();- },- }), []);+ const handle = React.useMemo<MockHandle>(+ () => ({+ setMarkdown: (value: string) => {+ contentRef.current = value;+ if (editableRef.current) editableRef.current.textContent = value;+ },+ insertMarkdown: (value: string) => {+ const next = contentRef.current+ ? `${contentRef.current}${value}`+ : value;+ contentRef.current = next;+ if (editableRef.current) editableRef.current.textContent = next;+ onChangeRef.current?.(next);+ },+ focus: (callback?: () => void) => {+ editableRef.current?.focus();+ callback?.();+ },+ }),+ [],+ );React.useEffect(() => {if (editableRef.current && contentRef.current) {@@ -105,7 +119,9 @@ vi.mock("@mdxeditor/editor", async () => {codeMirrorPlugin: () => ({}),createRootEditorSubscription$: Symbol("createRootEditorSubscription$"),headingsPlugin: () => ({}),- imagePlugin: (options: { imageUploadHandler?: (file: File) => Promise<string> }) => {+ imagePlugin: (options: {+ imageUploadHandler?: (file: File) => Promise<string>;+ }) => {mdxEditorMockState.imagePluginOptions = options;return {};},@@ -161,7 +177,14 @@ beforeEach(() => {// jsdom ranges have zero-size rects; the mention menu measures the caret.originalRangeRect = Range.prototype.getBoundingClientRect;Range.prototype.getBoundingClientRect = () => ({- x: 32, y: 24, width: 12, height: 18, top: 24, right: 44, bottom: 42, left: 32,+ x: 32,+ y: 24,+ width: 12,+ height: 18,+ top: 24,+ right: 44,+ bottom: 42,+ left: 32,toJSON: () => ({}),});});@@ -187,7 +210,9 @@ function editable() {}function sendButton() {- return container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-send"]')!;+ return container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-composer-send"]',+ )!;}/** Simulate typing: set the contenteditable's text and fire an input event. */@@ -205,14 +230,21 @@ function pressKey() {flushSync(() => {editable().dispatchEvent(- new KeyboardEvent("keydown", { key, ...modifiers, bubbles: true, cancelable: true }),+ new KeyboardEvent("keydown", {+ key,+ ...modifiers,+ bubbles: true,+ cancelable: true,+ }),);});}function pasteFiles(files: File[]) {const paste = new Event("paste", { bubbles: true, cancelable: true });- Object.defineProperty(paste, "clipboardData", { value: { files, types: ["Files"] } });+ Object.defineProperty(paste, "clipboardData", {+ value: { files, types: ["Files"] },+ });flushSync(() => {editable().dispatchEvent(paste);});@@ -238,10 +270,13 @@ async function placeCaretAtEnd() {}function autocompleteOption(matchText: string) {- const menu = document.body.querySelector('[data-testid="mention-autocomplete-menu"]');+ const menu = document.body.querySelector(+ '[data-testid="mention-autocomplete-menu"]',+ );expect(menu).toBeTruthy();- const option = Array.from(menu!.querySelectorAll<HTMLButtonElement>('button[type="button"]'))- .find((node) => node.textContent?.includes(matchText));+ const option = Array.from(+ menu!.querySelectorAll<HTMLButtonElement>('button[type="button"]'),+ ).find((node) => node.textContent?.includes(matchText));expect(option).toBeTruthy();return option!;}@@ -250,18 +285,50 @@ describe("TaskChatComposer", () => {it("adds 10px to the composer's original 8px interior padding", () => {render(<TaskChatComposer onAdd={async () => {}} workMode="standard" />);- const composer = container- .querySelector('[data-testid="task-chat-composer-input"]')- ?.parentElement;+ const composer = container.querySelector(+ '[data-testid="task-chat-composer-input"]',+ )?.parentElement;expect(composer?.className).toContain("p-(--sz-18px)");expect(composer?.className).not.toContain("p-2");});+ it("renders the composer shell and its selectors without outlines", () => {+ render(+ <TaskChatComposer+ onAdd={async () => {}}+ workMode="planning"+ onWorkModeChange={async () => {}}+ enableReassign+ currentAssigneeValue="agent:runner"+ reassignOptions={[{ id: "agent:runner", label: "Runner" }]}+ />,+ );++ const composer = container.firstElementChild as HTMLElement;+ const mode = container.querySelector<HTMLElement>(+ '[data-testid="task-chat-composer-mode"]',+ )!;+ const runner = container.querySelector<HTMLElement>(+ '[data-testid="task-chat-composer-assignee"]',+ )!;++ expect(composer.classList).not.toContain("border");+ expect(composer.className).not.toContain("shadow-");+ expect(composer.className).not.toContain("focus-within:ring-");+ expect(mode.classList).not.toContain("border");+ expect(mode.className).not.toContain("ring-");+ expect(runner.classList).toContain("border-0");+ expect(runner.classList).not.toContain("border");+ expect(runner.className).not.toContain("ring-2");+ });+it("scopes the wrapping placeholder override to the task-chat composer", () => {render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" />);- expect(container.firstElementChild?.classList).toContain("paperclip-task-chat-composer");+ expect(container.firstElementChild?.classList).toContain(+ "paperclip-task-chat-composer",+ );});it("reserves enough mobile editor height for a wrapped two-line placeholder", () => {@@ -314,10 +381,16 @@ describe("TaskChatComposer", () => {const onAdd = vi.fn().mockResolvedValue(undefined);const onWorkModeChange = vi.fn().mockResolvedValue(undefined);render(- <TaskChatComposer onAdd={onAdd} workMode="standard" onWorkModeChange={onWorkModeChange} />,+ <TaskChatComposer+ onAdd={onAdd}+ workMode="standard"+ onWorkModeChange={onWorkModeChange}+ />,);- const chip = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-mode"]')!;+ const chip = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-composer-mode"]',+ )!;expect(chip.getAttribute("data-pending-work-mode")).toBe("standard");expect(chip.textContent).toContain("Auto");@@ -353,7 +426,9 @@ describe("TaskChatComposer", () => {it("hides the attach button without an upload handler and shows it with one", () => {render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" />);- expect(container.querySelector('[data-testid="task-chat-composer-attach"]')).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-composer-attach"]'),+ ).toBeNull();render(<TaskChatComposer@@ -362,7 +437,9 @@ describe("TaskChatComposer", () => {onAttachImage={vi.fn().mockResolvedValue(undefined)}/>,);- expect(container.querySelector('[data-testid="task-chat-composer-attach"]')).not.toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-composer-attach"]'),+ ).not.toBeNull();});it("wires the editor's inline image upload to onAttachImage and returns the attachment URL", async () => {@@ -370,7 +447,13 @@ describe("TaskChatComposer", () => {contentPath: "/attachments/shot.png",originalFilename: "shot.png",});- render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" onAttachImage={onAttachImage} />);+ render(+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ onAttachImage={onAttachImage}+ />,+ );const handler = mdxEditorMockState.imagePluginOptions?.imageUploadHandler;expect(handler).toBeTypeOf("function");@@ -379,7 +462,9 @@ describe("TaskChatComposer", () => {await expect(handler!(file)).resolves.toBe("/attachments/shot.png");expect(onAttachImage).toHaveBeenCalledWith(file);// Inline images do not go through the attachment chip row.- expect(container.querySelector('[data-testid="task-chat-composer-attachments"]')).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-composer-attachments"]'),+ ).toBeNull();});it("does not register the image plugin without an upload handler", () => {@@ -393,7 +478,13 @@ describe("TaskChatComposer", () => {contentPath: "/attachments/notes.txt",originalFilename: "notes.txt",});- render(<TaskChatComposer onAdd={onAdd} workMode="standard" onAttachImage={onAttachImage} />);+ render(+ <TaskChatComposer+ onAdd={onAdd}+ workMode="standard"+ onAttachImage={onAttachImage}+ />,+ );const file = new File(["plain"], "notes.txt", { type: "text/plain" });const paste = pasteFiles([file]);@@ -402,16 +493,24 @@ describe("TaskChatComposer", () => {// The all-non-image paste is swallowed before the editor sees it.expect(paste.defaultPrevented).toBe(true);expect(onAttachImage).toHaveBeenCalledWith(file);- const chips = container.querySelector('[data-testid="task-chat-composer-attachments"]');+ const chips = container.querySelector(+ '[data-testid="task-chat-composer-attachments"]',+ );expect(chips?.textContent).toContain("notes.txt");// base/attachment chip: kind · size description and a settled state.expect(chips?.textContent).toContain("Text · 5 B");- expect(chips?.querySelector('[data-slot="attachment"]')?.getAttribute("data-state")).toBe("done");+ expect(+ chips+ ?.querySelector('[data-slot="attachment"]')+ ?.getAttribute("data-state"),+ ).toBe("done");// The editor stays prose-only; the reference rides along at submit time,// and an attached chip alone is enough to enable send.expect(editable().textContent ?? "").not.toContain("notes.txt");- const send = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-send"]')!;+ const send = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-composer-send"]',+ )!;expect(send.disabled).toBe(false);flushSync(() => send.click());await flushAsync();@@ -421,7 +520,9 @@ describe("TaskChatComposer", () => {undefined,);// Chips clear once the message posts.- expect(container.querySelector('[data-testid="task-chat-composer-attachments"]')).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-composer-attachments"]'),+ ).toBeNull();});it("appends file references after typed prose on submit", async () => {@@ -430,13 +531,21 @@ describe("TaskChatComposer", () => {contentPath: "/attachments/notes.txt",originalFilename: "notes.txt",});- render(<TaskChatComposer onAdd={onAdd} workMode="standard" onAttachImage={onAttachImage} />);+ render(+ <TaskChatComposer+ onAdd={onAdd}+ workMode="standard"+ onAttachImage={onAttachImage}+ />,+ );typeText("Please review this.");pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);await flushAsync();- const send = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-send"]')!;+ const send = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-composer-send"]',+ )!;flushSync(() => send.click());await flushAsync();expect(onAdd).toHaveBeenCalledWith(@@ -448,13 +557,24 @@ describe("TaskChatComposer", () => {it("blocks send while a file upload is pending, then includes the file once it lands", async () => {const onAdd = vi.fn().mockResolvedValue(undefined);- let resolveUpload!: (value: { contentPath: string; originalFilename: string }) => void;+ let resolveUpload!: (value: {+ contentPath: string;+ originalFilename: string;+ }) => void;const onAttachImage = vi.fn().mockReturnValue(- new Promise<{ contentPath: string; originalFilename: string }>((resolve) => {- resolveUpload = resolve;- }),+ new Promise<{ contentPath: string; originalFilename: string }>(+ (resolve) => {+ resolveUpload = resolve;+ },+ ),+ );+ render(+ <TaskChatComposer+ onAdd={onAdd}+ workMode="standard"+ onAttachImage={onAttachImage}+ />,);- render(<TaskChatComposer onAdd={onAdd} workMode="standard" onAttachImage={onAttachImage} />);typeText("Here is the file.");pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);@@ -467,7 +587,10 @@ describe("TaskChatComposer", () => {await flushAsync();expect(onAdd).not.toHaveBeenCalled();- resolveUpload({ contentPath: "/attachments/notes.txt", originalFilename: "notes.txt" });+ resolveUpload({+ contentPath: "/attachments/notes.txt",+ originalFilename: "notes.txt",+ });await flushAsync();expect(sendButton().disabled).toBe(false);flushSync(() => sendButton().click());@@ -482,7 +605,13 @@ describe("TaskChatComposer", () => {it("blocks send while a failed attachment chip remains, then sends after it is removed", async () => {const onAdd = vi.fn().mockResolvedValue(undefined);const onAttachImage = vi.fn().mockRejectedValue(new Error("Too large"));- render(<TaskChatComposer onAdd={onAdd} workMode="standard" onAttachImage={onAttachImage} />);+ render(+ <TaskChatComposer+ onAdd={onAdd}+ workMode="standard"+ onAttachImage={onAttachImage}+ />,+ );typeText("Here is the file.");pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);@@ -495,12 +624,18 @@ describe("TaskChatComposer", () => {await flushAsync();expect(onAdd).not.toHaveBeenCalled();- const remove = container.querySelector<HTMLButtonElement>('button[aria-label="Remove notes.txt"]');+ const remove = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Remove notes.txt"]',+ );flushSync(() => remove!.click());expect(sendButton().disabled).toBe(false);flushSync(() => sendButton().click());await flushAsync();- expect(onAdd).toHaveBeenCalledWith("Here is the file.", undefined, undefined);+ expect(onAdd).toHaveBeenCalledWith(+ "Here is the file.",+ undefined,+ undefined,+ );});it("removes an attachment chip via its remove button", async () => {@@ -508,26 +643,48 @@ describe("TaskChatComposer", () => {contentPath: "/attachments/notes.txt",originalFilename: "notes.txt",});- render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" onAttachImage={onAttachImage} />);+ render(+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ onAttachImage={onAttachImage}+ />,+ );pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);await flushAsync();- const remove = container.querySelector<HTMLButtonElement>('button[aria-label="Remove notes.txt"]');+ const remove = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Remove notes.txt"]',+ );expect(remove).not.toBeNull();flushSync(() => remove!.click());- expect(container.querySelector('[data-testid="task-chat-composer-attachments"]')).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-composer-attachments"]'),+ ).toBeNull();});it("shows an error-state chip when a non-image upload fails", async () => {const onAttachImage = vi.fn().mockRejectedValue(new Error("Too large"));- render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" onAttachImage={onAttachImage} />);+ render(+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ onAttachImage={onAttachImage}+ />,+ );pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);await flushAsync();- const chips = container.querySelector('[data-testid="task-chat-composer-attachments"]');- expect(chips?.querySelector('[data-slot="attachment"]')?.getAttribute("data-state")).toBe("error");+ const chips = container.querySelector(+ '[data-testid="task-chat-composer-attachments"]',+ );+ expect(+ chips+ ?.querySelector('[data-slot="attachment"]')+ ?.getAttribute("data-state"),+ ).toBe("error");expect(chips?.textContent).toContain("Too large");});@@ -536,7 +693,13 @@ describe("TaskChatComposer", () => {contentPath: "/attachments/notes.txt",originalFilename: "notes.txt",});- render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" onAttachImage={onAttachImage} />);+ render(+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ onAttachImage={onAttachImage}+ />,+ );const image = new File(["png-bytes"], "shot.png", { type: "image/png" });const text = new File(["plain"], "notes.txt", { type: "text/plain" });@@ -545,7 +708,9 @@ describe("TaskChatComposer", () => {// Mixed paste: the non-image is chipped, the image flows through untouched.expect(paste.defaultPrevented).toBe(false);- const chips = container.querySelector('[data-testid="task-chat-composer-attachments"]')!;+ const chips = container.querySelector(+ '[data-testid="task-chat-composer-attachments"]',+ )!;expect(chips.textContent).toContain("notes.txt");expect(chips.textContent).not.toContain("shot.png");expect(onAttachImage).toHaveBeenCalledTimes(1);@@ -558,7 +723,9 @@ describe("TaskChatComposer", () => {<TaskChatComposeronAdd={onAdd}workMode="standard"- mentions={[{ id: "agent:a1", kind: "agent", name: "Clippy", agentId: "a1" }]}+ mentions={[+ { id: "agent:a1", kind: "agent", name: "Clippy", agentId: "a1" },+ ]}/>,);@@ -567,7 +734,9 @@ describe("TaskChatComposer", () => {const option = autocompleteOption("Clippy");flushSync(() => {- option.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));+ option.dispatchEvent(+ new MouseEvent("mousedown", { bubbles: true, cancelable: true }),+ );});await flushAsync();@@ -588,7 +757,9 @@ describe("TaskChatComposer", () => {const option = autocompleteOption("/deploy");flushSync(() => {- option.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));+ option.dispatchEvent(+ new MouseEvent("mousedown", { bubbles: true, cancelable: true }),+ );});await flushAsync();@@ -597,7 +768,9 @@ describe("TaskChatComposer", () => {it("shows the assignee combobox only when reassign is enabled, with the current label", () => {render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" />);- expect(container.querySelector('[data-testid="task-chat-composer-assignee"]')).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-composer-assignee"]'),+ ).toBeNull();render(<TaskChatComposer@@ -611,17 +784,112 @@ describe("TaskChatComposer", () => {currentAssigneeValue="user:u1"/>,);- const trigger = container.querySelector('[data-testid="task-chat-composer-assignee"]');+ const trigger = container.querySelector(+ '[data-testid="task-chat-composer-assignee"]',+ );expect(trigger?.textContent).toContain("Sam");});+ it("shows configured agent icons in the assignee trigger and dropdown options", async () => {+ render(+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ enableReassign+ reassignOptions={[+ { id: "agent:a1", label: "Clippy" },+ { id: "agent:a2", label: "Plain Agent" },+ ]}+ agentMap={+ new Map([+ ["a1", { icon: "rocket" }],+ ["a2", { icon: null }],+ ])+ }+ currentAssigneeValue="agent:a1"+ />,+ );++ const trigger = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-composer-assignee"]',+ )!;+ expect(+ trigger.querySelector('[data-assignee-trigger-icon="rocket"]'),+ ).not.toBeNull();++ flushSync(() => {+ trigger.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushAsync();++ expect(+ document.querySelector('[data-assignee-option-icon="agent:a1"]'),+ ).not.toBeNull();+ expect(+ document.querySelector('[data-assignee-option-icon="agent:a2"]'),+ ).not.toBeNull();+ expect(+ document+ .querySelector('[data-assignee-identity="agent:a2"]')+ ?.getAttribute("data-assignee-option-icon"),+ ).toBe("agent:a2");+ });++ it("shows human avatars in assignee options and after selection", async () => {+ render(+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ enableReassign+ reassignOptions={[+ { id: "agent:a1", label: "Clippy" },+ { id: "user:u1", label: "Sam Rivera" },+ ]}+ agentMap={new Map([["a1", { icon: "rocket" }]])}+ userProfileMap={+ new Map([["u1", { label: "Sam Rivera", image: "/sam-avatar.png" }]])+ }+ currentAssigneeValue="agent:a1"+ />,+ );++ const trigger = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-composer-assignee"]',+ )!;+ flushSync(() => {+ trigger.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushAsync();++ const userOptionAvatar = document.querySelector(+ '[data-assignee-option-avatar="user:u1"]',+ );+ expect(userOptionAvatar).not.toBeNull();+ const userOption = userOptionAvatar?.closest("button");+ flushSync(() => {+ userOption?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushAsync();++ expect(trigger.textContent).toContain("Sam Rivera");+ expect(+ trigger.querySelector('[data-assignee-trigger-avatar="u1"]'),+ ).not.toBeNull();+ });+describe("draft persistence", () => {const draftKey = "task-chat-draft:issue-1";it("restores a saved draft on mount", () => {localStorage.setItem(draftKey, "unsent draft");- render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" draftKey={draftKey} />);+ render(+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ draftKey={draftKey}+ />,+ );expect(editable().textContent).toBe("unsent draft");expect(sendButton().disabled).toBe(false);@@ -632,7 +900,11 @@ describe("TaskChatComposer", () => {render(<StrictMode>- <TaskChatComposer onAdd={vi.fn()} workMode="standard" draftKey={draftKey} />+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ draftKey={draftKey}+ /></StrictMode>,);@@ -643,7 +915,13 @@ describe("TaskChatComposer", () => {it("saves after the debounce and flushes a pending value on unmount", () => {vi.useFakeTimers();try {- render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" draftKey={draftKey} />);+ render(+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ draftKey={draftKey}+ />,+ );typeText("work in progress");expect(localStorage.getItem(draftKey)).toBeNull();@@ -662,7 +940,13 @@ describe("TaskChatComposer", () => {it("flushes a pending value before page unload", () => {vi.useFakeTimers();try {- render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" draftKey={draftKey} />);+ render(+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ draftKey={draftKey}+ />,+ );typeText("save before reload");window.dispatchEvent(new Event("beforeunload"));@@ -676,22 +960,40 @@ describe("TaskChatComposer", () => {it("clears the composer and saved draft while the send is pending", async () => {localStorage.setItem(draftKey, "queued message");const onAdd = vi.fn().mockReturnValue(new Promise<void>(() => {}));- render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={draftKey} />);+ render(+ <TaskChatComposer+ onAdd={onAdd}+ workMode="standard"+ draftKey={draftKey}+ />,+ );pressKey("Enter", { metaKey: true });await flushAsync();- expect(onAdd).toHaveBeenCalledWith("queued message", undefined, undefined);+ expect(onAdd).toHaveBeenCalledWith(+ "queued message",+ undefined,+ undefined,+ );expect(editable().textContent).toBe("");expect(localStorage.getItem(draftKey)).toBeNull();});it("keeps text entered while an earlier send is pending", async () => {let resolveSend!: () => void;- const onAdd = vi.fn().mockReturnValue(new Promise<void>((resolve) => {- resolveSend = resolve;- }));- render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={draftKey} />);+ const onAdd = vi.fn().mockReturnValue(+ new Promise<void>((resolve) => {+ resolveSend = resolve;+ }),+ );+ render(+ <TaskChatComposer+ onAdd={onAdd}+ workMode="standard"+ draftKey={draftKey}+ />,+ );typeText("first message");pressKey("Enter", { metaKey: true });@@ -708,9 +1010,11 @@ describe("TaskChatComposer", () => {it("keeps an attachment added while an earlier send is pending", async () => {let resolveSend!: () => void;- const onAdd = vi.fn().mockReturnValue(new Promise<void>((resolve) => {- resolveSend = resolve;- }));+ const onAdd = vi.fn().mockReturnValue(+ new Promise<void>((resolve) => {+ resolveSend = resolve;+ }),+ );const onAttachImage = vi.fn().mockResolvedValue({contentPath: "/attachments/next.txt",originalFilename: "next.txt",@@ -734,18 +1038,29 @@ describe("TaskChatComposer", () => {await flushAsync();expect(onAdd).toHaveBeenCalledWith("first message", undefined, undefined);- expect(container.querySelector('[data-testid="task-chat-composer-attachments"]')?.textContent)- .toContain("next.txt");+ expect(+ container.querySelector(+ '[data-testid="task-chat-composer-attachments"]',+ )?.textContent,+ ).toContain("next.txt");});it("restores a failed send before text entered while it was pending", async () => {vi.useFakeTimers();try {let rejectSend!: (error: Error) => void;- const onAdd = vi.fn().mockReturnValue(new Promise<void>((_resolve, reject) => {- rejectSend = reject;- }));- render(<TaskChatComposer onAdd={onAdd} workMode="standard" draftKey={draftKey} />);+ const onAdd = vi.fn().mockReturnValue(+ new Promise<void>((_resolve, reject) => {+ rejectSend = reject;+ }),+ );+ render(+ <TaskChatComposer+ onAdd={onAdd}+ workMode="standard"+ draftKey={draftKey}+ />,+ );typeText("do not lose this");vi.advanceTimersByTime(DRAFT_DEBOUNCE_MS);vi.useRealTimers();@@ -761,10 +1076,390 @@ describe("TaskChatComposer", () => {await flushAsync();expect(editable().textContent).toBe("do not lose this\n\nnext draft");- expect(localStorage.getItem(draftKey)).toBe("do not lose this\n\nnext draft");+ expect(localStorage.getItem(draftKey)).toBe(+ "do not lose this\n\nnext draft",+ );} finally {vi.useRealTimers();}});});++ describe("queued message editing", () => {+ const draftKey = "task-chat-draft:queued-edit";++ function Harness({+ onSave,+ stale = false,+ }: {+ onSave: (commentId: string, body: string) => Promise<void>;+ stale?: boolean;+ }) {+ const [queuedEdit, setQueuedEdit] = useState<{+ commentId: string;+ body: string;+ stale?: boolean;+ } | null>({+ commentId: "queued-1",+ body: "Complete queued markdown",+ stale,+ });+ return (+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ draftKey={draftKey}+ queuedEdit={queuedEdit}+ onSaveQueuedEdit={onSave}+ onCancelQueuedEdit={() => setQueuedEdit(null)}+ />+ );+ }++ it("restores the existing composer draft after cancelling an edit", async () => {+ localStorage.setItem(draftKey, "Unsent normal draft");+ render(<Harness onSave={vi.fn().mockResolvedValue(undefined)} />);+ await flushAsync();+ await vi.waitFor(() => {+ expect(editable().textContent).toBe("Complete queued markdown");+ });+ expect(localStorage.getItem(draftKey)).toBe("Unsent normal draft");++ const cancel = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.trim() === "Cancel",+ );+ flushSync(() => cancel?.click());+ await flushAsync();++ expect(editable().textContent).toBe("Unsent normal draft");+ expect(localStorage.getItem(draftKey)).toBe("Unsent normal draft");+ });++ it("saves through the queue callback without posting a new comment", async () => {+ localStorage.setItem(draftKey, "Normal draft stays here");+ const onSave = vi.fn().mockResolvedValue(undefined);+ render(<Harness onSave={onSave} />);+ await flushAsync();+ typeText("Edited queued markdown");++ pressKey("Enter", { metaKey: true });+ await flushAsync();+ await flushAsync();++ expect(onSave).toHaveBeenCalledWith("queued-1", "Edited queued markdown");+ expect(editable().textContent).toBe("Normal draft stays here");+ });++ it("retains edited text when the queue target rejects the save", async () => {+ const onSave = vi+ .fn()+ .mockRejectedValue(new Error("queued_comment_stale_target"));+ render(<Harness onSave={onSave} />);+ await flushAsync();+ typeText("Keep this replacement text");++ pressKey("Enter", { metaKey: true });+ await flushAsync();++ await vi.waitFor(() => {+ expect(editable().textContent).toBe("Keep this replacement text");+ expect(container.textContent).toContain("Editing queued message");+ });+ });++ it("offers a stale edit as a new queued message and preserves its Markdown source", async () => {+ const onSave = vi.fn().mockResolvedValue(undefined);+ render(<Harness onSave={onSave} stale />);+ await flushAsync();++ typeText(" replacement with trailing Markdown ");+ expect(container.textContent).toContain("Queued message changed");+ expect(sendButton().getAttribute("aria-label")).toBe(+ "Queue as new message",+ );+ pressKey("Enter", { metaKey: true });+ await flushAsync();+ await flushAsync();++ expect(onSave).toHaveBeenCalledWith(+ "queued-1",+ " replacement with trailing Markdown ",+ );+ });+ });++ describe("composer takeovers", () => {+ it("replaces the editor with one action surface and exposes Skip", async () => {+ const onSkip = vi.fn().mockResolvedValue(undefined);+ render(+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ takeover={{+ id: "question-1",+ label: "Deployment target",+ pendingCount: 2,+ content: <p>Which environment should receive this?</p>,+ onDismiss: vi.fn(),+ onSkip,+ onShowNext: vi.fn(),+ }}+ />,+ );++ expect(+ container.querySelector('[data-testid="task-chat-composer-takeover"]')+ ?.textContent,+ ).toContain("Which environment should receive this?");+ expect(container.querySelector('[data-testid="mdx-editor"]')).toBeNull();+ expect(container.textContent).not.toContain("Input needed");+ expect(container.textContent).not.toContain("Write instead");+ const skip = Array.from(+ container.querySelectorAll<HTMLButtonElement>("button"),+ ).find((button) => button.textContent?.trim() === "Skip");+ flushSync(() => skip?.click());+ await flushAsync();+ expect(onSkip).toHaveBeenCalledTimes(1);+ });++ it("restores the exact ordinary draft after Skip", async () => {+ const draftKey = "task-composer-takeover-draft";+ localStorage.setItem(draftKey, "Preserved draft with **markdown**");++ function Harness() {+ const [open, setOpen] = useState(true);+ return (+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="planning"+ draftKey={draftKey}+ takeover={+ open+ ? {+ id: "plan-review",+ label: "Review plan",+ pendingCount: 1,+ content: <p>Do you accept this plan?</p>,+ onDismiss: () => setOpen(false),+ onSkip: () => setOpen(false),+ }+ : null+ }+ />+ );+ }++ render(<Harness />);+ const skip = Array.from(+ container.querySelectorAll<HTMLButtonElement>("button"),+ ).find((button) => button.textContent?.trim() === "Skip");+ flushSync(() => skip?.click());+ await flushAsync();++ expect(editable().textContent).toBe("Preserved draft with **markdown**");+ expect(container.textContent).not.toContain("Write instead");+ });++ it("keeps title, pending count, pagination, and dismiss on one header row", () => {+ render(+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ takeover={{+ id: "paged-questions",+ label: "Release decisions",+ pendingCount: 2,+ inlineSkip: true,+ content: (+ <QuestionForm+ id="release-decisions"+ questionSet={{+ schema: "paperclip.question_set.v1",+ questions: [+ {+ id: "scope",+ prompt: "Where should this ship?",+ required: false,+ answerMode: "single_select",+ options: [{ id: "pilot", label: "Pilot" }],+ },+ {+ id: "checks",+ prompt: "Which checks matter?",+ required: false,+ answerMode: "multi_select",+ options: [{ id: "a11y", label: "Accessibility" }],+ },+ ],+ }}+ onSubmit={vi.fn()}+ />+ ),+ onDismiss: vi.fn(),+ onSkip: vi.fn(),+ onShowNext: vi.fn(),+ }}+ />,+ );++ const header = container.querySelector(+ '[data-testid="task-chat-composer-takeover-header"]',+ );+ expect(header?.textContent).toContain("Release decisions");+ expect(header?.textContent).toContain("2 pending");+ expect(header?.textContent).toContain("1 of 2");+ expect(+ header?.querySelector('button[aria-label="Dismiss Release decisions"]'),+ ).not.toBeNull();+ expect(+ header?.querySelector('[aria-label="Question pagination"]'),+ ).not.toBeNull();+ expect(+ container.querySelector(+ '[data-testid="task-chat-composer-takeover-body"] [aria-label="Question pagination"]',+ ),+ ).toBeNull();+ });++ it("places Skip beside Submit answers for structured questions", () => {+ render(+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ takeover={{+ id: "structured-question",+ label: "Deployment target",+ pendingCount: 1,+ inlineSkip: true,+ content: (+ <QuestionForm+ id="deployment-target"+ questionSet={{+ schema: "paperclip.question_set.v1",+ questions: [+ {+ id: "environment",+ prompt: "Which environment should receive this?",+ required: true,+ answerMode: "multi_select",+ options: [+ { id: "staging", label: "Staging", recommended: true },+ { id: "production", label: "Production" },+ ],+ },+ ],+ }}+ onSubmit={vi.fn()}+ />+ ),+ onDismiss: vi.fn(),+ onSkip: vi.fn(),+ }}+ />,+ );++ const buttons = Array.from(+ container.querySelectorAll<HTMLButtonElement>("button"),+ );+ const skip = buttons.find(+ (button) => button.textContent?.trim() === "Skip",+ );+ const submit = buttons.find(+ (button) => button.textContent?.trim() === "Submit answers",+ );+ expect(skip).not.toBeUndefined();+ expect(submit).not.toBeUndefined();+ expect(skip?.parentElement).toBe(submit?.parentElement);+ expect(+ buttons.filter((button) => button.textContent?.trim() === "Skip"),+ ).toHaveLength(1);+ const takeoverBody = container.querySelector(+ '[data-testid="task-chat-composer-takeover-body"]',+ );+ expect(takeoverBody?.className).not.toContain("max-h-");+ expect(takeoverBody?.className).not.toContain("overflow-y-auto");+ expect(takeoverBody?.className).not.toContain("pr-8");++ const staging = buttons.find((button) =>+ button.textContent?.includes("Staging"),+ );+ const production = buttons.find(+ (button) => button.textContent?.trim() === "Production",+ );+ expect(staging?.getAttribute("data-recommended")).toBe("true");+ expect(staging?.className.split(" ")).toContain("bg-muted/50");+ expect(+ production?.className+ .split(" ")+ .some(+ (token) => token.startsWith("border") || token.startsWith("bg-"),+ ),+ ).toBe(false);++ flushSync(() => staging?.click());+ expect(staging?.getAttribute("data-selected")).toBe("true");+ expect(staging?.className.split(" ")).toContain("bg-muted/80");+ });++ it("hides Skip when the takeover already provides a request-changes path", () => {+ render(+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="planning"+ takeover={{+ id: "plan-review",+ label: "Review the proposed plan",+ pendingCount: 1,+ content: <p>Do you accept this plan?</p>,+ onDismiss: vi.fn(),+ onSkip: vi.fn(),+ hideSkip: true,+ }}+ />,+ );++ expect(container.textContent).not.toContain("Skip");+ expect(+ container.querySelector(+ 'button[aria-label="Dismiss Review the proposed plan"]',+ ),+ ).not.toBeNull();+ expect(+ container.querySelector(+ '[data-testid="task-chat-composer-takeover"] .border-t',+ ),+ ).toBeNull();+ });++ it("dismisses every takeover without invoking Skip", async () => {+ const onDismiss = vi.fn();+ const onSkip = vi.fn();+ render(+ <TaskChatComposer+ onAdd={vi.fn()}+ workMode="standard"+ takeover={{+ id: "dismissable-question",+ label: "Release questions",+ pendingCount: 1,+ content: <p>Which release should ship?</p>,+ onDismiss,+ onSkip,+ }}+ />,+ );++ flushSync(() =>+ container+ .querySelector<HTMLButtonElement>(+ 'button[aria-label="Dismiss Release questions"]',+ )+ ?.click(),+ );+ await flushAsync();++ expect(onDismiss).toHaveBeenCalledTimes(1);+ expect(onSkip).not.toHaveBeenCalled();+ });+ });});diff --git a/ui/src/components/task-chat/TaskChatComposer.tsx b/ui/src/components/task-chat/TaskChatComposer.tsxindex 8ff2a75ad2..9f4942eb97 100644--- a/ui/src/components/task-chat/TaskChatComposer.tsx+++ b/ui/src/components/task-chat/TaskChatComposer.tsx@@ -5,10 +5,25 @@ import {type ChangeEvent,type ClipboardEvent as ReactClipboardEvent,type CSSProperties,+ type ReactNode,} from "react";import { cn } from "@/lib/utils";-import { DRAFT_DEBOUNCE_MS, clearDraft, loadDraft, saveDraft } from "@/lib/composer-draft";-import { ArrowUp, Check, ChevronDown, Loader2, Plus, X } from "lucide-react";+import {+ DRAFT_DEBOUNCE_MS,+ clearDraft,+ loadDraft,+ saveDraft,+} from "@/lib/composer-draft";+import {+ ArrowUp,+ Check,+ ChevronDown,+ CircleHelp,+ Loader2,+ Plus,+ X,+} from "lucide-react";+import { Button } from "@/components/ui/button";import {DropdownMenu,DropdownMenuContent,@@ -26,11 +41,24 @@ import {AttachmentTitle,} from "@/components/ui/attachment";import { fileKindForName, formatFileSize } from "./task-chat-attachments";-import { MarkdownEditor, type MarkdownEditorRef } from "@/components/MarkdownEditor";-import { nextWorkMode, workModeMetaFor, workModeMetaList } from "@/lib/work-mode-meta";-import { InlineEntitySelector, type InlineEntityOption } from "@/components/InlineEntitySelector";+import {+ MarkdownEditor,+ type MarkdownEditorRef,+} from "@/components/MarkdownEditor";+import {+ nextWorkMode,+ workModeMetaFor,+ workModeMetaList,+} from "@/lib/work-mode-meta";+import {+ InlineEntitySelector,+ type InlineEntityOption,+} from "@/components/InlineEntitySelector";+import { AgentIcon } from "@/components/AgentIconPicker";+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";import type { MentionOption } from "@/components/MarkdownEditor";import type { IssueAttachment, IssueWorkMode } from "@paperclipai/shared";+import { TaskChatComposerTakeoverActionsContext } from "./TaskChatComposerTakeoverContext";/** Structurally identical to IssueChatThread's module-private CommentReassignment. */interface CommentReassignment {@@ -38,8 +66,27 @@ interface CommentReassignment {assigneeUserId: string | null;}+export interface TaskChatComposerTakeover {+ id: string;+ label: string;+ pendingCount: number;+ content: ReactNode;+ /** Hides the takeover without resolving it; the pending indicator can reopen it. */+ onDismiss: () => void;+ onSkip: () => Promise<void> | void;+ onShowNext?: () => void;+ /** Places Skip inside a structured question form's action row. */+ inlineSkip?: boolean;+ /** Some decision surfaces already provide a non-accept path of their own. */+ hideSkip?: boolean;+}+interface TaskChatComposerProps {- onAdd: (body: string, reopen?: boolean, reassignment?: CommentReassignment) => Promise<void> | void;+ onAdd: (+ body: string,+ reopen?: boolean,+ reassignment?: CommentReassignment,+ ) => Promise<void> | void;workMode: IssueWorkMode;onWorkModeChange?: (mode: IssueWorkMode) => Promise<void> | void;disabled?: boolean;@@ -53,12 +100,27 @@ interface TaskChatComposerProps {mentions?: MentionOption[];enableReassign?: boolean;reassignOptions?: InlineEntityOption[];+ agentMap?: ReadonlyMap<string, { icon?: string | null }>;+ userProfileMap?: ReadonlyMap<+ string,+ { label: string; image: string | null }+ > | null;currentAssigneeValue?: string;issueStatus?: string;/** Mobile document-flow host: 16px editor text so iOS doesn't zoom on focus. */mobile?: boolean;/** Storage key used to restore, persist, and clear this task's text draft. */draftKey?: string;+ /** When set, the main composer temporarily edits this queued message. */+ queuedEdit?: { commentId: string; body: string; stale?: boolean } | null;+ onSaveQueuedEdit?: (commentId: string, body: string) => Promise<void>;+ onCancelQueuedEdit?: () => void;+ takeover?: TaskChatComposerTakeover | null;+ pendingTakeover?: {+ count: number;+ label?: string;+ onOpen: () => void;+ } | null;}/** Per-mode hue token (see ui/src/index.css `--tc-mode-*`). */@@ -72,6 +134,74 @@ function modeHue(mode: IssueWorkMode): string {return MODE_HUE[mode] ?? "var(--tc-mode-agent)";}+function identityInitials(label: string): string {+ const parts = label.trim().split(/\s+/).filter(Boolean);+ if (parts.length === 0) return "?";+ if (parts.length === 1) return parts[0]!.slice(0, 2).toUpperCase();+ return `${parts[0]![0]}${parts[parts.length - 1]![0]}`.toUpperCase();+}++function AssigneeIdentityAvatar({+ assigneeValue,+ label,+ agentMap,+ userProfileMap,+ placement,+}: {+ assigneeValue: string;+ label: string;+ agentMap: ReadonlyMap<string, { icon?: string | null }> | undefined;+ userProfileMap:+ | ReadonlyMap<string, { label: string; image: string | null }>+ | null+ | undefined;+ placement: "trigger" | "option";+}) {+ if (assigneeValue.startsWith("agent:")) {+ const agentId = assigneeValue.slice("agent:".length);+ const icon = agentMap?.get(agentId)?.icon ?? "bot";+ return (+ <Avatar+ size="xs"+ className="shrink-0"+ data-assignee-identity={assigneeValue}+ data-assignee-trigger-icon={placement === "trigger" ? icon : undefined}+ data-assignee-option-icon={+ placement === "option" ? assigneeValue : undefined+ }+ >+ <AvatarFallback>+ <AgentIcon icon={icon} className="h-3 w-3" />+ </AvatarFallback>+ </Avatar>+ );+ }++ if (assigneeValue.startsWith("user:")) {+ const userId = assigneeValue.slice("user:".length);+ const profile = userProfileMap?.get(userId);+ const resolvedLabel = profile?.label ?? label;+ return (+ <Avatar+ size="xs"+ className="shrink-0"+ data-assignee-identity={assigneeValue}+ data-assignee-trigger-avatar={+ placement === "trigger" ? userId : undefined+ }+ data-assignee-option-avatar={+ placement === "option" ? assigneeValue : undefined+ }+ >+ {profile?.image ? <AvatarImage src={profile.image} alt="" /> : null}+ <AvatarFallback>{identityInitials(resolvedLabel)}</AvatarFallback>+ </Avatar>+ );+ }++ return null;+}+const MODE_DESCRIPTION: Partial<Record<IssueWorkMode, string>> = {standard: "Make changes and run work",planning: "Draft a plan before acting",@@ -100,9 +230,22 @@ type ComposerAttachment = {contentPath?: string;};+type QueuedEditBackup = {+ body: string;+ attachments: ComposerAttachment[];+ pendingMode: IssueWorkMode;+ pendingAssignee: string | null;+};+/** Local duplicate of IssueChatThread's module-private helper (same rule). */-function shouldImplicitlyReopenComment(issueStatus: string | undefined, assigneeValue: string) {- const resumesToTodo = issueStatus === "done" || issueStatus === "cancelled" || issueStatus === "blocked";+function shouldImplicitlyReopenComment(+ issueStatus: string | undefined,+ assigneeValue: string,+) {+ const resumesToTodo =+ issueStatus === "done" ||+ issueStatus === "cancelled" ||+ issueStatus === "blocked";return resumesToTodo && assigneeValue.startsWith("agent:");}@@ -147,13 +290,27 @@ export function TaskChatComposer({mentions,enableReassign = false,reassignOptions,+ agentMap,+ userProfileMap,currentAssigneeValue = "",issueStatus,mobile = false,draftKey,+ queuedEdit = null,+ onSaveQueuedEdit,+ onCancelQueuedEdit,+ takeover = null,+ pendingTakeover = null,}: TaskChatComposerProps) {const [body, setBody] = useState(() => (draftKey ? loadDraft(draftKey) : ""));const [submitting, setSubmitting] = useState(false);+ const [takeoverBusy, setTakeoverBusy] = useState(false);+ const [takeoverError, setTakeoverError] = useState<string | null>(null);+ const [takeoverHeaderClaimed, setTakeoverHeaderClaimed] = useState(false);+ const [takeoverHeaderSlot, setTakeoverHeaderSlot] =+ useState<HTMLElement | null>(null);+ const [takeoverControlsSlot, setTakeoverControlsSlot] =+ useState<HTMLElement | null>(null);const [pendingMode, setPendingMode] = useState<IssueWorkMode>(workMode);const [pendingAssignee, setPendingAssignee] = useState<string | null>(null);const [attachments, setAttachments] = useState<ComposerAttachment[]>([]);@@ -166,42 +323,105 @@ export function TaskChatComposer({const bodyRef = useRef(body);bodyRef.current = body;const draftTimer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const queuedEditRef = useRef(queuedEdit);+ queuedEditRef.current = queuedEdit;+ const queuedEditBackupRef = useRef<QueuedEditBackup | null>(null);+ const previousQueuedEditIdRef = useRef<string | null>(null);useEffect(() => {- if (!draftKey) return;+ setTakeoverBusy(false);+ setTakeoverError(null);+ }, [takeover?.id]);++ useEffect(() => {+ const previousId = previousQueuedEditIdRef.current;+ const nextEdit = queuedEdit;+ const nextId = nextEdit?.commentId ?? null;++ if (nextEdit && previousId !== nextId) {+ if (!queuedEditBackupRef.current) {+ queuedEditBackupRef.current = {+ body: bodyRef.current,+ attachments: attachmentsRef.current,+ pendingMode,+ pendingAssignee: pendingAssigneeRef.current,+ };+ if (draftKey) saveDraft(draftKey, bodyRef.current);+ }+ if (draftTimer.current) {+ clearTimeout(draftTimer.current);+ draftTimer.current = null;+ }+ bodyRef.current = nextEdit.body;+ setBody(nextEdit.body);+ setAttachments([]);+ requestAnimationFrame(() => editorRef.current?.focus());+ } else if (!nextId && previousId) {+ const backup = queuedEditBackupRef.current;+ if (backup) {+ bodyRef.current = backup.body;+ setBody(backup.body);+ setAttachments(backup.attachments);+ setPendingMode(backup.pendingMode);+ setPendingAssignee(backup.pendingAssignee);+ if (draftKey) saveDraft(draftKey, backup.body);+ }+ queuedEditBackupRef.current = null;+ requestAnimationFrame(() => editorRef.current?.focus());+ }++ previousQueuedEditIdRef.current = nextId;+ }, [draftKey, pendingMode, queuedEdit]);++ useEffect(() => {+ if (!draftKey || queuedEdit) return;setBody(loadDraft(draftKey));- }, [draftKey]);+ }, [draftKey, queuedEdit]);useEffect(() => {- if (!draftKey) return;+ if (!draftKey || queuedEdit) {+ if (draftTimer.current) {+ clearTimeout(draftTimer.current);+ draftTimer.current = null;+ }+ return;+ }if (draftTimer.current) clearTimeout(draftTimer.current);draftTimer.current = setTimeout(() => {saveDraft(draftKey, body);}, DRAFT_DEBOUNCE_MS);- }, [body, draftKey]);+ }, [body, draftKey, queuedEdit]);useEffect(() => {return () => {if (draftTimer.current) clearTimeout(draftTimer.current);- if (draftKey) saveDraft(draftKey, bodyRef.current);+ if (draftKey && !queuedEditRef.current)+ saveDraft(draftKey, bodyRef.current);};}, [draftKey]);useEffect(() => {if (!draftKey) return;- const flushDraft = () => saveDraft(draftKey, bodyRef.current);+ const flushDraft = () => {+ if (!queuedEditRef.current) saveDraft(draftKey, bodyRef.current);+ };window.addEventListener("beforeunload", flushDraft);return () => window.removeEventListener("beforeunload", flushDraft);}, [draftKey]);const modeMeta = workModeMetaFor(pendingMode);- const canAcceptFiles = Boolean(onAttachImage || onImageUpload);- const showAssignee = Boolean(enableReassign && reassignOptions && reassignOptions.length > 0);+ const canAcceptFiles = !queuedEdit && Boolean(onAttachImage || onImageUpload);+ const showAssignee = Boolean(+ enableReassign && reassignOptions && reassignOptions.length > 0,+ );const assigneeValue = pendingAssignee ?? currentAssigneeValue;const assigneeLabel =reassignOptions?.find((o) => o.id === assigneeValue)?.label ?? "Unassigned";- const assigneeName = assigneeLabel === "Unassigned" ? "the agent" : assigneeLabel;- const effectivePlaceholder = placeholder ?? modePlaceholder(pendingMode, assigneeName);+ const assigneeName =+ assigneeLabel === "Unassigned" ? "the agent" : assigneeLabel;+ const effectivePlaceholder = queuedEdit+ ? "Edit queued message…"+ : (placeholder ?? modePlaceholder(pendingMode, assigneeName));/** Upload an image and return its URL for inline `` markdown. */async function uploadInlineImage(file: File): Promise<string> {@@ -217,13 +437,20 @@ export function TaskChatComposer({/** Non-image files: attach to the task and track in the chip row. */async function attachNonImageFile(file: File) {const id = `${file.name}:${file.size}:${file.lastModified}:${Math.random().toString(36).slice(2)}`;- setAttachments((prev) => [...prev, { id, name: file.name, size: file.size, status: "uploading" }]);+ setAttachments((prev) => [+ ...prev,+ { id, name: file.name, size: file.size, status: "uploading" },+ ]);try {if (!onAttachImage) {setAttachments((prev) =>prev.map((item) =>item.id === id- ? { ...item, status: "error", error: "This file type cannot be attached here" }+ ? {+ ...item,+ status: "error",+ error: "This file type cannot be attached here",+ }: item,),);@@ -234,7 +461,12 @@ export function TaskChatComposer({setAttachments((prev) =>prev.map((item) =>item.id === id- ? { ...item, name, status: "attached", contentPath: attachment?.contentPath }+ ? {+ ...item,+ name,+ status: "attached",+ contentPath: attachment?.contentPath,+ }: item,),);@@ -242,7 +474,11 @@ export function TaskChatComposer({setAttachments((prev) =>prev.map((item) =>item.id === id- ? { ...item, status: "error", error: err instanceof Error ? err.message : "Upload failed" }+ ? {+ ...item,+ status: "error",+ error: err instanceof Error ? err.message : "Upload failed",+ }: item,),);@@ -258,7 +494,9 @@ export function TaskChatComposer({const id = `${file.name}:${file.size}:${file.lastModified}:${Math.random().toString(36).slice(2)}`;try {const url = await uploadInlineImage(file);- editorRef.current?.insertMarkdown(``);+ editorRef.current?.insertMarkdown(+ ``,+ );} catch (err) {setAttachments((prev) => [...prev,@@ -313,6 +551,16 @@ export function TaskChatComposer({// clear its error state, so both hold submission until resolved or removed.const uploadPending = attachments.some((item) => item.status === "uploading");const uploadFailed = attachments.some((item) => item.status === "error");+ const takeoverVisible = Boolean(+ takeover && !queuedEdit && !submitting && !uploadPending,+ );+ const previousTakeoverVisibleRef = useRef(takeoverVisible);+ useEffect(() => {+ if (previousTakeoverVisibleRef.current && !takeoverVisible && !queuedEdit) {+ requestAnimationFrame(() => editorRef.current?.focus());+ }+ previousTakeoverVisibleRef.current = takeoverVisible;+ }, [queuedEdit, takeoverVisible]);async function submit() {const submittedBody = bodyRef.current;@@ -331,10 +579,19 @@ export function TaskChatComposer({const refLines = attachedRefs.map((item) => `[${escapeMarkdownLabel(item.name)}](${item.contentPath})`).join("\n");- const fullBody = [trimmed, refLines].filter(Boolean).join("\n\n");- const hasReassignment = showAssignee && assigneeValue !== currentAssigneeValue;- const reassignment = hasReassignment ? parseAssigneeValue(assigneeValue) : undefined;- const reopen = shouldImplicitlyReopenComment(issueStatus, assigneeValue) ? true : undefined;+ // A queued edit must preserve the complete Markdown source. Normal sends+ // keep the longstanding trimmed-body behavior.+ const fullBody = queuedEdit+ ? submittedBody+ : [trimmed, refLines].filter(Boolean).join("\n\n");+ const hasReassignment =+ showAssignee && assigneeValue !== currentAssigneeValue;+ const reassignment = hasReassignment+ ? parseAssigneeValue(assigneeValue)+ : undefined;+ const reopen = shouldImplicitlyReopenComment(issueStatus, assigneeValue)+ ? true+ : undefined;// The thread renders the outgoing comment optimistically, so remove its// text from the composer at the same time. The editor remains writable for@@ -348,6 +605,12 @@ export function TaskChatComposer({setBody("");setSubmitting(true);try {+ if (queuedEdit) {+ if (!onSaveQueuedEdit) return;+ await onSaveQueuedEdit(queuedEdit.commentId, fullBody);+ onCancelQueuedEdit?.();+ return;+ }if (pendingMode !== workMode && onWorkModeChange) {await onWorkModeChange(pendingMode);}@@ -367,7 +630,9 @@ export function TaskChatComposer({// Restore the failed message for retry without discarding a next draft// that was entered while the request was pending.const nextDraft = bodyRef.current;- const restoredBody = nextDraft ? `${submittedBody}\n\n${nextDraft}` : submittedBody;+ const restoredBody = nextDraft+ ? `${submittedBody}\n\n${nextDraft}`+ : submittedBody;bodyRef.current = restoredBody;if (draftTimer.current) {clearTimeout(draftTimer.current);@@ -380,15 +645,44 @@ export function TaskChatComposer({}}+ function skipTakeover() {+ if (!takeover) return;+ setTakeoverBusy(true);+ setTakeoverError(null);+ Promise.resolve(takeover.onSkip()).catch((cause) => {+ setTakeoverBusy(false);+ setTakeoverError(+ cause instanceof Error+ ? cause.message+ : "This request could not be skipped.",+ );+ });+ }++ const takeoverSkipButton = takeover ? (+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={takeoverBusy}+ onClick={skipTakeover}+ >+ {takeoverBusy ? (+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden />+ ) : null}+ Skip+ </Button>+ ) : null;+return (<divclassName={cn(- "paperclip-task-chat-composer rounded-xl border border-input bg-card p-(--sz-18px) shadow-(--shadow-extract-7) transition-[border-color,box-shadow] focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/15",+ "paperclip-task-chat-composer rounded-xl bg-card p-(--sz-18px)",)}onKeyDownCapture={(e) => {// Shift+Tab cycles the pending mode; captured on the wrapper so it// wins over Lexical's list-outdent binding inside the editor.- if (disabled) return;+ if (disabled || queuedEdit || takeoverVisible) return;if (e.key === "Tab" && e.shiftKey) {e.preventDefault();e.stopPropagation();@@ -397,192 +691,372 @@ export function TaskChatComposer({}}onPasteCapture={handlePasteCapture}>- <div data-testid="task-chat-composer-input">- <MarkdownEditor- ref={editorRef}- value={body}- onChange={setBody}- placeholder={disabled ? (disabledReason ?? "Composer disabled") : effectivePlaceholder}- readOnly={disabled}- mentions={mentions}- onSubmit={() => void submit()}- imageUploadHandler={canAcceptFiles ? uploadInlineImage : undefined}- onDropFile={canAcceptFiles ? attachNonImageFile : undefined}- bordered={false}- className={cn(disabled && "opacity-60")}- contentClassName={- mobile- ? "max-h-(--sz-28dvh) min-h-(--sz-72px) overflow-y-auto px-1 py-1 text-base scrollbar-auto-hide"- : "max-h-(--sz-28dvh) min-h-(--sz-48px) overflow-y-auto px-1 py-1 text-sm scrollbar-auto-hide"- }- />- </div>-- {attachments.length > 0 ? (- <AttachmentGroup className="mb-1 px-1" data-testid="task-chat-composer-attachments">- {attachments.map((attachment) => {- const kind = fileKindForName(attachment.name);- const KindIcon = kind.icon;- const sizeLabel = formatFileSize(attachment.size);- return (- <Attachment- key={attachment.id}- size="sm"- state={- attachment.status === "uploading"- ? "uploading"- : attachment.status === "error"- ? "error"- : "done"- }+ {takeoverVisible && takeover ? (+ <section+ className="relative"+ aria-label={takeover.label}+ data-testid="task-chat-composer-takeover"+ >+ <div+ className="mb-3 flex min-w-0 items-center gap-2"+ data-testid="task-chat-composer-takeover-header"+ >+ <div className="min-w-0 flex-1">+ {!takeoverHeaderClaimed ? (+ <strong className="block truncate text-sm font-medium text-foreground">+ {takeover.label}+ </strong>+ ) : null}+ <div+ ref={setTakeoverHeaderSlot}+ className="flex min-w-0 items-center"+ data-testid="task-chat-composer-takeover-title-slot"+ />+ </div>+ <div className="ml-auto flex shrink-0 items-center gap-1">+ {takeover.pendingCount > 1 ? (+ <Button+ type="button"+ size="sm"+ variant="ghost"+ className="h-7 px-2"+ onClick={takeover.onShowNext}+ >+ {takeover.pendingCount} pending+ </Button>+ ) : null}+ <div+ ref={setTakeoverControlsSlot}+ className="flex shrink-0 items-center"+ data-testid="task-chat-composer-takeover-controls-slot"+ />+ <Button+ type="button"+ size="icon-xs"+ variant="ghost"+ className="text-muted-foreground hover:text-foreground"+ aria-label={`Dismiss ${takeover.label}`}+ disabled={takeoverBusy}+ onClick={takeover.onDismiss}>- <AttachmentMedia>- {attachment.status === "uploading" ? (- <Loader2 className="animate-spin" aria-hidden />- ) : (- <KindIcon aria-hidden />- )}- </AttachmentMedia>- <AttachmentContent>- <AttachmentTitle className="max-w-48">{attachment.name}</AttachmentTitle>- <AttachmentDescription className="max-w-48">- {attachment.status === "uploading"- ? "Uploading…"- : attachment.status === "error"- ? (attachment.error ?? "Upload failed")- : [kind.label, sizeLabel].filter(Boolean).join(" · ")}- </AttachmentDescription>- </AttachmentContent>- <AttachmentActions>- <AttachmentAction- aria-label={`Remove ${attachment.name}`}- onClick={() =>- setAttachments((prev) => prev.filter((item) => item.id !== attachment.id))- }- >- <X aria-hidden />- </AttachmentAction>- </AttachmentActions>- </Attachment>- );- })}- </AttachmentGroup>- ) : null}-- <div className="mt-1 flex items-center gap-2">- {canAcceptFiles ? (- <>- <input- ref={fileInputRef}- type="file"- className="hidden"- onChange={handleFileInputChange}- />+ <X aria-hidden />+ </Button>+ </div>+ </div>+ <div className="pr-1" data-testid="task-chat-composer-takeover-body">+ <TaskChatComposerTakeoverActionsContext.Provider+ value={{+ skipButton:+ takeover.inlineSkip &&+ !takeover.hideSkip &&+ takeoverSkipButton+ ? takeoverSkipButton+ : null,+ headerSlot: takeoverHeaderSlot,+ controlsSlot: takeoverControlsSlot,+ setHeaderClaimed: setTakeoverHeaderClaimed,+ }}+ >+ {takeover.content}+ </TaskChatComposerTakeoverActionsContext.Provider>+ </div>+ {takeoverError ? (+ <p className="mt-2 text-sm text-destructive" role="alert">+ {takeoverError}+ </p>+ ) : null}+ {!takeover.inlineSkip && !takeover.hideSkip ? (+ <div className="mt-3 flex items-center justify-end gap-2">+ {takeoverSkipButton}+ </div>+ ) : null}+ </section>+ ) : (+ <>+ {pendingTakeover || takeover ? (<buttontype="button"- onClick={() => fileInputRef.current?.click()}- disabled={disabled}- title="Attach file"- aria-label="Attach file"- className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50"- data-testid="task-chat-composer-attach"+ className="mb-2 flex w-full items-center gap-2 rounded-md bg-muted/50 px-2.5 py-2 text-left text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ onClick={pendingTakeover?.onOpen}+ data-testid="task-chat-pending-input-indicator">- <Plus className="h-4 w-4" aria-hidden />+ <CircleHelp className="h-4 w-4 shrink-0" aria-hidden />+ <span className="min-w-0 flex-1 truncate">+ {pendingTakeover?.label ?? takeover?.label ?? "Pending input"}+ </span>+ <span className="shrink-0 font-medium">+ {pendingTakeover?.count ?? takeover?.pendingCount ?? 1} pending+ </span></button>- </>- ) : null}+ ) : null}+ <div data-testid="task-chat-composer-input">+ <MarkdownEditor+ ref={editorRef}+ value={body}+ onChange={setBody}+ placeholder={+ disabled+ ? (disabledReason ?? "Composer disabled")+ : effectivePlaceholder+ }+ readOnly={disabled}+ mentions={mentions}+ onSubmit={() => void submit()}+ imageUploadHandler={+ canAcceptFiles ? uploadInlineImage : undefined+ }+ onDropFile={canAcceptFiles ? attachNonImageFile : undefined}+ bordered={false}+ className={cn(disabled && "opacity-60")}+ contentClassName={+ mobile+ ? "max-h-(--sz-28dvh) min-h-(--sz-72px) overflow-y-auto px-1 py-1 text-base scrollbar-auto-hide"+ : "max-h-(--sz-28dvh) min-h-(--sz-48px) overflow-y-auto px-1 py-1 text-sm scrollbar-auto-hide"+ }+ />+ </div>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button- type="button"- disabled={disabled || !onWorkModeChange}- className="status-chip flex h-8 shrink-0 items-center gap-1.5 rounded-md border px-2.5 text-xs font-medium transition-colors disabled:opacity-50"- style={{ "--sc": modeHue(pendingMode) } as CSSProperties}- data-testid="task-chat-composer-mode"- data-pending-work-mode={pendingMode}+ {attachments.length > 0 ? (+ <AttachmentGroup+ className="mb-1 px-1"+ data-testid="task-chat-composer-attachments">- {modeMeta.label}- <ChevronDown className="h-3 w-3" aria-hidden />- </button>- </DropdownMenuTrigger>- <DropdownMenuContent align="start" className="w-60">- {workModeMetaList().map((m) => {- const Icon = m.icon;- const selected = m.value === pendingMode;- return (- <DropdownMenuItem- key={m.value}- onSelect={() => setPendingMode(m.value)}- style={- selected- ? { backgroundColor: `color-mix(in srgb, ${modeHue(m.value)} 12%, transparent)` }- : undefined- }- >- <Icon className="h-4 w-4 shrink-0" style={{ color: modeHue(m.value) }} aria-hidden />- <span className="flex min-w-0 flex-1 flex-col">- <span className="font-medium">{m.label}</span>- <span className="text-xs text-muted-foreground">{MODE_DESCRIPTION[m.value] ?? ""}</span>- </span>- {selected ? <Check className="h-4 w-4 shrink-0" aria-hidden /> : null}- </DropdownMenuItem>- );- })}- </DropdownMenuContent>- </DropdownMenu>-- <div className="flex-1" />-- {showAssignee ? (- <InlineEntitySelector- value={assigneeValue}- options={reassignOptions ?? []}- placeholder="Assignee"- noneLabel="No assignee"- searchPlaceholder="Search assignees…"- emptyMessage="No matches."- onChange={setPendingAssignee}- disabled={disabled}- triggerTestId="task-chat-composer-assignee"- className="h-8 gap-1.5 bg-transparent px-2.5 text-xs hover:bg-accent"- renderTriggerValue={() => (+ {attachments.map((attachment) => {+ const kind = fileKindForName(attachment.name);+ const KindIcon = kind.icon;+ const sizeLabel = formatFileSize(attachment.size);+ return (+ <Attachment+ key={attachment.id}+ size="sm"+ state={+ attachment.status === "uploading"+ ? "uploading"+ : attachment.status === "error"+ ? "error"+ : "done"+ }+ >+ <AttachmentMedia>+ {attachment.status === "uploading" ? (+ <Loader2 className="animate-spin" aria-hidden />+ ) : (+ <KindIcon aria-hidden />+ )}+ </AttachmentMedia>+ <AttachmentContent>+ <AttachmentTitle className="max-w-48">+ {attachment.name}+ </AttachmentTitle>+ <AttachmentDescription className="max-w-48">+ {attachment.status === "uploading"+ ? "Uploading…"+ : attachment.status === "error"+ ? (attachment.error ?? "Upload failed")+ : [kind.label, sizeLabel]+ .filter(Boolean)+ .join(" · ")}+ </AttachmentDescription>+ </AttachmentContent>+ <AttachmentActions>+ <AttachmentAction+ aria-label={`Remove ${attachment.name}`}+ onClick={() =>+ setAttachments((prev) =>+ prev.filter((item) => item.id !== attachment.id),+ )+ }+ >+ <X aria-hidden />+ </AttachmentAction>+ </AttachmentActions>+ </Attachment>+ );+ })}+ </AttachmentGroup>+ ) : null}++ <div className="mt-1 flex items-center gap-2">+ {canAcceptFiles ? (<>- <span className="max-w-40 truncate">{assigneeLabel}</span>- <ChevronDown className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden />+ <input+ ref={fileInputRef}+ type="file"+ className="hidden"+ onChange={handleFileInputChange}+ />+ <button+ type="button"+ onClick={() => fileInputRef.current?.click()}+ disabled={disabled}+ title="Attach file"+ aria-label="Attach file"+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50"+ data-testid="task-chat-composer-attach"+ >+ <Plus className="h-4 w-4" aria-hidden />+ </button></>+ ) : null}++ {queuedEdit ? (+ <span className="px-1 text-xs font-medium text-muted-foreground">+ {queuedEdit.stale+ ? "Queued message changed"+ : "Editing queued message"}+ </span>+ ) : (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ disabled={disabled || !onWorkModeChange}+ className="status-chip flex h-8 shrink-0 items-center gap-1.5 rounded-md px-2.5 text-xs font-medium transition hover:brightness-110 focus-visible:brightness-110 focus-visible:outline-none disabled:opacity-50"+ style={{ "--sc": modeHue(pendingMode) } as CSSProperties}+ data-testid="task-chat-composer-mode"+ data-pending-work-mode={pendingMode}+ >+ {modeMeta.label}+ <ChevronDown className="h-3 w-3" aria-hidden />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-60">+ {workModeMetaList().map((m) => {+ const Icon = m.icon;+ const selected = m.value === pendingMode;+ return (+ <DropdownMenuItem+ key={m.value}+ onSelect={() => setPendingMode(m.value)}+ style={+ selected+ ? {+ backgroundColor: `color-mix(in srgb, ${modeHue(m.value)} 12%, transparent)`,+ }+ : undefined+ }+ >+ <Icon+ className="h-4 w-4 shrink-0"+ style={{ color: modeHue(m.value) }}+ aria-hidden+ />+ <span className="flex min-w-0 flex-1 flex-col">+ <span className="font-medium">{m.label}</span>+ <span className="text-xs text-muted-foreground">+ {MODE_DESCRIPTION[m.value] ?? ""}+ </span>+ </span>+ {selected ? (+ <Check className="h-4 w-4 shrink-0" aria-hidden />+ ) : null}+ </DropdownMenuItem>+ );+ })}+ </DropdownMenuContent>+ </DropdownMenu>)}- />- ) : null}-- <button- type="button"- onClick={() => void submit()}- disabled={- disabled ||- submitting ||- uploadPending ||- uploadFailed ||- (body.trim().length === 0 && attachedRefs.length === 0)- }- title={- uploadPending- ? "Waiting for upload to finish"- : uploadFailed- ? "Remove the failed attachment to send"- : "Send (⌘+Enter)"- }- aria-label="Send"- className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-primary text-primary-foreground transition-transform hover:scale-105 disabled:scale-100 disabled:bg-muted disabled:text-muted-foreground"- data-testid="task-chat-composer-send"- >- {submitting ? (- <Loader2 className="h-4 w-4 animate-spin" aria-hidden />- ) : (- <ArrowUp className="h-4 w-4" aria-hidden />- )}- </button>- </div>++ <div className="flex-1" />++ {showAssignee && !queuedEdit ? (+ <InlineEntitySelector+ value={assigneeValue}+ options={reassignOptions ?? []}+ placeholder="Assignee"+ noneLabel="No assignee"+ searchPlaceholder="Search assignees…"+ emptyMessage="No matches."+ onChange={setPendingAssignee}+ disabled={disabled}+ triggerTestId="task-chat-composer-assignee"+ className="h-8 gap-1.5 border-0 bg-transparent px-2.5 text-xs shadow-none hover:bg-accent focus-visible:bg-accent focus-visible:ring-0"+ renderTriggerValue={(option) => {+ return (+ <>+ <AssigneeIdentityAvatar+ assigneeValue={option?.id ?? ""}+ label={assigneeLabel}+ agentMap={agentMap}+ userProfileMap={userProfileMap}+ placement="trigger"+ />+ <span className="max-w-40 truncate">{assigneeLabel}</span>+ <ChevronDown+ className="h-3 w-3 shrink-0 text-muted-foreground"+ aria-hidden+ />+ </>+ );+ }}+ renderOption={(option) => {+ return (+ <>+ <AssigneeIdentityAvatar+ assigneeValue={option.id}+ label={option.label}+ agentMap={agentMap}+ userProfileMap={userProfileMap}+ placement="option"+ />+ <span className="truncate">{option.label}</span>+ </>+ );+ }}+ />+ ) : null}++ {queuedEdit ? (+ <button+ type="button"+ onClick={onCancelQueuedEdit}+ disabled={submitting}+ className="h-8 shrink-0 rounded-md px-2.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50"+ >+ Cancel+ </button>+ ) : null}++ <button+ type="button"+ onClick={() => void submit()}+ disabled={+ disabled ||+ submitting ||+ uploadPending ||+ uploadFailed ||+ (body.trim().length === 0 && attachedRefs.length === 0)+ }+ title={+ queuedEdit+ ? queuedEdit.stale+ ? "Queue as new message"+ : "Save queued message"+ : uploadPending+ ? "Waiting for upload to finish"+ : uploadFailed+ ? "Remove the failed attachment to send"+ : "Send (⌘+Enter)"+ }+ aria-label={+ queuedEdit+ ? queuedEdit.stale+ ? "Queue as new message"+ : "Save queued message"+ : "Send"+ }+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-primary text-primary-foreground transition-transform hover:scale-105 disabled:scale-100 disabled:bg-muted disabled:text-muted-foreground"+ data-testid="task-chat-composer-send"+ >+ {submitting ? (+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden />+ ) : (+ <ArrowUp className="h-4 w-4" aria-hidden />+ )}+ </button>+ </div>+ </>+ )}</div>);}diff --git a/ui/src/components/task-chat/TaskChatComposerTakeoverContext.ts b/ui/src/components/task-chat/TaskChatComposerTakeoverContext.tsnew file mode 100644index 0000000000..c2eb19a9c8--- /dev/null+++ b/ui/src/components/task-chat/TaskChatComposerTakeoverContext.ts@@ -0,0 +1,51 @@+import {+ createContext,+ useContext,+ useLayoutEffect,+ type ReactNode,+} from "react";+import { createPortal } from "react-dom";++interface TaskChatComposerTakeoverActions {+ skipButton: ReactNode;+ headerSlot: HTMLElement | null;+ controlsSlot: HTMLElement | null;+ setHeaderClaimed: (claimed: boolean) => void;+}++export const TaskChatComposerTakeoverActionsContext =+ createContext<TaskChatComposerTakeoverActions | null>(null);++export function useTaskChatComposerTakeoverActions(): TaskChatComposerTakeoverActions | null {+ return useContext(TaskChatComposerTakeoverActionsContext);+}++/** Moves a takeover's semantic title into the composer's shared top row. */+export function TaskChatComposerTakeoverHeader({+ children,+}: {+ children: ReactNode;+}) {+ const actions = useTaskChatComposerTakeoverActions();+ useLayoutEffect(() => {+ if (!actions) return;+ actions.setHeaderClaimed(true);+ return () => actions.setHeaderClaimed(false);+ }, [actions?.setHeaderClaimed]);++ if (!actions) return children;+ return actions.headerSlot ? createPortal(children, actions.headerSlot) : null;+}++/** Moves pagination or similar compact controls beside pending count and X. */+export function TaskChatComposerTakeoverControls({+ children,+}: {+ children: ReactNode;+}) {+ const actions = useTaskChatComposerTakeoverActions();+ if (!actions) return children;+ return actions.controlsSlot+ ? createPortal(children, actions.controlsSlot)+ : null;+}diff --git a/ui/src/components/task-chat/TaskChatInteractionCard.test.tsx b/ui/src/components/task-chat/TaskChatInteractionCard.test.tsxindex b4e4a0b5cd..20ab91e5ec 100644--- a/ui/src/components/task-chat/TaskChatInteractionCard.test.tsx+++ b/ui/src/components/task-chat/TaskChatInteractionCard.test.tsx@@ -1,16 +1,57 @@// @vitest-environment jsdom+import { act, forwardRef, useImperativeHandle, type ForwardedRef } from "react";import { flushSync } from "react-dom";import { createRoot, type Root } from "react-dom/client";-import { afterEach, beforeEach, describe, expect, it } from "vitest";-import type { RequestConfirmationInteraction } from "@/lib/issue-thread-interactions";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { IssueDocument } from "@paperclipai/shared";+import type {+ IssueThreadInteraction,+ RequestConfirmationInteraction,+} from "@/lib/issue-thread-interactions";import { ThemeProvider } from "@/context/ThemeContext";import { TooltipProvider } from "@/components/ui/tooltip";-import { expiredSecretProposalInteraction } from "@/fixtures/issueThreadInteractionFixtures";+import {+ expiredSecretProposalInteraction,+ pendingAskUserQuestionsInteraction,+ pendingRequestCheckboxConfirmationInteraction,+ pendingRequestItemVerdictsInteraction,+} from "@/fixtures/issueThreadInteractionFixtures";import { TaskChatInteractionCard } from "./TaskChatInteractionCard";import { TaskChatThreadView } from "./TaskChatThreadView";import type { TaskChatInteractionItem } from "./task-chat-model";+vi.mock("@/components/MarkdownEditor", () => ({+ MarkdownEditor: forwardRef(function MockMarkdownEditor(+ {+ value,+ onChange,+ placeholder,+ imageUploadHandler,+ }: {+ value: string;+ onChange: (value: string) => void;+ placeholder?: string;+ imageUploadHandler?: (file: File) => Promise<string>;+ },+ ref: ForwardedRef<unknown>,+ ) {+ useImperativeHandle(ref, () => ({+ insertMarkdown: (markdown: string) => onChange(`${value}${markdown}`),+ focus: () => {},+ }));+ return (+ <textarea+ data-testid="mock-markdown-editor"+ data-image-upload={imageUploadHandler ? "true" : "false"}+ value={value}+ placeholder={placeholder}+ onChange={(event) => onChange(event.target.value)}+ />+ );+ }),+}));+function createRequestConfirmation(overrides: Partial<RequestConfirmationInteraction> = {},): RequestConfirmationInteraction {@@ -28,7 +69,10 @@ function createRequestConfirmation(effectiveResolverPolicy: "anyone",resolverPolicyProvenance: "inherited",effectiveResolverPolicySource: "requested",- legacyResolverPolicyAliases: { requested: "board_or_agents", effective: "board_or_agents" },+ legacyResolverPolicyAliases: {+ requested: "board_or_agents",+ effective: "board_or_agents",+ },createdByAgentId: "agent-1",createdByUserId: null,resolvedByAgentId: null,@@ -46,9 +90,13 @@ function createRequestConfirmation(}function interactionItem(- interaction: RequestConfirmationInteraction,+ interaction: IssueThreadInteraction,): TaskChatInteractionItem {- return { id: `interaction:${interaction.id}`, kind: "interaction", interaction };+ return {+ id: `interaction:${interaction.id}`,+ kind: "interaction",+ interaction,+ };}describe("TaskChatInteractionCard", () => {@@ -66,29 +114,204 @@ describe("TaskChatInteractionCard", () => {container.remove();});- it("renders a pending confirmation as a full interaction card", () => {+ it("does not render a pending confirmation in the timeline", () => {flushSync(() => {root.render(<TooltipProvider><ThemeProvider>- <TaskChatInteractionCard item={interactionItem(createRequestConfirmation())} />- </ThemeProvider>+ <TaskChatInteractionCard+ item={interactionItem(createRequestConfirmation())}+ />+ </ThemeProvider></TooltipProvider>,);});- const card = container.querySelector('[data-testid="task-chat-interaction"]');- expect(card).not.toBeNull();- expect(card?.id).toBe("interaction-confirmation-1");- expect(container.textContent).toContain("Approve the plan");+ const card = container.querySelector(+ '[data-testid="task-chat-interaction"]',+ );+ expect(card).toBeNull();+ expect(container.textContent).not.toContain("Requested confirmation");+ expect(container.textContent).not.toContain("waiting for response");+ expect(container.textContent).not.toContain("Approve the plan?");+ });++ it("renders a plan confirmation as a linked document preview", () => {+ const interaction = createRequestConfirmation({+ sourceRunId: "run-plan",+ title: "Review plan revision 3",+ payload: {+ version: 1,+ prompt: "Approve plan revision 3?",+ acceptLabel: "Approve plan",+ target: {+ type: "issue_document",+ issueId: "issue-1",+ documentId: "document-plan",+ key: "plan",+ revisionId: "revision-3",+ revisionNumber: 3,+ label: "Plan v3",+ },+ },+ });+ const planDocument = {+ id: "document-plan",+ issueId: "issue-1",+ key: "plan",+ title: "Plan",+ body: "# Health-check endpoint\n1. Define the health response contract.\n2. Test readiness before and after startup.\n3. Document the verification request.",+ latestRevisionId: "revision-3",+ latestRevisionNumber: 3,+ } as IssueDocument;++ flushSync(() => {+ root.render(+ <TooltipProvider>+ <ThemeProvider>+ <TaskChatInteractionCard+ item={interactionItem(interaction)}+ planDocument={planDocument}+ />+ </ThemeProvider>+ </TooltipProvider>,+ );+ });++ const preview = container.querySelector(+ '[data-testid="plan-review-preview"]',+ );+ expect(preview?.getAttribute("href")).toBe("#document-plan");+ expect(preview?.getAttribute("aria-label")).toBe("Open Plan revision 3");+ expect(container.textContent).toContain("Health-check endpoint");+ expect(container.textContent).toContain(+ "Test readiness before and after startup.",+ );+ expect(container.textContent).not.toContain("Approve plan revision 3?");+ expect(container.textContent).not.toContain("Approve plan");+ expect(container.textContent).not.toContain("Requested plan review");});- it("puts the primary CTA on the right via a reversed action row", () => {+ it("renders a runner-owned expired plan review as a receipt without a second preview", () => {+ const interaction = createRequestConfirmation({+ sourceRunId: "run-plan",+ status: "expired",+ title: "Review plan revision 3",+ payload: {+ version: 1,+ prompt: "Approve plan revision 3?",+ target: {+ type: "issue_document",+ issueId: "issue-1",+ documentId: "document-plan",+ key: "plan",+ revisionId: "revision-3",+ label: "Plan v3",+ },+ },+ result: {+ version: 1,+ outcome: "superseded_by_comment",+ commentId: "comment-1",+ },+ });+ const planDocument = {+ id: "document-plan",+ issueId: "issue-1",+ key: "plan",+ title: "Plan",+ body: "# Health-check endpoint",+ latestRevisionId: "revision-3",+ latestRevisionNumber: 3,+ } as IssueDocument;+flushSync(() => {root.render(<TooltipProvider><ThemeProvider>- <TaskChatInteractionCard item={interactionItem(createRequestConfirmation())} />- </ThemeProvider>+ <TaskChatInteractionCard+ item={interactionItem(interaction)}+ planDocument={planDocument}+ showPlanPreview={false}+ />+ </ThemeProvider>+ </TooltipProvider>,+ );+ });++ expect(+ container.querySelector('[data-testid="plan-review-preview"]'),+ ).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-interaction-receipt"]'),+ ).not.toBeNull();+ expect(container.textContent).toContain(+ "Confirmation expired after comment",+ );+ });++ it("does not put the latest plan body into an older revision receipt", () => {+ const interaction = createRequestConfirmation({+ status: "expired",+ payload: {+ version: 1,+ prompt: "Approve plan revision 2?",+ target: {+ type: "issue_document",+ issueId: "issue-1",+ documentId: "document-plan",+ key: "plan",+ revisionId: "revision-2",+ label: "Plan revision 2",+ },+ },+ result: {+ version: 1,+ outcome: "superseded_by_comment",+ commentId: "comment-1",+ },+ });+ const currentPlan = {+ id: "document-plan",+ issueId: "issue-1",+ key: "plan",+ title: "Plan",+ body: "# Revision 3 only\nThis must not appear in the revision 2 receipt.",+ latestRevisionId: "revision-3",+ latestRevisionNumber: 3,+ } as IssueDocument;++ flushSync(() => {+ root.render(+ <TooltipProvider>+ <ThemeProvider>+ <TaskChatInteractionCard+ item={interactionItem(interaction)}+ planDocument={currentPlan}+ />+ </ThemeProvider>+ </TooltipProvider>,+ );+ });++ expect(+ container.querySelector('[data-testid="plan-review-preview"]'),+ ).not.toBeNull();+ expect(container.textContent).not.toContain("Revision 3 only");+ expect(container.textContent).toContain(+ "Confirmation expired after comment",+ );+ });++ it("puts the primary CTA at the right edge of the compact action row", () => {+ flushSync(() => {+ root.render(+ <TooltipProvider>+ <ThemeProvider>+ <TaskChatInteractionCard+ item={interactionItem(createRequestConfirmation())}+ presentation="takeover"+ />+ </ThemeProvider></TooltipProvider>,);});@@ -99,43 +322,511 @@ describe("TaskChatInteractionCard", () => {expect(reject).not.toBeUndefined();const row = approve?.parentElement;expect(row).toBe(reject?.parentElement);- expect(row?.className).toContain("flex-row-reverse");+ expect(Array.from(row?.querySelectorAll("button") ?? []).at(-1)).toBe(+ approve,+ );+ expect(container.textContent).not.toContain("proposed by");+ expect(container.textContent).not.toContain(+ "Review and approve the latest plan.",+ );+ expect(container.textContent).not.toContain("Needs response");+ expect(container.textContent).not.toContain("Anyone can respond");+ expect(+ container.querySelector('[data-testid="interaction-status-badge"]'),+ ).toBeNull();});- it("demotes an expired confirmation to a marker row", () => {+ it("keeps the plan revision in the header and hides the prompt while requesting changes", async () => {+ const interaction = createRequestConfirmation({+ sourceRunId: "run-plan",+ title: "Review the proposed plan",+ payload: {+ version: 1,+ prompt: "Do you accept this plan?",+ acceptLabel: "Approve plan",+ rejectLabel: "Request changes",+ rejectRequiresReason: true,+ rejectReasonLabel: "What should change?",+ target: {+ type: "issue_document",+ issueId: "issue-1",+ documentId: "document-plan",+ key: "plan",+ revisionId: "revision-4",+ revisionNumber: 4,+ },+ },+ });+flushSync(() => {root.render(<TooltipProvider><ThemeProvider>- <TaskChatInteractionCard- item={interactionItem(createRequestConfirmation({ status: "expired" }))}- />- </ThemeProvider>+ <TaskChatInteractionCard+ item={interactionItem(interaction)}+ presentation="takeover"+ onAcceptInteraction={vi.fn()}+ onRejectInteraction={vi.fn()}+ onUploadImage={vi.fn().mockResolvedValue("/uploads/boat.png")}+ />+ </ThemeProvider></TooltipProvider>,);});- expect(container.querySelector('[data-testid="task-chat-interaction"]')).toBeNull();++ const title = Array.from(container.querySelectorAll("strong")).find(+ (candidate) => candidate.textContent === "Review the proposed plan",+ );+ const revision = Array.from(container.querySelectorAll("span")).find(+ (candidate) => candidate.textContent === "plan · v4",+ );+ expect(title?.parentElement).toBe(revision?.parentElement);+ expect(container.textContent).toContain("Do you accept this plan?");+ expect(container.querySelectorAll(".border-t")).toHaveLength(0);++ const requestChanges = Array.from(+ container.querySelectorAll<HTMLButtonElement>("button"),+ ).find((button) => button.textContent?.trim() === "Request changes");+ await act(async () => requestChanges?.click());++ expect(container.textContent).not.toContain("Do you accept this plan?");+ expect(container.textContent).toContain("What should change?");+ expect(container.textContent).toContain("plan · v4");+ expect(+ container.querySelector('[data-testid="plan-revision-composer"]'),+ ).not.toBeNull();+ expect(+ container+ .querySelector('[data-testid="mock-markdown-editor"]')+ ?.getAttribute("data-image-upload"),+ ).toBe("true");+ expect(container.textContent).toContain("Attach image");+ expect(container.textContent).toContain("drop/paste an image");+ const reasonGroup = container.querySelector(+ '[data-testid="plan-revision-composer"]',+ )?.parentElement;+ expect(reasonGroup?.className).toContain("space-y-2");+ expect(reasonGroup?.className).not.toContain("mt-3");+ });++ it("shows one question at a time and preserves answers across pages", async () => {+ const submit = vi.fn();+ flushSync(() => {+ root.render(+ <TooltipProvider>+ <ThemeProvider>+ <TaskChatInteractionCard+ item={interactionItem(pendingAskUserQuestionsInteraction)}+ presentation="takeover"+ onSubmitInteractionAnswers={submit}+ />+ </ThemeProvider>+ </TooltipProvider>,+ );+ });++ expect(container.textContent).toContain("1 of 2");+ expect(container.textContent).not.toContain("Choose one");+ expect(container.textContent).toContain("How aggressive should");+ expect(container.textContent).not.toContain(+ "What should the answered-state card emphasize",+ );++ const firstAnswer = Array.from(container.querySelectorAll("button")).find(+ (button) =>+ button.textContent?.includes("Only collapse hidden descendants"),+ );+ await act(async () => firstAnswer?.click());++ expect(container.textContent).toContain("2 of 2");+ expect(container.textContent).toContain(+ "What should the answered-state card emphasize",+ );+ expect(container.textContent).not.toContain("How aggressive should");++ const secondAnswer = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.includes("Inline answer pills"),+ );+ await act(async () => secondAnswer?.click());+ const send = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.trim() === "Send answers",+ );+ await act(async () => send?.click());++ expect(submit).toHaveBeenCalledOnce();+ expect(submit.mock.calls[0]?.[1]).toEqual([+ { questionId: "collapse-depth", optionIds: ["visible-root"] },+ { questionId: "post-submit-summary", optionIds: ["answers-inline"] },+ ]);+ });++ it("collapses answered questions to one expandable timeline row", () => {+ const answered = structuredClone(pendingAskUserQuestionsInteraction);+ answered.status = "answered";+ answered.resolvedAt = new Date("2026-08-24T13:30:00.000Z");+ answered.result = {+ version: 1,+ answers: [{ questionId: "collapse-depth", optionIds: ["visible-root"] }],+ };+ flushSync(() => {+ root.render(+ <TooltipProvider>+ <ThemeProvider>+ <TaskChatInteractionCard item={interactionItem(answered)} />+ </ThemeProvider>+ </TooltipProvider>,+ );+ });++ const receipt = container.querySelector<HTMLDetailsElement>(+ '[data-testid="task-chat-answered-questions-receipt"]',+ );+ expect(receipt?.open).toBe(false);+ expect(receipt?.querySelector("summary")?.textContent).toBe(+ "Questions answered",+ );+ expect(receipt?.querySelectorAll("summary svg")).toHaveLength(2);+ expect(receipt?.className).not.toContain("border");+ expect(receipt?.className).not.toContain("bg-card");+ expect(receipt?.querySelector("summary")?.className).toContain("px-1");+ expect(receipt?.querySelector("summary")?.className).toContain(+ "text-muted-foreground",+ );+ expect(receipt?.querySelector("summary")?.className).toContain("leading-5");+ expect(receipt?.querySelector("summary span")?.className).not.toContain(+ "font-medium",+ );+ expect(+ receipt+ ?.querySelector('[data-testid="task-chat-interaction-receipt-icon"]')+ ?.classList.contains("h-3.5"),+ ).toBe(true);+ const iconSlot = receipt?.querySelector(+ '[data-testid="task-chat-interaction-receipt-icon-slot"]',+ );+ expect(iconSlot?.classList.contains("w-6")).toBe(true);+ expect(iconSlot?.classList.contains("items-center")).toBe(true);+ expect(iconSlot?.classList.contains("justify-center")).toBe(true);+ const caret = receipt?.querySelector(+ '[data-testid="task-chat-interaction-receipt-caret"]',+ );+ expect(caret?.classList.contains("h-3")).toBe(true);+ expect(caret?.classList.contains("opacity-0")).toBe(true);+ expect(caret?.getAttribute("class")).toContain("group-hover:opacity-70");+ expect(container.textContent).not.toContain("Answered 2 questions");+ expect(container.textContent).not.toContain(+ "View original request and resolution",+ );+ expect(container.textContent).not.toContain("Options:");+ expect(container.textContent).not.toContain("Asked by:");+ expect(container.textContent).not.toContain("Resolved by:");+ });++ it("collapses accepted confirmations and selections to one borderless row", () => {+ const acceptedConfirmation = createRequestConfirmation({+ status: "accepted",+ resolvedAt: new Date("2026-08-24T13:30:00.000Z"),+ result: { version: 1, outcome: "accepted" },+ });+ const acceptedSelection = structuredClone(+ pendingRequestCheckboxConfirmationInteraction,+ );+ acceptedSelection.status = "accepted";+ acceptedSelection.resolvedAt = new Date("2026-08-24T13:31:00.000Z");+ acceptedSelection.result = {+ version: 1,+ outcome: "accepted",+ selectedOptionIds: [],+ };++ flushSync(() => {+ root.render(+ <TooltipProvider>+ <ThemeProvider>+ <>+ <TaskChatInteractionCard+ item={interactionItem(acceptedConfirmation)}+ />+ <TaskChatInteractionCard+ item={interactionItem(acceptedSelection)}+ />+ </>+ </ThemeProvider>+ </TooltipProvider>,+ );+ });++ const receipts = container.querySelectorAll<HTMLDetailsElement>(+ '[data-testid="task-chat-interaction-receipt"]',+ );+ expect(receipts).toHaveLength(2);+ expect(receipts[0]?.querySelector("summary")?.textContent).toBe(+ "Confirmed request",+ );+ expect(receipts[1]?.querySelector("summary")?.textContent).toBe(+ "Confirmed with no options selected",+ );+ for (const receipt of receipts) {+ expect(receipt.open).toBe(false);+ expect(receipt.className).not.toContain("border");+ expect(receipt.className).not.toContain("bg-card");+ }+ expect(container.textContent).not.toContain("Asked by:");+ expect(container.textContent).not.toContain("Outcome:");+ });++ it("reuses the question form for a recovered harness text request", async () => {+ const submit = vi.fn();+ const recovered = structuredClone(pendingAskUserQuestionsInteraction);+ recovered.id = "recovered-runtime-question";+ recovered.title = "Configure deployment";+ recovered.payload = {+ version: 1,+ supersedeOnUserComment: false,+ submitLabel: "Continue",+ questions: [+ {+ id: "replicas",+ prompt: "How many replicas?",+ selectionMode: "single",+ required: true,+ options: [+ {+ id: "__paperclip_text__",+ label: "Enter an integer",+ freeText: true,+ },+ ],+ },+ ],+ questionSet: {+ schema: "paperclip.question_set.v1",+ title: "Configure deployment",+ description: "The provider disconnected while waiting for this answer.",+ submitLabel: "Continue",+ questions: [+ {+ id: "replicas",+ header: "Replicas",+ prompt: "How many replicas?",+ required: true,+ answerMode: "text",+ textValidation: { inputType: "integer", minimum: 1, maximum: 10 },+ },+ ],+ },+ };+ flushSync(() => {+ root.render(+ <TooltipProvider>+ <ThemeProvider>+ <TaskChatInteractionCard+ item={interactionItem(recovered)}+ presentation="takeover"+ onSubmitInteractionAnswers={submit}+ />+ </ThemeProvider>+ </TooltipProvider>,+ );+ });++ expect(container.textContent).toContain(+ "The provider disconnected while waiting for this answer.",+ );+ expect(container.textContent).toContain("Write an answer");+ expect(container.textContent).not.toContain("Required");+ const textarea = container.querySelector("textarea")!;+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(+ HTMLTextAreaElement.prototype,+ "value",+ )?.set;+ setter?.call(textarea, "3");+ textarea.dispatchEvent(new Event("input", { bubbles: true }));+ });+ const send = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.trim() === "Continue",+ );+ await act(async () => send?.click());++ expect(submit).toHaveBeenCalledWith(recovered, [+ {+ questionId: "replicas",+ optionIds: [],+ otherText: "3",+ },+ ]);+ });++ it("paginates item verdicts instead of expanding the whole review set", async () => {+ flushSync(() => {+ root.render(+ <TooltipProvider>+ <ThemeProvider>+ <TaskChatInteractionCard+ item={interactionItem(pendingRequestItemVerdictsInteraction)}+ presentation="takeover"+ onSubmitInteractionVerdicts={() => undefined}+ />+ </ThemeProvider>+ </TooltipProvider>,+ );+ });++ expect(container.textContent).toContain("1 of 5");+ expect(container.textContent).toContain("Spring launch recap");+ expect(container.textContent).not.toContain("Monthly changelog digest");+ expect(+ container.querySelector('[aria-label="Item pagination"]'),+ ).not.toBeNull();++ const approve = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.trim() === "approve",+ );+ const rejectOnFirstItem = Array.from(+ container.querySelectorAll("button"),+ ).find((button) => button.textContent?.trim() === "reject");+ expect(approve?.className).toContain("text-emerald-700");+ expect(rejectOnFirstItem?.className).toContain("text-destructive");+ expect(approve?.querySelector("svg")).not.toBeNull();+ expect(rejectOnFirstItem?.querySelector("svg")).not.toBeNull();+ await act(async () => approve?.click());++ expect(container.textContent).toContain("2 of 5");+ expect(container.textContent).toContain("Monthly changelog digest");+ expect(container.textContent).not.toContain("Spring launch recap");++ const reject = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.trim() === "reject",+ );+ await act(async () => reject?.click());+ expect(container.textContent).toContain("Why reject?");+ expect(container.textContent).toContain("Submit rejection reason");+ expect(container.textContent).toContain("2 of 5");+ expect(+ container.querySelector<HTMLButtonElement>('[aria-label="Next item"]')+ ?.disabled,+ ).toBe(true);++ const textarea = container.querySelector("textarea")!;+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(+ HTMLTextAreaElement.prototype,+ "value",+ )?.set;+ setter?.call(textarea, "Needs a warmer introduction.");+ textarea.dispatchEvent(new Event("input", { bubbles: true }));+ });+ expect(+ container.querySelector<HTMLButtonElement>('[aria-label="Next item"]')+ ?.disabled,+ ).toBe(true);+ const submitReason = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.trim() === "Submit rejection reason",+ );+ await act(async () => submitReason?.click());+ expect(container.textContent).toContain("3 of 5");+ expect(container.textContent).toContain("Founder's note on reliability");+ });++ it("collapses an expired confirmation receipt at the request position", () => {+ flushSync(() => {+ root.render(+ <TooltipProvider>+ <ThemeProvider>+ <TaskChatInteractionCard+ item={interactionItem(+ createRequestConfirmation({ status: "expired" }),+ )}+ />+ </ThemeProvider>+ </TooltipProvider>,+ );+ });+ const receipt = container.querySelector<HTMLDetailsElement>(+ '[data-testid="task-chat-interaction-receipt"]',+ );+ expect(receipt).not.toBeNull();+ expect(receipt?.open).toBe(false);expect(container.textContent).toContain("Approve the plan");expect(container.textContent).toContain("expired");+ expect(container.textContent).toContain("Approve the plan?");+ expect(receipt?.querySelector("summary")?.textContent).toBe(+ "Confirmation expired",+ );+ expect(container.textContent).not.toContain(+ "View original request and resolution",+ );});- it("renders an expired secret proposal as a full receipt", () => {+ it("keeps security details inside an expandable expired receipt", () => {flushSync(() => {root.render(<TooltipProvider><ThemeProvider>- <TaskChatInteractionCard item={interactionItem(expiredSecretProposalInteraction)} />+ <TaskChatInteractionCard+ item={interactionItem(expiredSecretProposalInteraction)}+ /></ThemeProvider></TooltipProvider>,);});- expect(container.querySelector('[data-testid="task-chat-interaction"]')).not.toBeNull();- expect(container.textContent).toContain("Secret binding requested");+ expect(+ container.querySelector('[data-testid="task-chat-interaction-receipt"]'),+ ).not.toBeNull();+ expect(container.textContent).toContain("Confirmation expired");expect(container.textContent).toContain("OpenAI API key");expect(container.textContent).toContain("access.evals_openai_api_key");expect(container.textContent).toContain("EvalsEngineer");- expect(container.textContent).toContain("A fresh proposal is required");+ expect(container.textContent).not.toContain("Asked by:");+ expect(container.textContent).not.toContain("Resolved:");+ expect(container.textContent).not.toContain("Outcome:");+ });++ it("keeps skipped confirmation context, actor metadata, and terminal reason expandable", () => {+ const skipped = createRequestConfirmation({+ status: "cancelled",+ resolvedByUserId: "user-1",+ resolvedAt: new Date("2026-04-06T12:05:00.000Z"),+ result: {+ version: 1,+ outcome: "skipped",+ reason: "I want to write a normal message.",+ },+ });+ flushSync(() => {+ root.render(+ <TooltipProvider>+ <ThemeProvider>+ <TaskChatInteractionCard+ item={interactionItem(skipped)}+ agentMap={+ new Map([+ ["agent-1", { id: "agent-1", name: "Planner" }],+ ]) as never+ }+ userLabelMap={new Map([["user-1", "Riley"]])}+ />+ </ThemeProvider>+ </TooltipProvider>,+ );+ });++ const receipt = container.querySelector<HTMLDetailsElement>(+ '[data-testid="task-chat-interaction-receipt"]',+ );+ expect(receipt?.open).toBe(false);+ expect(receipt?.querySelector("summary")?.textContent).toBe(+ "Skipped interaction",+ );+ expect(container.textContent).toContain("Approve the plan?");+ expect(container.textContent).not.toContain("Asked by:");+ expect(container.textContent).not.toContain("Resolved by:");+ expect(container.textContent).not.toContain("Outcome:");+ expect(container.textContent).toContain(+ "I want to write a normal message.",+ );});});@@ -155,21 +846,41 @@ describe("TaskChatThreadView interaction items", () => {});it("renders interaction items through renderInteraction", () => {- const item = interactionItem(createRequestConfirmation());+ const item = interactionItem(+ createRequestConfirmation({+ status: "accepted",+ result: { version: 1, outcome: "accepted" },+ }),+ );flushSync(() => {root.render(<TooltipProvider><ThemeProvider>- <TaskChatThreadView- items={[item]}- scroll={false}- renderInteraction={(it) => <TaskChatInteractionCard item={it} />}- />- </ThemeProvider>+ <TaskChatThreadView+ items={[+ {+ id: "turn-boundary",+ kind: "marker",+ variant: "turn_boundary",+ label: "Earlier activity",+ },+ item,+ ]}+ scroll={false}+ renderInteraction={(it) => <TaskChatInteractionCard item={it} />}+ />+ </ThemeProvider></TooltipProvider>,);});- expect(container.querySelector('[data-testid="task-chat-interaction"]')).not.toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-interaction"]'),+ ).not.toBeNull();+ expect(+ container+ .querySelector('[data-testid="task-chat-interaction"]')+ ?.parentElement?.classList.contains("-mt-3"),+ ).toBe(true);});it("renders nothing for interaction items without renderInteraction", () => {@@ -178,11 +889,13 @@ describe("TaskChatThreadView interaction items", () => {root.render(<TooltipProvider><ThemeProvider>- <TaskChatThreadView items={[item]} scroll={false} />- </ThemeProvider>+ <TaskChatThreadView items={[item]} scroll={false} />+ </ThemeProvider></TooltipProvider>,);});- expect(container.querySelector('[data-testid="task-chat-interaction"]')).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-interaction"]'),+ ).toBeNull();});});diff --git a/ui/src/components/task-chat/TaskChatInteractionCard.tsx b/ui/src/components/task-chat/TaskChatInteractionCard.tsxindex 8f2ee829b8..1901bfdfea 100644--- a/ui/src/components/task-chat/TaskChatInteractionCard.tsx+++ b/ui/src/components/task-chat/TaskChatInteractionCard.tsx@@ -1,41 +1,118 @@import type { ComponentProps } from "react";+import type { IssueDocument } from "@paperclipai/shared";+import type { MentionOption } from "@/components/MarkdownEditor";import { IssueThreadInteractionCard } from "@/components/IssueThreadInteractionCard";-import { TaskChatMarker } from "./TaskChatMarker";+import { shouldHideInteractionCard } from "@/lib/issue-thread-interactions";+import { TaskChatCompactInteractionCard } from "./TaskChatCompactInteractionCard";+import { TaskChatPlanPreviewCard } from "./TaskChatPlanPreviewCard";import type { TaskChatInteractionItem } from "./task-chat-model";-type InteractionCardProps = Omit<ComponentProps<typeof IssueThreadInteractionCard>, "interaction">;+type InteractionCardProps = Omit<+ ComponentProps<typeof IssueThreadInteractionCard>,+ "interaction"+>;export interface TaskChatInteractionCardProps extends InteractionCardProps {item: TaskChatInteractionItem;+ planDocument?: IssueDocument | null;+ showPlanPreview?: boolean;+ presentation?: "timeline" | "takeover";+ draftKey?: string;+ mentions?: MentionOption[];}/**- * v7-grammar wrapper for issue-thread interactions (plan confirmation,- * question card, suggested tasks…) inside the redesigned thread: cards are the- * only rows that get bubble-level emphasis, so the shared- * IssueThreadInteractionCard renders full-width with the standard bubble- * entrance. Generic expired confirmations demote to a marker row — superseded- * asks are history, not calls to action (legacy-thread parity). Secret proposals- * remain full receipts because their safe binding metadata and recovery guidance- * are part of the terminal outcome.+ * Task-page presentation for durable issue interactions. The new task view uses+ * a compact, protocol-card-aligned renderer with paginated questions and+ * verdicts; the classic issue thread keeps its existing card. Resolved inputs+ * collapse to one receipt row, with security and audit details preserved in the+ * disclosure.*/-export function TaskChatInteractionCard({ item, ...cardProps }: TaskChatInteractionCardProps) {+export function TaskChatInteractionCard({+ item,+ planDocument,+ showPlanPreview = true,+ presentation = "timeline",+ draftKey,+ ...cardProps+}: TaskChatInteractionCardProps) {const interaction = item.interaction;- if (- interaction.kind === "request_confirmation"- && interaction.status === "expired"- && !interaction.payload.secretProposal- ) {+ const isSupersededQuestionReceipt =+ interaction.kind === "ask_user_questions" &&+ interaction.status !== "pending" &&+ interaction.result?.expirationReason === "superseded_by_newer_interaction";+ if (shouldHideInteractionCard(interaction) && !isSupersededQuestionReceipt)+ return null;+ if (presentation === "timeline" && interaction.status === "pending") {+ const isPlanReview =+ interaction.kind === "request_confirmation" &&+ Boolean(interaction.sourceRunId) &&+ interaction.payload.target?.type === "issue_document" &&+ interaction.payload.target.key === "plan" &&+ Boolean(planDocument) &&+ (planDocument?.latestRevisionId+ ? interaction.payload.target.revisionId ===+ planDocument.latestRevisionId+ : interaction.payload.target.revisionNumber ===+ planDocument?.latestRevisionNumber);+ if (!isPlanReview || !showPlanPreview) return null;return (- <TaskChatMarker- item={{- id: item.id,- kind: "marker",- variant: "turn_boundary",- label: interaction.title ?? "Confirmation",- detail: "expired",- }}- />+ <div+ id={`interaction-${interaction.id}`}+ data-testid="task-chat-interaction"+ >+ <TaskChatPlanPreviewCard+ source={{ kind: "saved", document: planDocument }}+ testId="plan-review-preview"+ />+ </div>+ );+ }+ const isResolvedPlanReview =+ presentation === "timeline" &&+ interaction.kind === "request_confirmation" &&+ (interaction.status === "accepted" || interaction.status === "rejected") &&+ interaction.payload.target?.type === "issue_document" &&+ interaction.payload.target.key === "plan";+ const resolvedPlanMatchesDocument =+ isResolvedPlanReview &&+ planDocument != null &&+ (planDocument.latestRevisionId+ ? interaction.payload.target?.revisionId === planDocument.latestRevisionId+ : interaction.payload.target?.revisionNumber ===+ planDocument.latestRevisionNumber);+ if (isResolvedPlanReview) {+ if (resolvedPlanMatchesDocument && showPlanPreview && planDocument) {+ return (+ <div+ id={`interaction-${interaction.id}`}+ data-testid="task-chat-interaction"+ >+ <TaskChatPlanPreviewCard+ source={{ kind: "saved", document: planDocument }}+ testId="plan-review-preview"+ />+ </div>+ );+ }+ return null;+ }+ if (presentation === "timeline" && interaction.status !== "pending") {+ return (+ <div+ id={`interaction-${interaction.id}`}+ className="tc-enter-bubble w-full"+ data-testid="task-chat-interaction"+ >+ <TaskChatCompactInteractionCard+ interaction={interaction}+ planDocument={planDocument}+ showPlanPreview={showPlanPreview}+ presentation="timeline"+ draftKey={draftKey}+ {...cardProps}+ />+ </div>);}return (@@ -44,7 +121,14 @@ export function TaskChatInteractionCard({ item, ...cardProps }: TaskChatInteractclassName="tc-enter-bubble w-full"data-testid="task-chat-interaction">- <IssueThreadInteractionCard interaction={interaction} primaryActionOnRight {...cardProps} />+ <TaskChatCompactInteractionCard+ interaction={interaction}+ planDocument={planDocument}+ showPlanPreview={showPlanPreview}+ presentation={presentation}+ draftKey={draftKey}+ {...cardProps}+ /></div>);}diff --git a/ui/src/components/task-chat/TaskChatLiveRunPill.test.tsx b/ui/src/components/task-chat/TaskChatLiveRunPill.test.tsxindex 7e30ca0871..4f43289f8d 100644--- a/ui/src/components/task-chat/TaskChatLiveRunPill.test.tsx+++ b/ui/src/components/task-chat/TaskChatLiveRunPill.test.tsx@@ -89,4 +89,5 @@ describe("TaskChatLiveRunPill", () => {expect(pill?.textContent).toContain("for 42 seconds");expect(pill?.textContent).toContain("ran 1 command");});+});diff --git a/ui/src/components/task-chat/TaskChatLiveRunPill.tsx b/ui/src/components/task-chat/TaskChatLiveRunPill.tsxindex ca9fff787d..cf033f08bf 100644--- a/ui/src/components/task-chat/TaskChatLiveRunPill.tsx+++ b/ui/src/components/task-chat/TaskChatLiveRunPill.tsx@@ -62,7 +62,9 @@ export function TaskChatLiveRunPill({const elapsedMs =startedAtMs == null ? null : (active ? Date.now() : finishedAtMs ?? Date.now()) - startedAtMs;- const elapsed = elapsedMs != null ? formatDurationWords(elapsedMs) : null;+ const elapsed = elapsedMs != null+ ? formatDurationWords(elapsedMs)+ : null;const verb = active ? "Working" : "Worked";const suffix = elapsed ? `for ${elapsed}` : null;diff --git a/ui/src/components/task-chat/TaskChatLiveTail.test.tsx b/ui/src/components/task-chat/TaskChatLiveTail.test.tsxindex 57c4c20bb4..b38466f953 100644--- a/ui/src/components/task-chat/TaskChatLiveTail.test.tsx+++ b/ui/src/components/task-chat/TaskChatLiveTail.test.tsx@@ -53,14 +53,13 @@ describe("TaskChatLiveTail", () => {"Looking into the failing test.",);const phaseSummary = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-phase-summary"]');- expect(phaseSummary?.getAttribute("aria-expanded")).toBe("false");- flushSync(() => phaseSummary!.click());+ expect(phaseSummary?.getAttribute("aria-expanded")).toBe("true");// Tool row renders with its name + mono target.expect(container.textContent).toContain("Read");expect(container.textContent).toContain("src/app.ts");});- it("renders a tool's diff inset", () => {+ it("keeps tool diff bodies out of the activity feed", () => {const items = parse([{ kind: "tool_call", ts: TS, name: "Edit", toolUseId: "t1", input: { file_path: "a.ts" } },{ kind: "diff", ts: TS, changeType: "add", text: "const x = 1;" },@@ -69,10 +68,17 @@ describe("TaskChatLiveTail", () => {render(items);const phaseSummary = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-phase-summary"]');- expect(phaseSummary?.getAttribute("aria-expanded")).toBe("false");- flushSync(() => phaseSummary!.click());- expect(container.textContent).toContain("const x = 1;");+ expect(phaseSummary?.getAttribute("aria-expanded")).toBe("true");+ expect(container.textContent).not.toContain("const x = 1;");+ expect(container.textContent).not.toContain("+1 −1");++ const tool = container.querySelector<HTMLButtonElement>(".tc-enter-tool button");+ expect(tool).not.toBeNull();+ flushSync(() => tool?.click());+expect(container.textContent).toContain("+1 −1");+ expect(container.textContent).not.toContain("const x = 1;");+ expect(container.querySelector('[data-testid="task-chat-tool-change-summary"]')).not.toBeNull();});it("drops the debug plumbing kinds RunTranscriptView surfaced", () => {@@ -105,8 +111,7 @@ describe("TaskChatLiveTail", () => {"Here is the real reply.",);const phaseSummary = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-phase-summary"]');- expect(phaseSummary?.getAttribute("aria-expanded")).toBe("false");- flushSync(() => phaseSummary!.click());+ expect(phaseSummary?.getAttribute("aria-expanded")).toBe("true");const text = container.textContent ?? "";expect(text).toContain("Here is the real reply.");expect(text).toContain("pnpm test");@@ -125,15 +130,91 @@ describe("TaskChatLiveTail", () => {}});- it("does not render a thinking row (its signal is the status pill)", () => {+ it("renders provider-supplied reasoning in the live activity stream", () => {const items = parse([- { kind: "thinking", ts: TS, text: "SECRET internal reasoning" },+ { kind: "thinking", ts: TS, text: "Provider reasoning summary" },{ kind: "assistant", ts: TS, text: "Visible answer." },]);+ expect(items[0]).toMatchObject({ kind: "thinking", streaming: false });render(items);expect(container.textContent).toContain("Visible answer.");- expect(container.textContent).not.toContain("SECRET internal reasoning");+ const reasoningPhase = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-phase-summary"]',+ );+ expect(reasoningPhase?.textContent).toContain("Reasoning");+ expect(reasoningPhase?.getAttribute("aria-expanded")).toBe("true");++ expect(container.textContent).toContain("Provider reasoning summary");+ const thinking = container.querySelector('[data-testid="task-chat-thinking"]');+ expect(thinking?.getAttribute("data-state")).toBe("settled");+ expect(+ thinking?.querySelector('[data-testid="task-chat-thinking-text"]')+ ?.textContent,+ ).toContain("Provider reasoning summary");+ const phaseChildren = thinking?.closest(+ '[data-testid="task-chat-phase-children"]',+ );+ expect(phaseChildren?.classList.contains("ml-2.5")).toBe(true);+ expect(phaseChildren?.classList.contains("pl-6")).toBe(true);+ expect(+ phaseChildren?.querySelector('[data-testid="task-chat-phase-child-rail"]'),+ ).not.toBeNull();+ expect(thinking?.textContent).not.toContain("Reasoning");+ expect(thinking?.querySelector(".shimmer-text")).toBeNull();+ expect(+ thinking+ ?.querySelector('[data-testid="task-chat-thinking-icon"]')+ ?.classList.contains("text-(--status-agent-running)"),+ ).toBe(false);+ expect(+ thinking+ ?.querySelector('[data-testid="task-chat-thinking-icon"]')+ ?.classList.contains("text-muted-foreground/50"),+ ).toBe(true);+ expect(thinking?.querySelector(".task-chat-reasoning-markdown")).toBeNull();+ });++ it("bounds long tool targets and wraps the full value only when expanded", () => {+ const longPath =+ "/Users/dotta/paperclip/instances/default/companies/company-id/codex/home/skills/paperclip/references/API-reference.md";+ const items = parse([+ {+ kind: "tool_call",+ ts: TS,+ name: "Read",+ toolUseId: "long-read",+ input: { file_path: longPath },+ },+ ]);+ const renderedTarget = items+ .flatMap((item) =>+ item.kind === "activity_phase" ? item.items : [item],+ )+ .find((item) => item.kind === "tool")?.target;+ render(items);++ const tool = container.querySelector<HTMLButtonElement>(+ ".tc-enter-tool button",+ );+ const collapsedTarget = tool?.querySelector(+ ".task-chat-collapsed-line-fade",+ );+ expect(tool?.classList.contains("overflow-hidden")).toBe(true);+ expect(tool?.getAttribute("aria-expanded")).toBe("false");+ expect(renderedTarget).toBeTruthy();+ expect(collapsedTarget?.textContent).toBe(renderedTarget);++ flushSync(() => tool?.click());++ const expandedTarget = container.querySelector(+ '[data-testid="task-chat-tool-target-detail"]',+ );+ expect(tool?.getAttribute("aria-expanded")).toBe("true");+ expect(expandedTarget?.textContent).toBe(renderedTarget);+ expect(+ expandedTarget?.classList.contains("task-chat-expanded-line-wrap"),+ ).toBe(true);});it("shows the empty message when nothing renderable has streamed yet", () => {diff --git a/ui/src/components/task-chat/TaskChatLiveTail.tsx b/ui/src/components/task-chat/TaskChatLiveTail.tsxindex 2bb9eb8514..2a84e119f6 100644--- a/ui/src/components/task-chat/TaskChatLiveTail.tsx+++ b/ui/src/components/task-chat/TaskChatLiveTail.tsx@@ -1,10 +1,14 @@import type { ReactElement } from "react";import { MarkdownBody } from "@/components/MarkdownBody";-import type { TaskChatItem } from "./task-chat-model";+import type { TaskChatItem, TaskChatRuntimeRequestDecision, TaskChatRuntimeRequestItem } from "./task-chat-model";import { TaskChatToolCard } from "./TaskChatToolCard";import { TaskChatUsageReadout } from "./TaskChatUsageReadout";import { TaskChatActivityPhase } from "./TaskChatActivityPhase";-import { buildActivityPhases } from "./transcript-adapter";+import { TaskChatThinking } from "./TaskChatThinking";+import { TaskChatMarker } from "./TaskChatMarker";+import { TaskChatProtocolCard } from "./TaskChatProtocolCard";+import { TaskChatProtocolActivityRow } from "./TaskChatProtocolActivityRow";+import { buildTurnTimelineRows } from "./transcript-adapter";/*** Live-tail body for the experimental chat-style view (PAP-463, Workstream C1@@ -20,20 +24,31 @@ import { buildActivityPhases } from "./transcript-adapter";* no "Streaming" chip, no uppercase "USED TERMINAL" cards. The status pill above* this body (`TaskChatLiveRunPill`) owns the run-status affordance.*- * Stable assistant boundaries compact the rows into activity phases. The- * trailing streaming assistant chunk stays in the status pill's self-talk- * slot, while historical interstitials remain readable above their summaries.+ * Stable assistant and runtime-request boundaries compact the rows into an+ * ordered turn timeline. Commentary remains readable above the activity group+ * it introduced, and resolved request receipts keep their original slot.*/export function TaskChatLiveTail({items,emptyMessage,+ excludeFinal = false,+ onRuntimeRequestDecision,}: {items: readonly TaskChatItem[];/** Shown when nothing renderable has streamed yet (queued / pre-first-token). */emptyMessage?: string;+ /** New-runner turn renders final-answer messages in its dedicated response slot. */+ excludeFinal?: boolean;+ onRuntimeRequestDecision?: (+ item: TaskChatRuntimeRequestItem,+ decision: TaskChatRuntimeRequestDecision,+ ) => void | Promise<void>;}) {- const rows = buildActivityPhases(items, true)- .map((item) => renderTailRow(item))+ const visibleItems = excludeFinal+ ? items.filter((item) => item.kind !== "message" || item.interstitial)+ : items;+ const rows = buildTurnTimelineRows(visibleItems, true)+ .map((item) => renderTailRow(item, onRuntimeRequestDecision)).filter((row): row is ReactElement => row != null);if (rows.length === 0) {@@ -45,7 +60,13 @@ export function TaskChatLiveTail({return <div className="flex flex-col gap-2">{rows}</div>;}-function renderTailRow(item: TaskChatItem): ReactElement | null {+function renderTailRow(+ item: TaskChatItem,+ onRuntimeRequestDecision?: (+ item: TaskChatRuntimeRequestItem,+ decision: TaskChatRuntimeRequestDecision,+ ) => void | Promise<void>,+): ReactElement | null {switch (item.kind) {case "message": {// Streamed reply text (always interstitial from the transcript adapter).@@ -77,18 +98,37 @@ function renderTailRow(item: TaskChatItem): ReactElement | null {<TaskChatUsageReadout item={item} /></div>);+ case "thinking":+ return <TaskChatThinking key={item.id} item={item} />;case "activity_phase":return (<TaskChatActivityPhasekey={item.id}item={item}- renderChild={(child) => child.kind === "tool" ? <TaskChatToolCard item={child} /> : <TaskChatUsageReadout item={child} />}+ defaultOpen={item.items.some(+ (child) =>+ child.kind === "thinking" &&+ child.lines.some((line) => line.trim().length > 0),+ )}+ childrenClassName="relative ml-2.5 pl-6"+ showChildRail+ renderChild={(child) => child.kind === "tool"+ ? <TaskChatToolCard item={child} />+ : child.kind === "thinking"+ ? <TaskChatThinking item={child} />+ : child.kind === "marker"+ ? <TaskChatMarker item={child} />+ : child.kind === "protocol"+ ? child.surface === "runtime_request"+ ? <TaskChatProtocolCard item={child} onRuntimeRequestDecision={onRuntimeRequestDecision} />+ : <TaskChatProtocolActivityRow item={child} />+ : <TaskChatUsageReadout item={child} />}/>);- // Thinking never renders as a row (PAP-361): its live signal is the status- // pill, and the text stays in the run log / classic transcript. Every other- // kind (markers, interactions, briefs, statuses, turns, and the dropped- // debug kinds) cannot appear in a parsed live transcript.+ case "protocol":+ return <TaskChatProtocolCard key={item.id} item={item} onRuntimeRequestDecision={onRuntimeRequestDecision} />;+ // Markers, interactions, briefs, statuses, turns, and dropped debug kinds+ // cannot appear as direct live-tail rows.default:return null;}diff --git a/ui/src/components/task-chat/TaskChatMarker.tsx b/ui/src/components/task-chat/TaskChatMarker.tsxindex 7e4f8062e8..43cb8cd350 100644--- a/ui/src/components/task-chat/TaskChatMarker.tsx+++ b/ui/src/components/task-chat/TaskChatMarker.tsx@@ -1,6 +1,7 @@import { cn } from "@/lib/utils";import { CircleDot, OctagonX, Flag } from "lucide-react";import type { TaskChatMarkerItem } from "./task-chat-model";+import { Button } from "@/components/ui/button";const VARIANT_ICON = {session_start: CircleDot,@@ -13,9 +14,23 @@ const VARIANT_ICON = {* turn boundary) as a recessed rule, never a bubble. Interruptions use a dashed* destructive rule to read as a distinct state.*/-export function TaskChatMarker({ item }: { item: TaskChatMarkerItem }) {+export function TaskChatMarker({+ item,+ onTryAgain,+ tryAgainPending = false,+}: {+ item: TaskChatMarkerItem;+ onTryAgain?: () => Promise<void> | void;+ tryAgainPending?: boolean;+}) {const Icon = VARIANT_ICON[item.variant];const interrupted = item.variant === "interrupted";+ const handleTryAgain = () => {+ void Promise.resolve()+ .then(() => onTryAgain?.())+ // The parent mutation owns visible error feedback.+ .catch(() => undefined);+ };return (<div className="tc-enter-marker flex items-center gap-2 py-1 text-xs text-muted-foreground"><span className={cn("h-px flex-1", interrupted ? "border-t border-dashed border-destructive/50" : "bg-border")} />@@ -23,6 +38,18 @@ export function TaskChatMarker({ item }: { item: TaskChatMarkerItem }) {<Icon className="h-3.5 w-3.5" /><span className="font-medium">{item.label}</span>{item.detail ? <span className="text-muted-foreground">· {item.detail}</span> : null}+ {onTryAgain ? (+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={handleTryAgain}+ disabled={tryAgainPending}+ data-testid="task-chat-run-failed-try-again"+ >+ {tryAgainPending ? "Trying again..." : "Try again"}+ </Button>+ ) : null}</span><span className={cn("h-px flex-1", interrupted ? "border-t border-dashed border-destructive/50" : "bg-border")} /></div>diff --git a/ui/src/components/task-chat/TaskChatPlanPreviewCard.test.tsx b/ui/src/components/task-chat/TaskChatPlanPreviewCard.test.tsxnew file mode 100644index 0000000000..05b97c5ab6--- /dev/null+++ b/ui/src/components/task-chat/TaskChatPlanPreviewCard.test.tsx@@ -0,0 +1,130 @@+// @vitest-environment jsdom++import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import type { IssueDocument } from "@paperclipai/shared";+import { ThemeProvider } from "@/context/ThemeContext";+import {+ planPreviewContent,+ TaskChatPlanPreviewCard,+} from "./TaskChatPlanPreviewCard";+import type { TaskChatProviderActivityItem } from "./task-chat-model";++function planDocument(overrides: Partial<IssueDocument> = {}): IssueDocument {+ return {+ id: "plan-document",+ companyId: "company-1",+ issueId: "issue-1",+ key: "plan",+ title: "Plan",+ format: "markdown",+ body: "# Streaming task UX\n\n## Implementation\n- Extract the shared card.\n2. Stream provider steps.\n3. Reconcile the saved revision.\n4. Verify the mobile layout.",+ latestRevisionId: "plan-revision-4",+ latestRevisionNumber: 4,+ createdByAgentId: "agent-1",+ createdByUserId: null,+ updatedByAgentId: "agent-1",+ updatedByUserId: null,+ lockedAt: null,+ lockedByAgentId: null,+ lockedByUserId: null,+ createdAt: new Date("2026-08-23T10:00:00.000Z"),+ updatedAt: new Date("2026-08-23T10:01:00.000Z"),+ ...overrides,+ };+}++function livePlan(steps: TaskChatProviderActivityItem["steps"]): TaskChatProviderActivityItem {+ return {+ id: "live-plan",+ kind: "protocol",+ surface: "provider_activity",+ family: "plan",+ eventType: "plan.updated",+ status: "running",+ title: "Plan",+ summary: "Implement the streaming UX.",+ details: [{ label: "Revision", value: "5" }],+ steps,+ links: [],+ children: [],+ };+}++describe("TaskChatPlanPreviewCard", () => {+ let container: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ });++ afterEach(() => {+ act(() => root.unmount());+ container.remove();+ });++ it("extracts the Markdown H1 and the first three meaningful plan lines", () => {+ expect(planPreviewContent("# Ship it\n\n---\n## Build\n- **First** step\n2. Use [the docs](https://example.com)\n```\nFourth"))+ .toEqual({ title: "Ship it", preview: ["Build", "First step", "Use the docs"] });+ });++ it("renders a saved revision as a Plan-pane link", () => {+ act(() => root.render(+ <ThemeProvider>+ <TaskChatPlanPreviewCard source={{ kind: "saved", document: planDocument() }} />+ </ThemeProvider>,+ ));++ const preview = container.querySelector('[data-testid="task-chat-plan-preview"]');+ expect(preview?.getAttribute("href")).toBe("#document-plan");+ expect(preview?.getAttribute("aria-label")).toBe("Open Plan revision 4");+ expect(preview?.textContent).toContain("Plan· rev 4");+ expect(preview?.textContent).toContain("Streaming task UX");+ expect(preview?.textContent).toContain("Extract the shared card.");+ expect(preview?.textContent).not.toContain("Verify the mobile layout.");+ });++ it("replaces saved preview content when the canonical revision updates", () => {+ const render = (document: IssueDocument) => act(() => root.render(+ <ThemeProvider>+ <TaskChatPlanPreviewCard source={{ kind: "saved", document }} />+ </ThemeProvider>,+ ));+ render(planDocument());+ render(planDocument({+ body: "# Revised streaming UX\n- Preserve final-answer streaming.\n- Preserve provider redaction.",+ latestRevisionId: "plan-revision-5",+ latestRevisionNumber: 5,+ }));++ expect(container.querySelectorAll('[data-testid="task-chat-plan-preview"]')).toHaveLength(1);+ expect(container.textContent).toContain("Plan· rev 5");+ expect(container.textContent).toContain("Revised streaming UX");+ expect(container.textContent).not.toContain("Streaming task UX");+ });++ it("updates a live provider preview in place as steps stream", () => {+ const render = (steps: TaskChatProviderActivityItem["steps"]) => act(() => root.render(+ <ThemeProvider>+ <TaskChatPlanPreviewCard source={{ kind: "live", activity: livePlan(steps) }} />+ </ThemeProvider>,+ ));++ render([{ id: "one", label: "Inspect the existing card", status: "in_progress" }]);+ const preview = container.querySelector('[data-testid="task-chat-plan-preview"]');+ expect(preview?.tagName).toBe("SECTION");+ expect(preview?.textContent).toContain("Writing plan· rev 5");+ expect(preview?.textContent).toContain("Inspect the existing card");++ render([+ { id: "one", label: "Inspect the existing card", status: "completed" },+ { id: "two", label: "Render streamed plan steps", status: "in_progress" },+ ]);+ expect(container.querySelectorAll('[data-testid="task-chat-plan-preview"]')).toHaveLength(1);+ expect(container.textContent).toContain("Render streamed plan steps");+ });+});diff --git a/ui/src/components/task-chat/TaskChatPlanPreviewCard.tsx b/ui/src/components/task-chat/TaskChatPlanPreviewCard.tsxnew file mode 100644index 0000000000..99ddea242e--- /dev/null+++ b/ui/src/components/task-chat/TaskChatPlanPreviewCard.tsx@@ -0,0 +1,167 @@+import type { IssueDocument } from "@paperclipai/shared";+import { Lightbulb, Maximize2 } from "lucide-react";+import { cn } from "@/lib/utils";+import type { TaskChatProviderActivityItem } from "./task-chat-model";++const PLAN_PREVIEW_LINE_COUNT = 3;++export function planPreviewContent(markdown: string) {+ const lines = markdown+ .split("\n")+ .map((line) => line.trim())+ .filter(Boolean);+ const headingIndex = lines.findIndex((line) => /^#\s+/.test(line));+ const title = headingIndex >= 0+ ? lines[headingIndex]!.replace(/^#\s+/, "").trim()+ : "Plan";+ const preview = lines+ .filter((line, index) => index !== headingIndex && !/^(```|~~~|---+$|\*\*\*+$|___+$)/.test(line))+ .map((line) => line+ .replace(/^#{1,6}\s+/, "")+ .replace(/^[-*+]\s+/, "")+ .replace(/^\d+[.)]\s+/, "")+ .replace(/^>\s*/, "")+ .replace(/`([^`]+)`/g, "$1")+ .replace(/\*\*([^*]+)\*\*/g, "$1")+ .replace(/__([^_]+)__/g, "$1")+ .replace(/\[([^\]]+)]\([^)]*\)/g, "$1")+ .trim())+ .filter(Boolean)+ .slice(0, PLAN_PREVIEW_LINE_COUNT);+ return { title, preview };+}++export type TaskChatPlanPreviewSource =+ | {+ kind: "saved";+ document?: IssueDocument | null;+ revision?: number | null;+ fallbackTitle?: string | null;+ }+ | {+ kind: "live";+ activity: TaskChatProviderActivityItem;+ };++export interface TaskChatPlanPreviewCardProps {+ source: TaskChatPlanPreviewSource;+ href?: string | null;+ ariaLabel?: string;+ testId?: string;+ className?: string;+}++function livePlanContent(activity: TaskChatProviderActivityItem) {+ const title = activity.title.trim() && activity.title.trim().toLowerCase() !== "plan"+ ? activity.title.trim()+ : "Plan";+ const preview = activity.steps+ .map((step) => step.label.trim())+ .filter(Boolean)+ .slice(0, PLAN_PREVIEW_LINE_COUNT);+ if (preview.length === 0 && activity.summary?.trim()) preview.push(activity.summary.trim());+ return { title, preview };+}++function planRevision(source: TaskChatPlanPreviewSource): number | null {+ if (source.kind === "saved") {+ return source.revision ?? source.document?.latestRevisionNumber ?? null;+ }+ const detail = source.activity.details.find(({ label }) =>+ label === "Revision" || label === "Document Revision",+ );+ if (!detail) return null;+ const revision = Number.parseInt(detail.value, 10);+ return Number.isFinite(revision) ? revision : null;+}++export function TaskChatPlanPreviewCard({+ source,+ href = source.kind === "saved" ? "#document-plan" : null,+ ariaLabel,+ testId = "task-chat-plan-preview",+ className,+}: TaskChatPlanPreviewCardProps) {+ const revision = planRevision(source);+ const content = source.kind === "saved" && source.document+ ? planPreviewContent(source.document.body)+ : source.kind === "saved"+ ? { title: source.fallbackTitle?.trim() || "Plan", preview: [] as string[] }+ : livePlanContent(source.activity);+ const live = source.kind === "live";+ const headerDetail = revision == null+ ? null+ : `rev ${revision}`;+ const body = (+ <>+ <div className="flex items-center gap-2 border-b border-border/70 px-3 py-2.5 text-sm text-muted-foreground">+ <Lightbulb+ aria-hidden+ className={cn("h-4 w-4 shrink-0", live && "text-(--status-agent-running)")}+ />+ <span className={cn("font-medium", live && "shimmer-text shimmer-text-muted")} data-testid={live ? "task-chat-plan-streaming-status" : undefined}>+ {live ? "Writing plan" : "Plan"}+ </span>+ {headerDetail ? (+ <span+ className={cn("text-xs", live && "shimmer-text shimmer-text-muted")}+ >+ · {headerDetail}+ </span>+ ) : null}+ {href ? (+ <Maximize2+ aria-hidden+ className="ml-auto h-4 w-4 transition-transform group-hover:scale-105 group-hover:text-foreground"+ />+ ) : null}+ </div>+ <div className="relative max-h-36 overflow-hidden px-4 py-3">+ <h3 className="text-base font-semibold leading-6 text-foreground">{content.title}</h3>+ {content.preview.length > 0 ? (+ <ul className="mt-2 space-y-1.5 text-sm leading-5 text-muted-foreground">+ {content.preview.map((line, index) => (+ <li key={`${index}-${line}`} className="flex gap-2">+ <span aria-hidden className="shrink-0 text-muted-foreground/60">•</span>+ <span className="line-clamp-1">{line}</span>+ </li>+ ))}+ </ul>+ ) : (+ <p className="mt-1 text-sm text-muted-foreground">+ {live ? "Waiting for the first plan step…" : "Open the synchronized plan to review it."}+ </p>+ )}+ <div className="pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-linear-to-b from-transparent to-card/95" />+ </div>+ </>+ );+ const sharedClassName = cn(+ "group block w-full overflow-hidden rounded-md border border-border bg-muted/25 text-left",+ href && "transition-colors hover:border-foreground/25 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ className,+ );++ if (href) {+ return (+ <a+ href={href}+ data-testid={testId}+ aria-label={ariaLabel ?? `Open Plan${revision == null ? "" : ` revision ${revision}`}`}+ className={sharedClassName}+ >+ {body}+ </a>+ );+ }++ return (+ <section+ aria-label={ariaLabel ?? "Streaming Plan preview"}+ data-testid={testId}+ className={sharedClassName}+ >+ {body}+ </section>+ );+}diff --git a/ui/src/components/task-chat/TaskChatProtocolActivityRow.test.tsx b/ui/src/components/task-chat/TaskChatProtocolActivityRow.test.tsxnew file mode 100644index 0000000000..19ec43ff4b--- /dev/null+++ b/ui/src/components/task-chat/TaskChatProtocolActivityRow.test.tsx@@ -0,0 +1,187 @@+// @vitest-environment jsdom++import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { ThemeProvider } from "@/context/ThemeContext";+import { MemoryRouter } from "@/lib/router";+import type { TaskChatProtocolItem, TaskChatProviderActivityItem } from "./task-chat-model";+import { TaskChatProtocolActivityRow } from "./TaskChatProtocolActivityRow";++describe("TaskChatProtocolActivityRow", () => {+ let container: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ });++ afterEach(() => {+ act(() => root.unmount());+ container.remove();+ });++ function render(item: TaskChatProtocolItem) {+ act(() => root.render(+ <MemoryRouter>+ <ThemeProvider>+ <TaskChatProtocolActivityRow item={item} />+ </ThemeProvider>+ </MemoryRouter>,+ ));+ }++ it("renders long research results as a bounded readable list", () => {+ const item: TaskChatProviderActivityItem = {+ id: "research",+ kind: "protocol",+ surface: "provider_activity",+ family: "research",+ eventType: "research.completed",+ status: "completed",+ title: "Research",+ summary: "smoked pork shoulder",+ details: [+ { label: "Action", value: "search" },+ { label: "Status", value: "completed" },+ { label: "Query", value: "site:nextjs.org/docs/app/api-reference/config/eslint Next.js 16 eslint.config.mjs core-web-vitals typescript", mono: true },+ ],+ steps: [],+ links: Array.from({ length: 6 }, (_, index) => ({+ label: `Next.js configuration result ${index + 1}`,+ href: `https://nextjs.org/docs/result-${index + 1}`,+ description: "A long provider-authored snippet that stays on one compact line in the activity feed.",+ })),+ children: [],+ };+ render(item);++ const row = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-protocol-activity-row"] button');+ expect(container.querySelector("article")).toBeNull();+ expect(row?.textContent).toContain("Searched the web");+ expect(row?.textContent).toContain("smoked pork shoulder");+ expect(+ row+ ?.querySelector('[data-testid="task-chat-protocol-activity-icon"]')+ ?.parentElement?.classList.contains("justify-center"),+ ).toBe(true);+ expect(+ row?.querySelector(".task-chat-collapsed-line-fade")?.textContent,+ ).toContain("smoked pork shoulder");+ expect(row?.getAttribute("aria-expanded")).toBe("false");+ expect(row?.getAttribute("aria-controls")).toMatch(/^task-chat-protocol-activity-/);++ act(() => row?.click());++ expect(row?.getAttribute("aria-expanded")).toBe("true");+ const detail = container.querySelector('[data-testid="task-chat-protocol-activity-detail"]');+ expect(detail?.id).toBe(row?.getAttribute("aria-controls"));+ expect(detail?.querySelector('[data-testid="task-chat-research-query"]')?.textContent).toContain("eslint.config.mjs");+ expect(detail?.querySelectorAll('ol[aria-label="Research sources"] li')).toHaveLength(5);+ expect(detail?.textContent).toContain("Show 1 more result");+ expect(detail?.textContent).not.toContain("Actionsearch");++ const showMore = Array.from(detail?.querySelectorAll("button") ?? []).find((button) => button.textContent?.includes("Show 1 more result"));+ act(() => showMore?.click());+ expect(detail?.querySelectorAll('ol[aria-label="Research sources"] li')).toHaveLength(6);+ });++ it("summarizes workspace files without rendering inline diff bodies", () => {+ render({+ id: "workspace",+ kind: "protocol",+ surface: "workspace_change",+ changeSetId: "change-1",+ revision: 1,+ source: "runner_verified",+ complete: true,+ files: Array.from({ length: 10 }, (_, index) => ({+ path: `ui/src/file-${index + 1}.tsx`,+ operation: "modify" as const,+ previousPath: null,+ additions: 1,+ deletions: 1,+ binary: false,+ diff: `-old-${index + 1}\n+new-${index + 1}`,+ })),+ totals: { files: 10, additions: 10, deletions: 10 },+ patchArtifactRef: null,+ });++ const row = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-protocol-activity-row"] button');+ expect(row?.textContent).toContain("Edited files");+ act(() => row?.click());+ expect(container.textContent).toContain("ui/src/file-1.tsx");+ expect(container.textContent).toContain("2 more files not shown");+ expect(container.textContent).not.toContain("new-1");+ expect(container.querySelector('[data-testid="task-chat-workspace-change-details"] pre')).toBeNull();+ });++ it("renders durable resources as direct compact links", () => {+ render({+ id: "resource",+ kind: "protocol",+ surface: "resource",+ resourceKind: "document",+ title: "Implementation notes",+ subtitle: "markdown · ready",+ href: "/documents/notes",+ });++ const link = container.querySelector<HTMLAnchorElement>('[data-testid="task-chat-protocol-activity-row"]');+ expect(link?.getAttribute("href")).toBe("/documents/notes");+ expect(link?.textContent).toContain("Added a document");+ expect(link?.textContent).toContain("Implementation notes");+ });++ it("renders MCP executions with semantic copy, source metadata, and the MCP icon", () => {+ render({+ id: "tool",+ kind: "protocol",+ surface: "provider_activity",+ family: "tool_execution",+ eventType: "tool.execution.completed",+ status: "completed",+ title: "Tool execution",+ summary: "Searching the task index",+ details: [+ { label: "Transport", value: "mcp" },+ { label: "Namespace", value: "paperclip", mono: true },+ { label: "Operation", value: "search" },+ { label: "Name", value: "search_tasks", mono: true },+ ],+ steps: [],+ links: [],+ children: [],+ });++ const row = container.querySelector('[data-testid="task-chat-protocol-activity-row"]');+ expect(row?.textContent).toContain("Searched tasks");+ expect(row?.textContent).toContain("Searching the task index · Paperclip · search_tasks");+ expect(row?.textContent).not.toMatch(/Ran a tool|Tool execution|tool call/i);+ expect(row?.querySelector('[data-testid="task-chat-protocol-activity-icon"]')?.querySelectorAll("path")).toHaveLength(3);+ });++ it("does not make an informational row focusable when it has no details", () => {+ render({+ id: "notice",+ kind: "protocol",+ surface: "provider_activity",+ family: "provider_notice",+ eventType: "provider.notice.recorded",+ status: "informational",+ title: "Provider notice",+ summary: "Retrying automatically",+ details: [],+ steps: [],+ links: [],+ children: [],+ });++ const row = container.querySelector('[data-testid="task-chat-protocol-activity-row"]');+ expect(row?.querySelector("button")).toBeNull();+ expect(row?.querySelector('[aria-expanded]')).toBeNull();+ });+});diff --git a/ui/src/components/task-chat/TaskChatProtocolActivityRow.tsx b/ui/src/components/task-chat/TaskChatProtocolActivityRow.tsxnew file mode 100644index 0000000000..a6eba2d26b--- /dev/null+++ b/ui/src/components/task-chat/TaskChatProtocolActivityRow.tsx@@ -0,0 +1,314 @@+import { useId, useState, type ReactNode } from "react";+import {+ Check,+ ChevronRight,+ Circle,+ ExternalLink,+ Loader2,+ X,+} from "lucide-react";+import { MarkdownBody } from "@/components/MarkdownBody";+import { WorkspaceFileLink } from "@/components/WorkspaceFileLink";+import { cn } from "@/lib/utils";+import type {+ TaskChatProtocolDetail,+ TaskChatProtocolItem,+ TaskChatProtocolStep,+ TaskChatProviderActivityItem,+ TaskChatWorkspaceChangeItem,+ TaskChatWorkspaceFileItem,+} from "./task-chat-model";+import {+ protocolActivityIsRunning,+ protocolActivityLabel,+ protocolActivityPresentation,+} from "./task-chat-activity-presentation";++const COMPACT_RESEARCH_RESULT_LIMIT = 5;+const COMPACT_WORKSPACE_FILE_LIMIT = 8;++function StatusIcon({ status }: { status: "running" | "completed" | "failed" | "interrupted" | "informational" }) {+ if (status === "running") return <Loader2 className="h-3.5 w-3.5 animate-spin text-(--status-agent-running)" aria-hidden />;+ if (status === "failed" || status === "interrupted") return <X className="h-3.5 w-3.5 text-destructive" aria-hidden />;+ if (status === "completed") return <Check className="h-3.5 w-3.5 text-(--status-task-icon-done)" aria-hidden />;+ return <Circle className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />;+}++function stepStatusIcon(status: TaskChatProtocolStep["status"]) {+ if (status === "in_progress") return <Loader2 className="h-3 w-3 animate-spin text-(--status-agent-running)" aria-hidden />;+ if (status === "completed") return <Check className="h-3 w-3 text-(--status-task-icon-done)" aria-hidden />;+ if (status === "blocked" || status === "failed") return <X className="h-3 w-3 text-destructive" aria-hidden />;+ return <Circle className="h-3 w-3 text-muted-foreground" aria-hidden />;+}++function DetailList({ details }: { details: readonly TaskChatProtocolDetail[] }) {+ if (details.length === 0) return null;+ return (+ <dl className="flex min-w-0 flex-col gap-1.5" data-testid="task-chat-provider-detail-list">+ {details.map((detail) => (+ <div className="grid min-w-0 grid-cols-1 gap-0.5 sm:grid-cols-(--gtc-task-chat-details) sm:gap-3" key={`${detail.label}:${detail.value}`}>+ <dt className="text-muted-foreground">{detail.label}</dt>+ <dd className={cn("min-w-0 break-words text-foreground", detail.mono && "font-mono")}>{detail.value}</dd>+ </div>+ ))}+ </dl>+ );+}++function sourceHostname(href: string): string {+ try {+ return new URL(href).hostname.replace(/^www\./, "");+ } catch {+ return href;+ }+}++function ResearchDetails({ item }: { item: TaskChatProviderActivityItem }) {+ const [showAllResults, setShowAllResults] = useState(false);+ const query = item.details.find((detail) => detail.label.toLowerCase() === "query");+ const additionalDetails = item.details.filter((detail) => !["action", "query", "status"].includes(detail.label.toLowerCase()));+ const visibleLinks = showAllResults ? item.links : item.links.slice(0, COMPACT_RESEARCH_RESULT_LIMIT);+ const hiddenResultCount = item.links.length - visibleLinks.length;++ return (+ <div className="flex min-w-0 flex-col gap-2.5">+ {query ? (+ <div className="min-w-0 rounded-sm bg-muted/40 px-2.5 py-2" data-testid="task-chat-research-query">+ <p className="text-(length:--text-nano) font-medium uppercase tracking-wide text-muted-foreground">Query</p>+ <p className="mt-0.5 min-w-0 break-words font-mono text-(length:--text-micro) text-foreground">{query.value}</p>+ </div>+ ) : null}+ {item.links.length > 0 ? (+ <div className="min-w-0">+ <p className="mb-1 text-(length:--text-nano) font-medium uppercase tracking-wide text-muted-foreground">+ {item.links.length} {item.links.length === 1 ? "result" : "results"}+ </p>+ <ol className="divide-y divide-border/60" aria-label="Research sources">+ {visibleLinks.map((link, index) => (+ <li className="min-w-0 py-1.5 first:pt-0 last:pb-0" key={`${link.href}:${index}`}>+ <a className="flex min-w-0 items-center gap-1 font-medium text-foreground hover:underline" href={link.href} target="_blank" rel="noreferrer">+ <span className="truncate">{link.label}</span>+ <ExternalLink className="h-3 w-3 shrink-0" aria-hidden />+ </a>+ <p className="mt-0.5 flex min-w-0 gap-2 text-muted-foreground">+ <span className="shrink-0">{sourceHostname(link.href)}</span>+ {link.description ? <span className="min-w-0 truncate">{link.description}</span> : null}+ </p>+ </li>+ ))}+ </ol>+ {hiddenResultCount > 0 ? (+ <button+ type="button"+ className="mt-1.5 text-muted-foreground hover:text-foreground"+ onClick={() => setShowAllResults(true)}+ >+ Show {hiddenResultCount} more {hiddenResultCount === 1 ? "result" : "results"}+ </button>+ ) : showAllResults && item.links.length > COMPACT_RESEARCH_RESULT_LIMIT ? (+ <button+ type="button"+ className="mt-1.5 text-muted-foreground hover:text-foreground"+ onClick={() => setShowAllResults(false)}+ >+ Show fewer results+ </button>+ ) : null}+ </div>+ ) : null}+ <DetailList details={additionalDetails} />+ {item.output || item.outputTruncated ? (+ <p className="text-muted-foreground">Additional provider output is available in Runner Inspector.</p>+ ) : null}+ </div>+ );+}++function ProviderDetails({ item }: { item: TaskChatProviderActivityItem }) {+ if (item.family === "research") return <ResearchDetails item={item} />;+ return (+ <div className="flex min-w-0 flex-col gap-2">+ {item.steps.length > 0 ? (+ <ol className="flex flex-col gap-1" aria-label="Plan steps">+ {item.steps.map((step) => (+ <li className="flex min-w-0 items-start gap-2" key={step.id}>+ <span className="mt-0.5 shrink-0">{stepStatusIcon(step.status)}</span>+ <span className={cn("min-w-0", step.status === "completed" && "text-muted-foreground line-through")}>{step.label}</span>+ </li>+ ))}+ </ol>+ ) : null}+ {item.links.length > 0 ? (+ <ul className="flex flex-col gap-1.5" aria-label="Research sources">+ {item.links.map((link) => (+ <li key={link.href}>+ <a className="inline-flex min-w-0 items-center gap-1 font-medium text-primary hover:underline" href={link.href} target="_blank" rel="noreferrer">+ <span className="truncate">{link.label}</span>+ <ExternalLink className="h-3 w-3 shrink-0" aria-hidden />+ </a>+ {link.description ? <p className="mt-0.5 text-muted-foreground">{link.description}</p> : null}+ </li>+ ))}+ </ul>+ ) : null}+ {item.children.length > 0 ? (+ <ul className="flex flex-col gap-1.5" aria-label="Delegated agents">+ {item.children.map((child) => (+ <li className="flex min-w-0 flex-col gap-0.5" key={child.id}>+ <span className="flex min-w-0 items-center gap-2">+ <span className="font-medium text-foreground">{child.title}</span>+ <span className="capitalize text-muted-foreground">{child.status}</span>+ {child.metadata ? <span className="min-w-0 truncate font-mono text-(length:--text-micro)">{child.metadata}</span> : null}+ </span>+ {child.summary ? <span className="text-muted-foreground">{child.summary}</span> : null}+ </li>+ ))}+ </ul>+ ) : null}+ {item.details.length > 0 ? (+ <DetailList details={item.details} />+ ) : null}+ {item.output ? (+ <pre className="max-h-(--sz-64) overflow-auto whitespace-pre-wrap rounded-sm bg-muted/50 p-2 font-mono text-(length:--text-micro) text-foreground">{item.output}</pre>+ ) : null}+ {item.outputTruncated ? <p className="text-muted-foreground">Output truncated to 8 KiB.</p> : null}+ </div>+ );+}++function WorkspaceChangeDetails({ item }: { item: TaskChatWorkspaceChangeItem }) {+ if (item.files.length === 0) return <p className="text-muted-foreground">No changed-file details were reported.</p>;+ const visibleFiles = item.files.slice(0, COMPACT_WORKSPACE_FILE_LIMIT);+ const hiddenFileCount = item.files.length - visibleFiles.length;+ return (+ <div className="min-w-0" data-testid="task-chat-workspace-change-details">+ <ul className="flex min-w-0 flex-col divide-y divide-border/60" aria-label="Changed files">+ {visibleFiles.map((file) => (+ <li className="flex min-w-0 items-center gap-2 py-1.5 first:pt-0 last:pb-0" key={`${file.operation}:${file.path}`}>+ <span className="min-w-0 flex-1 truncate font-mono text-foreground" title={file.previousPath ? `${file.previousPath} → ${file.path}` : file.path}>+ {file.previousPath ? `${file.previousPath} → ${file.path}` : file.path}+ </span>+ <span className="shrink-0 capitalize text-muted-foreground">{file.operation.replaceAll("_", " ")}</span>+ {file.additions != null || file.deletions != null ? (+ <span className="shrink-0 font-mono text-(length:--text-micro) text-muted-foreground">+ {file.additions == null ? "" : `+${file.additions}`} {file.deletions == null ? "" : `−${file.deletions}`}+ </span>+ ) : null}+ </li>+ ))}+ </ul>+ {hiddenFileCount > 0 ? <p className="mt-1.5 text-muted-foreground">{hiddenFileCount} more {hiddenFileCount === 1 ? "file" : "files"} not shown</p> : null}+ </div>+ );+}++function WorkspaceFileDetails({ item }: { item: TaskChatWorkspaceFileItem }) {+ const workspaceFileRef = {+ path: item.path,+ resourceKind: "file" as const,+ line: item.line,+ column: null,+ raw: item.path,+ };+ return (+ <div className="flex min-w-0 flex-col gap-2">+ <WorkspaceFileLink workspaceFileRef={workspaceFileRef} label={item.path} />+ {item.preview ? (+ item.presentation === "document" ? (+ <div className="max-h-(--sz-64) overflow-auto rounded-sm bg-muted/30 p-2 text-foreground"><MarkdownBody>{item.preview}</MarkdownBody></div>+ ) : (+ <pre className="max-h-(--sz-64) overflow-auto whitespace-pre-wrap rounded-sm bg-muted/50 p-2 font-mono text-(length:--text-micro) text-foreground">{item.preview}</pre>+ )+ ) : <p className="text-muted-foreground">Preview unavailable.</p>}+ {item.previewTruncated ? <p className="text-muted-foreground">Preview truncated by the runner.</p> : null}+ </div>+ );+}++function detailContent(item: TaskChatProtocolItem): ReactNode | null {+ switch (item.surface) {+ case "provider_activity": {+ const expandable = item.details.length > 0 || item.steps.length > 0 || item.links.length > 0 || item.children.length > 0 || Boolean(item.output) || Boolean(item.outputTruncated);+ return expandable ? <ProviderDetails item={item} /> : null;+ }+ case "workspace_change": return <WorkspaceChangeDetails item={item} />;+ case "workspace_file": return <WorkspaceFileDetails item={item} />;+ case "resource":+ case "runtime_request":+ case "run_result":+ case "run_terminal":+ return null;+ }+}++function itemStatus(item: TaskChatProtocolItem): "running" | "completed" | "failed" | "interrupted" | "informational" {+ if (item.surface === "provider_activity") return item.status;+ if (item.surface === "workspace_change") return item.complete ? "completed" : "running";+ return "completed";+}++export function TaskChatProtocolActivityRow({ item }: { item: TaskChatProtocolItem }) {+ const [open, setOpen] = useState(false);+ const detailId = `task-chat-protocol-activity-${useId().replaceAll(":", "")}`;+ const presentation = protocolActivityPresentation(item);+ if (!presentation) return null;+ const detail = detailContent(item);+ const expandable = detail !== null;+ const Icon = presentation.icon;+ const label = protocolActivityLabel(item, presentation);+ const active = protocolActivityIsRunning(item);+ const status = itemStatus(item);+ const row = (+ <>+ <span className="flex w-5 shrink-0 items-center justify-center">+ <Icon className="h-3.5 w-3.5 shrink-0" aria-hidden data-testid="task-chat-protocol-activity-icon" />+ </span>+ <span className={cn("shrink-0 font-medium", active && "shimmer-text shimmer-text-muted")}>{label}{active ? "…" : ""}</span>+ {presentation.detail ? <span className="task-chat-collapsed-line-fade min-w-0 flex-1 font-mono text-(length:--text-micro)">{presentation.detail}</span> : null}+ <span className="ml-auto flex shrink-0 items-center gap-2">+ {expandable ? (+ <ChevronRight+ className={cn("tc-hover-disclosure-caret h-3 w-3 transition-[opacity,transform] group-hover/activity:opacity-80 group-focus-visible/activity:opacity-80", open ? "rotate-90 opacity-80" : "opacity-0")}+ aria-hidden+ />+ ) : null}+ <StatusIcon status={status} />+ </span>+ </>+ );++ if (item.surface === "resource" && item.href) {+ return (+ <a className="group/activity -mx-1.5 flex min-h-6 w-full min-w-0 max-w-full items-center gap-2 overflow-hidden rounded-sm px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground" href={item.href} data-testid="task-chat-protocol-activity-row">+ {row}+ </a>+ );+ }++ const activityRow = expandable ? (+ <button+ type="button"+ onClick={() => setOpen((value) => !value)}+ aria-expanded={open}+ aria-controls={detailId}+ className="group/activity -mx-1.5 flex min-h-6 w-full min-w-0 max-w-full items-center gap-2 overflow-hidden rounded-sm px-1.5 py-1 text-left text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {row}+ </button>+ ) : (+ <div className="group/activity -mx-1.5 flex min-h-6 w-full min-w-0 max-w-full items-center gap-2 overflow-hidden rounded-sm px-1.5 py-1 text-muted-foreground">+ {row}+ </div>+ );++ return (+ <div className="flex min-w-0 flex-col text-xs" data-testid="task-chat-protocol-activity-row" data-activity-family={item.surface === "provider_activity" ? item.family : item.surface}>+ {activityRow}+ {open && detail ? (+ <div id={detailId} className="ml-2.5 mt-0.5 border-l-2 border-border py-1 pl-2.5" data-testid="task-chat-protocol-activity-detail">+ {detail}+ </div>+ ) : null}+ </div>+ );+}diff --git a/ui/src/components/task-chat/TaskChatProtocolCard.test.tsx b/ui/src/components/task-chat/TaskChatProtocolCard.test.tsxnew file mode 100644index 0000000000..65166f59a9--- /dev/null+++ b/ui/src/components/task-chat/TaskChatProtocolCard.test.tsx@@ -0,0 +1,607 @@+// @vitest-environment jsdom++import { act, forwardRef, useImperativeHandle, type ForwardedRef } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ThemeProvider } from "@/context/ThemeContext";+import { MemoryRouter } from "@/lib/router";+import { TaskChatProtocolCard } from "./TaskChatProtocolCard";+import type {+ TaskChatProtocolItem,+ TaskChatProviderActivityFamily,+ TaskChatRuntimeRequestDecision,+} from "./task-chat-model";++vi.mock("@/components/MarkdownEditor", () => ({+ MarkdownEditor: forwardRef(function MockMarkdownEditor(+ {+ value,+ onChange,+ placeholder,+ imageUploadHandler,+ }: {+ value: string;+ onChange: (value: string) => void;+ placeholder?: string;+ imageUploadHandler?: (file: File) => Promise<string>;+ },+ ref: ForwardedRef<unknown>,+ ) {+ useImperativeHandle(ref, () => ({+ insertMarkdown: (markdown: string) => onChange(`${value}${markdown}`),+ focus: () => {},+ }));+ return (+ <textarea+ data-testid="mock-markdown-editor"+ data-image-upload={imageUploadHandler ? "true" : "false"}+ value={value}+ placeholder={placeholder}+ onChange={(event) => onChange(event.target.value)}+ />+ );+ }),+}));++function renderCard(+ root: Root,+ item: TaskChatProtocolItem,+ onDecision?: (+ decision: TaskChatRuntimeRequestDecision,+ ) => void | Promise<void>,+ presentation: "timeline" | "takeover" = "timeline",+) {+ flushSync(() =>+ root.render(+ <MemoryRouter>+ <ThemeProvider>+ <TaskChatProtocolCard+ item={item}+ presentation={presentation}+ imageUploadHandler={async () => "blob:question-image"}+ onRuntimeRequestDecision={+ onDecision+ ? (_request, decision) => onDecision(decision)+ : undefined+ }+ />+ </ThemeProvider>+ </MemoryRouter>,+ ),+ );+}++describe("TaskChatProtocolCard", () => {+ let container: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ });++ afterEach(() => {+ flushSync(() => root.unmount());+ container.remove();+ });++ it("renders provider plan steps and status", () => {+ renderCard(root, {+ id: "provider-plan",+ kind: "protocol",+ surface: "provider_activity",+ family: "plan",+ eventType: "plan.updated",+ status: "running",+ title: "Plan",+ summary: "Implement protocol surfaces",+ details: [],+ links: [],+ children: [],+ steps: [+ { id: "one", label: "Inventory events", status: "completed" },+ { id: "two", label: "Render widgets", status: "in_progress" },+ ],+ });+ expect(+ container.querySelector('[data-testid="task-chat-provider-plan"]'),+ ).not.toBeNull();+ expect(container.textContent).toContain("Inventory events");+ expect(container.textContent).toContain("Render widgets");+ });++ it("renders a structured history card for every provider family", () => {+ const families = [+ "plan",+ "tool_execution",+ "research",+ "delegation",+ "model_identity",+ "context",+ "artifact",+ "review",+ "hook",+ "memory",+ "safety",+ "terminal",+ "wait",+ "provider_notice",+ ] satisfies TaskChatProviderActivityFamily[];+ for (const family of families) {+ renderCard(root, {+ id: `provider-${family}`,+ kind: "protocol",+ surface: "provider_activity",+ family,+ eventType: `${family}.fixture`,+ status: "completed",+ title: `Visible ${family}`,+ summary: `Summary ${family}`,+ details: [{ label: "Reference", value: `${family}-1` }],+ links: [],+ children: [],+ steps: [],+ });+ expect(+ container.querySelector(`[data-testid="task-chat-provider-${family}"]`),+ family,+ ).not.toBeNull();+ expect(container.textContent, family).toContain(`Visible ${family}`);+ }+ });++ it("opens a workspace diff review dialog", async () => {+ renderCard(root, {+ id: "workspace",+ kind: "protocol",+ surface: "workspace_change",+ changeSetId: "changes-1",+ revision: 1,+ source: "runner_verified",+ complete: true,+ files: [+ {+ path: "ui/src/App.tsx",+ operation: "modify",+ previousPath: null,+ additions: 1,+ deletions: 1,+ binary: false,+ diff: "-old\n+new",+ },+ ],+ totals: { files: 1, additions: 1, deletions: 1 },+ patchArtifactRef: null,+ });+ const button = Array.from(container.querySelectorAll("button")).find(+ (candidate) => candidate.textContent === "Review diff",+ );+ expect(button).not.toBeUndefined();+ expect(container.textContent).toContain("1 file changed · +1 −1");+ await act(async () => button?.click());+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain(+ "ui/src/App.tsx",+ );+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain(+ "old",+ );+ });++ it("opens a bounded file preview", async () => {+ renderCard(root, {+ id: "file",+ kind: "protocol",+ surface: "workspace_file",+ referenceId: "file-1",+ source: "runner_verified",+ path: "doc/protocol.md",+ displayName: "protocol.md",+ mediaType: "text/markdown",+ presentation: "document",+ line: 12,+ preview: "# Protocol preview",+ previewTruncated: false,+ });+ const button = Array.from(container.querySelectorAll("button")).find(+ (candidate) => candidate.textContent === "Preview",+ );+ await act(async () => button?.click());+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain(+ "Protocol preview",+ );+ });++ it("submits a runtime choice only when a resolver is supplied", async () => {+ const onDecision = vi.fn();+ renderCard(+ root,+ {+ id: "request",+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-1",+ requestId: "request-1",+ requestKind: "command_approval",+ turnId: "turn-1",+ requestType: "permission",+ status: "pending",+ prompt: "Allow command?",+ choices: [{ key: "accept", label: "Allow once" }],+ fields: [],+ },+ onDecision,+ );+ const button = Array.from(container.querySelectorAll("button")).find(+ (candidate) => candidate.textContent === "Allow once",+ );+ expect(button?.disabled).toBe(false);+ await act(async () => button?.click());+ expect(onDecision).toHaveBeenCalledWith({ action: "accept" });+ });++ it("submits structured runtime input through the production card", async () => {+ const onDecision = vi.fn().mockResolvedValue(undefined);+ renderCard(+ root,+ {+ id: "input-request",+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-1",+ requestId: "request-input",+ requestKind: "user_input",+ turnId: "turn-1",+ requestType: "input",+ status: "pending",+ prompt: "Which environment should the run target?",+ choices: [],+ fields: [+ { name: "environment", label: "Environment", placeholder: "staging" },+ ],+ },+ onDecision,+ );+ const textarea = container.querySelector("textarea")!;+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(+ HTMLTextAreaElement.prototype,+ "value",+ )?.set;+ setter?.call(textarea, "production");+ textarea.dispatchEvent(new Event("input", { bubbles: true }));+ });+ const submit = Array.from(container.querySelectorAll("button")).find(+ (candidate) => candidate.textContent === "Submit response",+ );+ await act(async () => submit?.click());+ expect(onDecision).toHaveBeenCalledWith({+ action: "submit",+ values: { environment: "production" },+ });+ expect(container.textContent).toContain("Submitting…");+ });++ it("submits the canonical response from a v2 harness question set", async () => {+ const onDecision = vi.fn().mockResolvedValue(undefined);+ renderCard(+ root,+ {+ id: "canonical-input-request",+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-1",+ requestId: "request-canonical-input",+ requestKind: "runtime",+ turnId: "turn-1",+ requestType: "input",+ status: "pending",+ prompt: "Codex needs your input.",+ choices: [],+ fields: [],+ questionSet: {+ schema: "paperclip.question_set.v1",+ title: "Deployment input",+ submitLabel: "Continue",+ questions: [+ {+ id: "environment",+ header: "Environment",+ prompt: "Where should we deploy?",+ required: true,+ answerMode: "single_select",+ options: [+ { id: "staging", label: "Staging" },+ { id: "production", label: "Production" },+ ],+ },+ {+ id: "regions",+ header: "Regions",+ prompt: "Which regions should receive the release?",+ required: false,+ answerMode: "multi_select",+ options: [+ { id: "us", label: "US" },+ { id: "eu", label: "EU" },+ ],+ },+ {+ id: "notes",+ header: "Notes",+ prompt: "Anything else we should know?",+ required: false,+ answerMode: "text",+ },+ ],+ },+ },+ onDecision,+ );+ expect(container.textContent).toContain("Deployment input");+ expect(container.textContent).toContain("1 of 3");+ const production = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.includes("Production"),+ );+ await act(async () => production?.click());+ expect(container.textContent).toContain(+ "Which regions should receive the release?",+ );+ const progress = Array.from(+ container.querySelectorAll<HTMLButtonElement>("button"),+ ).find((button) => button.textContent?.trim() === "Continue");+ expect(progress).not.toBeUndefined();+ await act(async () => progress?.click());+ expect(container.textContent).toContain("Anything else we should know?");+ const submit = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.trim() === "Continue",+ );+ await act(async () => submit?.click());+ expect(onDecision).toHaveBeenCalledWith({+ action: "submit",+ response: {+ schema: "paperclip.question_response.v1",+ answers: { environment: { selectedOptionIds: ["production"] } },+ },+ });+ });++ it("renders structured runtime questions directly in the takeover without duplicate request copy", () => {+ renderCard(+ root,+ {+ id: "canonical-takeover-request",+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-1",+ requestId: "request-canonical-takeover",+ requestKind: "runtime",+ turnId: "turn-1",+ requestType: "input",+ status: "pending",+ prompt: "Codex requests user input.",+ choices: [],+ fields: [],+ questionSet: {+ schema: "paperclip.question_set.v1",+ title: "Codex needs your input",+ questions: [+ {+ id: "environment",+ header: "Environment",+ prompt: "Where should we deploy?",+ required: false,+ answerMode: "single_select",+ options: [{ id: "staging", label: "Staging" }],+ },+ ],+ },+ },+ vi.fn(),+ "takeover",+ );++ expect(container.textContent).not.toContain("Codex needs your input");+ expect(container.textContent).not.toContain("Codex requests user input.");+ expect(container.textContent).not.toContain("Choose one");+ expect(container.textContent).toContain("Where should we deploy?");+ });++ it("collapses resolved runtime questions to one expandable timeline row", () => {+ renderCard(root, {+ id: "resolved-input-request",+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-1",+ requestId: "request-resolved-input",+ requestKind: "runtime",+ turnId: "turn-1",+ requestType: "input",+ status: "resolved",+ prompt: "Codex needs your input.",+ choices: [],+ fields: [],+ resolvedAction: "submit",+ questionSet: {+ schema: "paperclip.question_set.v1",+ title: "Server setup",+ questions: [+ {+ id: "style",+ header: "Code style",+ prompt: "Which module style should the server use?",+ required: true,+ answerMode: "single_select",+ options: [{ id: "esm", label: "TypeScript ESM" }],+ },+ ],+ },+ response: {+ schema: "paperclip.question_response.v1",+ answers: { style: { selectedOptionIds: ["esm"] } },+ },+ });++ const receipt = container.querySelector<HTMLDetailsElement>(+ '[data-testid="task-chat-runtime-request"]',+ );+ expect(receipt?.open).toBe(false);+ expect(receipt?.querySelector("summary")?.textContent).toBe(+ "Questions answered",+ );+ expect(receipt?.querySelectorAll("summary svg")).toHaveLength(2);+ expect(receipt?.className).not.toContain("border");+ expect(receipt?.className).not.toContain("bg-card");+ expect(receipt?.querySelector("summary")?.className).toContain("px-1");+ expect(receipt?.querySelector("summary")?.className).toContain(+ "text-muted-foreground",+ );+ expect(receipt?.querySelector("summary")?.className).toContain("leading-5");+ expect(receipt?.querySelector("summary span")?.className).not.toContain(+ "font-medium",+ );+ expect(+ receipt+ ?.querySelector('[data-testid="task-chat-runtime-request-icon"]')+ ?.classList.contains("h-3.5"),+ ).toBe(true);+ const caret = receipt?.querySelector(+ '[data-testid="task-chat-runtime-request-caret"]',+ );+ expect(caret?.classList.contains("h-3")).toBe(true);+ expect(caret?.classList.contains("opacity-0")).toBe(true);+ expect(caret?.getAttribute("class")).toContain("group-hover:opacity-70");+ expect(+ container.querySelector(+ '[data-testid="task-chat-runtime-request-history"]',+ ),+ ).not.toBeNull();+ expect(container.textContent).toContain(+ "Which module style should the server use?",+ );+ expect(container.textContent).toContain("TypeScript ESM");+ expect(container.querySelector("textarea")).toBeNull();+ });++ it("collapses a cancelled runtime question with its original prompt expandable", () => {+ renderCard(root, {+ id: "cancelled-input-request",+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-1",+ requestId: "request-cancelled-input",+ requestKind: "runtime",+ turnId: "turn-1",+ requestType: "input",+ status: "cancelled",+ prompt: "Codex needs your input.",+ choices: [],+ fields: [],+ resolvedAction: "cancel",+ questionSet: {+ schema: "paperclip.question_set.v1",+ questions: [+ {+ id: "goal",+ prompt: "What should the server do?",+ required: false,+ answerMode: "text",+ },+ ],+ },+ });++ const receipt = container.querySelector<HTMLDetailsElement>(+ '[data-testid="task-chat-runtime-request"]',+ );+ expect(receipt?.open).toBe(false);+ expect(receipt?.querySelector("summary")?.textContent).toBe(+ "Questions cancelled",+ );+ const iconSlot = receipt?.querySelector(+ '[data-testid="task-chat-runtime-request-icon-slot"]',+ );+ expect(iconSlot?.classList.contains("w-6")).toBe(true);+ expect(iconSlot?.classList.contains("items-center")).toBe(true);+ expect(iconSlot?.classList.contains("justify-center")).toBe(true);+ expect(container.textContent).toContain(+ "No answers were submitted; this request was cancelled.",+ );+ });++ it("requires text when an explicit custom multi-select answer is active", async () => {+ renderCard(+ root,+ {+ id: "custom-input-request",+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-1",+ requestId: "request-custom-input",+ requestKind: "runtime",+ turnId: "turn-1",+ requestType: "input",+ status: "pending",+ prompt: "Choose regions.",+ choices: [],+ fields: [],+ questionSet: {+ schema: "paperclip.question_set.v1",+ questions: [+ {+ id: "regions",+ prompt: "Which regions?",+ required: true,+ answerMode: "multi_select",+ options: [{ id: "us", label: "US" }],+ customAnswer: { enabled: true, label: "Another region" },+ },+ {+ id: "notes",+ prompt: "Notes?",+ required: false,+ answerMode: "text",+ },+ ],+ },+ },+ vi.fn(),+ );++ const us = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.trim() === "US",+ );+ const custom = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.trim() === "Another region",+ );+ await act(async () => us?.click());+ await act(async () => custom?.click());++ const richInput = container.querySelector(+ '[data-testid="question-other-answer-composer"]',+ );+ expect(richInput).not.toBeNull();+ expect(richInput?.classList.contains("border")).toBe(false);+ expect(+ richInput?.querySelector('[data-image-upload="true"]'),+ ).not.toBeNull();++ const next = Array.from(+ container.querySelectorAll<HTMLButtonElement>("button"),+ ).find((button) => button.getAttribute("aria-label") === "Next question");+ expect(next?.disabled).toBe(false);+ expect(container.textContent).toContain("Enter a custom answer.");++ const textarea = container.querySelector("textarea")!;+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(+ HTMLTextAreaElement.prototype,+ "value",+ )?.set;+ setter?.call(textarea, "ap-south");+ textarea.dispatchEvent(new Event("input", { bubbles: true }));+ });+ expect(next?.disabled).toBe(false);+ });+});diff --git a/ui/src/components/task-chat/TaskChatProtocolCard.tsx b/ui/src/components/task-chat/TaskChatProtocolCard.tsxnew file mode 100644index 0000000000..215eac1e93--- /dev/null+++ b/ui/src/components/task-chat/TaskChatProtocolCard.tsx@@ -0,0 +1,1082 @@+import { useEffect, useMemo, useState } from "react";+import {+ AlertTriangle,+ Bot,+ Check,+ ChevronDown,+ ChevronRight,+ Circle,+ CircleHelp,+ Clock3,+ ExternalLink,+ FileCode2,+ FileText,+ GitBranch,+ Loader2,+ PackageCheck,+ ShieldCheck,+ TerminalSquare,+ X,+} from "lucide-react";+import { MarkdownBody } from "@/components/MarkdownBody";+import type { MentionOption } from "@/components/MarkdownEditor";+import { WorkspaceFileLink } from "@/components/WorkspaceFileLink";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Textarea } from "@/components/ui/textarea";+import { cn } from "@/lib/utils";+import {+ clearDraft,+ loadStructuredDraft,+ saveStructuredDraft,+} from "@/lib/composer-draft";+import type {+ TaskChatProtocolItem,+ TaskChatProtocolStep,+ TaskChatProviderActivityItem,+ TaskChatRuntimeRequestDecision,+ TaskChatRuntimeRequestItem,+ TaskChatWorkspaceChangeItem,+ TaskChatWorkspaceFileItem,+} from "./task-chat-model";+import { QuestionForm, QuestionResponseSummary } from "./QuestionForm";+import { TaskChatComposerTakeoverHeader } from "./TaskChatComposerTakeoverContext";++export interface TaskChatProtocolCardProps {+ item: TaskChatProtocolItem;+ presentation?: "timeline" | "takeover";+ draftKey?: string;+ imageUploadHandler?: (file: File) => Promise<string>;+ mentions?: MentionOption[];+ onRuntimeRequestDecision?: (+ item: TaskChatRuntimeRequestItem,+ decision: TaskChatRuntimeRequestDecision,+ ) => void | Promise<void>;+}++const FAMILY_ICON = {+ plan: GitBranch,+ tool_execution: TerminalSquare,+ research: FileText,+ delegation: Bot,+ model_identity: Bot,+ context: PackageCheck,+ artifact: PackageCheck,+ review: ShieldCheck,+ hook: GitBranch,+ memory: FileText,+ safety: ShieldCheck,+ terminal: TerminalSquare,+ wait: Clock3,+ provider_notice: AlertTriangle,+} as const;++function statusTone(status: string): string {+ if (+ ["failed", "blocked", "denied", "cancelled", "interrupted"].includes(status)+ )+ return "text-destructive";+ if (["running", "pending", "in_progress", "waiting"].includes(status))+ return "text-(--status-agent-running)";+ if (["completed", "done", "succeeded", "passed", "resolved"].includes(status))+ return "text-(--status-task-icon-done)";+ return "text-muted-foreground";+}++function StatusIcon({+ status,+ className,+}: {+ status: string;+ className?: string;+}) {+ if (["running", "pending", "in_progress", "waiting"].includes(status)) {+ return (+ <Loader2+ aria-hidden+ className={cn("h-4 w-4 animate-spin", statusTone(status), className)}+ />+ );+ }+ if (+ ["failed", "blocked", "denied", "cancelled", "interrupted"].includes(status)+ ) {+ return (+ <X aria-hidden className={cn("h-4 w-4", statusTone(status), className)} />+ );+ }+ if (+ ["completed", "done", "succeeded", "passed", "resolved"].includes(status)+ ) {+ return (+ <Check+ aria-hidden+ className={cn("h-4 w-4", statusTone(status), className)}+ />+ );+ }+ return (+ <Circle+ aria-hidden+ className={cn("h-4 w-4", statusTone(status), className)}+ />+ );+}++function CardShell({+ icon: Icon,+ title,+ status,+ summary,+ children,+ testId,+ presentation = "timeline",+}: {+ icon: typeof Circle;+ title: string;+ status: string;+ summary?: string;+ children?: React.ReactNode;+ testId: string;+ presentation?: "timeline" | "takeover";+}) {+ const titleRow = (+ <div className="flex min-w-0 items-center gap-2">+ <Icon aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />+ <strong className="min-w-0 truncate text-sm font-medium text-foreground">+ {title}+ </strong>+ {status !== "pending" ? (+ <span+ className={cn(+ "inline-flex shrink-0 items-center gap-1 text-xs capitalize",+ statusTone(status),+ )}+ >+ <StatusIcon status={status} className="h-3.5 w-3.5" />+ {status.replaceAll("_", " ")}+ </span>+ ) : null}+ </div>+ );++ if (presentation === "takeover") {+ return (+ <article className="overflow-hidden" data-testid={testId}>+ <TaskChatComposerTakeoverHeader>+ {titleRow}+ </TaskChatComposerTakeoverHeader>+ {summary ? (+ <p+ className={cn(+ "text-sm text-muted-foreground",+ Boolean(children) && "mb-3",+ )}+ >+ {summary}+ </p>+ ) : null}+ {children}+ </article>+ );+ }++ return (+ <article+ className={cn(+ "overflow-hidden",+ presentation === "timeline" &&+ "rounded-md border border-border bg-card/60",+ )}+ data-testid={testId}+ >+ <header className="flex min-w-0 items-start gap-2 px-3 py-2.5">+ <Icon+ aria-hidden+ className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"+ />+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">+ <strong className="text-sm font-medium text-foreground">+ {title}+ </strong>+ <span+ className={cn(+ "inline-flex items-center gap-1 text-xs capitalize",+ statusTone(status),+ )}+ >+ <StatusIcon status={status} className="h-3.5 w-3.5" />+ {status.replaceAll("_", " ")}+ </span>+ </div>+ {summary ? (+ <p className="mt-1 text-sm text-muted-foreground">{summary}</p>+ ) : null}+ </div>+ </header>+ {children ? (+ <div className="border-t border-border/70 px-3 py-2.5">{children}</div>+ ) : null}+ </article>+ );+}++function PlanSteps({ steps }: { steps: TaskChatProtocolStep[] }) {+ if (steps.length === 0) return null;+ return (+ <ol className="flex flex-col gap-1.5" aria-label="Plan steps">+ {steps.map((step) => (+ <li key={step.id} className="flex items-start gap-2 text-sm">+ <StatusIcon status={step.status} className="mt-0.5 shrink-0" />+ <span+ className={cn(+ "min-w-0 flex-1",+ step.status === "completed" &&+ "text-muted-foreground line-through",+ )}+ >+ {step.label}+ </span>+ </li>+ ))}+ </ol>+ );+}++function ProviderActivityCard({+ item,+}: {+ item: TaskChatProviderActivityItem;+}) {+ const Icon = FAMILY_ICON[item.family];+ const hasDetails =+ item.details.length > 0 ||+ item.links.length > 0 ||+ item.children.length > 0 ||+ Boolean(item.output);+ return (+ <CardShell+ icon={Icon}+ title={item.title}+ status={item.status}+ summary={item.summary}+ testId={`task-chat-provider-${item.family}`}+ >+ {item.steps.length > 0 ? <PlanSteps steps={item.steps} /> : null}+ {item.children.length > 0 ? (+ <ul className="flex flex-col gap-2" aria-label="Delegated agents">+ {item.children.map((child) => (+ <li+ key={child.id}+ className="rounded-sm bg-muted/40 px-2.5 py-2 text-sm"+ >+ <div className="flex items-center gap-2">+ <StatusIcon status={child.status} className="shrink-0" />+ <strong className="font-medium">{child.title}</strong>+ <span+ className={cn(+ "ml-auto text-xs capitalize",+ statusTone(child.status),+ )}+ >+ {child.status}+ </span>+ </div>+ {child.metadata ? (+ <p className="mt-1 text-xs text-muted-foreground">+ {child.metadata}+ </p>+ ) : null}+ {child.summary ? (+ <p className="mt-1 text-sm text-muted-foreground">+ {child.summary}+ </p>+ ) : null}+ </li>+ ))}+ </ul>+ ) : null}+ {item.links.length > 0 ? (+ <ul className="flex flex-col gap-2" aria-label="Research sources">+ {item.links.map((link) => (+ <li key={link.href}>+ <a+ className="inline-flex items-center gap-1 text-sm font-medium text-primary hover:underline"+ href={link.href}+ target="_blank"+ rel="noreferrer"+ >+ {link.label}+ <ExternalLink aria-hidden className="h-3.5 w-3.5" />+ </a>+ {link.description ? (+ <p className="text-xs text-muted-foreground">+ {link.description}+ </p>+ ) : null}+ </li>+ ))}+ </ul>+ ) : null}+ {hasDetails ? (+ <details+ className={cn(+ (item.steps.length > 0 ||+ item.links.length > 0 ||+ item.children.length > 0) &&+ "mt-2",+ )}+ >+ <summary className="flex cursor-pointer list-none items-center gap-1 text-xs font-medium text-muted-foreground">+ <ChevronDown aria-hidden className="h-3.5 w-3.5" /> Details+ </summary>+ {item.details.length > 0 ? (+ <dl className="mt-2 flex min-w-0 flex-col gap-1.5 text-xs">+ {item.details.map((detail) => (+ <div+ key={`${detail.label}:${detail.value}`}+ className="grid min-w-0 grid-cols-1 gap-0.5 sm:grid-cols-(--gtc-task-chat-details) sm:gap-3"+ >+ <dt className="text-muted-foreground">{detail.label}</dt>+ <dd+ className={cn(+ "min-w-0 break-words text-foreground",+ detail.mono && "font-mono",+ )}+ >+ {detail.value}+ </dd>+ </div>+ ))}+ </dl>+ ) : null}+ {item.output ? (+ <pre className="mt-2 max-h-(--sz-64) overflow-auto whitespace-pre-wrap rounded-sm bg-muted/50 p-2 font-mono text-xs text-foreground">+ {item.output}+ </pre>+ ) : null}+ {item.outputTruncated ? (+ <p className="mt-1 text-xs text-muted-foreground">+ Output truncated to 8 KiB.+ </p>+ ) : null}+ </details>+ ) : null}+ </CardShell>+ );+}++function diffStats(file: TaskChatWorkspaceChangeItem["files"][number]) {+ return (+ <span className="shrink-0 font-mono text-xs text-muted-foreground">+ {file.additions == null ? "" : `+${file.additions}`}+ {file.additions != null && file.deletions != null ? " " : ""}+ {file.deletions == null ? "" : `−${file.deletions}`}+ </span>+ );+}++function WorkspaceChangeCard({ item }: { item: TaskChatWorkspaceChangeItem }) {+ const [selectedPath, setSelectedPath] = useState<string | null>(null);+ const [expanded, setExpanded] = useState(false);+ const selected =+ item.files.find((file) => file.path === selectedPath) ?? null;+ const visibleFiles = expanded ? item.files : item.files.slice(0, 3);+ const fileCount = item.totals.files || item.files.length;+ const fileLabel = `${fileCount} ${fileCount === 1 ? "file" : "files"}`;+ const stats = [+ item.totals.additions == null ? null : `+${item.totals.additions}`,+ item.totals.deletions == null ? null : `−${item.totals.deletions}`,+ ].filter(Boolean).join(" ");+ const summary = item.complete+ ? `${fileLabel} changed${stats ? ` · ${stats}` : ""}`+ : "Workspace changes in progress";+ return (+ <>+ <CardShell+ icon={GitBranch}+ title="Workspace changes"+ status={item.complete ? "completed" : "running"}+ summary={summary}+ testId="task-chat-workspace-change"+ >+ <div className="flex flex-col gap-1">+ {visibleFiles.map((file) => (+ <button+ key={`${file.operation}:${file.path}`}+ type="button"+ className="flex min-w-0 items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm hover:bg-muted/60"+ onClick={() => setSelectedPath(file.path)}+ >+ <span className="min-w-0 flex-1">+ <span className="block truncate font-mono">+ {file.previousPath+ ? `${file.previousPath} → ${file.path}`+ : file.path}+ </span>+ <span className="text-xs capitalize text-muted-foreground">+ {file.binary ? "binary · " : ""}+ {file.operation.replaceAll("_", " ")}+ </span>+ </span>+ {diffStats(file)}+ </button>+ ))}+ </div>+ <div className="mt-2 flex flex-wrap items-center gap-2">+ {item.files.length > 3 ? (+ <Button+ type="button"+ size="sm"+ variant="ghost"+ onClick={() => setExpanded((value) => !value)}+ >+ {expanded+ ? "Show fewer files"+ : `Show ${item.files.length - 3} more files`}+ </Button>+ ) : null}+ {item.files.length > 0 ? (+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => setSelectedPath(item.files[0].path)}+ >+ Review diff+ </Button>+ ) : null}+ </div>+ </CardShell>+ <Dialog+ open={selected !== null}+ onOpenChange={(open) => {+ if (!open) setSelectedPath(null);+ }}+ >+ <DialogContent className="w-full max-w-(--pct-90) overflow-hidden">+ <DialogHeader>+ <DialogTitle className="font-mono text-sm">+ {selected?.path ?? "Workspace diff"}+ </DialogTitle>+ </DialogHeader>+ {item.files.length > 1 ? (+ <div+ className="flex max-w-full gap-1 overflow-x-auto pb-1"+ aria-label="Changed files"+ >+ {item.files.map((file) => (+ <Button+ key={file.path}+ type="button"+ size="sm"+ variant={file.path === selected?.path ? "secondary" : "ghost"}+ onClick={() => setSelectedPath(file.path)}+ >+ {file.path}+ </Button>+ ))}+ </div>+ ) : null}+ {selected?.binary ? (+ <p className="rounded-sm bg-muted/50 p-3 text-sm text-muted-foreground">+ Binary file; text diff is unavailable.+ </p>+ ) : selected?.diff ? (+ <pre className="max-h-(--sz-70vh) overflow-auto whitespace-pre rounded-sm bg-muted/50 p-3 font-mono text-xs">+ {selected.diff}+ </pre>+ ) : (+ <p className="rounded-sm bg-muted/50 p-3 text-sm text-muted-foreground">+ No inline patch was recorded for this file.+ </p>+ )}+ </DialogContent>+ </Dialog>+ </>+ );+}++function WorkspaceFileCard({ item }: { item: TaskChatWorkspaceFileItem }) {+ const [open, setOpen] = useState(false);+ const extension = item.displayName.includes(".")+ ? item.displayName.split(".").at(-1)?.toUpperCase()+ : "FILE";+ const label =+ item.presentation === "generic" ? "File" : titleCaseKey(item.presentation);+ const workspaceFileRef = useMemo(+ () => ({+ path: item.path,+ resourceKind: "file" as const,+ line: item.line,+ column: null,+ raw: item.path,+ }),+ [item.line, item.path],+ );+ return (+ <>+ <CardShell+ icon={FileCode2}+ title={item.displayName}+ status={+ item.source === "runner_verified" ? "completed" : "informational"+ }+ summary={`${label} · ${extension}${item.line ? ` · line ${item.line}` : ""}`}+ testId="task-chat-workspace-file"+ >+ <div className="flex flex-wrap items-center gap-2">+ <WorkspaceFileLink+ workspaceFileRef={workspaceFileRef}+ label={item.path}+ />+ <Button+ className="ml-auto"+ type="button"+ size="sm"+ variant="outline"+ onClick={() => setOpen(true)}+ >+ Preview+ </Button>+ </div>+ </CardShell>+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="w-full max-w-(--pct-90) overflow-hidden">+ <DialogHeader>+ <DialogTitle>{item.displayName}</DialogTitle>+ </DialogHeader>+ <p className="font-mono text-xs text-muted-foreground">{item.path}</p>+ {item.preview == null ? (+ <p className="rounded-sm bg-muted/50 p-3 text-sm text-muted-foreground">+ Preview unavailable. The verified workspace reference is still+ available above.+ </p>+ ) : item.presentation === "document" ? (+ <div className="max-h-(--sz-70vh) overflow-auto rounded-sm bg-muted/30 p-3">+ <MarkdownBody>{item.preview}</MarkdownBody>+ </div>+ ) : item.presentation === "image" &&+ item.mediaType?.startsWith("image/") &&+ item.preview.startsWith("data:") ? (+ <img+ className="max-h-(--sz-70vh) max-w-full object-contain"+ alt={item.displayName}+ src={item.preview}+ />+ ) : (+ <pre className="max-h-(--sz-70vh) overflow-auto whitespace-pre-wrap rounded-sm bg-muted/50 p-3 font-mono text-xs">+ {item.preview}+ </pre>+ )}+ {item.previewTruncated ? (+ <p className="text-xs text-muted-foreground">+ Preview truncated by the runner.+ </p>+ ) : null}+ </DialogContent>+ </Dialog>+ </>+ );+}++function titleCaseKey(value: string): string {+ return value+ .replaceAll("_", " ")+ .replace(/\b\w/g, (letter) => letter.toUpperCase());+}++function RuntimeQuestionHistory({+ item,+}: {+ item: TaskChatRuntimeRequestItem;+}) {+ const questionSet = item.questionSet;+ if (!questionSet) return null;+ return (+ <div+ className="flex flex-col gap-2"+ data-testid="task-chat-runtime-request-history"+ >+ {item.response ? (+ <QuestionResponseSummary+ questionSet={questionSet}+ response={item.response}+ />+ ) : (+ <div className="flex flex-col gap-2 text-sm">+ {questionSet.questions.map((question) => (+ <div key={question.id}>+ {question.header ? (+ <p className="text-xs font-medium text-muted-foreground">+ {question.header}+ </p>+ ) : null}+ <p className="text-foreground">{question.prompt}</p>+ </div>+ ))}+ <p className="text-xs text-muted-foreground">+ {item.status === "resolved"+ ? "Answer details were not recorded by this older runtime."+ : `No answers were submitted; this request was ${item.status}.`}+ </p>+ </div>+ )}+ </div>+ );+}++function RuntimeQuestionReceipt({+ item,+}: {+ item: TaskChatRuntimeRequestItem;+}) {+ const label =+ item.status === "resolved"+ ? "Questions answered"+ : item.status === "cancelled"+ ? "Questions cancelled"+ : item.status === "expired"+ ? "Questions expired"+ : "Questions resolved";+ return (+ <details className="group" data-testid="task-chat-runtime-request">+ <summary className="flex min-h-8 cursor-pointer list-none items-center gap-2 rounded-sm px-1 py-1.5 text-sm leading-5 text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <span+ className="flex w-6 shrink-0 items-center justify-center"+ data-testid="task-chat-runtime-request-icon-slot"+ >+ <CircleHelp+ aria-hidden+ className="h-3.5 w-3.5 shrink-0 text-muted-foreground"+ data-testid="task-chat-runtime-request-icon"+ />+ </span>+ <span>{label}</span>+ <ChevronRight+ aria-hidden+ className="ml-auto h-3 w-3 shrink-0 text-muted-foreground opacity-0 transition-[opacity,transform] group-hover:opacity-70 group-focus-visible:opacity-70 group-open:rotate-90"+ data-testid="task-chat-runtime-request-caret"+ />+ </summary>+ <div className="pb-3 pl-7 pr-1">+ <div className="mb-3">+ <p className="text-sm font-medium text-foreground">+ {item.questionSet?.title ?? "Runtime input"}+ </p>+ <p className="mt-1 text-sm text-muted-foreground">{item.prompt}</p>+ </div>+ <RuntimeQuestionHistory item={item} />+ </div>+ </details>+ );+}++function RuntimeRequestCard({+ item,+ onDecision,+ presentation,+ draftKey,+ imageUploadHandler,+ mentions,+}: {+ item: TaskChatRuntimeRequestItem;+ onDecision?: TaskChatProtocolCardProps["onRuntimeRequestDecision"];+ presentation: "timeline" | "takeover";+ draftKey?: string;+ imageUploadHandler?: (file: File) => Promise<string>;+ mentions?: MentionOption[];+}) {+ const title =+ item.questionSet?.title ??+ (item.requestType === "permission"+ ? "Runtime permission"+ : "Runtime input");+ const fields =+ item.fields.length > 0+ ? item.fields+ : [{ name: "answer", label: "Response", placeholder: null }];+ const [values, setValues] = useState<Record<string, string>>(() =>+ draftKey ? loadStructuredDraft(draftKey, {}) : {},+ );+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ useEffect(() => {+ if (!draftKey) setValues({});+ setSubmitting(false);+ setError(null);+ }, [draftKey, item.requestId, item.status]);+ useEffect(() => {+ if (draftKey) saveStructuredDraft(draftKey, values);+ }, [draftKey, values]);++ if (+ presentation === "timeline" &&+ item.requestType === "input" &&+ item.status !== "pending" &&+ item.questionSet+ ) {+ return <RuntimeQuestionReceipt item={item} />;+ }++ const submit = async (decision: TaskChatRuntimeRequestDecision) => {+ if (!onDecision || item.status !== "pending" || submitting) return;+ setSubmitting(true);+ setError(null);+ try {+ await onDecision(item, decision);+ if (draftKey) clearDraft(draftKey);+ } catch (cause) {+ setSubmitting(false);+ setError(+ cause instanceof Error+ ? cause.message+ : "The runtime request could not be resolved.",+ );+ }+ };+ const canSubmitInput = fields.some(+ (field) => (values[field.name] ?? "").trim().length > 0,+ );++ if (+ presentation === "takeover" &&+ item.requestType === "input" &&+ item.status === "pending" &&+ item.questionSet+ ) {+ return (+ <QuestionForm+ id={item.id}+ questionSet={item.questionSet}+ draftKey={draftKey}+ disabled={!onDecision || submitting}+ imageUploadHandler={imageUploadHandler}+ mentions={mentions}+ onSubmit={(response) => submit({ action: "submit", response })}+ />+ );+ }++ return (+ <CardShell+ icon={ShieldCheck}+ title={title}+ status={item.status}+ summary={item.prompt}+ testId="task-chat-runtime-request"+ presentation={presentation}+ >+ {item.requestType === "input" &&+ item.status === "pending" &&+ item.questionSet ? (+ <QuestionForm+ id={item.id}+ questionSet={item.questionSet}+ draftKey={draftKey}+ disabled={!onDecision || submitting}+ imageUploadHandler={imageUploadHandler}+ mentions={mentions}+ onSubmit={(response) => submit({ action: "submit", response })}+ onCancel={+ presentation === "timeline"+ ? () => submit({ action: "cancel" })+ : undefined+ }+ />+ ) : item.requestType === "input" &&+ item.status !== "pending" &&+ item.questionSet ? (+ <RuntimeQuestionHistory item={item} />+ ) : item.requestType === "input" && item.status === "pending" ? (+ <form+ className="flex flex-col gap-3"+ onSubmit={(event) => {+ event.preventDefault();+ if (canSubmitInput) void submit({ action: "submit", values });+ }}+ >+ {fields.map((field) => {+ const inputId = `${item.id}:${field.name}`;+ return (+ <label+ key={field.name}+ className="flex flex-col gap-1.5 text-sm"+ htmlFor={inputId}+ >+ <span className="font-medium text-foreground">+ {field.label}+ </span>+ <Textarea+ id={inputId}+ value={values[field.name] ?? ""}+ placeholder={field.placeholder ?? undefined}+ disabled={!onDecision || submitting}+ rows={2}+ className="resize-y border-0 bg-muted/35 shadow-none focus-visible:ring-0 focus-visible:ring-offset-0"+ onChange={(event) =>+ setValues((current) => ({+ ...current,+ [field.name]: event.target.value,+ }))+ }+ />+ </label>+ );+ })}+ <div className="flex flex-wrap gap-2">+ <Button+ type="submit"+ size="sm"+ disabled={!onDecision || submitting || !canSubmitInput}+ >+ {submitting ? "Submitting…" : "Submit response"}+ </Button>+ {item.choices.some((choice) => choice.key === "decline") ? (+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={!onDecision || submitting}+ onClick={() => void submit({ action: "decline" })}+ >+ Deny+ </Button>+ ) : null}+ {presentation === "timeline" ? (+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={!onDecision || submitting}+ onClick={() => void submit({ action: "cancel" })}+ >+ Cancel+ </Button>+ ) : null}+ </div>+ </form>+ ) : item.status === "pending" && item.choices.length > 0 ? (+ <div className="flex flex-wrap gap-2">+ {item.choices+ .filter(+ (choice) =>+ presentation === "timeline" || choice.key !== "cancel",+ )+ .map((choice) => (+ <Button+ key={choice.key}+ type="button"+ size="sm"+ variant="outline"+ disabled={+ item.status !== "pending" || !onDecision || submitting+ }+ onClick={() => {+ if (+ choice.key === "accept" ||+ choice.key === "accept_for_session" ||+ choice.key === "decline" ||+ choice.key === "cancel"+ ) {+ void submit({ action: choice.key });+ }+ }}+ >+ {submitting ? "Submitting…" : choice.label}+ </Button>+ ))}+ </div>+ ) : null}+ {item.status === "pending" && !onDecision ? (+ <p className="mt-2 text-xs text-muted-foreground">+ Resolve this request in the active runtime session.+ </p>+ ) : null}+ {error ? (+ <p className="mt-2 text-xs text-destructive" role="alert">+ {error}+ </p>+ ) : null}+ </CardShell>+ );+}++function ResultCard({+ item,+}: {+ item: Extract<TaskChatProtocolItem, { surface: "run_result" }>;+}) {+ const hasDetails =+ item.verification.length > 0 ||+ item.remainingWork.length > 0 ||+ item.artifacts.length > 0 ||+ item.blocker;+ return (+ <CardShell+ icon={PackageCheck}+ title="Run result"+ status={item.disposition}+ summary={item.summary}+ testId="task-chat-run-result"+ >+ {hasDetails ? (+ <div className="flex flex-col gap-3 text-sm">+ {item.blocker ? (+ <div className="rounded-sm bg-muted/50 p-2">+ <strong>Blocked: {item.blocker.reasonCode}</strong>+ <p className="mt-1 text-muted-foreground">+ {item.blocker.unblockAction}+ </p>+ </div>+ ) : null}+ {item.verification.length > 0 ? (+ <ul+ className="flex flex-col gap-1"+ aria-label="Verification results"+ >+ {item.verification.map((check, index) => (+ <li+ key={`${check.commandOrCheck}:${index}`}+ className="flex items-start gap-2"+ >+ <StatusIcon+ status={check.status}+ className="mt-0.5 shrink-0"+ />+ <span>+ <span className="font-mono text-xs">+ {check.commandOrCheck}+ </span>+ {check.detail ? (+ <span className="block text-xs text-muted-foreground">+ {check.detail}+ </span>+ ) : null}+ </span>+ </li>+ ))}+ </ul>+ ) : null}+ {item.remainingWork.length > 0 ? (+ <ul className="list-disc space-y-1 pl-5 text-muted-foreground">+ {item.remainingWork.map((work, index) => (+ <li key={`${work.description}:${index}`}>+ {work.description}+ {work.blocksCompletion ? " · blocks completion" : ""}+ </li>+ ))}+ </ul>+ ) : null}+ {item.artifacts.length > 0 ? (+ <div className="flex flex-wrap gap-2">+ {item.artifacts.map((artifact) => (+ <span+ key={`${artifact.kind}:${artifact.ref}`}+ className="rounded-sm border border-border px-2 py-1 font-mono text-xs"+ >+ {artifact.title ?? artifact.ref}+ </span>+ ))}+ </div>+ ) : null}+ </div>+ ) : null}+ </CardShell>+ );+}++function TerminalCard({+ item,+}: {+ item: Extract<TaskChatProtocolItem, { surface: "run_terminal" }>;+}) {+ return (+ <CardShell+ icon={TerminalSquare}+ title="Run ended"+ status={item.runState}+ summary={[item.disposition.replaceAll("_", " "), item.stopReason]+ .filter(Boolean)+ .join(" · ")}+ testId="task-chat-run-terminal"+ />+ );+}++function ResourceCard({+ item,+}: {+ item: Extract<TaskChatProtocolItem, { surface: "resource" }>;+}) {+ const Icon =+ item.resourceKind === "document"+ ? FileText+ : item.resourceKind === "attachment"+ ? FileCode2+ : PackageCheck;+ const body = (+ <CardShell+ icon={Icon}+ title={item.title}+ status="completed"+ summary={item.subtitle}+ testId={`task-chat-resource-${item.resourceKind}`}+ />+ );+ return item.href ? (+ <a+ className="block rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ href={item.href}+ >+ {body}+ </a>+ ) : (+ body+ );+}++export function TaskChatProtocolCard({+ item,+ onRuntimeRequestDecision,+ presentation = "timeline",+ draftKey,+ imageUploadHandler,+ mentions,+}: TaskChatProtocolCardProps) {+ switch (item.surface) {+ case "provider_activity":+ return <ProviderActivityCard item={item} />;+ case "workspace_change":+ return <WorkspaceChangeCard item={item} />;+ case "workspace_file":+ return <WorkspaceFileCard item={item} />;+ case "runtime_request":+ return (+ <RuntimeRequestCard+ item={item}+ onDecision={onRuntimeRequestDecision}+ presentation={presentation}+ draftKey={draftKey}+ imageUploadHandler={imageUploadHandler}+ mentions={mentions}+ />+ );+ case "run_result":+ return <ResultCard item={item} />;+ case "run_terminal":+ return <TerminalCard item={item} />;+ case "resource":+ return <ResourceCard item={item} />;+ default: {+ const unreachable: never = item;+ return unreachable;+ }+ }+}diff --git a/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx b/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsxnew file mode 100644index 0000000000..fd0ea64faa--- /dev/null+++ b/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx@@ -0,0 +1,165 @@+// @vitest-environment jsdom++import { act, type ComponentProps } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { IssueQueuedCommentQueue } from "@paperclipai/shared";+import { TaskChatQueuedMessages } from "./TaskChatQueuedMessages";++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((innerResolve) => {+ resolve = innerResolve;+ });+ return { promise, resolve };+}++const queue: IssueQueuedCommentQueue = {+ issueId: "issue-1",+ queueId: "wake-1",+ state: "deferred",+ targetRunId: "run-1",+ revision: "rev-1",+ protocol: "paperclip_runner_v1",+ steeringDisposition: "available",+ entries: ["First queued message", "Second queued message"].map((body, position) => ({+ comment: {+ id: `comment-${position + 1}`,+ companyId: "company-1",+ issueId: "issue-1",+ authorType: "user",+ authorAgentId: null,+ authorUserId: "user-1",+ body,+ presentation: null,+ metadata: null,+ createdAt: new Date(),+ updatedAt: new Date(),+ },+ position,+ canEdit: true,+ canDiscard: true,+ })),+};++describe("TaskChatQueuedMessages", () => {+ let container: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ });++ afterEach(() => {+ flushSync(() => root.unmount());+ container.remove();+ });++ function render(overrides: Partial<ComponentProps<typeof TaskChatQueuedMessages>> = {}) {+ const props = {+ queue,+ onEdit: vi.fn(),+ onReorder: vi.fn().mockResolvedValue(undefined),+ onSteer: vi.fn().mockResolvedValue(undefined),+ onDiscard: vi.fn().mockResolvedValue(undefined),+ ...overrides,+ };+ flushSync(() => root.render(<TaskChatQueuedMessages {...props} />));+ return props;+ }++ it("renders each queued message once as a compact one-line row", () => {+ render();+ const pane = container.querySelector('[data-testid="task-chat-queued-messages"]');+ expect(pane?.classList).toContain("mx-3");+ expect(pane?.classList).toContain("rounded-b-none");+ expect(pane?.classList).toContain("border-b-0");+ expect(pane?.classList).toContain("-mb-px");+ expect(container.querySelectorAll('[data-testid^="task-chat-queued-message-"]')).toHaveLength(2);+ expect(container.textContent).toContain("First queued message");+ expect(container.textContent).toContain("Second queued message");+ });++ it("removes only the acknowledged steering row", async () => {+ const props = render();+ await act(async () => {+ container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-steer-comment-1"]')?.click();+ });+ expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-1");+ expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).toBeNull();+ expect(container.querySelector('[data-testid="task-chat-queued-message-comment-2"]')).not.toBeNull();+ });++ it("keeps a row queued when steering fails and announces the retryable state", async () => {+ render({ onSteer: vi.fn().mockRejectedValue(new Error("steering_timeout")) });+ await act(async () => {+ container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-steer-comment-1"]')?.click();+ });+ expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).not.toBeNull();+ expect(container.textContent).toContain("Couldn’t steer. Message is still queued.");+ });++ it("disables steering when the provider does not advertise it", () => {+ render({ queue: { ...queue, steeringDisposition: "unsupported" } });+ expect(container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-steer-comment-1"]')?.disabled)+ .toBe(true);+ });++ it("waits for authoritative discard acknowledgement before removing the row", async () => {+ const acknowledgement = deferred<void>();+ render({ onDiscard: vi.fn().mockReturnValue(acknowledgement.promise) });+ await act(async () => {+ container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-discard-comment-1"]')?.click();+ await Promise.resolve();+ });+ expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).not.toBeNull();+ expect(container.textContent).not.toContain("Queued message discarded.");++ await act(async () => {+ acknowledgement.resolve();+ await acknowledgement.promise;+ });+ expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).toBeNull();+ expect(container.textContent).toContain("Queued message discarded.");+ });++ it("keeps a too-late discard visible with an explicit error", async () => {+ render({+ onDiscard: vi.fn().mockRejectedValue({+ body: { details: { code: "queued_comment_already_dispatching" } },+ }),+ });+ await act(async () => {+ container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-discard-comment-1"]')?.click();+ });+ expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).not.toBeNull();+ expect(container.textContent).toContain("Too late to discard: this message is already being sent.");+ });++ it("shows stale revisions without announcing a discard", async () => {+ render({+ onDiscard: vi.fn().mockRejectedValue({+ body: { details: { code: "queued_comment_revision_conflict" } },+ }),+ });+ await act(async () => {+ container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-discard-comment-1"]')?.click();+ });+ expect(container.textContent).toContain("The queue changed in another session. Review it and try again.");+ expect(container.textContent).not.toContain("Queued message discarded.");+ });++ it("does not expose queue controls before a real queue id is acknowledged", () => {+ const props = render({ queue: { ...queue, queueId: null, state: null } });+ const discard = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-queued-discard-comment-1"]',+ );+ expect(discard?.disabled).toBe(true);+ discard?.click();+ expect(props.onDiscard).not.toHaveBeenCalled();+ });++});diff --git a/ui/src/components/task-chat/TaskChatQueuedMessages.tsx b/ui/src/components/task-chat/TaskChatQueuedMessages.tsxnew file mode 100644index 0000000000..1f9670e705--- /dev/null+++ b/ui/src/components/task-chat/TaskChatQueuedMessages.tsx@@ -0,0 +1,295 @@+import { useEffect, useMemo, useState } from "react";+import {+ DndContext,+ KeyboardSensor,+ PointerSensor,+ closestCenter,+ useSensor,+ useSensors,+ type DragEndEvent,+} from "@dnd-kit/core";+import {+ SortableContext,+ arrayMove,+ sortableKeyboardCoordinates,+ useSortable,+ verticalListSortingStrategy,+} from "@dnd-kit/sortable";+import { CSS } from "@dnd-kit/utilities";+import {+ CornerDownRight,+ GripVertical,+ Loader2,+ MoreHorizontal,+ Pencil,+ Trash2,+} from "lucide-react";+import type {+ IssueQueuedCommentEntry,+ IssueQueuedCommentQueue,+} from "@paperclipai/shared";+import { cn } from "@/lib/utils";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";++type QueueAction = "steer" | "discard" | null;++function queueActionErrorCode(error: unknown): string | null {+ if (typeof error !== "object" || error === null) return null;+ const body = (error as { body?: unknown }).body;+ if (typeof body !== "object" || body === null) return null;+ const directCode = (body as { code?: unknown }).code;+ if (typeof directCode === "string") return directCode;+ const details = (body as { details?: unknown }).details;+ if (typeof details !== "object" || details === null) return null;+ const detailCode = (details as { code?: unknown }).code;+ return typeof detailCode === "string" ? detailCode : null;+}++export interface TaskChatQueuedMessagesProps {+ queue: IssueQueuedCommentQueue;+ onEdit: (commentId: string) => void;+ onReorder: (orderedCommentIds: string[], revision: string) => Promise<void>;+ onSteer: (commentId: string, revision: string) => Promise<void>;+ onDiscard: (commentId: string, revision: string) => Promise<void>;+}++function SortableQueuedMessage({+ entry,+ queue,+ disabled,+ action,+ onEdit,+ onSteer,+ onDiscard,+}: {+ entry: IssueQueuedCommentEntry;+ queue: IssueQueuedCommentQueue;+ disabled: boolean;+ action: QueueAction;+ onEdit: () => void;+ onSteer: () => void;+ onDiscard: () => void;+}) {+ const sortable = useSortable({ id: entry.comment.id, disabled });+ const style = {+ transform: CSS.Transform.toString(sortable.transform),+ transition: sortable.transition,+ };+ const steerDisabled = disabled || queue.steeringDisposition !== "available";+ const steerTitle =+ queue.steeringDisposition === "unsupported"+ ? "This runner does not support steering"+ : queue.steeringDisposition === "temporarily_unavailable"+ ? "Steering is temporarily unavailable"+ : "Steer this message into the active turn";++ return (+ <div+ ref={sortable.setNodeRef}+ style={style}+ className={cn(+ "group flex h-11 min-w-0 items-center gap-1 border-b border-border/55 bg-card/95 px-2.5 text-sm last:border-b-0",+ sortable.isDragging && "relative z-20 rounded-lg border border-border shadow-lg",+ )}+ data-testid={`task-chat-queued-message-${entry.comment.id}`}+ >+ <button+ type="button"+ ref={sortable.setActivatorNodeRef}+ {...sortable.attributes}+ {...sortable.listeners}+ disabled={disabled}+ aria-label={`Reorder queued message: ${entry.comment.body}`}+ className="flex h-7 w-7 shrink-0 cursor-grab items-center justify-center rounded-md text-muted-foreground/70 transition-colors hover:bg-accent hover:text-foreground active:cursor-grabbing disabled:cursor-default disabled:opacity-40"+ >+ <GripVertical className="h-3.5 w-3.5" aria-hidden />+ </button>++ <CornerDownRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />+ <span className="min-w-0 flex-1 truncate px-1" title={entry.comment.body}>+ {entry.comment.body}+ </span>++ <button+ type="button"+ onClick={onSteer}+ disabled={steerDisabled}+ title={steerTitle}+ className="flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"+ data-testid={`task-chat-queued-steer-${entry.comment.id}`}+ >+ {action === "steer" ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ ) : (+ <CornerDownRight className="h-3.5 w-3.5" aria-hidden />+ )}+ Steer+ </button>++ <button+ type="button"+ onClick={onDiscard}+ disabled={disabled || !entry.canDiscard}+ title="Discard queued message"+ aria-label={`Discard queued message: ${entry.comment.body}`}+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive disabled:opacity-40"+ data-testid={`task-chat-queued-discard-${entry.comment.id}`}+ >+ {action === "discard" ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ ) : (+ <Trash2 className="h-3.5 w-3.5" aria-hidden />+ )}+ </button>++ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ disabled={disabled}+ title="Queued message actions"+ aria-label={`Queued message actions: ${entry.comment.body}`}+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"+ >+ <MoreHorizontal className="h-4 w-4" aria-hidden />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-44">+ <DropdownMenuItem disabled={!entry.canEdit} onSelect={onEdit}>+ <Pencil className="h-4 w-4" aria-hidden />+ Edit message+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}++/** Compact production queue shown immediately above the default task composer. */+export function TaskChatQueuedMessages({+ queue,+ onEdit,+ onReorder,+ onSteer,+ onDiscard,+}: TaskChatQueuedMessagesProps) {+ const [entries, setEntries] = useState(queue.entries);+ const [pending, setPending] = useState<{ commentId: string; action: Exclude<QueueAction, null> } | null>(null);+ const [reordering, setReordering] = useState(false);+ const [announcement, setAnnouncement] = useState("");+ const [visibleError, setVisibleError] = useState<string | null>(null);+ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),+ );++ useEffect(() => {+ setEntries(queue.entries);+ }, [queue.entries, queue.revision]);++ const ids = useMemo(() => entries.map((entry) => entry.comment.id), [entries]);++ async function handleDragEnd(event: DragEndEvent) {+ const { active, over } = event;+ if (!queue.queueId || !over || active.id === over.id || reordering || pending) return;+ const from = ids.indexOf(String(active.id));+ const to = ids.indexOf(String(over.id));+ if (from < 0 || to < 0) return;++ const previous = entries;+ const next = arrayMove(entries, from, to).map((entry, position) => ({ ...entry, position }));+ const orderedIds = next.map((entry) => entry.comment.id);+ setEntries(next);+ setReordering(true);+ setVisibleError(null);+ setAnnouncement(`Moved queued message to position ${to + 1} of ${next.length}.`);+ try {+ await onReorder(orderedIds, queue.revision);+ } catch (error) {+ setEntries(previous);+ setAnnouncement("");+ setVisibleError(+ queueActionErrorCode(error) === "queued_comment_revision_conflict"+ ? "The queue changed in another session. Its latest order has been restored."+ : "Couldn’t reorder. Previous order restored.",+ );+ } finally {+ setReordering(false);+ }+ }++ async function runRowAction(commentId: string, action: Exclude<QueueAction, null>) {+ if (!queue.queueId || pending || reordering) return;+ setPending({ commentId, action });+ setVisibleError(null);+ setAnnouncement(action === "steer" ? "Steering queued message." : "Discarding queued message.");+ try {+ if (action === "steer") await onSteer(commentId, queue.revision);+ else await onDiscard(commentId, queue.revision);+ setEntries((current) => current.filter((entry) => entry.comment.id !== commentId));+ setAnnouncement(action === "steer" ? "Message steered into the active turn." : "Queued message discarded.");+ } catch (error) {+ setAnnouncement("");+ const code = queueActionErrorCode(error);+ setVisibleError(+ code === "queued_comment_already_dispatching"+ ? "Too late to discard: this message is already being sent."+ : action === "steer"+ ? "Couldn’t steer. Message is still queued."+ : code === "queued_comment_revision_conflict"+ ? "The queue changed in another session. Review it and try again."+ : "Couldn’t discard. Message is still queued.",+ );+ } finally {+ setPending(null);+ }+ }++ if (entries.length === 0) return null;++ return (+ <div+ className="relative z-0 mx-3 -mb-px overflow-hidden rounded-t-xl rounded-b-none border border-b-0 border-border/75 bg-card shadow-sm"+ data-testid="task-chat-queued-messages"+ aria-label="Queued messages"+ >+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={(event) => void handleDragEnd(event)}>+ <SortableContext items={ids} strategy={verticalListSortingStrategy}>+ {entries.map((entry) => {+ const action = pending?.commentId === entry.comment.id ? pending.action : null;+ const disabled = Boolean(!queue.queueId || pending || reordering);+ return (+ <SortableQueuedMessage+ key={entry.comment.id}+ entry={entry}+ queue={queue}+ disabled={disabled}+ action={action}+ onEdit={() => onEdit(entry.comment.id)}+ onSteer={() => void runRowAction(entry.comment.id, "steer")}+ onDiscard={() => void runRowAction(entry.comment.id, "discard")}+ />+ );+ })}+ </SortableContext>+ </DndContext>+ {visibleError ? (+ <div+ role="status"+ aria-live="polite"+ className="border-t border-destructive/20 bg-destructive/5 px-3 py-1.5 text-xs text-destructive"+ >+ {visibleError}+ </div>+ ) : null}+ <div className="sr-only" aria-live="polite" aria-atomic="true">+ {announcement}+ </div>+ </div>+ );+}diff --git a/ui/src/components/task-chat/TaskChatRichInput.tsx b/ui/src/components/task-chat/TaskChatRichInput.tsxnew file mode 100644index 0000000000..151690879a--- /dev/null+++ b/ui/src/components/task-chat/TaskChatRichInput.tsx@@ -0,0 +1,145 @@+import { useEffect, useRef, useState } from "react";+import { ImagePlus, Loader2 } from "lucide-react";+import {+ MarkdownEditor,+ type MarkdownEditorRef,+ type MentionOption,+} from "@/components/MarkdownEditor";+import { Button } from "@/components/ui/button";++interface TaskChatRichInputProps {+ value: string;+ onChange: (value: string) => void;+ placeholder?: string;+ imageUploadHandler?: (file: File) => Promise<string>;+ mentions?: MentionOption[];+ disabled?: boolean;+ autoFocus?: boolean;+ onSubmit?: () => void;+ onUploadingChange?: (uploading: boolean) => void;+ ariaLabelledBy?: string;+ testId?: string;+ attachAriaLabel?: string;+}++/** Composer-grade rich text field for takeover answers and revision notes. */+export function TaskChatRichInput({+ value,+ onChange,+ placeholder,+ imageUploadHandler,+ mentions,+ disabled = false,+ autoFocus = false,+ onSubmit,+ onUploadingChange,+ ariaLabelledBy,+ testId = "task-chat-rich-input",+ attachAriaLabel = "Attach image",+}: TaskChatRichInputProps) {+ const editorRef = useRef<MarkdownEditorRef>(null);+ const fileInputRef = useRef<HTMLInputElement>(null);+ const uploadCountRef = useRef(0);+ const [uploading, setUploading] = useState(false);+ const [uploadError, setUploadError] = useState<string | null>(null);++ useEffect(() => {+ if (!autoFocus) return;+ const frame = requestAnimationFrame(() => editorRef.current?.focus());+ return () => cancelAnimationFrame(frame);+ }, [autoFocus]);++ function updateUploading(next: boolean) {+ setUploading(next);+ onUploadingChange?.(next);+ }++ async function uploadImage(file: File): Promise<string> {+ if (!imageUploadHandler) throw new Error("Image uploads are unavailable.");+ uploadCountRef.current += 1;+ updateUploading(true);+ setUploadError(null);+ try {+ return await imageUploadHandler(file);+ } catch (error) {+ setUploadError(+ error instanceof Error+ ? error.message+ : "The image could not be uploaded.",+ );+ throw error;+ } finally {+ uploadCountRef.current = Math.max(0, uploadCountRef.current - 1);+ if (uploadCountRef.current === 0) updateUploading(false);+ }+ }++ async function chooseImage(file: File | null) {+ if (!file) return;+ try {+ const url = await uploadImage(file);+ const alt = (file.name || "image").replace(/[[\]]/g, "\\$&");+ editorRef.current?.insertMarkdown(`\n\n\n\n`);+ } catch {+ // uploadImage owns the visible error state.+ }+ }++ return (+ <div+ className="rounded-md bg-muted/35 px-3 py-2"+ role="group"+ aria-labelledby={ariaLabelledBy}+ data-testid={testId}+ >+ <MarkdownEditor+ ref={editorRef}+ value={value}+ onChange={onChange}+ placeholder={placeholder}+ imageUploadHandler={imageUploadHandler ? uploadImage : undefined}+ mentions={mentions}+ readOnly={disabled}+ onSubmit={onSubmit}+ bordered={false}+ contentClassName="max-h-(--sz-28dvh) min-h-(--sz-72px) overflow-y-auto px-0 py-0 text-sm scrollbar-auto-hide"+ />+ {imageUploadHandler ? (+ <div className="mt-1 flex flex-wrap items-center gap-1 text-xs text-muted-foreground">+ <input+ ref={fileInputRef}+ type="file"+ accept="image/*"+ className="hidden"+ aria-label={attachAriaLabel}+ onChange={(event) => {+ void chooseImage(event.target.files?.[0] ?? null);+ event.target.value = "";+ }}+ />+ <Button+ type="button"+ size="sm"+ variant="ghost"+ className="-ml-2 h-7 px-2"+ disabled={disabled || uploading}+ onClick={() => fileInputRef.current?.click()}+ >+ {uploading ? (+ <Loader2 aria-hidden className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <ImagePlus aria-hidden className="h-3.5 w-3.5" />+ )}+ Attach image+ </Button>+ <span>or drop/paste an image into the note</span>+ </div>+ ) : null}+ {uploadError ? (+ <p className="mt-1 text-xs text-destructive" role="alert">+ {uploadError}+ </p>+ ) : null}+ </div>+ );+}diff --git a/ui/src/components/task-chat/TaskChatRunnerTurn.test.tsx b/ui/src/components/task-chat/TaskChatRunnerTurn.test.tsxnew file mode 100644index 0000000000..2e79e5c8fd--- /dev/null+++ b/ui/src/components/task-chat/TaskChatRunnerTurn.test.tsx@@ -0,0 +1,1474 @@+// @vitest-environment jsdom++import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ThemeProvider } from "@/context/ThemeContext";+import { MemoryRouter } from "@/lib/router";+import { TaskChatRunnerTurn } from "./TaskChatRunnerTurn";+import type {+ TaskChatItem,+ TaskChatProviderActivityFamily,+ TaskChatProviderActivityItem,+ TaskChatRuntimeRequestDecision,+ TaskChatRuntimeRequestItem,+} from "./task-chat-model";++describe("TaskChatRunnerTurn", () => {+ let container: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ });++ afterEach(() => {+ act(() => root.unmount());+ container.remove();+ });++ const render = (+ items: TaskChatItem[],+ status = "running",+ runId = "run-1",+ onRuntimeRequestDecision?: (+ item: TaskChatRuntimeRequestItem,+ decision: TaskChatRuntimeRequestDecision,+ ) => void,+ ) =>+ act(() =>+ root.render(+ <MemoryRouter>+ <ThemeProvider>+ <TaskChatRunnerTurn+ runId={runId}+ agentName="Runner"+ items={items}+ status={status}+ startedAtMs={Date.now() - 2_000}+ onRuntimeRequestDecision={onRuntimeRequestDecision}+ />+ </ThemeProvider>+ </MemoryRouter>,+ ),+ );++ const resolvedQuestion = (+ id: string,+ prompt: string,+ ): TaskChatRuntimeRequestItem => ({+ id,+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-1",+ requestId: id,+ requestKind: "user_input",+ turnId: "turn-1",+ requestType: "input",+ status: "resolved",+ prompt: "Codex needs your input.",+ choices: [],+ fields: [],+ questionSet: {+ schema: "paperclip.question_set.v1",+ questions: [+ { id: `${id}-field`, prompt, required: true, answerMode: "text" },+ ],+ },+ response: {+ schema: "paperclip.question_response.v1",+ answers: { [`${id}-field`]: { text: "Answered" } },+ },+ });++ it("shows a stable Working header with Thinking at the turn tail", () => {+ render([], "queued");+ expect(container.textContent).toContain("Thinking");+ expect(container.textContent).toContain("Runner");+ expect(+ container.querySelector(+ '[data-testid="task-chat-runner-disclosure-caret"]',+ ),+ ).toBeNull();+ expect(+ container.querySelector(+ '[data-testid="task-chat-current-activity-icon"]',+ ),+ ).toBeNull();+ expect(+ container.querySelector(+ '[data-testid="task-chat-current-activity-label"]',+ )?.textContent,+ ).toBe("Thinking");+ expect(+ container.querySelector('[data-testid="task-chat-current-activity"]')+ ?.tagName,+ ).toBe("DIV");+ expect(+ container.querySelector('[data-testid="task-chat-turn-status-header"]')+ ?.textContent,+ ).toContain("Working for");+ expect(container.textContent).not.toContain("Waiting for transcript");+ const identity = container.querySelector(+ '[data-testid="task-chat-agent-identity"]',+ );+ const status = container.querySelector(+ '[data-testid="task-chat-turn-status-header"]',+ );+ const identityRow = container.querySelector(+ '[data-testid="task-chat-runner-identity-row"]',+ );+ const activity = container.querySelector(+ '[data-testid="task-chat-current-activity"]',+ );+ expect(identity?.parentElement).toBe(identityRow);+ expect(status?.parentElement).toBe(identityRow);+ expect(status?.getAttribute("data-turn-position")).toBe("identity");+ expect(identity?.compareDocumentPosition(activity!)).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ expect(activity?.getAttribute("data-turn-position")).toBe("tail");+ expect(activity?.classList.contains("px-1")).toBe(true);+ expect(activity?.firstElementChild?.hasAttribute("aria-hidden")).toBe(+ false,+ );+ });++ it("keeps progress mounted above its grouped current command", () => {+ render([+ {+ id: "p1",+ kind: "message",+ author: "agent",+ text: "Running the exact command now.",+ interstitial: true,+ channel: "progress",+ streaming: true,+ },+ {+ id: "t1",+ kind: "tool",+ name: "command",+ rawName: "Bash",+ target: "for i in 1 2 3 4; do echo STREAM-$i; done",+ status: "in_progress",+ detail: "STREAM-1\n",+ },+ ]);+ expect(+ container.querySelector('[data-testid="task-chat-phase-interstitial"]')+ ?.textContent,+ ).toContain("Running the exact command now.");+ expect(+ container.querySelector('[data-testid="task-chat-phase-summary"]')+ ?.textContent,+ ).toContain("Ran a command");+ expect(+ container.querySelector('[data-testid="task-chat-current-activity"]')+ ?.textContent,+ ).toContain("Running a command");+ expect(container.textContent).toContain("STREAM-$i");+ const identity = container.querySelector(+ '[data-testid="task-chat-agent-identity"]',+ );+ const activity = container.querySelector(+ '[data-testid="task-chat-current-activity"]',+ );+ const timeline = container.querySelector(+ '[data-testid="task-chat-turn-timeline"]',+ );+ expect(identity?.compareDocumentPosition(timeline!)).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ expect(timeline?.compareDocumentPosition(activity!)).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ expect(+ container+ .querySelector('[data-testid="task-chat-runner-identity-row"]')+ ?.classList.contains("pt-2"),+ ).toBe(true);+ });++ it("keeps the timer at the top and moves resumed Thinking below completed activity", () => {+ render([+ {+ id: "commentary",+ kind: "message",+ author: "agent",+ text: "I’ll inspect the workspace.",+ interstitial: true,+ channel: "progress",+ },+ {+ id: "tool",+ kind: "tool",+ name: "Command",+ rawName: "bash",+ status: "completed",+ },+ {+ id: "thinking",+ kind: "thinking",+ lines: [],+ lifecycleOnly: true,+ streaming: true,+ },+ ]);++ const header = container.querySelector(+ '[data-testid="task-chat-turn-status-header"]',+ );+ const timeline = container.querySelector(+ '[data-testid="task-chat-turn-timeline"]',+ );+ const activity = container.querySelector(+ '[data-testid="task-chat-current-activity"]',+ );+ expect(header?.textContent).toContain("Working for");+ expect(activity?.textContent).toBe("Thinking");+ expect(header?.compareDocumentPosition(timeline!)).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ expect(timeline?.compareDocumentPosition(activity!)).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ });++ it("keeps earlier commentary mounted when later commentary streams", () => {+ render([+ {+ id: "commentary",+ kind: "message",+ author: "agent",+ text: "I’ll inspect the card.",+ interstitial: true,+ channel: "progress",+ transcriptIndex: 1,+ },+ {+ id: "reasoning",+ kind: "thinking",+ lines: ["The saved preview can be reused."],+ streaming: true,+ channel: "summary",+ transcriptIndex: 2,+ },+ ]);+ expect(+ container.querySelector('[data-testid="task-chat-phase-interstitial"]')+ ?.textContent,+ ).toContain("I’ll inspect the card.");++ render([+ {+ id: "commentary",+ kind: "message",+ author: "agent",+ text: "I’ll inspect the card.",+ interstitial: true,+ channel: "progress",+ transcriptIndex: 1,+ },+ {+ id: "reasoning",+ kind: "thinking",+ lines: ["The saved preview can be reused."],+ streaming: true,+ channel: "summary",+ transcriptIndex: 2,+ },+ {+ id: "commentary-later",+ kind: "message",+ author: "agent",+ text: "I’ve found the rendering seam.",+ interstitial: true,+ channel: "progress",+ transcriptIndex: 3,+ },+ ]);+ const commentary = container.querySelectorAll(+ '[data-testid="task-chat-phase-interstitial"]',+ );+ expect(commentary).toHaveLength(2);+ expect(commentary[0]?.textContent).toContain("I’ll inspect the card.");+ expect(commentary[1]?.textContent).toContain(+ "I’ve found the rendering seam.",+ );+ expect(+ container.querySelector('[data-testid="task-chat-thinking"]'),+ ).toBeNull();+ act(() =>+ container+ .querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-phase-summary"]',+ )+ ?.click(),+ );+ expect(+ container.querySelector('[data-testid="task-chat-thinking"]')+ ?.textContent,+ ).toContain("Reasoning");+ });++ it("starts a separate activity group at every commentary boundary", () => {+ render([+ {+ id: "commentary-one",+ kind: "message",+ author: "agent",+ text: "First phase.",+ interstitial: true,+ channel: "progress",+ },+ {+ id: "tool-one",+ kind: "tool",+ name: "Read",+ rawName: "read_file",+ status: "completed",+ },+ {+ id: "commentary-two",+ kind: "message",+ author: "agent",+ text: "Second phase.",+ interstitial: true,+ channel: "progress",+ },+ {+ id: "tool-two",+ kind: "tool",+ name: "Bash",+ rawName: "bash",+ status: "completed",+ },+ ]);+ const rows = container.querySelectorAll(+ '[data-testid="task-chat-turn-timeline-row"]',+ );+ expect(rows).toHaveLength(2);+ expect(rows[0]?.textContent).toContain("First phase.");+ expect(rows[0]?.textContent).toContain("Read a file");+ expect(rows[1]?.textContent).toContain("Second phase.");+ expect(rows[1]?.textContent).toContain("Ran a command");+ act(() =>+ rows[0]+ ?.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-phase-summary"]',+ )+ ?.click(),+ );+ expect(+ rows[0]+ ?.querySelector('[data-testid="task-chat-tool-icon"]')+ ?.parentElement?.classList.contains("w-5"),+ ).toBe(true);+ });++ it("keeps internal reasoning nested inside its activity group", () => {+ render([+ {+ id: "summary",+ kind: "thinking",+ lines: ["Inspect the current card."],+ streaming: false,+ channel: "summary",+ transcriptIndex: 1,+ },+ {+ id: "detail",+ kind: "thinking",+ lines: ["Keep the canonical revision atomic."],+ streaming: true,+ channel: "detail",+ transcriptIndex: 2,+ },+ ]);+ expect(+ container.querySelectorAll('[data-testid="task-chat-thinking"]'),+ ).toHaveLength(0);+ act(() =>+ container+ .querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-phase-summary"]',+ )+ ?.click(),+ );+ const history = container.querySelector(+ '[data-testid="task-chat-runner-activity-list"]',+ );+ const rail = container.querySelector(+ '[data-testid="task-chat-runner-activity-rail"]',+ )?.parentElement;+ expect(rail?.classList.contains("pl-6")).toBe(true);+ expect(rail?.classList.contains("ml-4")).toBe(true);+ expect(history?.textContent).toContain("Inspect the current card.");+ expect(history?.textContent).toContain("Keep the canonical revision atomic.");+ const thinkingRows = history?.querySelectorAll(+ '[data-testid="task-chat-thinking"]',+ );+ expect(thinkingRows).toHaveLength(2);+ expect(thinkingRows?.[0]?.textContent).not.toContain("Reasoning");+ expect(thinkingRows?.[0]?.querySelector(".shimmer-text")).toBeNull();+ expect(+ thinkingRows?.[0]+ ?.querySelector('[data-testid="task-chat-thinking-icon"]')+ ?.classList.contains("text-(--status-agent-running)"),+ ).toBe(false);+ expect(thinkingRows?.[1]?.textContent).toContain("Reasoning detail…");+ expect(thinkingRows?.[1]?.querySelector(".shimmer-text")).not.toBeNull();+ expect(+ thinkingRows?.[1]+ ?.querySelector('[data-testid="task-chat-thinking-icon"]')+ ?.classList.contains("text-(--status-agent-running)"),+ ).toBe(true);+ expect(thinkingRows?.[0]?.classList.contains("text-xs")).toBe(true);+ expect(thinkingRows?.[0]?.classList.contains("font-normal")).toBe(true);+ expect(+ thinkingRows?.[0]+ ?.querySelector('[data-testid="task-chat-thinking-icon"]')+ ?.parentElement?.classList.contains("w-5"),+ ).toBe(true);+ expect(+ thinkingRows?.[0]+ ?.querySelector('[data-testid="task-chat-thinking-icon"]')+ ?.parentElement?.classList.contains("justify-center"),+ ).toBe(true);+ expect(+ thinkingRows?.[0]?.querySelector(+ '[data-testid="task-chat-thinking-text"]',+ )?.textContent,+ ).toContain("Inspect the current card.");+ expect(+ thinkingRows?.[0]?.querySelector(".task-chat-reasoning-markdown"),+ ).toBeNull();+ expect(+ thinkingRows?.[1]?.querySelector("button")?.classList.contains(+ "font-normal",+ ),+ ).toBe(true);+ });++ it("renders only the current reasoning block as active", () => {+ render([+ {+ id: "old-reasoning",+ kind: "thinking",+ lines: ["Inspect the current card."],+ streaming: true,+ transcriptIndex: 1,+ },+ {+ id: "read",+ kind: "tool",+ name: "Read files",+ rawName: "Read",+ status: "completed",+ },+ {+ id: "current-reasoning",+ kind: "thinking",+ lines: ["Verify the updated state."],+ streaming: true,+ transcriptIndex: 3,+ },+ ]);++ act(() =>+ container+ .querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-phase-summary"]',+ )+ ?.click(),+ );++ const oldReasoning = container.querySelector(+ '[data-activity-item-id="old-reasoning"]',+ );+ expect(oldReasoning?.textContent).toBe("Inspect the current card.");+ expect(oldReasoning?.querySelector(".shimmer-text")).toBeNull();+ expect(+ oldReasoning?.querySelector('[data-testid="task-chat-thinking-text"]'),+ ).not.toBeNull();++ const currentReasoning = container.querySelector(+ '[data-activity-item-id="current-reasoning"]',+ );+ expect(currentReasoning?.textContent).toContain("Reasoning…");+ expect(+ currentReasoning+ ?.querySelector('[data-testid="task-chat-thinking-icon"]')+ ?.classList.contains("text-(--status-agent-running)"),+ ).toBe(true);+ });++ it("does not let a textless reasoning lifecycle remove sticky commentary", () => {+ render([+ {+ id: "commentary",+ kind: "message",+ author: "agent",+ text: "Old commentary",+ interstitial: true,+ channel: "progress",+ transcriptIndex: 1,+ },+ {+ id: "reasoning",+ kind: "thinking",+ lines: [],+ lifecycleOnly: true,+ streaming: true,+ transcriptIndex: 2,+ },+ ]);+ expect(+ container.querySelector('[data-testid="task-chat-phase-interstitial"]')+ ?.textContent,+ ).toContain("Old commentary");+ expect(+ container.querySelector('[data-testid="task-chat-phase-summary"]'),+ ).toBeNull();+ expect(+ container.querySelector(+ '[data-testid="task-chat-current-activity-label"]',+ )?.textContent,+ ).toBe("Thinking");+ });++ it("keeps the within-turn plan in activity history without rendering a Plan document preview", () => {+ const activity: TaskChatProviderActivityItem = {+ id: "live-plan",+ kind: "protocol",+ surface: "provider_activity",+ family: "plan",+ eventType: "plan.updated",+ status: "running",+ title: "Plan",+ details: [{ label: "Revision", value: "4" }],+ steps: [+ {+ id: "one",+ label: "Extract the shared preview",+ status: "in_progress",+ },+ ],+ links: [],+ children: [],+ transcriptIndex: 1,+ };+ render([activity]);+ expect(+ container.querySelector('[data-testid="task-chat-live-plan-preview"]'),+ ).toBeNull();+ const disclosure = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-phase-summary"]',+ );+ expect(disclosure?.getAttribute("aria-label")).toContain("Expand activity");+ act(() => disclosure?.click());+ const history = container.querySelector(+ '[data-testid="task-chat-runner-activity-list"]',+ );+ expect(history?.textContent).toContain("Updating the plan");+ expect(+ history?.querySelector('[data-activity-family="plan"]'),+ ).not.toBeNull();+ expect(+ history?.querySelector('[data-testid="task-chat-protocol-activity-icon"]')+ ?.parentElement?.classList.contains("w-5"),+ ).toBe(true);+ });++ it("shows canonical web research as the current Codex-style activity", () => {+ render([+ {+ id: "research-1",+ kind: "protocol",+ surface: "provider_activity",+ family: "research",+ eventType: "research.started",+ status: "running",+ title: "Research",+ summary: "site:openai.com model guide GPT-5.4",+ details: [+ { label: "Query", value: "site:openai.com model guide GPT-5.4" },+ ],+ steps: [],+ links: [],+ children: [],+ },+ ]);++ const activity = container.querySelector(+ '[data-testid="task-chat-current-activity"]',+ );+ expect(activity?.textContent).toContain("Searching the web");+ expect(activity?.textContent).toContain(+ "site:openai.com model guide GPT-5.4",+ );+ expect(activity?.getAttribute("data-activity-family")).toBe("research");+ });++ it("has a purpose-built current-activity presentation for every provider family", () => {+ const cases: Array<{+ family: TaskChatProviderActivityFamily;+ eventType: string;+ status: TaskChatProviderActivityItem["status"];+ expected: string;+ details?: TaskChatProviderActivityItem["details"];+ }> = [+ {+ family: "plan",+ eventType: "plan.updated",+ status: "running",+ expected: "Updating the plan",+ },+ {+ family: "tool_execution",+ eventType: "tool.execution.started",+ status: "running",+ expected: "Running an unnamed tool",+ },+ {+ family: "research",+ eventType: "research.started",+ status: "running",+ expected: "Searching the web",+ details: [{ label: "Action", value: "search" }],+ },+ {+ family: "delegation",+ eventType: "delegation.started",+ status: "running",+ expected: "Starting a subagent",+ details: [{ label: "Action", value: "spawn" }],+ },+ {+ family: "model_identity",+ eventType: "model.route.changed",+ status: "informational",+ expected: "Switched models",+ },+ {+ family: "context",+ eventType: "context.compacted",+ status: "completed",+ expected: "Compacted context",+ },+ {+ family: "artifact",+ eventType: "artifact.generated",+ status: "running",+ expected: "Generating an artifact",+ },+ {+ family: "review",+ eventType: "review.mode.changed",+ status: "informational",+ expected: "Entered review mode",+ details: [{ label: "State", value: "entered" }],+ },+ {+ family: "hook",+ eventType: "hook.started",+ status: "running",+ expected: "Running a hook",+ },+ {+ family: "memory",+ eventType: "memory.citation.referenced",+ status: "informational",+ expected: "Referenced memory",+ },+ {+ family: "safety",+ eventType: "safety.review.started",+ status: "running",+ expected: "Reviewing safety",+ },+ {+ family: "terminal",+ eventType: "terminal.input.sent",+ status: "informational",+ expected: "Sent terminal input",+ },+ {+ family: "wait",+ eventType: "wait.started",+ status: "running",+ expected: "Waiting",+ },+ {+ family: "provider_notice",+ eventType: "provider.notice.recorded",+ status: "informational",+ expected: "Provider notice",+ },+ ];++ expect(cases.map((entry) => entry.family)).toEqual([+ "plan",+ "tool_execution",+ "research",+ "delegation",+ "model_identity",+ "context",+ "artifact",+ "review",+ "hook",+ "memory",+ "safety",+ "terminal",+ "wait",+ "provider_notice",+ ] satisfies TaskChatProviderActivityFamily[]);++ for (const entry of cases) {+ render([+ {+ id: `provider-${entry.family}`,+ kind: "protocol",+ surface: "provider_activity",+ family: entry.family,+ eventType: entry.eventType,+ status: entry.status,+ title: entry.family,+ details: entry.details ?? [],+ steps: [],+ links: [],+ children: [],+ },+ ]);+ const activity = container.querySelector(+ '[data-testid="task-chat-current-activity"]',+ );+ expect(activity?.getAttribute("data-activity-family"), entry.family).toBe(+ entry.family,+ );+ expect(activity?.textContent, entry.family).toContain(entry.expected);+ }+ });++ it("shows provider failures and interruptions instead of a successful past-tense label", () => {+ const provider = (+ status: "failed" | "interrupted",+ ): TaskChatProviderActivityItem => ({+ id: `research-${status}`,+ kind: "protocol",+ surface: "provider_activity",+ family: "research",+ eventType: "research.completed",+ status,+ title: "Research",+ details: [],+ steps: [],+ links: [],+ children: [],+ });+ render([provider("failed")]);+ expect(+ container.querySelector('[data-testid="task-chat-current-activity"]')+ ?.textContent,+ ).toContain("Web search failed");+ render([provider("interrupted")]);+ expect(+ container.querySelector('[data-testid="task-chat-current-activity"]')+ ?.textContent,+ ).toContain("Web search stopped");+ });++ it("surfaces workspace changes and file references as current activity", () => {+ render([+ {+ id: "workspace-change",+ kind: "protocol",+ surface: "workspace_change",+ changeSetId: "change-1",+ revision: 1,+ source: "harness_reported",+ complete: false,+ files: [],+ totals: { files: 2, additions: 3, deletions: 1 },+ patchArtifactRef: null,+ },+ ]);+ expect(+ container.querySelector('[data-testid="task-chat-current-activity"]')+ ?.textContent,+ ).toContain("Editing files");+ expect(+ container.querySelector('[data-testid="task-chat-current-activity"]')+ ?.textContent,+ ).toContain("2 files");+ const card = container.querySelector(+ '[data-testid="task-chat-workspace-change"]',+ );+ expect(card).not.toBeNull();+ expect(card?.closest('[data-testid="task-chat-activity-phase"]')).toBeNull();++ render([+ {+ id: "workspace-file",+ kind: "protocol",+ surface: "workspace_file",+ referenceId: "file-1",+ source: "runner_verified",+ path: "ui/src/App.tsx",+ displayName: "App.tsx",+ mediaType: "text/typescript",+ presentation: "code",+ line: 42,+ preview: null,+ previewTruncated: false,+ },+ ]);+ const activity = container.querySelector(+ '[data-testid="task-chat-current-activity"]',+ );+ expect(activity?.textContent).toContain("Referenced a file");+ expect(activity?.textContent).toContain("ui/src/App.tsx:42");+ expect(activity?.classList.contains("px-1")).toBe(true);+ const icon = activity?.querySelector(+ '[data-testid="task-chat-current-activity-icon"]',+ );+ expect(icon).not.toBeNull();+ expect(icon?.parentElement?.classList.contains("w-5")).toBe(true);+ expect(icon?.parentElement?.classList.contains("justify-center")).toBe(+ true,+ );+ });++ it("streams the final response in its durable slot and settles the disclosure", () => {+ render(+ [+ {+ id: "p1",+ kind: "message",+ author: "agent",+ text: "Checking.",+ interstitial: true,+ channel: "progress",+ },+ {+ id: "f1",+ kind: "message",+ author: "agent",+ authorName: "Runner",+ text: "Completed successfully.",+ channel: "final",+ streaming: true,+ },+ ],+ "succeeded",+ );+ expect(+ container.querySelector('[data-testid="task-chat-final-response"]')+ ?.textContent,+ ).toContain("Completed successfully.");+ expect(+ container.querySelectorAll('[data-testid="task-chat-agent-avatar"]'),+ ).toHaveLength(1);+ expect(+ container.querySelector('[data-testid="task-chat-turn-status-header"]')+ ?.textContent,+ ).toContain("Worked for");+ expect(+ container.querySelector('[data-testid="task-chat-phase-interstitial"]')+ ?.textContent,+ ).toContain("Checking.");+ });++ it("uses an accepted run-result summary when a yielded run has no final message", () => {+ render(+ [+ {+ id: "result",+ kind: "protocol",+ surface: "run_result",+ disposition: "yielded",+ summary: "Waiting for Review browser RTS plan.",+ objectiveSatisfied: false,+ verification: [],+ remainingWork: [],+ blocker: null,+ artifacts: [],+ },+ ],+ "succeeded",+ );++ expect(+ container.querySelector('[data-testid="task-chat-final-response"]')+ ?.textContent,+ ).toContain("Waiting for Review browser RTS plan.");+ });++ it("waits for settlement before using a structured result fallback", () => {+ const items: TaskChatItem[] = [+ {+ id: "result",+ kind: "protocol",+ surface: "run_result",+ disposition: "done",+ summary: "Structured fallback.",+ objectiveSatisfied: true,+ verification: [],+ remainingWork: [],+ blocker: null,+ artifacts: [],+ },+ ];++ render(items, "running");++ expect(+ container.querySelector('[data-testid="task-chat-final-response"]'),+ ).toBeNull();+ });++ it("lets a shorter provider final replace a structured result fallback", () => {+ const result: TaskChatItem = {+ id: "result",+ kind: "protocol",+ surface: "run_result",+ disposition: "done",+ summary: "A much longer structured summary fallback.",+ objectiveSatisfied: true,+ verification: [],+ remainingWork: [],+ blocker: null,+ artifacts: [],+ };++ render([result], "succeeded");+ expect(container.textContent).toContain(+ "A much longer structured summary fallback.",+ );++ render(+ [+ result,+ {+ id: "provider-final",+ kind: "message",+ author: "agent",+ text: "Done.",+ channel: "final",+ streaming: false,+ },+ ],+ "succeeded",+ );++ expect(+ container.querySelector('[data-testid="task-chat-final-response"]')+ ?.textContent,+ ).toContain("Done.");+ expect(container.textContent).not.toContain(+ "A much longer structured summary fallback.",+ );+ });++ it("collapses terminal reasoning to the existing Worked summary", () => {+ render(+ [+ {+ id: "reasoning",+ kind: "thinking",+ lines: ["Provider-authored trace"],+ channel: "summary",+ transcriptIndex: 1,+ },+ ],+ "succeeded",+ );+ expect(+ container.querySelector('[data-testid="task-chat-live-narration"]'),+ ).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-turn-status-header"]')+ ?.textContent,+ ).toContain("Worked for");+ expect(+ container.querySelector('[data-testid="task-chat-phase-summary"]')+ ?.textContent,+ ).toContain("Reasoning");+ });++ it("keeps final text mounted through a transient replay gap", () => {+ render([+ {+ id: "f1",+ kind: "message",+ author: "agent",+ authorName: "Runner",+ text: "Completed successfully.",+ channel: "final",+ streaming: true,+ },+ ]);+ render([+ { id: "t1", kind: "tool", name: "Paperclip_finish", status: "completed" },+ ]);++ expect(+ container.querySelector('[data-testid="task-chat-final-response"]')+ ?.textContent,+ ).toContain("Completed successfully.");+ expect(+ container.querySelectorAll('[data-testid="task-chat-final-response"]'),+ ).toHaveLength(1);+ });++ it("clears replay-latched final text when the next run takes over the lane", () => {+ render(+ [+ {+ id: "f1",+ kind: "message",+ author: "agent",+ authorName: "Runner",+ text: "First answer.",+ channel: "final",+ },+ ],+ "running",+ "run-1",+ );+ render([], "running", "run-2");++ expect(container.textContent).not.toContain("First answer.");+ expect(+ container.querySelector('[data-testid="task-chat-current-activity"]')+ ?.textContent,+ ).toContain("Thinking");+ });++ it("omits runner lifecycle and token noise while preserving useful history", () => {+ render([+ {+ id: "session",+ kind: "marker",+ variant: "session_start",+ label: "Session started",+ detail: "session-id",+ },+ {+ id: "start",+ kind: "marker",+ variant: "turn_boundary",+ label: "Turn started",+ },+ {+ id: "usage",+ kind: "usage",+ usage: {+ used: 10_520,+ size: 0,+ inputTokens: 10_254,+ outputTokens: 266,+ },+ },+ {+ id: "tool",+ kind: "tool",+ name: "Paperclip_finish",+ rawName: "paperclip_finish",+ target: "reportedWorkDisposition: done",+ status: "completed",+ },+ {+ id: "interrupt",+ kind: "marker",+ variant: "interrupted",+ label: "Interrupted",+ },+ {+ id: "complete",+ kind: "marker",+ variant: "turn_boundary",+ label: "Turn completed",+ },+ ]);++ expect(container.textContent).not.toContain("Paperclip_finish");+ expect(container.textContent).toContain("Interrupted");+ expect(container.textContent).not.toContain("Session started");+ expect(container.textContent).not.toContain("Turn started");+ expect(container.textContent).not.toContain("Turn completed");+ expect(container.textContent).not.toContain("10,520");+ act(() =>+ container+ .querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-phase-summary"]',+ )+ ?.click(),+ );+ expect(+ container+ .querySelector('[data-testid="task-chat-marker-icon"]')+ ?.parentElement?.classList.contains("w-5"),+ ).toBe(true);+ });++ it("does not leave a pending runtime marker after action moves to the composer", async () => {+ const onDecision = vi.fn();+ render(+ [+ {+ id: "request",+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-1",+ requestId: "request-1",+ requestKind: "command_approval",+ turnId: "turn-1",+ requestType: "permission",+ status: "pending",+ prompt: "Allow command?",+ choices: [{ key: "accept", label: "Allow once" }],+ fields: [],+ },+ ],+ "running",+ "run-1",+ onDecision,+ );++ expect(+ container.querySelector(+ '[data-testid="task-chat-runtime-request-marker"]',+ ),+ ).toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-runtime-request"]'),+ ).toBeNull();+ expect(onDecision).not.toHaveBeenCalled();+ });++ it("keeps a resolved question as a compact expandable receipt outside folded activity", () => {+ render(+ [+ {+ id: "resolved-request",+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-1",+ requestId: "request-1",+ requestKind: "runtime",+ turnId: "turn-1",+ requestType: "input",+ status: "resolved",+ prompt: "Codex needs your input.",+ choices: [],+ fields: [],+ questionSet: {+ schema: "paperclip.question_set.v1",+ questions: [+ {+ id: "goal",+ prompt: "What should the server do?",+ required: true,+ answerMode: "text",+ },+ ],+ },+ response: {+ schema: "paperclip.question_response.v1",+ answers: { goal: { text: "Serve a small JSON API." } },+ },+ },+ ],+ "succeeded",+ );++ const receipt = container.querySelector<HTMLDetailsElement>(+ '[data-testid="task-chat-runtime-request"]',+ );+ const history = receipt?.querySelector(+ '[data-testid="task-chat-runtime-request-history"]',+ );+ expect(receipt?.open).toBe(false);+ expect(receipt?.querySelector("summary")?.textContent).toBe(+ "Questions answered",+ );+ expect(history?.closest(".tc-turn-fold")).toBeNull();+ expect(history?.textContent).toContain("What should the server do?");+ expect(history?.textContent).toContain("Serve a small JSON API.");+ });++ it("renders the DOT-217 mixed turn in exact transcript order", () => {+ render(+ [+ {+ id: "commentary-1",+ kind: "message",+ author: "agent",+ text: "I’ll inspect the workspace first.",+ interstitial: true,+ channel: "progress",+ },+ {+ id: "tool-1",+ kind: "tool",+ name: "Read",+ rawName: "read_file",+ status: "completed",+ },+ {+ id: "tool-2",+ kind: "tool",+ name: "Read",+ rawName: "read_file",+ status: "completed",+ },+ {+ id: "commentary-2",+ kind: "message",+ author: "agent",+ text: "I need the first product choices.",+ interstitial: true,+ channel: "progress",+ },+ resolvedQuestion("questions-1", "Which core loop?"),+ {+ id: "commentary-3",+ kind: "message",+ author: "agent",+ text: "Now I’ll pin down the simulation.",+ interstitial: true,+ channel: "progress",+ },+ {+ id: "tool-3",+ kind: "tool",+ name: "Search",+ rawName: "web_search",+ status: "completed",+ },+ resolvedQuestion("questions-2", "How should time work?"),+ {+ id: "commentary-4",+ kind: "message",+ author: "agent",+ text: "The final implementation shape is clear.",+ interstitial: true,+ channel: "progress",+ },+ {+ id: "tool-4",+ kind: "tool",+ name: "Bash",+ rawName: "bash",+ status: "completed",+ },+ {+ id: "final",+ kind: "message",+ author: "agent",+ text: "The plan is ready.",+ channel: "final",+ },+ ],+ "succeeded",+ );++ const timeline = container.querySelector(+ '[data-testid="task-chat-turn-timeline"]',+ );+ const rows = Array.from(+ timeline?.querySelectorAll(+ '[data-testid="task-chat-turn-timeline-row"]',+ ) ?? [],+ );+ expect(rows.map((row) => row.getAttribute("data-timeline-row-id"))).toEqual(+ [+ "commentary-1:phase",+ "commentary-2:phase",+ "questions-1",+ "commentary-3:phase",+ "questions-2",+ "commentary-4:phase",+ ],+ );+ expect(rows[0]?.textContent).toContain("Read 2 files");+ expect(rows[2]?.textContent).toContain("Questions answered");+ expect(rows[3]?.textContent).toContain("Used a tool");+ expect(rows[5]?.textContent).toContain("Ran a command");+ const worked = container.querySelector(+ '[data-testid="task-chat-turn-status-header"]',+ );+ const identityRow = container.querySelector(+ '[data-testid="task-chat-runner-identity-row"]',+ );+ const identity = container.querySelector(+ '[data-testid="task-chat-agent-identity"]',+ );+ const final = container.querySelector(+ '[data-testid="task-chat-final-response"]',+ );+ expect(worked?.getAttribute("data-turn-position")).toBe("identity");+ expect(worked?.parentElement).toBe(identityRow);+ expect(identity?.parentElement).toBe(identityRow);+ expect(identityRow?.classList.contains("items-center")).toBe(true);+ expect(worked?.classList.contains("border-b")).toBe(false);+ expect(worked?.compareDocumentPosition(timeline!)).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ expect(timeline?.compareDocumentPosition(final!)).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ });++ it("expands a grouped live phase without hiding its commentary", () => {+ render([+ {+ id: "thinking-empty",+ kind: "thinking",+ lines: [],+ streaming: false,+ lifecycleOnly: true,+ },+ {+ id: "commentary",+ kind: "message",+ author: "agent",+ text: "Checking the current implementation.",+ interstitial: true,+ channel: "progress",+ },+ {+ id: "tool",+ kind: "tool",+ name: "Read",+ rawName: "read_file",+ target: "ui/src/App.tsx",+ status: "completed",+ detail: "export function App() {}",+ },+ ]);++ const disclosure = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-phase-summary"]',+ );+ expect(disclosure?.getAttribute("aria-expanded")).toBe("false");+ expect(+ container.querySelectorAll('[data-testid="task-chat-thinking"]'),+ ).toHaveLength(0);++ act(() => disclosure?.click());++ expect(disclosure?.getAttribute("aria-expanded")).toBe("true");+ expect(+ container.querySelector('[data-testid="task-chat-runner-activity-list"]'),+ ).not.toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-phase-interstitial"]')+ ?.textContent,+ ).toContain("Checking the current implementation.");+ expect(container.textContent).toContain("ui/src/App.tsx");+ });++ it("preserves an open phase while the live run becomes terminal", () => {+ const items: TaskChatItem[] = [+ {+ id: "tool",+ kind: "tool",+ name: "Search",+ rawName: "web_search",+ target: "smoked pork shoulder",+ status: "in_progress",+ },+ ];+ render(items);+ const disclosure = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-phase-summary"]',+ );+ act(() => disclosure?.click());+ expect(disclosure?.getAttribute("aria-expanded")).toBe("true");++ render(+ [{ ...items[0], kind: "tool", status: "completed" } as TaskChatItem],+ "succeeded",+ );++ const settled = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-phase-summary"]',+ );+ expect(settled?.getAttribute("aria-expanded")).toBe("true");+ expect(+ container.querySelector('[data-testid="task-chat-turn-status-header"]')+ ?.textContent,+ ).toContain("Worked for");+ });++ it("resets phase disclosure state when a different run takes over", () => {+ const items: TaskChatItem[] = [+ {+ id: "tool",+ kind: "tool",+ name: "Read",+ rawName: "read_file",+ target: "ui/src/App.tsx",+ status: "completed",+ },+ ];+ render(items, "running", "run-1");+ act(() =>+ container+ .querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-phase-summary"]',+ )+ ?.click(),+ );+ expect(+ container+ .querySelector('[data-testid="task-chat-phase-summary"]')+ ?.getAttribute("aria-expanded"),+ ).toBe("true");++ render(items, "running", "run-2");++ expect(+ container+ .querySelector('[data-testid="task-chat-phase-summary"]')+ ?.getAttribute("aria-expanded"),+ ).toBe("false");+ });++ it("renders a failed terminal disclosure without treating prose as status authority", () => {+ render(+ [+ {+ id: "final",+ kind: "message",+ author: "agent",+ text: "I finished the draft.",+ channel: "final",+ },+ {+ id: "tool",+ kind: "tool",+ name: "Command",+ rawName: "bash",+ target: "pnpm test",+ status: "failed",+ },+ ],+ "failed",+ );++ expect(+ container.querySelector('[data-testid="task-chat-turn-status-header"]')+ ?.textContent,+ ).toContain("Stopped after");+ expect(+ container.querySelector('[data-testid="task-chat-final-response"]')+ ?.textContent,+ ).toContain("I finished the draft.");+ });+});diff --git a/ui/src/components/task-chat/TaskChatRunnerTurn.tsx b/ui/src/components/task-chat/TaskChatRunnerTurn.tsxindex 357b2548a0..fdaf7b3c5b 100644--- a/ui/src/components/task-chat/TaskChatRunnerTurn.tsx+++ b/ui/src/components/task-chat/TaskChatRunnerTurn.tsx@@ -1,15 +1,38 @@-import { Brain } from "lucide-react";+import { useRef, type ComponentType, type SVGProps } from "react";+import { OctagonX } from "lucide-react";import { MarkdownBody } from "@/components/MarkdownBody";+import { useSecondTick } from "@/hooks/useSecondTick";import { cn } from "@/lib/utils";import type {TaskChatItem,TaskChatMessageItem,+ TaskChatMarkerItem,+ TaskChatProtocolItem,+ TaskChatProviderActivityItem,+ TaskChatRuntimeRequestDecision,+ TaskChatRuntimeRequestItem,TaskChatThinkingItem,TaskChatToolItem,} from "./task-chat-model";-import { TaskChatLiveRunPill } from "./TaskChatLiveRunPill";-import { TaskChatLiveTail } from "./TaskChatLiveTail";-import { isTerminalRunStatus } from "./transcript-adapter";+import { TaskChatAgentIdentity } from "./TaskChatBubble";+import { TaskChatActivityPhase } from "./TaskChatActivityPhase";+import { TaskChatProtocolActivityRow } from "./TaskChatProtocolActivityRow";+import { TaskChatProtocolCard } from "./TaskChatProtocolCard";+import { TaskChatPlanPreviewCard } from "./TaskChatPlanPreviewCard";+import { TaskChatThinking } from "./TaskChatThinking";+import { TaskChatToolCard } from "./TaskChatToolCard";+import { TaskChatUsageReadout } from "./TaskChatUsageReadout";+import {+ protocolActivityIsRunning,+ protocolActivityLabel,+ protocolActivityPresentation,+} from "./task-chat-activity-presentation";+import {+ buildTurnTimelineRows,+ isTerminalRunStatus,+ paperclipRunnerFinalResponse,+ paperclipRunnerTimelineItems,+} from "./transcript-adapter";import { toolTaxonomy } from "./tool-taxonomy";function lastOf<T extends TaskChatItem>(@@ -18,123 +41,391 @@ function lastOf<T extends TaskChatItem>(): T | undefined {for (let index = items.length - 1; index >= 0; index -= 1) {const item = items[index];- if (item && predicate(item)) return item;+ if (predicate(item)) return item;}return undefined;}-function CurrentActivity({ items }: { items: readonly TaskChatItem[] }) {- const activity = lastOf<TaskChatThinkingItem | TaskChatToolItem>(- items,- (item): item is TaskChatThinkingItem | TaskChatToolItem =>- item.kind === "thinking" || item.kind === "tool",+function isHeadlineProtocolActivity(+ item: TaskChatItem,+): item is TaskChatProtocolItem {+ return (+ item.kind === "protocol" && protocolActivityPresentation(item) !== null);- if (!activity || activity.kind === "thinking") {- return (- <div- className="flex items-center gap-2 px-1 py-1.5 text-sm text-muted-foreground"- data-testid="task-chat-current-activity"+}++function currentActivityStatusItems(+ items: readonly TaskChatItem[],+): readonly TaskChatItem[] {+ let boundaryIndex = -1;+ for (let index = items.length - 1; index >= 0; index -= 1) {+ const item = items[index];+ if (+ item.kind === "message" ||+ item.kind === "plan_document" ||+ (item.kind === "protocol" &&+ (item.surface === "runtime_request" ||+ item.surface === "run_result" ||+ item.surface === "run_terminal"))+ ) {+ boundaryIndex = index;+ break;+ }+ }+ return items.slice(boundaryIndex + 1);+}++function formatCompactDuration(ms: number | null): string | null {+ if (ms == null || !Number.isFinite(ms)) return null;+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));+ if (totalSeconds < 60) return `${totalSeconds}s`;+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;+ return seconds === 0 ? `${minutes}m` : `${minutes}m ${seconds}s`;+}++function terminalStatusFailed(status: string): boolean {+ return (+ status === "failed" ||+ status === "cancelled" ||+ status === "timed_out" ||+ status === "interrupted"+ );+}++function RunnerActivityTimeline({ items }: { items: readonly TaskChatItem[] }) {+ if (items.length === 0) return null;+ return (+ <div className="relative ml-4 min-w-0 pl-6">+ <span+ className="absolute inset-y-1 left-0 w-px bg-border/70"+ aria-hidden+ data-testid="task-chat-runner-activity-rail"+ />+ <ol+ className="flex min-w-0 flex-col gap-2 py-1"+ aria-label="Run activity"+ data-testid="task-chat-runner-activity-list">- <Brain className="h-3.5 w-3.5 shrink-0" aria-hidden />- <span className="shimmer-text shimmer-text-muted">Thinking</span>- </div>- );+ {items.map((item, index) => (+ <li className="min-w-0" key={item.id} data-activity-item-id={item.id}>+ {item.kind === "message" ? (+ <div+ className="tc-enter-cot-line min-w-0 px-1 text-sm text-foreground/90"+ data-testid="task-chat-activity-commentary"+ >+ <MarkdownBody softBreaks linkIssueReferences>+ {item.text}+ </MarkdownBody>+ </div>+ ) : item.kind === "thinking" ? (+ <TaskChatThinking+ item={item}+ active={Boolean(item.streaming) && index === items.length - 1}+ defaultOpen={false}+ rowClassName="mx-0 px-0"+ />+ ) : item.kind === "tool" ? (+ <TaskChatToolCard item={item} />+ ) : item.kind === "usage" ? (+ <TaskChatUsageReadout item={item} />+ ) : item.kind === "marker" ? (+ <RunnerActivityMarker item={item} />+ ) : item.kind === "protocol" ? (+ <TaskChatProtocolActivityRow item={item} />+ ) : null}+ </li>+ ))}+ </ol>+ </div>+ );+}++function RunnerActivityMarker({ item }: { item: TaskChatMarkerItem }) {+ return (+ <div className="flex min-h-6 min-w-0 items-center gap-2 py-1 text-xs text-destructive">+ <span className="flex w-5 shrink-0 items-center justify-center">+ <OctagonX+ className="h-3.5 w-3.5 shrink-0"+ aria-hidden+ data-testid="task-chat-marker-icon"+ />+ </span>+ <span className="shrink-0 font-medium">{item.label}</span>+ {item.detail ? (+ <span className="min-w-0 truncate text-muted-foreground">+ {item.detail}+ </span>+ ) : null}+ </div>+ );+}++function RunnerTurnStatus({+ status,+ startedAtMs,+ finishedAtMs,+}: {+ status: string;+ startedAtMs: number | null;+ finishedAtMs?: number | null;+}) {+ const terminal = isTerminalRunStatus(status);+ useSecondTick(!terminal && startedAtMs != null);+ const elapsedMs =+ startedAtMs == null+ ? null+ : Math.max(+ 0,+ (terminal ? (finishedAtMs ?? Date.now()) : Date.now()) - startedAtMs,+ );+ const elapsed = formatCompactDuration(elapsedMs);++ const failed = terminalStatusFailed(status);+ const label = terminal ? (failed ? "Stopped" : "Worked") : "Working";+ const semanticLabel = terminal+ ? elapsed+ ? `${label} ${failed ? "after" : "for"} ${elapsed}`+ : label+ : `${label} for ${elapsed ?? "0s"}`;++ return (+ <span+ className="min-w-0 truncate text-sm font-normal text-muted-foreground"+ data-testid="task-chat-turn-status-header"+ data-turn-position="identity"+ aria-live="polite"+ aria-atomic="true"+ >+ {semanticLabel}+ </span>+ );+}++function RunnerCurrentActivityTail({+ items,+ status,+}: {+ items: readonly TaskChatItem[];+ status: string;+}) {+ if (isTerminalRunStatus(status)) return null;+ const activity = lastOf<+ TaskChatThinkingItem | TaskChatToolItem | TaskChatProtocolItem+ >(+ items,+ (+ item,+ ): item is TaskChatThinkingItem | TaskChatToolItem | TaskChatProtocolItem =>+ item.kind === "thinking" ||+ item.kind === "tool" ||+ isHeadlineProtocolActivity(item),+ );++ let Icon: ComponentType<SVGProps<SVGSVGElement>> | null = null;+ let label = "Thinking";+ let detail: string | undefined;+ let family: string | undefined;+ let active = true;+ if (activity?.kind === "tool") {+ const taxonomy = toolTaxonomy(activity.rawName ?? activity.name);+ Icon = taxonomy.icon;+ label = taxonomy.verbLabel;+ detail = activity.target;+ active = activity.status === "pending" || activity.status === "in_progress";+ } else if (activity?.kind === "protocol") {+ const presentation = protocolActivityPresentation(activity);+ if (presentation) {+ Icon = presentation.icon;+ label = protocolActivityLabel(activity, presentation);+ detail = presentation.detail;+ active = protocolActivityIsRunning(activity);+ family =+ activity.surface === "provider_activity"+ ? activity.family+ : activity.surface;+ }}- const taxonomy = toolTaxonomy(activity.rawName ?? activity.name);- const Icon = taxonomy.icon;- const active = activity.status === "pending" || activity.status === "in_progress";+return (<div- className="flex min-w-0 items-center gap-2 px-1 py-1.5 text-sm text-muted-foreground"+ className="mt-2 flex min-h-8 min-w-0 items-center gap-2 px-1 py-1 text-xs text-muted-foreground"data-testid="task-chat-current-activity"+ data-activity-family={family}+ data-turn-position="tail">- <Icon className="h-3.5 w-3.5 shrink-0" aria-hidden />- <span className={cn("shrink-0", active && "shimmer-text shimmer-text-muted")}>- {taxonomy.verbLabel}- </span>- {activity.target ? (- <span className="min-w-0 truncate font-mono text-xs">{activity.target}</span>+ {Icon ? (+ <span className="flex w-5 shrink-0 items-center justify-center">+ <Icon+ className={cn(+ "h-3.5 w-3.5 shrink-0",+ active && "text-(--status-agent-running)",+ )}+ aria-hidden+ data-testid="task-chat-current-activity-icon"+ />+ </span>) : null}+ <span className="flex min-w-0 flex-1 items-baseline gap-2">+ <span+ className={cn(+ "shrink-0 font-normal",+ active && "shimmer-text shimmer-text-muted",+ )}+ aria-live="polite"+ aria-atomic="true"+ data-testid="task-chat-current-activity-label"+ >+ {label}+ </span>+ {detail ? (+ <span className="min-w-0 truncate font-mono text-(length:--text-micro)">+ {detail}+ </span>+ ) : null}+ </span></div>);}-/**- * Runner-only live turn. Its compact parent row and final response are driven- * by persisted runtime facts; direct adapters continue through TaskChatLiveTail.- */export function TaskChatRunnerTurn({+ runId,+ agentName,+ agentIcon,items,status,startedAtMs,finishedAtMs,- toolSummary,+ onRuntimeRequestDecision,}: {+ /** Stable identity used to clear replay-latched final text for the next turn. */+ runId?: string | null;+ agentName?: string | null;+ agentIcon?: string | null;items: readonly TaskChatItem[];status: string;startedAtMs: number | null;finishedAtMs?: number | null;- toolSummary: string | null;+ onRuntimeRequestDecision?: (+ item: TaskChatRuntimeRequestItem,+ decision: TaskChatRuntimeRequestDecision,+ ) => void | Promise<void>;}) {const terminal = isTerminalRunStatus(status);- const progress = lastOf<TaskChatMessageItem>(- items,- (item): item is TaskChatMessageItem =>- item.kind === "message" &&- (item.channel === "progress" || (!terminal && item.channel === "unknown")),+ const timelineRows = buildTurnTimelineRows(+ paperclipRunnerTimelineItems(items),+ !terminal,);- const final = lastOf<TaskChatMessageItem>(- items,- (item): item is TaskChatMessageItem =>- item.kind === "message" &&- (item.channel === "final" || (terminal && item.channel === "unknown")),+ const currentActivityItems = currentActivityStatusItems(items);+ const observedFinal = paperclipRunnerFinalResponse(items, {+ allowFallback: terminal,+ });+ const observedProviderText = Boolean(+ observedFinal &&+ items.some(+ (item) =>+ item.kind === "message" &&+ item.id === observedFinal.id &&+ item.channel !== "progress",+ ),);- const activityItems = items.filter((item) => item.kind !== "message");-- if (status === "queued") {- return (- <div className="py-1" data-testid="task-chat-runner-turn" data-phase="startup">- <CurrentActivity items={items} />- </div>- );+ // A reconnect/replay can briefly rebuild the transcript without the final+ // item (or with an earlier, shorter prefix). Provider-authored final text+ // always replaces a structured summary fallback, even when it is shorter;+ // within either class, displayed answer text remains monotonic.+ const finalRef = useRef<{+ runId?: string | null;+ item?: TaskChatMessageItem;+ providerText?: boolean;+ }>({ runId });+ if (finalRef.current.runId !== runId) finalRef.current = { runId };+ if (+ observedFinal &&+ (!finalRef.current.item ||+ (observedProviderText && !finalRef.current.providerText) ||+ (observedProviderText === Boolean(finalRef.current.providerText) &&+ observedFinal.text.length >= finalRef.current.item.text.length))+ ) {+ finalRef.current.item = observedFinal;+ finalRef.current.providerText = observedProviderText;}+ const final = finalRef.current.item;return (- <div className="flex min-w-0 flex-col" data-testid="task-chat-runner-turn">- <TaskChatLiveRunPill- status={status}- startedAtMs={startedAtMs}- finishedAtMs={finishedAtMs}- toolSummary={toolSummary}- />- <div className="flex flex-col gap-2 py-2">- <TaskChatLiveTail items={activityItems} />+ <div+ className="flex min-w-0 flex-col"+ data-testid="task-chat-runner-turn"+ data-phase={status === "queued" ? "startup" : undefined}+ >+ <div+ className={cn(+ "flex min-h-8 min-w-0 items-center gap-2",+ status === "queued" ? "pb-1" : "pb-1 pt-2",+ )}+ data-testid="task-chat-runner-identity-row"+ >+ {agentName ? (+ <TaskChatAgentIdentity agentName={agentName} agentIcon={agentIcon} />+ ) : null}+ <RunnerTurnStatus+ status={status}+ startedAtMs={startedAtMs}+ finishedAtMs={finishedAtMs}+ /></div>- {progress || (!final && !terminal) ? (- <div className="flex min-w-0 flex-col py-1">- {progress ? (+ {timelineRows.length > 0 ? (+ <div+ className="flex min-w-0 flex-col gap-2 py-1"+ data-testid="task-chat-turn-timeline"+ >+ {timelineRows.map((row) => (<div- className="tc-enter-cot-line min-w-0 px-1 py-1.5 text-sm text-foreground/90"- data-testid="task-chat-progress-update"+ className="min-w-0"+ key={`${runId ?? "run"}:${row.id}`}+ data-testid="task-chat-turn-timeline-row"+ data-timeline-row-id={row.id}>- <MarkdownBody softBreaks linkIssueReferences>- {progress.text}- </MarkdownBody>+ {row.kind === "activity_phase" ? (+ <TaskChatActivityPhase+ item={row}+ appearance="runner"+ autoOpen={false}+ childrenClassName="pl-0"+ renderChild={() => null}+ renderChildren={(children) => (+ <RunnerActivityTimeline items={children} />+ )}+ />+ ) : row.kind === "plan_document" ? (+ <TaskChatPlanPreviewCard+ source={{ kind: "saved", document: row.document }}+ />+ ) : row.kind === "protocol" ? (+ <TaskChatProtocolCard+ item={row}+ onRuntimeRequestDecision={onRuntimeRequestDecision}+ />+ ) : null}</div>- ) : null}- {!final && !terminal ? <CurrentActivity items={items} /> : null}+ ))}</div>) : null}{final ? (<div- className="tc-enter-bubble px-1 py-2 text-sm text-foreground"+ className="tc-enter-bubble w-full"data-testid="task-chat-final-response">- <MarkdownBody softBreaks linkIssueReferences>- {final.text}- </MarkdownBody>+ <div+ className="break-words px-1 py-2 text-sm text-foreground"+ data-testid="task-chat-agent-bubble"+ >+ <MarkdownBody softBreaks linkIssueReferences>+ {final.text}+ </MarkdownBody>+ </div></div>) : null}+ <RunnerCurrentActivityTail items={currentActivityItems} status={status} /></div>);}diff --git a/ui/src/components/task-chat/TaskChatSystemNotice.test.tsx b/ui/src/components/task-chat/TaskChatSystemNotice.test.tsxindex 6d34d7b45e..488c6ba8a1 100644--- a/ui/src/components/task-chat/TaskChatSystemNotice.test.tsx+++ b/ui/src/components/task-chat/TaskChatSystemNotice.test.tsx@@ -2,7 +2,7 @@import { flushSync } from "react-dom";import { createRoot, type Root } from "react-dom/client";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { ThemeProvider } from "@/context/ThemeContext";import { TaskChatSystemNotice } from "./TaskChatSystemNotice";import type { TaskChatMessageItem } from "./task-chat-model";@@ -27,7 +27,13 @@ describe("TaskChatSystemNotice (PAP-443)", () => {"Paperclip stopped before dispatching the adapter because required secret/env bindings are missing. " +"Latest retry failure: `configuration_incomplete`. Moving it to `blocked` with a source-scoped recovery action.";- function renderNotice(overrides: Partial<TaskChatMessageItem> = {}) {+ function renderNotice(+ overrides: Partial<TaskChatMessageItem> = {},+ props: {+ onTryAgainNoLiveExecutionPath?: () => Promise<void> | void;+ tryAgainNoLiveExecutionPathPending?: boolean;+ } = {},+ ) {const item: TaskChatMessageItem = {id: "sys-1",kind: "message",@@ -39,7 +45,7 @@ describe("TaskChatSystemNotice (PAP-443)", () => {flushSync(() =>root!.render(<ThemeProvider>- <TaskChatSystemNotice item={item} />+ <TaskChatSystemNotice item={item} {...props} /></ThemeProvider>,),);@@ -47,7 +53,7 @@ describe("TaskChatSystemNotice (PAP-443)", () => {function toggleButton() {return container.querySelector<HTMLButtonElement>(- '[data-testid="task-chat-system-notice"] button',+ '[data-testid="task-chat-system-notice"] button[aria-expanded]',)!;}@@ -120,4 +126,97 @@ describe("TaskChatSystemNotice (PAP-443)", () => {container.querySelector('[data-testid="task-chat-system-notice-details"]'),).not.toBeNull();});++ it("shows Try again while folded and invokes it without expanding the notice", async () => {+ const onTryAgain = vi.fn();+ renderNotice(+ {+ text: "Paperclip retried continuation, but it still has no live execution path.",+ presentation: {+ kind: "system_notice",+ tone: "danger",+ title: "No live execution path",+ detailsDefaultOpen: false,+ },+ },+ { onTryAgainNoLiveExecutionPath: onTryAgain },+ );++ const tryAgain = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-no-live-path-try-again"]',+ );+ expect(tryAgain?.textContent).toBe("Try again");+ flushSync(() => tryAgain!.click());+ await Promise.resolve();++ expect(onTryAgain).toHaveBeenCalledTimes(1);+ expect(toggleButton().getAttribute("aria-expanded")).toBe("false");+ });++ it("moves Try again into the expanded notice footer", () => {+ renderNotice(+ {+ text: "Paperclip retried continuation, but it still has no live execution path.",+ presentation: {+ kind: "system_notice",+ tone: "danger",+ title: "No live execution path",+ detailsDefaultOpen: false,+ },+ },+ { onTryAgainNoLiveExecutionPath: vi.fn() },+ );++ flushSync(() => toggleButton().click());++ const details = container.querySelector(+ '[data-testid="task-chat-system-notice-details"]',+ );+ expect(+ details?.querySelector('[data-testid="task-chat-no-live-path-try-again"]'),+ ).not.toBeNull();+ expect(+ container.querySelectorAll('[data-testid="task-chat-no-live-path-try-again"]'),+ ).toHaveLength(1);+ });++ it("shows the pending state and omits Try again from unrelated notices", () => {+ renderNotice(+ {+ text: "Paperclip retried continuation, but it still has no live execution path.",+ presentation: {+ kind: "system_notice",+ tone: "danger",+ title: "No live execution path",+ detailsDefaultOpen: false,+ },+ },+ {+ onTryAgainNoLiveExecutionPath: vi.fn(),+ tryAgainNoLiveExecutionPathPending: true,+ },+ );++ const pending = container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-no-live-path-try-again"]',+ );+ expect(pending?.disabled).toBe(true);+ expect(pending?.textContent).toBe("Trying again...");++ renderNotice(+ {+ text: recoveryBody,+ presentation: {+ kind: "system_notice",+ tone: "danger",+ title: "Configuration incomplete",+ detailsDefaultOpen: false,+ },+ },+ { onTryAgainNoLiveExecutionPath: vi.fn() },+ );+ expect(+ container.querySelector('[data-testid="task-chat-no-live-path-try-again"]'),+ ).toBeNull();+ });});diff --git a/ui/src/components/task-chat/TaskChatSystemNotice.tsx b/ui/src/components/task-chat/TaskChatSystemNotice.tsxindex da9c40bd1b..0ec8f07a8c 100644--- a/ui/src/components/task-chat/TaskChatSystemNotice.tsx+++ b/ui/src/components/task-chat/TaskChatSystemNotice.tsx@@ -9,6 +9,7 @@ import {} from "lucide-react";import { cn } from "@/lib/utils";import { MarkdownBody } from "@/components/MarkdownBody";+import { Button } from "@/components/ui/button";import {SystemNoticeMetadataSections,type SystemNoticeTone,@@ -42,7 +43,15 @@ const TONE_ICON_CLASS: Record<SystemNoticeTone, string> = {* markdown-rendered body plus any structured metadata sections; nothing is* suppressed, only folded.*/-export function TaskChatSystemNotice({ item }: { item: TaskChatMessageItem }) {+export function TaskChatSystemNotice({+ item,+ onTryAgainNoLiveExecutionPath,+ tryAgainNoLiveExecutionPathPending = false,+}: {+ item: TaskChatMessageItem;+ onTryAgainNoLiveExecutionPath?: () => Promise<void> | void;+ tryAgainNoLiveExecutionPathPending?: boolean;+}) {const [open, setOpen] = useState(Boolean(item.presentation?.detailsDefaultOpen));const detailsId = useId();const { title, tone, detail } = humanizeSystemNotice({@@ -54,29 +63,53 @@ export function TaskChatSystemNotice({ item }: { item: TaskChatMessageItem }) {});const ToneIcon = TONE_ICON[tone];const relative = item.createdAtIso ? timeAgo(item.createdAtIso) : undefined;+ const showTryAgain =+ Boolean(onTryAgainNoLiveExecutionPath) &&+ (item.presentation?.title?.trim() === "No live execution path" ||+ item.text.toLowerCase().includes("no live execution path"));+ const handleTryAgain = () => {+ void Promise.resolve()+ .then(() => onTryAgainNoLiveExecutionPath?.())+ // The parent mutation owns visible error feedback.+ .catch(() => undefined);+ };return (<div className="tc-enter-bubble flex flex-col items-center py-1" data-testid="task-chat-system-notice">- <button- type="button"- onClick={() => setOpen((v) => !v)}- aria-expanded={open}- aria-controls={detailsId}- className={cn(- "flex max-w-(--pct-85) items-center gap-1.5 rounded-md px-2 py-0.5 text-xs text-muted-foreground",- "hover:bg-muted/50 hover:text-foreground",- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",- )}- >- <ToneIcon className={cn("h-3.5 w-3.5 shrink-0", TONE_ICON_CLASS[tone])} aria-hidden />- <span className="truncate font-medium">{title}</span>- {detail ? <span className="hidden truncate sm:inline">· {detail}</span> : null}- {relative ? <span className="shrink-0 text-muted-foreground/70">· {relative}</span> : null}- <ChevronDown- className={cn("tc-notice-chevron h-3.5 w-3.5 shrink-0 transition-transform", open && "rotate-180")}- aria-hidden- />- </button>+ <div className="flex max-w-(--pct-85) items-center gap-1.5">+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ aria-expanded={open}+ aria-controls={detailsId}+ className={cn(+ "flex min-w-0 items-center gap-1.5 rounded-md px-2 py-0.5 text-xs text-muted-foreground",+ "hover:bg-muted/50 hover:text-foreground",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",+ )}+ >+ <ToneIcon className={cn("h-3.5 w-3.5 shrink-0", TONE_ICON_CLASS[tone])} aria-hidden />+ <span className="truncate font-medium">{title}</span>+ {detail ? <span className="hidden truncate sm:inline">· {detail}</span> : null}+ {relative ? <span className="shrink-0 text-muted-foreground/70">· {relative}</span> : null}+ <ChevronDown+ className={cn("tc-notice-chevron h-3.5 w-3.5 shrink-0 transition-transform", open && "rotate-180")}+ aria-hidden+ />+ </button>+ {showTryAgain && !open ? (+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={handleTryAgain}+ disabled={tryAgainNoLiveExecutionPathPending}+ data-testid="task-chat-no-live-path-try-again"+ >+ {tryAgainNoLiveExecutionPathPending ? "Trying again..." : "Try again"}+ </Button>+ ) : null}+ </div>{open ? (<divid={detailsId}@@ -93,6 +126,19 @@ export function TaskChatSystemNotice({ item }: { item: TaskChatMessageItem }) {<SystemNoticeMetadataSections sections={sections} tone={tone} /></div>) : null}+ {showTryAgain ? (+ <div className="flex justify-end border-t border-border/70 bg-background/50 px-3 py-2 dark:bg-background/30">+ <Button+ type="button"+ size="xs"+ onClick={handleTryAgain}+ disabled={tryAgainNoLiveExecutionPathPending}+ data-testid="task-chat-no-live-path-try-again"+ >+ {tryAgainNoLiveExecutionPathPending ? "Trying again..." : "Try again"}+ </Button>+ </div>+ ) : null}</div>) : null}</div>diff --git a/ui/src/components/task-chat/TaskChatThinking.tsx b/ui/src/components/task-chat/TaskChatThinking.tsxnew file mode 100644index 0000000000..bc611355dc--- /dev/null+++ b/ui/src/components/task-chat/TaskChatThinking.tsx@@ -0,0 +1,98 @@+import { useState } from "react";+import { Brain, ChevronRight } from "lucide-react";+import { cn } from "@/lib/utils";+import { MarkdownBody } from "@/components/MarkdownBody";+import type { TaskChatThinkingItem } from "./task-chat-model";+import { flattenSelfTalk } from "./transcript-adapter";++/** Provider-authored reasoning summaries and deltas; never reconstructed hidden reasoning. */+export function TaskChatThinking({+ item,+ defaultOpen,+ rowClassName,+ active = Boolean(item.streaming),+}: {+ item: TaskChatThinkingItem;+ /** Activity timelines keep reasoning as one compact row until requested. */+ defaultOpen?: boolean;+ /** Optional alignment override for a containing activity rail. */+ rowClassName?: string;+ /** Whether this reasoning block is the runner's current activity. */+ active?: boolean;+}) {+ const [open, setOpen] = useState(defaultOpen ?? false);+ const body = item.lines.join("\n").trim();+ const preview = flattenSelfTalk(body);+ const baseLabel = item.channel === "detail" ? "Reasoning detail" : "Reasoning";+ const label = active+ ? body ? `${baseLabel}…` : "Thinking…"+ : item.summaryLabel ?? (body ? baseLabel : "Thought");++ if (body && !active) {+ return (+ <div+ className={cn(+ "flex min-w-0 items-start gap-1.5 px-1 py-0.5 text-xs font-normal text-muted-foreground",+ rowClassName,+ )}+ data-testid="task-chat-thinking"+ data-state="settled"+ >+ <span className="flex w-5 shrink-0 items-center justify-center">+ <Brain+ className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/50"+ aria-hidden+ data-testid="task-chat-thinking-icon"+ />+ </span>+ <div className="min-w-0 flex-1" data-testid="task-chat-thinking-text">+ <MarkdownBody softBreaks linkIssueReferences>{body}</MarkdownBody>+ </div>+ </div>+ );+ }++ if (!body) {+ return (+ <div className={cn("-mx-1.5 flex min-w-0 items-center gap-2 px-1.5 py-0.5 text-xs font-normal text-muted-foreground", rowClassName)} data-testid="task-chat-thinking">+ <span className="flex w-5 shrink-0 items-center justify-center">+ <Brain className={cn("h-3.5 w-3.5 shrink-0", active && "text-(--status-agent-running)")} aria-hidden data-testid="task-chat-thinking-icon" />+ </span>+ <span className={cn(active && "shimmer-text shimmer-text-muted")}>{label}</span>+ </div>+ );+ }++ return (+ <div className="flex min-w-0 max-w-full flex-col overflow-hidden text-xs font-normal" data-testid="task-chat-thinking">+ <button+ type="button"+ aria-expanded={open}+ aria-label={`${open ? "Collapse" : "Expand"} ${baseLabel.toLowerCase()}: ${preview}`}+ onClick={() => setOpen((value) => !value)}+ className={cn("group/thinking -mx-1.5 flex w-full min-w-0 max-w-full items-center gap-2 overflow-hidden rounded-sm px-1.5 py-0.5 text-left font-normal text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", rowClassName)}+ >+ <span className="flex w-5 shrink-0 items-center justify-center">+ <Brain className={cn("h-3.5 w-3.5 shrink-0", active && "text-(--status-agent-running)")} aria-hidden data-testid="task-chat-thinking-icon" />+ </span>+ {active ? (+ <span className="shimmer-text shimmer-text-muted shrink-0">{label}</span>+ ) : null}+ {!open ? (+ <span+ className="task-chat-collapsed-line-fade min-w-0 flex-1"+ data-testid="task-chat-thinking-preview"+ >+ {preview}+ </span>+ ) : null}+ <ChevronRight className={cn("tc-hover-disclosure-caret h-3 w-3 shrink-0 transition-[opacity,transform] group-hover/thinking:opacity-80 group-focus-visible/thinking:opacity-80", open ? "rotate-90 opacity-80" : "opacity-0")} aria-hidden />+ </button>+ {open ? (+ <div className="task-chat-expanded-line-wrap ml-2.5 mt-1 min-w-0 max-w-full overflow-hidden border-l-2 border-border pl-2.5 text-xs font-normal text-muted-foreground">+ <MarkdownBody className="task-chat-reasoning-markdown" softBreaks linkIssueReferences>{body}</MarkdownBody>+ </div>+ ) : null}+ </div>+ );+}diff --git a/ui/src/components/task-chat/TaskChatThreadView.tsx b/ui/src/components/task-chat/TaskChatThreadView.tsxindex a3bb398c3b..92226bd1d8 100644--- a/ui/src/components/task-chat/TaskChatThreadView.tsx+++ b/ui/src/components/task-chat/TaskChatThreadView.tsx@@ -4,6 +4,8 @@ import type {TaskChatInteractionItem,TaskChatItem,TaskChatMessageItem,+ TaskChatRuntimeRequestDecision,+ TaskChatRuntimeRequestItem,} from "./task-chat-model";import { TaskChatTurn } from "./TaskChatTurn";import { TaskChatBubble } from "./TaskChatBubble";@@ -12,7 +14,11 @@ import { TaskChatStatusPill } from "./TaskChatStatusPill";import { TaskChatToolCard } from "./TaskChatToolCard";import { TaskChatUsageReadout } from "./TaskChatUsageReadout";import { TaskChatActivityPhase } from "./TaskChatActivityPhase";+import { TaskChatThinking } from "./TaskChatThinking";import { TaskMessageScroller } from "./TaskMessageScroller";+import { TaskChatProtocolCard } from "./TaskChatProtocolCard";+import { TaskChatProtocolActivityRow } from "./TaskChatProtocolActivityRow";+import { TaskChatPlanPreviewCard } from "./TaskChatPlanPreviewCard";interface TaskChatThreadViewProps {items: TaskChatItem[];@@ -23,6 +29,10 @@ interface TaskChatThreadViewProps {*/header?: ReactNode;onApprovalDecision?: (statusItemId: string, optionId: string) => void;+ onRuntimeRequestDecision?: (+ item: TaskChatRuntimeRequestItem,+ decision: TaskChatRuntimeRequestDecision,+ ) => void | Promise<void>;/*** Renders an interleaved issue-thread interaction (the live thread supplies* TaskChatInteractionCard bound to its accept/reject handlers). Interaction@@ -43,6 +53,9 @@ interface TaskChatThreadViewProps {renderMessageActions?: (item: TaskChatMessageItem) => ReactNode;/** Renders an interrupt action beside a queued human message. */renderQueuedAction?: (item: TaskChatMessageItem) => ReactNode;+ /** Requeues a blocked task from its no-live-execution-path failure surfaces. */+ onTryAgainNoLiveExecutionPath?: () => Promise<void> | void;+ tryAgainNoLiveExecutionPathPending?: boolean;/** Content appended inside the transcript scroller after the settled thread. */tail?: ReactNode;/** Optional streaming-aware key when `tail` changes without changing `items`. */@@ -59,6 +72,14 @@ function renderItem(renderBrief?: () => ReactNode,renderMessageActions?: (item: TaskChatMessageItem) => ReactNode,renderQueuedAction?: (item: TaskChatMessageItem) => ReactNode,+ onRuntimeRequestDecision?: (+ item: TaskChatRuntimeRequestItem,+ decision: TaskChatRuntimeRequestDecision,+ ) => void | Promise<void>,+ activityAppearance: "classic" | "runner" = "classic",+ onTryAgainNoLiveExecutionPath?: () => Promise<void> | void,+ tryAgainNoLiveExecutionPathPending = false,+ retryableMarkerId?: string,) {switch (item.kind) {case "message": {@@ -68,54 +89,142 @@ function renderItem(// put when the tool history expands (PAP-413). The two paths are mutually// exclusive at runtime, so only one host ever mounts the node.const actions = renderMessageActions?.(item);+ const attachedTurnItem = item.attachedTurn?.standaloneHeader+ ? {+ ...item.attachedTurn,+ agentName: item.attachedTurn.agentName ?? item.authorName,+ agentIcon: item.attachedTurn.agentIcon ?? item.agentIcon,+ }+ : item.attachedTurn;+ const turn = attachedTurnItem ? (+ <TaskChatTurn+ item={attachedTurnItem}+ timestampPrefix={+ attachedTurnItem.standaloneHeader ? undefined : item.timestamp+ }+ leading={attachedTurnItem.standaloneHeader ? undefined : actions}+ renderChild={(child) =>+ renderItem(+ child,+ onApprovalDecision,+ undefined,+ undefined,+ undefined,+ undefined,+ onRuntimeRequestDecision,+ item.attachedTurn?.standaloneHeader ? "runner" : "classic",+ )+ }+ />+ ) : undefined;return (<TaskChatBubbleitem={item}- actions={actions}- queuedAction={renderQueuedAction?.(item)}- attachedTurn={- item.attachedTurn ? (- <TaskChatTurn- item={item.attachedTurn}- timestampPrefix={item.timestamp}- leading={actions}- renderChild={(child) => renderItem(child, onApprovalDecision)}- />- ) : undefined+ // Human messages are inserted optimistically and later replaced by+ // their canonical server IDs. Animating either mount makes the same+ // text visibly fade twice during that handoff; user sends should+ // paint immediately and remain visually stable.+ animateEntry={+ item.author !== "human" && !item.attachedTurn?.standaloneHeader}+ actions={+ item.attachedTurn?.standaloneHeader+ ? actions+ : item.attachedTurn+ ? undefined+ : actions+ }+ queuedAction={renderQueuedAction?.(item)}+ beforeTurn={item.attachedTurn?.standaloneHeader ? turn : undefined}+ attachedTurn={item.attachedTurn?.standaloneHeader ? undefined : turn}+ hideAgentIdentity={Boolean(item.attachedTurn?.standaloneHeader)}+ onTryAgainNoLiveExecutionPath={onTryAgainNoLiveExecutionPath}+ tryAgainNoLiveExecutionPathPending={tryAgainNoLiveExecutionPathPending}/>);}case "marker":- return <TaskChatMarker item={item} />;+ return (+ <TaskChatMarker+ item={item}+ onTryAgain={+ item.id === retryableMarkerId+ ? onTryAgainNoLiveExecutionPath+ : undefined+ }+ tryAgainPending={tryAgainNoLiveExecutionPathPending}+ />+ );case "thinking":- // Thinking never renders as a row (PAP-361): its live signal is the- // pill's "Thinking…" state, and the text stays in the run log / classic- // transcript. The kind survives in the model because the transcript- // parser still emits it (both nesting rules filter it out).- return null;+ return <TaskChatThinking item={item} />;case "tool":return <TaskChatToolCard item={item} />;case "status":return (<TaskChatStatusPillitem={item}- onApprovalDecision={(optionId) => onApprovalDecision?.(item.id, optionId)}+ onApprovalDecision={(optionId) =>+ onApprovalDecision?.(item.id, optionId)+ }/>);case "usage":return <TaskChatUsageReadout item={item} />;case "activity_phase":- return <TaskChatActivityPhase item={item} renderChild={(child) => renderItem(child, onApprovalDecision)} />;+ return (+ <TaskChatActivityPhase+ item={item}+ appearance={activityAppearance}+ renderChild={(child) =>+ child.kind === "protocol" && child.surface !== "runtime_request" ? (+ <TaskChatProtocolActivityRow item={child} />+ ) : (+ renderItem(+ child,+ onApprovalDecision,+ undefined,+ undefined,+ undefined,+ undefined,+ onRuntimeRequestDecision,+ )+ )+ }+ />+ );case "interaction":return renderInteraction ? renderInteraction(item) : null;+ case "plan_document":+ return (+ <TaskChatPlanPreviewCard+ source={{ kind: "saved", document: item.document }}+ />+ );case "brief":return renderBrief ? renderBrief() : null;case "turn":return (<TaskChatTurnitem={item}- renderChild={(child) => renderItem(child, onApprovalDecision)}+ renderChild={(child) =>+ renderItem(+ child,+ onApprovalDecision,+ undefined,+ undefined,+ undefined,+ undefined,+ onRuntimeRequestDecision,+ item.standaloneHeader ? "runner" : "classic",+ )+ }+ />+ );+ case "protocol":+ return (+ <TaskChatProtocolCard+ item={item}+ onRuntimeRequestDecision={onRuntimeRequestDecision}/>);default: {@@ -136,24 +245,53 @@ export function TaskChatThreadView({items,header,onApprovalDecision,+ onRuntimeRequestDecision,renderInteraction,renderBrief,renderMessageActions,renderQueuedAction,+ onTryAgainNoLiveExecutionPath,+ tryAgainNoLiveExecutionPathPending = false,tail,contentKey,className,scroll = true,}: TaskChatThreadViewProps) {+ const retryableMarkerId = onTryAgainNoLiveExecutionPath+ ? [...items]+ .reverse()+ .find(+ (item) =>+ item.kind === "marker" &&+ item.variant === "interrupted" &&+ item.label === "Run failed",+ )?.id+ : undefined;const body = (- <div className={cn("mx-auto flex w-full max-w-(--tc-shell-max-w) flex-col gap-5 px-4 py-4", className)}>+ <div+ className={cn(+ "mx-auto flex w-full max-w-(--tc-shell-max-w) flex-col gap-5 px-4 py-4",+ className,+ )}+ >{header ? (- <div className="flex flex-col gap-6 pb-2" data-testid="task-chat-thread-header">+ <div+ className="flex flex-col gap-6 pb-2"+ data-testid="task-chat-thread-header"+ >{header}</div>) : null}- {items.map((item) => (- <div key={item.id}>+ {items.map((item, index) => (+ <div+ key={item.id}+ className={cn(+ index > 0 &&+ item.kind === "interaction" &&+ item.interaction.status !== "pending" &&+ "-mt-3",+ )}+ >{renderItem(item,onApprovalDecision,@@ -161,6 +299,11 @@ export function TaskChatThreadView({renderBrief,renderMessageActions,renderQueuedAction,+ onRuntimeRequestDecision,+ "classic",+ onTryAgainNoLiveExecutionPath,+ tryAgainNoLiveExecutionPathPending,+ retryableMarkerId,)}</div>))}@@ -183,9 +326,13 @@ export function TaskChatThreadView({function signatureOf(it: TaskChatItem): number {if (it.kind === "message") return it.text.length + (it.attachedTurn ? 1 : 0);if (it.kind === "thinking") return it.lines.reduce((n, l) => n + l.length, 0);- if (it.kind === "tool") return (it.diff?.lines?.length ?? 0) + (it.status === "completed" ? 1 : 0);+ if (it.kind === "tool")+ return (it.diff?.lines?.length ?? 0) + (it.status === "completed" ? 1 : 0);+ if (it.kind === "plan_document") {+ return it.document.body.length + it.document.latestRevisionNumber;+ }if (it.kind === "turn") {- if (it.settled) return 1;+ if (it.settled) return 1 + (it.finalResponse?.text.length ?? 0);// The live parent row's header changes (gerund ↔ tool-state flashes,// streaming interstitial text growing) count too, so the collapsed// single-line turn still advances the key.@@ -194,10 +341,16 @@ function signatureOf(it: TaskChatItem): number {(it.liveStatus.detail?.length ?? 0) +(it.liveStatus.selfTalk?.length ?? 0): 0;- return it.items.reduce((n, child) => n + signatureOf(child), it.items.length + headerSig);+ return it.items.reduce(+ (n, child) => n + signatureOf(child),+ it.items.length + headerSig + (it.finalResponse?.text.length ?? 0),+ );}if (it.kind === "activity_phase") {- return it.items.reduce((n, child) => n + signatureOf(child), it.summary.length + (it.interstitial?.text.length ?? 0));+ return it.items.reduce(+ (n, child) => n + signatureOf(child),+ it.summary.length + (it.interstitial?.text.length ?? 0),+ );}return 1;}diff --git a/ui/src/components/task-chat/TaskChatToolCard.tsx b/ui/src/components/task-chat/TaskChatToolCard.tsxindex 49c89d7bfc..ba40af19a2 100644--- a/ui/src/components/task-chat/TaskChatToolCard.tsx+++ b/ui/src/components/task-chat/TaskChatToolCard.tsx@@ -13,48 +13,71 @@ import { toolTaxonomy } from "./tool-taxonomy";const STATUS_ICON = {pending: { Icon: Loader2, spin: false, tone: "text-muted-foreground" },- in_progress: { Icon: Loader2, spin: true, tone: "text-(--status-agent-running)" },+ in_progress: {+ Icon: Loader2,+ spin: true,+ tone: "text-(--status-agent-running)",+ },completed: { Icon: Check, spin: false, tone: "text-muted-foreground" },failed: { Icon: X, spin: false, tone: "text-destructive" },+ interrupted: { Icon: X, spin: false, tone: "text-muted-foreground" },} as const;/*** Tool invocation as a flat activity row (v7): [glyph] [name] [mono target] …* [hover chevron] [status]. No card chrome — activity is metadata, not- * content. Clicking toggles the mono result/detail block (left-rail inset);- * diffs render as an inset panel below the row.+ * content. Clicking toggles a compact result/change summary (left-rail+ * inset). Full diff bodies stay out of the activity feed.*/export function TaskChatToolCard({ item }: { item: TaskChatToolItem }) {const { Icon, spin, tone } = STATUS_ICON[item.status];const RowIcon = toolTaxonomy(item.rawName ?? item.name).icon;const [showDetail, setShowDetail] = useState(false);- const expandable = Boolean(item.detail);+ const expandable = Boolean(item.target || item.detail || item.diff);return (- <div className="tc-enter-tool flex flex-col text-xs">+ <div className="tc-enter-tool flex min-w-0 max-w-full flex-col text-xs"><buttontype="button"onClick={expandable ? () => setShowDetail((v) => !v) : undefined}aria-expanded={expandable ? showDetail : undefined}className={cn(- "group/tool -mx-1.5 flex min-w-0 items-center gap-2 rounded-sm px-1.5 py-0.5 text-left text-muted-foreground",- expandable ? "cursor-pointer transition-colors hover:bg-muted/60 hover:text-foreground" : "cursor-default",+ "group/tool -mx-1.5 flex min-h-6 w-full min-w-0 max-w-full items-center gap-2 overflow-hidden rounded-sm px-1.5 py-1 text-left leading-none text-muted-foreground",+ expandable+ ? "cursor-pointer transition-colors hover:bg-muted/60 hover:text-foreground"+ : "cursor-default",)}>- <RowIcon className="h-3.5 w-3.5 shrink-0" aria-hidden />- <span className="shrink-0 font-medium">{item.name}</span>- {item.target ? (- <span className="min-w-0 truncate font-mono text-(length:--text-micro)">{item.target}</span>- ) : null}+ <span className="flex w-5 shrink-0 items-center justify-center">+ <RowIcon+ className="h-3.5 w-3.5 shrink-0"+ aria-hidden+ data-testid="task-chat-tool-icon"+ />+ </span>+ <span className="flex min-w-0 flex-1 items-baseline gap-2 overflow-hidden">+ <span className="shrink-0 font-medium leading-4">{item.name}</span>+ {item.target ? (+ <span className="task-chat-collapsed-line-fade min-w-0 flex-1 font-mono text-(length:--text-micro) leading-4">+ {item.target}+ </span>+ ) : null}+ </span><span className="ml-auto flex shrink-0 items-center gap-2">{item.decision ? (<spanclassName={cn("flex items-center gap-1 text-(length:--text-micro)",- item.decision === "allowed" ? "text-(--status-task-icon-done)" : "text-destructive",+ item.decision === "allowed"+ ? "text-(--status-task-icon-done)"+ : "text-destructive",)}>- {item.decision === "allowed" ? <ShieldCheck className="h-3 w-3" /> : <ShieldX className="h-3 w-3" />}+ {item.decision === "allowed" ? (+ <ShieldCheck className="h-3 w-3" />+ ) : (+ <ShieldX className="h-3 w-3" />+ )}{item.decision}</span>) : null}@@ -67,38 +90,46 @@ export function TaskChatToolCard({ item }: { item: TaskChatToolItem }) {aria-hidden/>) : null}- <Icon className={cn("h-3.5 w-3.5", tone, spin && "animate-spin")} aria-hidden />+ <Icon+ className={cn("h-3.5 w-3.5", tone, spin && "animate-spin")}+ aria-hidden+ />+ {item.status === "interrupted" ? (+ <span className="text-(length:--text-micro) text-muted-foreground">+ Interrupted+ </span>+ ) : null}</span></button>- {expandable && showDetail ? (- <pre className="ml-2.5 mt-0.5 overflow-x-auto whitespace-pre-wrap border-l-2 border-border py-1 pl-2.5 font-mono text-(length:--text-micro) leading-relaxed text-muted-foreground">+ {item.target && showDetail ? (+ <div+ className="task-chat-expanded-line-wrap ml-1.5 mt-0.5 min-w-0 max-w-full overflow-hidden border-l-2 border-border py-1 pl-2.5 font-mono text-(length:--text-micro) leading-relaxed text-muted-foreground"+ data-testid="task-chat-tool-target-detail"+ >+ {item.target}+ </div>+ ) : null}+ {item.detail && showDetail ? (+ <pre className="task-chat-expanded-line-wrap ml-1.5 mt-0.5 min-w-0 max-w-full overflow-hidden whitespace-pre-wrap border-l-2 border-border py-1 pl-2.5 font-mono text-(length:--text-micro) leading-relaxed text-muted-foreground">{item.detail}</pre>) : null}- {item.diff ? (- <div className="tc-reveal-diff ml-2.5 mt-1 border-l-2 border-border pl-2.5">- <div className="mb-1 flex items-center gap-2 text-(length:--text-micro) text-muted-foreground">- {item.diff.path ? <span className="truncate font-mono">{item.diff.path}</span> : null}- <span className="ml-auto shrink-0 font-mono font-semibold">+ {item.diff && showDetail ? (+ <div+ className="ml-1.5 mt-0.5 border-l-2 border-border py-1 pl-2.5"+ data-testid="task-chat-tool-change-summary"+ >+ <div className="flex min-w-0 items-center gap-2 text-(length:--text-micro) text-muted-foreground">+ <span className="shrink-0">Changed</span>+ {item.diff.path ? (+ <span className="min-w-0 truncate font-mono text-foreground">+ {item.diff.path}+ </span>+ ) : null}+ <span className="ml-auto shrink-0 font-mono">+{item.diff.added} −{item.diff.removed}</span></div>- {item.diff.lines?.length ? (- <pre className="overflow-x-auto rounded-sm bg-muted/50 p-2 text-(length:--text-micro) leading-relaxed">- {item.diff.lines.map((l, i) => (- <div- key={i}- className={cn(- l.kind === "add" && "text-(--status-task-icon-done)",- l.kind === "remove" && "text-destructive",- l.kind === "context" && "text-muted-foreground",- )}- >- {l.kind === "add" ? "+" : l.kind === "remove" ? "−" : " "} {l.text}- </div>- ))}- </pre>- ) : null}</div>) : null}</div>diff --git a/ui/src/components/task-chat/TaskChatTurn.test.tsx b/ui/src/components/task-chat/TaskChatTurn.test.tsxindex ff29568825..8f3cced81e 100644--- a/ui/src/components/task-chat/TaskChatTurn.test.tsx+++ b/ui/src/components/task-chat/TaskChatTurn.test.tsx@@ -6,6 +6,8 @@ import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it } from "vitest";import { TaskChatTurn, turnSummaryText } from "./TaskChatTurn";import { buildTurnSummary } from "./transcript-adapter";+import { ThemeProvider } from "@/context/ThemeContext";+import { MemoryRouter } from "@/lib/router";import type { TranscriptEntry } from "@/adapters";import type {TaskChatStatusItem,@@ -14,7 +16,10 @@ import type {TaskChatTurnItem,} from "./task-chat-model";-const tool = (id: string, status: TaskChatToolStatus = "completed"): TaskChatTurnChildItem => ({+const tool = (+ id: string,+ status: TaskChatToolStatus = "completed",+): TaskChatTurnChildItem => ({id,kind: "tool",name: "Read",@@ -25,8 +30,16 @@ const SETTLED: TaskChatTurnItem = {id: "t1",kind: "turn",settled: true,- summary: { durationLabel: "38s", toolCount: 3, added: 34, removed: 3, tokensLabel: "12.3k tokens" },- items: [{ id: "c1", kind: "tool", name: "read auth.ts", status: "completed" }],+ summary: {+ durationLabel: "38s",+ toolCount: 3,+ added: 34,+ removed: 3,+ tokensLabel: "12.3k tokens",+ },+ items: [+ { id: "c1", kind: "tool", name: "read auth.ts", status: "completed" },+ ],};// Non-generic label so the header shows it verbatim (no whimsy substitution).@@ -51,27 +64,56 @@ const parentRowTurn = (describe("turnSummaryText", () => {it("joins the known parts with dots", () => {- expect(turnSummaryText(SETTLED.summary)).toBe("Worked · 38s · 3 tools · +34 −3 · 12.3k tokens");+ expect(turnSummaryText(SETTLED.summary)).toBe(+ "Worked · 38s · 3 tools · +34 −3 · 12.3k tokens",+ );});it("omits unknown parts and singularizes one tool", () => {- expect(turnSummaryText({ toolCount: 1, added: 0, removed: 0 })).toBe("Worked · 1 tool");+ expect(turnSummaryText({ toolCount: 1, added: 0, removed: 0 })).toBe(+ "Worked · 1 tool",+ );});it("labels failed turns Stopped", () => {- expect(turnSummaryText({ toolCount: 0, added: 0, removed: 0, failed: true })).toBe("Stopped");+ expect(+ turnSummaryText({ toolCount: 0, added: 0, removed: 0, failed: true }),+ ).toBe("Stopped");});});describe("buildTurnSummary", () => {it("counts tools, diff lines and result tokens from a transcript", () => {const entries: TranscriptEntry[] = [- { kind: "tool_call", ts: "2026-07-29T10:00:00Z", name: "edit", input: {} },- { kind: "diff", ts: "2026-07-29T10:00:05Z", changeType: "add", text: "+a" },- { kind: "diff", ts: "2026-07-29T10:00:05Z", changeType: "remove", text: "-b" },{- kind: "result", ts: "2026-07-29T10:00:38Z", text: "done", inputTokens: 12000,- outputTokens: 300, cachedTokens: 0, costUsd: 0.01, subtype: "success", isError: false, errors: [],+ kind: "tool_call",+ ts: "2026-07-29T10:00:00Z",+ name: "edit",+ input: {},+ },+ {+ kind: "diff",+ ts: "2026-07-29T10:00:05Z",+ changeType: "add",+ text: "+a",+ },+ {+ kind: "diff",+ ts: "2026-07-29T10:00:05Z",+ changeType: "remove",+ text: "-b",+ },+ {+ kind: "result",+ ts: "2026-07-29T10:00:38Z",+ text: "done",+ inputTokens: 12000,+ outputTokens: 300,+ cachedTokens: 0,+ costUsd: 0.01,+ subtype: "success",+ isError: false,+ errors: [],},];const summary = buildTurnSummary(entries);@@ -106,31 +148,207 @@ describe("TaskChatTurn", () => {const renderTurn = (item: TaskChatTurnItem) => {flushSync(() => {- root.render(<TaskChatTurn item={item} renderChild={(c) => <span>{c.id}</span>} />);+ root.render(+ <MemoryRouter>+ <ThemeProvider>+ <TaskChatTurn+ item={item}+ renderChild={(c) => <span>{c.id}</span>}+ />+ </ThemeProvider>+ </MemoryRouter>,+ );});};const fold = () => container.querySelector(".tc-turn-fold");const summaryBtn = () =>- container.querySelector<HTMLButtonElement>('[data-testid="task-chat-turn-summary"]');+ container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-turn-summary"]',+ );const liveHeaderBtn = () =>- container.querySelector<HTMLButtonElement>('[data-testid="task-chat-live-turn"]');+ container.querySelector<HTMLButtonElement>(+ '[data-testid="task-chat-live-turn"]',+ );it("renders a settled turn folded with its summary line", () => {renderTurn(SETTLED);// Label and mono metrics are adjacent spans (v7 runsum grammar).expect(summaryBtn()?.textContent).toContain("Worked");- expect(summaryBtn()?.textContent).toContain("38s · 3 tools · +34 −3 · 12.3k tokens");+ expect(summaryBtn()?.textContent).toContain(+ "38s · 3 tools · +34 −3 · 12.3k tokens",+ );expect(fold()?.getAttribute("data-folded")).toBe("true");- expect(summaryBtn()?.firstElementChild?.tagName).toBe("svg");- expect(summaryBtn()?.querySelector(".tc-turn-metrics")?.getAttribute("data-visible")).toBe("false");+ expect(summaryBtn()?.lastElementChild?.tagName).toBe("svg");+ expect(+ summaryBtn()+ ?.querySelector(".tc-turn-metrics")+ ?.getAttribute("data-visible"),+ ).toBe("false");+ });++ it("renders the new-runner Worked header above its settled timeline", () => {+ renderTurn({+ ...SETTLED,+ standaloneHeader: true,+ agentName: "Codex",+ agentIcon: "code",+ });+ expect(summaryBtn()?.textContent).toContain("Worked for 38s");+ expect(summaryBtn()?.textContent).toContain("Codex");+ expect(summaryBtn()?.textContent).not.toContain("3 tools");+ expect(+ summaryBtn()?.querySelector('[data-testid="task-chat-agent-avatar"]'),+ ).not.toBeNull();+ expect(fold()).toBeNull();+ const timeline = container.querySelector(+ '[data-testid="task-chat-turn-timeline"]',+ );+ expect(timeline?.textContent).toContain("c1");+ expect(summaryBtn()?.getAttribute("data-turn-position")).toBe("identity");+ expect(summaryBtn()?.classList.contains("pb-1")).toBe(true);+ expect(summaryBtn()?.classList.contains("pt-1.5")).toBe(true);+ expect(summaryBtn()?.classList.contains("border-b")).toBe(false);+ expect(summaryBtn()?.compareDocumentPosition(timeline!)).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ });++ it("keeps a yielded runner summary after the settled timeline", () => {+ renderTurn({+ ...SETTLED,+ standaloneHeader: true,+ finalResponse: {+ id: "result-summary",+ kind: "message",+ author: "agent",+ text: "Waiting for Review browser RTS plan.",+ channel: "final",+ },+ });++ const timeline = container.querySelector(+ '[data-testid="task-chat-turn-timeline"]',+ );+ const final = container.querySelector(+ '[data-testid="task-chat-final-response"]',+ );+ expect(final?.textContent).toContain(+ "Waiting for Review browser RTS plan.",+ );+ expect(timeline?.compareDocumentPosition(final!)).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ });++ it("keeps standalone commentary phases and question receipts in projected order", () => {+ renderTurn({+ ...SETTLED,+ standaloneHeader: true,+ items: [+ {+ id: "commentary-1:phase",+ kind: "activity_phase",+ interstitial: {+ id: "commentary-1",+ kind: "message",+ author: "agent",+ text: "First commentary",+ interstitial: true,+ channel: "progress",+ },+ items: [+ {+ id: "tool-1",+ kind: "tool",+ name: "Read",+ status: "completed",+ },+ ],+ summary: "Read 1 file",+ active: false,+ },+ {+ id: "question-1",+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-1",+ requestId: "question-1",+ requestKind: "runtime",+ turnId: "turn-1",+ requestType: "input",+ status: "resolved",+ prompt: "Question one",+ choices: [],+ fields: [],+ },+ {+ id: "commentary-2:phase",+ kind: "activity_phase",+ interstitial: {+ id: "commentary-2",+ kind: "message",+ author: "agent",+ text: "Second commentary",+ interstitial: true,+ channel: "progress",+ },+ items: [],+ summary: "No tool activity",+ active: false,+ },+ ],+ });++ expect(+ Array.from(+ container.querySelectorAll(+ '[data-testid="task-chat-turn-timeline-row"]',+ ),+ ).map((row) => row.getAttribute("data-timeline-row-id")),+ ).toEqual(["commentary-1:phase", "question-1", "commentary-2:phase"]);+ });++ it("keeps settled runtime question history outside the Worked fold", () => {+ renderTurn({+ ...SETTLED,+ items: [+ SETTLED.items[0]!,+ {+ id: "question-history",+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-1",+ requestId: "question-1",+ requestKind: "runtime",+ turnId: "turn-1",+ requestType: "input",+ status: "resolved",+ prompt: "Choose an environment",+ choices: [],+ fields: [],+ },+ ],+ });++ expect(fold()?.textContent).toContain("c1");+ expect(fold()?.textContent).not.toContain("question-history");+ const history = container.querySelector(+ '[data-testid="task-chat-turn-persistent-history"]',+ );+ expect(history?.textContent).toContain("question-history");+ expect(history?.closest(".tc-turn-fold")).toBeNull();});it("toggles open on summary click", () => {renderTurn(SETTLED);flushSync(() => summaryBtn()!.click());expect(fold()?.getAttribute("data-folded")).toBe("false");- expect(summaryBtn()?.querySelector(".tc-turn-metrics")?.getAttribute("data-visible")).toBe("true");+ expect(+ summaryBtn()+ ?.querySelector(".tc-turn-metrics")+ ?.getAttribute("data-visible"),+ ).toBe("true");});it("a headerless live turn renders expanded with no summary line", () => {@@ -162,7 +380,12 @@ describe("TaskChatTurn", () => {renderTurn(parentRowTurn([tool("a")]));expect(liveHeaderBtn()?.textContent).toContain("Editing files…");renderTurn(- parentRowTurn([tool("a")], { ...LIVE_STATUS, label: "Reading a file", detail: "Read · auth.ts", toolName: "Read" }),+ parentRowTurn([tool("a")], {+ ...LIVE_STATUS,+ label: "Reading a file",+ detail: "Read · auth.ts",+ toolName: "Read",+ }),);expect(liveHeaderBtn()?.textContent).toContain("Reading a file…");expect(liveHeaderBtn()?.textContent).toContain("Read · auth.ts");@@ -191,16 +414,23 @@ describe("TaskChatTurn", () => {// act() so the held-line effect state (useHeldSelfTalk) flushes.act(() => {renderTurn(- parentRowTurn([tool("a")], { ...LIVE_STATUS, selfTalk: "Streaming an update." }),+ parentRowTurn([tool("a")], {+ ...LIVE_STATUS,+ selfTalk: "Streaming an update.",+ }),);});const btn = liveHeaderBtn();expect(btn).not.toBeNull();// The button (hover + click target) wraps ONLY the gerund status line;// the interstitial text renders above it, outside the button.- expect(btn?.querySelector('[data-testid="task-chat-interstitial-row"]')).toBeNull();+ expect(+ btn?.querySelector('[data-testid="task-chat-interstitial-row"]'),+ ).toBeNull();expect(btn?.textContent).not.toContain("Streaming an update.");- const row = container.querySelector('[data-testid="task-chat-interstitial-row"]');+ const row = container.querySelector(+ '[data-testid="task-chat-interstitial-row"]',+ );expect(row?.textContent).toContain("Streaming an update.");// Expanding still works from the status line alone.flushSync(() => btn!.click());@@ -255,13 +485,19 @@ describe("TaskChatTurn", () => {it("leads the settled summary with the bubble timestamp when attached (round 9)", () => {flushSync(() => {root.render(- <TaskChatTurn item={SETTLED} timestampPrefix="2:34 PM" renderChild={(c) => <span>{c.id}</span>} />,+ <TaskChatTurn+ item={SETTLED}+ timestampPrefix="2:34 PM"+ renderChild={(c) => <span>{c.id}</span>}+ />,);});// "2:34 PM · ✓ Worked · …" — timestamp first, always visible, and the// expand affordance still works from the same line.expect(summaryBtn()?.textContent).toMatch(/^2:34 PM·Worked/);- expect(summaryBtn()?.firstElementChild?.tagName).toBe("svg");+ // The branch task view intentionally keeps the expand affordance at the+ // end of the timestamp-led summary row.+ expect(summaryBtn()?.lastElementChild?.tagName).toBe("svg");flushSync(() => summaryBtn()!.click());expect(fold()?.getAttribute("data-folded")).toBe("false");});diff --git a/ui/src/components/task-chat/TaskChatTurn.tsx b/ui/src/components/task-chat/TaskChatTurn.tsxindex 762dd042ce..3cd09304ab 100644--- a/ui/src/components/task-chat/TaskChatTurn.tsx+++ b/ui/src/components/task-chat/TaskChatTurn.tsx@@ -1,8 +1,13 @@import { useState, type ReactNode } from "react";import { cn } from "@/lib/utils";import { Check, ChevronRight, X } from "lucide-react";-import type { TaskChatTurnItem, TaskChatTurnChildItem } from "./task-chat-model";+import { MarkdownBody } from "@/components/MarkdownBody";+import type {+ TaskChatTurnItem,+ TaskChatTurnChildItem,+} from "./task-chat-model";import { TaskChatStatusPill } from "./TaskChatStatusPill";+import { TaskChatAgentIdentity } from "./TaskChatBubble";interface TaskChatTurnProps {item: TaskChatTurnItem;@@ -23,11 +28,17 @@ interface TaskChatTurnProps {}/** Metric segments after the label: "38s · 3 tools · +34 −3 · 12.3k tokens". */-export function turnSummaryMetrics(summary: TaskChatTurnItem["summary"]): string {+export function turnSummaryMetrics(+ summary: TaskChatTurnItem["summary"],+): string {const parts: string[] = [];if (summary.durationLabel) parts.push(summary.durationLabel);- if (summary.toolCount > 0) parts.push(`${summary.toolCount} tool${summary.toolCount === 1 ? "" : "s"}`);- if (summary.added > 0 || summary.removed > 0) parts.push(`+${summary.added} −${summary.removed}`);+ if (summary.toolCount > 0)+ parts.push(+ `${summary.toolCount} tool${summary.toolCount === 1 ? "" : "s"}`,+ );+ if (summary.added > 0 || summary.removed > 0)+ parts.push(`+${summary.added} −${summary.removed}`);if (summary.tokensLabel) parts.push(summary.tokensLabel);return parts.join(" · ");}@@ -40,7 +51,8 @@ export function turnSummaryText(summary: TaskChatTurnItem["summary"]): string {}/**- * One agent turn's activity behind a single expandable header row.+ * One agent turn's activity behind a single expandable header row. Paperclip+ * Runner turns opt into the chronological-timeline branch below instead.** While the turn is live and carries `liveStatus`, that status line (whimsy or* taxonomy gerund + elapsed + tokens) IS the turn: one parent row, collapsed@@ -57,11 +69,91 @@ export function turnSummaryText(summary: TaskChatTurnItem["summary"]): string {* `liveStatus` (harness fixtures) renders its children expanded with no header* and folds when it settles.*/-export function TaskChatTurn({ item, renderChild, timestampPrefix, leading }: TaskChatTurnProps) {+export function TaskChatTurn({+ item,+ renderChild,+ timestampPrefix,+ leading,+}: TaskChatTurnProps) {const parentRow = !item.settled && item.liveStatus != null;+ // The new Paperclip Runner task surface owns one durable chronological+ // timeline. The Worked/Stopped row is its stable header, so it stays directly+ // below the preceding human bubble and above commentary, activity phases,+ // request receipts, and plan artifacts. The classic task interface continues+ // to use the run-wide fold below.+ if (item.standaloneHeader) {+ return (+ <div+ data-testid="task-chat-turn"+ data-settled={item.settled ? "true" : "false"}+ >+ <div+ className="flex min-h-8 w-full min-w-0 items-center gap-2 pb-1 pt-1.5 text-sm text-muted-foreground"+ data-testid="task-chat-turn-summary"+ data-turn-position="identity"+ >+ {item.agentName ? (+ <TaskChatAgentIdentity+ agentName={item.agentName}+ agentIcon={item.agentIcon}+ />+ ) : null}+ <span className="min-w-0 truncate">+ {item.summary.durationLabel+ ? `${item.summary.failed ? "Stopped" : "Worked"} for ${item.summary.durationLabel}`+ : item.summary.failed+ ? "Stopped"+ : "Worked"}+ </span>+ </div>+ {item.items.length > 0 ? (+ <div+ className="flex min-w-0 flex-col gap-2 py-1"+ data-testid="task-chat-turn-timeline"+ >+ {item.items.map((child) => (+ <div+ className="min-w-0"+ key={child.id}+ data-testid="task-chat-turn-timeline-row"+ data-timeline-row-id={child.id}+ >+ {renderChild(child)}+ </div>+ ))}+ </div>+ ) : null}+ {item.finalResponse ? (+ <div className="w-full" data-testid="task-chat-final-response">+ <div+ className="break-words px-1 py-2 text-sm text-foreground"+ data-testid="task-chat-agent-bubble"+ >+ <MarkdownBody softBreaks linkIssueReferences>+ {item.finalResponse.text}+ </MarkdownBody>+ </div>+ </div>+ ) : null}+ </div>+ );+ }+ const persistentItems = item.settled+ ? item.items.filter(+ (child) =>+ child.kind === "protocol" && child.surface === "runtime_request",+ )+ : [];+ const persistentItemIds = new Set(persistentItems.map((child) => child.id));+ const foldedItems =+ persistentItems.length > 0+ ? item.items.filter((child) => !persistentItemIds.has(child.id))+ : item.items;// Parent-row live turns and settled turns start as their one-line header;// only the headerless legacy live turn starts expanded.- const [open, setOpen] = useState(() => !item.settled && item.liveStatus == null);+ const [open, setOpen] = useState(+ () => !item.settled && item.liveStatus == null,+ );const [prevSettled, setPrevSettled] = useState(item.settled);const [wasParentRow, setWasParentRow] = useState(parentRow);@@ -76,7 +168,7 @@ export function TaskChatTurn({ item, renderChild, timestampPrefix, leading }: Taif (item.settled && !wasParentRow) setOpen(false);}- const expandable = item.items.length > 0;+ const expandable = foldedItems.length > 0;const folded = (item.settled || parentRow) && !open;const SummaryIcon = item.summary.failed ? X : Check;@@ -85,29 +177,54 @@ export function TaskChatTurn({ item, renderChild, timestampPrefix, leading }: Tatype="button"onClick={() => setOpen((o) => !o)}aria-expanded={open}- className="group flex items-center gap-2 px-1 py-0.5 text-xs text-muted-foreground transition-colors hover:text-foreground"+ className={cn(+ "group flex w-full items-center gap-2 px-1 text-muted-foreground transition-colors hover:text-foreground",+ item.standaloneHeader+ ? "border-b border-border/70 py-2 text-sm"+ : "py-0.5 text-xs",+ )}data-testid="task-chat-turn-summary">- <ChevronRight className={cn("h-3 w-3 shrink-0 transition-transform", open ? "rotate-90" : null)} aria-hidden />{timestampPrefix ? (<><span className="text-(length:--text-micro)">{timestampPrefix}</span>- <span aria-hidden className="text-(length:--text-micro)">·</span>+ <span aria-hidden className="text-(length:--text-micro)">+ ·+ </span></>) : null}- <SummaryIcon className="h-3.5 w-3.5 shrink-0" />- <span>{item.summary.failed ? "Stopped" : "Worked"}</span>- {turnSummaryMetrics(item.summary) ? (+ {!item.standaloneHeader ? (+ <SummaryIcon className="h-3.5 w-3.5 shrink-0" />+ ) : null}+ <span>+ {item.standaloneHeader && item.summary.durationLabel+ ? `${item.summary.failed ? "Stopped" : "Worked"} for ${item.summary.durationLabel}`+ : item.summary.failed+ ? "Stopped"+ : "Worked"}+ </span>+ {!item.standaloneHeader && turnSummaryMetrics(item.summary) ? (// Time/tools/tokens is demoted, not deleted (PAP-502): it stays in the// DOM (and the accessible tree) but fades in only on hover/focus so the// settled line reads as "2:34 PM · ✓ Worked" at rest. Revealed too when// the fold is open, so the metrics don't vanish while you read below.- <span className="tc-turn-metrics" data-visible={open ? "true" : "false"}>+ <span+ className="tc-turn-metrics"+ data-visible={open ? "true" : "false"}+ ><span className="min-w-0 overflow-hidden whitespace-nowrap font-mono text-(length:--text-micro)">{turnSummaryMetrics(item.summary)}</span></span>) : null}+ <ChevronRight+ className={cn(+ "h-3 w-3 shrink-0 transition-transform",+ item.standaloneHeader && "ml-auto",+ open ? "rotate-90" : null,+ )}+ aria-hidden+ /></button>) : parentRow ? (// The pill renders the expand button itself, wrapped around only the@@ -122,7 +239,10 @@ export function TaskChatTurn({ item, renderChild, timestampPrefix, leading }: Ta) : null;return (- <div data-testid="task-chat-turn" data-settled={item.settled ? "true" : "false"}>+ <div+ data-testid="task-chat-turn"+ data-settled={item.settled ? "true" : "false"}+ >{leading ? (// Actions ride the header row (items-center matches them to the summary// line), and the fold below is a separate sibling — so expanding the@@ -134,15 +254,29 @@ export function TaskChatTurn({ item, renderChild, timestampPrefix, leading }: Ta) : (header)}- <div className="tc-turn-fold" data-folded={folded ? "true" : "false"} aria-hidden={folded}>+ <div+ className="tc-turn-fold"+ data-folded={folded ? "true" : "false"}+ aria-hidden={folded}+ ><div><div className="flex flex-col gap-2 pt-1">- {item.items.map((child) => (+ {foldedItems.map((child) => (<div key={child.id}>{renderChild(child)}</div>))}</div></div></div>+ {persistentItems.length > 0 ? (+ <div+ className="flex flex-col gap-2 pt-2"+ data-testid="task-chat-turn-persistent-history"+ >+ {persistentItems.map((child) => (+ <div key={child.id}>{renderChild(child)}</div>+ ))}+ </div>+ ) : null}</div>);}diff --git a/ui/src/components/task-chat/TaskChatTurnStatusIsland.test.tsx b/ui/src/components/task-chat/TaskChatTurnStatusIsland.test.tsxnew file mode 100644index 0000000000..58b123193c--- /dev/null+++ b/ui/src/components/task-chat/TaskChatTurnStatusIsland.test.tsx@@ -0,0 +1,152 @@+// @vitest-environment jsdom++import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import type { TaskChatItem, TaskChatProviderActivityItem } from "./task-chat-model";+import {+ TaskChatTurnStatusIsland,+ taskChatTurnStatusModel,+} from "./TaskChatTurnStatusIsland";++function plan(steps: TaskChatProviderActivityItem["steps"], transcriptIndex = 1): TaskChatProviderActivityItem {+ return {+ id: "plan",+ kind: "protocol",+ surface: "provider_activity",+ family: "plan",+ eventType: "plan.updated",+ status: "running",+ title: "Plan",+ details: [],+ steps,+ links: [],+ children: [],+ transcriptIndex,+ };+}++const workspace: TaskChatItem = {+ id: "workspace",+ kind: "protocol",+ surface: "workspace_change",+ changeSetId: "turn-1:workspace",+ revision: 2,+ source: "harness_reported",+ complete: false,+ files: [+ { path: "one.ts", operation: "modify", previousPath: null, additions: 4, deletions: 2, binary: false, diff: null },+ { path: "two.ts", operation: "create", previousPath: null, additions: 8, deletions: 0, binary: false, diff: null },+ ],+ totals: { files: 2, additions: 12, deletions: 2 },+ patchArtifactRef: null,+};++describe("TaskChatTurnStatusIsland", () => {+ let container: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ });++ afterEach(() => {+ act(() => root.unmount());+ document.body.replaceChildren();+ });++ it("selects in-progress, blocked, pending, then final completed steps", () => {+ const inProgress = taskChatTurnStatusModel([plan([+ { id: "one", label: "Done", status: "completed" },+ { id: "two", label: "Active", status: "in_progress" },+ { id: "three", label: "Later", status: "pending" },+ ])]);+ expect(inProgress?.segments[0]).toMatchObject({ kind: "plan", currentStepIndex: 1, complete: false });++ const blocked = taskChatTurnStatusModel([plan([+ { id: "one", label: "Blocked", status: "blocked" },+ { id: "two", label: "Later", status: "pending" },+ ])]);+ expect(blocked?.segments[0]).toMatchObject({ kind: "plan", currentStepIndex: 0 });++ const completed = taskChatTurnStatusModel([plan([+ { id: "one", label: "Done", status: "completed" },+ { id: "two", label: "Also done", status: "completed" },+ ])]);+ expect(completed?.segments[0]).toMatchObject({ kind: "plan", currentStepIndex: 1, complete: true });+ });++ it("uses the latest plan snapshot and combines it with diff totals", () => {+ const model = taskChatTurnStatusModel([+ plan([{ id: "old", label: "Old", status: "in_progress" }], 1),+ workspace,+ plan([+ { id: "one", label: "Inspect", status: "completed" },+ { id: "two", label: "Build", status: "in_progress" },+ ], 3),+ ]);+ expect(model?.segments).toEqual([+ expect.objectContaining({ kind: "plan", currentStepIndex: 1 }),+ { kind: "workspace_diff", files: 2, additions: 12, deletions: 2 },+ ]);+ });++ it("renders a focusable plan capsule and opens the complete checklist", () => {+ const model = taskChatTurnStatusModel([+ plan([+ { id: "one", label: "Inspect", status: "completed" },+ { id: "two", label: "Build the island", status: "in_progress" },+ { id: "three", label: "Verify", status: "pending" },+ ]),+ workspace,+ ])!;+ act(() => root.render(<TaskChatTurnStatusIsland model={model} />));+ const island = container.querySelector('[data-testid="task-chat-turn-status-island"]') as HTMLButtonElement;+ expect(island.tagName).toBe("BUTTON");+ expect(island.textContent).toContain("Step 2 / 3");+ expect(island.textContent).toContain("2 files changed");+ expect(island.getAttribute("aria-label")).toContain("Build the island");++ act(() => island.focus());+ const checklist = document.body.querySelector('[aria-label="Within-turn checklist"]');+ expect(checklist?.textContent).toContain("Inspect");+ expect(checklist?.textContent).toContain("Build the island");+ expect(checklist?.textContent).toContain("Verify");+ expect(checklist?.querySelector('[aria-current="step"]')?.textContent).toContain("Build the island");+ });++ it("renders diff-only status without an empty interactive popover", () => {+ const model = taskChatTurnStatusModel([workspace])!;+ act(() => root.render(<TaskChatTurnStatusIsland model={model} />));+ const island = container.querySelector('[data-testid="task-chat-turn-status-island"]') as HTMLElement;+ expect(island.tagName).toBe("DIV");+ expect(island.getAttribute("role")).toBe("status");+ expect(island.textContent).toContain("+12");+ expect(document.body.querySelector('[aria-label="Within-turn checklist"]')).toBeNull();+ });++ it("toggles the checklist for touch/click input and closes it with Escape", () => {+ const model = taskChatTurnStatusModel([plan([+ { id: "one", label: "Inspect", status: "completed" },+ { id: "two", label: "Build", status: "in_progress" },+ ])])!;+ act(() => root.render(<TaskChatTurnStatusIsland model={model} />));+ const island = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-turn-status-island"]')!;++ act(() => island.click());+ expect(document.body.querySelector('[aria-label="Within-turn checklist"]')).not.toBeNull();+ act(() => island.click());+ expect(document.body.querySelector('[aria-label="Within-turn checklist"]')).toBeNull();++ act(() => island.click());+ act(() => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })));+ expect(document.body.querySelector('[aria-label="Within-turn checklist"]')).toBeNull();+ });++ it("hides empty snapshots", () => {+ expect(taskChatTurnStatusModel([])).toBeNull();+ expect(taskChatTurnStatusModel([plan([]), { ...workspace, files: [], totals: { files: 0, additions: 0, deletions: 0 } }])).toBeNull();+ });+});diff --git a/ui/src/components/task-chat/TaskChatTurnStatusIsland.tsx b/ui/src/components/task-chat/TaskChatTurnStatusIsland.tsxnew file mode 100644index 0000000000..5a25bba2bb--- /dev/null+++ b/ui/src/components/task-chat/TaskChatTurnStatusIsland.tsx@@ -0,0 +1,280 @@+import { useEffect, useRef, useState } from "react";+import {+ CheckCircle2,+ Circle,+ CircleAlert,+ LoaderCircle,+} from "lucide-react";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import { cn } from "@/lib/utils";+import type {+ TaskChatItem,+ TaskChatProtocolStep,+ TaskChatProviderActivityItem,+ TaskChatWorkspaceChangeItem,+} from "./task-chat-model";++export type TaskChatTurnStatusSegment =+ | {+ kind: "plan";+ steps: TaskChatProtocolStep[];+ currentStepIndex: number;+ complete: boolean;+ }+ | {+ kind: "workspace_diff";+ files: number;+ additions: number | null;+ deletions: number | null;+ };++export interface TaskChatTurnStatusModel {+ segments: TaskChatTurnStatusSegment[];+}++function latestPlan(items: readonly TaskChatItem[]): TaskChatProviderActivityItem | null {+ let latest: TaskChatProviderActivityItem | null = null;+ let latestOrder = -1;+ for (const [index, item] of items.entries()) {+ if (item.kind !== "protocol" || item.surface !== "provider_activity" || item.family !== "plan") continue;+ const order = item.transcriptIndex ?? index;+ if (order >= latestOrder) {+ latest = item;+ latestOrder = order;+ }+ }+ return latest;+}++function latestWorkspaceDiff(items: readonly TaskChatItem[]): TaskChatWorkspaceChangeItem | null {+ let latest: TaskChatWorkspaceChangeItem | null = null;+ for (const item of items) {+ if (item.kind === "protocol" && item.surface === "workspace_change") latest = item;+ }+ return latest;+}++function currentStepIndex(steps: readonly TaskChatProtocolStep[]): number {+ const inProgress = steps.findIndex((step) => step.status === "in_progress");+ if (inProgress >= 0) return inProgress;+ const blocked = steps.findIndex((step) => step.status === "blocked" || step.status === "failed");+ if (blocked >= 0) return blocked;+ const pending = steps.findIndex((step) => step.status === "pending");+ if (pending >= 0) return pending;+ return Math.max(0, steps.length - 1);+}++export function taskChatTurnStatusModel(items: readonly TaskChatItem[]): TaskChatTurnStatusModel | null {+ const segments: TaskChatTurnStatusSegment[] = [];+ const plan = latestPlan(items);+ if (plan && plan.steps.length > 0) {+ segments.push({+ kind: "plan",+ steps: plan.steps,+ currentStepIndex: currentStepIndex(plan.steps),+ complete: plan.steps.every((step) => step.status === "completed"),+ });+ }+ const workspace = latestWorkspaceDiff(items);+ const files = workspace ? workspace.totals.files || workspace.files.length : 0;+ if (workspace && files > 0) {+ segments.push({+ kind: "workspace_diff",+ files,+ additions: workspace.totals.additions,+ deletions: workspace.totals.deletions,+ });+ }+ return segments.length > 0 ? { segments } : null;+}++function planIcon(plan: Extract<TaskChatTurnStatusSegment, { kind: "plan" }>) {+ const status = plan.steps[plan.currentStepIndex]?.status;+ if (plan.complete) return <CheckCircle2 className="size-4 text-(--status-task-icon-done)" aria-hidden />;+ if (status === "blocked" || status === "failed") {+ return <CircleAlert className="size-4 text-(--status-task-icon-blocked)" aria-hidden />;+ }+ return <LoaderCircle className="size-4 text-(--status-agent-running) motion-safe:animate-spin" aria-hidden />;+}++function checklistIcon(step: TaskChatProtocolStep) {+ if (step.status === "completed") {+ return <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-(--status-task-icon-done)" aria-hidden />;+ }+ if (step.status === "in_progress") {+ return <LoaderCircle className="mt-0.5 size-4 shrink-0 text-(--status-agent-running) motion-safe:animate-spin" aria-hidden />;+ }+ if (step.status === "blocked" || step.status === "failed") {+ return <CircleAlert className="mt-0.5 size-4 shrink-0 text-(--status-task-icon-blocked)" aria-hidden />;+ }+ return <Circle className="mt-0.5 size-4 shrink-0 text-muted-foreground" aria-hidden />;+}++function fileCountLabel(files: number): string {+ return `${files} ${files === 1 ? "file" : "files"} changed`;+}++function IslandBody({ model }: { model: TaskChatTurnStatusModel }) {+ const plan = model.segments.find(+ (segment): segment is Extract<TaskChatTurnStatusSegment, { kind: "plan" }> => segment.kind === "plan",+ );+ const workspace = model.segments.find(+ (segment): segment is Extract<TaskChatTurnStatusSegment, { kind: "workspace_diff" }> => segment.kind === "workspace_diff",+ );+ return (+ <span className="flex min-w-0 items-center gap-2">+ {plan ? (+ <span className="flex shrink-0 items-center gap-2">+ {planIcon(plan)}+ <span className="font-mono text-sm tabular-nums" aria-live="polite" aria-atomic="true">+ Step {plan.currentStepIndex + 1} / {plan.steps.length}+ <span className="sr-only">: {plan.steps[plan.currentStepIndex]?.label}</span>+ </span>+ </span>+ ) : null}+ {plan && workspace ? <span className="text-muted-foreground" aria-hidden>·</span> : null}+ {workspace ? (+ <span className="flex min-w-0 items-center gap-2">+ <span className="min-w-0 truncate text-sm text-muted-foreground">+ {fileCountLabel(workspace.files)}+ </span>+ {workspace.additions != null ? (+ <span className="shrink-0 font-mono text-sm tabular-nums text-(--status-task-icon-done)">+ +{workspace.additions}+ </span>+ ) : null}+ {workspace.deletions != null ? (+ <span className="shrink-0 font-mono text-sm tabular-nums text-(--status-task-icon-blocked)">+ −{workspace.deletions}+ </span>+ ) : null}+ </span>+ ) : null}+ </span>+ );+}++function islandLabel(model: TaskChatTurnStatusModel): string {+ const parts: string[] = [];+ for (const segment of model.segments) {+ if (segment.kind === "plan") {+ const step = segment.steps[segment.currentStepIndex];+ parts.push(`Step ${segment.currentStepIndex + 1} of ${segment.steps.length}${step ? `: ${step.label}` : ""}`);+ } else {+ parts.push(fileCountLabel(segment.files));+ if (segment.additions != null) parts.push(`${segment.additions} additions`);+ if (segment.deletions != null) parts.push(`${segment.deletions} deletions`);+ }+ }+ return parts.join(", ");+}++const ISLAND_CLASS_NAME = "mx-auto flex min-h-10 max-w-(--sz-turn-status-island) items-center overflow-hidden rounded-full border border-border bg-popover/95 px-4 py-2 text-foreground shadow-sm backdrop-blur";++const HOVER_CLOSE_GRACE_MS = 100;++export function TaskChatTurnStatusIsland({ model }: { model: TaskChatTurnStatusModel }) {+ const plan = model.segments.find(+ (segment): segment is Extract<TaskChatTurnStatusSegment, { kind: "plan" }> => segment.kind === "plan",+ );+ const [open, setOpen] = useState(false);+ const [pinned, setPinned] = useState(false);+ const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);++ useEffect(() => () => {+ if (closeTimer.current) clearTimeout(closeTimer.current);+ }, []);++ const cancelClose = () => {+ if (closeTimer.current) clearTimeout(closeTimer.current);+ closeTimer.current = null;+ };+ const scheduleClose = () => {+ cancelClose();+ if (pinned) return;+ closeTimer.current = setTimeout(() => setOpen(false), HOVER_CLOSE_GRACE_MS);+ };++ if (!plan) {+ return (+ <div className={ISLAND_CLASS_NAME} role="status" data-testid="task-chat-turn-status-island">+ <IslandBody model={model} />+ </div>+ );+ }++ return (+ <Popover+ open={open}+ onOpenChange={(nextOpen) => {+ setOpen(nextOpen);+ if (!nextOpen) setPinned(false);+ }}+ >+ <PopoverTrigger asChild>+ <button+ type="button"+ aria-label={islandLabel(model)}+ className={cn(+ ISLAND_CLASS_NAME,+ "cursor-pointer transition-colors hover:bg-muted/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background motion-reduce:transition-none",+ )}+ data-testid="task-chat-turn-status-island"+ onPointerEnter={(event) => {+ if (event.pointerType !== "mouse") return;+ cancelClose();+ setOpen(true);+ }}+ onPointerLeave={(event) => {+ if (event.pointerType === "mouse") scheduleClose();+ }}+ onFocus={() => setOpen(true)}+ onClick={(event) => {+ event.preventDefault();+ const nextPinned = !pinned;+ setPinned(nextPinned);+ setOpen(nextPinned);+ }}+ >+ <IslandBody model={model} />+ </button>+ </PopoverTrigger>+ <PopoverContent+ side="top"+ align="center"+ sideOffset={8}+ className="w-(--sz-turn-status-popover) p-2"+ aria-label="Turn plan"+ onPointerEnter={(event) => {+ if (event.pointerType === "mouse") cancelClose();+ }}+ onPointerLeave={(event) => {+ if (event.pointerType === "mouse") scheduleClose();+ }}+ onEscapeKeyDown={() => setPinned(false)}+ onInteractOutside={() => setPinned(false)}+ >+ <ol className="flex flex-col gap-1" aria-label="Within-turn checklist">+ {plan.steps.map((step, index) => (+ <li+ key={step.id}+ className={cn(+ "flex items-start gap-2 rounded-md px-2 py-1.5 text-sm leading-5",+ index === plan.currentStepIndex && "bg-muted",+ step.status === "completed" && "text-muted-foreground",+ )}+ aria-current={index === plan.currentStepIndex ? "step" : undefined}+ >+ {checklistIcon(step)}+ <span className="min-w-0 break-words">{step.label}</span>+ </li>+ ))}+ </ol>+ </PopoverContent>+ </Popover>+ );+}diff --git a/ui/src/components/task-chat/TaskMessageScroller.test.tsx b/ui/src/components/task-chat/TaskMessageScroller.test.tsxindex fbe9e82704..a57beac995 100644--- a/ui/src/components/task-chat/TaskMessageScroller.test.tsx+++ b/ui/src/components/task-chat/TaskMessageScroller.test.tsx@@ -24,6 +24,34 @@ function fakeGeometry(el: HTMLElement, { scrollHeight = 1000, clientHeight = 400});}+function fakeResizableGeometry(+ el: HTMLElement,+ { scrollHeight = 1000, clientHeight = 400 } = {},+) {+ let currentClientHeight = clientHeight;+ let scrollTop = 0;+ Object.defineProperty(el, "scrollHeight", {+ value: scrollHeight,+ configurable: true,+ });+ Object.defineProperty(el, "clientHeight", {+ get: () => currentClientHeight,+ configurable: true,+ });+ Object.defineProperty(el, "scrollTop", {+ get: () => scrollTop,+ set: (value: number) => {+ scrollTop = value;+ },+ configurable: true,+ });+ return {+ setClientHeight(value: number) {+ currentClientHeight = value;+ },+ };+}+/*** Scroll/wheel are continuous-priority events, so React flushes the resulting* state updates asynchronously — wait a macrotask after dispatching.@@ -91,6 +119,8 @@ describe("TaskMessageScroller", () => {afterEach(() => {flushSync(() => root.unmount());container.remove();+ document.documentElement.style.removeProperty("--motion-scrollbar-idle-delay");+ vi.useRealTimers();vi.unstubAllGlobals();});@@ -110,6 +140,26 @@ describe("TaskMessageScroller", () => {expect(frame?.className).toBe("relative min-h-0 flex-1");});+ it("shows the scrollbar only while scroll activity is recent", () => {+ vi.useFakeTimers();+ document.documentElement.style.setProperty("--motion-scrollbar-idle-delay", "600ms");+ render();+ const el = scroller();+ fakeGeometry(el);++ expect(el.className).toContain("scrollbar-while-scrolling");+ expect(el.getAttribute("data-scroll-active")).toBeNull();++ el.scrollTop = 100;+ el.dispatchEvent(new Event("scroll", { bubbles: true }));+ expect(el.getAttribute("data-scroll-active")).toBe("true");++ vi.advanceTimersByTime(599);+ expect(el.getAttribute("data-scroll-active")).toBe("true");+ vi.advanceTimersByTime(1);+ expect(el.getAttribute("data-scroll-active")).toBeNull();+ });+it("auto-follows content instantly while pinned", async () => {render(1);const el = scroller();@@ -139,6 +189,59 @@ describe("TaskMessageScroller", () => {expect(el.scrollTop).toBe(100);});+ it("follows a shrinking viewport while pinned so a growing composer cannot cover the latest text", async () => {+ let triggerResize = () => {};+ vi.stubGlobal(+ "ResizeObserver",+ class {+ constructor(callback: ResizeObserverCallback) {+ triggerResize = () =>+ callback([], this as unknown as ResizeObserver);+ }+ observe() {}+ disconnect() {}+ },+ );+ render();+ const el = scroller();+ const geometry = fakeResizableGeometry(el);+ triggerResize();+ await scrollTo(el, 600);++ geometry.setClientHeight(200);+ triggerResize();++ expect(el.scrollTop).toBe(el.scrollHeight);+ expect(pill()).toBeNull();+ });++ it("holds a reader's position when the composer grows while they are scrolled up", async () => {+ let triggerResize = () => {};+ vi.stubGlobal(+ "ResizeObserver",+ class {+ constructor(callback: ResizeObserverCallback) {+ triggerResize = () =>+ callback([], this as unknown as ResizeObserver);+ }+ observe() {}+ disconnect() {}+ },+ );+ render();+ const el = scroller();+ const geometry = fakeResizableGeometry(el);+ triggerResize();+ await scrollTo(el, 100);+ await waitForPill(true);++ geometry.setClientHeight(200);+ triggerResize();++ expect(el.scrollTop).toBe(100);+ expect(pill()).not.toBeNull();+ });+it("small drifts within the pin threshold do not show the pill", async () => {render();const el = scroller();diff --git a/ui/src/components/task-chat/TaskMessageScroller.tsx b/ui/src/components/task-chat/TaskMessageScroller.tsxindex 4ece3b85a2..107d52d68b 100644--- a/ui/src/components/task-chat/TaskMessageScroller.tsx+++ b/ui/src/components/task-chat/TaskMessageScroller.tsx@@ -1,6 +1,7 @@import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";import { cn } from "@/lib/utils";import { ArrowDown } from "lucide-react";+import { parseCssTimeMs } from "./motion-tokens";const PIN_THRESHOLD_PX = 48;@@ -44,8 +45,29 @@ export function TaskMessageScroller({ children, contentKey, className }: TaskMesconst ref = useRef<HTMLDivElement>(null);const pinnedRef = useRef(true);const easingRef = useRef(false);+ const clientHeightRef = useRef<number | null>(null);+ const scrollbarIdleTimerRef = useRef<number | null>(null);+ const scrollbarIdleDelayRef = useRef<number | null>(null);const [pillPhase, setPillPhase] = useState<PillPhase>("hidden");+ const showScrollbarWhileScrolling = useCallback(() => {+ const el = ref.current;+ if (!el) return;+ el.dataset.scrollActive = "true";+ if (scrollbarIdleTimerRef.current !== null) {+ window.clearTimeout(scrollbarIdleTimerRef.current);+ }+ const idleDelay = scrollbarIdleDelayRef.current ?? parseCssTimeMs(+ getComputedStyle(document.documentElement).getPropertyValue("--motion-scrollbar-idle-delay"),+ );+ scrollbarIdleDelayRef.current = idleDelay;+ scrollbarIdleTimerRef.current = window.setTimeout(() => {+ delete el.dataset.scrollActive;+ scrollbarIdleTimerRef.current = null;+ scrollbarIdleDelayRef.current = null;+ }, idleDelay);+ }, []);+const showPill = useCallback(() => {setPillPhase("in");}, []);@@ -68,7 +90,34 @@ export function TaskMessageScroller({ children, contentKey, className }: TaskMesel.scrollTop = el.scrollHeight; // instant, never smooth}, []);+ const followViewportResize = useCallback(() => {+ const el = ref.current;+ if (!el) return false;+ const previousClientHeight = clientHeightRef.current;+ const nextClientHeight = el.clientHeight;+ clientHeightRef.current = nextClientHeight;+ if (+ previousClientHeight == null ||+ previousClientHeight <= 0 ||+ previousClientHeight === nextClientHeight ||+ !pinnedRef.current+ ) {+ return false;+ }+ scrollToBottom();+ return true;+ }, [scrollToBottom]);+const handleScroll = useCallback(() => {+ showScrollbarWhileScrolling();+ // A growing composer shrinks this viewport. Some browsers dispatch the+ // resulting scroll event before ResizeObserver, so preserve the previous+ // pinned state here instead of mistaking the layout change for a user+ // scroll away from the bottom.+ if (followViewportResize()) {+ hidePill();+ return;+ }const pinned = isPinned();if (easingRef.current) {// Smooth re-follow in flight: intermediate scroll events must not@@ -83,7 +132,13 @@ export function TaskMessageScroller({ children, contentKey, className }: TaskMespinnedRef.current = pinned;if (pinned) hidePill();else showPill();- }, [isPinned, hidePill, showPill]);+ }, [+ followViewportResize,+ isPinned,+ hidePill,+ showPill,+ showScrollbarWhileScrolling,+ ]);const handleJumpToLatest = useCallback(() => {const el = ref.current;@@ -125,6 +180,24 @@ export function TaskMessageScroller({ children, contentKey, className }: TaskMes};}, [showPill]);+ useEffect(() => () => {+ if (scrollbarIdleTimerRef.current !== null) {+ window.clearTimeout(scrollbarIdleTimerRef.current);+ }+ }, []);++ useLayoutEffect(() => {+ const el = ref.current;+ if (!el) return;+ clientHeightRef.current = el.clientHeight;+ if (typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(() => {+ if (followViewportResize()) hidePill();+ });+ observer.observe(el);+ return () => observer.disconnect();+ }, [followViewportResize, hidePill]);+// Follow new content only when already pinned; otherwise hold position.useLayoutEffect(() => {if (pinnedRef.current) scrollToBottom();@@ -143,7 +216,7 @@ export function TaskMessageScroller({ children, contentKey, className }: TaskMes// absolute inset-0 (not h-full): the viewport must equal the flex-sized// wrapper exactly — percentage heights don't reliably resolve against// flex-determined block heights, which let the thread overflow the page.- className={cn("absolute inset-0 overflow-y-auto", className)}+ className={cn("scrollbar-while-scrolling absolute inset-0 overflow-y-auto", className)}data-testid="task-chat-scroller">{children}diff --git a/ui/src/components/task-chat/interaction-thread-order.test.ts b/ui/src/components/task-chat/interaction-thread-order.test.tsindex 6f6183d56d..3371ca8413 100644--- a/ui/src/components/task-chat/interaction-thread-order.test.ts+++ b/ui/src/components/task-chat/interaction-thread-order.test.ts@@ -127,7 +127,7 @@ describe("interactionThreadAnchorMs", () => {expect(interactionThreadAnchorMs(confirmation(), CREATED_MS)).toBe(CREATED_MS);});- it("re-anchors a resolved card to its resolution time", () => {+ it("places a resolved confirmation at the decision time", () => {const resolved = confirmation({status: "accepted",result: result("accepted"),@@ -136,7 +136,29 @@ describe("interactionThreadAnchorMs", () => {expect(interactionThreadAnchorMs(resolved, CREATED_MS)).toBe(RESOLVED_MS);});- it("never drags a resolved card above its own request slot", () => {+ it("keeps an answered question card where the question was originally asked", () => {+ const answeredQuestion = confirmation({+ kind: "ask_user_questions",+ status: "answered",+ payload: {+ version: 1,+ questions: [{+ id: "environment",+ prompt: "Which environment?",+ selectionMode: "single",+ options: [{ id: "production", label: "Production" }],+ }],+ },+ result: {+ version: 1,+ answers: [{ questionId: "environment", optionIds: ["production"] }],+ },+ resolvedAt: new Date(RESOLVED_MS),+ } as never);+ expect(interactionThreadAnchorMs(answeredQuestion, CREATED_MS)).toBe(CREATED_MS);+ });++ it("never drags a resolved confirmation above its own request slot", () => {// Clock skew: resolvedAt reads earlier than the handoff/created fallback.const resolved = confirmation({status: "accepted",diff --git a/ui/src/components/task-chat/interaction-thread-order.ts b/ui/src/components/task-chat/interaction-thread-order.tsindex 5f218a121b..a81e91314c 100644--- a/ui/src/components/task-chat/interaction-thread-order.ts+++ b/ui/src/components/task-chat/interaction-thread-order.ts@@ -6,11 +6,11 @@ import type { IssueThreadInteraction } from "@/lib/issue-thread-interactions";** Two problems this fixes:*- * 1. Cards were pinned to `createdAt`, but the user answers them later and the- * agent's follow-up lands later still — so a card you just resolved could- * sit ABOVE a message written before you answered, reading backwards. We- * settle a RESOLVED card at its resolution time (`resolvedAt`) so it never- * floats above an earlier message. Pending cards stay where they were asked.+ * 1. Question receipts keep the request's original slot because a separate+ * answer-delivery bubble records when those answers entered a successor+ * run. A resolved confirmation is itself the user's decision receipt, so+ * it moves to `resolvedAt` and separates the work before and after that+ * decision.** 2. Withdrawn / superseded confirmation cards lingered in the thread, stacking* a dead card above the accepted one. We suppress those from the backbone@@ -60,26 +60,30 @@ export function isSuppressedThreadInteraction(interaction: IssueThreadInteractioreturn outcome != null && SUPPRESSED_CONFIRMATION_OUTCOMES.has(outcome);}-function toMs(value: Date | string | null | undefined): number {- if (!value) return 0;- const ms = new Date(value).getTime();- return Number.isNaN(ms) ? 0 : ms;-}-/*** The chronological slot for an interaction card.*- * `fallbackMs` is the caller's existing anchor (the same-run handoff shift when- * present, else `createdAt`). A resolved card re-anchors to its resolution time- * so it lands next to the answer, never above an earlier message; we take the- * later of the two so clock skew can't drag it back above its own request. A- * still-pending card keeps the request-time slot.+ * `fallbackMs` is the caller's existing request anchor (the same-run handoff+ * shift when present, else `createdAt`). Pending confirmations and question+ * receipts keep that slot. Terminal confirmation-family receipts move to the+ * decision time, clamped so clock skew can never place them before the request.*/export function interactionThreadAnchorMs(interaction: IssueThreadInteraction,fallbackMs: number,): number {- if (interaction.status === "pending") return fallbackMs;- const resolvedMs = toMs(interaction.resolvedAt);- return resolvedMs > 0 ? Math.max(resolvedMs, fallbackMs) : fallbackMs;+ if (+ interaction.status === "pending" ||+ !CONFIRMATION_KINDS.has(interaction.kind) ||+ !interaction.resolvedAt+ ) {+ return fallbackMs;+ }+ const resolvedAtMs =+ interaction.resolvedAt instanceof Date+ ? interaction.resolvedAt.getTime()+ : new Date(interaction.resolvedAt).getTime();+ return Number.isFinite(resolvedAtMs)+ ? Math.max(fallbackMs, resolvedAtMs)+ : fallbackMs;}diff --git a/ui/src/components/task-chat/motion-tokens.ts b/ui/src/components/task-chat/motion-tokens.tsindex c6259c2f5c..98b864e7f7 100644--- a/ui/src/components/task-chat/motion-tokens.ts+++ b/ui/src/components/task-chat/motion-tokens.ts@@ -63,7 +63,9 @@ export const MOTION_TOKENS: MotionTokenDef[] = [{ name: "--motion-interstitial-dwell", group: "States", kind: "time", min: 0, max: 10000, step: 100 },{ name: "--motion-scroll-pill-enter", group: "States", kind: "time", min: 0, max: 1500, step: 10 },{ name: "--motion-scroll-pill-exit", group: "States", kind: "time", min: 0, max: 1500, step: 10 },+ { name: "--motion-scrollbar-idle-delay", group: "States", kind: "time", min: 0, max: 2000, step: 10 },{ name: "--motion-pane-glide", group: "States", kind: "time", min: 0, max: 1500, step: 10 },+ { name: "--motion-side-panel-tab", group: "States", kind: "time", min: 0, max: 1500, step: 10 },];/** Common easing presets offered by the tweak panel's easing picker. */diff --git a/ui/src/components/task-chat/question-validation-pattern.test.ts b/ui/src/components/task-chat/question-validation-pattern.test.tsnew file mode 100644index 0000000000..4b0aa0b050--- /dev/null+++ b/ui/src/components/task-chat/question-validation-pattern.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";+import { matchSafeQuestionValidationPattern } from "./question-validation-pattern";++describe("matchSafeQuestionValidationPattern", () => {+ it("matches the bounded fixed-width subset without a dynamic RegExp", () => {+ expect(matchSafeQuestionValidationPattern("^#[0-9A-F][0-9A-F]$", "#2F"))+ .toBe("match");+ expect(matchSafeQuestionValidationPattern("^#[0-9A-F][0-9A-F]$", "#GG"))+ .toBe("no_match");+ expect(matchSafeQuestionValidationPattern("^item\\.\\d$", "item.7"))+ .toBe("match");+ });++ it("rejects provider patterns that can trigger backtracking", () => {+ expect(+ matchSafeQuestionValidationPattern("^(a+)+$", `${"a".repeat(50_000)}!`),+ ).toBe("unsupported");+ expect(matchSafeQuestionValidationPattern("^[a-z]*[a-z]*$", "abc"))+ .toBe("unsupported");+ expect(matchSafeQuestionValidationPattern("[a-z]", "a"))+ .toBe("unsupported");+ });+});diff --git a/ui/src/components/task-chat/question-validation-pattern.ts b/ui/src/components/task-chat/question-validation-pattern.tsnew file mode 100644index 0000000000..d689ef332a--- /dev/null+++ b/ui/src/components/task-chat/question-validation-pattern.ts@@ -0,0 +1,147 @@+export type QuestionValidationPatternResult =+ | "match"+ | "no_match"+ | "unsupported";++const MAX_SAFE_PATTERN_LENGTH = 256;+const UNSUPPORTED_PATTERN_TOKENS = new Set([+ "(",+ ")",+ "{",+ "}",+ "*",+ "+",+ "?",+ "|",+ "^",+ "$",+]);++type CharacterMatcher = (character: string) => boolean;++function escapedMatcher(token: string): CharacterMatcher {+ if (token === "d")+ return (character) => character >= "0" && character <= "9";+ if (token === "D") return (character) => character < "0" || character > "9";+ if (token === "w")+ return (character) =>+ (character >= "0" && character <= "9") ||+ (character >= "A" && character <= "Z") ||+ (character >= "a" && character <= "z") ||+ character === "_";+ if (token === "W") {+ const word = escapedMatcher("w");+ return (character) => !word(character);+ }+ if (token === "s")+ return (character) => " \t\n\r\f\v".includes(character);+ if (token === "S") {+ const whitespace = escapedMatcher("s");+ return (character) => !whitespace(character);+ }+ return (character) => character === token;+}++function classMatcher(+ source: string,+ start: number,+): { matcher: CharacterMatcher; next: number } | null {+ let cursor = start;+ const negated = source[cursor] === "^";+ if (negated) cursor += 1;+ const ranges: Array<[number, number]> = [];++ const readCharacter = (): string | null => {+ if (cursor >= source.length || source[cursor] === "]") return null;+ const current = source[cursor++]!;+ if (current !== "\\") return current;+ if (cursor >= source.length) return null;+ const escaped = source[cursor++]!;+ // Character-class escapes with semantic expansion would make range+ // parsing ambiguous. Fail closed; escaped punctuation remains literal.+ if ("dDsSwW".includes(escaped)) return null;+ return escaped;+ };++ while (cursor < source.length && source[cursor] !== "]") {+ const first = readCharacter();+ if (first === null) return null;+ if (+ source[cursor] === "-" &&+ cursor + 1 < source.length &&+ source[cursor + 1] !== "]"+ ) {+ cursor += 1;+ const last = readCharacter();+ if (last === null || first.charCodeAt(0) > last.charCodeAt(0))+ return null;+ ranges.push([first.charCodeAt(0), last.charCodeAt(0)]);+ } else {+ ranges.push([first.charCodeAt(0), first.charCodeAt(0)]);+ }+ }+ if (source[cursor] !== "]" || ranges.length === 0) return null;+ const next = cursor + 1;+ return {+ next,+ matcher: (character) => {+ const code = character.charCodeAt(0);+ const included = ranges.some(+ ([first, last]) => code >= first && code <= last,+ );+ return negated ? !included : included;+ },+ };+}++/**+ * Evaluate a deliberately small, fixed-width subset of regular-expression+ * syntax without invoking JavaScript's backtracking RegExp engine. Provider+ * patterns outside this subset fail closed instead of reaching the UI thread.+ */+export function matchSafeQuestionValidationPattern(+ pattern: string,+ value: string,+): QuestionValidationPatternResult {+ if (+ pattern.length < 2 ||+ pattern.length > MAX_SAFE_PATTERN_LENGTH ||+ !pattern.startsWith("^") ||+ !pattern.endsWith("$")+ ) {+ return "unsupported";+ }++ const source = pattern.slice(1, -1);+ const matchers: CharacterMatcher[] = [];+ let cursor = 0;+ while (cursor < source.length) {+ const token = source[cursor++]!;+ if (UNSUPPORTED_PATTERN_TOKENS.has(token)) return "unsupported";+ if (token === "[") {+ const parsed = classMatcher(source, cursor);+ if (!parsed) return "unsupported";+ matchers.push(parsed.matcher);+ cursor = parsed.next;+ continue;+ }+ if (token === "]") return "unsupported";+ if (token === "\\") {+ if (cursor >= source.length) return "unsupported";+ matchers.push(escapedMatcher(source[cursor++]!));+ continue;+ }+ if (token === ".") {+ matchers.push(+ (character) => !["\n", "\r", "\u2028", "\u2029"].includes(character),+ );+ continue;+ }+ matchers.push((character) => character === token);+ }++ if (value.length !== matchers.length) return "no_match";+ return matchers.every((matcher, index) => matcher(value[index]!))+ ? "match"+ : "no_match";+}diff --git a/ui/src/components/task-chat/task-chat-activity-presentation.ts b/ui/src/components/task-chat/task-chat-activity-presentation.tsnew file mode 100644index 0000000000..4d905b65ff--- /dev/null+++ b/ui/src/components/task-chat/task-chat-activity-presentation.ts@@ -0,0 +1,192 @@+import {+ AlertTriangle,+ BookOpen,+ Bot,+ Box,+ Clock3,+ Database,+ FileCheck2,+ FilePenLine,+ FileText,+ GitBranch,+ ListChecks,+ PackageCheck,+ Search,+ ShieldCheck,+ TerminalSquare,+ Users,+} from "lucide-react";+import type {+ TaskChatMaterializedResourceItem,+ TaskChatProtocolItem,+ TaskChatProviderActivityItem,+ TaskChatWorkspaceChangeItem,+ TaskChatWorkspaceFileItem,+} from "./task-chat-model";+import {+ humanizeToolName,+ isGenericToolName,+ mcpToolIdentity,+ toolActivityPresentation,+ type ToolIcon,+} from "./tool-taxonomy";++export interface TaskChatActivityPresentation {+ icon: ToolIcon;+ runningLabel: string;+ completedLabel: string;+ failedLabel?: string;+ interruptedLabel?: string;+ detail?: string;+}++function providerDetail(item: TaskChatProviderActivityItem, ...labels: string[]): string | undefined {+ return item.details.find((entry) => labels.includes(entry.label))?.value;+}++function meaningfulToolDetail(value: string | undefined): string | undefined {+ if (!value || isGenericToolName(value) || /^tool(?:\s+|_)call\b/i.test(value)) return undefined;+ return value;+}++export function providerActivityPresentation(item: TaskChatProviderActivityItem): TaskChatActivityPresentation {+ const detail = item.summary+ ?? providerDetail(item, "Query", "URL", "Target", "Name", "Reference", "Reason", "Summary");+ switch (item.family) {+ case "research": {+ const action = providerDetail(item, "Action")?.toLowerCase();+ if (action === "open_page") {+ return { icon: Search, runningLabel: "Opening a web page", completedLabel: "Opened a web page", failedLabel: "Couldn’t open the web page", interruptedLabel: "Stopped opening the web page", detail };+ }+ if (action === "find_in_page") {+ return { icon: Search, runningLabel: "Searching the page", completedLabel: "Searched the page", failedLabel: "Page search failed", interruptedLabel: "Page search stopped", detail };+ }+ return { icon: Search, runningLabel: "Searching the web", completedLabel: "Searched the web", failedLabel: "Web search failed", interruptedLabel: "Web search stopped", detail };+ }+ case "tool_execution": {+ const name = providerDetail(item, "Name");+ const target = providerDetail(item, "Target");+ const progress = providerDetail(item, "Progress");+ const tool = toolActivityPresentation({+ name,+ transport: providerDetail(item, "Transport"),+ namespace: providerDetail(item, "Namespace"),+ operation: providerDetail(item, "Operation"),+ target,+ progress,+ });+ const boundedActivity = meaningfulToolDetail(item.summary)+ ?? meaningfulToolDetail(progress)+ ?? meaningfulToolDetail(target);+ const activityIsIdentity = Boolean(+ boundedActivity && name && humanizeToolName(boundedActivity) === humanizeToolName(name),+ );+ const technicalName = name ? mcpToolIdentity(name)?.name ?? name : tool.displayName;+ const source = tool.sourceLabel+ ? `${tool.sourceLabel} · ${technicalName}`+ : name && !isGenericToolName(name) && humanizeToolName(name) !== tool.runningLabel.replace(/^Running /, "")+ ? name+ : undefined;+ return {+ icon: tool.icon,+ runningLabel: tool.runningLabel,+ completedLabel: tool.completedLabel,+ failedLabel: tool.failedLabel,+ interruptedLabel: tool.interruptedLabel,+ detail: [activityIsIdentity ? undefined : boundedActivity, source].filter(Boolean).join(" · ") || undefined,+ };+ }+ case "plan":+ return { icon: ListChecks, runningLabel: "Updating the plan", completedLabel: "Updated the plan", failedLabel: "Plan update failed", interruptedLabel: "Plan update stopped", detail };+ case "delegation": {+ const action = providerDetail(item, "Action")?.toLowerCase();+ if (action === "message") return { icon: Users, runningLabel: "Messaging a subagent", completedLabel: "Messaged a subagent", failedLabel: "Subagent message failed", interruptedLabel: "Subagent message stopped", detail };+ if (action === "resume") return { icon: Users, runningLabel: "Resuming a subagent", completedLabel: "Resumed a subagent", failedLabel: "Couldn’t resume the subagent", interruptedLabel: "Subagent resume stopped", detail };+ if (action === "close") return { icon: Users, runningLabel: "Closing a subagent", completedLabel: "Closed a subagent", failedLabel: "Couldn’t close the subagent", interruptedLabel: "Subagent close stopped", detail };+ if (action === "wait") return { icon: Users, runningLabel: "Waiting for subagents", completedLabel: "Finished waiting for subagents", failedLabel: "Subagent wait failed", interruptedLabel: "Stopped waiting for subagents", detail };+ return { icon: Users, runningLabel: "Starting a subagent", completedLabel: "Started a subagent", failedLabel: "Subagent start failed", interruptedLabel: "Subagent start stopped", detail };+ }+ case "model_identity":+ return item.eventType === "model.route.changed"+ ? { icon: Bot, runningLabel: "Switching models", completedLabel: "Switched models", failedLabel: "Model switch failed", interruptedLabel: "Model switch stopped", detail }+ : { icon: Bot, runningLabel: "Verifying the model", completedLabel: "Verified the model", failedLabel: "Model verification failed", interruptedLabel: "Model verification stopped", detail };+ case "context":+ return { icon: Database, runningLabel: "Compacting context", completedLabel: "Compacted context", failedLabel: "Context compaction failed", interruptedLabel: "Context compaction stopped", detail };+ case "artifact": {+ const viewed = item.eventType === "artifact.viewed";+ return viewed+ ? { icon: Box, runningLabel: "Viewing an artifact", completedLabel: "Viewed an artifact", failedLabel: "Couldn’t view the artifact", interruptedLabel: "Artifact view stopped", detail }+ : { icon: Box, runningLabel: "Generating an artifact", completedLabel: "Generated an artifact", failedLabel: "Artifact generation failed", interruptedLabel: "Artifact generation stopped", detail };+ }+ case "review": {+ const state = providerDetail(item, "State")?.toLowerCase();+ return state === "exited"+ ? { icon: FileCheck2, runningLabel: "Leaving review mode", completedLabel: "Left review mode", failedLabel: "Couldn’t leave review mode", interruptedLabel: "Review-mode change stopped", detail }+ : { icon: FileCheck2, runningLabel: "Entering review mode", completedLabel: "Entered review mode", failedLabel: "Couldn’t enter review mode", interruptedLabel: "Review-mode change stopped", detail };+ }+ case "hook":+ return { icon: GitBranch, runningLabel: "Running a hook", completedLabel: "Ran a hook", failedLabel: "Hook failed", interruptedLabel: "Hook stopped", detail };+ case "memory":+ return { icon: BookOpen, runningLabel: "Checking memory", completedLabel: "Referenced memory", failedLabel: "Memory lookup failed", interruptedLabel: "Memory lookup stopped", detail };+ case "safety":+ return { icon: ShieldCheck, runningLabel: "Reviewing safety", completedLabel: "Reviewed safety", failedLabel: "Safety review failed", interruptedLabel: "Safety review stopped", detail };+ case "terminal":+ return { icon: TerminalSquare, runningLabel: "Sending terminal input", completedLabel: "Sent terminal input", failedLabel: "Terminal input failed", interruptedLabel: "Terminal input stopped", detail };+ case "wait":+ return { icon: Clock3, runningLabel: "Waiting", completedLabel: "Finished waiting", failedLabel: "Wait failed", interruptedLabel: "Wait stopped", detail };+ case "provider_notice":+ return { icon: AlertTriangle, runningLabel: "Provider notice", completedLabel: "Provider notice", failedLabel: "Provider error", interruptedLabel: "Provider notice", detail };+ }+}++function workspaceChangePresentation(item: TaskChatWorkspaceChangeItem): TaskChatActivityPresentation {+ const count = item.totals.files || item.files.length;+ const detail = count > 0 ? `${count} ${count === 1 ? "file" : "files"}` : undefined;+ return { icon: FilePenLine, runningLabel: "Editing files", completedLabel: "Edited files", detail };+}++function workspaceFilePresentation(item: TaskChatWorkspaceFileItem): TaskChatActivityPresentation {+ return {+ icon: FileText,+ runningLabel: "Referencing a file",+ completedLabel: "Referenced a file",+ detail: item.line == null ? item.path : `${item.path}:${item.line}`,+ };+}++function resourcePresentation(item: TaskChatMaterializedResourceItem): TaskChatActivityPresentation {+ return {+ icon: item.resourceKind === "document" ? FileText : PackageCheck,+ runningLabel: "Saving a resource",+ completedLabel: item.resourceKind === "document" ? "Added a document" : "Added a deliverable",+ detail: item.title,+ };+}++export function protocolActivityPresentation(item: TaskChatProtocolItem): TaskChatActivityPresentation | null {+ switch (item.surface) {+ case "provider_activity": return providerActivityPresentation(item);+ case "workspace_change": return workspaceChangePresentation(item);+ case "workspace_file": return workspaceFilePresentation(item);+ case "resource": return resourcePresentation(item);+ case "runtime_request":+ case "run_result":+ case "run_terminal":+ return null;+ }+}++export function protocolActivityIsRunning(item: TaskChatProtocolItem): boolean {+ if (item.surface === "provider_activity") return item.status === "running";+ if (item.surface === "workspace_change") return !item.complete;+ return false;+}++export function protocolActivityLabel(item: TaskChatProtocolItem, presentation: TaskChatActivityPresentation): string {+ if (item.surface !== "provider_activity") {+ return protocolActivityIsRunning(item) ? presentation.runningLabel : presentation.completedLabel;+ }+ if (item.status === "failed") return presentation.failedLabel ?? `${presentation.completedLabel} · failed`;+ if (item.status === "interrupted") return presentation.interruptedLabel ?? `${presentation.completedLabel} · interrupted`;+ return item.status === "running" ? presentation.runningLabel : presentation.completedLabel;+}diff --git a/ui/src/components/task-chat/task-chat-adapter.test.ts b/ui/src/components/task-chat/task-chat-adapter.test.tsindex 3596177cc1..7a32604b27 100644--- a/ui/src/components/task-chat/task-chat-adapter.test.ts+++ b/ui/src/components/task-chat/task-chat-adapter.test.ts@@ -56,6 +56,31 @@ describe("commentsToTaskChatItems", () => {expect(item.author).toBe("system");});+ it("attaches verification caveats using durable comment run provenance", () => {+ const verificationCaveats = [{+ commandOrCheck: "external-validator",+ reasonCode: "tool_unavailable",+ detail: "The optional validator is unavailable.",+ }];+ const comments = [{+ id: "c-final",+ body: "Implemented and locally verified.",+ authorType: "agent",+ authorAgentId: "agent-1",+ createdByRunId: "run-1",+ createdAt: "2026-08-22T09:00:00.000Z",+ } as unknown as IssueChatComment];++ const items = commentsToTaskChatItems(comments, {+ verificationCaveatsByRunId: new Map([["run-1", verificationCaveats]]),+ });++ expect(items).toEqual([expect.objectContaining({+ kind: "message",+ verificationCaveats,+ })]);+ });+it("carries presentation, metadata, and the raw timestamp for system comments", () => {const presentation = {kind: "system_notice",diff --git a/ui/src/components/task-chat/task-chat-adapter.ts b/ui/src/components/task-chat/task-chat-adapter.tsindex 62af3ca33e..b5dfa52e38 100644--- a/ui/src/components/task-chat/task-chat-adapter.ts+++ b/ui/src/components/task-chat/task-chat-adapter.ts@@ -10,7 +10,7 @@import type { Agent } from "@paperclipai/shared";import type { IssueChatComment } from "@/lib/issue-chat-messages";import { resolveCommentAttribution } from "@/lib/comment-attribution";-import type { TaskChatAuthorKind, TaskChatItem } from "./task-chat-model";+import type { TaskChatAuthorKind, TaskChatItem, TaskChatMessageItem } from "./task-chat-model";export interface TaskChatAdapterContext {agentMap?: Map<string, Agent>;@@ -21,6 +21,7 @@ export interface TaskChatAdapterContext {* writes and get a "for {user}" attribution chip (the open cross-task write design (attribution)).*/issueAssigneeAgentId?: string | null;+ verificationCaveatsByRunId?: ReadonlyMap<string, TaskChatMessageItem["verificationCaveats"]>;}function effectiveAgentId(comment: IssueChatComment): string | null {@@ -83,6 +84,15 @@ export function commentsToTaskChatItems(: comment.createdAt? String(comment.createdAt): undefined;+ // Durable run-authored comments already carry their source run directly.+ // Activity-derived `runId` is a useful fallback for older rows, but it may+ // arrive later (or be omitted entirely for server-materialized final+ // replies). Prefer the stored provenance so settled-response decorations+ // such as verification caveats are never lost.+ const sourceRunId = comment.createdByRunId+ ?? comment.runId+ ?? comment.derivedCreatedByRunId+ ?? null;items.push({id: comment.id || comment.clientId || `${comment.createdAt}`,kind: "message",@@ -92,6 +102,9 @@ export function commentsToTaskChatItems(timestamp: formatTaskChatTimestamp(comment.createdAt),optimistic,queueTargetRunId: queued ? comment.queueTargetRunId ?? null : null,+ verificationCaveats: sourceRunId+ ? ctx.verificationCaveatsByRunId?.get(sourceRunId)+ : undefined,agentIcon,onBehalfOfUserName,// System notices carry their structured hints through to the renderdiff --git a/ui/src/components/task-chat/task-chat-model.test.ts b/ui/src/components/task-chat/task-chat-model.test.tsnew file mode 100644index 0000000000..f77a06df59--- /dev/null+++ b/ui/src/components/task-chat/task-chat-model.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from "vitest";++import {+ latestPendingRuntimeRequest,+ runtimeRequestReplacesComposerSkip,+ type TaskChatRuntimeRequestItem,+} from "./task-chat-model";++function runtimeRequest(+ requestId: string,+ status: TaskChatRuntimeRequestItem["status"],+): TaskChatRuntimeRequestItem {+ return {+ id: `${requestId}:${status}`,+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-1",+ requestId,+ requestKind: "runtime",+ turnId: "turn-1",+ requestType: "input",+ status,+ prompt: "Choose",+ choices: [],+ fields: [],+ };+}++describe("latestPendingRuntimeRequest", () => {+ it("suppresses a stale pending card after every terminal lifecycle outcome", () => {+ for (const status of ["resolved", "expired", "cancelled"] as const) {+ expect(+ latestPendingRuntimeRequest([+ runtimeRequest("request-1", "pending"),+ runtimeRequest("request-1", status),+ ]),+ ).toBeNull();+ }+ });++ it("retains another request that is still pending", () => {+ expect(+ latestPendingRuntimeRequest([+ runtimeRequest("request-1", "pending"),+ runtimeRequest("request-2", "pending"),+ runtimeRequest("request-2", "resolved"),+ ]),+ ).toMatchObject({ requestId: "request-1", status: "pending" });+ });+});++describe("runtimeRequestReplacesComposerSkip", () => {+ it("uses an explicit denial choice instead of showing a redundant composer Skip", () => {+ expect(+ runtimeRequestReplacesComposerSkip({+ ...runtimeRequest("permission-1", "pending"),+ requestType: "permission",+ choices: [+ { key: "accept", label: "Allow once" },+ { key: "decline", label: "Deny" },+ ],+ }),+ ).toBe(true);+ });++ it("keeps Skip for runtime input without a negative choice", () => {+ expect(+ runtimeRequestReplacesComposerSkip(runtimeRequest("input-1", "pending")),+ ).toBe(false);+ });+});diff --git a/ui/src/components/task-chat/task-chat-model.ts b/ui/src/components/task-chat/task-chat-model.tsindex 3ab4a96c6b..3e8d577f8c 100644--- a/ui/src/components/task-chat/task-chat-model.ts+++ b/ui/src/components/task-chat/task-chat-model.ts@@ -12,21 +12,61 @@* inventory for the mapping. No timing/motion values live here — those are* CSS motion tokens in ui/src/index.css.*/-import type { IssueCommentMetadata, IssueCommentPresentation } from "@paperclipai/shared";+import type {+ IssueAttachment,+ IssueCommentMetadata,+ IssueCommentPresentation,+ IssueDocument,+ IssueDocumentSummary,+ IssueWorkProduct,+} from "@paperclipai/shared";+import type {+ PaperclipQuestionResponse,+ PaperclipQuestionSet,+} from "@paperclipai/adapter-utils";++export type { PaperclipQuestionResponse, PaperclipQuestionSet };++export type TaskChatProviderActivityFamily =+ | "plan"+ | "tool_execution"+ | "research"+ | "delegation"+ | "model_identity"+ | "context"+ | "artifact"+ | "review"+ | "hook"+ | "memory"+ | "safety"+ | "terminal"+ | "wait"+ | "provider_notice";++export type TaskChatProviderActivityStatus =+ "running" | "completed" | "failed" | "interrupted" | "informational";++export interface TaskChatWorkspaceChangeFile {+ path: string;+ operation: "create" | "modify" | "delete" | "rename" | "mode_change";+ previousPath: string | null;+ additions: number | null;+ deletions: number | null;+ binary: boolean;+ diff: string | null;+}import type { IssueThreadInteraction } from "@/lib/issue-thread-interactions";/** Who authored a thread row — the primary legibility signal. */export type TaskChatAuthorKind = "human" | "agent" | "system";/** ACP ToolCallStatus. */-export type TaskChatToolStatus = "pending" | "in_progress" | "completed" | "failed";+export type TaskChatToolStatus =+ "pending" | "in_progress" | "completed" | "failed" | "interrupted";/** ACP PermissionOptionKind. */export type TaskChatApprovalOptionKind =- | "allow_once"- | "allow_always"- | "reject_once"- | "reject_always";+ "allow_once" | "allow_always" | "reject_once" | "reject_always";/** ACP PlanEntryStatus. */export type TaskChatPlanEntryStatus = "pending" | "in_progress" | "completed";@@ -74,6 +114,12 @@ export interface TaskChatMessageItem {optimistic?: "pending" | "queued";/** Live run this queued message is waiting behind. */queueTargetRunId?: string | null;+ /** Non-blocking verification limitations attached to the run's durable reply. */+ verificationCaveats?: Array<{+ commandOrCheck: string;+ reasonCode?: string | null;+ detail?: string | null;+ }>;/** Assigned agent icon name (AgentIconName) for the avatar header. */agentIcon?: string | null;/**@@ -82,16 +128,12 @@ export interface TaskChatMessageItem {* "for {user}" chip beside the author name (the open cross-task write design (attribution)).*/onBehalfOfUserName?: string;- /**- * Agent text streamed inside a run turn (interstitial updates between tool- * calls). Ephemeral in the redesigned view (PAP-361): while streaming it- * takes the live parent row's line (TaskChatStatusItem.selfTalk); once- * finished it renders nowhere — the run log / classic transcript remain the- * archive. Tagged for live and settled transcripts alike.- */+ /** A transient provider progress update, distinct from the durable final response. */interstitial?: boolean;/** Epoch ms of the message's first streamed chunk. */atMs?: number;+ /** Index of the latest transcript event folded into this logical block. */+ transcriptIndex?: number;/*** The settled run turn "attached" to this bubble (round 9): when the run's* final reply lands, the live parent row transforms into the "Worked · …"@@ -125,6 +167,10 @@ export interface TaskChatThinkingItem {summaryLabel?: string;/** Provider-emitted reasoning surface; never synthesized by the UI. */channel?: "summary" | "detail" | "unknown";+ /** A real provider reasoning lifecycle with no provider-authored text. */+ lifecycleOnly?: boolean;+ /** Index of the latest transcript event folded into this logical block. */+ transcriptIndex?: number;}/** A tool invocation row (ACP tool_call / tool_call_update). */@@ -211,7 +257,13 @@ export interface TaskChatActivityPhaseItem {/** Historical assistant update that introduced this phase. */interstitial?: TaskChatMessageItem;/** Chronological tool/usage rows owned exclusively by this phase. */- items: Array<TaskChatToolItem | TaskChatUsageItem>;+ items: Array<+ | TaskChatToolItem+ | TaskChatUsageItem+ | TaskChatThinkingItem+ | TaskChatMarkerItem+ | TaskChatProtocolItem+ >;/** Deterministic, taxonomy-based summary (for example "Read 3 files, ran 1 command"). */summary: string;/** The tail phase of an in-flight run stays foregrounded. */@@ -242,6 +294,171 @@ export interface TaskChatInteractionItem {interaction: IssueThreadInteraction;}+/** A canonical, atomically saved Plan document interleaved into the thread. */+export interface TaskChatPlanDocumentItem {+ id: string;+ kind: "plan_document";+ document: IssueDocument;+}++export interface TaskChatProtocolDetail {+ label: string;+ value: string;+ mono?: boolean;+}++export interface TaskChatProtocolStep {+ id: string;+ label: string;+ status: "pending" | "in_progress" | "completed" | "blocked" | "failed";+}++export interface TaskChatProtocolLink {+ label: string;+ href: string;+ description?: string;+}++export interface TaskChatProtocolChild {+ id: string;+ title: string;+ status: string;+ metadata?: string;+ summary?: string;+}++export interface TaskChatProviderActivityItem {+ id: string;+ kind: "protocol";+ surface: "provider_activity";+ family: TaskChatProviderActivityFamily;+ eventType: string;+ status: TaskChatProviderActivityStatus;+ title: string;+ summary?: string;+ details: TaskChatProtocolDetail[];+ steps: TaskChatProtocolStep[];+ links: TaskChatProtocolLink[];+ children: TaskChatProtocolChild[];+ output?: string;+ outputTruncated?: boolean;+ /** Index of the latest provider event coalesced into this activity. */+ transcriptIndex?: number;+}++export interface TaskChatWorkspaceChangeItem {+ id: string;+ kind: "protocol";+ surface: "workspace_change";+ changeSetId: string;+ revision: number;+ source: "harness_reported" | "runner_verified";+ complete: boolean;+ files: TaskChatWorkspaceChangeFile[];+ totals: { files: number; additions: number | null; deletions: number | null };+ patchArtifactRef: string | null;+}++export interface TaskChatWorkspaceFileItem {+ id: string;+ kind: "protocol";+ surface: "workspace_file";+ referenceId: string;+ source: "harness_reported" | "runner_verified";+ path: string;+ displayName: string;+ mediaType: string | null;+ presentation: "document" | "code" | "image" | "generic";+ line: number | null;+ preview: string | null;+ previewTruncated: boolean;+}++export interface TaskChatRuntimeRequestItem {+ id: string;+ kind: "protocol";+ surface: "runtime_request";+ runId: string;+ requestId: string;+ requestKind:+ | "runtime"+ | "command_approval"+ | "file_approval"+ | "permission_approval"+ | "user_input"+ | "elicitation"+ | null;+ turnId: string | null;+ requestType: "permission" | "input";+ status: "pending" | "resolved" | "expired" | "cancelled";+ prompt: string;+ choices: Array<{ key: string; label: string }>;+ fields: Array<{ name: string; label: string; placeholder: string | null }>;+ questionSet?: PaperclipQuestionSet | null;+ resolvedAction?: string | null;+ response?: PaperclipQuestionResponse | null;+}++export type TaskChatRuntimeRequestDecision =+ | { action: "accept" | "accept_for_session" | "decline" | "cancel" }+ | { action: "submit"; values: Record<string, string> }+ | { action: "submit"; response: PaperclipQuestionResponse };++export interface TaskChatRunResultItem {+ id: string;+ kind: "protocol";+ surface: "run_result";+ disposition: "done" | "blocked" | "needs_review" | "yielded";+ summary: string;+ objectiveSatisfied: boolean | null;+ verification: Array<{+ commandOrCheck: string;+ status: "passed" | "failed" | "not_run";+ detail?: string;+ artifactRef?: string;+ }>;+ remainingWork: Array<{ description: string; blocksCompletion: boolean }>;+ blocker: {+ reasonCode: string;+ unblockAction: string;+ scope: "current_track" | "task_wide";+ } | null;+ artifacts: Array<{ kind: string; ref: string; title?: string }>;+}++export interface TaskChatRunTerminalItem {+ id: string;+ kind: "protocol";+ surface: "run_terminal";+ turnState: "completed" | "failed" | "interrupted" | "cancelled";+ runState: "succeeded" | "failed" | "cancelled";+ disposition: "done" | "blocked" | "needs_review" | "yielded";+ stopReason?: string;+}++export interface TaskChatMaterializedResourceItem {+ id: string;+ kind: "protocol";+ surface: "resource";+ resourceKind: "document" | "deliverable" | "attachment";+ title: string;+ subtitle: string;+ href: string | null;+ timestamp?: string;+ document?: IssueDocumentSummary;+ workProduct?: IssueWorkProduct;+ attachment?: IssueAttachment;+}++export type TaskChatProtocolItem =+ | TaskChatProviderActivityItem+ | TaskChatWorkspaceChangeItem+ | TaskChatWorkspaceFileItem+ | TaskChatRuntimeRequestItem+ | TaskChatRunResultItem+ | TaskChatRunTerminalItem+ | TaskChatMaterializedResourceItem;+/** Items a turn can group — everything except another turn. */export type TaskChatTurnChildItem =| TaskChatMessageItem@@ -250,7 +467,9 @@ export type TaskChatTurnChildItem =| TaskChatStatusItem| TaskChatMarkerItem| TaskChatUsageItem- | TaskChatActivityPhaseItem;+ | TaskChatActivityPhaseItem+ | TaskChatPlanDocumentItem+ | TaskChatProtocolItem;/*** One agent turn's activity (thinking/tools/diffs) grouped so a finished turn@@ -267,6 +486,9 @@ export interface TaskChatTurnItem {kind: "turn";items: TaskChatTurnChildItem[];settled: boolean;+ /** Agent identity retained when a live runner turn becomes durable history. */+ agentName?: string;+ agentIcon?: string | null;/*** The in-flight run's status line, hoisted to be THE turn's single visible* row while collapsed (PAP-354 parent-row model). Absent once settled.@@ -274,6 +496,10 @@ export interface TaskChatTurnItem {liveStatus?: TaskChatStatusItem;/** Animate the fold when settling (false = collapse instantly, e.g. history). */animateFold?: boolean;+ /** New-runner turns keep Worked/Stopped fixed above their ordered timeline. */+ standaloneHeader?: boolean;+ /** Durable response shown after the ordered Paperclip Runner timeline. */+ finalResponse?: TaskChatMessageItem;summary: {/** e.g. "38s" — omitted when unknown. */durationLabel?: string;@@ -296,8 +522,61 @@ export type TaskChatItem =| TaskChatUsageItem| TaskChatActivityPhaseItem| TaskChatInteractionItem+ | TaskChatPlanDocumentItem| TaskChatTurnItem- | TaskChatBriefItem;+ | TaskChatBriefItem+ | TaskChatProtocolItem;++/** Latest lifecycle state wins for each request; terminal entries suppress stale pending cards. */+export function latestPendingRuntimeRequest(+ items: readonly TaskChatItem[],+): TaskChatRuntimeRequestItem | null {+ const seen = new Set<string>();+ for (let index = items.length - 1; index >= 0; index -= 1) {+ const item = items[index];+ if (item.kind !== "protocol" || item.surface !== "runtime_request")+ continue;+ const key = `${item.runId}:${item.requestId}`;+ if (seen.has(key)) continue;+ seen.add(key);+ if (item.status === "pending") return item;+ }+ return null;+}++/** A protocol denial is the explicit negative path, so a second Skip action is redundant. */+export function runtimeRequestReplacesComposerSkip(+ item: TaskChatRuntimeRequestItem,+): boolean {+ return item.choices.some((choice) => {+ const key = choice.key.trim().toLowerCase();+ const label = choice.label.trim().toLowerCase();+ return (+ ["deny", "decline", "reject"].includes(key) ||+ /^(deny|decline|reject)(\b|\s)/.test(label)+ );+ });+}++/** One latest lifecycle entry per request, in the order each request began. */+export function latestRuntimeRequests(+ items: readonly TaskChatItem[],+): TaskChatRuntimeRequestItem[] {+ const latest = new Map<+ string,+ { order: number; item: TaskChatRuntimeRequestItem }+ >();+ for (const [order, item] of items.entries()) {+ if (item.kind !== "protocol" || item.surface !== "runtime_request")+ continue;+ const key = `${item.runId}:${item.requestId}`;+ const existing = latest.get(key);+ latest.set(key, { order: existing?.order ?? order, item });+ }+ return [...latest.values()]+ .sort((left, right) => left.order - right.order)+ .map(({ item }) => item);+}/** A structured plan entry (ACP PlanEntry) for the Plans tab. */export interface TaskChatPlanEntry {diff --git a/ui/src/components/task-chat/task-chat-states.ts b/ui/src/components/task-chat/task-chat-states.tsindex 9f109ce45c..ed512ac49c 100644--- a/ui/src/components/task-chat/task-chat-states.ts+++ b/ui/src/components/task-chat/task-chat-states.ts@@ -64,10 +64,10 @@ export const TASK_CHAT_STATE_META: Record<TaskChatStateId, TaskChatStateMeta> =},"agent-message": {id: "agent-message",- label: "Agent message",+ label: "Final response",tier: "live",surface: "thread",- protocol: "text_delta stream:output (ACP agent_message_chunk)",+ protocol: 'PRP item.delta kind:"agentMessage" channel:"final"',},thinking: {id: "thinking",@@ -78,14 +78,14 @@ export const TASK_CHAT_STATE_META: Record<TaskChatStateId, TaskChatStateMeta> =},responding: {id: "responding",- label: "Responding (streaming)",+ label: "Progress update (streaming)",tier: "live",surface: "thread",- protocol: "text_delta stream:output, streaming",+ protocol: 'PRP item.delta kind:"agentMessage" channel:"progress"',},"responding-burst": {id: "responding-burst",- label: "Responding (update burst)",+ label: "Progress update burst",tier: "live",surface: "thread",protocol: "text_delta stream:output ×N, tool calls between (PAP-368 dwell)",diff --git a/ui/src/components/task-chat/task-protocol-surfaces.test.ts b/ui/src/components/task-chat/task-protocol-surfaces.test.tsnew file mode 100644index 0000000000..acc38d8106--- /dev/null+++ b/ui/src/components/task-chat/task-protocol-surfaces.test.ts@@ -0,0 +1,77 @@+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import {+ TASK_PROTOCOL_EVENT_SURFACE_REGISTRY,+ TASK_PROTOCOL_REQUEST_SURFACE_REGISTRY,+ TASK_PROTOCOL_RESULT_DISPOSITION_REGISTRY,+ TASK_PROTOCOL_RUN_TERMINAL_REGISTRY,+ TASK_PROTOCOL_TURN_TERMINAL_REGISTRY,+} from "./task-protocol-surfaces";++function schema(name: string): Record<string, unknown> {+ const path = fileURLToPath(new URL(`../../../../packages/paperclip-runner/protocol/schemas/${name}`, import.meta.url));+ return JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;+}++function record(value: unknown): Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value)+ ? value as Record<string, unknown>+ : {};+}++function enumStrings(value: unknown): string[] {+ return Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === "string") : [];+}++describe("Paperclip task protocol surface registry", () => {+ it("classifies every canonical event exactly once", () => {+ const eventSchema = schema("event.schema.json");+ const properties = record(eventSchema.properties);+ const eventType = record(properties.eventType);+ const canonical = enumStrings(eventType.enum).sort();+ const registered = Object.keys(TASK_PROTOCOL_EVENT_SURFACE_REGISTRY).sort();+ expect(registered).toEqual(canonical);+ });++ it("gives every inline event a Storybook verification surface", () => {+ for (const [eventType, registration] of Object.entries(TASK_PROTOCOL_EVENT_SURFACE_REGISTRY)) {+ if (registration.disposition !== "inline") continue;+ expect(registration.story, eventType).toMatch(/^Task Page\/Runner Protocol\//);+ }+ });++ it("classifies both runtime request types and all issue-thread request kinds", () => {+ const requestSchema = schema("request.schema.json");+ const alternatives = Array.isArray(requestSchema.oneOf) ? requestSchema.oneOf.map(record) : [];+ const runtimeProperties = alternatives+ .filter((candidate) => record(record(candidate.properties).requestKind).const === "runtime")+ .map((candidate) => record(candidate.properties));+ const issueProperties = record(alternatives.find((candidate) => record(record(candidate.properties).requestKind).const === "issue_thread")?.properties);+ const expected = [...new Set([+ ...runtimeProperties.flatMap((properties) => {+ const type = record(properties.type);+ const kinds = typeof type.const === "string" ? [type.const] : enumStrings(type.enum);+ return kinds.map((kind) => `runtime.${kind}`);+ }),+ ...enumStrings(record(issueProperties.kind).enum).map((kind) => `issue_thread.${kind}`),+ ])].sort();+ expect(Object.keys(TASK_PROTOCOL_REQUEST_SURFACE_REGISTRY).sort()).toEqual(expected);+ });++ it("covers result dispositions and both terminal state axes", () => {+ const resultSchema = schema("result.schema.json");+ const terminalSchema = schema("terminal.schema.json");+ const resultProperties = record(resultSchema.properties);+ const terminalProperties = record(terminalSchema.properties);+ expect(Object.keys(TASK_PROTOCOL_RESULT_DISPOSITION_REGISTRY).sort()).toEqual(+ enumStrings(record(resultProperties.reportedWorkDisposition).enum).sort(),+ );+ expect(Object.keys(TASK_PROTOCOL_TURN_TERMINAL_REGISTRY).sort()).toEqual(+ enumStrings(record(terminalProperties.turnTerminalState).enum).sort(),+ );+ expect(Object.keys(TASK_PROTOCOL_RUN_TERMINAL_REGISTRY).sort()).toEqual(+ enumStrings(record(terminalProperties.runTerminalState).enum).sort(),+ );+ });+});diff --git a/ui/src/components/task-chat/task-protocol-surfaces.ts b/ui/src/components/task-chat/task-protocol-surfaces.tsnew file mode 100644index 0000000000..138aa08588--- /dev/null+++ b/ui/src/components/task-chat/task-protocol-surfaces.ts@@ -0,0 +1,143 @@+/**+ * Exhaustive product disposition for Paperclip Runner Protocol surfaces.+ *+ * This is intentionally separate from the renderer: adding a protocol event+ * must be a conscious product decision even when the decision is to fold it+ * into an existing turn or keep it in DevTools. The contract test compares+ * these keys with the canonical JSON schemas.+ */+export type TaskProtocolDisposition = "inline" | "folded" | "debug-only";++export interface TaskProtocolSurfaceRegistration {+ disposition: TaskProtocolDisposition;+ surface: string;+ story: string | null;+ rationale: string;+}++const inline = (surface: string, story: string, rationale: string): TaskProtocolSurfaceRegistration => ({+ disposition: "inline",+ surface,+ story,+ rationale,+});++const folded = (surface: string, rationale: string): TaskProtocolSurfaceRegistration => ({+ disposition: "folded",+ surface,+ story: null,+ rationale,+});++const debugOnly = (surface: string, rationale: string): TaskProtocolSurfaceRegistration => ({+ disposition: "debug-only",+ surface,+ story: null,+ rationale,+});++const providerEvents = [+ "plan.updated",+ "tool.execution.started", "tool.execution.progressed", "tool.execution.completed",+ "research.started", "research.progressed", "research.completed",+ "delegation.started", "delegation.updated", "delegation.completed",+ "model.route.changed", "model.verification.updated", "context.compacted",+ "artifact.viewed", "artifact.generated", "review.mode.changed",+ "hook.started", "hook.completed", "memory.citation.referenced",+ "safety.review.started", "safety.review.completed", "terminal.input.sent",+ "wait.started", "wait.completed", "provider.notice.recorded",+] as const;++const runnerLifecycleEvents = [+ "runner.connected", "runner.reconnected", "runner.reconciled", "runner.disconnected",+ "runner.draining", "runner.backpressure", "runner.suspending", "runner.suspended", "runner.stopped",+ "runtime.phase.changed", "workspace.ready",+ "harness.starting", "harness.ready", "harness.exited",+ "session.starting", "session.started", "session.resuming", "session.resumed",+ "session.reconciled", "session.updated", "session.closed",+ "turn.submitted", "turn.accepted", "turn.started", "turn.completed",+ "run.attached", "run.detached",+] as const;++const diagnosticEvents = [+ "runner.diagnostic", "harness.diagnostic", "session.failed", "turn.failed",+ "turn.interrupted", "turn.cancelled", "item.failed",+] as const;++const itemEvents = ["item.started", "item.delta", "item.completed", "usage.reported"] as const;++const mcpLifecycleEvents = [+ "mcp_app.discovered", "mcp_app.resource.resolved", "mcp_app.initializing", "mcp_app.ready",+ "mcp_app.host_context.changed", "mcp_app.failed", "mcp_app.teardown",+] as const;++const interactionLifecycleEvents = [+ "interaction.request.proposed", "interaction.request.materialized", "interaction.request.rejected",+ "interaction.response.progressed", "interaction.response.resolved", "interaction.response.delivered",+] as const;++const governanceEvents = [+ "attention.request.proposed", "attention.request.routed", "attention.request.resolved",+ "attention.request.expired", "attention.request.superseded", "work.assessment.recorded",+ "issue.status.decision.recorded", "issue.status.decision.applied", "issue.status.decision.rejected",+ "issue.status.decision.superseded",+] as const;++export const TASK_PROTOCOL_EVENT_SURFACE_REGISTRY: Readonly<Record<string, TaskProtocolSurfaceRegistration>> = Object.freeze({+ ...Object.fromEntries(providerEvents.map((eventType) => [eventType, inline("provider_activity", "Task Page/Runner Protocol/Provider semantics", "Provider-neutral semantic activity is readable in the task turn.")])),+ "workspace.change.updated": inline("workspace_change", "Task Page/Runner Protocol/Workspace changes", "In-progress workspace changes update one diff card."),+ "workspace.diff.recorded": inline("workspace_change", "Task Page/Runner Protocol/Workspace changes", "The runner-verified final diff replaces the in-progress revision."),+ "workspace.file.referenced": inline("workspace_file", "Task Page/Runner Protocol/File references", "Verified references open a bounded preview and the production file viewer."),+ "semantic_tool.input": folded("tool", "Semantic operations reuse the production tool row."),+ "semantic_tool.result": folded("tool", "Semantic operation outcomes update the matching tool row."),+ "semantic_tool.reconciled": folded("tool", "Recovered semantic operation outcomes update the matching tool row without duplicating it."),+ "mcp_app.tool_input": folded("tool", "MCP inputs reuse the production tool row."),+ "mcp_app.tool_result": folded("tool", "MCP outcomes update the matching tool row."),+ "mcp_app.action.requested": folded("interaction", "Action requests materialize as authoritative issue-thread interactions."),+ "mcp_app.action.resolved": folded("interaction", "Action resolution is shown on the authoritative interaction card."),+ "runtime_request.created": inline("runtime_request", "Task Page/Runner Protocol/Runtime requests", "Pending provider runtime requests remain visible and actionable when a resolver is available."),+ "runtime_request.resolved": folded("runtime_request", "Resolution updates the existing request card."),+ "runtime_request.expired": folded("runtime_request", "Expiry updates the existing request card."),+ "runtime_request.cancelled": folded("runtime_request", "Cancellation updates the existing request card."),+ ...Object.fromEntries(interactionLifecycleEvents.map((eventType) => [eventType, folded("interaction", "The control-plane interaction record is canonical and owns rendering." )])),+ "run.result.proposed": inline("run_result", "Task Page/Runner Protocol/Results and terminal states", "Structured completion, evidence, verification, blockers, and artifacts remain inspectable."),+ "run.result.accepted": folded("run_result", "Acceptance updates the existing result without duplicating it."),+ "run.result.rejected": folded("run_result", "Rejected results remain part of run governance rather than a second completion card."),+ "run.terminal": inline("run_terminal", "Task Page/Runner Protocol/Results and terminal states", "Terminal outcome and stop reason remain visible."),+ ...Object.fromEntries(runnerLifecycleEvents.map((eventType) => [eventType, folded("turn", "Routine lifecycle transitions are summarized by the run turn and composer state.")])),+ ...Object.fromEntries(diagnosticEvents.map((eventType) => [eventType, folded("system_notice", "Actionable failure text is folded into the run or system notice.")])),+ ...Object.fromEntries(itemEvents.map((eventType) => [eventType, folded("conversation_or_tool", "Item payloads normalize into messages, reasoning, tools, diffs, or usage." )])),+ "sandbox.metric": debugOnly("run_debug", "Sandbox telemetry is available in run details, not the primary task thread."),+ ...Object.fromEntries(mcpLifecycleEvents.map((eventType) => [eventType, debugOnly("run_debug", "MCP application transport lifecycle remains in run details unless it produces an actionable failure.")])),+ ...Object.fromEntries(governanceEvents.map((eventType) => [eventType, folded("governance", "Authoritative task status, attention, and interaction records own this state." )])),+});++export const TASK_PROTOCOL_REQUEST_SURFACE_REGISTRY = Object.freeze({+ "runtime.permission": inline("runtime_request", "Task Page/Runner Protocol/Runtime requests", "Permission choices render on the runtime request card."),+ "runtime.input": inline("runtime_request", "Task Page/Runner Protocol/Runtime requests", "Structured runtime input renders on the runtime request card."),+ "issue_thread.request_confirmation": inline("interaction", "Task Page/Runner Protocol/Interactions", "Uses the production confirmation card."),+ "issue_thread.request_checkbox_confirmation": inline("interaction", "Task Page/Runner Protocol/Interactions", "Uses the production bounded checkbox card."),+ "issue_thread.request_item_verdicts": inline("interaction", "Task Page/Runner Protocol/Interactions", "Uses the production per-item verdict card."),+ "issue_thread.ask_user_questions": inline("interaction", "Task Page/Runner Protocol/Interactions", "Uses the production typed question controls."),+ "issue_thread.suggest_tasks": inline("interaction", "Task Page/Runner Protocol/Interactions", "Uses the production task suggestion tree."),+});++export const TASK_PROTOCOL_RESULT_DISPOSITION_REGISTRY = Object.freeze({+ done: "run_result",+ blocked: "run_result",+ needs_review: "run_result",+ yielded: "run_result",+} as const);++export const TASK_PROTOCOL_TURN_TERMINAL_REGISTRY = Object.freeze({+ completed: "run_terminal",+ failed: "run_terminal",+ interrupted: "run_terminal",+ cancelled: "run_terminal",+} as const);++export const TASK_PROTOCOL_RUN_TERMINAL_REGISTRY = Object.freeze({+ succeeded: "run_terminal",+ failed: "run_terminal",+ cancelled: "run_terminal",+} as const);diff --git a/ui/src/components/task-chat/tool-taxonomy.test.ts b/ui/src/components/task-chat/tool-taxonomy.test.tsindex 0758e1986f..438ec0640e 100644--- a/ui/src/components/task-chat/tool-taxonomy.test.ts+++ b/ui/src/components/task-chat/tool-taxonomy.test.ts@@ -3,6 +3,8 @@ import {BookOpen,Brain,ChevronsLeftRightEllipsis,+ CircleHelp,+ FilePenLine,MessageSquareReply,Network,Search,@@ -11,129 +13,143 @@ import {Wrench,} from "lucide-react";import { McpIcon } from "./McpIcon";-import { isGenericToolName, mcpToolSegment, statusLabelIcon, toolTaxonomy } from "./tool-taxonomy";--describe("toolTaxonomy", () => {- it("maps each family to its icon and verb", () => {- expect(toolTaxonomy("Bash")).toEqual({- family: "terminal",- icon: Terminal,- verbLabel: "Running a command",- });- expect(toolTaxonomy("Shell").family).toBe("terminal");-- expect(toolTaxonomy("Grep")).toEqual({- family: "grep",- icon: SearchCode,- verbLabel: "Grepping",- });-- expect(toolTaxonomy("Glob")).toEqual({- family: "search",- icon: Search,- verbLabel: "Searching",- });- expect(toolTaxonomy("WebSearch").family).toBe("search");-- expect(toolTaxonomy("Read")).toEqual({- family: "read",- icon: BookOpen,- verbLabel: "Reading files",- });- expect(toolTaxonomy("NotebookRead").family).toBe("read");+import {+ humanizeToolName,+ isGenericToolName,+ mcpToolIdentity,+ mcpToolSegment,+ statusLabelIcon,+ toolActivityPresentation,+ toolTaxonomy,+} from "./tool-taxonomy";++describe("tool activity vocabulary", () => {+ it("maps Claude, Codex, and Pi built-ins to action-specific copy and icons", () => {+ expect(toolTaxonomy("Bash")).toEqual({ family: "terminal", icon: Terminal, verbLabel: "Running a command" });+ expect(toolTaxonomy("exec_command")).toEqual({ family: "terminal", icon: Terminal, verbLabel: "Running a command" });+ expect(toolTaxonomy("Grep")).toEqual({ family: "grep", icon: SearchCode, verbLabel: "Searching file contents" });+ expect(toolTaxonomy("Glob")).toEqual({ family: "search", icon: Search, verbLabel: "Searching files" });+ expect(toolTaxonomy("Read")).toEqual({ family: "read", icon: BookOpen, verbLabel: "Reading a file" });+ expect(toolTaxonomy("NotebookEdit")).toEqual({ family: "edit", icon: FilePenLine, verbLabel: "Editing a notebook" });+ expect(toolTaxonomy("WebFetch")).toEqual({ family: "web", icon: ChevronsLeftRightEllipsis, verbLabel: "Fetching a web page" });+ expect(toolTaxonomy("Agent")).toEqual({ family: "agent", icon: Network, verbLabel: "Starting a subagent" });+ expect(toolTaxonomy("AskUserQuestion")).toEqual({ family: "question", icon: CircleHelp, verbLabel: "Requesting input" });+ });- // Round-4 board feedback: edits share the terminal glyph.- expect(toolTaxonomy("Edit")).toEqual({- family: "edit",- icon: Terminal,- verbLabel: "Editing files",+ it("normalizes camel, Pascal, snake, kebab, dotted, and both MCP formats", () => {+ for (const name of ["searchIssues", "SearchIssues", "search_issues", "search-issues", "search.issues"]) {+ expect(toolActivityPresentation({ name }).runningLabel).toBe("Searching issues");+ }+ expect(mcpToolIdentity("mcp__linear-server__search_issues")).toEqual({ namespace: "linear-server", name: "search_issues" });+ expect(mcpToolIdentity("mcp.linear-server.search_issues")).toEqual({ namespace: "linear-server", name: "search_issues" });+ expect(mcpToolSegment("mcp__linear-server__search_issues")).toBe("Search issues");+ expect(mcpToolSegment("mcp.linear-server.search_issues")).toBe("Search issues");+ const mcp = toolActivityPresentation({ name: "mcp.paperclip.search_tasks" });+ expect(mcp).toMatchObject({+ family: "mcp",+ icon: McpIcon,+ runningLabel: "Searching tasks",+ completedLabel: "Searched tasks",+ sourceLabel: "Paperclip",+ confidence: "exact",});- expect(toolTaxonomy("Write").family).toBe("edit");- expect(toolTaxonomy("MultiEdit").family).toBe("edit");- expect(toolTaxonomy("NotebookEdit").family).toBe("edit");+ });- expect(toolTaxonomy("WebFetch")).toEqual({- family: "web",- icon: ChevronsLeftRightEllipsis,- verbLabel: "Fetching the web",- });+ it("covers every ACP kind before falling back to a future extension name", () => {+ const expected: Record<string, string> = {+ read: "Reading data",+ edit: "Updating data",+ delete: "Deleting an item",+ move: "Moving an item",+ search: "Searching",+ execute: "Running a command",+ think: "Thinking",+ fetch: "Fetching data",+ switch_mode: "Switching mode",+ other: "Running Custom extension",+ };+ for (const [operation, runningLabel] of Object.entries(expected)) {+ expect(toolActivityPresentation({ name: "custom_extension", operation }).runningLabel).toBe(runningLabel);+ }+ expect(toolActivityPresentation({ name: "Read file '/tmp/private.json'", operation: "read" }).runningLabel).toBe("Reading data");+ });- expect(toolTaxonomy("Task")).toEqual({- family: "agent",- icon: Network,- verbLabel: "Delegating",- });- expect(toolTaxonomy("Agent").family).toBe("agent");+ it("covers every normalized verb-prefix family", () => {+ const cases: Array<[string, string]> = [+ ["get_record", "Reading record"], ["list_records", "Listing records"],+ ["lookup_record", "Searching record"], ["fetch_record", "Fetching record"],+ ["open_record", "Opening record"], ["patch_record", "Updating record"],+ ["register_record", "Creating record"], ["remove_record", "Deleting record"],+ ["rename_record", "Moving record"], ["execute_record", "Running a command"],+ ["prompt_user", "Requesting user"], ["comment_record", "Posting record"],+ ["delegate_record", "Starting record"], ["interrupt_record", "Stopping record"],+ ["poll_record", "Waiting"], ["complete_record", "Reporting completion"],+ ["block_record", "Reporting a blocker"],+ ];+ for (const [name, runningLabel] of cases) {+ expect(toolActivityPresentation({ name }).runningLabel).toBe(runningLabel);+ }});- it("collapses mcp__ names to the MCP logo with the tool segment verb", () => {- const entry = toolTaxonomy("mcp__linear-server__search_issues");- expect(entry.family).toBe("mcp");- expect(entry.icon).toBe(McpIcon);- expect(entry.verbLabel).toBe("Using Search_issues");+ it("gives anticipated provider tools and Paperclip operations purpose-specific labels", () => {+ const anticipated = [+ "ToolSearch", "NotebookRead", "NotebookEdit", "TaskOutput", "TaskStop", "SendMessage",+ "EnterPlanMode", "ExitPlanMode", "LSP", "TodoWrite", "ReportFindings", "Skill",+ "view_image", "Image generation", "Compact conversation", "Guardian Review",+ "apply_patch", "multi_tool_use.parallel", "wait_agent", "interrupt_agent",+ ];+ const paperclip = [+ "get_task_context", "get_task_history", "list_documents", "read_document", "list_document_revisions",+ "report_progress", "answer_status_question", "write_document", "request_human_input",+ "register_deliverable", "finish_task", "paperclip_finish", "block_task", "paperclip_block",+ "request_review", "list_agents", "get_agent", "search_tasks", "list_approvals", "get_approval",+ "get_approval_context", "get_workspace_runtime", "control_workspace_service", "set_dependencies",+ "create_task", "request_approval", "decide_approval", "comment_on_approval", "schedule_wake",+ "generic_api_request",+ ];+ for (const name of [...anticipated, ...paperclip]) {+ const presentation = toolActivityPresentation({ name, namespace: paperclip.includes(name) ? "paperclip" : undefined });+ expect(presentation.confidence, name).toBe("exact");+ expect(presentation.runningLabel, name).not.toMatch(/running a tool|tool call/i);+ expect(presentation.completedLabel, name).not.toMatch(/ran a tool|tool call/i);+ }+ expect(toolActivityPresentation({ name: "report_progress", namespace: "paperclip" }).runningLabel).toBe("Reporting progress");+ expect(toolActivityPresentation({ name: "paperclip_block", namespace: "paperclip" }).completedLabel).toBe("Reported a blocker");+ expect(toolActivityPresentation({ name: "schedule_wake", namespace: "paperclip" }).runningLabel).toBe("Scheduling a wake-up");});- it("falls back to the Wrench for unknown or empty names", () => {- expect(toolTaxonomy("SomethingNovel")).toEqual({- family: "other",+ it("humanizes unknown named extensions and reserves the unnamed copy for missing identity", () => {+ expect(toolActivityPresentation({ name: "CustomExtension" })).toMatchObject({icon: Wrench,- verbLabel: "Working",+ runningLabel: "Running Custom extension",+ completedLabel: "Ran Custom extension",+ displayName: "Custom extension",+ confidence: "fallback",});- expect(toolTaxonomy("")).toEqual({ family: "other", icon: Wrench, verbLabel: "Working" });- expect(toolTaxonomy(undefined).icon).toBe(Wrench);- expect(toolTaxonomy(null).icon).toBe(Wrench);- });-});--describe("toolTaxonomy multi-word ACP titles", () => {- it("classifies by the first word", () => {- expect(toolTaxonomy("Read File").icon).toBe(BookOpen);- expect(toolTaxonomy("Edit File").icon).toBe(Terminal);- expect(toolTaxonomy("Write File").icon).toBe(Terminal);- expect(toolTaxonomy("Terminal").icon).toBe(Terminal);+ for (const name of ["", undefined, null, "tool call"]) {+ expect(toolActivityPresentation({ name })).toMatchObject({+ runningLabel: "Running an unnamed tool",+ completedLabel: "Ran an unnamed tool",+ confidence: "unnamed",+ });+ }+ expect(humanizeToolName("someFuture-extension.v2")).toBe("Some future extension v2");});});-describe("statusLabelIcon", () => {- it("gives the tool-free informative statuses their glyphs", () => {+describe("status and placeholder helpers", () => {+ it("gives tool-free informative statuses their glyphs", () => {expect(statusLabelIcon("Thinking")).toBe(Brain);expect(statusLabelIcon("Responding")).toBe(MessageSquareReply);expect(statusLabelIcon("Responding (streaming)")).toBe(MessageSquareReply);+ expect(statusLabelIcon("Working")).toBeNull();});- it("leaves whimsified and generic labels glyph-free", () => {- for (const label of ["Running", "Working", "Clipping", "Brewing", "Queued", "", undefined, null]) {- expect(statusLabelIcon(label)).toBeNull();+ it("recognizes ACPX placeholders but keeps real names", () => {+ for (const name of ["tool call", "tool call (completed)", "Tool Call (failed)", "acp_tool", "tool", ""]) {+ expect(isGenericToolName(name)).toBe(true);}- });-});--describe("isGenericToolName", () => {- it("flags acpx placeholder names, including status-suffixed variants", () => {- expect(isGenericToolName("tool call")).toBe(true);- expect(isGenericToolName("tool call (completed)")).toBe(true);- expect(isGenericToolName("Tool Call (failed)")).toBe(true);- expect(isGenericToolName("acp_tool")).toBe(true);- expect(isGenericToolName("tool")).toBe(true);- expect(isGenericToolName("")).toBe(true);- expect(isGenericToolName(undefined)).toBe(true);- });-- it("keeps real names", () => {expect(isGenericToolName("Terminal")).toBe(false);- expect(isGenericToolName("Read")).toBe(false);expect(isGenericToolName("mcp__linear__search_issues")).toBe(false);});});--describe("mcpToolSegment", () => {- it("extracts and capitalizes the tool segment", () => {- expect(mcpToolSegment("mcp__linear-server__search_issues")).toBe("Search_issues");- expect(mcpToolSegment("mcp__gh__create_pr")).toBe("Create_pr");- });-- it("returns null for non-mcp names", () => {- expect(mcpToolSegment("Bash")).toBeNull();- expect(mcpToolSegment("mcpish")).toBeNull();- });-});diff --git a/ui/src/components/task-chat/tool-taxonomy.ts b/ui/src/components/task-chat/tool-taxonomy.tsindex c9ee6579f7..41b2370cfd 100644--- a/ui/src/components/task-chat/tool-taxonomy.ts+++ b/ui/src/components/task-chat/tool-taxonomy.ts@@ -1,18 +1,22 @@/**- * Shared tool taxonomy: raw ACP tool_call names ("Bash", "Grep",- * "mcp__<server>__<tool>", …) → { family, icon, verbLabel } so the live status- * pill, the chat tool rows, and the classic transcript all agree on which- * glyph and verb a tool gets. The Wrench is reserved for genuinely unknown- * tools.+ * Provider-neutral tool vocabulary shared by live status, transcript rows,+ * and canonical provider activity. Exact semantic tools get purpose-specific+ * copy; ACP kinds and normalized name prefixes cover future adapters.*/import {BookOpen,Brain,ChevronsLeftRightEllipsis,+ CircleHelp,+ Clock3,+ FilePenLine,+ Image,+ ListChecks,MessageSquareReply,Network,Search,SearchCode,+ ShieldCheck,Terminal,Wrench,} from "lucide-react";@@ -29,7 +33,12 @@ export type ToolFamily =| "read"| "edit"| "web"+ | "plan"+ | "question"| "agent"+ | "safety"+ | "image"+ | "wait"| "mcp"| "other";@@ -40,81 +49,387 @@ export interface ToolTaxonomyEntry {verbLabel: string;}-/**- * Placeholder names that carry no tool identity. acpx fills a tool_call_update- * whose ACP payload omits `title` with the literal "tool call", and older- * stored logs carry "tool call (completed)" / "acp_tool" variants — none of- * these should ever displace a real name like "Terminal" or "Read".- */+export type ToolClassificationConfidence = "exact" | "kind" | "inferred" | "fallback" | "unnamed";++export interface ToolActivityPresentationInput {+ name?: string | null;+ transport?: string | null;+ namespace?: string | null;+ /** ACP kind or canonical operation. */+ operation?: string | null;+ target?: string | null;+ progress?: string | null;+}++export interface ToolSummaryGroup {+ key: string;+ singular: string;+ plural: string;+}++export interface ToolActivityPresentation {+ icon: ToolIcon;+ family: ToolFamily;+ runningLabel: string;+ completedLabel: string;+ failedLabel: string;+ interruptedLabel: string;+ displayName: string;+ sourceLabel?: string;+ technicalName?: string;+ confidence: ToolClassificationConfidence;+ summaryGroup: ToolSummaryGroup;+}++/** ACPX's placeholder title must never displace real lifecycle identity. */const GENERIC_TOOL_NAMES = new Set(["tool", "tool call", "tool_call", "acp_tool"]);export function isGenericToolName(name: string | undefined | null): boolean {const raw = (name ?? "").trim().toLowerCase()- .replace(/\s*\((?:pending|in_progress|completed|failed|cancelled)\)$/, "");+ .replace(/\s*\((?:pending|in[_ -]?progress|completed|failed|cancelled|canceled)\)$/, "");return !raw || GENERIC_TOOL_NAMES.has(raw);}-/**- * Collapse an MCP tool name ("mcp__server__tool") to its tool segment,- * capitalized — the same rule toolDisplayName() applies. Returns null for- * non-MCP names.- */+interface McpIdentity {+ namespace: string;+ name: string;+}++export function mcpToolIdentity(name: string): McpIdentity | null {+ const doubleUnderscore = name.match(/^mcp__(.+?)__(.+)$/i);+ if (doubleUnderscore) return { namespace: doubleUnderscore[1], name: doubleUnderscore[2] };+ const dotted = name.match(/^mcp\.([^.]+)\.(.+)$/i);+ return dotted ? { namespace: dotted[1], name: dotted[2] } : null;+}++function identifierWords(value: string): string[] {+ return value+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")+ .replace(/[^A-Za-z0-9]+/g, " ")+ .trim()+ .toLowerCase()+ .split(/\s+/)+ .filter(Boolean);+}++function sentenceCase(words: readonly string[]): string {+ if (words.length === 0) return "";+ const text = words.map((word) => {+ if (["api", "id", "lsp", "mcp", "pr", "url"].includes(word)) return word.toUpperCase();+ return word;+ }).join(" ");+ return text.charAt(0).toUpperCase() + text.slice(1);+}++export function humanizeToolName(name: string | undefined | null): string {+ const raw = (name ?? "").trim();+ if (isGenericToolName(raw)) return "Unnamed tool";+ const mcp = mcpToolIdentity(raw);+ return sentenceCase(identifierWords(mcp?.name ?? raw));+}++/** Humanized MCP tool segment for both mcp__server__tool and mcp.server.tool. */export function mcpToolSegment(name: string): string | null {- const mcp = name.match(/^mcp__[^_]+(?:_[^_]+)*__(.+)$/);- if (!mcp) return null;- const base = mcp[1];- return base.charAt(0).toUpperCase() + base.slice(1);-}--const FAMILY_META: Record<Exclude<ToolFamily, "mcp">, Omit<ToolTaxonomyEntry, "family">> = {- terminal: { icon: Terminal, verbLabel: "Running a command" },- grep: { icon: SearchCode, verbLabel: "Grepping" },- search: { icon: Search, verbLabel: "Searching" },- read: { icon: BookOpen, verbLabel: "Reading files" },- // Board round-4 feedback asked for the terminal glyph on edits as well.- edit: { icon: Terminal, verbLabel: "Editing files" },- web: { icon: ChevronsLeftRightEllipsis, verbLabel: "Fetching the web" },- agent: { icon: Network, verbLabel: "Delegating" },- other: { icon: Wrench, verbLabel: "Working" },+ const identity = mcpToolIdentity(name);+ return identity ? humanizeToolName(identity.name) : null;+}++type Action =+ | "read" | "list" | "search" | "fetch" | "open" | "update" | "create"+ | "delete" | "move" | "run" | "request" | "post" | "start" | "stop"+ | "wait" | "finish" | "block" | "think" | "switch" | "other";++interface ExactAction {+ action: Action;+ running?: string;+ completed?: string;+ group?: ToolSummaryGroup;+ family?: ToolFamily;+}++const group = (key: string, singular: string, plural: string): ToolSummaryGroup => ({ key, singular, plural });++const EXACT_ACTIONS: Record<string, ExactAction> = {+ bash: { action: "run" },+ terminal: { action: "run" },+ shell: { action: "run" },+ command: { action: "run" },+ run: { action: "run" },+ execute: { action: "run" },+ exec_command: { action: "run" },+ apply_patch: { action: "update", running: "Applying a patch", completed: "Applied a patch" },+ read: { action: "read", running: "Reading a file", completed: "Read a file" },+ write: { action: "update", running: "Writing a file", completed: "Wrote a file" },+ edit: { action: "update", running: "Editing a file", completed: "Edited a file" },+ notebook_read: { action: "read", running: "Reading a notebook", completed: "Read a notebook" },+ notebook_edit: { action: "update", running: "Editing a notebook", completed: "Edited a notebook" },+ glob: { action: "search", running: "Searching files", completed: "Searched files" },+ grep: { action: "search", running: "Searching file contents", completed: "Searched file contents", family: "grep" },+ tool_search: { action: "search", running: "Searching available tools", completed: "Searched available tools", group: group("tool_search", "tool search", "tool searches") },+ web_search: { action: "search", running: "Searching the web", completed: "Searched the web", family: "web" },+ web_fetch: { action: "fetch", running: "Fetching a web page", completed: "Fetched a web page", family: "web" },+ todo_write: { action: "update", running: "Updating the task list", completed: "Updated the task list", family: "plan", group: group("task_operation", "task operation", "task operations") },+ task_create: { action: "create", running: "Creating a task", completed: "Created a task", family: "plan", group: group("task_operation", "task operation", "task operations") },+ task_update: { action: "update", running: "Updating a task", completed: "Updated a task", family: "plan", group: group("task_operation", "task operation", "task operations") },+ task_list: { action: "list", running: "Listing tasks", completed: "Listed tasks", family: "plan", group: group("task_operation", "task operation", "task operations") },+ task_get: { action: "read", running: "Reading a task", completed: "Read a task", family: "plan", group: group("task_operation", "task operation", "task operations") },+ enter_plan_mode: { action: "switch", running: "Entering plan mode", completed: "Entered plan mode", family: "plan" },+ exit_plan_mode: { action: "switch", running: "Leaving plan mode", completed: "Left plan mode", family: "plan" },+ skill: { action: "read", running: "Loading a skill", completed: "Loaded a skill" },+ ask_user_question: { action: "request", running: "Requesting input", completed: "Requested input", family: "question" },+ request_human_input: { action: "request", running: "Requesting input", completed: "Requested input", family: "question", group: group("task_operation", "task operation", "task operations") },+ agent: { action: "start", running: "Starting a subagent", completed: "Started a subagent", family: "agent" },+ task: { action: "start", running: "Starting a subagent", completed: "Started a subagent", family: "agent" },+ task_output: { action: "read", running: "Checking subagent progress", completed: "Checked subagent progress", family: "agent" },+ task_stop: { action: "stop", running: "Stopping a subagent", completed: "Stopped a subagent", family: "agent" },+ send_message: { action: "post", running: "Messaging a subagent", completed: "Messaged a subagent", family: "agent" },+ spawn_agent: { action: "start", running: "Starting a subagent", completed: "Started a subagent", family: "agent" },+ wait_agent: { action: "wait", running: "Checking subagent progress", completed: "Checked subagent progress", family: "agent" },+ wait_threads: { action: "wait", running: "Checking task progress", completed: "Checked task progress", family: "agent" },+ interrupt_agent: { action: "stop", running: "Interrupting a subagent", completed: "Interrupted a subagent", family: "agent" },+ report_findings: { action: "post", running: "Reporting findings", completed: "Reported findings", family: "safety" },+ guardian_review: { action: "think", running: "Reviewing safety", completed: "Reviewed safety", family: "safety" },+ lsp: { action: "read", running: "Inspecting code intelligence", completed: "Inspected code intelligence" },+ compact_conversation: { action: "think", running: "Compacting context", completed: "Compacted context" },+ image_generation: { action: "create", running: "Generating an image", completed: "Generated an image", family: "image" },+ view_image: { action: "read", running: "Viewing an image", completed: "Viewed an image", family: "image" },+ multi_tool_use_parallel: { action: "run", running: "Running tools in parallel", completed: "Ran tools in parallel" },+ get_task_context: { action: "read", running: "Reading task context", completed: "Read task context" },+ get_task_history: { action: "read", running: "Reading task history", completed: "Read task history" },+ list_documents: { action: "list", running: "Listing documents", completed: "Listed documents" },+ read_document: { action: "read", running: "Reading a document", completed: "Read a document" },+ list_document_revisions: { action: "list", running: "Listing document revisions", completed: "Listed document revisions" },+ report_progress: { action: "post", running: "Reporting progress", completed: "Reported progress" },+ answer_status_question: { action: "post", running: "Answering a status question", completed: "Answered a status question" },+ write_document: { action: "update", running: "Writing a document", completed: "Wrote a document" },+ register_deliverable: { action: "create", running: "Registering a deliverable", completed: "Registered a deliverable" },+ finish_task: { action: "finish", running: "Reporting completion", completed: "Reported completion" },+ paperclip_finish: { action: "finish", running: "Reporting completion", completed: "Reported completion" },+ block_task: { action: "block", running: "Reporting a blocker", completed: "Reported a blocker" },+ paperclip_block: { action: "block", running: "Reporting a blocker", completed: "Reported a blocker" },+ request_review: { action: "request", running: "Requesting review", completed: "Requested review" },+ list_agents: { action: "list", running: "Listing agents", completed: "Listed agents" },+ get_agent: { action: "read", running: "Reading agent details", completed: "Read agent details" },+ search_tasks: { action: "search", running: "Searching tasks", completed: "Searched tasks" },+ list_approvals: { action: "list", running: "Listing approvals", completed: "Listed approvals" },+ get_approval: { action: "read", running: "Reading an approval", completed: "Read an approval" },+ get_approval_context: { action: "read", running: "Reading approval context", completed: "Read approval context" },+ get_workspace_runtime: { action: "read", running: "Reading workspace status", completed: "Read workspace status" },+ control_workspace_service: { action: "run", running: "Controlling a workspace service", completed: "Controlled a workspace service" },+ set_dependencies: { action: "update", running: "Updating task dependencies", completed: "Updated task dependencies" },+ create_task: { action: "create", running: "Creating a task", completed: "Created a task" },+ request_approval: { action: "request", running: "Requesting approval", completed: "Requested approval" },+ decide_approval: { action: "update", running: "Deciding an approval", completed: "Decided an approval" },+ comment_on_approval: { action: "post", running: "Commenting on an approval", completed: "Commented on an approval" },+ schedule_wake: { action: "create", running: "Scheduling a wake-up", completed: "Scheduled a wake-up", family: "wait" },+ generic_api_request: { action: "request", running: "Calling the Paperclip API", completed: "Called the Paperclip API" },};-function classify(n: string): Exclude<ToolFamily, "mcp"> {- // ACP titles are often multi-word ("Read File", "Edit File") — the first- // word carries the family.- const first = n.split(/[\s_:-]+/, 1)[0] ?? "";- if (first === "read" || n === "notebookread") return "read";- if (first === "edit" || first === "write" || n === "multiedit" || n === "notebookedit") {- return "edit";- }- if (first === "bash" || first === "shell" || first === "run" || n.includes("terminal")) {- return "terminal";+const ACTION_PREFIXES: Record<Action, readonly string[]> = {+ read: ["get", "read", "inspect", "view"],+ list: ["list", "glob"],+ search: ["find", "search", "grep", "query", "lookup"],+ fetch: ["fetch", "browse"],+ open: ["open"],+ update: ["write", "edit", "update", "set", "patch", "upsert", "sync"],+ create: ["create", "add", "register", "upload"],+ delete: ["delete", "remove"],+ move: ["move", "rename"],+ run: ["run", "execute", "bash", "shell", "command"],+ request: ["request", "ask", "prompt"],+ post: ["send", "message", "comment", "report", "answer"],+ start: ["start", "spawn", "delegate"],+ stop: ["stop", "cancel", "interrupt"],+ wait: ["wait", "sleep", "poll"],+ finish: ["finish", "complete"],+ block: ["block"],+ think: ["think", "reason", "compact", "review"],+ switch: ["switch", "enter", "exit"],+ other: [],+};++const OPERATION_ACTIONS: Record<string, Action> = {+ read: "read",+ edit: "update",+ delete: "delete",+ move: "move",+ search: "search",+ list: "list",+ execute: "run",+ think: "think",+ fetch: "fetch",+ switch_mode: "switch",+};++function normalizedKey(name: string): string {+ return identifierWords(name).join("_");+}++function inferredAction(words: readonly string[]): Action | null {+ const first = words[0];+ if (!first) return null;+ for (const [action, prefixes] of Object.entries(ACTION_PREFIXES) as Array<[Action, readonly string[]]>) {+ if (prefixes.includes(first)) return action;}- // Content grep is its own action (search-code glyph); file-name globbing and- // generic searches stay under the plain Search family.- if (first === "grep") return "grep";- if (first === "glob" || n.includes("search")) return "search";- if (n.includes("fetch") || n.includes("web") || n.includes("http")) return "web";- if (first === "task" || first === "agent") return "agent";+ return null;+}++function actionFamily(action: Action): ToolFamily {+ if (action === "run") return "terminal";+ if (action === "read" || action === "list") return "read";+ if (action === "search") return "search";+ if (action === "fetch" || action === "open") return "web";+ if (["update", "create", "delete", "move"].includes(action)) return "edit";+ if (action === "request") return "question";+ if (action === "start" || action === "stop") return "agent";+ if (action === "wait") return "wait";return "other";}-/** Map a raw tool name to its taxonomy entry; unknown/empty names → Wrench. */-export function toolTaxonomy(name: string | undefined | null): ToolTaxonomyEntry {- const raw = (name ?? "").trim();- if (!raw) return { family: "other", ...FAMILY_META.other };- const mcpTool = mcpToolSegment(raw);- if (mcpTool) return { family: "mcp", icon: McpIcon, verbLabel: `Using ${mcpTool}` };- const family = classify(raw.toLowerCase());- return { family, ...FAMILY_META[family] };+const FAMILY_ICONS: Record<ToolFamily, ToolIcon> = {+ terminal: Terminal,+ grep: SearchCode,+ search: Search,+ read: BookOpen,+ edit: FilePenLine,+ web: ChevronsLeftRightEllipsis,+ plan: ListChecks,+ question: CircleHelp,+ agent: Network,+ safety: ShieldCheck,+ image: Image,+ wait: Clock3,+ mcp: McpIcon,+ other: Wrench,+};++function actionCopy(action: Action, object: string | undefined): { running: string; completed: string } {+ const suffix = object ? ` ${object}` : "";+ switch (action) {+ case "read": return { running: `Reading${suffix || " data"}`, completed: `Read${suffix || " data"}` };+ case "list": return { running: `Listing${suffix || " items"}`, completed: `Listed${suffix || " items"}` };+ case "search": return { running: `Searching${suffix || ""}`, completed: `Searched${suffix || ""}` };+ case "fetch": return { running: `Fetching${suffix || " data"}`, completed: `Fetched${suffix || " data"}` };+ case "open": return { running: `Opening${suffix || " an item"}`, completed: `Opened${suffix || " an item"}` };+ case "update": return { running: `Updating${suffix || " data"}`, completed: `Updated${suffix || " data"}` };+ case "create": return { running: `Creating${suffix || " an item"}`, completed: `Created${suffix || " an item"}` };+ case "delete": return { running: `Deleting${suffix || " an item"}`, completed: `Deleted${suffix || " an item"}` };+ case "move": return { running: `Moving${suffix || " an item"}`, completed: `Moved${suffix || " an item"}` };+ case "run": return { running: "Running a command", completed: "Ran a command" };+ case "request": return { running: `Requesting${suffix || " input"}`, completed: `Requested${suffix || " input"}` };+ case "post": return { running: `Posting${suffix || " an update"}`, completed: `Posted${suffix || " an update"}` };+ case "start": return { running: `Starting${suffix || " an operation"}`, completed: `Started${suffix || " an operation"}` };+ case "stop": return { running: `Stopping${suffix || " an operation"}`, completed: `Stopped${suffix || " an operation"}` };+ case "wait": return { running: "Waiting", completed: "Finished waiting" };+ case "finish": return { running: "Reporting completion", completed: "Reported completion" };+ case "block": return { running: "Reporting a blocker", completed: "Reported a blocker" };+ case "think": return { running: "Thinking", completed: "Finished thinking" };+ case "switch": return { running: `Switching${suffix || " mode"}`, completed: `Switched${suffix || " mode"}` };+ case "other": return { running: "Running", completed: "Ran" };+ }+}++function defaultSummaryGroup(action: Action): ToolSummaryGroup {+ switch (action) {+ case "run": return group("command", "command", "commands");+ case "read":+ case "list": return group("read", "read", "reads");+ case "search": return group("search", "search", "searches");+ case "update":+ case "create":+ case "delete":+ case "move": return group("file_change", "file change", "file changes");+ case "start":+ case "stop": return group("delegation", "delegation", "delegations");+ case "wait": return group("wait", "wait", "waits");+ default: return group("tool_action", "tool action", "tool actions");+ }+}++function paperclipSummaryGroup(action: Action): ToolSummaryGroup {+ if (action === "read" || action === "list") return group("paperclip_read", "Paperclip read", "Paperclip reads");+ return group("task_operation", "task operation", "task operations");}/**- * Icons for the tool-free informative statuses ("Thinking", "Responding",- * "Responding (streaming)"). Whimsified and generic labels get no glyph — the- * pulse dot alone carries those.+ * Resolve one tool into status-specific copy and iconography. Precedence is:+ * exact aliases, canonical ACP operation/kind, normalized verb, then a named+ * fallback. MCP remains visible as the source icon without losing semantics.*/+export function toolActivityPresentation(input: ToolActivityPresentationInput): ToolActivityPresentation {+ const rawName = (input.name ?? "").trim();+ const parsedMcp = mcpToolIdentity(rawName);+ const namespace = (input.namespace ?? parsedMcp?.namespace ?? "").trim();+ // The name itself is authoritative for historical ACPX records that were+ // persisted as builtin before MCP transport normalization existed.+ const transport = (parsedMcp ? "mcp" : input.transport ?? "builtin").toLowerCase();+ const semanticName = (parsedMcp?.name ?? rawName).trim();+ const words = identifierWords(semanticName);+ const key = normalizedKey(semanticName);+ const exact = EXACT_ACTIONS[key];+ const operationAction = OPERATION_ACTIONS[(input.operation ?? "").trim().toLowerCase()];+ const inferred = inferredAction(words);+ const action = exact?.action ?? operationAction ?? inferred ?? "other";+ const confidence: ToolClassificationConfidence = exact+ ? "exact"+ : operationAction+ ? "kind"+ : inferred+ ? "inferred"+ : isGenericToolName(semanticName)+ ? "unnamed"+ : "fallback";+ const displayName = isGenericToolName(semanticName) ? "Unnamed tool" : humanizeToolName(semanticName);+ const identifierLikeName = /^[A-Za-z][A-Za-z0-9_.:-]*$/.test(semanticName);+ const objectWords = inferred && identifierLikeName && words.length > 1 ? words.slice(1) : [];+ const object = objectWords.length ? sentenceCase(objectWords).replace(/^./, (letter) => letter.toLowerCase()) : undefined;+ const copy = exact?.running && exact.completed+ ? { running: exact.running, completed: exact.completed }+ : action === "other"+ ? isGenericToolName(semanticName)+ ? { running: "Running an unnamed tool", completed: "Ran an unnamed tool" }+ : { running: `Running ${displayName}`, completed: `Ran ${displayName}` }+ : actionCopy(action, exact ? undefined : object);+ const semanticFamily = exact?.family ?? actionFamily(action);+ const family = transport === "mcp" ? "mcp" : semanticFamily;+ const sourceLabel = namespace+ ? humanizeToolName(namespace)+ : transport === "mcp"+ ? "MCP"+ : undefined;+ const summaryGroup = namespace.toLowerCase() === "paperclip"+ ? paperclipSummaryGroup(action)+ : exact?.group ?? defaultSummaryGroup(action);++ return {+ icon: FAMILY_ICONS[family],+ family,+ runningLabel: copy.running,+ completedLabel: copy.completed,+ failedLabel: `${copy.completed} · failed`,+ interruptedLabel: `${copy.running} · stopped`,+ displayName,+ sourceLabel,+ technicalName: rawName || undefined,+ confidence,+ summaryGroup,+ };+}++/** Compact compatibility mapping used by legacy tool rows and live pills. */+export function toolTaxonomy(name: string | undefined | null): ToolTaxonomyEntry {+ const presentation = toolActivityPresentation({ name });+ return {+ family: presentation.family,+ icon: presentation.icon,+ verbLabel: presentation.runningLabel,+ };+}++/** Icons for tool-free informative statuses. */export function statusLabelIcon(label: string | undefined | null): ToolIcon | null {const raw = (label ?? "").trim().toLowerCase();if (raw === "thinking") return Brain;diff --git a/ui/src/components/task-chat/transcript-adapter.test.ts b/ui/src/components/task-chat/transcript-adapter.test.tsindex c719b066b6..b5b168cd93 100644--- a/ui/src/components/task-chat/transcript-adapter.test.ts+++ b/ui/src/components/task-chat/transcript-adapter.test.ts@@ -3,46 +3,101 @@ import type { TranscriptEntry } from "@/adapters";import {assembleThreadItems,attachSettledTurns,+ buildActivityPhases,+ buildTurnTimelineRows,buildMergedTurnSummary,buildTurnSummary,coalesceSettledTurns,deriveRunStatusLabel,+ embedPlanDocumentAtWriteBoundary,flattenSelfTalk,isNestableLiveChild,ISSUE_BRIEF_ITEM_ID,+ paperclipRunnerActivityItems,+ paperclipRunnerFinalResponse,+ paperclipRunnerHistoryItems,+ paperclipRunnerTimelineItems,prependIssueBrief,settledRunChildren,+ splitTranscriptAtAnchors,toolDisplayName,transcriptToTaskChatItems,type SettledTurnMergeMeta,type ThreadBackboneEntry,} from "./transcript-adapter";-import type { TaskChatItem, TaskChatTurnItem } from "./task-chat-model";+import type {+ TaskChatItem,+ TaskChatPlanDocumentItem,+ TaskChatTurnItem,+} from "./task-chat-model";+import { providerActivityPresentation } from "./task-chat-activity-presentation";const TS = "2026-07-31T12:00:00.000Z";function toolCall(name: string, input?: unknown): TranscriptEntry {- return { kind: "tool_call", ts: TS, name, toolUseId: `tool-${name}`, input } as TranscriptEntry;+ return {+ kind: "tool_call",+ ts: TS,+ name,+ toolUseId: `tool-${name}`,+ input,+ } as TranscriptEntry;}+describe("splitTranscriptAtAnchors", () => {+ const assistant = (ts: string, text: string): TranscriptEntry =>+ ({ kind: "assistant", ts, channel: "progress", text }) as TranscriptEntry;++ it("assigns each boundary and its following entries to the next segment", () => {+ const entries = [+ assistant("2026-08-25T17:20:50.000Z", "before"),+ assistant("2026-08-25T17:21:44.541Z", "first boundary"),+ assistant("2026-08-25T17:22:10.000Z", "between"),+ assistant("2026-08-25T17:23:00.000Z", "second boundary"),+ ];+ const segments = splitTranscriptAtAnchors(+ entries,+ Date.parse("2026-08-25T17:20:45.369Z"),+ [+ Date.parse("2026-08-25T17:23:00.000Z"),+ Date.parse("2026-08-25T17:21:44.541Z"),+ Date.parse("2026-08-25T17:21:44.541Z"),+ ],+ );++ expect(segments.map((segment) => segment.entries.length)).toEqual([+ 1, 2, 1,+ ]);+ expect(+ segments.map((segment) =>+ segment.entries.map((entry) =>+ entry.kind === "assistant" ? entry.text : entry.kind,+ ),+ ),+ ).toEqual([["before"], ["first boundary", "between"], ["second boundary"]]);+ });+});+describe("deriveRunStatusLabel", () => {it("labels a tail tool_call with the taxonomy verb and tool · target detail", () => {- const status = deriveRunStatusLabel([toolCall("Grep", { pattern: "ui/src/components" })]);- expect(status.label).toBe("Grepping");+ const status = deriveRunStatusLabel([+ toolCall("Grep", { pattern: "ui/src/components" }),+ ]);+ expect(status.label).toBe("Searching file contents");expect(status.detail).toBe("Grep · ui/src/components");expect(status.toolName).toBe("Grep");});it("uses family verbs per tool", () => {- expect(deriveRunStatusLabel([toolCall("Bash", { command: "pnpm test" })]).label).toBe(- "Running a command",- );- expect(deriveRunStatusLabel([toolCall("Edit", { file_path: "a.ts" })]).label).toBe(- "Editing files",- );- expect(deriveRunStatusLabel([toolCall("mcp__linear__search_issues")]).label).toBe(- "Using Search_issues",- );+ expect(+ deriveRunStatusLabel([toolCall("Bash", { command: "pnpm test" })]).label,+ ).toBe("Running a command");+ expect(+ deriveRunStatusLabel([toolCall("Edit", { file_path: "a.ts" })]).label,+ ).toBe("Editing a file");+ expect(+ deriveRunStatusLabel([toolCall("mcp__linear__search_issues")]).label,+ ).toBe("Searching issues");});it("omits the target from the detail when the input has none", () => {@@ -52,17 +107,26 @@ describe("deriveRunStatusLabel", () => {it("keeps Thinking / Responding / Running fallbacks", () => {expect(- deriveRunStatusLabel([{ kind: "thinking", ts: TS, text: "hmm" } as TranscriptEntry]).label,+ deriveRunStatusLabel([+ { kind: "thinking", ts: TS, text: "hmm" } as TranscriptEntry,+ ]).label,).toBe("Thinking");expect(- deriveRunStatusLabel([{ kind: "assistant", ts: TS, text: "done" } as TranscriptEntry]).label,+ deriveRunStatusLabel([+ { kind: "assistant", ts: TS, text: "done" } as TranscriptEntry,+ ]).label,).toBe("Responding");expect(deriveRunStatusLabel([]).label).toBe("Running");// A settled tool (tool_result at the tail) means "between tools" → Running.expect(deriveRunStatusLabel([toolCall("Bash", { command: "ls" }),- { kind: "tool_result", ts: TS, toolUseId: "tool-Bash", content: "ok" } as TranscriptEntry,+ {+ kind: "tool_result",+ ts: TS,+ toolUseId: "tool-Bash",+ content: "ok",+ } as TranscriptEntry,]).label,).toBe("Running");});@@ -70,16 +134,18 @@ describe("deriveRunStatusLabel", () => {describe("toolDisplayName", () => {it("collapses mcp names the same way the taxonomy does", () => {- expect(toolDisplayName("mcp__linear-server__search_issues")).toBe("Search_issues");+ expect(toolDisplayName("mcp__linear-server__search_issues")).toBe(+ "Search issues",+ );expect(toolDisplayName("bash")).toBe("Bash");- expect(toolDisplayName("")).toBe("Tool");- expect(toolDisplayName("tool")).toBe("Tool");+ expect(toolDisplayName("")).toBe("Unnamed tool");+ expect(toolDisplayName("tool")).toBe("Unnamed tool");});- it("maps acpx placeholder names to the generic Tool label", () => {- expect(toolDisplayName("tool call")).toBe("Tool");- expect(toolDisplayName("tool call (completed)")).toBe("Tool");- expect(toolDisplayName("acp_tool")).toBe("Tool");+ it("maps acpx placeholder names to the explicit unnamed-tool label", () => {+ expect(toolDisplayName("tool call")).toBe("Unnamed tool");+ expect(toolDisplayName("tool call (completed)")).toBe("Unnamed tool");+ expect(toolDisplayName("acp_tool")).toBe("Unnamed tool");});});@@ -128,8 +194,18 @@ describe("transcriptToTaskChatItems tool_call updates", () => {// generic "tool call" completion updates.const items = transcriptToTaskChatItems([- { kind: "tool_call", ts: TS, name: "Terminal", toolUseId: "tc-2" } as TranscriptEntry,- { kind: "tool_call", ts: TS, name: "ls -la", toolUseId: "tc-2" } as TranscriptEntry,+ {+ kind: "tool_call",+ ts: TS,+ name: "Terminal",+ toolUseId: "tc-2",+ } as TranscriptEntry,+ {+ kind: "tool_call",+ ts: TS,+ name: "ls -la",+ toolUseId: "tc-2",+ } as TranscriptEntry,update("tc-2", "completed"),],opts,@@ -142,7 +218,10 @@ describe("transcriptToTaskChatItems tool_call updates", () => {});it("never renders the synthesized { text, status } input as a target", () => {- const items = transcriptToTaskChatItems([update("tc-orphan", "pending")], opts);+ const items = transcriptToTaskChatItems(+ [update("tc-orphan", "pending")],+ opts,+ );expect(items).toHaveLength(1);if (items[0].kind !== "tool") return;expect(items[0].target).toBeUndefined();@@ -151,8 +230,18 @@ describe("transcriptToTaskChatItems tool_call updates", () => {it("upgrades a generic-named call when a later entry carries the real name", () => {const items = transcriptToTaskChatItems([- { kind: "tool_call", ts: TS, name: "tool call", toolUseId: "tc-1" } as TranscriptEntry,- { kind: "tool_call", ts: TS, name: "Read", toolUseId: "tc-1" } as TranscriptEntry,+ {+ kind: "tool_call",+ ts: TS,+ name: "tool call",+ toolUseId: "tc-1",+ } as TranscriptEntry,+ {+ kind: "tool_call",+ ts: TS,+ name: "Read",+ toolUseId: "tc-1",+ } as TranscriptEntry,],opts,);@@ -160,6 +249,784 @@ describe("transcriptToTaskChatItems tool_call updates", () => {if (items[0].kind !== "tool") return;expect(items[0].name).toBe("Read");});++ it("marks an unfinished tool interrupted once the transcript is settled", () => {+ const items = transcriptToTaskChatItems(+ [toolCall("Terminal", { command: "sleep 120" })],+ opts,+ );+ expect(items).toHaveLength(1);+ expect(items[0]).toMatchObject({+ kind: "tool",+ name: "Terminal",+ status: "interrupted",+ detail: "Interrupted before the provider reported completion.",+ });+ });+});++describe("transcriptToTaskChatItems protocol surfaces", () => {+ const opts = { runId: "run-protocol", running: false };++ it("retains and updates provider activity instead of dropping it", () => {+ const items = transcriptToTaskChatItems(+ [+ {+ kind: "provider_activity",+ ts: TS,+ family: "plan",+ eventType: "plan.updated",+ status: "running",+ title: "Plan",+ summary: "Drafting",+ payload: {+ planId: "plan-1",+ revision: 1,+ steps: [+ { stepId: "one", body: "Inventory", status: "in_progress" },+ ],+ },+ },+ {+ kind: "provider_activity",+ ts: TS,+ family: "plan",+ eventType: "plan.updated",+ status: "completed",+ title: "Plan",+ summary: "Ready",+ payload: {+ planId: "plan-1",+ revision: 2,+ steps: [{ stepId: "one", body: "Inventory", status: "completed" }],+ },+ },+ ],+ opts,+ );+ expect(items).toHaveLength(1);+ expect(items[0]).toMatchObject({+ kind: "protocol",+ surface: "provider_activity",+ family: "plan",+ status: "completed",+ summary: "Ready",+ });+ });++ it("preserves named ACPX tool identity and progress when terminal updates omit them", () => {+ const items = transcriptToTaskChatItems(+ [+ {+ kind: "provider_activity",+ ts: TS,+ family: "tool_execution",+ eventType: "tool.execution.started",+ status: "running",+ title: "Tool execution",+ summary: "Searching the task index",+ payload: {+ executionId: "exec-lifecycle",+ transport: "mcp",+ namespace: "paperclip",+ name: "search_tasks",+ operation: "search",+ progress: "Searching the task index",+ target: "doc/plan.md",+ },+ },+ {+ kind: "provider_activity",+ ts: TS,+ family: "tool_execution",+ eventType: "tool.execution.completed",+ status: "completed",+ title: "Tool execution",+ summary: "tool call",+ payload: {+ executionId: "exec-lifecycle",+ transport: "builtin",+ name: "tool call",+ status: "completed",+ output: "done",+ },+ },+ ] as TranscriptEntry[],+ opts,+ );+ expect(items).toHaveLength(1);+ const item = items[0];+ expect(item).toMatchObject({+ kind: "protocol",+ surface: "provider_activity",+ family: "tool_execution",+ status: "completed",+ summary: "Searching the task index",+ output: "done",+ });+ if (item.kind !== "protocol" || item.surface !== "provider_activity")+ return;+ expect(item.details).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ label: "Name", value: "search_tasks" }),+ expect.objectContaining({ label: "Namespace", value: "paperclip" }),+ expect.objectContaining({ label: "Operation", value: "search" }),+ expect.objectContaining({ label: "Target", value: "doc/plan.md" }),+ expect.objectContaining({+ label: "Progress",+ value: "Searching the task index",+ }),+ ]),+ );+ expect(providerActivityPresentation(item)).toMatchObject({+ runningLabel: "Searching tasks",+ completedLabel: "Searched tasks",+ detail: "Searching the task index · Paperclip · search_tasks",+ });+ });++ it("marks a running provider activity interrupted in a settled transcript", () => {+ const items = transcriptToTaskChatItems(+ [+ {+ kind: "provider_activity",+ ts: TS,+ family: "tool_execution",+ eventType: "tool.execution.started",+ status: "running",+ title: "Tool execution",+ summary: "sleep 120",+ payload: {},+ },+ ],+ opts,+ );+ expect(items[0]).toMatchObject({+ kind: "protocol",+ surface: "provider_activity",+ status: "interrupted",+ summary: "sleep 120 · Interrupted before completion.",+ });+ });++ it("coalesces workspace revisions and runtime request lifecycle states", () => {+ const items = transcriptToTaskChatItems(+ [+ {+ kind: "workspace_change",+ ts: TS,+ changeSetId: "change-1",+ revision: 1,+ source: "harness_reported",+ complete: false,+ files: [],+ totals: { files: 0, additions: null, deletions: null },+ patchArtifactRef: null,+ },+ {+ kind: "workspace_change",+ ts: TS,+ changeSetId: "change-1",+ revision: 2,+ source: "runner_verified",+ complete: true,+ files: [+ {+ path: "ui/src/App.tsx",+ operation: "modify",+ previousPath: null,+ additions: 1,+ deletions: 0,+ binary: false,+ diff: "+ok",+ },+ ],+ totals: { files: 1, additions: 1, deletions: 0 },+ patchArtifactRef: null,+ },+ {+ kind: "runtime_request",+ ts: TS,+ requestId: "request-1",+ requestKind: "command_approval",+ turnId: "turn-1",+ requestType: "permission",+ status: "pending",+ prompt: "Allow?",+ choices: [],+ fields: [],+ },+ {+ kind: "runtime_request",+ ts: TS,+ requestId: "request-1",+ requestKind: "command_approval",+ turnId: "turn-1",+ requestType: "permission",+ status: "resolved",+ prompt: "Allow?",+ choices: [],+ fields: [],+ },+ ],+ opts,+ );+ expect(items).toHaveLength(2);+ expect(items[0]).toMatchObject({+ kind: "protocol",+ surface: "workspace_change",+ revision: 2,+ complete: true,+ });+ expect(items[1]).toMatchObject({+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-protocol",+ turnId: "turn-1",+ requestKind: "command_approval",+ status: "resolved",+ });+ });++ it("bounds provider output and workspace previews to 8 KiB", () => {+ const oversized = "x".repeat(9 * 1024);+ const items = transcriptToTaskChatItems(+ [+ {+ kind: "provider_activity",+ ts: TS,+ family: "tool_execution",+ eventType: "tool.execution.completed",+ status: "completed",+ title: "Tool execution",+ summary: "Done",+ payload: { executionId: "exec-1", output: oversized },+ },+ {+ kind: "workspace_file_reference",+ ts: TS,+ referenceId: "file-1",+ source: "runner_verified",+ path: "ui/src/App.tsx",+ displayName: "App.tsx",+ mediaType: "text/typescript",+ presentation: "code",+ line: null,+ preview: oversized,+ previewTruncated: false,+ contentDigest: null,+ },+ ],+ opts,+ );+ const provider = items.find(+ (item) =>+ item.kind === "protocol" && item.surface === "provider_activity",+ );+ const file = items.find(+ (item) => item.kind === "protocol" && item.surface === "workspace_file",+ );+ expect(+ provider && provider.surface === "provider_activity"+ ? provider.output?.length+ : 0,+ ).toBe(8 * 1024);+ expect(+ provider && provider.surface === "provider_activity"+ ? provider.outputTruncated+ : false,+ ).toBe(true);+ expect(+ file && file.surface === "workspace_file" ? file.preview?.length : 0,+ ).toBe(8 * 1024);+ expect(+ file && file.surface === "workspace_file" ? file.previewTruncated : false,+ ).toBe(true);+ });++ it("turns canonical research sources into safe links and exposes notice metadata", () => {+ const items = transcriptToTaskChatItems(+ [+ {+ kind: "provider_activity",+ ts: TS,+ family: "research",+ eventType: "research.completed",+ status: "completed",+ title: "Research",+ summary: "PRP",+ payload: {+ researchId: "research-1",+ sources: [+ {+ title: "Protocol notes",+ url: "https://example.com/prp",+ snippet: "Canonical event details",+ },+ { title: "Unsafe", url: "file:///etc/passwd" },+ ],+ },+ },+ {+ kind: "provider_activity",+ ts: TS,+ family: "provider_notice",+ eventType: "provider.notice.recorded",+ status: "informational",+ title: "Provider notice",+ summary: "Update configuration",+ payload: {+ noticeId: "notice-1",+ severity: "warning",+ category: "config",+ scope: "environment",+ recoverable: true,+ userActionable: false,+ },+ },+ ],+ opts,+ );+ const research = items.find(+ (item) =>+ item.kind === "protocol" &&+ item.surface === "provider_activity" &&+ item.family === "research",+ );+ const notice = items.find(+ (item) =>+ item.kind === "protocol" &&+ item.surface === "provider_activity" &&+ item.family === "provider_notice",+ );+ expect(+ research?.kind === "protocol" && research.surface === "provider_activity"+ ? research.links+ : [],+ ).toEqual([+ {+ label: "Protocol notes",+ href: "https://example.com/prp",+ description: "Canonical event details",+ },+ ]);+ expect(+ notice?.kind === "protocol" && notice.surface === "provider_activity"+ ? notice.details+ : [],+ ).toEqual(+ expect.arrayContaining([+ { label: "Severity", value: "warning", mono: false },+ { label: "Category", value: "config", mono: false },+ { label: "Scope", value: "environment", mono: false },+ { label: "Recoverable", value: "Yes", mono: false },+ { label: "User Actionable", value: "No", mono: false },+ ]),+ );+ });++ it("retains every canonical provider family for live and settled rendering", () => {+ const families = [+ "plan",+ "tool_execution",+ "research",+ "delegation",+ "model_identity",+ "context",+ "artifact",+ "review",+ "hook",+ "memory",+ "safety",+ "terminal",+ "wait",+ "provider_notice",+ ] as const;+ const entries = families.map((family, index): TranscriptEntry => ({+ kind: "provider_activity",+ ts: new Date(Date.parse(TS) + index).toISOString(),+ family,+ eventType: `${family}.fixture`,+ status: index % 2 === 0 ? "running" : "completed",+ title: family,+ summary: `Visible ${family}`,+ payload: { [`${family}Id`]: `${family}-1` },+ }));+ const items = transcriptToTaskChatItems(entries, {+ ...opts,+ running: true,+ });+ expect(+ items.map((item) =>+ item.kind === "protocol" && item.surface === "provider_activity"+ ? item.family+ : null,+ ),+ ).toEqual(families);+ });+});++describe("buildActivityPhases provider summaries", () => {+ it("includes canonical provider work in the folded activity summary", () => {+ const provider = (+ id: string,+ family: "research" | "hook",+ ): TaskChatItem => ({+ id,+ kind: "protocol",+ surface: "provider_activity",+ family,+ eventType: `${family}.completed`,+ status: "completed",+ title: family,+ details: [],+ steps: [],+ links: [],+ children: [],+ });+ const phases = buildActivityPhases(+ [+ {+ id: "finish",+ kind: "tool",+ name: "Paperclip_finish",+ status: "completed",+ },+ provider("research-1", "research"),+ provider("research-2", "research"),+ provider("research-3", "research"),+ provider("hook-1", "hook"),+ {+ id: "workspace",+ kind: "protocol",+ surface: "workspace_change",+ changeSetId: "change-1",+ revision: 1,+ source: "runner_verified",+ complete: true,+ files: [],+ totals: { files: 2, additions: 1, deletions: 1 },+ patchArtifactRef: null,+ },+ ],+ false,+ );+ expect(phases[0]?.summary).toBe(+ "Used a tool, searched 3 times, ran a hook",+ );+ });++ it("counts canonical tool execution when no native tool row exists", () => {+ const phases = buildActivityPhases(+ [+ {+ id: "provider-tool",+ kind: "protocol",+ surface: "provider_activity",+ family: "tool_execution",+ eventType: "tool.execution.completed",+ status: "completed",+ title: "Tool execution",+ details: [],+ steps: [],+ links: [],+ children: [],+ },+ ],+ false,+ );+ expect(phases[0]?.summary).toBe("Used a tool");+ });++ it("summarizes the sanitized DOT-212 mix with at most three semantic groups", () => {+ const providerTool = (+ id: string,+ name: string,+ operation: string,+ namespace?: string,+ ): TaskChatItem => ({+ id,+ kind: "protocol",+ surface: "provider_activity",+ family: "tool_execution",+ eventType: "tool.execution.completed",+ status: "completed",+ title: "Tool execution",+ details: [+ { label: "Transport", value: namespace ? "mcp" : "builtin" },+ { label: "Operation", value: operation },+ { label: "Name", value: name, mono: true },+ ...(namespace+ ? [{ label: "Namespace", value: namespace, mono: true }]+ : []),+ ],+ steps: [],+ links: [],+ children: [],+ });+ const items: TaskChatItem[] = [+ ...Array.from({ length: 6 }, (_, index) =>+ providerTool(`search-${index}`, "ToolSearch", "search"),+ ),+ providerTool("context", "get_task_context", "read", "paperclip"),+ providerTool("documents", "list_documents", "list", "paperclip"),+ providerTool("history", "get_task_history", "read", "paperclip"),+ providerTool("tasks", "search_tasks", "search", "paperclip"),+ providerTool("progress", "report_progress", "edit", "paperclip"),+ providerTool("block", "paperclip_block", "edit", "paperclip"),+ ];+ expect(buildActivityPhases(items, false)[0]?.summary).toBe(+ "Searched available tools 6 times, read from Paperclip 3 times, used Paperclip 3 times",+ );+ });+});++describe("buildTurnTimelineRows (DOT-217)", () => {+ const commentary = (id: string, text: string): TaskChatItem => ({+ id,+ kind: "message",+ author: "agent",+ text,+ interstitial: true,+ channel: "progress",+ });+ const tool = (id: string): TaskChatItem => ({+ id,+ kind: "tool",+ name: "Read",+ rawName: "read_file",+ target: `${id}.ts`,+ status: "completed",+ });+ const request = (+ id: string,+ status: "pending" | "resolved" | "cancelled" | "expired",+ ): TaskChatItem => ({+ id: `${id}:${status}`,+ kind: "protocol",+ surface: "runtime_request",+ runId: "run-dot-217",+ requestId: id,+ requestKind: "user_input",+ turnId: "turn-dot-217",+ requestType: "input",+ status,+ prompt: `Question ${id}`,+ choices: [],+ fields: [],+ });++ const workspace: TaskChatItem = {+ id: "workspace-change",+ kind: "protocol",+ surface: "workspace_change",+ changeSetId: "turn-dot-217:workspace",+ revision: 2,+ source: "runner_verified",+ complete: true,+ files: [+ {+ path: "src/App.tsx",+ operation: "modify",+ previousPath: null,+ additions: 2,+ deletions: 1,+ binary: false,+ diff: "+new\n-old\n",+ },+ ],+ totals: { files: 1, additions: 2, deletions: 1 },+ patchArtifactRef: null,+ };++ it("keeps commentary, grouped tools, and latest question receipts in first-seen order", () => {+ const input = [+ commentary("commentary-1", "Inspecting the workspace."),+ tool("tool-1"),+ tool("tool-2"),+ commentary("commentary-2", "I need two product choices."),+ request("questions-1", "pending"),+ commentary("commentary-3", "I’ll continue with the selected scope."),+ tool("tool-3"),+ request("questions-2", "pending"),+ commentary("commentary-4", "The final constraint is clear."),+ tool("tool-4"),+ request("questions-1", "resolved"),+ request("questions-2", "cancelled"),+ ];++ const rows = buildTurnTimelineRows(input, false);+ expect(+ rows.map((row) => {+ if (row.kind === "activity_phase") {+ return `${row.interstitial?.id ?? "opening"}:${row.items.map((item) => item.id).join(",")}`;+ }+ if (row.kind === "protocol" && row.surface === "runtime_request") {+ return `${row.requestId}:${row.status}`;+ }+ return row.kind;+ }),+ ).toEqual([+ "commentary-1:tool-1,tool-2",+ "commentary-2:",+ "questions-1:resolved",+ "commentary-3:tool-3",+ "questions-2:cancelled",+ "commentary-4:tool-4",+ ]);+ });++ it("keeps a pending request composer-only while preserving its group boundary", () => {+ const rows = buildTurnTimelineRows(+ [tool("before"), request("pending", "pending"), tool("after")],+ true,+ );++ expect(rows).toHaveLength(2);+ expect(rows.every((row) => row.kind === "activity_phase")).toBe(true);+ expect(+ rows.map((row) =>+ row.kind === "activity_phase" ? row.items[0]?.id : null,+ ),+ ).toEqual(["before", "after"]);+ expect(rows[0]).toMatchObject({ kind: "activity_phase", active: false });+ expect(rows[1]).toMatchObject({ kind: "activity_phase", active: true });+ });++ it("retains progress-only phases and uses the same row order for settled assembly", () => {+ const input = [+ tool("opening"),+ commentary("commentary-only", "Still checking the edge case."),+ request("expired", "expired"),+ ];+ expect(settledRunChildren(input)).toEqual(+ buildTurnTimelineRows(input, false),+ );+ expect(buildTurnTimelineRows(input, false).map((row) => row.kind)).toEqual([+ "activity_phase",+ "activity_phase",+ "protocol",+ ]);+ });++ it("keeps runtime requests in the Paperclip Runner timeline input", () => {+ const pending = request("pending", "pending");+ expect(+ paperclipRunnerTimelineItems([+ commentary("commentary", "Checking."),+ pending,+ { id: "usage", kind: "usage", usage: { used: 1, size: 10 } },+ ]).map((item) => item.id),+ ).toEqual(["commentary", pending.id, "usage"]);+ });++ it("keeps aggregate workspace changes at the turn boundary outside activity", () => {+ const rows = buildTurnTimelineRows(+ paperclipRunnerTimelineItems([tool("before"), workspace, tool("after")]),+ false,+ );+ expect(rows.map((row) => row.kind)).toEqual([+ "activity_phase",+ "protocol",+ "activity_phase",+ ]);+ expect(rows[1]).toMatchObject({+ surface: "workspace_change",+ changeSetId: "turn-dot-217:workspace",+ });+ });++ it("suppresses file-change fragments only when an aggregate event exists", () => {+ const fileChange: TaskChatItem = {+ id: "provider-file-change",+ kind: "tool",+ name: "File change",+ rawName: "fileChange",+ status: "completed",+ diff: { path: "src/App.tsx", added: 2, removed: 1 },+ };+ expect(paperclipRunnerActivityItems([fileChange])).toEqual([fileChange]);+ expect(paperclipRunnerActivityItems([fileChange, workspace])).toEqual([+ workspace,+ ]);+ });++ it("projects a yielded run-result summary into the durable final slot", () => {+ expect(+ paperclipRunnerFinalResponse([+ {+ id: "result",+ kind: "protocol",+ surface: "run_result",+ disposition: "yielded",+ summary: "Waiting for Review browser RTS plan.",+ objectiveSatisfied: false,+ verification: [],+ remainingWork: [],+ blocker: null,+ artifacts: [],+ },+ ]),+ ).toMatchObject({+ kind: "message",+ channel: "final",+ text: "Waiting for Review browser RTS plan.",+ });+ });++ it("keeps a saved plan at its write_document boundary", () => {+ const plan: TaskChatPlanDocumentItem = {+ id: "plan-doc:revision-1",+ kind: "plan_document",+ document: {} as TaskChatPlanDocumentItem["document"],+ };+ const embedded = embedPlanDocumentAtWriteBoundary(+ [+ commentary("commentary-1", "Inspecting."),+ tool("read-before-plan"),+ commentary("commentary-2", "Publishing the plan."),+ {+ id: "write-plan",+ kind: "tool",+ name: "Write document",+ rawName: "write_document",+ status: "completed",+ },+ {+ id: "write-plan-provider",+ kind: "protocol",+ surface: "provider_activity",+ family: "tool_execution",+ eventType: "tool.execution.completed",+ status: "completed",+ title: "write_document",+ details: [{ label: "Name", value: "write_document" }],+ steps: [],+ links: [],+ children: [],+ },+ commentary("commentary-3", "The plan is published."),+ ],+ plan,+ );++ const rows = buildTurnTimelineRows(+ paperclipRunnerTimelineItems(embedded),+ false,+ );+ expect(+ rows.map((row) =>+ row.kind === "activity_phase"+ ? `${row.interstitial?.id}:${row.items.map((item) => item.id).join(",")}`+ : row.id,+ ),+ ).toEqual([+ "commentary-1:read-before-plan",+ "commentary-2:write-plan,write-plan-provider",+ plan.id,+ "commentary-3:",+ ]);+ });});describe("transcriptToTaskChatItems native usage", () => {@@ -262,7 +1129,10 @@ describe("transcriptToTaskChatItems native usage", () => {});describe("buildTurnSummary tool counting", () => {- function statusEntry(toolUseId: string | undefined, status: string): TranscriptEntry {+ function statusEntry(+ toolUseId: string | undefined,+ status: string,+ ): TranscriptEntry {return {kind: "tool_call",ts: TS,@@ -338,8 +1208,18 @@ describe("deriveRunStatusLabel with generic tail updates", () => {it("treats a tail retitle as the invocation, not the identity", () => {const status = deriveRunStatusLabel([- { kind: "tool_call", ts: TS, name: "Terminal", toolUseId: "tc-3" } as TranscriptEntry,- { kind: "tool_call", ts: TS, name: "pnpm test", toolUseId: "tc-3" } as TranscriptEntry,+ {+ kind: "tool_call",+ ts: TS,+ name: "Terminal",+ toolUseId: "tc-3",+ } as TranscriptEntry,+ {+ kind: "tool_call",+ ts: TS,+ name: "pnpm test",+ toolUseId: "tc-3",+ } as TranscriptEntry,]);expect(status.label).toBe("Running a command");expect(status.toolName).toBe("Terminal");@@ -352,25 +1232,36 @@ describe("isNestableLiveChild", () => {{ id: "t", kind: "tool", name: "Read", status: "completed" },{ id: "th", kind: "thinking", lines: ["hm"] },{ id: "u", kind: "usage", usage: { used: 1, size: 2 } },- { id: "m", kind: "message", author: "agent", text: "finished self-talk", interstitial: true },- { id: "mk", kind: "marker", variant: "session_start", label: "Session started" },+ {+ id: "m",+ kind: "message",+ author: "agent",+ text: "finished self-talk",+ interstitial: true,+ },+ {+ id: "mk",+ kind: "marker",+ variant: "session_start",+ label: "Session started",+ },{ id: "s", kind: "status", status: "running", label: "Running" },{ id: "i", kind: "interaction", interaction: {} as never },];- it("nests only tool and usage rows inside the live parent row (PAP-361)", () => {+ it("nests tools, provider reasoning, and usage inside the live parent row", () => {expect(items.filter(isNestableLiveChild).map((it) => it.kind)).toEqual(["tool",+ "thinking","usage",]);});- it("keeps messages, thinking, markers, statuses and interactions out", () => {+ it("keeps messages, markers, statuses and interactions out", () => {// Interstitial updates — finished or streaming — never nest: they are- // ephemeral, living on the live line only while streaming. Thinking never- // nests either (its live signal is the pill's "Thinking…" state), and the- // final reply keeps its bubble.- for (const kind of ["message", "thinking", "marker", "status", "interaction"]) {+ // ephemeral, living on the live line only while streaming, and the final+ // reply keeps its bubble.+ for (const kind of ["message", "marker", "status", "interaction"]) {const item = items.find((it) => it.kind === kind)!;expect(isNestableLiveChild(item)).toBe(false);}@@ -385,22 +1276,36 @@ describe("isNestableLiveChild", () => {}),).toBe(false);expect(- isNestableLiveChild({ id: "m3", kind: "message", author: "agent", text: "Final reply." }),+ isNestableLiveChild({+ id: "m3",+ kind: "message",+ author: "agent",+ text: "Final reply.",+ }),).toBe(false);});});describe("interstitial self-talk classification (PAP-355)", () => {const stream: TranscriptEntry[] = [- { kind: "assistant", ts: TS, text: "Let me check the adapter." } as TranscriptEntry,+ {+ kind: "assistant",+ ts: TS,+ text: "Let me check the adapter.",+ } as TranscriptEntry,toolCall("Read", { file_path: "a.ts" }),- { kind: "assistant", ts: "2026-07-31T12:00:05.000Z", text: "Found it — fixing now." } as TranscriptEntry,+ {+ kind: "assistant",+ ts: "2026-07-31T12:00:05.000Z",+ text: "Found it — fixing now.",+ } as TranscriptEntry,];it("tags agent messages streamed inside a live run turn as interstitial", () => {- const messages = transcriptToTaskChatItems(stream, { runId: "run-1", running: true }).filter(- (it) => it.kind === "message",- );+ const messages = transcriptToTaskChatItems(stream, {+ runId: "run-1",+ running: true,+ }).filter((it) => it.kind === "message");expect(messages).toHaveLength(2);for (const m of messages) {if (m.kind !== "message") continue;@@ -409,9 +1314,13 @@ describe("interstitial self-talk classification (PAP-355)", () => {});it("marks only the message still open at the tail as streaming", () => {- const items = transcriptToTaskChatItems(stream, { runId: "run-1", running: true });+ const items = transcriptToTaskChatItems(stream, {+ runId: "run-1",+ running: true,+ });const messages = items.filter((it) => it.kind === "message");- if (messages[0].kind !== "message" || messages[1].kind !== "message") return;+ if (messages[0].kind !== "message" || messages[1].kind !== "message")+ return;// The first message was closed by the tool call — finished self-talk.expect(messages[0].streaming).toBe(false);expect(messages[1].streaming).toBe(true);@@ -428,9 +1337,10 @@ describe("interstitial self-talk classification (PAP-355)", () => {});it("tags settled-history messages interstitial too, so live and history agree", () => {- const messages = transcriptToTaskChatItems(stream, { runId: "run-1", running: false }).filter(- (it) => it.kind === "message",- );+ const messages = transcriptToTaskChatItems(stream, {+ runId: "run-1",+ running: false,+ }).filter((it) => it.kind === "message");expect(messages).toHaveLength(2);for (const m of messages) {if (m.kind !== "message") continue;@@ -440,10 +1350,12 @@ describe("interstitial self-talk classification (PAP-355)", () => {});it("stamps atMs from the first streamed chunk", () => {- const messages = transcriptToTaskChatItems(stream, { runId: "run-1", running: false }).filter(- (it) => it.kind === "message",- );- if (messages[0].kind !== "message" || messages[1].kind !== "message") return;+ const messages = transcriptToTaskChatItems(stream, {+ runId: "run-1",+ running: false,+ }).filter((it) => it.kind === "message");+ if (messages[0].kind !== "message" || messages[1].kind !== "message")+ return;expect(messages[0].atMs).toBe(Date.parse(TS));expect(messages[1].atMs).toBe(Date.parse("2026-07-31T12:00:05.000Z"));});@@ -452,12 +1364,16 @@ describe("interstitial self-talk classification (PAP-355)", () => {describe("flattenSelfTalk", () => {it("strips markdown markers to one plain line", () => {expect(- flattenSelfTalk("## Plan\n\nI'll **extend** the `ipRateLimit` helper:\n- read it\n- patch it"),+ flattenSelfTalk(+ "## Plan\n\nI'll **extend** the `ipRateLimit` helper:\n- read it\n- patch it",+ ),).toBe("Plan I'll extend the ipRateLimit helper: read it patch it");});it("keeps link text, drops the url, and is stream-safe on unclosed markers", () => {- expect(flattenSelfTalk("see [the docs](https://x) for **bol")).toBe("see the docs for bol");+ expect(flattenSelfTalk("see [the docs](https://x) for **bol")).toBe(+ "see the docs for bol",+ );expect(flattenSelfTalk("```ts\nconst a = 1;")).toBe("const a = 1;");});});@@ -465,8 +1381,16 @@ describe("flattenSelfTalk", () => {describe("deriveRunStatusLabel streaming interstitial text (PAP-361)", () => {it("returns the trailing message's flattened text with the Responding label", () => {const status = deriveRunStatusLabel([- { kind: "assistant", ts: TS, text: "I'll **extend** " } as TranscriptEntry,- { kind: "assistant", ts: TS, text: "the `ipRateLimit` helper." } as TranscriptEntry,+ {+ kind: "assistant",+ ts: TS,+ text: "I'll **extend** ",+ } as TranscriptEntry,+ {+ kind: "assistant",+ ts: TS,+ text: "the `ipRateLimit` helper.",+ } as TranscriptEntry,]);expect(status.label).toBe("Responding");expect(status.selfTalk).toBe("I'll extend the ipRateLimit helper.");@@ -485,7 +1409,9 @@ describe("deriveRunStatusLabel streaming interstitial text (PAP-361)", () => {it("carries no selfTalk for tool or thinking tails", () => {expect(deriveRunStatusLabel([toolCall("Read")]).selfTalk).toBeUndefined();expect(- deriveRunStatusLabel([{ kind: "thinking", ts: TS, text: "hm" } as TranscriptEntry]).selfTalk,+ deriveRunStatusLabel([+ { kind: "thinking", ts: TS, text: "hm" } as TranscriptEntry,+ ]).selfTalk,).toBeUndefined();expect(deriveRunStatusLabel([]).selfTalk).toBeUndefined();});@@ -493,20 +1419,35 @@ describe("deriveRunStatusLabel streaming interstitial text (PAP-361)", () => {describe("settledRunChildren (PAP-361)", () => {const transcript: TranscriptEntry[] = [- { kind: "assistant", ts: TS, text: "Checking the adapter first." } as TranscriptEntry,+ {+ kind: "assistant",+ ts: TS,+ text: "Checking the adapter first.",+ } as TranscriptEntry,toolCall("Read", { file_path: "a.ts" }),{ kind: "thinking", ts: TS, text: "wire it in" } as TranscriptEntry,toolCall("Edit", { file_path: "a.ts" }),- { kind: "assistant", ts: TS, text: "Done — the limiter is wired in." } as TranscriptEntry,+ {+ kind: "assistant",+ ts: TS,+ text: "Done — the limiter is wired in.",+ } as TranscriptEntry,];- const parsed = transcriptToTaskChatItems(transcript, { runId: "run-1", running: false });+ const parsed = transcriptToTaskChatItems(transcript, {+ runId: "run-1",+ running: false,+ });it("groups tools under the historical assistant boundary and excludes the final reply", () => {const children = settledRunChildren(parsed);expect(children.map((c) => c.kind)).toEqual(["activity_phase"]);const phase = children[0];- expect(phase.kind === "activity_phase" && phase.interstitial?.text).toBe("Checking the adapter first.");- expect(phase.kind === "activity_phase" && phase.items.map((item) => item.kind)).toEqual(["tool", "tool"]);+ expect(phase.kind === "activity_phase" && phase.interstitial?.text).toBe(+ "Checking the adapter first.",+ );+ expect(+ phase.kind === "activity_phase" && phase.items.map((item) => item.kind),+ ).toEqual(["tool", "thinking", "tool"]);});it("excludes an explicit final reply when runner usage follows it", () => {@@ -540,40 +1481,520 @@ describe("settledRunChildren (PAP-361)", () => {expect(phase.items.map((item) => item.kind)).toEqual(["usage"]);});+ it("keeps a channel-less final reply out of activity when bookkeeping follows it", () => {+ const finalThenBookkeeping = transcriptToTaskChatItems([+ {+ kind: "assistant",+ ts: TS,+ text: "Done — the direct adapter finished.",+ } as TranscriptEntry,+ {+ kind: "result",+ ts: TS,+ text: "",+ inputTokens: 40,+ outputTokens: 10,+ cachedTokens: 0,+ costUsd: 0,+ subtype: "paperclip_runner_usage",+ isError: false,+ errors: [],+ } as TranscriptEntry,+ ], { runId: "legacy-run", running: false });++ const children = settledRunChildren(finalThenBookkeeping);+ expect(children).toHaveLength(1);+ const phase = children[0];+ expect(phase.kind).toBe("activity_phase");+ if (phase.kind !== "activity_phase") return;+ expect(phase.interstitial).toBeUndefined();+ expect(phase.items.map((item) => item.kind)).toEqual(["usage"]);+ });++ it("keeps a channel-less final reply out of activity when a workspace summary follows it", () => {+ const finalReply = transcriptToTaskChatItems(+ [+ {+ kind: "assistant",+ ts: TS,+ text: "Done — the workspace is updated.",+ } as TranscriptEntry,+ ],+ { runId: "legacy-run", running: false },+ );+ const children = settledRunChildren([+ ...finalReply,+ {+ id: "workspace-summary",+ kind: "protocol",+ surface: "workspace_change",+ changeSetId: "changes-1",+ revision: 1,+ source: "harness_reported",+ complete: true,+ files: [],+ totals: { files: 0, additions: 0, deletions: 0 },+ patchArtifactRef: null,+ },+ ]);++ expect(children).toHaveLength(1);+ expect(children[0]?.kind).toBe("protocol");+ expect(+ children.some(+ (child) =>+ child.kind === "activity_phase" &&+ child.interstitial?.text === "Done — the workspace is updated.",+ ),+ ).toBe(false);+ });++ it("does not hide channel-less commentary when real activity follows it", () => {+ const commentaryThenToolAndUsage = transcriptToTaskChatItems([+ {+ kind: "assistant",+ ts: TS,+ text: "Checking the direct adapter first.",+ } as TranscriptEntry,+ toolCall("Read", { file_path: "a.ts" }),+ {+ kind: "result",+ ts: TS,+ text: "",+ inputTokens: 40,+ outputTokens: 10,+ cachedTokens: 0,+ costUsd: 0,+ subtype: "paperclip_runner_usage",+ isError: false,+ errors: [],+ } as TranscriptEntry,+ ], { runId: "legacy-run", running: false });++ const children = settledRunChildren(commentaryThenToolAndUsage);+ expect(children).toHaveLength(1);+ const phase = children[0];+ expect(phase.kind).toBe("activity_phase");+ if (phase.kind !== "activity_phase") return;+ expect(phase.interstitial?.text).toBe(+ "Checking the direct adapter first.",+ );+ expect(phase.items.map((item) => item.kind)).toEqual(["tool", "usage"]);+ });+it("matches the folded summary's tool count exactly (row-count parity)", () => {const children = settledRunChildren(parsed);const summary = buildTurnSummary(transcript);const phaseToolCount = children.reduce(- (count, child) => count + (child.kind === "activity_phase" ? child.items.filter((item) => item.kind === "tool").length : 0),+ (count, child) =>+ count ++ (child.kind === "activity_phase"+ ? child.items.filter((item) => item.kind === "tool").length+ : 0),0,);expect(phaseToolCount).toBe(summary.toolCount);});it("creates a stable opening phase for calls before the first interstitial", () => {- const opening = transcriptToTaskChatItems([- toolCall("Read", { file_path: "a.ts" }),- { kind: "assistant", ts: TS, text: "Now editing." } as TranscriptEntry,- toolCall("Edit", { file_path: "a.ts" }),- { kind: "assistant", ts: TS, text: "Done." } as TranscriptEntry,- ], { runId: "run-opening", running: false });+ const opening = transcriptToTaskChatItems(+ [+ toolCall("Read", { file_path: "a.ts" }),+ { kind: "assistant", ts: TS, text: "Now editing." } as TranscriptEntry,+ toolCall("Edit", { file_path: "a.ts" }),+ { kind: "assistant", ts: TS, text: "Done." } as TranscriptEntry,+ ],+ { runId: "run-opening", running: false },+ );const phases = settledRunChildren(opening);expect(phases).toHaveLength(2);expect(phases[0].id).toContain(":phase:opening");- expect(phases[1].kind === "activity_phase" && phases[1].summary).toBe("Edited 1 file");+ expect(phases[1].kind === "activity_phase" && phases[1].summary).toBe(+ "Edited a file",+ );+ });+});++describe("paperclip runner semantic channels", () => {+ it("concatenates fragmented reasoning deltas into logical lines", () => {+ const parsed = transcriptToTaskChatItems(+ [+ {+ kind: "thinking",+ ts: TS,+ text: "Inspect",+ delta: true,+ channel: "summary",+ },+ {+ kind: "thinking",+ ts: TS,+ text: "ing the ",+ delta: true,+ channel: "summary",+ },+ {+ kind: "thinking",+ ts: TS,+ text: "runner",+ delta: true,+ channel: "summary",+ },+ {+ kind: "thinking",+ ts: TS,+ text: "\nThen ",+ delta: true,+ channel: "summary",+ },+ {+ kind: "thinking",+ ts: TS,+ text: "verify streaming",+ delta: true,+ channel: "summary",+ },+ ],+ { runId: "run-fragmented-reasoning", running: true },+ );++ expect(parsed).toHaveLength(1);+ expect(parsed[0]).toMatchObject({+ kind: "thinking",+ lines: ["Inspecting the runner", "Then verify streaming"],+ transcriptIndex: 4,+ });+ });++ it("ends reasoning when a newer transcript surface becomes current", () => {+ const parsed = transcriptToTaskChatItems(+ [+ {+ kind: "thinking",+ ts: TS,+ text: "Inspecting the runner",+ channel: "summary",+ delta: true,+ },+ {+ kind: "assistant",+ ts: TS,+ text: "I found the relevant component.",+ channel: "progress",+ },+ {+ kind: "thinking",+ ts: TS,+ text: "Checking the render state",+ channel: "summary",+ delta: true,+ },+ toolCall("Read", { file_path: "TaskChatThinking.tsx" }),+ {+ kind: "thinking",+ ts: TS,+ text: "Verifying the fix",+ channel: "summary",+ delta: true,+ },+ ],+ { runId: "run-reasoning-activity", running: true },+ );+ const thinking = parsed.filter(+ (item): item is Extract<TaskChatItem, { kind: "thinking" }> =>+ item.kind === "thinking",+ );+ expect(thinking.map((item) => item.streaming)).toEqual([+ false,+ false,+ true,+ ]);+ });++ it("turns empty reasoning lifecycle frames into a visible thinking item", () => {+ const parsed = transcriptToTaskChatItems(+ [+ {+ kind: "thinking",+ ts: "2026-08-21T12:00:00.000Z",+ text: "",+ lifecycle: "started",+ channel: "summary",+ },+ {+ kind: "thinking",+ ts: "2026-08-21T12:00:02.000Z",+ text: "",+ lifecycle: "completed",+ channel: "summary",+ },+ ],+ { runId: "run-empty-reasoning", running: true },+ );++ expect(parsed).toEqual([+ expect.objectContaining({+ kind: "thinking",+ lines: [],+ streaming: false,+ lifecycleOnly: true,+ summaryLabel: "Thought for 2s",+ }),+ ]);+ });++ it("keeps progress/final messages and reasoning summary/detail in distinct items", () => {+ const parsed = transcriptToTaskChatItems(+ [+ {+ kind: "assistant",+ ts: TS,+ text: "Checking.",+ channel: "progress",+ delta: true,+ },+ {+ kind: "thinking",+ ts: TS,+ text: "Summary",+ channel: "summary",+ delta: true,+ },+ {+ kind: "thinking",+ ts: TS,+ text: "Detail",+ channel: "detail",+ delta: true,+ },+ {+ kind: "assistant",+ ts: TS,+ text: "Done.",+ channel: "final",+ delta: true,+ },+ ],+ { runId: "run-channels", running: true },+ );+ expect(parsed.map((item) => item.kind)).toEqual([+ "message",+ "thinking",+ "thinking",+ "message",+ ]);+ expect(parsed[0]).toMatchObject({+ interstitial: true,+ channel: "progress",+ });+ expect(parsed[1]).toMatchObject({ channel: "summary", streaming: false });+ expect(parsed[2]).toMatchObject({ channel: "detail", streaming: false });+ expect(parsed[3]).toMatchObject({ interstitial: false, channel: "final" });+ const history = settledRunChildren(parsed);+ expect(JSON.stringify(history)).not.toContain("Done.");+ });++ it("filters lifecycle and usage noise from only the runner history surface", () => {+ const items: TaskChatItem[] = [+ {+ id: "session",+ kind: "marker",+ variant: "session_start",+ label: "Session started",+ detail: "session-id",+ },+ {+ id: "start",+ kind: "marker",+ variant: "turn_boundary",+ label: "Turn started",+ },+ {+ id: "usage",+ kind: "usage",+ usage: {+ used: 1_024,+ size: 128_000,+ inputTokens: 1_000,+ outputTokens: 24,+ },+ },+ {+ id: "tool",+ kind: "tool",+ name: "Paperclip_finish",+ status: "completed",+ target: "done",+ },+ {+ id: "interrupt",+ kind: "marker",+ variant: "interrupted",+ label: "Interrupted",+ },+ {+ id: "runner",+ kind: "marker",+ variant: "turn_boundary",+ label: "Runner update",+ },+ {+ id: "complete",+ kind: "marker",+ variant: "turn_boundary",+ label: "Turn completed",+ },+ ];++ expect(paperclipRunnerHistoryItems(items).map((item) => item.id)).toEqual([+ "tool",+ "interrupt",+ "runner",+ ]);+ expect(items).toHaveLength(7);+ });++ it("projects one semantic activity row per useful logical item", () => {+ const items: TaskChatItem[] = [+ {+ id: "progress",+ kind: "message",+ author: "agent",+ text: "Looking this up.",+ interstitial: true,+ channel: "progress",+ },+ {+ id: "final",+ kind: "message",+ author: "agent",+ text: "Finished.",+ channel: "final",+ },+ {+ id: "empty-thinking",+ kind: "thinking",+ lines: [],+ lifecycleOnly: true,+ },+ {+ id: "thinking",+ kind: "thinking",+ lines: ["Provider-authored summary"],+ },+ {+ id: "tool",+ kind: "tool",+ name: "Search",+ rawName: "web_search",+ status: "completed",+ },+ {+ id: "finish",+ kind: "tool",+ name: "Paperclip_finish",+ rawName: "paperclip_finish",+ status: "completed",+ },+ {+ id: "session",+ kind: "marker",+ variant: "session_start",+ label: "Session started",+ },+ {+ id: "interrupt",+ kind: "marker",+ variant: "interrupted",+ label: "Interrupted",+ },+ { id: "usage", kind: "usage", usage: { used: 20, size: 100 } },+ {+ id: "research",+ kind: "protocol",+ surface: "provider_activity",+ family: "research",+ eventType: "research.completed",+ status: "completed",+ title: "Research",+ details: [],+ steps: [],+ links: [],+ children: [],+ },+ {+ id: "result",+ kind: "protocol",+ surface: "run_result",+ disposition: "done",+ summary: "Finished.",+ objectiveSatisfied: true,+ verification: [],+ remainingWork: [],+ blocker: null,+ artifacts: [],+ },+ {+ id: "terminal",+ kind: "protocol",+ surface: "run_terminal",+ turnState: "completed",+ runState: "succeeded",+ disposition: "done",+ },+ ];++ expect(paperclipRunnerActivityItems(items).map((item) => item.id)).toEqual([+ "progress",+ "thinking",+ "tool",+ "interrupt",+ "usage",+ "research",+ ]);});});describe("buildMergedTurnSummary (PAP-362)", () => {const runA: TranscriptEntry[] = [- { kind: "tool_call", ts: "2026-07-31T12:00:00.000Z", name: "Read", toolUseId: "a-1" } as TranscriptEntry,- { kind: "tool_call", ts: "2026-07-31T12:00:05.000Z", name: "Edit", toolUseId: "a-2" } as TranscriptEntry,- { kind: "diff", ts: "2026-07-31T12:00:06.000Z", changeType: "add", text: "+x" } as TranscriptEntry,- { kind: "result", ts: "2026-07-31T12:00:10.000Z", inputTokens: 500, outputTokens: 300 } as TranscriptEntry,+ {+ kind: "tool_call",+ ts: "2026-07-31T12:00:00.000Z",+ name: "Read",+ toolUseId: "a-1",+ } as TranscriptEntry,+ {+ kind: "tool_call",+ ts: "2026-07-31T12:00:05.000Z",+ name: "Edit",+ toolUseId: "a-2",+ } as TranscriptEntry,+ {+ kind: "diff",+ ts: "2026-07-31T12:00:06.000Z",+ changeType: "add",+ text: "+x",+ } as TranscriptEntry,+ {+ kind: "result",+ ts: "2026-07-31T12:00:10.000Z",+ inputTokens: 500,+ outputTokens: 300,+ } as TranscriptEntry,];const runB: TranscriptEntry[] = [- { kind: "tool_call", ts: "2026-07-31T12:30:00.000Z", name: "Bash", toolUseId: "b-1" } as TranscriptEntry,- { kind: "result", ts: "2026-07-31T12:30:05.000Z", inputTokens: 300, outputTokens: 100 } as TranscriptEntry,+ {+ kind: "tool_call",+ ts: "2026-07-31T12:30:00.000Z",+ name: "Bash",+ toolUseId: "b-1",+ } as TranscriptEntry,+ {+ kind: "result",+ ts: "2026-07-31T12:30:05.000Z",+ inputTokens: 300,+ outputTokens: 100,+ } as TranscriptEntry,];it("sums tool count, diffs, tokens, and duration across runs", () => {@@ -590,7 +2011,10 @@ describe("buildMergedTurnSummary (PAP-362)", () => {it("sums per-run ts spans — never the idle gap between runs", () => {// runA spans 10s, runB spans 5s, the gap between them is ~30min.- const summary = buildMergedTurnSummary([{ entries: runA }, { entries: runB }]);+ const summary = buildMergedTurnSummary([+ { entries: runA },+ { entries: runB },+ ]);expect(summary.durationLabel).toBe("15s");});@@ -605,17 +2029,42 @@ describe("buildMergedTurnSummary (PAP-362)", () => {describe("coalesceSettledTurns (PAP-362)", () => {const runA: TranscriptEntry[] = [- { kind: "tool_call", ts: TS, name: "Read", toolUseId: "a-1" } as TranscriptEntry,- { kind: "tool_call", ts: TS, name: "Edit", toolUseId: "a-2" } as TranscriptEntry,+ {+ kind: "tool_call",+ ts: TS,+ name: "Read",+ toolUseId: "a-1",+ } as TranscriptEntry,+ {+ kind: "tool_call",+ ts: TS,+ name: "Edit",+ toolUseId: "a-2",+ } as TranscriptEntry,];const runB: TranscriptEntry[] = [- { kind: "tool_call", ts: TS, name: "Bash", toolUseId: "b-1" } as TranscriptEntry,+ {+ kind: "tool_call",+ ts: TS,+ name: "Bash",+ toolUseId: "b-1",+ } as TranscriptEntry,];function agentBubble(id: string): TaskChatItem {- return { id, kind: "message", author: "agent", authorName: "CEO", text: "Done." };+ return {+ id,+ kind: "message",+ author: "agent",+ authorName: "CEO",+ text: "Done.",+ };}- function turn(id: string, entries: TranscriptEntry[], durationMs: number): TaskChatItem {+ function turn(+ id: string,+ entries: TranscriptEntry[],+ durationMs: number,+ ): TaskChatItem {return {id,kind: "turn",@@ -630,8 +2079,22 @@ describe("coalesceSettledTurns (PAP-362)", () => {};}const metaById = new Map<string, SettledTurnMergeMeta>([- ["run-a:turn", { agentKey: "agent-1", agentName: "CEO", parts: [{ entries: runA, durationMs: 30_000 }] }],- ["run-b:turn", { agentKey: "agent-1", agentName: "CEO", parts: [{ entries: runB, durationMs: 15_000 }] }],+ [+ "run-a:turn",+ {+ agentKey: "agent-1",+ agentName: "CEO",+ parts: [{ entries: runA, durationMs: 30_000 }],+ },+ ],+ [+ "run-b:turn",+ {+ agentKey: "agent-1",+ agentName: "CEO",+ parts: [{ entries: runB, durationMs: 15_000 }],+ },+ ],]);it("merges two back-to-back runs into ONE Worked row summing tools and duration", () => {@@ -666,7 +2129,13 @@ describe("coalesceSettledTurns (PAP-362)", () => {];const out = coalesceSettledTurns(items, metaById);expect(out.filter((i) => i.kind === "turn")).toHaveLength(2);- expect(out.map((i) => i.id)).toEqual(["msg-a", "run-a:turn", "msg-u", "msg-b", "run-b:turn"]);+ expect(out.map((i) => i.id)).toEqual([+ "msg-a",+ "run-a:turn",+ "msg-u",+ "msg-b",+ "run-b:turn",+ ]);});it("does not merge across an interaction or into another agent's turn", () => {@@ -675,29 +2144,66 @@ describe("coalesceSettledTurns (PAP-362)", () => {{ id: "int-1", kind: "interaction", interaction: {} } as TaskChatItem,turn("run-b:turn", runB, 15_000),];- expect(coalesceSettledTurns(withInteraction, metaById).filter((i) => i.kind === "turn")).toHaveLength(2);+ expect(+ coalesceSettledTurns(withInteraction, metaById).filter(+ (i) => i.kind === "turn",+ ),+ ).toHaveLength(2);const otherAgent = new Map(metaById);- otherAgent.set("run-b:turn", { agentKey: "agent-2", agentName: "QA", parts: [{ entries: runB }] });- const sameShape: TaskChatItem[] = [turn("run-a:turn", runA, 30_000), turn("run-b:turn", runB, 15_000)];- expect(coalesceSettledTurns(sameShape, otherAgent).filter((i) => i.kind === "turn")).toHaveLength(2);+ otherAgent.set("run-b:turn", {+ agentKey: "agent-2",+ agentName: "QA",+ parts: [{ entries: runB }],+ });+ const sameShape: TaskChatItem[] = [+ turn("run-a:turn", runA, 30_000),+ turn("run-b:turn", runB, 15_000),+ ];+ expect(+ coalesceSettledTurns(sameShape, otherAgent).filter(+ (i) => i.kind === "turn",+ ),+ ).toHaveLength(2);});it("never merges the live (unsettled) turn and preserves animateFold", () => {- const live: TaskChatItem = { id: "run-b:turn", kind: "turn", settled: false, items: [], summary: buildTurnSummary([]) };- const out = coalesceSettledTurns([turn("run-a:turn", runA, 30_000), live], metaById);+ const live: TaskChatItem = {+ id: "run-b:turn",+ kind: "turn",+ settled: false,+ items: [],+ summary: buildTurnSummary([]),+ };+ const out = coalesceSettledTurns(+ [turn("run-a:turn", runA, 30_000), live],+ metaById,+ );expect(out).toHaveLength(2);- const seenLive = { ...turn("run-b:turn", runB, 15_000), animateFold: true } as TaskChatItem;- const merged = coalesceSettledTurns([turn("run-a:turn", runA, 30_000), seenLive], metaById);+ const seenLive = {+ ...turn("run-b:turn", runB, 15_000),+ animateFold: true,+ } as TaskChatItem;+ const merged = coalesceSettledTurns(+ [turn("run-a:turn", runA, 30_000), seenLive],+ metaById,+ );expect(merged).toHaveLength(1);- expect((merged[0] as Extract<TaskChatItem, { kind: "turn" }>).animateFold).toBe(true);+ expect(+ (merged[0] as Extract<TaskChatItem, { kind: "turn" }>).animateFold,+ ).toBe(true);});});describe("attachSettledTurns (round 9)", () => {const runA: TranscriptEntry[] = [- { kind: "tool_call", ts: TS, name: "Read", toolUseId: "a-1" } as TranscriptEntry,+ {+ kind: "tool_call",+ ts: TS,+ name: "Read",+ toolUseId: "a-1",+ } as TranscriptEntry,];function agentBubble(id: string, authorName = "CEO"): TaskChatItem {@@ -708,16 +2214,28 @@ describe("attachSettledTurns (round 9)", () => {id,kind: "turn",settled: true,- items: [{ id: `${id}:tool:0`, kind: "tool", name: "Read", status: "completed" }],+ items: [+ { id: `${id}:tool:0`, kind: "tool", name: "Read", status: "completed" },+ ],summary: buildTurnSummary(runA, { durationMs: 30_000 }),};}const metaById = new Map<string, SettledTurnMergeMeta>([- ["run-a:turn", { agentKey: "agent-1", agentName: "CEO", parts: [{ entries: runA, durationMs: 30_000 }] }],+ [+ "run-a:turn",+ {+ agentKey: "agent-1",+ agentName: "CEO",+ parts: [{ entries: runA, durationMs: 30_000 }],+ },+ ],]);it("folds a settled turn into the agent reply bubble directly above it", () => {- const out = attachSettledTurns([agentBubble("msg-a"), settledTurn("run-a:turn")], metaById);+ const out = attachSettledTurns(+ [agentBubble("msg-a"), settledTurn("run-a:turn")],+ metaById,+ );expect(out).toHaveLength(1);const bubble = out[0] as Extract<TaskChatItem, { kind: "message" }>;expect(bubble.id).toBe("msg-a");@@ -728,15 +2246,24 @@ describe("attachSettledTurns (round 9)", () => {it("keeps the standalone row when the preceding item is not that agent's bubble", () => {// Human message directly above.const afterHuman = attachSettledTurns(- [{ id: "msg-u", kind: "message", author: "human", text: "hi" }, settledTurn("run-a:turn")],+ [+ { id: "msg-u", kind: "message", author: "human", text: "hi" },+ settledTurn("run-a:turn"),+ ],metaById,);expect(afterHuman.map((i) => i.kind)).toEqual(["message", "turn"]);// Another agent's bubble above.- const otherAgent = attachSettledTurns([agentBubble("msg-q", "QA"), settledTurn("run-a:turn")], metaById);+ const otherAgent = attachSettledTurns(+ [agentBubble("msg-q", "QA"), settledTurn("run-a:turn")],+ metaById,+ );expect(otherAgent.map((i) => i.kind)).toEqual(["message", "turn"]);// No meta (unknown identity) → conservative standalone fallback.- const noMeta = attachSettledTurns([agentBubble("msg-a"), settledTurn("run-x:turn")], metaById);+ const noMeta = attachSettledTurns(+ [agentBubble("msg-a"), settledTurn("run-x:turn")],+ metaById,+ );expect(noMeta.map((i) => i.kind)).toEqual(["message", "turn"]);// Nothing above at all.const first = attachSettledTurns([settledTurn("run-a:turn")], metaById);@@ -757,20 +2284,36 @@ describe("attachSettledTurns (round 9)", () => {// A second settled turn behind an already-attached bubble stays standalone// (coalesceSettledTurns runs first, so same-agent turns arrive pre-merged).const twice = attachSettledTurns(- [agentBubble("msg-a"), settledTurn("run-a:turn"), settledTurn("run-a:turn")],+ [+ agentBubble("msg-a"),+ settledTurn("run-a:turn"),+ settledTurn("run-a:turn"),+ ],metaById,);expect(twice.map((i) => i.kind)).toEqual(["message", "turn"]);- expect((twice[0] as Extract<TaskChatItem, { kind: "message" }>).attachedTurn?.id).toBe("run-a:turn");+ expect(+ (twice[0] as Extract<TaskChatItem, { kind: "message" }>).attachedTurn?.id,+ ).toBe("run-a:turn");});});describe("assembleThreadItems (PAP-367)", () => {- function entry(id: string, ms: number, item?: Partial<TaskChatItem>): ThreadBackboneEntry {+ function entry(+ id: string,+ ms: number,+ item?: Partial<TaskChatItem>,+ ): ThreadBackboneEntry {return {ms,id,- item: { id, kind: "message", author: "human", text: `msg ${id}`, ...item } as TaskChatItem,+ item: {+ id,+ kind: "message",+ author: "human",+ text: `msg ${id}`,+ ...item,+ } as TaskChatItem,};}function settledTurn(id: string): TaskChatTurnItem {@@ -778,15 +2321,23 @@ describe("assembleThreadItems (PAP-367)", () => {id,kind: "turn",settled: true,- items: [{ id: `${id}:tool:0`, kind: "tool", name: "Read", status: "completed" }],+ items: [+ { id: `${id}:tool:0`, kind: "tool", name: "Read", status: "completed" },+ ],summary: buildTurnSummary([toolCall("Read")], { durationMs: 34_000 }),};}const noAnchors = new Map<string, TaskChatTurnItem[]>();it("inserts a comment-less settled turn chronologically at its run's start time", () => {- const backbone = [entry("u1", 1_000), entry("a1", 2_000, { author: "agent", authorName: "CEO" }), entry("u2", 3_000)];- const out = assembleThreadItems(backbone, noAnchors, [{ turn: settledTurn("run-x:turn"), startMs: 2_500 }]);+ const backbone = [+ entry("u1", 1_000),+ entry("a1", 2_000, { author: "agent", authorName: "CEO" }),+ entry("u2", 3_000),+ ];+ const out = assembleThreadItems(backbone, noAnchors, [+ { turn: settledTurn("run-x:turn"), startMs: 2_500 },+ ]);expect(out.map((i) => i.id)).toEqual(["u1", "a1", "run-x:turn", "u2"]);});@@ -794,13 +2345,19 @@ describe("assembleThreadItems (PAP-367)", () => {// The screenshot bug: an OLD stopped run (start 1_500) re-pinning its// "Worked · 34s" row under every NEW user bubble (3_000).const backbone = [entry("u1", 1_000), entry("u2", 3_000)];- const out = assembleThreadItems(backbone, noAnchors, [{ turn: settledTurn("run-x:turn"), startMs: 1_500 }]);+ const out = assembleThreadItems(backbone, noAnchors, [+ { turn: settledTurn("run-x:turn"), startMs: 1_500 },+ ]);expect(out.map((i) => i.id)).toEqual(["u1", "run-x:turn", "u2"]);expect(out[out.length - 1].id).toBe("u2");});it("keeps anchored turns directly after their run's reply comment", () => {- const backbone = [entry("u1", 1_000), entry("a1", 2_000, { author: "agent", authorName: "CEO" }), entry("u2", 3_000)];+ const backbone = [+ entry("u1", 1_000),+ entry("a1", 2_000, { author: "agent", authorName: "CEO" }),+ entry("u2", 3_000),+ ];const anchors = new Map([["a1", [settledTurn("run-a:turn")]]]);const out = assembleThreadItems(backbone, anchors, []);expect(out.map((i) => i.id)).toEqual(["u1", "a1", "run-a:turn", "u2"]);@@ -814,7 +2371,9 @@ describe("assembleThreadItems (PAP-367)", () => {]);expect(tail.map((i) => i.id)).toEqual(["u1", "u2", "run-x:turn"]);// Tie with the trigger comment: comment renders first.- const tie = assembleThreadItems(backbone, noAnchors, [{ turn: settledTurn("run-y:turn"), startMs: 1_000 }]);+ const tie = assembleThreadItems(backbone, noAnchors, [+ { turn: settledTurn("run-y:turn"), startMs: 1_000 },+ ]);expect(tie.map((i) => i.id)).toEqual(["u1", "run-y:turn", "u2"]);});@@ -823,12 +2382,31 @@ describe("assembleThreadItems (PAP-367)", () => {// later passes must neither merge it into anything nor attach it.const backbone = [entry("u1", 1_000), entry("u2", 3_000)];const metaById = new Map<string, SettledTurnMergeMeta>([- ["run-x:turn", { agentKey: "agent-1", agentName: "CEO", parts: [{ entries: [toolCall("Read")], durationMs: 34_000 }] }],+ [+ "run-x:turn",+ {+ agentKey: "agent-1",+ agentName: "CEO",+ parts: [{ entries: [toolCall("Read")], durationMs: 34_000 }],+ },+ ],]);- const assembled = assembleThreadItems(backbone, noAnchors, [{ turn: settledTurn("run-x:turn"), startMs: 1_500 }]);- const out = attachSettledTurns(coalesceSettledTurns(assembled, metaById), metaById);+ const assembled = assembleThreadItems(backbone, noAnchors, [+ { turn: settledTurn("run-x:turn"), startMs: 1_500 },+ ]);+ const out = attachSettledTurns(+ coalesceSettledTurns(assembled, metaById),+ metaById,+ );expect(out.map((i) => i.id)).toEqual(["u1", "run-x:turn", "u2"]);- expect(out.every((i) => i.kind !== "message" || (i as Extract<TaskChatItem, { kind: "message" }>).attachedTurn == null)).toBe(true);+ expect(+ out.every(+ (i) =>+ i.kind !== "message" ||+ (i as Extract<TaskChatItem, { kind: "message" }>).attachedTurn ==+ null,+ ),+ ).toBe(true);});});@@ -837,7 +2415,12 @@ describe("prependIssueBrief (PAP-375)", () => {return {ms,id,- item: { id, kind: "message", author: "human", text: `msg ${id}` } as TaskChatItem,+ item: {+ id,+ kind: "message",+ author: "human",+ text: `msg ${id}`,+ } as TaskChatItem,};}function settledTurn(id: string): TaskChatTurnItem {@@ -845,7 +2428,9 @@ describe("prependIssueBrief (PAP-375)", () => {id,kind: "turn",settled: true,- items: [{ id: `${id}:tool:0`, kind: "tool", name: "Read", status: "completed" }],+ items: [+ { id: `${id}:tool:0`, kind: "tool", name: "Read", status: "completed" },+ ],summary: buildTurnSummary([toolCall("Read")], { durationMs: 34_000 }),};}@@ -859,7 +2444,12 @@ describe("prependIssueBrief (PAP-375)", () => {{ turn: settledTurn("run-x:turn"), startMs: 0 },]);const out = prependIssueBrief(assembled, true);- expect(out.map((i) => i.id)).toEqual([ISSUE_BRIEF_ITEM_ID, "run-x:turn", "u1", "u2"]);+ expect(out.map((i) => i.id)).toEqual([+ ISSUE_BRIEF_ITEM_ID,+ "run-x:turn",+ "u1",+ "u2",+ ]);expect(out[0].kind).toBe("brief");});diff --git a/ui/src/components/task-chat/transcript-adapter.ts b/ui/src/components/task-chat/transcript-adapter.tsindex 55af6aae53..c59863e9bc 100644--- a/ui/src/components/task-chat/transcript-adapter.ts+++ b/ui/src/components/task-chat/transcript-adapter.ts@@ -3,7 +3,7 @@* useLiveRunTranscripts — the same source the current thread consumes) into the* redesign's TaskChatItem[]. This is what lets a real task stream* thinking → tool → diff → responding while a run is in flight, rather than- * only showing the final message once the turn produces a comment.+ * only showing a response after the turn settles.*/import type { TranscriptEntry } from "@/adapters";import type {@@ -13,8 +13,20 @@ import type {TaskChatToolItem,TaskChatTurnChildItem,TaskChatTurnItem,+ TaskChatProviderActivityItem,+ TaskChatProtocolDetail,+ TaskChatProtocolItem,+ TaskChatProtocolStep,+ TaskChatRunResultItem,+ TaskChatMessageItem,+ TaskChatPlanDocumentItem,} from "./task-chat-model";-import { isGenericToolName, mcpToolSegment, toolTaxonomy } from "./tool-taxonomy";+import {+ humanizeToolName,+ isGenericToolName,+ toolActivityPresentation,+ toolTaxonomy,+} from "./tool-taxonomy";const TERMINAL_STATUSES = new Set(["failed",@@ -24,22 +36,77 @@ const TERMINAL_STATUSES = new Set(["succeeded",]);-export function isTerminalRunStatus(status: string | undefined | null): boolean {+export function isTerminalRunStatus(+ status: string | undefined | null,+): boolean {return status != null && TERMINAL_STATUSES.has(status);}+export interface TranscriptTimeSegment {+ startMs: number;+ endMs: number;+ entries: TranscriptEntry[];+}++/**+ * Split one provider run at durable in-turn input timestamps. Each boundary+ * belongs to the segment after it, so a steering acknowledgement can stay in+ * the thread between the work produced before and after the steer. Live and+ * settled renderers share this projector to avoid re-sorting at handoff.+ */+export function splitTranscriptAtAnchors(+ entries: readonly TranscriptEntry[],+ startMs: number,+ rawAnchors: readonly number[],+): TranscriptTimeSegment[] {+ const anchors = [...new Set(rawAnchors.filter(Number.isFinite))].sort(+ (a, b) => a - b,+ );+ if (anchors.length === 0) {+ return [+ {+ startMs,+ endMs: Number.POSITIVE_INFINITY,+ entries: [...entries],+ },+ ];+ }+ return [startMs, ...anchors].map((segmentStartMs, index) => {+ const segmentEndMs = anchors[index] ?? Number.POSITIVE_INFINITY;+ return {+ startMs: segmentStartMs,+ endMs: segmentEndMs,+ entries: entries.filter((entry) => {+ const parsed = Date.parse(entry.ts);+ const entryMs = Number.isFinite(parsed) ? parsed : 0;+ const afterStart = index === 0 || entryMs >= segmentStartMs;+ return afterStart && entryMs < segmentEndMs;+ }),+ };+ });+}+/*** The live parent row's nesting rule (PAP-354, narrowed by PAP-361): only tool- * calls and usage readouts nest inside the expandable live turn. Messages- * never nest — an interstitial update streams on the parent row's own line- * (TaskChatStatusItem.selfTalk) and vanishes when it completes, and the run's- * final reply lands as its posted comment bubble. Thinking never nests either:- * its live signal is the pill's "Thinking…" state, and the text stays in the- * run log / classic transcript. Markers, statuses and interaction cards stay- * in the thread outside.+ * calls, provider-supplied reasoning summaries, and usage readouts nest inside+ * the expandable live turn. The classic parent-row surface may flatten a live+ * interstitial into its status line; the Paperclip Runner task surface instead+ * projects commentary as durable chronological phase boundaries. The run's+ * final reply is resolved separately into the turn's durable response slot or+ * its posted comment bubble. Markers, statuses and interaction cards stay in+ * the thread outside.*/-export function isNestableLiveChild(item: TaskChatItem): item is TaskChatTurnChildItem {- return item.kind === "tool" || item.kind === "usage" || item.kind === "activity_phase";+export function isNestableLiveChild(+ item: TaskChatItem,+): item is TaskChatTurnChildItem {+ return (+ item.kind === "tool" ||+ item.kind === "thinking" ||+ item.kind === "usage" ||+ item.kind === "activity_phase" ||+ item.kind === "plan_document" ||+ item.kind === "protocol"+ );}/**@@ -95,23 +162,30 @@ function clip(text: string, max: number): string {*/export function summarizeToolInput(input: unknown): string | undefined {if (input == null) return undefined;- if (typeof input === "string") return input.trim() ? clip(input, TARGET_MAX) : undefined;+ if (typeof input === "string")+ return input.trim() ? clip(input, TARGET_MAX) : undefined;if (typeof input !== "object") return clip(String(input), TARGET_MAX);const record = input as Record<string, unknown>;for (const key of TARGET_KEYS) {const value = record[key];- if (typeof value === "string" && value.trim()) return clip(value, TARGET_MAX);+ if (typeof value === "string" && value.trim())+ return clip(value, TARGET_MAX);}// The acpx log parser synthesizes { text, status } onto tool inputs from the// event's summary line — presentation noise, not call parameters.const entries = Object.entries(record).filter(([k, v]) =>- (typeof v === "string" || typeof v === "number" || typeof v === "boolean") &&+ (typeof v === "string" ||+ typeof v === "number" ||+ typeof v === "boolean") &&k !== "text" &&k !== "status",);if (entries.length === 0) return undefined;- return clip(entries.map(([k, v]) => `${k}: ${String(v)}`).join(", "), TARGET_MAX);+ return clip(+ entries.map(([k, v]) => `${k}: ${String(v)}`).join(", "),+ TARGET_MAX,+ );}/**@@ -121,24 +195,351 @@ export function summarizeToolInput(input: unknown): string | undefined {*/export function toolDisplayName(name: string | undefined | null): string {const raw = (name ?? "").trim();- if (isGenericToolName(raw)) return "Tool";- const mcp = mcpToolSegment(raw);- if (mcp) return mcp;- return raw.charAt(0).toUpperCase() + raw.slice(1);+ return isGenericToolName(raw) ? "Unnamed tool" : humanizeToolName(raw);}/** "Thought for Ns" once a coalesced thinking group spans ≥1s. */-function thoughtDurationLabel(startTs: string | undefined, endTs: string): string | undefined {+function thoughtDurationLabel(+ startTs: string | undefined,+ endTs: string,+): string | undefined {if (!startTs) return undefined;const start = Date.parse(startTs);const end = Date.parse(endTs);if (!Number.isFinite(start) || !Number.isFinite(end)) return undefined;const secs = Math.round((end - start) / 1000);if (secs < 1) return undefined;- return secs < 60 ? `Thought for ${secs}s` : `Thought for ${Math.floor(secs / 60)}m ${secs % 60}s`;+ return secs < 60+ ? `Thought for ${secs}s`+ : `Thought for ${Math.floor(secs / 60)}m ${secs % 60}s`;+}++/** Append token deltas onto the open logical line while preserving real newlines. */+function appendThinkingText(+ lines: string[],+ text: string,+ delta: boolean | undefined,+) {+ const fragments = text.split("\n");+ if (!delta || lines.length === 0) {+ lines.push(...fragments);+ return;+ }+ lines[lines.length - 1] =+ `${lines[lines.length - 1] ?? ""}${fragments[0] ?? ""}`;+ lines.push(...fragments.slice(1));}const DETAIL_MAX = 600;+const PROTOCOL_OUTPUT_MAX = 8 * 1024;++function objectRecord(value: unknown): Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+}++function stringValue(value: unknown): string | undefined {+ return typeof value === "string" && value.trim().length > 0+ ? value.trim()+ : undefined;+}++function scalarValue(value: unknown): string | undefined {+ if (typeof value === "string" && value.trim()) return value.trim();+ if (typeof value === "number" && Number.isFinite(value)) return String(value);+ if (typeof value === "boolean") return value ? "Yes" : "No";+ return undefined;+}++function titleCaseKey(value: string): string {+ return value+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")+ .replaceAll("_", " ")+ .replace(/\b\w/g, (letter) => letter.toUpperCase());+}++function safeHttpHref(value: unknown): string | null {+ const href = stringValue(value);+ if (!href) return null;+ try {+ const url = new URL(href);+ return url.protocol === "http:" || url.protocol === "https:" ? href : null;+ } catch {+ return null;+ }+}++const PROVIDER_DETAIL_KEYS: Record<+ TaskChatProviderActivityItem["family"],+ readonly string[]+> = {+ plan: ["revision", "syncStatus", "documentRevision", "complete"],+ tool_execution: [+ "transport",+ "operation",+ "name",+ "target",+ "namespace",+ "readOnly",+ "status",+ "progress",+ "durationMs",+ "exitCode",+ "outputBytes",+ ],+ research: ["action", "status", "query", "pattern", "url"],+ delegation: ["action", "status"],+ model_identity: [+ "provider",+ "requestedModel",+ "fromModel",+ "effectiveModel",+ "reason",+ "status",+ "buffering",+ "summary",+ ],+ context: ["reason", "preTokens", "postTokens", "sameSession"],+ artifact: [+ "status",+ "reference",+ "mediaType",+ "title",+ "registered",+ "transparentBackground",+ "failure",+ ],+ review: ["state", "scope"],+ hook: ["event", "scope", "status", "blocking", "durationMs", "summary"],+ memory: ["label", "available", "reference"],+ safety: ["status", "decision", "targetExecutionId", "summary"],+ terminal: ["origin", "inputClass", "byteCount"],+ wait: ["reason", "status", "plannedDurationMs", "elapsedDurationMs"],+ provider_notice: [+ "severity",+ "category",+ "scope",+ "recoverable",+ "userActionable",+ "summary",+ ],+};++function providerActivityKey(+ entry: Extract<TranscriptEntry, { kind: "provider_activity" }>,+): string {+ const idKeys = [+ "planId",+ "executionId",+ "researchId",+ "delegationId",+ "routeId",+ "verificationId",+ "compactionId",+ "artifactId",+ "reviewId",+ "hookId",+ "citationId",+ "waitId",+ "noticeId",+ ];+ for (const key of idKeys) {+ const value = stringValue(entry.payload[key]);+ if (value) return `${entry.family}:${value}`;+ }+ return `${entry.family}:${entry.eventType}:${entry.ts}`;+}++function providerActivityItem(+ entry: Extract<TranscriptEntry, { kind: "provider_activity" }>,+ runId: string,+ index: number,+): TaskChatProviderActivityItem {+ const details: TaskChatProtocolDetail[] = [];+ for (const key of PROVIDER_DETAIL_KEYS[entry.family]) {+ const value = scalarValue(entry.payload[key]);+ if (!value) continue;+ if (+ entry.family === "tool_execution" &&+ key === "name" &&+ isGenericToolName(value)+ )+ continue;+ if (+ entry.family === "tool_execution" &&+ key === "progress" &&+ !meaningfulProviderToolSummary(value)+ )+ continue;+ details.push({+ label: titleCaseKey(key),+ value: clip(+ value,+ key === "message" || key === "summary" || key === "reason" ? 320 : 160,+ ),+ mono: /(?:id|model|target|reference|url|code|bytes)$/i.test(key),+ });+ }++ const steps =+ entry.family === "plan" && Array.isArray(entry.payload.steps)+ ? entry.payload.steps+ .map(objectRecord)+ .slice(0, 256)+ .map((step, stepIndex) => {+ const rawStatus = stringValue(step.status);+ const status: TaskChatProtocolStep["status"] =+ rawStatus === "in_progress" ||+ rawStatus === "completed" ||+ rawStatus === "blocked"+ ? rawStatus+ : "pending";+ return {+ id: stringValue(step.stepId) ?? `${runId}:plan-step:${stepIndex}`,+ label: stringValue(step.body) ?? "Plan step",+ status,+ };+ })+ : [];++ const links =+ entry.family === "research" && Array.isArray(entry.payload.sources)+ ? entry.payload.sources+ .map(objectRecord)+ .slice(0, 64)+ .flatMap((source) => {+ const href = safeHttpHref(source.url);+ return href+ ? [+ {+ label: stringValue(source.title) ?? href,+ href,+ description: stringValue(source.snippet),+ },+ ]+ : [];+ })+ : [];++ const children =+ entry.family === "delegation" && Array.isArray(entry.payload.children)+ ? entry.payload.children+ .map(objectRecord)+ .slice(0, 64)+ .map((child, childIndex) => ({+ id:+ stringValue(child.childId) ?? `${runId}:delegation:${childIndex}`,+ title: stringValue(child.role) ?? "Subagent",+ status: stringValue(child.status) ?? "unknown",+ metadata:+ [stringValue(child.model), stringValue(child.activitySummary)]+ .filter(Boolean)+ .join(" · ") || undefined,+ summary: stringValue(child.summary),+ }))+ : [];++ const rawOutput =+ entry.family === "tool_execution"+ ? stringValue(entry.payload.output)+ : undefined;+ const outputTruncated =+ entry.payload.outputTruncated === true ||+ Boolean(rawOutput && rawOutput.length > PROTOCOL_OUTPUT_MAX);+ const summary =+ entry.summary && entry.summary !== entry.eventType+ ? entry.summary+ : (stringValue(entry.payload.explanation) ??+ stringValue(entry.payload.progress) ??+ stringValue(entry.payload.message) ??+ stringValue(entry.payload.summary));++ return {+ id: `${runId}:provider:${providerActivityKey(entry)}:${index}`,+ kind: "protocol",+ surface: "provider_activity",+ family: entry.family,+ eventType: entry.eventType,+ status: entry.status,+ title: entry.title,+ summary,+ details,+ steps,+ links,+ children,+ output: rawOutput ? rawOutput.slice(0, PROTOCOL_OUTPUT_MAX) : undefined,+ outputTruncated,+ transcriptIndex: index,+ };+}++function providerItemDetail(+ item: TaskChatProviderActivityItem,+ label: string,+): string | undefined {+ return item.details.find((detail) => detail.label === label)?.value;+}++function meaningfulProviderToolSummary(value: string | undefined): boolean {+ return Boolean(+ value && !isGenericToolName(value) && !/^tool(?:\s+|_)call\b/i.test(value),+ );+}++/**+ * Provider lifecycle records are deltas. A terminal update owns status and+ * output, while earlier identity/progress fields survive when later frames+ * omit them or carry ACPX's literal `tool call` placeholder.+ */+function mergeProviderActivityItem(+ previous: TaskChatProviderActivityItem,+ incoming: TaskChatProviderActivityItem,+): TaskChatProviderActivityItem {+ if (+ previous.family !== "tool_execution" ||+ incoming.family !== "tool_execution"+ ) {+ return { ...incoming, id: previous.id };+ }+ const details = new Map(+ previous.details.map((detail) => [detail.label, detail]),+ );+ const incomingName = providerItemDetail(incoming, "Name");+ const genericIncomingIdentity = isGenericToolName(incomingName);+ const identityLabels = new Set([+ "Name",+ "Transport",+ "Namespace",+ "Operation",+ "Target",+ ]);+ for (const detail of incoming.details) {+ if (+ identityLabels.has(detail.label) &&+ genericIncomingIdentity &&+ details.has(detail.label)+ ) {+ continue;+ }+ if (+ detail.label === "Progress" &&+ !meaningfulProviderToolSummary(detail.value) &&+ details.has("Progress")+ ) {+ continue;+ }+ details.set(detail.label, detail);+ }+ return {+ ...incoming,+ id: previous.id,+ summary: meaningfulProviderToolSummary(incoming.summary)+ ? incoming.summary+ : previous.summary,+ details: [...details.values()],+ };+}/** Result content → the expandable mono detail block (clipped, trimmed). */function formatToolResultDetail(content: unknown): string | undefined {@@ -146,7 +547,9 @@ function formatToolResultDetail(content: unknown): string | undefined {const text = typeof content === "string" ? content : String(content);const trimmed = text.trim();if (!trimmed) return undefined;- return trimmed.length > DETAIL_MAX ? `${trimmed.slice(0, DETAIL_MAX)}\n…` : trimmed;+ return trimmed.length > DETAIL_MAX+ ? `${trimmed.slice(0, DETAIL_MAX)}\n…`+ : trimmed;}interface TranscriptAdapterOptions {@@ -167,6 +570,7 @@ export function transcriptToTaskChatItems(): TaskChatItem[] {const items: TaskChatItem[] = [];const toolIndexById = new Map<string, number>();+ const protocolIndexByKey = new Map<string, number>();const thinkingStartTs = new Map<number, string>();let lastToolIndex = -1;let thinkingIndex = -1;@@ -174,9 +578,17 @@ export function transcriptToTaskChatItems(let messageIndex = -1;let messageChannel: "progress" | "final" | "unknown" | undefined;- const resetInline = () => {+ const finishThinking = () => {+ if (thinkingIndex >= 0) {+ const item = items[thinkingIndex];+ if (item?.kind === "thinking") item.streaming = false;+ }thinkingIndex = -1;thinkingChannel = undefined;+ };++ const resetInline = () => {+ finishThinking();messageIndex = -1;messageChannel = undefined;};@@ -184,42 +596,61 @@ export function transcriptToTaskChatItems(for (const [i, entry] of entries.entries()) {switch (entry.kind) {case "thinking": {- if (!entry.text) break;- const channel = entry.channel;- if (thinkingIndex >= 0 && thinkingChannel === channel) {+ const lifecycleOnly = !entry.text;+ if (thinkingIndex >= 0 && thinkingChannel === entry.channel) {const it = items[thinkingIndex];if (it.kind === "thinking") {- it.lines.push(...entry.text.split("\n"));+ if (entry.text) {+ appendThinkingText(it.lines, entry.text, entry.delta);+ it.lifecycleOnly = false;+ }+ it.transcriptIndex = i;const startTs = thinkingStartTs.get(thinkingIndex);const label = thoughtDurationLabel(startTs, entry.ts);if (label) it.summaryLabel = label;+ if (entry.lifecycle === "completed") it.streaming = false;}} else {+ // A reasoning item is active only until the provider moves on to a+ // different reasoning channel or another transcript surface. ACPX+ // does not always send an explicit completed lifecycle frame, so+ // waiting for one leaves every earlier brain blue and shimmering.+ finishThinking();items.push({id: `${runId}:think:${i}`,kind: "thinking",- lines: entry.text.split("\n"),- streaming: running,+ lines: entry.text ? entry.text.split("\n") : [],+ streaming: running && entry.lifecycle !== "completed",// Settled history folds its thinking behind the header (v7);// the in-flight run streams it expanded.collapsed: !running,- channel,+ channel: entry.channel,+ lifecycleOnly,+ transcriptIndex: i,});thinkingIndex = items.length - 1;- thinkingChannel = channel;+ thinkingChannel = entry.channel;thinkingStartTs.set(thinkingIndex, entry.ts);messageIndex = -1;messageChannel = undefined;}+ if (entry.lifecycle === "completed") {+ finishThinking();+ }break;}case "assistant": {if (!entry.text) break;+ finishThinking();const channel = entry.channel;if (messageIndex >= 0 && messageChannel === channel) {const it = items[messageIndex];- if (it.kind === "message") it.text += entry.text;+ if (it.kind === "message") {+ it.text += entry.text;+ it.transcriptIndex = i;+ }} else {+ finishThinking();const atMs = Date.parse(entry.ts);items.push({id: `${runId}:msg:${i}`,@@ -229,22 +660,23 @@ export function transcriptToTaskChatItems(text: entry.text,channel,streaming: running,- // Everything the agent says inside a run turn is self-talk until it- // lands as the posted comment — live and history tag it alike.+ // Explicit final-answer items stream durably. Unclassified text+ // remains transient for backwards compatibility and fail-closed+ // handling of a delta whose start metadata was missed.interstitial: channel !== "final",atMs: Number.isFinite(atMs) ? atMs : undefined,+ transcriptIndex: i,});messageIndex = items.length - 1;messageChannel = channel;- thinkingIndex = -1;- thinkingChannel = undefined;}break;}case "tool_call": {const toolCallId = entry.toolUseId || `tool-${i}`;const existingIndex = toolIndexById.get(toolCallId);- const existing = existingIndex != null ? items[existingIndex] : undefined;+ const existing =+ existingIndex != null ? items[existingIndex] : undefined;if (existing?.kind === "tool") {// tool_call_update for a call already in the list: merge. Updates// often omit the title (acpx fills in a literal "tool call"), so a@@ -281,14 +713,24 @@ export function transcriptToTaskChatItems(if (idx != null) {const existing = items[idx];if (existing.kind === "tool") {- existing.status = entry.isError ? "failed" : "completed";- if (isGenericToolName(existing.rawName) && !isGenericToolName(entry.toolName)) {+ existing.status = entry.delta+ ? "in_progress"+ : entry.isError+ ? "failed"+ : "completed";+ if (+ isGenericToolName(existing.rawName) &&+ !isGenericToolName(entry.toolName)+ ) {existing.name = toolDisplayName(entry.toolName);existing.rawName = entry.toolName;}- if (!existing.detail) {- const detail = formatToolResultDetail(entry.content);- if (detail) existing.detail = detail;+ const detail = formatToolResultDetail(entry.content);+ if (detail) {+ existing.detail =+ entry.delta && existing.detail+ ? `${existing.detail}${detail}`+ : detail;}}}@@ -296,10 +738,31 @@ export function transcriptToTaskChatItems(break;}case "diff": {- const line = { kind: diffKind(entry.changeType), text: entry.text ?? "" };+ if (entry.changeType === "file_header") {+ if (lastToolIndex >= 0 && items[lastToolIndex].kind === "tool") {+ const tool = items[lastToolIndex] as TaskChatToolItem;+ tool.diff = tool.diff ?? {+ path: entry.text,+ added: 0,+ removed: 0,+ lines: [],+ };+ tool.diff.path = entry.text;+ }+ resetInline();+ break;+ }+ const line = {+ kind: diffKind(entry.changeType),+ text: entry.text ?? "",+ };if (lastToolIndex >= 0 && items[lastToolIndex].kind === "tool") {const tool = items[lastToolIndex] as TaskChatToolItem;- const diff: TaskChatDiff = tool.diff ?? { added: 0, removed: 0, lines: [] };+ const diff: TaskChatDiff = tool.diff ?? {+ added: 0,+ removed: 0,+ lines: [],+ };diff.lines = diff.lines ?? [];diff.lines.push(line);if (line.kind === "add") diff.added += 1;@@ -322,6 +785,153 @@ export function transcriptToTaskChatItems(resetInline();break;}+ case "provider_activity": {+ const key = `provider:${providerActivityKey(entry)}`;+ const item = providerActivityItem(entry, runId, i);+ const existingIndex = protocolIndexByKey.get(key);+ if (existingIndex == null) {+ items.push(item);+ protocolIndexByKey.set(key, items.length - 1);+ } else {+ const existing = items[existingIndex];+ items[existingIndex] =+ existing.kind === "protocol" &&+ existing.surface === "provider_activity"+ ? mergeProviderActivityItem(existing, item)+ : item;+ }+ resetInline();+ break;+ }+ case "workspace_change": {+ const key = `workspace:${entry.changeSetId}`;+ const item: TaskChatProtocolItem = {+ id: `${runId}:workspace:${entry.changeSetId}`,+ kind: "protocol",+ surface: "workspace_change",+ changeSetId: entry.changeSetId,+ revision: entry.revision,+ source: entry.source,+ complete: entry.complete,+ files: entry.files.map((file) => ({+ ...file,+ diff:+ file.diff == null+ ? null+ : file.diff.slice(0, PROTOCOL_OUTPUT_MAX),+ })),+ totals: entry.totals,+ patchArtifactRef: entry.patchArtifactRef,+ };+ const existingIndex = protocolIndexByKey.get(key);+ if (existingIndex == null) {+ items.push(item);+ protocolIndexByKey.set(key, items.length - 1);+ } else {+ items[existingIndex] = { ...item, id: items[existingIndex].id };+ }+ resetInline();+ break;+ }+ case "workspace_file_reference": {+ const key = `workspace-file:${entry.referenceId}`;+ const item: TaskChatProtocolItem = {+ id: `${runId}:workspace-file:${entry.referenceId}`,+ kind: "protocol",+ surface: "workspace_file",+ referenceId: entry.referenceId,+ source: entry.source,+ path: entry.path,+ displayName: entry.displayName,+ mediaType: entry.mediaType,+ presentation: entry.presentation,+ line: entry.line,+ preview:+ entry.preview == null+ ? null+ : entry.preview.slice(0, PROTOCOL_OUTPUT_MAX),+ previewTruncated:+ entry.previewTruncated ||+ Boolean(+ entry.preview && entry.preview.length > PROTOCOL_OUTPUT_MAX,+ ),+ };+ const existingIndex = protocolIndexByKey.get(key);+ if (existingIndex == null) {+ items.push(item);+ protocolIndexByKey.set(key, items.length - 1);+ } else {+ items[existingIndex] = { ...item, id: items[existingIndex].id };+ }+ resetInline();+ break;+ }+ case "runtime_request": {+ const key = `runtime-request:${entry.requestId}`;+ const item: TaskChatProtocolItem = {+ id: `${runId}:runtime-request:${entry.requestId}`,+ kind: "protocol",+ surface: "runtime_request",+ runId,+ requestId: entry.requestId,+ requestKind: entry.requestKind,+ turnId: entry.turnId,+ requestType: entry.requestType,+ status: entry.status,+ prompt: entry.prompt,+ choices: entry.choices,+ fields: entry.fields,+ questionSet: entry.questionSet,+ resolvedAction: entry.resolvedAction,+ response: entry.response,+ };+ const existingIndex = protocolIndexByKey.get(key);+ if (existingIndex == null) {+ items.push(item);+ protocolIndexByKey.set(key, items.length - 1);+ } else {+ items[existingIndex] = { ...item, id: items[existingIndex].id };+ }+ resetInline();+ break;+ }+ case "run_result": {+ items.push({+ id: `${runId}:result:${i}`,+ kind: "protocol",+ surface: "run_result",+ disposition: entry.disposition,+ summary: entry.summary,+ objectiveSatisfied: entry.objectiveSatisfied,+ verification: entry.verification,+ remainingWork: entry.remainingWork,+ blocker: entry.blocker,+ artifacts: entry.artifacts,+ });+ resetInline();+ break;+ }+ case "run_terminal": {+ const key = "run-terminal";+ const item: TaskChatProtocolItem = {+ id: `${runId}:terminal`,+ kind: "protocol",+ surface: "run_terminal",+ turnState: entry.turnState,+ runState: entry.runState,+ disposition: entry.disposition,+ stopReason: entry.stopReason,+ };+ const existingIndex = protocolIndexByKey.get(key);+ if (existingIndex == null) {+ items.push(item);+ protocolIndexByKey.set(key, items.length - 1);+ } else {+ items[existingIndex] = item;+ }+ resetInline();+ break;+ }case "result": {if (entry.subtype !== "paperclip_runner_usage" &&@@ -359,30 +969,308 @@ export function transcriptToTaskChatItems(}// Only the message still open at the transcript tail is streaming; earlier- // self-talk is finished and nests as a settled row even mid-run.+ // provider commentary is complete but remains a durable phase boundary.if (running) {for (const [idx, it] of items.entries()) {if (it.kind === "message" && idx !== messageIndex) it.streaming = false;}+ } else {+ // A terminal transcript cannot retain live spinners forever when a+ // provider disconnects or the operator cancels while a tool is active.+ // Preserve the unfinished lifecycle honestly instead of inventing a+ // success/failure result the provider never emitted.+ for (const item of items) {+ if (+ item.kind === "tool" &&+ (item.status === "pending" || item.status === "in_progress")+ ) {+ item.status = "interrupted";+ item.detail = item.detail+ ? `${item.detail}\nInterrupted before the provider reported completion.`+ : "Interrupted before the provider reported completion.";+ } else if (+ item.kind === "protocol" &&+ item.surface === "provider_activity" &&+ item.status === "running"+ ) {+ item.status = "interrupted";+ item.summary = item.summary+ ? `${item.summary} · Interrupted before completion.`+ : "Interrupted before completion.";+ } else if (+ item.kind === "protocol" &&+ item.surface === "runtime_request" &&+ item.status === "pending"+ ) {+ item.status = "cancelled";+ }+ }}return items;}/**- * A settled run's nested children: activity phases containing chronological- * tool rows and their historical interstitial boundary. The final reply is- * excluded because its posted comment is canonical. Thinking stays in the- * run log / classic transcript.+ * A settled run's chronological children. Commentary remains attached to the+ * phase it introduced, while terminal runtime-request receipts keep the slot+ * where the request first appeared. Final text is excluded because the turn's+ * dedicated response slot or posted comment owns it.*/-export function settledRunChildren(parsed: readonly TaskChatItem[]): TaskChatTurnChildItem[] {- return buildActivityPhases(parsed, false);+export function settledRunChildren(+ parsed: readonly TaskChatItem[],+): TaskChatTurnChildItem[] {+ return buildTurnTimelineRows(parsed, false);+}++/**+ * Keep the paperclip runner's expanded activity history focused on work the+ * user can act on. The normalized transcript remains lossless; this is only a+ * presentation filter for the new-runner turn surface. Legacy adapters keep+ * their existing lifecycle and usage rows.+ */+export function paperclipRunnerHistoryItems(+ parsed: readonly TaskChatItem[],+): TaskChatItem[] {+ return parsed.filter((item) => {+ if (item.kind === "usage") return false;+ if (item.kind !== "marker") return true;+ if (item.variant === "session_start") return false;+ return (+ item.variant !== "turn_boundary" ||+ (item.label !== "Turn started" && item.label !== "Turn completed")+ );+ });+}++/**+ * Semantic rows for the Paperclip runner's Codex-style activity disclosure.+ *+ * This is intentionally narrower than the stored transcript and the runner+ * inspector: it keeps work a person can understand or act on while excluding+ * transport/lifecycle bookkeeping, terminal authority, and the final+ * response. Logical provider/tool lifecycles have already been coalesced by+ * `transcriptToTaskChatItems`, so each returned item is one visible "thing".+ */+export function paperclipRunnerActivityItems(+ parsed: readonly TaskChatItem[],+): TaskChatItem[] {+ const hasAggregateWorkspaceChange = parsed.some(+ (item) => item.kind === "protocol" && item.surface === "workspace_change",+ );+ return parsed.filter((item) => {+ switch (item.kind) {+ case "message":+ return Boolean(item.interstitial && item.text.trim());+ case "thinking":+ // A textless reasoning lifecycle drives the live "Thinking…" label,+ // but repeating it as an empty child row adds no information.+ return item.lines.some((line) => line.trim().length > 0);+ case "tool": {+ const normalizedName = (item.rawName ?? item.name)+ .replaceAll("-", "_")+ .toLowerCase();+ if (+ hasAggregateWorkspaceChange &&+ (normalizedName === "file_change" || normalizedName === "filechange")+ ) return false;+ return normalizedName !== "paperclip_finish";+ }+ case "marker":+ return item.variant === "interrupted";+ case "protocol":+ if (+ hasAggregateWorkspaceChange &&+ item.surface === "provider_activity" &&+ item.family === "tool_execution"+ ) {+ const presentation = toolActivityPresentation({+ name: providerItemDetail(item, "Name"),+ transport: providerItemDetail(item, "Transport"),+ namespace: providerItemDetail(item, "Namespace"),+ operation: providerItemDetail(item, "Operation"),+ target: providerItemDetail(item, "Target"),+ progress: providerItemDetail(item, "Progress"),+ });+ if (presentation.summaryGroup.key === "file_change") return false;+ }+ return (+ item.surface === "provider_activity" ||+ item.surface === "workspace_change" ||+ item.surface === "workspace_file" ||+ item.surface === "resource"+ );+ case "usage":+ return true;+ case "status":+ case "activity_phase":+ case "interaction":+ case "turn":+ case "brief":+ case "plan_document":+ return false;+ }+ });+}++/**+ * Ordered input for the Paperclip Runner task-turn timeline. This keeps the+ * semantic activity filter above, but retains runtime-request lifecycles so+ * the shared projector can use each request as a phase boundary and place its+ * terminal receipt at the request's first-seen position.+ */+export function paperclipRunnerTimelineItems(+ parsed: readonly TaskChatItem[],+): TaskChatItem[] {+ const activityIds = new Set(+ paperclipRunnerActivityItems(parsed).map((item) => item.id),+ );+ return parsed.filter(+ (item) =>+ activityIds.has(item.id) ||+ item.kind === "plan_document" ||+ (item.kind === "protocol" && item.surface === "runtime_request"),+ );+}++/**+ * Resolve the durable response owned by a Paperclip Runner turn. Provider final+ * text wins when present; yielded control-plane runs fall back to the accepted+ * run-result summary because those runs intentionally do not post a comment.+ */+export function paperclipRunnerFinalResponse(+ parsed: readonly TaskChatItem[],+ options?: {+ runId?: string;+ agentName?: string;+ fallbackSummary?: string | null;+ /** Structured summaries are terminal fallbacks, never live partial replies. */+ allowFallback?: boolean;+ },+): TaskChatMessageItem | undefined {+ for (let index = parsed.length - 1; index >= 0; index -= 1) {+ const item = parsed[index];+ if (+ item.kind === "message" &&+ item.channel === "final" &&+ item.text.trim()+ ) {+ return item;+ }+ }+ if (options?.allowFallback === false) return undefined;+ // Historical runner transcripts may contain a complete assistant reply from+ // before message channels were persisted. Keep that user-authored text as+ // the terminal response and do not replace it with a structured result+ // summary. Explicit progress text is intentionally excluded.+ for (let index = parsed.length - 1; index >= 0; index -= 1) {+ const item = parsed[index];+ if (+ item.kind === "message" &&+ item.channel !== "progress" &&+ item.text.trim()+ ) {+ return { ...item, channel: "final", interstitial: false, streaming: false };+ }+ }+ const runResult = [...parsed]+ .reverse()+ .find(+ (item): item is TaskChatRunResultItem =>+ item.kind === "protocol" &&+ item.surface === "run_result" &&+ Boolean(item.summary?.trim()),+ );+ const text = runResult?.summary?.trim() ?? options?.fallbackSummary?.trim();+ if (!text) return undefined;+ return {+ id: runResult+ ? `${runResult.id}:final-response`+ : `${options?.runId ?? "run"}:result-summary:final-response`,+ kind: "message",+ author: "agent",+ authorName: options?.agentName,+ text,+ channel: "final",+ streaming: false,+ };+}++/**+ * Materialize a saved plan at the tool boundary that created its revision.+ * The document query and transcript stream update independently, so folding+ * the document into the parsed turn gives live, settling, and replay the same+ * stable owner and DOM position.+ */+export function embedPlanDocumentAtWriteBoundary(+ parsed: readonly TaskChatItem[],+ plan: TaskChatPlanDocumentItem,+): TaskChatItem[] {+ const withoutPlan = parsed.filter((item) => item.id !== plan.id);+ let writeIndex = -1;+ for (let index = 0; index < withoutPlan.length; index += 1) {+ const item = withoutPlan[index];+ const name =+ item.kind === "tool"+ ? (item.rawName ?? item.name)+ : item.kind === "protocol" &&+ item.surface === "provider_activity" &&+ item.family === "tool_execution"+ ? providerItemDetail(item, "Name")+ : null;+ if (!name) continue;+ const normalizedName = name.replaceAll("-", "_").toLowerCase();+ if (normalizedName === "write_document") writeIndex = index;+ }+ if (writeIndex < 0) return withoutPlan;+ return [+ ...withoutPlan.slice(0, writeIndex + 1),+ plan,+ ...withoutPlan.slice(writeIndex + 1),+ ];}-function phaseSummary(items: readonly (TaskChatToolItem | { kind: "usage" })[]): string {+function phaseSummary(+ items: ReadonlyArray<TaskChatActivityPhaseItem["items"][number]>,+): string {const counts = new Map<string, number>();+ const providerCounts = new Map<+ TaskChatProviderActivityItem["family"],+ number+ >();+ const providerToolGroups = new Map<string, number>();+ let providerToolActions = 0;let generic = 0;+ let workspaceFiles = 0;for (const item of items) {+ if (item.kind === "protocol") {+ if (item.surface === "provider_activity") {+ providerCounts.set(+ item.family,+ (providerCounts.get(item.family) ?? 0) + 1,+ );+ if (item.family === "tool_execution") {+ const presentation = toolActivityPresentation({+ name: providerItemDetail(item, "Name"),+ transport: providerItemDetail(item, "Transport"),+ namespace: providerItemDetail(item, "Namespace"),+ operation: providerItemDetail(item, "Operation"),+ target: providerItemDetail(item, "Target"),+ progress: providerItemDetail(item, "Progress"),+ });+ const summaryGroup = presentation.summaryGroup;+ providerToolGroups.set(+ summaryGroup.key,+ (providerToolGroups.get(summaryGroup.key) ?? 0) + 1,+ );+ providerToolActions += 1;+ }+ } else if (item.surface === "workspace_change") {+ workspaceFiles += item.totals.files || item.files.length;+ } else if (item.surface === "workspace_file") {+ workspaceFiles += 1;+ }+ continue;+ }if (item.kind !== "tool") continue;if (isGenericToolName(item.rawName ?? item.name)) {generic += 1;@@ -391,37 +1279,240 @@ function phaseSummary(items: readonly (TaskChatToolItem | { kind: "usage" })[]):const family = toolTaxonomy(item.rawName ?? item.name).family;counts.set(family, (counts.get(family) ?? 0) + 1);}- const phrases: string[] = [];- const add = (family: string, verb: string, singular: string, plural: string) => {+ const phrases: Array<{ text: string; count: number }> = [];+ const add = (+ family: string,+ singular: string,+ plural: (count: number) => string,+ ) => {const count = counts.get(family) ?? 0;- if (count) phrases.push(`${verb} ${count} ${count === 1 ? singular : plural}`);+ if (count)+ phrases.push({ text: count === 1 ? singular : plural(count), count });};- add("read", "Read", "file", "files");- add("edit", "Edited", "file", "files");- add("terminal", "Ran", "command", "commands");+ add("read", "Read a file", (count) => `Read ${count} files`);+ add("edit", "Edited a file", (count) => `Edited ${count} files`);+ add("terminal", "Ran a command", (count) => `Ran ${count} commands`);const searched = (counts.get("grep") ?? 0) + (counts.get("search") ?? 0);- if (searched) phrases.push(`Searched ${searched} ${searched === 1 ? "time" : "times"}`);+ if (searched)+ phrases.push({+ text: searched === 1 ? "Searched once" : `Searched ${searched} times`,+ count: searched,+ });const known = new Set(["read", "edit", "terminal", "grep", "search"]);- const other = [...counts].reduce((n, [family, count]) => n + (known.has(family) ? 0 : count), 0) + generic;- if (other) phrases.push(`Called ${other} ${other === 1 ? "tool" : "tools"}`);- return phrases.join(", ") || "No tool activity";+ const other =+ [...counts].reduce(+ (n, [family, count]) => n + (known.has(family) ? 0 : count),+ 0,+ ) + generic;+ if (other)+ phrases.push({+ text: other === 1 ? "Used a tool" : `Used ${other} tools`,+ count: other,+ });+ const providerCount = (family: TaskChatProviderActivityItem["family"]) =>+ providerCounts.get(family) ?? 0;+ const addProvider = (+ family: TaskChatProviderActivityItem["family"],+ singular: string,+ plural: (count: number) => string,+ ) => {+ const count = providerCount(family);+ if (count)+ phrases.push({ text: count === 1 ? singular : plural(count), count });+ };+ addProvider("plan", "Updated the plan", (count) => `Updated ${count} plans`);+ addProvider(+ "research",+ "Searched once",+ (count) => `Searched ${count} times`,+ );+ addProvider(+ "delegation",+ "Used a subagent",+ (count) => `Used ${count} subagents`,+ );+ addProvider(+ "model_identity",+ "Updated the model",+ (count) => `Updated the model ${count} times`,+ );+ addProvider(+ "context",+ "Compacted context",+ (count) => `Compacted context ${count} times`,+ );+ addProvider(+ "artifact",+ "Handled an artifact",+ (count) => `Handled ${count} artifacts`,+ );+ addProvider(+ "review",+ "Changed review mode",+ (count) => `Changed review mode ${count} times`,+ );+ addProvider("hook", "Ran a hook", (count) => `Ran ${count} hooks`);+ addProvider(+ "memory",+ "Referenced memory",+ (count) => `Referenced memory ${count} times`,+ );+ addProvider(+ "safety",+ "Ran a safety review",+ (count) => `Ran ${count} safety reviews`,+ );+ addProvider(+ "terminal",+ "Sent terminal input",+ (count) => `Sent terminal input ${count} times`,+ );+ addProvider("wait", "Waited", (count) => `Waited ${count} times`);+ addProvider(+ "provider_notice",+ "Received a provider notice",+ (count) => `Received ${count} provider notices`,+ );+ // A canonical tool-execution row can be the only tool representation for a+ // provider. Avoid double-counting when the adapter also produced native+ // TaskChatToolItems for the same executions.+ const nativeToolCount = [...counts.values()].reduce(+ (total, count) => total + count,+ generic,+ );+ if (nativeToolCount === 0 && providerToolActions > 0) {+ for (const [key, count] of providerToolGroups) {+ let text: string;+ switch (key) {+ case "command":+ text = count === 1 ? "Ran a command" : `Ran ${count} commands`;+ break;+ case "read":+ text = count === 1 ? "Read a file" : `Read ${count} files`;+ break;+ case "search":+ text = count === 1 ? "Searched once" : `Searched ${count} times`;+ break;+ case "file_change":+ text = count === 1 ? "Edited a file" : `Edited ${count} files`;+ break;+ case "delegation":+ text = count === 1 ? "Used a subagent" : `Used ${count} subagents`;+ break;+ case "wait":+ text = count === 1 ? "Waited" : `Waited ${count} times`;+ break;+ case "tool_search":+ text =+ count === 1+ ? "Searched available tools"+ : `Searched available tools ${count} times`;+ break;+ case "paperclip_read":+ text =+ count === 1+ ? "Read from Paperclip"+ : `Read from Paperclip ${count} times`;+ break;+ case "task_operation":+ text =+ count === 1 ? "Used Paperclip" : `Used Paperclip ${count} times`;+ break;+ default:+ text = count === 1 ? "Used a tool" : `Used ${count} tools`;+ }+ phrases.push({+ text,+ count,+ });+ }+ }+ if (workspaceFiles > 0)+ phrases.push({+ text:+ workspaceFiles === 1+ ? "Changed a file"+ : `Changed ${workspaceFiles} files`,+ count: workspaceFiles,+ });+ if (phrases.length > 0) {+ const visible = phrases.slice(0, 3);+ const hidden = phrases+ .slice(3)+ .reduce((total, phrase) => total + phrase.count, 0);+ const summary = visible+ .map((phrase, index) =>+ index === 0+ ? phrase.text+ : phrase.text.charAt(0).toLowerCase() + phrase.text.slice(1),+ )+ .join(", ");+ return `${summary}${hidden > 0 ? `, +${hidden} more` : ""}`;+ }+ const protocolCount = items.filter((item) => item.kind === "protocol").length;+ if (protocolCount > 0)+ return protocolCount === 1+ ? "Runner activity"+ : `${protocolCount} runner updates`;+ if (items.some((item) => item.kind === "thinking")) return "Reasoning";+ const interrupted = items.find(+ (item) => item.kind === "marker" && item.variant === "interrupted",+ );+ return interrupted?.kind === "marker"+ ? interrupted.label+ : "No tool activity";}-/** Segment parsed transcript rows at assistant boundaries with stable run-derived ids. */-export function buildActivityPhases(+/**+ * Project one turn into its durable chronological rows.+ *+ * Commentary starts a sticky phase. Consecutive diagnostic activity belongs+ * to that phase until the next commentary or runtime request. Request lifecycle+ * updates are coalesced to their latest state but emitted at the first request+ * slot; pending requests stay composer-only while still breaking activity+ * grouping at that slot.+ */+export function buildTurnTimelineRows(parsed: readonly TaskChatItem[],running: boolean,-): TaskChatActivityPhaseItem[] {- const phases: TaskChatActivityPhaseItem[] = [];+): TaskChatTurnChildItem[] {+ const rows: TaskChatTurnChildItem[] = [];let current: TaskChatActivityPhaseItem | null = null;+ const latestRequestByKey = new Map<string, TaskChatProtocolItem>();+ for (const item of parsed) {+ if (item.kind !== "protocol" || item.surface !== "runtime_request")+ continue;+ latestRequestByKey.set(`${item.runId}:${item.requestId}`, item);+ }+ const seenRequests = new Set<string>();const ensureOpening = (seed: string) => {if (!current) {- current = { id: `${seed}:phase:opening`, kind: "activity_phase", items: [], summary: "", active: false };- phases.push(current);+ current = {+ id: `${seed}:phase:opening`,+ kind: "activity_phase",+ items: [],+ summary: "",+ active: false,+ };+ rows.push(current);}return current;};- const lastVisible = [...parsed].reverse().find((item) => item.kind !== "thinking");+ const legacyReplyBoundary = [...parsed]+ .reverse()+ .find((item) => {+ if (item.kind === "usage" || item.kind === "status") return false;+ if (item.kind === "marker") {+ return item.variant === "interrupted";+ }+ if (item.kind === "protocol") {+ return (+ item.surface === "provider_activity" ||+ item.surface === "runtime_request"+ );+ }+ return true;+ });for (const item of parsed) {if (item.kind === "message") {// Explicit final-channel replies remain canonical even when a later@@ -429,7 +1520,8 @@ export function buildActivityPhases(// the last-visible fallback until the posted reply lands.const explicitFinal = item.channel === "final" || item.interstitial === false;const legacyTrailingReply =- (item.channel == null || item.channel === "unknown") && item === lastVisible;+ (item.channel == null || item.channel === "unknown") &&+ item === legacyReplyBoundary;if (!running && (explicitFinal || legacyTrailingReply)) continue;current = {id: `${item.id}:phase`,@@ -439,17 +1531,56 @@ export function buildActivityPhases(summary: "",active: false,};- phases.push(current);- } else if (item.kind === "tool" || item.kind === "usage") {+ rows.push(current);+ } else if (item.kind === "protocol" && item.surface === "runtime_request") {+ const key = `${item.runId}:${item.requestId}`;+ if (seenRequests.has(key)) continue;+ seenRequests.add(key);+ current = null;+ const latest = latestRequestByKey.get(key);+ if (+ latest?.surface === "runtime_request" &&+ latest.status !== "pending"+ ) {+ rows.push(latest.id === item.id ? latest : { ...latest, id: item.id });+ }+ } else if (item.kind === "protocol" && item.surface === "workspace_change") {+ current = null;+ rows.push(item);+ } else if (item.kind === "plan_document") {+ current = null;+ rows.push(item);+ } else if (+ item.kind === "tool" ||+ item.kind === "usage" ||+ item.kind === "thinking" ||+ item.kind === "marker" ||+ item.kind === "protocol"+ ) {ensureOpening(item.id).items.push(item);}}- for (const phase of phases) phase.summary = phaseSummary(phase.items);- const meaningful = phases.filter((phase) => phase.interstitial || phase.items.length > 0);- if (running && meaningful.length) meaningful[meaningful.length - 1].active = true;+ const meaningful = rows.filter(+ (row) =>+ row.kind !== "activity_phase" || row.interstitial || row.items.length > 0,+ );+ for (const row of meaningful) {+ if (row.kind === "activity_phase") row.summary = phaseSummary(row.items);+ }+ if (running && current && meaningful.includes(current)) current.active = true;return meaningful;}+/** Segment parsed transcript rows at assistant/request boundaries. */+export function buildActivityPhases(+ parsed: readonly TaskChatItem[],+ running: boolean,+): TaskChatActivityPhaseItem[] {+ return buildTurnTimelineRows(parsed, running).filter(+ (item): item is TaskChatActivityPhaseItem => item.kind === "activity_phase",+ );+}+function formatDurationLabel(ms: number): string | undefined {if (!Number.isFinite(ms) || ms <= 0) return undefined;const totalSec = Math.round(ms / 1000);@@ -467,7 +1598,9 @@ function formatTokensLabel(tokens: number): string | undefined {}/** First→last ts span of a transcript, or undefined when unknowable. */-function transcriptSpanMs(entries: readonly TranscriptEntry[]): number | undefined {+function transcriptSpanMs(+ entries: readonly TranscriptEntry[],+): number | undefined {if (entries.length < 2) return undefined;const first = Date.parse(entries[0].ts);const last = Date.parse(entries[entries.length - 1].ts);@@ -508,7 +1641,8 @@ export function buildTurnSummary(}const durationMs = opts.durationMs ?? transcriptSpanMs(entries);return {- durationLabel: durationMs != null ? formatDurationLabel(durationMs) : undefined,+ durationLabel:+ durationMs != null ? formatDurationLabel(durationMs) : undefined,toolCount: toolIds.size,added,removed,@@ -540,14 +1674,16 @@ export function buildMergedTurnSummary(all.push(...part.entries);if (part.failed) failed = true;const d = part.durationMs ?? transcriptSpanMs(part.entries);- if (d != null && Number.isFinite(d)) durationMs = (durationMs ?? 0) + Math.max(0, d);+ if (d != null && Number.isFinite(d))+ durationMs = (durationMs ?? 0) + Math.max(0, d);}// durationMs: 0 suppresses the concatenated-span fallback (which would count// the gap between runs); the summed label is applied over it below.const counts = buildTurnSummary(all, { durationMs: 0, failed });return {...counts,- durationLabel: durationMs != null ? formatDurationLabel(durationMs) : undefined,+ durationLabel:+ durationMs != null ? formatDurationLabel(durationMs) : undefined,};}@@ -598,7 +1734,10 @@ export const ISSUE_BRIEF_ITEM_ID = "issue-brief";* turn whose startMs predates every backbone entry (F15) lands below the* description bubble.*/-export function prependIssueBrief(items: TaskChatItem[], hasBrief: boolean): TaskChatItem[] {+export function prependIssueBrief(+ items: TaskChatItem[],+ hasBrief: boolean,+): TaskChatItem[] {if (!hasBrief) return items;return [{ id: ISSUE_BRIEF_ITEM_ID, kind: "brief" }, ...items];}@@ -636,12 +1775,19 @@ export function coalesceSettledTurns(const meta = metaFor(item.id);const held = heldIdx >= 0 ? (out[heldIdx] as TaskChatTurnItem) : null;const heldMeta = held ? metaFor(held.id) : undefined;- if (held && meta && heldMeta && meta.agentKey && meta.agentKey === heldMeta.agentKey) {+ if (+ held &&+ meta &&+ heldMeta &&+ meta.agentKey &&+ meta.agentKey === heldMeta.agentKey+ ) {out.splice(heldIdx, 1);const parts = [...heldMeta.parts, ...meta.parts];out.push({...held,items: [...held.items, ...item.items],+ finalResponse: item.finalResponse ?? held.finalResponse,animateFold: held.animateFold || item.animateFold || undefined,summary: buildMergedTurnSummary(parts),});@@ -656,8 +1802,15 @@ export function coalesceSettledTurns(if (item.kind === "message" && item.author === "agent") {// The same agent's reply bubble sits between its runs — keep merging// across it. A different agent's bubble ends the run of turns.- const heldMeta = heldIdx >= 0 ? metaFor((out[heldIdx] as TaskChatTurnItem).id) : undefined;- if (heldMeta?.agentName && item.authorName && item.authorName !== heldMeta.agentName) {+ const heldMeta =+ heldIdx >= 0+ ? metaFor((out[heldIdx] as TaskChatTurnItem).id)+ : undefined;+ if (+ heldMeta?.agentName &&+ item.authorName &&+ item.authorName !== heldMeta.agentName+ ) {heldIdx = -1;}} else {@@ -694,7 +1847,10 @@ export function attachSettledTurns() {const meta = metaById.get(item.id);const sameAgent =- meta != null && (meta.agentName == null || prev.authorName == null || meta.agentName === prev.authorName);+ meta != null &&+ (meta.agentName == null ||+ prev.authorName == null ||+ meta.agentName === prev.authorName);if (sameAgent) {out[out.length - 1] = { ...prev, attachedTurn: item };continue;@@ -744,7 +1900,8 @@ export function deriveRunStatusLabel(entries: readonly TranscriptEntry[]): {}}const target =- summarizeToolInput(entry.input) ?? (invocation ? clip(invocation, TARGET_MAX) : undefined);+ summarizeToolInput(entry.input) ??+ (invocation ? clip(invocation, TARGET_MAX) : undefined);const display = toolDisplayName(name);return {label: toolTaxonomy(name).verbLabel,@@ -777,6 +1934,8 @@ export function deriveRunStatusLabel(entries: readonly TranscriptEntry[]): {return { label: "Responding", selfTalk: selfTalk || undefined };}if (entry.kind === "thinking") return { label: "Thinking" };+ if (entry.kind === "system" && entry.text === "Reasoning started")+ return { label: "Thinking" };}return { label: "Running" };}diff --git a/ui/src/components/task-chat/useWindowAutoFollow.test.tsx b/ui/src/components/task-chat/useWindowAutoFollow.test.tsxindex ce84c32701..9d269015f1 100644--- a/ui/src/components/task-chat/useWindowAutoFollow.test.tsx+++ b/ui/src/components/task-chat/useWindowAutoFollow.test.tsx@@ -21,8 +21,17 @@ describe("useWindowAutoFollow", () => {function fakeWindowGeometry({ scrollHeight = 2000, innerHeight = 800 } = {}) {const el = document.scrollingElement ?? document.documentElement;- Object.defineProperty(el, "scrollHeight", { value: scrollHeight, configurable: true });+ let currentScrollHeight = scrollHeight;+ Object.defineProperty(el, "scrollHeight", {+ get: () => currentScrollHeight,+ configurable: true,+ });Object.defineProperty(window, "innerHeight", { value: innerHeight, configurable: true });+ return {+ setScrollHeight(value: number) {+ currentScrollHeight = value;+ },+ };}function setWindowScrollY(y: number) {@@ -95,6 +104,56 @@ describe("useWindowAutoFollow", () => {expect(scrollToCalls).toHaveLength(0);});+ it("follows document growth while pinned on mobile", async () => {+ let triggerResize = () => {};+ vi.stubGlobal(+ "ResizeObserver",+ class {+ constructor(callback: ResizeObserverCallback) {+ triggerResize = () =>+ callback([], this as unknown as ResizeObserver);+ }+ observe() {}+ disconnect() {}+ },+ );+ const geometry = fakeWindowGeometry();+ render(0);+ await flushRaf();+ await scrollWindowTo(1200);+ scrollToCalls = [];++ geometry.setScrollHeight(2300);+ triggerResize();++ expect(scrollToCalls).toContain(2300);+ });++ it("holds document position through mobile composer growth when scrolled up", async () => {+ let triggerResize = () => {};+ vi.stubGlobal(+ "ResizeObserver",+ class {+ constructor(callback: ResizeObserverCallback) {+ triggerResize = () =>+ callback([], this as unknown as ResizeObserver);+ }+ observe() {}+ disconnect() {}+ },+ );+ const geometry = fakeWindowGeometry();+ render(0);+ await flushRaf();+ await scrollWindowTo(100);+ scrollToCalls = [];++ geometry.setScrollHeight(2300);+ triggerResize();++ expect(scrollToCalls).toHaveLength(0);+ });+it("does nothing when disabled", () => {render(0, false);expect(scrollToCalls).toHaveLength(0);diff --git a/ui/src/components/task-chat/useWindowAutoFollow.ts b/ui/src/components/task-chat/useWindowAutoFollow.tsindex 8aa1ca30a9..58f6c3c5da 100644--- a/ui/src/components/task-chat/useWindowAutoFollow.ts+++ b/ui/src/components/task-chat/useWindowAutoFollow.ts@@ -43,6 +43,25 @@ export function useWindowAutoFollow(contentKey: unknown, enabled: boolean): voidreturn () => window.removeEventListener("scroll", onScroll);}, [enabled]);+ useLayoutEffect(() => {+ if (!enabled || typeof ResizeObserver === "undefined") return;+ const observed = document.body;+ let previousScrollHeight = scrollingElement()?.scrollHeight ?? null;+ const observer = new ResizeObserver(() => {+ const nextScrollHeight = scrollingElement()?.scrollHeight ?? null;+ if (+ nextScrollHeight == null ||+ nextScrollHeight === previousScrollHeight+ ) {+ return;+ }+ previousScrollHeight = nextScrollHeight;+ if (pinnedRef.current) scrollWindowToBottom();+ });+ observer.observe(observed);+ return () => observer.disconnect();+ }, [enabled]);+// Follow new content only when already pinned; otherwise hold position.useLayoutEffect(() => {if (!enabled) return;diff --git a/ui/src/components/task-side-panel/TaskDocumentPanel.tsx b/ui/src/components/task-side-panel/TaskDocumentPanel.tsxnew file mode 100644index 0000000000..3b38da9b89--- /dev/null+++ b/ui/src/components/task-side-panel/TaskDocumentPanel.tsx@@ -0,0 +1,103 @@+import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import type { IssueDocument } from "@paperclipai/shared";+import { FileQuestion, Loader2 } from "lucide-react";+import { ApiError } from "@/api/client";+import { issuesApi } from "@/api/issues";+import { DocumentAnnotationsCountChip, IssueDocumentAnnotations } from "@/components/IssueDocumentAnnotations";+import { MarkdownBody } from "@/components/MarkdownBody";+import { queryKeys } from "@/lib/queryKeys";+import { documentDisplayTitle } from "@/lib/issue-artifacts";+import { useLocation } from "@/lib/router";++export function TaskDocumentPanel({+ issueId,+ documentKey,+ initialDocument,+}: {+ issueId: string;+ documentKey: string;+ initialDocument?: IssueDocument;+}) {+ const location = useLocation();+ const [annotationPanelOpen, setAnnotationPanelOpen] = useState(false);+ const query = useQuery<IssueDocument | null>({+ queryKey: [...queryKeys.issues.documents(issueId), documentKey],+ queryFn: async () => {+ try {+ return await issuesApi.getDocument(issueId, documentKey);+ } catch (error) {+ if (error instanceof ApiError && error.status === 404) return null;+ throw error;+ }+ },+ initialData: initialDocument,+ });++ if (query.isLoading) {+ return (+ <div className="flex items-center gap-2 py-8 text-sm text-muted-foreground" role="status">+ <Loader2 className="size-4 animate-spin" aria-hidden />+ Loading document…+ </div>+ );+ }+ if (query.isError) {+ return (+ <div className="py-8 text-sm text-muted-foreground" role="alert">+ The document could not be loaded. Retry from the tab launcher or refresh the task.+ </div>+ );+ }+ const document = query.data;+ if (!document) {+ return (+ <div className="flex items-start gap-3 py-8 text-sm" role="status">+ <FileQuestion className="mt-0.5 size-5 shrink-0 text-muted-foreground" aria-hidden />+ <div className="space-y-1">+ <p className="font-medium">Document no longer available</p>+ <p className="text-muted-foreground">+ This tab is preserved so the missing resource is explicit. Close it or choose another document.+ </p>+ </div>+ </div>+ );+ }++ return (+ <article className="space-y-4">+ <header className="space-y-1">+ <h2 className="text-lg font-semibold">{documentDisplayTitle(document)}</h2>+ <div className="flex flex-wrap items-center gap-1 text-xs text-muted-foreground">+ <span>{`Revision ${document.latestRevisionNumber ?? 1}`}</span>+ <span aria-hidden>·</span>+ <span>{`Updated ${new Date(document.updatedAt).toLocaleString()}`}</span>+ <DocumentAnnotationsCountChip+ issueId={issueId}+ docKey={document.key}+ panelOpen={annotationPanelOpen}+ onToggle={() => setAnnotationPanelOpen((open) => !open)}+ />+ </div>+ </header>+ {document.body.trim() ? (+ <IssueDocumentAnnotations+ issueId={issueId}+ doc={document}+ bodyMarkdown={document.body}+ draftDirty={false}+ draftConflicted={false}+ historicalPreview={false}+ locationHash={location.hash}+ panelOpen={annotationPanelOpen}+ onPanelOpenChange={setAnnotationPanelOpen}+ panelPlacement="popover"+ >+ <MarkdownBody>{document.body}</MarkdownBody>+ </IssueDocumentAnnotations>+ ) : (+ <p className="text-sm text-muted-foreground">Document is empty.</p>+ )}+ </article>+ );+}diff --git a/ui/src/components/task-side-panel/TaskSidePanel.test.tsx b/ui/src/components/task-side-panel/TaskSidePanel.test.tsxnew file mode 100644index 0000000000..cb95325763--- /dev/null+++ b/ui/src/components/task-side-panel/TaskSidePanel.test.tsx@@ -0,0 +1,286 @@+// @vitest-environment jsdom++import { act, type ReactNode } from "react";+import { createRoot, type Root } from "react-dom/client";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { Issue, IssueDocument } from "@paperclipai/shared";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { TooltipProvider } from "@/components/ui/tooltip";+import {+ taskPanelDocumentTab,+ taskPanelPropertiesTab,+ writeTaskSidePanelState,+} from "@/lib/task-side-panel-state";+import { TaskSidePanel } from "./TaskSidePanel";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++class ResizeObserverStub {+ observe() {}+ unobserve() {}+ disconnect() {}+}++(globalThis as { ResizeObserver?: typeof ResizeObserver }).ResizeObserver = ResizeObserverStub as unknown as typeof ResizeObserver;++const fixture = vi.hoisted(() => ({+ documents: [] as IssueDocument[] | undefined,+ plan: null as IssueDocument | null | undefined,+}));++const routeFixture = vi.hoisted(() => ({+ location: {+ pathname: "/issues/PAP-1",+ search: "",+ hash: "",+ state: null as unknown,+ },+ navigate: vi.fn(),+}));++vi.mock("@/hooks/useIssueDocuments", () => ({+ useIssueDocuments: () => ({ data: fixture.documents }),+}));++vi.mock("@/hooks/useIssuePlanDocument", () => ({+ useIssuePlanDocument: () => ({ data: fixture.plan }),+}));++vi.mock("@/lib/router", () => ({+ useLocation: () => routeFixture.location,+ useNavigate: () => routeFixture.navigate,+}));++vi.mock("@/components/IssueProperties", () => ({+ IssueProperties: () => <div>Properties content</div>,+}));++vi.mock("@/components/issue-properties/IssuePropertiesArtifactsTab", () => ({+ IssuePropertiesArtifactsTab: () => <div>Artifacts content</div>,+}));++vi.mock("@/components/issue-properties/IssuePropertiesPlansTab", () => ({+ IssuePropertiesPlansTab: () => <div>Plan content</div>,+}));++vi.mock("@/components/WorkspaceFileBrowser", () => ({+ WorkspaceFileBrowser: () => <div>Files browser</div>,+}));++vi.mock("./TaskDocumentPanel", () => ({+ TaskDocumentPanel: ({ documentKey }: { documentKey: string }) => <div>{`Document ${documentKey}`}</div>,+}));++vi.mock("./TaskWorkspaceFilePanel", () => ({+ TaskWorkspaceFilePanel: () => <div>Workspace file</div>,+}));++function issue(overrides: Partial<Issue> = {}): Issue {+ return {+ id: "task-1",+ companyId: "company-1",+ title: "Portable tabs",+ workMode: "agent",+ ...overrides,+ } as Issue;+}++function issueDocument(key: string, title: string): IssueDocument {+ return {+ id: `document-${key}`,+ issueId: "task-1",+ key,+ title,+ body: `# ${title}`,+ latestRevisionNumber: 1,+ createdAt: "2026-08-23T12:00:00.000Z",+ updatedAt: "2026-08-23T12:00:00.000Z",+ } as unknown as IssueDocument;+}++describe("TaskSidePanel", () => {+ let root: Root;+ let container: HTMLDivElement;+ let queryClient: QueryClient;++ beforeEach(() => {+ window.localStorage.clear();+ fixture.documents = [];+ fixture.plan = null;+ routeFixture.location.search = "";+ window.history.replaceState(null, "", routeFixture.location.pathname);+ routeFixture.navigate.mockReset();+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ Element.prototype.scrollIntoView = vi.fn();+ HTMLElement.prototype.scrollTo = vi.fn();+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {+ callback(0);+ return 1;+ });+ });++ afterEach(() => {+ act(() => root.unmount());+ queryClient.clear();+ container.remove();+ vi.restoreAllMocks();+ });++ async function render(node: ReactNode) {+ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <TooltipProvider>{node}</TooltipProvider>+ </QueryClientProvider>,+ );+ });+ }++ function panel(props: Partial<Parameters<typeof TaskSidePanel>[0]> = {}) {+ return (+ <TaskSidePanel+ issue={issue()}+ accountScope="user-1"+ onUpdate={() => {}}+ fileTabsEnabled={false}+ inline+ {...props}+ />+ );+ }++ it("opens Properties on first visit", async () => {+ await render(panel());+ expect(container.querySelector('[role="tab"][aria-selected="true"]')?.textContent).toContain("Properties");+ expect(container.textContent).toContain("Properties content");+ });++ it("does not create a Plan tab for planning mode before a plan exists", async () => {+ await render(panel({ issue: issue({ workMode: "planning" }) }));+ expect(container.querySelector('[role="tab"][aria-selected="true"]')?.textContent).toContain("Properties");+ expect(container.querySelector('[data-side-panel-tab-target="document:plan"]')).toBeNull();++ await act(async () => container.querySelector<HTMLButtonElement>('button[aria-label="Open a new tab"]')?.click());+ expect(Array.from(container.querySelectorAll('[role="option"]')).some((item) => item.textContent?.includes("Plan"))).toBe(false);+ });++ it("opens a newly materialized plan until the user has interacted", async () => {+ await render(panel());+ fixture.plan = issueDocument("plan", "Plan");+ fixture.documents = [fixture.plan];+ await render(panel());+ expect(container.querySelector('[role="tab"][aria-selected="true"]')?.textContent).toContain("Plan");+ });++ it("opens a plan deep link without looping while document metadata loads", async () => {+ fixture.documents = undefined;+ fixture.plan = undefined;++ await render(panel({+ issue: issue({ workMode: "planning" }),+ documentDeepLink: { requestId: 1, documentKey: "plan" },+ }));++ expect(container.querySelector('[role="tab"][aria-selected="true"]')?.textContent).toContain("Plan");+ });++ it("does not auto-open a plan after manual tab interaction", async () => {+ await render(panel());+ await act(async () => container.querySelector<HTMLButtonElement>('#side-panel-tab-properties')?.click());+ fixture.plan = issueDocument("plan", "Plan");+ fixture.documents = [fixture.plan];+ await render(panel());+ expect(container.querySelector('[role="tab"][aria-selected="true"]')?.textContent).toContain("Properties");+ expect(container.querySelector('[data-side-panel-tab-target="document:plan"]')).toBeNull();+ });++ it("lets a persisted intentionally empty state win over defaults", async () => {+ writeTaskSidePanelState("user-1", "company-1", "task-1", {+ state: { tabs: [], activeTabId: null },+ launcherOpen: false,+ userInteracted: true,+ autoPlanHandled: true,+ updatedAt: 1,+ });+ await render(panel({ issue: issue({ workMode: "planning" }) }));+ expect(container.querySelector('[role="tab"]')).toBeNull();+ expect(container.getElementsByTagName("input")[0]?.getAttribute("aria-label")).toBe("Search tabs and resources…");+ });++ it("removes a Plan tab persisted before a plan document existed", async () => {+ writeTaskSidePanelState("user-1", "company-1", "task-1", {+ state: {+ tabs: [taskPanelPropertiesTab(), taskPanelDocumentTab("plan", "Plan")],+ activeTabId: "document:plan",+ },+ launcherOpen: false,+ userInteracted: false,+ autoPlanHandled: false,+ updatedAt: 1,+ });++ await render(panel({ issue: issue({ workMode: "planning" }) }));++ expect(container.querySelector('[data-side-panel-tab-target="document:plan"]')).toBeNull();+ expect(container.querySelector('[role="tab"][aria-selected="true"]')?.textContent).toContain("Properties");+ });++ it("opens an ordinary document deep link in a deduplicated document tab", async () => {+ fixture.documents = [issueDocument("brief", "Implementation brief")];+ await render(panel({ documentDeepLink: { requestId: 1, documentKey: "brief" } }));+ expect(container.querySelectorAll('[data-side-panel-tab-target="document:brief"]')).toHaveLength(1);+ expect(container.textContent).toContain("Document brief");+ await render(panel({ documentDeepLink: { requestId: 2, documentKey: "brief" } }));+ expect(container.querySelectorAll('[data-side-panel-tab-target="document:brief"]')).toHaveLength(1);+ });++ it("keeps Files out of the launcher when the experiment is disabled", async () => {+ writeTaskSidePanelState("user-1", "company-1", "task-1", {+ state: { tabs: [], activeTabId: null },+ launcherOpen: false,+ userInteracted: true,+ autoPlanHandled: true,+ updatedAt: 1,+ });+ await render(panel());+ expect(Array.from(container.querySelectorAll('[role="option"]')).some((item) => item.textContent?.includes("Files"))).toBe(false);+ });++ it("restores a persisted Properties tab", async () => {+ writeTaskSidePanelState("user-1", "company-1", "task-1", {+ state: { tabs: [taskPanelPropertiesTab()], activeTabId: "properties" },+ launcherOpen: false,+ userInteracted: true,+ autoPlanHandled: true,+ updatedAt: 1,+ });+ await render(panel({ issue: issue({ workMode: "planning" }) }));+ expect(container.querySelectorAll('[role="tab"]')).toHaveLength(1);+ expect(container.textContent).toContain("Properties content");+ });++ it("opens a URL-backed workspace file tab outside file-viewer provider ancestry", async () => {+ routeFixture.location.search = "?file=ui%2Fsrc%2FApp.tsx&line=7&workspace=project";+ window.history.replaceState(null, "", `${routeFixture.location.pathname}${routeFixture.location.search}`);+ await render(panel({ fileTabsEnabled: true }));++ expect(container.querySelector('[role="tab"][aria-selected="true"]')?.textContent).toContain("App.tsx");+ expect(container.textContent).toContain("Workspace file");+ });++ it("clears file-viewer URL state when switching to a non-file tab", async () => {+ routeFixture.location.search = "?file=ui%2Fsrc%2FApp.tsx&line=7&workspace=project";+ window.history.replaceState(null, "", `${routeFixture.location.pathname}${routeFixture.location.search}`);+ await render(panel({ fileTabsEnabled: true }));++ await act(async () => container.querySelector<HTMLButtonElement>("#side-panel-tab-properties")?.click());++ expect(routeFixture.navigate).toHaveBeenCalledWith(+ expect.objectContaining({ pathname: "/issues/PAP-1", search: "" }),+ expect.objectContaining({ replace: false }),+ );+ });+});diff --git a/ui/src/components/task-side-panel/TaskSidePanel.tsx b/ui/src/components/task-side-panel/TaskSidePanel.tsxnew file mode 100644index 0000000000..4a7ae76ed0--- /dev/null+++ b/ui/src/components/task-side-panel/TaskSidePanel.tsx@@ -0,0 +1,614 @@+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type ReactNode,+} from "react";+import { createPortal } from "react-dom";+import { useQuery } from "@tanstack/react-query";+import {+ isArtifactReviewDocumentKey,+ type Issue,+ type IssueDocument,+} from "@paperclipai/shared";+import {+ Box,+ FileCode2,+ FileText,+ FolderOpen,+ Lightbulb,+ Plus,+ SlidersHorizontal,+} from "lucide-react";+import { fileResourcesApi } from "@/api/file-resources";+import { IssueProperties } from "@/components/IssueProperties";+import { PROPERTIES_PANE_HEADER_SLOT_ID } from "@/components/PropertiesPanel";+import { WorkspaceFileBrowser } from "@/components/WorkspaceFileBrowser";+import { IssuePropertiesArtifactsTab } from "@/components/issue-properties/IssuePropertiesArtifactsTab";+import { IssuePropertiesPlansTab } from "@/components/issue-properties/IssuePropertiesPlansTab";+import {+ SidePanelLauncher,+ SidePanelToggleButton,+ SidePanelTabs,+ useScrollbarWhileScrolling,+ useSidePanelTabs,+ type SidePanelLauncherItem,+ type SidePanelLauncherSection,+ type SidePanelTabItem,+ type SidePanelTabRecord,+} from "@/components/side-panel";+import { Button } from "@/components/ui/button";+import {+ FILE_VIEWER_NAVIGATE_OPTIONS,+ getCurrentFileViewerSearch,+ readBrowseStateFromSearch,+ readFileViewerStateFromSearch,+ shouldNavigateFileViewerSearch,+ writeBrowseStateToSearch,+ writeFileViewerStateToSearch,+ type FileViewerBrowseState,+ type FileViewerUrlState,+} from "@/context/FileViewerContext";+import { useIssueDocuments } from "@/hooks/useIssueDocuments";+import type { IssueExternalObjectGroup } from "@/hooks/useIssueExternalObjects";+import { useIssuePlanDocument } from "@/hooks/useIssuePlanDocument";+import { documentDisplayTitle } from "@/lib/issue-artifacts";+import { queryKeys } from "@/lib/queryKeys";+import { useLocation, useNavigate } from "@/lib/router";+import {+ readTaskSidePanelState,+ taskPanelArtifactsTab,+ taskPanelDocumentTab,+ taskPanelFilesTab,+ taskPanelPropertiesTab,+ taskPanelWorkspaceFileTab,+ writeTaskSidePanelState,+ type TaskSidePanelTabPayload,+} from "@/lib/task-side-panel-state";+import { cn } from "@/lib/utils";+import { TaskDocumentPanel } from "./TaskDocumentPanel";+import { TaskWorkspaceFilePanel } from "./TaskWorkspaceFilePanel";++export interface TaskSidePanelProps {+ issue: Issue;+ accountScope: string;+ childIssues?: Issue[];+ onAddSubIssue?: () => void;+ onUpdate: (data: Record<string, unknown>) => void;+ inline?: boolean;+ hasActiveRun?: boolean;+ externalObjects?: IssueExternalObjectGroup[];+ externalObjectsLoading?: boolean;+ externalObjectsError?: boolean;+ onRetryExternalObjects?: () => void;+ onCheckMonitorNow?: () => void;+ checkingMonitorNow?: boolean;+ fileTabsEnabled: boolean;+ documentDeepLink?: { requestId: number; documentKey: string } | null;+ onRequestClose?: () => void;+}++const EMPTY_ISSUE_DOCUMENTS: IssueDocument[] = [];++function tabIcon(tab: SidePanelTabRecord<TaskSidePanelTabPayload>): ReactNode {+ switch (tab.payload.kind) {+ case "properties": return <SlidersHorizontal />;+ case "artifacts": return <Box />;+ case "files-browser": return <FolderOpen />;+ case "workspace-file": return <FileCode2 />;+ case "issue-document": return tab.payload.documentKey === "plan" ? <Lightbulb /> : <FileText />;+ }+}++function selectorForWorkspaceKind(kind: "execution_workspace" | "project_workspace") {+ return kind === "execution_workspace" ? "execution" as const : "project" as const;+}++/**+ * The desktop panel is rendered beside the route outlet, so task file routing+ * deliberately lives in this adapter instead of depending on provider ancestry.+ */+function useTaskSidePanelFileRouting() {+ const location = useLocation();+ const navigate = useNavigate();+ const state = useMemo(() => readFileViewerStateFromSearch(location.search), [location.search]);+ const browseState = useMemo(() => readBrowseStateFromSearch(location.search), [location.search]);+ const navigateSearch = useCallback((nextSearch: string, replace = false) => {+ if (!shouldNavigateFileViewerSearch(nextSearch, location.search)) return;+ navigate(+ { pathname: location.pathname, hash: location.hash, search: nextSearch },+ { ...FILE_VIEWER_NAVIGATE_OPTIONS, replace, state: location.state },+ );+ }, [location.hash, location.pathname, location.search, location.state, navigate]);++ const open = useCallback((ref: FileViewerUrlState, options?: {+ fromBrowse?: boolean;+ browseState?: Partial<FileViewerBrowseState>;+ }) => {+ let nextSearch = writeFileViewerStateToSearch(location.search, ref);+ if (options?.fromBrowse) {+ const params = new URLSearchParams(nextSearch);+ const previous = new URLSearchParams(location.search);+ params.set("browse", "1");+ const query = Object.prototype.hasOwnProperty.call(options.browseState ?? {}, "q")+ ? options.browseState?.q+ : previous.get("q");+ const folder = Object.prototype.hasOwnProperty.call(options.browseState ?? {}, "folderPath")+ ? options.browseState?.folderPath+ : previous.get("folder");+ if (query) params.set("q", query);+ else params.delete("q");+ if (folder) params.set("folder", folder);+ else params.delete("folder");+ nextSearch = params.toString() ? `?${params.toString()}` : "";+ }+ navigateSearch(nextSearch);+ }, [location.search, navigateSearch]);++ const openBrowse = useCallback((options?: { q?: string }) => {+ const params = new URLSearchParams(location.search);+ params.delete("file");+ params.delete("line");+ params.delete("column");+ params.delete("folder");+ params.set("browse", "1");+ if (options?.q) params.set("q", options.q);+ else params.delete("q");+ navigateSearch(params.toString() ? `?${params.toString()}` : "");+ }, [location.search, navigateSearch]);++ const updateBrowseState = useCallback((next: Partial<FileViewerBrowseState>) => {+ navigateSearch(writeBrowseStateToSearch(location.search, next), true);+ }, [location.search, navigateSearch]);++ const close = useCallback(() => {+ const currentSearch = getCurrentFileViewerSearch(location.search);+ const params = new URLSearchParams(writeFileViewerStateToSearch(currentSearch, null).replace(/^\?/, ""));+ params.delete("browse");+ params.delete("q");+ params.delete("folder");+ navigateSearch(params.toString() ? `?${params.toString()}` : "");+ }, [location.search, navigateSearch]);++ return {+ state,+ browse: browseState !== null,+ query: browseState?.q ?? null,+ folderPath: browseState?.folderPath ?? null,+ browseProjectId: browseState?.projectId ?? null,+ browseWorkspaceId: browseState?.workspaceId ?? null,+ open,+ openBrowse,+ updateBrowseState,+ close,+ };+}++export function TaskSidePanel({+ issue,+ accountScope,+ childIssues = [],+ onAddSubIssue,+ onUpdate,+ inline = false,+ hasActiveRun = false,+ externalObjects,+ externalObjectsLoading,+ externalObjectsError,+ onRetryExternalObjects,+ onCheckMonitorNow,+ checkingMonitorNow = false,+ fileTabsEnabled,+ documentDeepLink,+ onRequestClose,+}: TaskSidePanelProps) {+ const handleScroll = useScrollbarWhileScrolling();+ const viewer = useTaskSidePanelFileRouting();+ const { data: documentsData } = useIssueDocuments(issue.id);+ const documents = documentsData ?? EMPTY_ISSUE_DOCUMENTS;+ const { data: planDocument } = useIssuePlanDocument(issue.id);+ const restoredRef = useRef(+ readTaskSidePanelState(accountScope, issue.companyId, issue.id, fileTabsEnabled),+ );+ const [launcherOpen, setLauncherOpen] = useState(restoredRef.current?.launcherOpen ?? false);+ const [paneHeaderSlot, setPaneHeaderSlot] = useState<HTMLElement | null>(null);+ const bodyRef = useRef<HTMLDivElement>(null);+ const scrollPositionsRef = useRef(new Map<string, number>());+ const userInteractedRef = useRef(restoredRef.current?.userInteracted ?? false);+ const autoPlanHandledRef = useRef(restoredRef.current?.autoPlanHandled ?? false);+ const initialState = useMemo(() => restoredRef.current?.state ?? ({+ tabs: [taskPanelPropertiesTab()],+ activeTabId: "properties",+ }), []);++ const persist = useCallback((state: { tabs: SidePanelTabRecord<TaskSidePanelTabPayload>[]; activeTabId: string | null }) => {+ writeTaskSidePanelState(accountScope, issue.companyId, issue.id, {+ state,+ launcherOpen,+ userInteracted: userInteractedRef.current,+ autoPlanHandled: autoPlanHandledRef.current,+ updatedAt: Date.now(),+ });+ }, [accountScope, issue.companyId, issue.id, launcherOpen]);+ const controller = useSidePanelTabs<TaskSidePanelTabPayload>({ initialState, onStateChange: persist });+ const activeTab = controller.tabs.find((tab) => tab.id === controller.activeTabId) ?? null;++ useEffect(() => {+ if (inline) {+ setPaneHeaderSlot(null);+ return;+ }+ setPaneHeaderSlot(document.getElementById(PROPERTIES_PANE_HEADER_SLOT_ID));+ }, [inline]);++ // Older clients persisted an empty Plan tab merely because the task was in+ // planning mode. Remove that stale tab once the plan lookup confirms there+ // is no document; a real plan will be opened by the materialization effect+ // below when it arrives.+ useEffect(() => {+ if (planDocument !== null || !controller.tabs.some((tab) => tab.id === "document:plan")) return;+ autoPlanHandledRef.current = false;+ controller.closeTab("document:plan");+ }, [controller.closeTab, controller.tabs, planDocument]);++ // Surface a newly materialized plan exactly once until the user takes manual+ // control of the tab set. Persisted empty/custom states therefore stay put.+ useEffect(() => {+ if (!planDocument || autoPlanHandledRef.current || userInteractedRef.current) return;+ autoPlanHandledRef.current = true;+ controller.openTab(taskPanelDocumentTab("plan", documentDisplayTitle(planDocument)));+ }, [controller.openTab, planDocument]);++ useEffect(() => {+ if (!documentDeepLink) return;+ if (+ documentDeepLink.documentKey === "plan" &&+ planDocument === null+ ) return;+ const document = documents.find((candidate) => candidate.key === documentDeepLink.documentKey);+ const label = document ? documentDisplayTitle(document) : documentDeepLink.documentKey === "plan" ? "Plan" : documentDeepLink.documentKey;+ controller.openTab(taskPanelDocumentTab(documentDeepLink.documentKey, label));+ }, [controller.openTab, documentDeepLink, documents, planDocument]);++ // Existing URL-backed workspace links remain the external integration API.+ useEffect(() => {+ if (!fileTabsEnabled) return;+ if (viewer.state) {+ controller.openTab(taskPanelWorkspaceFileTab(viewer.state));+ } else if (viewer.browse) {+ controller.openTab(taskPanelFilesTab());+ controller.updateTab("files", {+ payload: {+ kind: "files-browser",+ query: viewer.query,+ folderPath: viewer.folderPath,+ projectId: viewer.browseProjectId,+ workspaceId: viewer.browseWorkspaceId,+ },+ });+ }+ }, [+ controller.openTab,+ controller.updateTab,+ fileTabsEnabled,+ viewer.browse,+ viewer.browseProjectId,+ viewer.browseWorkspaceId,+ viewer.folderPath,+ viewer.query,+ viewer.state,+ ]);++ const recentFilesQuery = useQuery({+ queryKey: queryKeys.issues.fileResources(issue.id, {+ workspace: "auto",+ mode: "recent",+ limit: 5,+ offset: 0,+ }),+ queryFn: () => fileResourcesApi.list(issue.id, { workspace: "auto", mode: "recent", limit: 5, offset: 0 }),+ enabled: fileTabsEnabled && (launcherOpen || !activeTab),+ retry: false,+ staleTime: 15_000,+ });++ function markInteracted() {+ userInteractedRef.current = true;+ }++ function captureScroll() {+ if (controller.activeTabId && bodyRef.current) {+ scrollPositionsRef.current.set(controller.activeTabId, bodyRef.current.scrollTop);+ }+ }++ function selectTab(tabId: string) {+ captureScroll();+ markInteracted();+ controller.selectTab(tabId);+ const tab = controller.tabs.find((candidate) => candidate.id === tabId);+ if (!tab) return;+ if (tab.payload.kind === "workspace-file") {+ viewer.open(tab.payload);+ } else if (tab.payload.kind === "files-browser") {+ viewer.openBrowse({ q: tab.payload.query ?? undefined });+ } else if (viewer.state || viewer.browse) {+ viewer.close();+ }+ }++ useEffect(() => {+ const top = controller.activeTabId ? scrollPositionsRef.current.get(controller.activeTabId) ?? 0 : 0;+ window.requestAnimationFrame(() => bodyRef.current?.scrollTo({ top, behavior: "auto" }));+ }, [controller.activeTabId]);++ useEffect(() => {+ if (activeTab) return;+ window.requestAnimationFrame(() => {+ bodyRef.current?.querySelector<HTMLInputElement>('input[aria-label="Search tabs and resources…"]')?.focus();+ });+ }, [activeTab]);++ function closeTab(tabId: string) {+ markInteracted();+ const tab = controller.tabs.find((candidate) => candidate.id === tabId);+ controller.closeTab(tabId);+ if (tabId === controller.activeTabId && (tab?.payload.kind === "workspace-file" || tab?.payload.kind === "files-browser")) {+ viewer.close();+ }+ }++ function openDocument(document: Pick<IssueDocument, "key" | "title">) {+ markInteracted();+ controller.openTab(taskPanelDocumentTab(document.key, documentDisplayTitle(document)));+ }++ function openWorkspaceFile(ref: {+ path: string;+ workspace: "auto" | "execution" | "project";+ line?: number | null;+ column?: number | null;+ projectId?: string | null;+ workspaceId?: string | null;+ }) {+ markInteracted();+ const tab = taskPanelWorkspaceFileTab(ref);+ controller.openTab(tab);+ viewer?.open({+ ...ref,+ projectId: ref.projectId ?? null,+ workspaceId: ref.workspaceId ?? null,+ line: ref.line ?? null,+ column: ref.column ?? null,+ }, { fromBrowse: true });+ }++ const documentByKey = useMemo(() => new Map(documents.map((document) => [document.key, document])), [documents]);+ const visualTabs = useMemo<SidePanelTabItem[]>(() => controller.tabs.map((tab) => {+ const document = tab.payload.kind === "issue-document" ? documentByKey.get(tab.payload.documentKey) : null;+ return {+ id: tab.id,+ type: tab.type,+ label: document ? documentDisplayTitle(document) : tab.label,+ ariaLabel: tab.ariaLabel,+ closable: true,+ contentMode: tab.contentMode,+ icon: tabIcon(tab),+ };+ }), [controller.tabs, documentByKey]);++ const launcherSections = useMemo<SidePanelLauncherSection[]>(() => {+ const primary: SidePanelLauncherItem[] = [+ { id: "properties", label: "Properties", icon: <SlidersHorizontal />, alreadyOpen: controller.tabs.some((tab) => tab.id === "properties") },+ { id: "artifacts", label: "Artifacts", icon: <Box />, alreadyOpen: controller.tabs.some((tab) => tab.id === "artifacts") },+ ];+ if (fileTabsEnabled) {+ primary.push({ id: "files", label: "Files", icon: <FolderOpen />, shortcut: "G F", alreadyOpen: controller.tabs.some((tab) => tab.id === "files") });+ }+ const documentItems: SidePanelLauncherItem[] = [+ ...(planDocument ? [{+ id: "document:plan",+ label: documentDisplayTitle(planDocument),+ description: `Revision ${planDocument.latestRevisionNumber ?? 1}`,+ icon: <Lightbulb />,+ alreadyOpen: controller.tabs.some((tab) => tab.id === "document:plan"),+ }] : []),+ ...documents+ .filter((document) => document.key !== "plan" && !isArtifactReviewDocumentKey(document.key))+ .sort((left, right) => new Date(right.updatedAt).getTime() - new Date(left.updatedAt).getTime())+ .map((document) => ({+ id: `document:${document.key}`,+ label: documentDisplayTitle(document),+ description: `Revision ${document.latestRevisionNumber ?? 1}`,+ icon: <FileText />,+ alreadyOpen: controller.tabs.some((tab) => tab.id === `document:${document.key}`),+ })),+ ];+ const sections: SidePanelLauncherSection[] = [+ { id: "open", label: "Open", items: primary },+ ];+ if (documentItems.length > 0) {+ sections.push({ id: "documents", label: "Task documents", items: documentItems });+ }+ if (fileTabsEnabled) {+ const recentItems = recentFilesQuery.data?.state === "available"+ ? recentFilesQuery.data.items.filter((item) => item.kind === "file").slice(0, 5).map((item) => ({+ id: `recent-file:${item.workspaceId}:${item.relativePath}`,+ label: item.title,+ description: item.displayPath,+ searchText: item.relativePath,+ icon: <FileCode2 />,+ }))+ : [];+ sections.push({+ id: "recent-files",+ label: "Recent workspace files",+ items: recentItems,+ loading: recentFilesQuery.isLoading,+ error: recentFilesQuery.isError ? "Recent files are temporarily unavailable." : null,+ });+ }+ return sections;+ }, [controller.tabs, documents, fileTabsEnabled, planDocument, recentFilesQuery.data, recentFilesQuery.isError, recentFilesQuery.isLoading]);++ function selectLauncherItem(item: SidePanelLauncherItem) {+ markInteracted();+ if (item.id === "properties") controller.openTab(taskPanelPropertiesTab());+ else if (item.id === "artifacts") controller.openTab(taskPanelArtifactsTab());+ else if (item.id === "files") {+ controller.openTab(taskPanelFilesTab());+ viewer.openBrowse();+ } else if (item.id.startsWith("document:")) {+ const key = item.id.slice("document:".length);+ controller.openTab(taskPanelDocumentTab(key, item.label));+ } else if (item.id.startsWith("recent-file:") && recentFilesQuery.data?.state === "available") {+ const recent = recentFilesQuery.data.items.find((candidate) =>+ item.id === `recent-file:${candidate.workspaceId}:${candidate.relativePath}`,+ );+ if (recent?.kind === "file") {+ openWorkspaceFile({+ path: recent.relativePath,+ workspace: selectorForWorkspaceKind(recent.workspaceKind),+ projectId: recent.projectId ?? null,+ workspaceId: recent.workspaceId,+ });+ }+ }+ }++ const launcherControl = (+ <SidePanelLauncher+ sections={launcherSections}+ onSelect={selectLauncherItem}+ presentation="popover"+ open={launcherOpen}+ onOpenChange={setLauncherOpen}+ trigger={(+ <Button type="button" variant="ghost" size="icon-sm" className="h-(--side-panel-tab-height) w-(--side-panel-tab-height) shrink-0 rounded-(--side-panel-control-radius) text-muted-foreground hover:text-foreground focus-visible:text-foreground" aria-label="Open a new tab">+ <Plus aria-hidden />+ </Button>+ )}+ />+ );+ const tabStrip = (+ <SidePanelTabs+ tabs={visualTabs}+ activeTabId={controller.activeTabId}+ onActiveTabChange={selectTab}+ onCloseTab={closeTab}+ onReorderTabs={(ordered) => {+ markInteracted();+ controller.reorderTabs(ordered);+ }}+ addControl={launcherControl}+ />+ );++ let content: ReactNode;+ if (!activeTab) {+ content = <SidePanelLauncher sections={launcherSections} onSelect={selectLauncherItem} />;+ } else if (activeTab.payload.kind === "properties") {+ content = (+ <IssueProperties+ issue={issue}+ childIssues={childIssues}+ onAddSubIssue={onAddSubIssue}+ onUpdate={onUpdate}+ inline={inline}+ hasActiveRun={hasActiveRun}+ externalObjects={externalObjects}+ externalObjectsLoading={externalObjectsLoading}+ externalObjectsError={externalObjectsError}+ onRetryExternalObjects={onRetryExternalObjects}+ onCheckMonitorNow={onCheckMonitorNow}+ checkingMonitorNow={checkingMonitorNow}+ sidePanelContentOnly+ />+ );+ } else if (activeTab.payload.kind === "artifacts") {+ content = <IssuePropertiesArtifactsTab issue={issue} onOpenDocument={openDocument} />;+ } else if (activeTab.payload.kind === "issue-document") {+ content = activeTab.payload.documentKey === "plan" ? (+ <IssuePropertiesPlansTab issue={issue} inline={inline} />+ ) : (+ <TaskDocumentPanel+ issueId={issue.id}+ documentKey={activeTab.payload.documentKey}+ initialDocument={documentByKey.get(activeTab.payload.documentKey)}+ />+ );+ } else if (activeTab.payload.kind === "files-browser") {+ content = (+ <WorkspaceFileBrowser+ issueId={issue.id}+ companyId={issue.companyId}+ onOpen={openWorkspaceFile}+ onBrowseStateChange={(next) => {+ controller.updateTab(activeTab.id, {+ payload: {+ kind: "files-browser",+ query: next.q,+ folderPath: next.folderPath,+ projectId: next.projectId,+ workspaceId: next.workspaceId,+ },+ });+ viewer.updateBrowseState(next);+ }}+ initialQuery={activeTab.payload.query}+ initialFolderPath={activeTab.payload.folderPath}+ initialProjectId={activeTab.payload.projectId}+ initialWorkspaceId={activeTab.payload.workspaceId}+ active+ className="h-full min-h-0 p-3"+ />+ );+ } else {+ const filePayload = activeTab.payload;+ content = (+ <TaskWorkspaceFilePanel+ issueId={issue.id}+ payload={filePayload}+ onFallbackToProject={filePayload.workspace !== "project" && !filePayload.projectId && !filePayload.workspaceId+ ? () => openWorkspaceFile({ ...filePayload, workspace: "project" })+ : undefined}+ />+ );+ }++ const contentMode = activeTab?.contentMode ?? "full-bleed";+ return (+ <div className="flex h-full min-h-0 flex-col">+ {paneHeaderSlot ? createPortal(tabStrip, paneHeaderSlot) : (+ <div className="flex h-(--side-panel-header-height) shrink-0 items-center gap-1 px-2">+ {tabStrip}+ {onRequestClose ? (+ <SidePanelToggleButton open onToggle={onRequestClose} />+ ) : null}+ </div>+ )}+ <div+ ref={bodyRef}+ data-side-panel-content-viewport="true"+ onScroll={handleScroll}+ role={activeTab ? "tabpanel" : undefined}+ id={activeTab ? `side-panel-content-${activeTab.id}` : undefined}+ aria-labelledby={activeTab ? `side-panel-tab-${activeTab.id}` : undefined}+ className={cn(+ "min-h-0 flex-1",+ contentMode === "full-bleed" ? "overflow-hidden" : "overflow-auto",+ contentMode !== "full-bleed" && "scrollbar-while-scrolling",+ contentMode === "padded" && "p-4",+ )}+ >+ {contentMode === "prose" ? (+ <div data-side-panel-prose-content="true" className="mx-auto w-full max-w-4xl px-6 py-4">+ {content}+ </div>+ ) : content}+ </div>+ </div>+ );+}diff --git a/ui/src/components/task-side-panel/TaskWorkspaceFilePanel.tsx b/ui/src/components/task-side-panel/TaskWorkspaceFilePanel.tsxnew file mode 100644index 0000000000..4c776e94bb--- /dev/null+++ b/ui/src/components/task-side-panel/TaskWorkspaceFilePanel.tsx@@ -0,0 +1,102 @@+import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { Check, Copy, Download } from "lucide-react";+import { fileResourcesApi } from "@/api/file-resources";+import { FileViewerBody, FileViewerMetadataRow } from "@/components/FileViewerSheet";+import { Button } from "@/components/ui/button";+import type { FileViewerUrlState } from "@/context/FileViewerContext";+import { copyTextToClipboard } from "@/lib/clipboard";+import { queryKeys } from "@/lib/queryKeys";+import type { TaskSidePanelTabPayload } from "@/lib/task-side-panel-state";++type WorkspaceFilePayload = Extract<TaskSidePanelTabPayload, { kind: "workspace-file" }>;++export function TaskWorkspaceFilePanel({+ issueId,+ payload,+ onFallbackToProject,+}: {+ issueId: string;+ payload: WorkspaceFilePayload;+ onFallbackToProject?: () => void;+}) {+ const [copied, setCopied] = useState(false);+ const [announcement, setAnnouncement] = useState("");+ const state: FileViewerUrlState = {+ path: payload.path,+ workspace: payload.workspace,+ projectId: payload.projectId,+ workspaceId: payload.workspaceId,+ line: payload.line,+ column: payload.column,+ };+ const resourceQuery = useQuery({+ queryKey: queryKeys.issues.fileResource(issueId, state),+ queryFn: () => fileResourcesApi.resolve(issueId, state),+ retry: false,+ });+ const resource = resourceQuery.data;+ const contentQuery = useQuery({+ queryKey: queryKeys.issues.fileResourceContent(issueId, state),+ queryFn: () => fileResourcesApi.content(issueId, state),+ enabled: resource?.capabilities.preview === true,+ retry: false,+ });+ const downloadUrl = resource?.capabilities.download+ ? fileResourcesApi.downloadUrl(issueId, state)+ : null;++ return (+ <div className="flex h-full min-h-0 flex-col bg-muted/20">+ <header className="flex min-w-0 items-start gap-2 border-b border-border bg-card px-3 py-2">+ <div className="min-w-0 flex-1">+ <h2 className="truncate text-sm font-medium" title={payload.path}>{resource?.title ?? payload.path}</h2>+ <p className="truncate font-mono text-xs text-muted-foreground" title={payload.path}>{payload.path}</p>+ <FileViewerMetadataRow resolvedResource={resource} state={state} />+ </div>+ <div className="flex shrink-0 items-center gap-1">+ {contentQuery.data ? (+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Copy file contents"+ title={copied ? "Copied" : "Copy file contents"}+ onClick={() => {+ void copyTextToClipboard(contentQuery.data!.content.data).then(() => {+ setCopied(true);+ window.setTimeout(() => setCopied(false), 1800);+ });+ }}+ >+ {copied ? <Check aria-hidden /> : <Copy aria-hidden />}+ </Button>+ ) : null}+ {downloadUrl ? (+ <Button asChild variant="ghost" size="icon-sm">+ <a href={downloadUrl} download={resource?.title} aria-label="Download file" title="Download file">+ <Download aria-hidden />+ </a>+ </Button>+ ) : null}+ </div>+ </header>+ <div className="min-h-0 flex-1 overflow-hidden">+ <div className="sr-only" aria-live="polite">{announcement}</div>+ <FileViewerBody+ resolveQuery={resourceQuery}+ contentQuery={contentQuery}+ elapsedMs={0}+ canPreview={resource?.capabilities.preview ?? false}+ highlightedLine={payload.line}+ onRetry={() => {+ void resourceQuery.refetch();+ if (resource?.capabilities.preview) void contentQuery.refetch();+ }}+ onSetAnnouncement={setAnnouncement}+ onFallbackToProject={onFallbackToProject ?? null}+ />+ </div>+ </div>+ );+}diff --git a/ui/src/components/task-side-panel/index.ts b/ui/src/components/task-side-panel/index.tsnew file mode 100644index 0000000000..30ec65c9b5--- /dev/null+++ b/ui/src/components/task-side-panel/index.ts@@ -0,0 +1,3 @@+export { TaskSidePanel, type TaskSidePanelProps } from "./TaskSidePanel";+export { TaskDocumentPanel } from "./TaskDocumentPanel";+export { TaskWorkspaceFilePanel } from "./TaskWorkspaceFilePanel";diff --git a/ui/src/components/transcript/RunTranscriptView.test.tsx b/ui/src/components/transcript/RunTranscriptView.test.tsxindex 1639fb3c67..5441816ca6 100644--- a/ui/src/components/transcript/RunTranscriptView.test.tsx+++ b/ui/src/components/transcript/RunTranscriptView.test.tsx@@ -9,6 +9,12 @@ import { ThemeProvider } from "../../context/ThemeContext";import { RunTranscriptView, keyTranscriptBlocks, normalizeTranscript } from "./RunTranscriptView";describe("RunTranscriptView", () => {+ it("renders provider activity semantically without dumping the payload", () => {+ const html = renderToStaticMarkup(<RunTranscriptView entries={[{ kind: "provider_activity", ts: "2026-08-21T12:00:00.000Z", family: "plan", eventType: "plan.updated", status: "completed", title: "Plan", summary: "Plan completed", payload: { steps: [{ stepId: "s1", body: "Validate schemas", status: "completed" }], hiddenSecret: "must-not-render" } }]} />);+ expect(html).toContain("Plan");+ expect(html).toContain("Plan completed");+ expect(html).not.toContain("must-not-render");+ });it("folds repeated tool_call status updates for the same toolUseId into one block", () => {const entries: TranscriptEntry[] = [{diff --git a/ui/src/context/BreadcrumbContext.tsx b/ui/src/context/BreadcrumbContext.tsxindex 2726c9a904..c3b8a79b82 100644--- a/ui/src/context/BreadcrumbContext.tsx+++ b/ui/src/context/BreadcrumbContext.tsx@@ -21,6 +21,8 @@ export interface Breadcrumb {interface BreadcrumbContextValue {breadcrumbs: Breadcrumb[];setBreadcrumbs: (crumbs: Breadcrumb[]) => void;+ breadcrumbToolbar: ReactNode | null;+ setBreadcrumbToolbar: (node: ReactNode | null) => void;mobileToolbar: ReactNode | null;setMobileToolbar: (node: ReactNode | null) => void;}@@ -59,6 +61,7 @@ export function buildDocumentTitle(breadcrumbs: Breadcrumb[], companyName?: striexport function BreadcrumbProvider({ children, companyName }: BreadcrumbProviderProps) {const [breadcrumbs, setBreadcrumbsState] = useState<Breadcrumb[]>([]);+ const [breadcrumbToolbar, setBreadcrumbToolbarState] = useState<ReactNode | null>(null);const [mobileToolbar, setMobileToolbarState] = useState<ReactNode | null>(null);const setBreadcrumbs = useCallback((crumbs: Breadcrumb[]) => {@@ -69,12 +72,25 @@ export function BreadcrumbProvider({ children, companyName }: BreadcrumbProvidersetMobileToolbarState(node);}, []);+ const setBreadcrumbToolbar = useCallback((node: ReactNode | null) => {+ setBreadcrumbToolbarState(node);+ }, []);+useEffect(() => {document.title = buildDocumentTitle(breadcrumbs, companyName);}, [breadcrumbs, companyName]);return (- <BreadcrumbContext.Provider value={{ breadcrumbs, setBreadcrumbs, mobileToolbar, setMobileToolbar }}>+ <BreadcrumbContext.Provider+ value={{+ breadcrumbs,+ setBreadcrumbs,+ breadcrumbToolbar,+ setBreadcrumbToolbar,+ mobileToolbar,+ setMobileToolbar,+ }}+ >{children}</BreadcrumbContext.Provider>);diff --git a/ui/src/context/LiveUpdatesProvider.test.ts b/ui/src/context/LiveUpdatesProvider.test.tsindex 7f25ccc7e7..b3194cd165 100644--- a/ui/src/context/LiveUpdatesProvider.test.ts+++ b/ui/src/context/LiveUpdatesProvider.test.ts@@ -669,6 +669,58 @@ describe("LiveUpdatesProvider issue invalidation", () => {});});+ it("actively refreshes interactions materialized by a visible native status decision", () => {+ const invalidations: unknown[] = [];+ const queryClient = {+ invalidateQueries: (input: unknown) => {+ invalidations.push(input);+ },+ getQueryData: (key: unknown) => {+ if (JSON.stringify(key) === JSON.stringify(queryKeys.issues.detail("PAP-759"))) {+ return {+ id: "issue-1",+ identifier: "PAP-759",+ assigneeAgentId: "agent-1",+ };+ }+ return undefined;+ },+ };++ __liveUpdatesTestUtils.invalidateActivityQueries(+ queryClient as never,+ "company-1",+ {+ entityType: "issue",+ entityId: "issue-1",+ action: "issue.updated",+ actorType: "system",+ actorId: "native-status-committer",+ details: {+ identifier: "PAP-759",+ source: "native_status_decision",+ toStatus: "in_review",+ reasonCode: "external_verification_required",+ effectCount: 2,+ },+ },+ { userId: null, agentId: null },+ { pathname: "/PAP/issues/PAP-759", isForegrounded: true },+ );++ expect(invalidations).toContainEqual({+ queryKey: queryKeys.issues.detail("issue-1"),+ refetchType: "inactive",+ });+ expect(invalidations).toContainEqual({+ queryKey: queryKeys.issues.interactions("issue-1"),+ });+ expect(invalidations).not.toContainEqual({+ queryKey: queryKeys.issues.interactions("issue-1"),+ refetchType: "inactive",+ });+ });+it("keeps visible issue comment updates inactive-only instead of active refetching", () => {const invalidations: unknown[] = [];const queryClient = {diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsxindex 586c1272c7..3b407c35a7 100644--- a/ui/src/context/LiveUpdatesProvider.tsx+++ b/ui/src/context/LiveUpdatesProvider.tsx@@ -1035,8 +1035,16 @@ function invalidateActivityQueries(...invalidationOptions,});}- if (action?.startsWith("issue.thread_interaction_")) {- queryClient.invalidateQueries({ queryKey: queryKeys.issues.interactions(ref), ...invalidationOptions });+ if (+ action?.startsWith("issue.thread_interaction_")+ || ((action === "issue.updated" || action === "issue.status_decision_recorded")+ && readString(details?.source) === "native_status_decision")+ ) {+ // Native status decisions may materialize a review interaction in the+ // same transaction. Unlike run/activity rows, that card is not present+ // in the streamed PRP projection, so inactive-only invalidation leaves+ // the visible task stale until a full reload.+ queryClient.invalidateQueries({ queryKey: queryKeys.issues.interactions(ref) });}}}diff --git a/ui/src/context/PanelContext.tsx b/ui/src/context/PanelContext.tsxindex a29fbbb43d..fcb79e9245 100644--- a/ui/src/context/PanelContext.tsx+++ b/ui/src/context/PanelContext.tsx@@ -1,11 +1,13 @@import { createContext, useCallback, useContext, useState, type ReactNode } from "react";+import type { SidePanelContentMode } from "@/components/side-panel";const STORAGE_KEY = "paperclip:panel-visible";interface PanelContextValue {panelContent: ReactNode | null;+ panelContentMode: SidePanelContentMode;panelVisible: boolean;- openPanel: (content: ReactNode) => void;+ openPanel: (content: ReactNode, options?: { contentMode?: SidePanelContentMode }) => void;closePanel: () => void;setPanelVisible: (visible: boolean) => void;togglePanelVisible: () => void;@@ -32,14 +34,17 @@ function writePreference(visible: boolean) {export function PanelProvider({ children }: { children: ReactNode }) {const [panelContent, setPanelContent] = useState<ReactNode | null>(null);+ const [panelContentMode, setPanelContentMode] = useState<SidePanelContentMode>("padded");const [panelVisible, setPanelVisibleState] = useState(readPreference);- const openPanel = useCallback((content: ReactNode) => {+ const openPanel = useCallback((content: ReactNode, options?: { contentMode?: SidePanelContentMode }) => {setPanelContent(content);+ setPanelContentMode(options?.contentMode ?? "padded");}, []);const closePanel = useCallback(() => {setPanelContent(null);+ setPanelContentMode("padded");}, []);const setPanelVisible = useCallback((visible: boolean) => {@@ -57,7 +62,7 @@ export function PanelProvider({ children }: { children: ReactNode }) {return (<PanelContext.Provider- value={{ panelContent, panelVisible, openPanel, closePanel, setPanelVisible, togglePanelVisible }}+ value={{ panelContent, panelContentMode, panelVisible, openPanel, closePanel, setPanelVisible, togglePanelVisible }}>{children}</PanelContext.Provider>diff --git a/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx b/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsxindex b3fcc1b73d..873d1c9630 100644--- a/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx+++ b/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdom-import { act as reactAct, type ReactNode } from "react";+import { act as reactAct, useState, type ReactNode } from "react";import { createRoot, type Root } from "react-dom/client";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import type {@@ -111,11 +111,7 @@ function terminal(} as ConnectionIntentInteraction;}-function renderBody(- interaction: ConnectionIntentInteraction = pendingConnectionIntentInteraction,- currentUserId:- string | null = issueThreadInteractionFixtureMeta.currentUserId,-) {+function renderNode(node: ReactNode) {host = document.createElement("div");document.body.appendChild(host);root = createRoot(host);@@ -125,17 +121,27 @@ function renderBody(void act(() => {root?.render(<QueryClientProvider client={queryClient}>- <ConnectionIntentInteractionBody- interaction={interaction}- currentUserId={currentUserId}- addresseeLabel="Carol"- />+ {node}</QueryClientProvider>,);});return host;}+function renderBody(+ interaction: ConnectionIntentInteraction = pendingConnectionIntentInteraction,+ currentUserId:+ string | null = issueThreadInteractionFixtureMeta.currentUserId,+) {+ return renderNode(+ <ConnectionIntentInteractionBody+ interaction={interaction}+ currentUserId={currentUserId}+ addresseeLabel="Carol"+ />,+ );+}+function button(label: string) {return Array.from(document.body.querySelectorAll("button")).find((candidate) => candidate.textContent?.trim() === label,@@ -295,6 +301,57 @@ describe("ConnectionIntentInteractionBody dialog behavior", () => {});});+ it("restores focus when completion remounts the intent in a different task host", async () => {+ setupOptionsMock.mockResolvedValue({+ requestedAgentId: "agent-requesting",+ existingConnections: [{ id: "connection-one", name: "Carol's Notion" }],+ });+ const acceptedInteraction = {+ ...pendingConnectionIntentInteraction,+ status: "accepted",+ resolvedAt: new Date("2026-08-26T12:00:00.000Z"),+ result: {+ version: 1,+ outcome: "connected",+ connectionId: "connection-one",+ },+ } as ConnectionIntentInteraction;+ let showAcceptedInteraction!: () => void;++ function RemountingTaskHost() {+ const [interaction, setInteraction] = useState(+ pendingConnectionIntentInteraction,+ );+ showAcceptedInteraction = () => setInteraction(acceptedInteraction);+ return (+ <ConnectionIntentInteractionBody+ key={interaction.status}+ interaction={interaction}+ currentUserId={issueThreadInteractionFixtureMeta.currentUserId}+ addresseeLabel="Carol"+ />+ );+ }++ completeMock.mockImplementation(async () => {+ showAcceptedInteraction();+ return acceptedInteraction;+ });+ renderNode(<RemountingTaskHost />);++ await act(() => button("Connect / Use existing")?.click());+ await flush();+ await act(() => button("Use Carol's Notion")?.click());++ await waitForAssertion(() => {+ const target = document.getElementById(+ `connection-intent-focus-target-${acceptedInteraction.id}`,+ );+ expect(document.body.textContent).toContain("Notion connected");+ expect(document.activeElement).toBe(target);+ });+ });+it("keeps the dialog open and surfaces completion failures", async () => {completeMock.mockRejectedValue(new Error("install commit failed"));renderBody();diff --git a/ui/src/features/connections/ConnectionIntentInteractionBody.tsx b/ui/src/features/connections/ConnectionIntentInteractionBody.tsxindex ab6653080e..a510a0ebcb 100644--- a/ui/src/features/connections/ConnectionIntentInteractionBody.tsx+++ b/ui/src/features/connections/ConnectionIntentInteractionBody.tsx@@ -43,6 +43,7 @@ export function ConnectionIntentInteractionBody({currentUserId && interaction.addresseeUserId === currentUserId,);const isPending = interaction.status === "pending";+ const focusTargetId = `connection-intent-focus-target-${interaction.id}`;const invalidateTask = async (updatedInteraction?: ConnectionIntentInteraction,@@ -67,7 +68,21 @@ export function ConnectionIntentInteractionBody({]);};const returnFocusToCard = () => {- window.requestAnimationFrame(() => focusTargetRef.current?.focus());+ // Completing an intent can move it from the composer takeover to the+ // durable timeline. That replaces this component instance, so its ref can+ // be cleared before focus restoration runs. Retry for a few paint frames+ // and resolve the stable interaction-specific target from the new host.+ const focusCurrentTarget = (remainingAttempts: number) => {+ window.requestAnimationFrame(() => {+ const target =+ document.getElementById(focusTargetId) ?? focusTargetRef.current;+ target?.focus();+ if (remainingAttempts > 1) {+ focusCurrentTarget(remainingAttempts - 1);+ }+ });+ };+ focusCurrentTarget(3);};const setupQuery = useQuery({@@ -148,6 +163,7 @@ export function ConnectionIntentInteractionBody({if (status && StatusIcon) {return (<div+ id={focusTargetId}ref={focusTargetRef}tabIndex={-1}data-testid="connection-intent-focus-target"@@ -169,6 +185,7 @@ export function ConnectionIntentInteractionBody({if (!isAddressee) {return (<div+ id={focusTargetId}ref={focusTargetRef}tabIndex={-1}data-testid="connection-intent-focus-target"@@ -197,6 +214,7 @@ export function ConnectionIntentInteractionBody({return (<div+ id={focusTargetId}ref={focusTargetRef}tabIndex={-1}data-testid="connection-intent-focus-target"diff --git a/ui/src/index.css b/ui/src/index.cssindex cdf8aca5ef..ce07222ebe 100644--- a/ui/src/index.css+++ b/ui/src/index.css@@ -91,6 +91,10 @@--border: oklch(0.922 0 0);--input: oklch(0.922 0 0);--ring: oklch(0.708 0 0);+ --scrollbar-thumb: oklch(0.7 0 0);+ --scrollbar-thumb-hover: oklch(0.6 0 0);+ --scrollbar-size: 8px;+ --scrollbar-radius: 999px;--chart-1: oklch(0.87 0 0);--chart-2: oklch(0.556 0 0);--chart-3: oklch(0.439 0 0);@@ -116,10 +120,14 @@--chip-match-identifier-bg: var(--muted);--chip-match-identifier-fg: var(--muted-foreground);--chip-match-identifier-border: var(--border);- --paperclip-doc-annotation-highlight-open: #fef08a;- --paperclip-doc-annotation-highlight-focused: #fde047;- --paperclip-doc-annotation-highlight-stale: #fef08a;- --paperclip-doc-annotation-highlight-resolved: #fef9c3;+ --paperclip-doc-annotation-highlight-source: oklch(0.78 0.16 89);+ --paperclip-doc-annotation-highlight-open: color-mix(in srgb, var(--paperclip-doc-annotation-highlight-source) 58%, var(--background));+ --paperclip-doc-annotation-highlight-focused: color-mix(in srgb, var(--paperclip-doc-annotation-highlight-source) 60%, var(--background));+ --paperclip-doc-annotation-highlight-stale: color-mix(in srgb, var(--paperclip-doc-annotation-highlight-source) 48%, var(--background));+ --paperclip-doc-annotation-highlight-resolved: color-mix(in srgb, var(--paperclip-doc-annotation-highlight-source) 28%, var(--background));+ --paperclip-doc-annotation-highlight-x-outset: 0.25rem;+ --paperclip-doc-annotation-highlight-y-outset: 0.125rem;+ --paperclip-doc-annotation-highlight-radius: 0.1875rem;/* Brand agent-capsule gradient stops (paperclip.ing/brand/)."The capsule is the agent" — each agent gets a 2-stop gradient,@@ -250,9 +258,26 @@--motion-interstitial-dwell: 4000ms; /* interstitial update hold: minimum before the next swaps in, and how long a finished update sits before sliding away */--motion-scroll-pill-enter: 200ms; /* scroll-to-latest pill entry */--motion-scroll-pill-exit: 400ms; /* scroll-to-latest pill exit */+ --motion-scrollbar-idle-delay: 600ms; /* keep the task-thread thumb visible briefly after scrolling settles */--motion-ease-scroll-pill-in: cubic-bezier(0.23, 1, 0.32, 1);--motion-ease-scroll-pill-out: cubic-bezier(0.7, 0, 0.84, 0);--motion-pane-glide: 320ms; /* properties-pane maximize/restore glide */+ --motion-side-panel-tab: var(--motion-duration-fast);++ /* Portable side-panel geometry and hierarchy. These stay centralized so+ task, project, agent, and future hosts render the same Codex-like chrome. */+ --side-panel-header-height: var(--sz-48px);+ --side-panel-tab-height: var(--sz-30px);+ --side-panel-tab-label-max-width: var(--sz-100px);+ --side-panel-tab-label-expanded-max-width: calc(var(--side-panel-tab-label-max-width) + var(--sz-18px));+ --side-panel-tab-label-fade-width: var(--sz-18px);+ --side-panel-tab-radius: var(--radius-xl);+ --side-panel-control-radius: var(--radius-xl);+ --side-panel-launcher-width: var(--sz-320px);+ --side-panel-bg: var(--background);+ --side-panel-fg: var(--foreground);+ --side-panel-tab-active-bg: color-mix(in oklab, var(--accent) 88%, var(--background));+ --side-panel-tab-hover-bg: color-mix(in oklab, var(--accent) 58%, transparent);/* Composer mode-chip hues (v5–v7 decisions): agent + plan reuse the taskstatus hues; ask is the v5 blue. Consumed as `--sc` seeds through the@@ -278,6 +303,10 @@wrapper, thread body, and pinned composer so they widen in lockstep. */--tc-shell-max-w: 60rem;+ /* Active-turn status island and its checklist overlay. */+ --sz-turn-status-island: min(100%, 42rem);+ --sz-turn-status-popover: min(32rem, calc(100vw - 2rem));+/* Mobile pinned-composer bottom offset (PAP-495). Default clears just thesafe-area inset (+20px); Layout raises it to the bottom-nav height(--sz-calc-14) while the auto-hiding mobile nav is on screen, so the@@ -289,6 +318,8 @@.dark {--background: oklch(0.145 0 0);--foreground: oklch(0.985 0 0);+ --side-panel-bg: rgb(10 10 10);+ --side-panel-fg: oklch(0.985 0 0);--card: oklch(0.205 0 0);--card-foreground: oklch(0.985 0 0);--popover: oklch(0.205 0 0);@@ -307,6 +338,8 @@--border: oklch(1 0 0 / 10%);--input: oklch(1 0 0 / 15%);--ring: oklch(0.556 0 0);+ --scrollbar-thumb: oklch(0.4 0 0);+ --scrollbar-thumb-hover: oklch(0.5 0 0);--chart-1: oklch(0.87 0 0);--chart-2: oklch(0.556 0 0);--chart-3: oklch(0.439 0 0);@@ -332,11 +365,6 @@--chip-match-identifier-bg: var(--muted);--chip-match-identifier-fg: var(--muted-foreground);--chip-match-identifier-border: var(--border);- --paperclip-doc-annotation-highlight-open: #a16207;- --paperclip-doc-annotation-highlight-focused: #ca8a04;- --paperclip-doc-annotation-highlight-stale: #854d0e;- --paperclip-doc-annotation-highlight-resolved: #713f12;-/* Dark-mode AA overrides for the status-icon hues that need a mode-specificvalue (PAP-238). in_progress / blocked stay identical (same blue / red bothmodes) and in_queue tracks in_progress, so they need no override. */@@ -348,25 +376,51 @@}::highlight(paperclip-doc-annotation-open) {- background-color: var(--paperclip-doc-annotation-highlight-open);+ background-color: transparent;color: inherit;}::highlight(paperclip-doc-annotation-focused) {- background-color: var(--paperclip-doc-annotation-highlight-focused);+ background-color: transparent;color: inherit;}::highlight(paperclip-doc-annotation-stale) {- background-color: var(--paperclip-doc-annotation-highlight-stale);+ background-color: transparent;color: inherit;}::highlight(paperclip-doc-annotation-resolved) {- background-color: var(--paperclip-doc-annotation-highlight-resolved);+ background-color: transparent;color: inherit;}+.paperclip-doc-annotation-highlight::before {+ position: absolute;+ inset:+ calc(-1 * var(--paperclip-doc-annotation-highlight-y-outset))+ calc(-1 * var(--paperclip-doc-annotation-highlight-x-outset));+ border-radius: var(--paperclip-doc-annotation-highlight-radius);+ background-color: var(--paperclip-doc-annotation-highlight-open);+ content: "";+ transition-property: background-color;+ transition-duration: var(--motion-duration-fast);+ transition-timing-function: var(--motion-ease-standard);+}++.paperclip-doc-annotation-highlight[data-focused="true"]:not([data-anchor-state="stale"]):not([data-status="resolved"])::before,+.paperclip-doc-annotation-highlight[data-hovered="true"]:not([data-anchor-state="stale"]):not([data-status="resolved"])::before {+ background-color: var(--paperclip-doc-annotation-highlight-focused);+}++.paperclip-doc-annotation-highlight[data-anchor-state="stale"]:not([data-status="resolved"])::before {+ background-color: var(--paperclip-doc-annotation-highlight-stale);+}++.paperclip-doc-annotation-highlight[data-status="resolved"]::before {+ background-color: var(--paperclip-doc-annotation-highlight-resolved);+}+@layer base {* {@apply border-border outline-ring/50;@@ -476,6 +530,32 @@background: transparent !important;}+/* Task thread: keep the gutter available without painting a persistent rail.+ Scroll events temporarily add data-scroll-active; hovering alone stays idle. */+.scrollbar-while-scrolling {+ scrollbar-width: thin;+ scrollbar-color: transparent transparent;+}+.scrollbar-while-scrolling::-webkit-scrollbar {+ width: var(--scrollbar-size);+ height: var(--scrollbar-size);+ background: transparent;+}+.scrollbar-while-scrolling::-webkit-scrollbar-track,+.scrollbar-while-scrolling::-webkit-scrollbar-thumb {+ background: transparent;+}+.scrollbar-while-scrolling[data-scroll-active="true"] {+ scrollbar-color: var(--scrollbar-thumb) transparent;+}+.scrollbar-while-scrolling[data-scroll-active="true"]::-webkit-scrollbar-thumb {+ background: var(--scrollbar-thumb);+ border-radius: var(--scrollbar-radius);+}+.scrollbar-while-scrolling[data-scroll-active="true"]::-webkit-scrollbar-thumb:hover {+ background: var(--scrollbar-thumb-hover);+}+/* The task-chat shell owns its desktop scroll viewport. Release Layout'sotherwise-useful reserved main scrollbar gutter so that viewport can meetthe properties-pane border instead of stopping one scrollbar-width early. */@@ -568,6 +648,8 @@/* --motion-interstitial-dwell is deliberately NOT zeroed: it is a pacinghold, not a movement — zeroing it would make the interstitial line churnfaster under reduced motion. Swaps themselves snap (line-scroll: 0). */+ /* --motion-scrollbar-idle-delay is also a visibility hold, not movement;+ keeping it lets reduced-motion users see the thumb while scrolling. */--motion-scroll-pill-enter: 0ms;--motion-scroll-pill-exit: 0ms;--motion-pane-glide: 0ms;@@ -684,6 +766,11 @@.tc-turn-fold[data-folded="true"] { grid-template-rows: 0fr; opacity: 0; }.tc-turn-fold > * { overflow: hidden; min-height: 0; }+/* Hover-revealed activity carets remain discoverable on touch-only devices. */+@media (hover: none) {+ .tc-hover-disclosure-caret { opacity: 1; }+}+/* Settled-turn metadata remains available on hover/focus and while expanded,but its collapsed grid track consumes no width at rest. */.tc-turn-metrics {@@ -703,6 +790,17 @@/* Properties-pane maximize/restore glide (left animates between docked andsidebar-flush while the pane is position:fixed). */.tc-pane-glide { transition: left var(--motion-pane-glide) var(--motion-ease-standard); }+.side-panel-tab-motion {+ transition-property: color, background-color, border-color, opacity, box-shadow, transform;+ transition-duration: var(--motion-side-panel-tab);+ transition-timing-function: var(--motion-ease-standard);+}+.side-panel-tab-label-fade {+ -webkit-mask-image: linear-gradient(to right, black calc(100% - var(--side-panel-tab-label-fade-width)), transparent);+ mask-image: linear-gradient(to right, black calc(100% - var(--side-panel-tab-label-fade-width)), transparent);+ -webkit-mask-repeat: no-repeat;+ mask-repeat: no-repeat;+}@media (prefers-reduced-motion: reduce) {.tc-enter-bubble,@@ -717,7 +815,8 @@.tc-turn-fold,.tc-turn-metrics,.tc-line-scroll-inner,- .tc-pane-glide { transition: none; }+ .tc-pane-glide,+ .side-panel-tab-motion { transition: none; }/* The pill keyframes carry the X-centering; with animation:none restore it. */.tc-scroll-pill-in,.tc-scroll-pill-out { transform: translate(-50%, 0); }@@ -945,6 +1044,41 @@animation: tc-live-ping var(--motion-approval-pulse) var(--motion-ease-standard) infinite;}+.paperclip-markdown.task-chat-reasoning-markdown,+.paperclip-markdown.task-chat-reasoning-markdown :is(h1, h2, h3, h4, h5, h6, strong) {+ font-size: inherit;+ font-weight: inherit;+ line-height: inherit;+}++/* Activity rows stay on one bounded line until explicitly expanded. The mask+ gives long provider text a quieter edge than an ellipsis, while the shared+ expanded treatment safely wraps paths, identifiers, and unbroken tokens. */+.task-chat-collapsed-line-fade {+ overflow: hidden;+ white-space: nowrap;+ text-overflow: clip;+ -webkit-mask-image: linear-gradient(+ to right,+ black 0,+ black calc(100% - 2rem),+ transparent 100%+ );+ mask-image: linear-gradient(+ to right,+ black 0,+ black calc(100% - 2rem),+ transparent 100%+ );+}++.task-chat-expanded-line-wrap,+.paperclip-markdown.task-chat-reasoning-markdown,+.paperclip-markdown.task-chat-reasoning-markdown :is(p, strong, em, a, code) {+ overflow-wrap: anywhere;+ word-break: break-word;+}+@media (prefers-reduced-motion: reduce) {.tc-stream-block-enter,.tc-live-ping {@@ -2130,6 +2264,8 @@ span.paperclip-mention-chip[data-mention-kind="external-object"] {--sz-52vh: 52vh;--sz-40rem: 40rem;--sz-44rem: 44rem;+ --sz-36rem: 36rem;+ --sz-neg-1_25rem: -1.25rem;--sz-30pct: 30%;--sz-24pct: 24%;--sz-18pct: 18%;@@ -2302,6 +2438,7 @@ span.paperclip-mention-chip[data-mention-kind="external-object"] {:root {--gtc-1: 56px 56px 24px minmax(0,1fr); /* Extracted from ui/src/components/DocumentDiffModal.tsx (grid-cols-[56px_56px_24px_minmax(0,1fr)]). */--gtc-case-revisions: 16rem 1fr; /* Extracted from ui/src/components/CaseRevisionRail.tsx (grid-cols-[16rem_1fr]). */+ --gtc-task-chat-details: 6rem minmax(0,1fr);--gtc-2: auto minmax(0,1fr) 2.25rem; /* Extracted from ui/src/components/FileTree.tsx (grid-cols-[auto_minmax(0,1fr)_2.25rem]). */--gtc-3: minmax(0,1fr) 2.25rem; /* Extracted from ui/src/components/FileTree.tsx (grid-cols-[minmax(0,1fr)_2.25rem]). */--gtc-4: minmax(0,1fr); /* Extracted from ui/src/components/FileTree.tsx (grid-cols-[minmax(0,1fr)]). */@@ -2363,6 +2500,12 @@ span.paperclip-mention-chip[data-mention-kind="external-object"] {--gtc-63: 280px 1fr;--gtc-64: minmax(0,20rem) 1fr;--gtc-65: minmax(8rem,0.38fr) minmax(0,0.62fr) auto;+ --gtc-runner-inspector-stage: 1.25rem minmax(0,1fr);+ --gtc-runner-inspector-filters: minmax(14rem,1fr) repeat(5,minmax(8rem,auto));+ --gtc-runner-inspector-pipeline: 21rem minmax(0,1fr);+ --gtc-runner-inspector-fields: 8rem 1fr;+ --gtc-runner-inspector-presentation: minmax(18rem,0.8fr) minmax(20rem,1.2fr);+ --gtc-runner-inspector-trace: 20rem minmax(0,1fr);--gtr-1: auto auto; /* Extracted from ui/src/components/ui/card.tsx (grid-rows-[auto_auto]). */--gtr-2: 1fr; /* Extracted from ui/src/pages/CompanySkills.tsx (grid-rows-[1fr]). */--gtr-3: 0fr; /* Extracted from ui/src/pages/CompanySkills.tsx (grid-rows-[0fr]). */diff --git a/ui/src/lib/activity-format.ts b/ui/src/lib/activity-format.tsindex 52552d1c29..f1dc710c3c 100644--- a/ui/src/lib/activity-format.ts+++ b/ui/src/lib/activity-format.ts@@ -80,6 +80,7 @@ const ACTIVITY_ROW_VERBS: Record<string, string> = {"issue.thread_interaction_answered": "answered the request on","issue.thread_interaction_withdrawn": "withdrew the request on","issue.thread_interaction_cancelled": "cancelled the request on",+ "issue.thread_interaction_skipped": "skipped the request on","issue.thread_interaction_expired": "expired the request on","issue.thread_interaction_item_verdicts_submitted": "submitted verdicts on","issue.stalled_review_decided": "recorded a review verdict on",@@ -153,6 +154,7 @@ const ISSUE_ACTIVITY_LABELS: Record<string, string> = {"issue.thread_interaction_answered": "answered the request","issue.thread_interaction_withdrawn": "withdrew the request","issue.thread_interaction_cancelled": "cancelled the request",+ "issue.thread_interaction_skipped": "skipped the request","issue.thread_interaction_expired": "expired the request","issue.thread_interaction_item_verdicts_submitted": "submitted verdicts on the request","issue.stalled_review_decided": "recorded a review verdict",diff --git a/ui/src/lib/composer-draft.ts b/ui/src/lib/composer-draft.tsindex 400007ccac..eeb3f99b3f 100644--- a/ui/src/lib/composer-draft.ts+++ b/ui/src/lib/composer-draft.ts@@ -36,3 +36,20 @@ export function clearDraft(draftKey: string) {// Ignore localStorage failures.}}++export function loadStructuredDraft<T>(draftKey: string, fallback: T): T {+ try {+ const value = localStorage.getItem(draftKey);+ return value ? JSON.parse(value) as T : fallback;+ } catch {+ return fallback;+ }+}++export function saveStructuredDraft(draftKey: string, value: unknown) {+ try {+ localStorage.setItem(draftKey, JSON.stringify(value));+ } catch {+ // Ignore localStorage failures.+ }+}diff --git a/ui/src/lib/interaction-audience.test.ts b/ui/src/lib/interaction-audience.test.tsindex 8ac3a162d0..bc38b40e56 100644--- a/ui/src/lib/interaction-audience.test.ts+++ b/ui/src/lib/interaction-audience.test.ts@@ -172,7 +172,7 @@ describe("describeInteractionAudience", () => {expect(audience.label).toBe("Addressed");});- it("lets human_only win over a named addressee", () => {+ it("keeps named ownership visible while human_only controls authorization", () => {const audience = describeInteractionAudience({interaction: confirmation({addresseeAgentId: "agent-release",@@ -182,8 +182,9 @@ describe("describeInteractionAudience", () => {addresseeLabel: "ReleaseBot",});expect(audience.summary).toBe(- "Only a person on the board can respond — agents cannot resolve this card.",+ "Assigned to ReleaseBot. Only a person on the board can respond — agents cannot resolve this card.",);+ expect(audience.shortSummary).toBe("Assigned to ReleaseBot · board only");expect(audience.label).toBe("Human only");});diff --git a/ui/src/lib/interaction-audience.ts b/ui/src/lib/interaction-audience.tsindex 398cb8a05c..708c15ed06 100644--- a/ui/src/lib/interaction-audience.ts+++ b/ui/src/lib/interaction-audience.ts@@ -191,7 +191,7 @@ export function describeResolverAudience({const summary = isUserAddressee? `Only ${addressee} can respond.`: policy === "human_only"- ? "Only a person on the board can respond — agents cannot resolve this card."+ ? `${hasAddressee ? `Assigned to ${addressee}. ` : ""}Only a person on the board can respond — agents cannot resolve this card.`: hasAddressee? `Only ${addressee} or a person on the board can respond.`: policy === "not_creator"@@ -203,7 +203,9 @@ export function describeResolverAudience({const shortSummary = isUserAddressee? `Only ${addressee} can respond`: policy === "human_only"- ? "Only the board can respond"+ ? hasAddressee+ ? `Assigned to ${addressee} · board only`+ : "Only the board can respond": hasAddressee? `Only ${addressee} or the board can respond`: policy === "not_creator"diff --git a/ui/src/lib/issue-chat-messages.test.ts b/ui/src/lib/issue-chat-messages.test.tsindex 4828b7650d..3d325d7e3f 100644--- a/ui/src/lib/issue-chat-messages.test.ts+++ b/ui/src/lib/issue-chat-messages.test.ts@@ -207,6 +207,31 @@ function createRequestConfirmation(}describe("buildAssistantPartsFromTranscript", () => {+ it("keeps canonical provider activity structured for the task-thread widget", () => {+ const result = buildAssistantPartsFromTranscript([{+ kind: "provider_activity",+ ts: "2026-08-21T12:00:00.000Z",+ family: "plan",+ eventType: "plan.updated",+ status: "completed",+ title: "Plan",+ summary: "Plan synchronized",+ payload: { steps: [{ stepId: "s1", body: "Validate schemas", status: "completed" }] },+ }]);+ expect(result.parts).toHaveLength(1);+ expect(result.parts[0]).toMatchObject({+ type: "tool-call",+ toolName: "paperclip_provider_activity",+ args: {+ family: "plan",+ eventType: "plan.updated",+ payload: { steps: [{ body: "Validate schemas" }] },+ },+ result: { status: "completed" },+ });+ expect(JSON.stringify(result.parts)).not.toContain("reasoning");+ });+it("maps assistant text, reasoning, and tool activity while omitting noisy stderr", () => {const result = buildAssistantPartsFromTranscript([{@@ -260,6 +285,19 @@ describe("buildAssistantPartsFromTranscript", () => {expect(result.notices).toEqual([]);});+ it("accumulates streamed tool output before the completed result", () => {+ const result = buildAssistantPartsFromTranscript([+ { kind: "tool_call", ts: "2026-04-06T12:00:00.000Z", name: "shell", toolUseId: "tool-1", input: {} },+ { kind: "tool_result", ts: "2026-04-06T12:00:01.000Z", toolUseId: "tool-1", content: "first\n", delta: true },+ { kind: "tool_result", ts: "2026-04-06T12:00:02.000Z", toolUseId: "tool-1", content: "second\n", delta: true },+ { kind: "tool_result", ts: "2026-04-06T12:00:03.000Z", toolUseId: "tool-1", content: "", isError: false },+ ]);++ expect(result.parts).toMatchObject([+ { type: "tool-call", toolCallId: "tool-1", result: "first\nsecond\n", isError: false },+ ]);+ });+it("preserves transcript ordering when text and tool activity are interleaved", () => {const result = buildAssistantPartsFromTranscript([{ kind: "assistant", ts: "2026-04-06T12:00:00.000Z", text: "First." },diff --git a/ui/src/lib/issue-chat-messages.ts b/ui/src/lib/issue-chat-messages.tsindex 10b224fe81..7bd8f3fd70 100644--- a/ui/src/lib/issue-chat-messages.ts+++ b/ui/src/lib/issue-chat-messages.ts@@ -36,6 +36,12 @@ export interface IssueChatComment extends IssueComment {queueTargetRunId?: string | null;queueReason?: "hold" | "active_run" | "other";followUpRequested?: boolean;+ /** Causal conversation slot: the run that actually consumed this input. */+ consumedByRunId?: string | null;+ /** Same-turn PRP steering acknowledgement for this human input. */+ steeredIntoRunId?: string | null;+ conversationAnchorAt?: Date | string | null;+ conversationAnchorSequence?: number;}export interface IssueChatLinkedRun {@@ -51,6 +57,8 @@ export interface IssueChatLinkedRun {hasStoredOutput?: boolean;logBytes?: number | null;errorCode?: string | null;+ scheduledRetryAt?: string | null;+ nextAction?: string | null;resultJson?: Record<string, unknown> | null;}@@ -965,13 +973,17 @@ export function buildAssistantPartsFromTranscript(entries: readonly IssueChatTraif (entry.kind === "tool_result") {const toolCallId = entry.toolUseId || `tool-result-${index}`;const existing = toolParts.get(toolCallId);+ const existingResult = typeof existing?.result === "string" ? existing.result : "";+ const result = entry.delta+ ? `${existingResult}${entry.content ?? ""}`+ : (entry.content || existingResult);const nextPart: ToolCallMessagePart<JsonObject, unknown> = {type: "tool-call",toolCallId,toolName: existing?.toolName || entry.toolName || "tool",args: existing?.args ?? {},argsText: existing?.argsText ?? "",- result: entry.content ?? "",+ result,isError: entry.isError === true,};if (existing) {diff --git a/ui/src/lib/issue-document-deep-link.test.ts b/ui/src/lib/issue-document-deep-link.test.tsindex f7f2a53dfd..fca00b3ae1 100644--- a/ui/src/lib/issue-document-deep-link.test.ts+++ b/ui/src/lib/issue-document-deep-link.test.ts@@ -16,10 +16,10 @@ describe("resolveIssueDocumentDeepLink", () => {});});- it("routes ordinary and annotated documents to Artifacts", () => {+ it("routes ordinary and annotated documents to a dedicated document tab", () => {expect(resolveIssueDocumentDeepLink("#document-qa%20evidence&thread=thread-1")).toEqual({kind: "properties-pane",- tab: "artifacts",+ tab: "document",documentKey: "qa evidence",});});diff --git a/ui/src/lib/issue-document-deep-link.ts b/ui/src/lib/issue-document-deep-link.tsindex 558f99a69e..cfee5e2a01 100644--- a/ui/src/lib/issue-document-deep-link.ts+++ b/ui/src/lib/issue-document-deep-link.ts@@ -4,13 +4,13 @@ import { parseDocumentAnnotationHash } from "./document-annotation-hash";export type IssueDocumentDeepLinkRoute =| { kind: "continuation-summary" }| { kind: "properties-pane"; tab: "plans"; documentKey: "plan" }- | { kind: "properties-pane"; tab: "artifacts"; documentKey: string };+ | { kind: "properties-pane"; tab: "document"; documentKey: string };/*** Maps an issue document hash to the surface that owns that document.** The continuation summary remains in the activity/handoff surface, the plan- * keeps its dedicated pane tab, and every other document belongs to Artifacts.+ * keeps its dedicated pane tab, and every other document opens in its own tab.*/export function resolveIssueDocumentDeepLink(hash: string): IssueDocumentDeepLinkRoute | null {const target = parseDocumentAnnotationHash(hash);@@ -22,5 +22,5 @@ export function resolveIssueDocumentDeepLink(hash: string): IssueDocumentDeepLinif (target.documentKey === "plan") {return { kind: "properties-pane", tab: "plans", documentKey: "plan" };}- return { kind: "properties-pane", tab: "artifacts", documentKey: target.documentKey };+ return { kind: "properties-pane", tab: "document", documentKey: target.documentKey };}diff --git a/ui/src/lib/issue-queued-comment-queue.test.ts b/ui/src/lib/issue-queued-comment-queue.test.tsnew file mode 100644index 0000000000..d0d7bac6de--- /dev/null+++ b/ui/src/lib/issue-queued-comment-queue.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from "vitest";+import { normalizeIssueQueuedCommentQueue } from "./issue-queued-comment-queue";++describe("normalizeIssueQueuedCommentQueue", () => {+ it("sorts, deduplicates, and drops malformed queue entries", () => {+ const queue = normalizeIssueQueuedCommentQueue({+ issueId: "issue-1",+ queueId: "wake-1",+ state: "deferred",+ targetRunId: "run-1",+ revision: "rev-1",+ protocol: "paperclip_runner_v1",+ steeringDisposition: "available",+ entries: [+ { comment: { id: "second", body: "Second" }, position: 2, canEdit: true, canDiscard: true },+ { comment: { id: "first", body: "First" }, position: 0, canEdit: false, canDiscard: true },+ { comment: { id: "first", body: "Duplicate" }, position: 1, canEdit: true, canDiscard: true },+ { comment: { body: "Missing id" }, position: 3 },+ ],+ }, "fallback");++ expect(queue.entries.map((entry) => entry.comment.id)).toEqual(["first", "second"]);+ expect(queue.entries.map((entry) => entry.position)).toEqual([0, 1]);+ expect(queue.protocol).toBe("paperclip_runner_v1");+ expect(queue.queueId).toBe("wake-1");+ expect(queue.state).toBe("deferred");+ expect(queue.steeringDisposition).toBe("available");+ });++ it("fails closed for malformed protocol and steering data", () => {+ const queue = normalizeIssueQueuedCommentQueue({ entries: "nope" }, "issue-fallback");+ expect(queue).toMatchObject({+ issueId: "issue-fallback",+ queueId: null,+ state: null,+ targetRunId: null,+ revision: "unavailable",+ protocol: "legacy",+ steeringDisposition: "unsupported",+ entries: [],+ });+ });+});diff --git a/ui/src/lib/issue-queued-comment-queue.ts b/ui/src/lib/issue-queued-comment-queue.tsnew file mode 100644index 0000000000..b4296dab64--- /dev/null+++ b/ui/src/lib/issue-queued-comment-queue.ts@@ -0,0 +1,68 @@+import type {+ IssueComment,+ IssueQueuedCommentQueue,+ IssueQueuedCommentQueueState,+ IssueQueuedCommentSteeringDisposition,+} from "@paperclipai/shared";++function record(value: unknown): Record<string, unknown> | null {+ return typeof value === "object" && value !== null && !Array.isArray(value)+ ? value as Record<string, unknown>+ : null;+}++const STEERING_DISPOSITIONS = new Set<IssueQueuedCommentSteeringDisposition>([+ "available",+ "unsupported",+ "temporarily_unavailable",+]);+const QUEUE_STATES = new Set<IssueQueuedCommentQueueState>(["deferred", "queued"]);++/** Defensive boundary shared by IssueDetail and Storybook queue fixtures. */+export function normalizeIssueQueuedCommentQueue(+ value: unknown,+ fallbackIssueId: string,+): IssueQueuedCommentQueue {+ const source = record(value);+ const seen = new Set<string>();+ const entries = (Array.isArray(source?.entries) ? source.entries : [])+ .flatMap((candidate, sourcePosition) => {+ const entry = record(candidate);+ const comment = record(entry?.comment);+ const id = typeof comment?.id === "string" ? comment.id : "";+ const body = typeof comment?.body === "string" ? comment.body : null;+ if (!id || body === null || seen.has(id)) return [];+ seen.add(id);+ const position = typeof entry?.position === "number" && Number.isFinite(entry.position)+ ? entry.position+ : sourcePosition;+ return [{+ comment: comment as unknown as IssueComment,+ position,+ canEdit: entry?.canEdit === true,+ canDiscard: entry?.canDiscard === true,+ }];+ })+ .sort((left, right) => left.position - right.position)+ .map((entry, position) => ({ ...entry, position }));+ const disposition = source?.steeringDisposition;+ const state = source?.state;++ return {+ issueId: typeof source?.issueId === "string" ? source.issueId : fallbackIssueId,+ queueId: typeof source?.queueId === "string" ? source.queueId : null,+ state:+ typeof state === "string" && QUEUE_STATES.has(state as IssueQueuedCommentQueueState)+ ? state as IssueQueuedCommentQueueState+ : null,+ targetRunId: typeof source?.targetRunId === "string" ? source.targetRunId : null,+ revision: typeof source?.revision === "string" ? source.revision : "unavailable",+ protocol: source?.protocol === "paperclip_runner_v1" ? "paperclip_runner_v1" : "legacy",+ steeringDisposition:+ typeof disposition === "string"+ && STEERING_DISPOSITIONS.has(disposition as IssueQueuedCommentSteeringDisposition)+ ? disposition as IssueQueuedCommentSteeringDisposition+ : "unsupported",+ entries,+ };+}diff --git a/ui/src/lib/issue-thread-interactions.test.ts b/ui/src/lib/issue-thread-interactions.test.tsindex 536a34b6aa..4eb8cad051 100644--- a/ui/src/lib/issue-thread-interactions.test.ts+++ b/ui/src/lib/issue-thread-interactions.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from "vitest";import {+ buildAnsweredQuestionsDeliveryText,buildIssueThreadInteractionSummary,buildSuggestedTaskTree,collectSuggestedTaskClientKeys,@@ -8,6 +9,7 @@ import {getItemVerdictProgress,getRequestConfirmationTargetHref,getQuestionAnswerLabels,+ interactionReplacesComposerSkip,isDegenerateAskUserQuestions,isSupersededByNewerSiblingInteraction,shouldHideInteractionCard,@@ -59,6 +61,91 @@ describe("buildSuggestedTaskTree", () => {});describe("issue thread interaction helpers", () => {+ it("replaces composer Skip only when the durable form has its own alternative path", () => {+ const base = {+ id: "interaction-1",+ companyId: "company-1",+ issueId: "issue-1",+ status: "pending",+ continuationPolicy: "wake_assignee",+ ...resolverPolicyFields,+ createdAt: "2026-04-06T12:00:00.000Z",+ updatedAt: "2026-04-06T12:00:00.000Z",+ result: null,+ } as const;+ expect(interactionReplacesComposerSkip({+ ...base,+ kind: "request_confirmation",+ payload: { version: 1, prompt: "Proceed?" },+ } as IssueThreadInteraction)).toBe(true);+ expect(interactionReplacesComposerSkip({+ ...base,+ kind: "request_checkbox_confirmation",+ payload: { version: 1, prompt: "Select", options: [] },+ } as IssueThreadInteraction)).toBe(true);+ expect(interactionReplacesComposerSkip({+ ...base,+ kind: "suggest_tasks",+ payload: { version: 1, tasks: [] },+ } as IssueThreadInteraction)).toBe(true);+ expect(interactionReplacesComposerSkip({+ ...base,+ kind: "ask_user_questions",+ payload: { version: 1, questions: [] },+ } as IssueThreadInteraction)).toBe(false);+ expect(interactionReplacesComposerSkip({+ ...base,+ kind: "request_item_verdicts",+ payload: { version: 1, prompt: "Review", items: [] },+ } as IssueThreadInteraction)).toBe(false);+ });++ it("formats successor-turn answer delivery with canonical prompts and labels", () => {+ const interaction = {+ id: "interaction-answers",+ companyId: "company-1",+ issueId: "issue-1",+ kind: "ask_user_questions",+ status: "answered",+ continuationPolicy: "wake_assignee",+ ...resolverPolicyFields,+ createdAt: "2026-04-06T12:00:00.000Z",+ updatedAt: "2026-04-06T12:01:00.000Z",+ payload: {+ version: 1,+ questions: [+ { id: "purpose", prompt: "What is it for?", selectionMode: "single", options: [] },+ { id: "runtime", prompt: "Which runtime?", selectionMode: "single", options: [{ id: "node", label: "Node.js" }] },+ { id: "features", prompt: "Which features?", selectionMode: "multi", options: [{ id: "logs", label: "Request logs" }] },+ ],+ questionSet: {+ schema: "paperclip.question_set.v1",+ questions: [+ { id: "purpose", header: "Purpose", prompt: "What is it for?", required: true, answerMode: "text" },+ { id: "runtime", header: "Runtime", prompt: "Which runtime?", required: true, answerMode: "single_select", options: [{ id: "node", label: "Node.js" }] },+ { id: "features", header: "Features", prompt: "Which features?", required: false, answerMode: "multi_select", options: [{ id: "logs", label: "Request logs" }], customAnswer: { enabled: true, label: "Other" } },+ ],+ },+ },+ result: {+ version: 1,+ answers: [+ { questionId: "purpose", optionIds: [], otherText: "Internal API" },+ { questionId: "runtime", optionIds: ["node"] },+ { questionId: "features", optionIds: ["logs"], otherText: "Metrics" },+ ],+ },+ } satisfies AskUserQuestionsInteraction;++ expect(buildAnsweredQuestionsDeliveryText(interaction)).toBe([+ "Answered questions",+ "",+ "- Purpose — What is it for?: Internal API",+ "- Runtime — Which runtime?: Node.js",+ "- Features — Which features?: Request logs, Metrics",+ ].join("\n"));+ });+it("summarizes task and question interactions", () => {expect(buildIssueThreadInteractionSummary({id: "interaction-1",diff --git a/ui/src/lib/issue-thread-interactions.ts b/ui/src/lib/issue-thread-interactions.tsindex b1217bed57..560d86ce19 100644--- a/ui/src/lib/issue-thread-interactions.ts+++ b/ui/src/lib/issue-thread-interactions.ts@@ -63,6 +63,19 @@ export interface SuggestedTaskTreeNode {children: SuggestedTaskTreeNode[];}+/**+ * These takeovers already expose a deliberate non-accept path in their form.+ * Showing the composer's generic Skip beside Reject/Revise duplicates that+ * escape hatch and makes the action hierarchy ambiguous.+ */+export function interactionReplacesComposerSkip(+ interaction: IssueThreadInteraction,+): boolean {+ return interaction.kind === "request_confirmation"+ || interaction.kind === "request_checkbox_confirmation"+ || interaction.kind === "suggest_tasks";+}+export function isIssueThreadInteraction(value: unknown,): value is IssueThreadInteraction {@@ -188,6 +201,7 @@ export function buildIssueThreadInteractionSummary(const administrativeOutcome = interaction.result && "outcome" in interaction.result? interaction.result.outcome: null;+ if (administrativeOutcome === "skipped") return "Skipped interaction";if (administrativeOutcome === "withdrawn") return "Withdrawn interaction";if (administrativeOutcome === "issue_closed") return "Expired when issue closed";if (administrativeOutcome === "addressee_deleted") return "Cancelled when addressee was deleted";@@ -271,6 +285,34 @@ export function buildIssueThreadInteractionSummary(return count === 1 ? "Asked 1 question" : `Asked ${count} questions`;}+/** Readable model input for a durable answer delivered into a successor run. */+export function buildAnsweredQuestionsDeliveryText(+ interaction: AskUserQuestionsInteraction,+): string {+ const questionSet = interaction.payload.questionSet;+ const legacyQuestionById = new Map(+ interaction.payload.questions.map((question) => [question.id, question] as const),+ );+ const canonicalQuestionById = new Map(+ (questionSet?.questions ?? []).map((question) => [question.id, question] as const),+ );+ const lines = (interaction.result?.answers ?? []).map((answer) => {+ const canonical = canonicalQuestionById.get(answer.questionId);+ const legacy = legacyQuestionById.get(answer.questionId);+ const optionLabels = new Map(+ (canonical?.options ?? legacy?.options ?? []).map((option) => [option.id, option.label] as const),+ );+ const values = answer.optionIds.map((optionId) => optionLabels.get(optionId) ?? optionId);+ if (answer.otherText?.trim()) values.push(answer.otherText.trim());+ const prompt = canonical?.prompt ?? legacy?.prompt ?? answer.questionId;+ const label = canonical?.header && canonical.header !== prompt+ ? `${canonical.header} — ${prompt}`+ : prompt;+ return `- ${label}: ${values.join(", ") || "No answer"}`;+ });+ return ["Answered questions", ...(lines.length > 0 ? ["", ...lines] : [])].join("\n");+}+export function buildSuggestedTaskTree(tasks: readonly SuggestedTaskDraft[],): SuggestedTaskTreeNode[] {diff --git a/ui/src/lib/optimistic-issue-comments.test.ts b/ui/src/lib/optimistic-issue-comments.test.tsindex e3527976ae..94e8b62f99 100644--- a/ui/src/lib/optimistic-issue-comments.test.ts+++ b/ui/src/lib/optimistic-issue-comments.test.ts@@ -112,6 +112,65 @@ describe("optimistic issue comments", () => {expect(merged.map((comment) => comment.id)).toEqual(["optimistic-1", "comment-2"]);});+ it("reconciles an optimistic comment with its canonical server copy", () => {+ const optimistic = createOptimisticIssueComment({+ companyId: "company-1",+ issueId: "issue-1",+ body: "Do not flash twice",+ authorUserId: "board-1",+ });+ const { clientId: _clientId, clientStatus: _clientStatus, queueTargetRunId: _queueTargetRunId, ...persisted } = optimistic;++ const merged = mergeIssueComments(+ [{ ...persisted, id: "comment-1" }],+ [optimistic],+ );++ expect(merged.map((comment) => comment.id)).toEqual(["comment-1"]);+ });++ it("reconciles repeated identical comments one-for-one", () => {+ const first = createOptimisticIssueComment({+ companyId: "company-1",+ issueId: "issue-1",+ body: "Same text",+ authorUserId: "board-1",+ });+ const second = createOptimisticIssueComment({+ companyId: "company-1",+ issueId: "issue-1",+ body: "Same text",+ authorUserId: "board-1",+ });+ const { clientId: _clientId, clientStatus: _clientStatus, queueTargetRunId: _queueTargetRunId, ...persisted } = first;++ const merged = mergeIssueComments(+ [{ ...persisted, id: "comment-1" }],+ [first, second],+ );++ expect(merged).toHaveLength(2);+ expect(merged.map((comment) => comment.id)).toContain("comment-1");+ expect(merged.map((comment) => comment.id)).toContain(second.id);+ });++ it("keeps repeated identical optimistic comments when neither is persisted", () => {+ const first = createOptimisticIssueComment({+ companyId: "company-1",+ issueId: "issue-1",+ body: "Same pending text",+ authorUserId: "board-1",+ });+ const second = createOptimisticIssueComment({+ companyId: "company-1",+ issueId: "issue-1",+ body: "Same pending text",+ authorUserId: "board-1",+ });++ expect(mergeIssueComments([], [first, second])).toHaveLength(2);+ });+it("can take one optimistic queued comment back out of the queue", () => {const first = createOptimisticIssueComment({companyId: "company-1",diff --git a/ui/src/lib/optimistic-issue-comments.ts b/ui/src/lib/optimistic-issue-comments.tsindex f5b4814e1a..1c76a400df 100644--- a/ui/src/lib/optimistic-issue-comments.ts+++ b/ui/src/lib/optimistic-issue-comments.ts@@ -132,12 +132,31 @@ export function mergeIssueComments(comments: IssueComment[] | undefined,optimisticComments: OptimisticIssueComment[],): IssueTimelineComment[] {- const merged = [...(comments ?? [])];+ const persistedComments = comments ?? [];+ const merged = [...persistedComments];const existingIds = new Set(merged.map((comment) => comment.id));+ const reconciledPersistedIds = new Set<string>();for (const comment of optimisticComments) {- if (!existingIds.has(comment.id)) {- merged.push(comment);+ if (existingIds.has(comment.id)) continue;++ // The mutation response and comments feed can publish the canonical+ // comment in different React Query notifications. Keep the optimistic row+ // mounted through that handoff without briefly rendering both versions.+ // Consume matches one-for-one so repeated identical messages remain valid.+ const matchingPersistedComment = persistedComments.find((persisted) =>+ !reconciledPersistedIds.has(persisted.id) &&+ persisted.issueId === comment.issueId &&+ persisted.authorType === comment.authorType &&+ persisted.authorUserId === comment.authorUserId &&+ persisted.body === comment.body &&+ Math.abs(toTimestamp(persisted.createdAt) - toTimestamp(comment.createdAt)) <= 60_000+ );+ if (matchingPersistedComment) {+ reconciledPersistedIds.add(matchingPersistedComment.id);+ continue;}++ merged.push(comment);}return sortIssueComments(merged);}diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.tsindex 963cc18a88..135caefd8d 100644--- a/ui/src/lib/queryKeys.ts+++ b/ui/src/lib/queryKeys.ts@@ -14,19 +14,24 @@ export const queryKeys = {* asked. A different account is a different entry, so there is nothing to* mistake. `null` is the signed-out/local_trusted key.*/- list: (userId: string | null) => ["companies", "list", userId ?? "anonymous"] as const,+ list: (userId: string | null) =>+ ["companies", "list", userId ?? "anonymous"] as const,detail: (id: string) => ["companies", id] as const,stats: ["companies", "stats"] as const,- exportFidelity: (companyId: string) => ["companies", companyId, "export-fidelity"] as const,+ exportFidelity: (companyId: string) =>+ ["companies", companyId, "export-fidelity"] as const,},apps: {gallery: (companyId: string) => ["apps", companyId, "gallery"] as const,attention: (companyId: string) => ["apps", companyId, "attention"] as const,},tools: {- applications: (companyId: string) => ["tools", companyId, "applications"] as const,- connections: (companyId: string) => ["tools", companyId, "connections"] as const,- connection: (connectionId: string) => ["tools", "connection", connectionId] as const,+ applications: (companyId: string) =>+ ["tools", companyId, "applications"] as const,+ connections: (companyId: string) =>+ ["tools", companyId, "connections"] as const,+ connection: (connectionId: string) =>+ ["tools", "connection", connectionId] as const,connectionInstalls: (connectionId: string) =>["tools", "connection", connectionId, "installs"] as const,connectionGrants: (connectionId: string) =>@@ -39,22 +44,36 @@ export const queryKeys = {testAgents: (connectionId: string) =>["tools", "connection", connectionId, "test-agents"] as const,testCallStatus: (connectionId: string, actionRequestId: string) =>- ["tools", "connection", connectionId, "test-calls", actionRequestId] as const,+ [+ "tools",+ "connection",+ connectionId,+ "test-calls",+ actionRequestId,+ ] as const,actionRequests: (companyId: string, status: string) =>["tools", companyId, "action-requests", status] as const,gateways: (companyId: string) => ["tools", "gateways", companyId] as const,profiles: (companyId: string) => ["tools", companyId, "profiles"] as const,- profileNewTools: (profileId: string) => ["tools", "profiles", profileId, "new-tools"] as const,+ profileNewTools: (profileId: string) =>+ ["tools", "profiles", profileId, "new-tools"] as const,effectiveProfilesForAgent: (companyId: string, agentId: string) =>["tools", companyId, "profiles", "effective", "agent", agentId] as const,- stdioTemplates: (companyId: string) => ["tools", companyId, "stdio-templates"] as const,- runtimeSlots: (companyId: string) => ["tools", companyId, "runtime-slots"] as const,- runtimeHealth: (companyId: string) => ["tools", companyId, "runtime-health"] as const,- runDecisions: (companyId: string, runId: string) => ["tools", companyId, "runs", runId, "decisions"] as const,- liveRuntimeSlots: (companyId: string) => ["tools", companyId, "runtime-slots", "live"] as const,+ stdioTemplates: (companyId: string) =>+ ["tools", companyId, "stdio-templates"] as const,+ runtimeSlots: (companyId: string) =>+ ["tools", companyId, "runtime-slots"] as const,+ runtimeHealth: (companyId: string) =>+ ["tools", companyId, "runtime-health"] as const,+ runDecisions: (companyId: string, runId: string) =>+ ["tools", companyId, "runs", runId, "decisions"] as const,+ liveRuntimeSlots: (companyId: string) =>+ ["tools", companyId, "runtime-slots", "live"] as const,policies: (companyId: string) => ["tools", companyId, "policies"] as const,- trustRules: (companyId: string) => ["tools", companyId, "trust-rules"] as const,- audit: (companyId: string, limit: number) => ["tools", companyId, "audit", limit] as const,+ trustRules: (companyId: string) =>+ ["tools", companyId, "trust-rules"] as const,+ audit: (companyId: string, limit: number) =>+ ["tools", companyId, "audit", limit] as const,activity: (companyId: string,filters: { gateway?: string; app?: string; agent?: string; outcome?: string; window?: string; search?: string },@@ -102,17 +121,22 @@ export const queryKeys = {] as const,},smokeLab: {- services: (companyId: string) => ["smoke-lab", companyId, "services"] as const,+ services: (companyId: string) =>+ ["smoke-lab", companyId, "services"] as const,runs: (companyId: string) => ["smoke-lab", companyId, "runs"] as const,- run: (companyId: string, runId: string) => ["smoke-lab", companyId, "runs", runId] as const,+ run: (companyId: string, runId: string) =>+ ["smoke-lab", companyId, "runs", runId] as const,},companySkills: {list: (companyId: string) => ["company-skills", companyId] as const,listRecent: (companyId: string) =>["company-skills", companyId, "recent-updated"] as const,- detail: (companyId: string, skillId: string) => ["company-skills", companyId, skillId] as const,- versions: (companyId: string, skillId: string) => ["company-skills", companyId, skillId, "versions"] as const,- comments: (companyId: string, skillId: string) => ["company-skills", companyId, skillId, "comments"] as const,+ detail: (companyId: string, skillId: string) =>+ ["company-skills", companyId, skillId] as const,+ versions: (companyId: string, skillId: string) =>+ ["company-skills", companyId, skillId, "versions"] as const,+ comments: (companyId: string, skillId: string) =>+ ["company-skills", companyId, skillId, "comments"] as const,updateStatus: (companyId: string, skillId: string) =>["company-skills", companyId, skillId, "update-status"] as const,forkPrecheck: (companyId: string, skillId: string) =>@@ -120,8 +144,15 @@ export const queryKeys = {file: (companyId: string, skillId: string, relativePath: string) =>["company-skills", companyId, skillId, "file", relativePath] as const,catalog: (filters: { kind?: string; category?: string; q?: string } = {}) =>- ["company-skills", "catalog", filters.kind ?? "__all-kinds__", filters.category ?? "__all-categories__", filters.q ?? ""] as const,- catalogDetail: (catalogRef: string) => ["company-skills", "catalog", "detail", catalogRef] as const,+ [+ "company-skills",+ "catalog",+ filters.kind ?? "__all-kinds__",+ filters.category ?? "__all-categories__",+ filters.q ?? "",+ ] as const,+ catalogDetail: (catalogRef: string) =>+ ["company-skills", "catalog", "detail", catalogRef] as const,catalogFile: (catalogRef: string, relativePath: string) =>["company-skills", "catalog", "file", catalogRef, relativePath] as const,testInputs: (companyId: string, skillId: string) =>@@ -129,17 +160,31 @@ export const queryKeys = {testRunTemplates: (companyId: string) =>["company-skills", companyId, "test-run-templates"] as const,testRuns: (companyId: string, skillId: string, inputId?: string | null) =>- ["company-skills", companyId, skillId, "test-runs", inputId ?? "__all-inputs__"] as const,+ [+ "company-skills",+ companyId,+ skillId,+ "test-runs",+ inputId ?? "__all-inputs__",+ ] as const,testRunDetail: (companyId: string, skillId: string, runId: string) =>["company-skills", companyId, skillId, "test-run", runId] as const,},teamCatalog: {catalog: (filters: { kind?: string; category?: string; q?: string } = {}) =>- ["team-catalog", "catalog", filters.kind ?? "__all-kinds__", filters.category ?? "__all-categories__", filters.q ?? ""] as const,- catalogDetail: (catalogRef: string) => ["team-catalog", "catalog", "detail", catalogRef] as const,+ [+ "team-catalog",+ "catalog",+ filters.kind ?? "__all-kinds__",+ filters.category ?? "__all-categories__",+ filters.q ?? "",+ ] as const,+ catalogDetail: (catalogRef: string) =>+ ["team-catalog", "catalog", "detail", catalogRef] as const,catalogFile: (catalogRef: string, relativePath: string) =>["team-catalog", "catalog", "file", catalogRef, relativePath] as const,- installed: (companyId: string) => ["team-catalog", "installed", companyId] as const,+ installed: (companyId: string) =>+ ["team-catalog", "installed", companyId] as const,},agents: {list: (companyId: string) => ["agents", companyId] as const,@@ -147,13 +192,25 @@ export const queryKeys = {runtimeState: (id: string) => ["agents", "runtime-state", id] as const,taskSessions: (id: string) => ["agents", "task-sessions", id] as const,skills: (id: string) => ["agents", "skills", id] as const,- instructionsBundle: (id: string) => ["agents", "instructions-bundle", id] as const,+ instructionsBundle: (id: string) =>+ ["agents", "instructions-bundle", id] as const,instructionsFile: (id: string, relativePath: string) =>["agents", "instructions-bundle", id, "file", relativePath] as const,keys: (agentId: string) => ["agents", "keys", agentId] as const,- configRevisions: (agentId: string) => ["agents", "config-revisions", agentId] as const,- adapterModels: (companyId: string, adapterType: string, environmentId?: string | null) =>- ["agents", companyId, "adapter-models", adapterType, environmentId ?? null] as const,+ configRevisions: (agentId: string) =>+ ["agents", "config-revisions", agentId] as const,+ adapterModels: (+ companyId: string,+ adapterType: string,+ environmentId?: string | null,+ ) =>+ [+ "agents",+ companyId,+ "adapter-models",+ adapterType,+ environmentId ?? null,+ ] as const,adapterModelProfiles: (companyId: string, adapterType: string) =>["agents", companyId, "adapter-model-profiles", adapterType] as const,detectModel: (companyId: string, adapterType: string) =>@@ -165,65 +222,140 @@ export const queryKeys = {list: (companyId: string) => ["built-in-agents", companyId] as const,},summarySlots: {- detail: (companyId: string, scopeKind: string, slotKey: string, scopeId?: string | null) =>- ["summary-slots", companyId, scopeKind, slotKey, scopeId ?? null] as const,- revisions: (companyId: string, scopeKind: string, slotKey: string, scopeId?: string | null) =>- ["summary-slots", companyId, scopeKind, slotKey, scopeId ?? null, "revisions"] as const,+ detail: (+ companyId: string,+ scopeKind: string,+ slotKey: string,+ scopeId?: string | null,+ ) =>+ [+ "summary-slots",+ companyId,+ scopeKind,+ slotKey,+ scopeId ?? null,+ ] as const,+ revisions: (+ companyId: string,+ scopeKind: string,+ slotKey: string,+ scopeId?: string | null,+ ) =>+ [+ "summary-slots",+ companyId,+ scopeKind,+ slotKey,+ scopeId ?? null,+ "revisions",+ ] as const,},statusCards: {list: (companyId: string, archived: boolean) =>["status-cards", companyId, archived ? "archived" : "active"] as const,detail: (id: string) => ["status-cards", "detail", id] as const,updates: (id: string) => ["status-cards", "detail", id, "updates"] as const,- summaryRevisions: (id: string) => ["status-cards", "detail", id, "summary-revisions"] as const,+ summaryRevisions: (id: string) =>+ ["status-cards", "detail", id, "summary-revisions"] as const,dryRun: (id: string) => ["status-cards", "detail", id, "dry-run"] as const,},issues: {list: (companyId: string) => ["issues", companyId] as const,- mentionPool: (companyId: string) => ["issues", companyId, "mention-pool"] as const,- search: (companyId: string, q: string, projectId?: string, limit?: number) =>- ["issues", companyId, "search", q, projectId ?? "__all-projects__", limit ?? "__no-limit__"] as const,- listAssignedToMe: (companyId: string) => ["issues", companyId, "assigned-to-me"] as const,- listMineByMe: (companyId: string) => ["issues", companyId, "mine-by-me"] as const,- listTouchedByMe: (companyId: string) => ["issues", companyId, "touched-by-me"] as const,- listUnreadTouchedByMe: (companyId: string) => ["issues", companyId, "unread-touched-by-me"] as const,- listBlockedAttention: (companyId: string) => ["issues", companyId, "blocked-attention"] as const,- countBlockedAttention: (companyId: string) => ["issues", companyId, "blocked-attention", "count"] as const,+ mentionPool: (companyId: string) =>+ ["issues", companyId, "mention-pool"] as const,+ search: (+ companyId: string,+ q: string,+ projectId?: string,+ limit?: number,+ ) =>+ [+ "issues",+ companyId,+ "search",+ q,+ projectId ?? "__all-projects__",+ limit ?? "__no-limit__",+ ] as const,+ listAssignedToMe: (companyId: string) =>+ ["issues", companyId, "assigned-to-me"] as const,+ listMineByMe: (companyId: string) =>+ ["issues", companyId, "mine-by-me"] as const,+ listTouchedByMe: (companyId: string) =>+ ["issues", companyId, "touched-by-me"] as const,+ listUnreadTouchedByMe: (companyId: string) =>+ ["issues", companyId, "unread-touched-by-me"] as const,+ listBlockedAttention: (companyId: string) =>+ ["issues", companyId, "blocked-attention"] as const,+ countBlockedAttention: (companyId: string) =>+ ["issues", companyId, "blocked-attention", "count"] as const,labels: (companyId: string) => ["issues", companyId, "labels"] as const,listByProject: (companyId: string, projectId: string) =>["issues", companyId, "project", projectId] as const,- listPluginOperationsByProject: (companyId: string, projectId: string, originKindPrefix: string) =>- ["issues", companyId, "project", projectId, "plugin-operations", originKindPrefix] as const,+ listPluginOperationsByProject: (+ companyId: string,+ projectId: string,+ originKindPrefix: string,+ ) =>+ [+ "issues",+ companyId,+ "project",+ projectId,+ "plugin-operations",+ originKindPrefix,+ ] as const,listByParent: (companyId: string, parentId: string) =>["issues", companyId, "parent", parentId] as const,listByDescendantRoot: (companyId: string, rootIssueId: string) =>["issues", companyId, "descendants", rootIssueId] as const,- listByExecutionWorkspace: (companyId: string, executionWorkspaceId: string) =>- ["issues", companyId, "execution-workspace", executionWorkspaceId] as const,+ listByExecutionWorkspace: (+ companyId: string,+ executionWorkspaceId: string,+ ) =>+ [+ "issues",+ companyId,+ "execution-workspace",+ executionWorkspaceId,+ ] as const,detail: (id: string) => ["issues", "detail", id] as const,comments: (issueId: string) => ["issues", "comments", issueId] as const,- commentsList: (issueId: string) => ["issues", "comments", issueId, "list"] as const,- interactions: (issueId: string) => ["issues", "interactions", issueId] as const,+ commentsList: (issueId: string) =>+ ["issues", "comments", issueId, "list"] as const,+ queuedComments: (issueId: string) =>+ ["issues", "queued-comments", issueId] as const,+ interactions: (issueId: string) =>+ ["issues", "interactions", issueId] as const,acceptedPlanDecompositions: (issueId: string) =>["issues", "accepted-plan-decompositions", issueId] as const,- feedbackVotes: (issueId: string) => ["issues", "feedback-votes", issueId] as const,+ feedbackVotes: (issueId: string) =>+ ["issues", "feedback-votes", issueId] as const,costSummary: (issueId: string, options: { excludeRoot?: boolean } = {}) =>options.excludeRoot? (["issues", "cost-summary", issueId, "exclude-root"] as const): (["issues", "cost-summary", issueId] as const),- attachments: (issueId: string) => ["issues", "attachments", issueId] as const,- attachmentPreview: (attachmentId: string) => ["issues", "attachment-preview", attachmentId] as const,+ attachments: (issueId: string) =>+ ["issues", "attachments", issueId] as const,+ attachmentPreview: (attachmentId: string) =>+ ["issues", "attachment-preview", attachmentId] as const,documents: (issueId: string) => ["issues", "documents", issueId] as const,- document: (issueId: string, key: string) => ["issues", "document", issueId, key] as const,- documentRevisions: (issueId: string, key: string) => ["issues", "document-revisions", issueId, key] as const,- documentAnnotations: (issueId: string, key: string, status: "open" | "resolved" | "all" = "all") =>- ["issues", "document-annotations", issueId, key, status] as const,+ document: (issueId: string, key: string) =>+ ["issues", "document", issueId, key] as const,+ documentRevisions: (issueId: string, key: string) =>+ ["issues", "document-revisions", issueId, key] as const,+ documentAnnotations: (+ issueId: string,+ key: string,+ status: "open" | "resolved" | "all" = "all",+ ) => ["issues", "document-annotations", issueId, key, status] as const,activity: (issueId: string) => ["issues", "activity", issueId] as const,runs: (issueId: string) => ["issues", "runs", issueId] as const,approvals: (issueId: string) => ["issues", "approvals", issueId] as const,liveRuns: (issueId: string) => ["issues", "live-runs", issueId] as const,activeRun: (issueId: string) => ["issues", "active-run", issueId] as const,- workProducts: (issueId: string) => ["issues", "work-products", issueId] as const,+ workProducts: (issueId: string) =>+ ["issues", "work-products", issueId] as const,fileResources: (issueId: string,options: {@@ -236,18 +368,25 @@ export const queryKeys = {limit?: number;offset?: number;} = {},- ) =>- ["issues", "file-resources", issueId, "list", options] as const,+ ) => ["issues", "file-resources", issueId, "list", options] as const,fileResource: (issueId: string,- query: { path: string; workspace?: string; projectId?: string | null; workspaceId?: string | null },- ) =>- ["issues", "file-resources", issueId, "resolve", query] as const,+ query: {+ path: string;+ workspace?: string;+ projectId?: string | null;+ workspaceId?: string | null;+ },+ ) => ["issues", "file-resources", issueId, "resolve", query] as const,fileResourceContent: (issueId: string,- query: { path: string; workspace?: string; projectId?: string | null; workspaceId?: string | null },- ) =>- ["issues", "file-resources", issueId, "content", query] as const,+ query: {+ path: string;+ workspace?: string;+ projectId?: string | null;+ workspaceId?: string | null;+ },+ ) => ["issues", "file-resources", issueId, "content", query] as const,/*** Batched availability preflight. `refKeys` are the deduplicated,* lexicographically sorted reference keys in the request so identical@@ -258,52 +397,83 @@ export const queryKeys = {},routines: {list: (companyId: string, filters?: { projectId?: string | null }) =>- ["routines", companyId, filters?.projectId ?? "__all-projects__"] as const,+ [+ "routines",+ companyId,+ filters?.projectId ?? "__all-projects__",+ ] as const,detail: (id: string) => ["routines", "detail", id] as const,runs: (id: string) => ["routines", "runs", id] as const,revisions: (id: string) => ["routines", "revisions", id] as const,- activity: (companyId: string, id: string) => ["routines", "activity", companyId, id] as const,- documentAnnotations: (routineId: string, key: "description", status: "open" | "resolved" | "all" = "all") =>- ["routines", "document-annotations", routineId, key, status] as const,+ activity: (companyId: string, id: string) =>+ ["routines", "activity", companyId, id] as const,+ documentAnnotations: (+ routineId: string,+ key: "description",+ status: "open" | "resolved" | "all" = "all",+ ) => ["routines", "document-annotations", routineId, key, status] as const,},folders: {- list: (companyId: string, kind: string) => ["folders", companyId, kind] as const,+ list: (companyId: string, kind: string) =>+ ["folders", companyId, kind] as const,},pipelines: {list: (companyId: string) => ["pipelines", companyId] as const,- detail: (pipelineId: string) => ["pipelines", "detail", pipelineId] as const,+ detail: (pipelineId: string) =>+ ["pipelines", "detail", pipelineId] as const,cases: (pipelineId: string) => ["pipelines", "cases", pipelineId] as const,caseDetail: (caseId: string) => ["pipelines", "item", caseId] as const,- caseChildren: (caseId: string) => ["pipelines", "item", caseId, "children"] as const,- caseEvents: (caseId: string) => ["pipelines", "item", caseId, "events"] as const,- caseIssueLinks: (caseId: string) => ["pipelines", "item", caseId, "issue-links"] as const,- caseOutputs: (caseId: string) => ["pipelines", "item", caseId, "outputs"] as const,- caseDocument: (caseId: string, key: string) => ["pipelines", "item", caseId, "document", key] as const,+ caseChildren: (caseId: string) =>+ ["pipelines", "item", caseId, "children"] as const,+ caseEvents: (caseId: string) =>+ ["pipelines", "item", caseId, "events"] as const,+ caseIssueLinks: (caseId: string) =>+ ["pipelines", "item", caseId, "issue-links"] as const,+ caseOutputs: (caseId: string) =>+ ["pipelines", "item", caseId, "outputs"] as const,+ caseDocument: (caseId: string, key: string) =>+ ["pipelines", "item", caseId, "document", key] as const,caseDocumentRevisions: (caseId: string, key: string) =>["pipelines", "item", caseId, "document-revisions", key] as const,- intakeForm: (pipelineId: string) => ["pipelines", "intake-form", pipelineId] as const,- health: (pipelineId: string) => ["pipelines", "health", pipelineId] as const,- document: (pipelineId: string, key: string) => ["pipelines", "document", pipelineId, key] as const,+ intakeForm: (pipelineId: string) =>+ ["pipelines", "intake-form", pipelineId] as const,+ health: (pipelineId: string) =>+ ["pipelines", "health", pipelineId] as const,+ document: (pipelineId: string, key: string) =>+ ["pipelines", "document", pipelineId, key] as const,documentRevisions: (pipelineId: string, key: string) =>["pipelines", "document-revisions", pipelineId, key] as const,- attention: (companyId: string) => ["pipelines", "attention", companyId] as const,- reviewCases: (companyId: string) => ["pipelines", "review-cases", companyId] as const,- learnings: (companyId: string, offset: number) => ["pipelines", "learnings", companyId, offset] as const,+ attention: (companyId: string) =>+ ["pipelines", "attention", companyId] as const,+ reviewCases: (companyId: string) =>+ ["pipelines", "review-cases", companyId] as const,+ learnings: (companyId: string, offset: number) =>+ ["pipelines", "learnings", companyId, offset] as const,},executionWorkspaces: {- list: (companyId: string, filters?: Record<string, string | boolean | undefined>) =>- ["execution-workspaces", companyId, filters ?? {}] as const,- summaryList: (companyId: string, filters?: Record<string, string | boolean | undefined>) =>- ["execution-workspaces", companyId, "summary", filters ?? {}] as const,- overview: (companyId: string, filters?: Record<string, string | number | boolean | undefined>) =>+ list: (+ companyId: string,+ filters?: Record<string, string | boolean | undefined>,+ ) => ["execution-workspaces", companyId, filters ?? {}] as const,+ summaryList: (+ companyId: string,+ filters?: Record<string, string | boolean | undefined>,+ ) => ["execution-workspaces", companyId, "summary", filters ?? {}] as const,+ overview: (+ companyId: string,+ filters?: Record<string, string | number | boolean | undefined>,+ ) =>["execution-workspaces", companyId, "overview", filters ?? {}] as const,detail: (id: string) => ["execution-workspaces", "detail", id] as const,- closeReadiness: (id: string) => ["execution-workspaces", "close-readiness", id] as const,- workspaceOperations: (id: string) => ["execution-workspaces", "workspace-operations", id] as const,+ closeReadiness: (id: string) =>+ ["execution-workspaces", "close-readiness", id] as const,+ workspaceOperations: (id: string) =>+ ["execution-workspaces", "workspace-operations", id] as const,},environments: {list: (companyId: string) => ["environments", companyId] as const,- capabilities: (companyId: string) => ["environment-capabilities", companyId] as const,+ capabilities: (companyId: string) =>+ ["environment-capabilities", companyId] as const,customImageTemplate: (environmentId: string) =>["environments", environmentId, "custom-image-template"] as const,customImageSetupSession: (sessionId: string) =>@@ -312,26 +482,37 @@ export const queryKeys = {projects: {all: (companyId: string) => ["projects", companyId] as const,list: (companyId: string, opts: { includeArchived?: boolean } = {}) =>- ["projects", companyId, { includeArchived: opts.includeArchived === true }] as const,+ [+ "projects",+ companyId,+ { includeArchived: opts.includeArchived === true },+ ] as const,detail: (id: string) => ["projects", "detail", id] as const,},cases: {list: (companyId: string) => ["cases", companyId] as const,detail: (id: string) => ["cases", "detail", id] as const,documents: (id: string) => ["cases", "documents", id] as const,- documentAnnotations: (caseId: string, key: string, status: "open" | "resolved" | "all" = "all") =>- ["cases", "document-annotations", caseId, key, status] as const,+ documentAnnotations: (+ caseId: string,+ key: string,+ status: "open" | "resolved" | "all" = "all",+ ) => ["cases", "document-annotations", caseId, key, status] as const,events: (id: string) => ["cases", "events", id] as const,children: (parentId: string) => ["cases", "children", parentId] as const,- revisions: (id: string, key: string) => ["cases", "revisions", id, key] as const,+ revisions: (id: string, key: string) =>+ ["cases", "revisions", id, key] as const,forIssue: (issueId: string) => ["cases", "for-issue", issueId] as const,},externalObjects: {- byIssue: (issueId: string) => ["external-objects", "by-issue", issueId] as const,- issueSummary: (issueId: string) => ["external-objects", "issue-summary", issueId] as const,+ byIssue: (issueId: string) =>+ ["external-objects", "by-issue", issueId] as const,+ issueSummary: (issueId: string) =>+ ["external-objects", "issue-summary", issueId] as const,issueSummaries: (companyId: string, issueIds: readonly string[]) =>["external-objects", "issue-summaries", companyId, issueIds] as const,- projectSummary: (projectId: string) => ["external-objects", "project-summary", projectId] as const,+ projectSummary: (projectId: string) =>+ ["external-objects", "project-summary", projectId] as const,},goals: {list: (companyId: string) => ["goals", companyId] as const,@@ -355,24 +536,31 @@ export const queryKeys = {] as const,},budgets: {- overview: (companyId: string) => ["budgets", "overview", companyId] as const,+ overview: (companyId: string) =>+ ["budgets", "overview", companyId] as const,},approvals: {list: (companyId: string, status?: string) =>["approvals", companyId, status] as const,- detail: (approvalId: string) => ["approvals", "detail", approvalId] as const,- comments: (approvalId: string) => ["approvals", "comments", approvalId] as const,- issues: (approvalId: string) => ["approvals", "issues", approvalId] as const,+ detail: (approvalId: string) =>+ ["approvals", "detail", approvalId] as const,+ comments: (approvalId: string) =>+ ["approvals", "comments", approvalId] as const,+ issues: (approvalId: string) =>+ ["approvals", "issues", approvalId] as const,},access: {invites: (companyId: string, state: string = "all", limit: number = 20) =>["access", "invites", "paginated-v1", companyId, state, limit] as const,joinRequests: (companyId: string, status: string = "pending_approval") =>["access", "join-requests", companyId, status] as const,- companyMembers: (companyId: string) => ["access", "company-members", companyId] as const,- companyUserDirectory: (companyId: string) => ["access", "company-user-directory", companyId] as const,+ companyMembers: (companyId: string) =>+ ["access", "company-members", companyId] as const,+ companyUserDirectory: (companyId: string) =>+ ["access", "company-user-directory", companyId] as const,adminUsers: (query: string) => ["access", "admin-users", query] as const,- userCompanyAccess: (userId: string) => ["access", "user-company-access", userId] as const,+ userCompanyAccess: (userId: string) =>+ ["access", "user-company-access", userId] as const,invite: (token: string) => ["access", "invite", token] as const,currentBoardAccess: ["access", "current-board-access"] as const,},@@ -380,15 +568,18 @@ export const queryKeys = {session: ["auth", "session"] as const,},inboxAgentPolicy: {- mine: (companyId: string) => ["inbox-agent-policy", companyId, "me"] as const,+ mine: (companyId: string) =>+ ["inbox-agent-policy", companyId, "me"] as const,},sidebarPreferences: {- companyOrder: (userId: string) => ["sidebar-preferences", "company-order", userId] as const,+ companyOrder: (userId: string) =>+ ["sidebar-preferences", "company-order", userId] as const,projectOrder: (companyId: string, userId: string) =>["sidebar-preferences", "project-order", companyId, userId] as const,},resourceMemberships: {- mine: (companyId: string) => ["resource-memberships", companyId, "me"] as const,+ mine: (companyId: string) =>+ ["resource-memberships", companyId, "me"] as const,},instance: {settings: ["instance", "settings"] as const,@@ -402,19 +593,28 @@ export const queryKeys = {secrets: {list: (companyId: string) => ["secrets", companyId] as const,providers: (companyId: string) => ["secret-providers", companyId] as const,- providerConfigs: (companyId: string) => ["secret-provider-configs", companyId] as const,+ providerConfigs: (companyId: string) =>+ ["secret-provider-configs", companyId] as const,usage: (secretId: string) => ["secrets", "usage", secretId] as const,- accessEvents: (secretId: string) => ["secrets", "access-events", secretId] as const,- userDefinitions: (companyId: string) => ["user-secret-definitions", companyId] as const,+ accessEvents: (secretId: string) =>+ ["secrets", "access-events", secretId] as const,+ userDefinitions: (companyId: string) =>+ ["user-secret-definitions", companyId] as const,userDefinitionCoverage: (companyId: string, definitionId: string) =>["user-secret-definitions", companyId, definitionId, "coverage"] as const,- myUserSecrets: (companyId: string) => ["my-user-secrets", companyId] as const,+ myUserSecrets: (companyId: string) =>+ ["my-user-secrets", companyId] as const,proposals: (companyId: string, status: string = "pending") =>["secret-proposals", companyId, status] as const,},companySearch: {- search: (companyId: string, q: string, scope: string, limit: number, offset: number) =>- ["company-search", companyId, q, scope, limit, offset] as const,+ search: (+ companyId: string,+ q: string,+ scope: string,+ limit: number,+ offset: number,+ ) => ["company-search", companyId, q, scope, limit, offset] as const,},dashboard: (companyId: string) => ["dashboard", companyId] as const,attention: (companyId: string) => ["attention", companyId] as const,@@ -427,16 +627,20 @@ export const queryKeys = {},decisionQueues: {list: (companyId: string) => ["decision-queues", companyId] as const,- items: (companyId: string, key: string) => ["decision-queues", companyId, "items", key] as const,- seedRules: (companyId: string) => ["decision-queues", companyId, "seed-rules"] as const,+ items: (companyId: string, key: string) =>+ ["decision-queues", companyId, "items", key] as const,+ seedRules: (companyId: string) =>+ ["decision-queues", companyId, "seed-rules"] as const,triage: (companyId: string, sourceKind: string, sourceId: string) =>["decision-triage", companyId, sourceKind, sourceId] as const,},- workTimeline: (companyId: string, lens?: string) => ["work-timeline", companyId, lens ?? "all"] as const,+ workTimeline: (companyId: string, lens?: string) =>+ ["work-timeline", companyId, lens ?? "all"] as const,userProfile: (companyId: string, userSlug: string) =>["user-profile", companyId, userSlug] as const,sidebarBadges: (companyId: string) => ["sidebar-badges", companyId] as const,- inboxDismissals: (companyId: string) => ["inbox-dismissals", companyId] as const,+ inboxDismissals: (companyId: string) =>+ ["inbox-dismissals", companyId] as const,activity: (companyId: string) => ["activity", companyId] as const,costs: (companyId: string, from?: string, to?: string) =>["costs", companyId, from, to] as const,@@ -450,8 +654,12 @@ export const queryKeys = {["finance-by-biller", companyId, from, to] as const,financeByKind: (companyId: string, from?: string, to?: string) =>["finance-by-kind", companyId, from, to] as const,- financeEvents: (companyId: string, from?: string, to?: string, limit: number = 100) =>- ["finance-events", companyId, from, to, limit] as const,+ financeEvents: (+ companyId: string,+ from?: string,+ to?: string,+ limit: number = 100,+ ) => ["finance-events", companyId, from, to, limit] as const,usageWindowSpend: (companyId: string) =>["usage-window-spend", companyId] as const,usageQuotaWindows: (companyId: string) =>@@ -459,7 +667,10 @@ export const queryKeys = {heartbeats: (companyId: string, agentId?: string) =>["heartbeats", companyId, agentId] as const,runDetail: (runId: string) => ["heartbeat-run", runId] as const,- runWorkspaceOperations: (runId: string) => ["heartbeat-run", runId, "workspace-operations"] as const,+ providerTraceMetadata: (companyId: string, runIds: readonly string[]) =>+ ["provider-trace-metadata", companyId, [...runIds].sort()] as const,+ runWorkspaceOperations: (runId: string) =>+ ["heartbeat-run", runId, "workspace-operations"] as const,liveRuns: (companyId: string) => ["live-runs", companyId] as const,runIssues: (runId: string) => ["run-issues", runId] as const,org: (companyId: string) => ["org", companyId] as const,@@ -472,10 +683,12 @@ export const queryKeys = {detail: (pluginId: string) => ["plugins", pluginId] as const,health: (pluginId: string) => ["plugins", pluginId, "health"] as const,uiContributions: ["plugins", "ui-contributions"] as const,- config: (pluginId: string, companyId: string) => ["plugins", pluginId, "companies", companyId, "config"] as const,+ config: (pluginId: string, companyId: string) =>+ ["plugins", pluginId, "companies", companyId, "config"] as const,localFolders: (pluginId: string, companyId: string) =>["plugins", pluginId, "companies", companyId, "local-folders"] as const,- dashboard: (pluginId: string) => ["plugins", pluginId, "dashboard"] as const,+ dashboard: (pluginId: string) =>+ ["plugins", pluginId, "dashboard"] as const,logs: (pluginId: string) => ["plugins", pluginId, "logs"] as const,},adapters: {diff --git a/ui/src/lib/task-side-panel-state.test.ts b/ui/src/lib/task-side-panel-state.test.tsnew file mode 100644index 0000000000..4e0dbf4ea5--- /dev/null+++ b/ui/src/lib/task-side-panel-state.test.ts@@ -0,0 +1,70 @@+// @vitest-environment jsdom++import { beforeEach, describe, expect, it } from "vitest";+import {+ readTaskSidePanelState,+ taskPanelDocumentTab,+ taskPanelFilesTab,+ taskPanelPropertiesTab,+ writeTaskSidePanelState,+} from "./task-side-panel-state";++describe("task side-panel persistence", () => {+ beforeEach(() => window.localStorage.clear());++ it("round-trips an intentionally empty task state", () => {+ writeTaskSidePanelState("user-1", "company-1", "task-1", {+ state: { tabs: [], activeTabId: null },+ launcherOpen: false,+ userInteracted: true,+ autoPlanHandled: true,+ updatedAt: 1,+ });+ expect(readTaskSidePanelState("user-1", "company-1", "task-1", true)).toMatchObject({+ state: { tabs: [], activeTabId: null },+ userInteracted: true,+ });+ });++ it("isolates account and company state", () => {+ writeTaskSidePanelState("user-1", "company-1", "task-1", {+ state: { tabs: [taskPanelPropertiesTab()], activeTabId: "properties" },+ launcherOpen: false,+ userInteracted: false,+ autoPlanHandled: false,+ updatedAt: 1,+ });+ expect(readTaskSidePanelState("user-2", "company-1", "task-1", true)).toBeNull();+ expect(readTaskSidePanelState("user-1", "company-2", "task-1", true)).toBeNull();+ });++ it("drops file tabs when the experiment is disabled while keeping documents", () => {+ writeTaskSidePanelState("user-1", "company-1", "task-1", {+ state: {+ tabs: [taskPanelPropertiesTab(), taskPanelFilesTab(), taskPanelDocumentTab("plan", "Plan")],+ activeTabId: "files",+ },+ launcherOpen: false,+ userInteracted: true,+ autoPlanHandled: true,+ updatedAt: 1,+ });+ const restored = readTaskSidePanelState("user-1", "company-1", "task-1", false);+ expect(restored?.state.tabs.map((tab) => tab.id)).toEqual(["properties", "document:plan"]);+ expect(restored?.state.activeTabId).toBe("properties");+ });++ it("retains only the 50 most recently written tasks", () => {+ for (let index = 0; index < 52; index += 1) {+ writeTaskSidePanelState("user-1", "company-1", `task-${index}`, {+ state: { tabs: [taskPanelPropertiesTab()], activeTabId: "properties" },+ launcherOpen: false,+ userInteracted: false,+ autoPlanHandled: false,+ updatedAt: index,+ });+ }+ expect(readTaskSidePanelState("user-1", "company-1", "task-0", true)).toBeNull();+ expect(readTaskSidePanelState("user-1", "company-1", "task-51", true)).not.toBeNull();+ });+});diff --git a/ui/src/lib/task-side-panel-state.ts b/ui/src/lib/task-side-panel-state.tsnew file mode 100644index 0000000000..0a6f448e31--- /dev/null+++ b/ui/src/lib/task-side-panel-state.ts@@ -0,0 +1,241 @@+import type { WorkspaceFileSelector } from "@paperclipai/shared";+import type { SidePanelTabRecord, SidePanelTabsState } from "@/components/side-panel";++const STORAGE_VERSION = 1;+const MAX_TASK_STATES = 50;++export type TaskSidePanelTabPayload =+ | { kind: "properties" }+ | { kind: "artifacts" }+ | { kind: "issue-document"; documentKey: string }+ | {+ kind: "files-browser";+ query: string | null;+ folderPath: string | null;+ projectId: string | null;+ workspaceId: string | null;+ }+ | {+ kind: "workspace-file";+ path: string;+ workspace: WorkspaceFileSelector;+ projectId: string | null;+ workspaceId: string | null;+ line: number | null;+ column: number | null;+ };++export interface StoredTaskSidePanelState {+ state: SidePanelTabsState<TaskSidePanelTabPayload>;+ launcherOpen: boolean;+ userInteracted: boolean;+ autoPlanHandled: boolean;+ updatedAt: number;+}++interface TaskSidePanelStore {+ version: number;+ tasks: Record<string, StoredTaskSidePanelState>;+}++function storageKey(accountScope: string, companyId: string) {+ return `paperclip:task-side-panel:v${STORAGE_VERSION}:${accountScope}:${companyId}`;+}++function record(value: unknown): Record<string, unknown> | null {+ return value !== null && typeof value === "object" && !Array.isArray(value)+ ? value as Record<string, unknown>+ : null;+}++function nullableString(value: unknown): string | null | undefined {+ return value === null ? null : typeof value === "string" ? value : undefined;+}++function positiveInteger(value: unknown): number | null | undefined {+ if (value === null) return null;+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;+}++function parsePayload(value: unknown): TaskSidePanelTabPayload | null {+ const input = record(value);+ if (!input) return null;+ const kind = input.kind;+ if (kind === "properties") return { kind };+ if (kind === "artifacts") return { kind };+ if (kind === "issue-document") {+ return typeof input.documentKey === "string" && input.documentKey.length > 0+ ? { kind, documentKey: input.documentKey }+ : null;+ }+ if (kind === "files-browser") {+ const query = nullableString(input.query);+ const folderPath = nullableString(input.folderPath);+ const projectId = nullableString(input.projectId);+ const workspaceId = nullableString(input.workspaceId);+ if ([query, folderPath, projectId, workspaceId].some((entry) => typeof entry === "undefined")) return null;+ return { kind, query: query!, folderPath: folderPath!, projectId: projectId!, workspaceId: workspaceId! };+ }+ if (kind === "workspace-file") {+ if (typeof input.path !== "string" || input.path.length === 0) return null;+ const workspace = input.workspace === "execution" || input.workspace === "project" ? input.workspace : "auto";+ const projectId = nullableString(input.projectId);+ const workspaceId = nullableString(input.workspaceId);+ const line = positiveInteger(input.line);+ const column = positiveInteger(input.column);+ if ([projectId, workspaceId, line, column].some((entry) => typeof entry === "undefined")) return null;+ return {+ kind,+ path: input.path,+ workspace,+ projectId: projectId!,+ workspaceId: workspaceId!,+ line: line!,+ column: column!,+ };+ }+ return null;+}++function parseTab(value: unknown, fileTabsEnabled: boolean): SidePanelTabRecord<TaskSidePanelTabPayload> | null {+ const input = record(value);+ if (!input || typeof input.id !== "string" || typeof input.type !== "string" || typeof input.label !== "string") return null;+ const payload = parsePayload(input.payload);+ if (!payload) return null;+ if (!fileTabsEnabled && (payload.kind === "files-browser" || payload.kind === "workspace-file")) return null;+ return {+ id: input.id,+ type: input.type,+ label: input.label,+ ariaLabel: typeof input.ariaLabel === "string" ? input.ariaLabel : undefined,+ closable: typeof input.closable === "boolean" ? input.closable : true,+ contentMode: input.contentMode === "full-bleed" || input.contentMode === "prose" ? input.contentMode : "padded",+ payload,+ };+}++function parseEntry(value: unknown, fileTabsEnabled: boolean): StoredTaskSidePanelState | null {+ const input = record(value);+ const rawState = record(input?.state);+ if (!input || !rawState || !Array.isArray(rawState.tabs)) return null;+ const seen = new Set<string>();+ const tabs = rawState.tabs.flatMap((raw) => {+ const tab = parseTab(raw, fileTabsEnabled);+ if (!tab || seen.has(tab.id)) return [];+ seen.add(tab.id);+ return [tab];+ });+ const requestedActive = typeof rawState.activeTabId === "string" ? rawState.activeTabId : null;+ return {+ state: {+ tabs,+ activeTabId: requestedActive && seen.has(requestedActive) ? requestedActive : tabs[0]?.id ?? null,+ },+ launcherOpen: input.launcherOpen === true,+ userInteracted: input.userInteracted === true,+ autoPlanHandled: input.autoPlanHandled === true,+ updatedAt: typeof input.updatedAt === "number" && Number.isFinite(input.updatedAt) ? input.updatedAt : 0,+ };+}++function readStore(accountScope: string, companyId: string): TaskSidePanelStore {+ if (typeof window === "undefined") return { version: STORAGE_VERSION, tasks: {} };+ try {+ const parsed = record(JSON.parse(window.localStorage.getItem(storageKey(accountScope, companyId)) ?? "null"));+ if (parsed?.version !== STORAGE_VERSION || !record(parsed.tasks)) return { version: STORAGE_VERSION, tasks: {} };+ return { version: STORAGE_VERSION, tasks: parsed.tasks as Record<string, StoredTaskSidePanelState> };+ } catch {+ return { version: STORAGE_VERSION, tasks: {} };+ }+}++export function readTaskSidePanelState(+ accountScope: string,+ companyId: string,+ taskId: string,+ fileTabsEnabled: boolean,+): StoredTaskSidePanelState | null {+ return parseEntry(readStore(accountScope, companyId).tasks[taskId], fileTabsEnabled);+}++export function writeTaskSidePanelState(+ accountScope: string,+ companyId: string,+ taskId: string,+ entry: StoredTaskSidePanelState,+) {+ if (typeof window === "undefined") return;+ try {+ const store = readStore(accountScope, companyId);+ const tasks = { ...store.tasks, [taskId]: entry };+ const retained = Object.entries(tasks)+ .sort((left, right) => (right[1].updatedAt ?? 0) - (left[1].updatedAt ?? 0))+ .slice(0, MAX_TASK_STATES);+ window.localStorage.setItem(storageKey(accountScope, companyId), JSON.stringify({+ version: STORAGE_VERSION,+ tasks: Object.fromEntries(retained),+ } satisfies TaskSidePanelStore));+ } catch {+ // Storage is an enhancement; panel behavior stays usable when unavailable.+ }+}++export function taskPanelPropertiesTab(): SidePanelTabRecord<TaskSidePanelTabPayload> {+ return { id: "properties", type: "properties", label: "Properties", closable: true, contentMode: "padded", payload: { kind: "properties" } };+}++export function taskPanelArtifactsTab(): SidePanelTabRecord<TaskSidePanelTabPayload> {+ return { id: "artifacts", type: "artifacts", label: "Artifacts", closable: true, contentMode: "padded", payload: { kind: "artifacts" } };+}++export function taskPanelDocumentTab(documentKey: string, label: string): SidePanelTabRecord<TaskSidePanelTabPayload> {+ return {+ id: `document:${documentKey}`,+ type: "issue-document",+ label,+ closable: true,+ contentMode: "prose",+ payload: { kind: "issue-document", documentKey },+ };+}++export function taskPanelFilesTab(): SidePanelTabRecord<TaskSidePanelTabPayload> {+ return {+ id: "files",+ type: "files-browser",+ label: "Files",+ closable: true,+ contentMode: "full-bleed",+ payload: { kind: "files-browser", query: null, folderPath: null, projectId: null, workspaceId: null },+ };+}++export function taskPanelWorkspaceFileTab(input: {+ path: string;+ workspace?: WorkspaceFileSelector;+ projectId?: string | null;+ workspaceId?: string | null;+ line?: number | null;+ column?: number | null;+}): SidePanelTabRecord<TaskSidePanelTabPayload> {+ const projectId = input.projectId ?? null;+ const workspaceId = input.workspaceId ?? null;+ const scope = projectId && workspaceId ? `${projectId}:${workspaceId}` : input.workspace ?? "auto";+ return {+ id: `workspace-file:${scope}:${input.path}`,+ type: "workspace-file",+ label: input.path.split("/").filter(Boolean).at(-1) ?? input.path,+ ariaLabel: input.path,+ closable: true,+ contentMode: "full-bleed",+ payload: {+ kind: "workspace-file",+ path: input.path,+ workspace: input.workspace ?? "auto",+ projectId,+ workspaceId,+ line: input.line ?? null,+ column: input.column ?? null,+ },+ };+}diff --git a/ui/src/pages/IssueDetail.test.tsx b/ui/src/pages/IssueDetail.test.tsxindex e63429e2e7..4696b47c0e 100644--- a/ui/src/pages/IssueDetail.test.tsx+++ b/ui/src/pages/IssueDetail.test.tsx@@ -1,13 +1,28 @@// @vitest-environment jsdomimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import type { Agent, Issue, IssueAttachment, IssueComment, IssueTreeControlPreview, IssueTreeHold, IssueWorkProduct } from "@paperclipai/shared";+import type {+ Agent,+ Issue,+ IssueAttachment,+ IssueComment,+ IssueQueuedCommentQueue,+ IssueTreeControlPreview,+ IssueTreeHold,+ IssueWorkProduct,+} from "@paperclipai/shared";import { ONBOARDING_FIRST_TASK_ORIGIN_KIND } from "@paperclipai/shared";-import type { AnchorHTMLAttributes, ButtonHTMLAttributes, ReactNode } from "react";+import type {+ AnchorHTMLAttributes,+ ButtonHTMLAttributes,+ ReactElement,+ ReactNode,+} from "react";import { NavigationType } from "react-router-dom";import { flushSync } from "react-dom";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { TooltipProvider } from "@/components/ui/tooltip";import {canBoardManageRuntime,canBoardResolveRecoveryAction,@@ -17,6 +32,7 @@ import {} from "./IssueDetail";import { queryKeys } from "../lib/queryKeys";import { createIssueDetailLocationState } from "../lib/issueDetailBreadcrumb";+import { ApiError } from "../api/client";const mockIssuesApi = vi.hoisted(() => ({get: vi.fn(),@@ -26,8 +42,15 @@ const mockIssuesApi = vi.hoisted(() => ({listAttachments: vi.fn(),listWorkProducts: vi.fn(),listFeedbackVotes: vi.fn(),+ listInteractions: vi.fn(),+ getQueuedComments: vi.fn(),+ editQueuedComment: vi.fn(),+ reorderQueuedComments: vi.fn(),+ steerQueuedComment: vi.fn(),+ discardQueuedComment: vi.fn(),markRead: vi.fn(),update: vi.fn(),+ resolveRecoveryAction: vi.fn(),previewTreeControl: vi.fn(),getTreeControlState: vi.fn(),listTreeHolds: vi.fn(),@@ -94,13 +117,23 @@ const mockSetPanelVisible = vi.hoisted(() => vi.fn());const mockPanelState = vi.hoisted(() => ({ panelVisible: true }));const mockSidebarState = vi.hoisted(() => ({ isMobile: false }));const mockIssuePropertiesRender = vi.hoisted(() => vi.fn());+const mockTaskSidePanelRender = vi.hoisted(() => vi.fn());const mockSetBreadcrumbs = vi.hoisted(() => vi.fn());+const mockSetBreadcrumbToolbar = vi.hoisted(() => vi.fn());const mockSetMobileToolbar = vi.hoisted(() => vi.fn());const mockPushToast = vi.hoisted(() => vi.fn());const mockIssuesListRender = vi.hoisted(() => vi.fn());const mockIssueChatThreadRender = vi.hoisted(() => vi.fn());const mockImageGalleryRender = vi.hoisted(() => vi.fn());const mockIssueWorkspaceCardRender = vi.hoisted(() => vi.fn());+const DIRECT_ADAPTER_TYPES = [+ "codex_local",+ "claude_local",+ "opencode_local",+ "process",+ "http",+ "custom_plugin",+] as const;class ResizeObserverStub {observe() {}@@ -108,7 +141,8 @@ class ResizeObserverStub {disconnect() {}}-(globalThis as any).ResizeObserver = (globalThis as any).ResizeObserver ?? ResizeObserverStub;+(globalThis as any).ResizeObserver =+ (globalThis as any).ResizeObserver ?? ResizeObserverStub;vi.mock("../api/issues", () => ({issuesApi: mockIssuesApi,@@ -170,7 +204,9 @@ vi.mock("@/lib/router", () => ({issueQuicklookSide?: unknown;issueQuicklookAlign?: unknown;} & AnchorHTMLAttributes<HTMLAnchorElement>) => (- <a href={to} {...props}>{children}</a>+ <a href={to} {...props}>+ {children}+ </a>),useLocation: () => mockLocation,useNavigate: () => mockNavigate,@@ -180,9 +216,21 @@ vi.mock("@/lib/router", () => ({vi.mock("../context/CompanyContext", () => ({useCompany: () => ({- companies: [{ id: "company-1", name: "Paperclip", issuePrefix: "PAP", status: "active" }],+ companies: [+ {+ id: "company-1",+ name: "Paperclip",+ issuePrefix: "PAP",+ status: "active",+ },+ ],selectedCompanyId: "company-1",- selectedCompany: { id: "company-1", name: "Paperclip", issuePrefix: "PAP", status: "active" },+ selectedCompany: {+ id: "company-1",+ name: "Paperclip",+ issuePrefix: "PAP",+ status: "active",+ },selectionSource: "manual",loading: false,error: null,@@ -223,6 +271,7 @@ vi.mock("../context/SidebarContext", () => ({vi.mock("../context/BreadcrumbContext", () => ({useBreadcrumbs: () => ({setBreadcrumbs: mockSetBreadcrumbs,+ setBreadcrumbToolbar: mockSetBreadcrumbToolbar,setMobileToolbar: mockSetMobileToolbar,}),}));@@ -250,9 +299,13 @@ vi.mock("@/plugins/launchers", () => ({}));vi.mock("../components/InlineEditor", () => ({- InlineEditor: ({ value, placeholder }: { value?: string; placeholder?: string }) => (- <div>{value || placeholder}</div>- ),+ InlineEditor: ({+ value,+ placeholder,+ }: {+ value?: string;+ placeholder?: string;+ }) => <div>{value || placeholder}</div>,}));vi.mock("../components/IssueChatThread", () => ({@@ -282,7 +335,10 @@ vi.mock("../components/IssueChatThread", () => ({<div data-testid="issue-chat-thread">Chat thread{props.onStopRun ? (- <button type="button" onClick={() => void props.onStopRun?.("run-active-1")}>+ <button+ type="button"+ onClick={() => void props.onStopRun?.("run-active-1")}+ >{props.stopRunLabel ?? "Stop run"}</button>) : null}@@ -312,6 +368,7 @@ vi.mock("../components/TaskChatThread", () => ({threadHeader?: ReactNode;onStopRun?: (runId: string) => Promise<void>;stopRunLabel?: string;+ onTryAgainNoLiveExecutionPath?: () => Promise<void> | void;runFinalizationActions?: readonly {id: string;label: string;@@ -325,10 +382,22 @@ vi.mock("../components/TaskChatThread", () => ({{props.threadHeader}Task chat thread{props.onStopRun ? (- <button type="button" onClick={() => void props.onStopRun?.("run-active-1")}>+ <button+ type="button"+ onClick={() => void props.onStopRun?.("run-active-1")}+ >{props.stopRunLabel ?? "Stop run"}</button>) : null}+ {props.onTryAgainNoLiveExecutionPath ? (+ <button+ type="button"+ data-testid="mock-no-live-path-try-again"+ onClick={() => void props.onTryAgainNoLiveExecutionPath?.()}+ >+ Try again+ </button>+ ) : null}{props.runFinalizationActions?.map((action) => (<buttonkey={action.id}@@ -349,7 +418,9 @@ vi.mock("../components/IssueDocumentsSection", () => ({}));vi.mock("../components/MarkdownBody", () => ({- MarkdownBody: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ MarkdownBody: ({ children }: { children?: ReactNode }) => (+ <div>{children}</div>+ ),}));vi.mock("../components/IssuesList", () => ({@@ -358,9 +429,13 @@ vi.mock("../components/IssuesList", () => ({return (<div>Sub-issues- {Array.from(props.issueBadgeById?.entries() ?? []).map(([issueId, label]) => (- <span key={issueId}>{issueId}:{label}</span>- ))}+ {Array.from(props.issueBadgeById?.entries() ?? []).map(+ ([issueId, label]) => (+ <span key={issueId}>+ {issueId}:{label}+ </span>+ ),+ )}</div>);},@@ -373,19 +448,33 @@ vi.mock("../components/IssueProperties", () => ({},}));+vi.mock("../components/task-side-panel", () => ({+ TaskSidePanel: (props: unknown) => {+ mockTaskSidePanelRender(props);+ return <div>Task side panel</div>;+ },+}));+vi.mock("../components/IssueRunLedger", () => ({IssueRunLedger: () => <div>Runs</div>,}));vi.mock("../components/IssueWorkspaceCard", () => ({- IssueWorkspaceCard: (props: { onBrowseFiles?: () => void; onOpenFileByPath?: () => void }) => {+ IssueWorkspaceCard: (props: {+ onBrowseFiles?: () => void;+ onOpenFileByPath?: () => void;+ }) => {mockIssueWorkspaceCardRender(props);return <div>Workspace</div>;},}));vi.mock("../components/ImageGalleryModal", () => ({- ImageGalleryModal: (props: { items: IssueAttachment[]; initialIndex: number; open: boolean }) => {+ ImageGalleryModal: (props: {+ items: IssueAttachment[];+ initialIndex: number;+ open: boolean;+ }) => {mockImageGalleryRender(props);return null;},@@ -404,28 +493,40 @@ vi.mock("../components/StatusIcon", () => ({status: string;blockerAttention?: Issue["blockerAttention"];onChange?: (status: string) => void;- }) => onChange ? (- <button- type="button"- aria-label={`Change status (current: ${status})`}- data-status-icon-state={blockerAttention?.state}- onClick={() => onChange("done")}- >- {status}- </button>- ) : <span data-status-icon-state={blockerAttention?.state}>{status}</span>,+ }) =>+ onChange ? (+ <button+ type="button"+ aria-label={`Change status (current: ${status})`}+ data-status-icon-state={blockerAttention?.state}+ onClick={() => onChange("done")}+ >+ {status}+ </button>+ ) : (+ <span data-status-icon-state={blockerAttention?.state}>{status}</span>+ ),}));vi.mock("../components/PriorityIcon", () => ({- PriorityIcon: ({ priority, onChange }: { priority: string; onChange?: (priority: string) => void }) => onChange ? (- <button- type="button"- aria-label={`Change priority (current: ${priority})`}- onClick={() => onChange("high")}- >- {priority}- </button>- ) : <span>{priority}</span>,+ PriorityIcon: ({+ priority,+ onChange,+ }: {+ priority: string;+ onChange?: (priority: string) => void;+ }) =>+ onChange ? (+ <button+ type="button"+ aria-label={`Change priority (current: ${priority})`}+ onClick={() => onChange("high")}+ >+ {priority}+ </button>+ ) : (+ <span>{priority}</span>+ ),}));vi.mock("../components/ApprovalCard", () => ({@@ -433,7 +534,9 @@ vi.mock("../components/ApprovalCard", () => ({}));vi.mock("../components/Identity", () => ({- Identity: ({ name, shape }: { name: string; shape?: string }) => <span data-shape={shape ?? "circle"}>{name}</span>,+ Identity: ({ name, shape }: { name: string; shape?: string }) => (+ <span data-shape={shape ?? "circle"}>{name}</span>+ ),}));vi.mock("@/components/ui/button", () => ({@@ -446,7 +549,11 @@ vi.mock("@/components/ui/button", () => ({size: _size,asChild: _asChild,...props- }: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: string; size?: string; asChild?: boolean }) => (+ }: ButtonHTMLAttributes<HTMLButtonElement> & {+ variant?: string;+ size?: string;+ asChild?: boolean;+ }) => (<button {...props} type={type} disabled={disabled} onClick={onClick}>{children}</button>@@ -460,25 +567,80 @@ vi.mock("@/components/ui/separator", () => ({vi.mock("@/components/ui/popover", () => ({Popover: ({ children }: { children?: ReactNode }) => <>{children}</>,PopoverTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,- PopoverContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ PopoverContent: ({ children }: { children?: ReactNode }) => (+ <div>{children}</div>+ ),}));vi.mock("@/components/ui/dialog", () => ({- Dialog: ({ children, open }: { children?: ReactNode; open?: boolean }) => (open ? <div>{children}</div> : null),- DialogContent: ({ children, className }: { children?: ReactNode; className?: string }) => (- <div data-slot="dialog-content" className={className}>{children}</div>+ Dialog: ({ children, open }: { children?: ReactNode; open?: boolean }) =>+ open ? <div>{children}</div> : null,+ DialogContent: ({+ children,+ className,+ }: {+ children?: ReactNode;+ className?: string;+ }) => (+ <div data-slot="dialog-content" className={className}>+ {children}+ </div>),- DialogDescription: ({ children, className }: { children?: ReactNode; className?: string }) => <p className={className}>{children}</p>,- DialogFooter: ({ children, className }: { children?: ReactNode; className?: string }) => <div className={className}>{children}</div>,- DialogHeader: ({ children, className }: { children?: ReactNode; className?: string }) => <div className={className}>{children}</div>,- DialogTitle: ({ children, className }: { children?: ReactNode; className?: string }) => <h2 className={className}>{children}</h2>,+ DialogDescription: ({+ children,+ className,+ }: {+ children?: ReactNode;+ className?: string;+ }) => <p className={className}>{children}</p>,+ DialogFooter: ({+ children,+ className,+ }: {+ children?: ReactNode;+ className?: string;+ }) => <div className={className}>{children}</div>,+ DialogHeader: ({+ children,+ className,+ }: {+ children?: ReactNode;+ className?: string;+ }) => <div className={className}>{children}</div>,+ DialogTitle: ({+ children,+ className,+ }: {+ children?: ReactNode;+ className?: string;+ }) => <h2 className={className}>{children}</h2>,}));vi.mock("@/components/ui/sheet", () => ({- Sheet: ({ children, open }: { children?: ReactNode; open?: boolean }) => (open ? <div>{children}</div> : null),- SheetContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,- SheetHeader: ({ children }: { children?: ReactNode }) => <div>{children}</div>,- SheetDescription: ({ children }: { children?: ReactNode }) => <p>{children}</p>,+ Sheet: ({ children, open }: { children?: ReactNode; open?: boolean }) =>+ open ? <div>{children}</div> : null,+ SheetContent: ({+ children,+ className,+ "data-testid": testId,+ }: {+ children?: ReactNode;+ className?: string;+ "data-testid"?: string;+ }) => (+ <div data-slot="sheet-content" className={className} data-testid={testId}>+ {children}+ <button type="button" data-slot="sheet-close">+ Close+ </button>+ </div>+ ),+ SheetHeader: ({ children }: { children?: ReactNode }) => (+ <div>{children}</div>+ ),+ SheetDescription: ({ children }: { children?: ReactNode }) => (+ <p>{children}</p>+ ),SheetTitle: ({ children }: { children?: ReactNode }) => <h2>{children}</h2>,}));@@ -492,13 +654,29 @@ vi.mock("@/components/ui/skeleton", () => ({vi.mock("@/components/ui/tabs", () => ({Tabs: ({ children }: { children?: ReactNode }) => <div>{children}</div>,- TabsContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ TabsContent: ({+ children,+ className,+ "data-testid": testId,+ }: {+ children?: ReactNode;+ className?: string;+ "data-testid"?: string;+ }) => (+ <div className={className} data-testid={testId}>+ {children}+ </div>+ ),TabsList: ({ children }: { children?: ReactNode }) => <div>{children}</div>,- TabsTrigger: ({ children }: { children?: ReactNode }) => <button type="button">{children}</button>,+ TabsTrigger: ({ children }: { children?: ReactNode }) => (+ <button type="button">{children}</button>+ ),}));vi.mock("@/components/ui/textarea", () => ({- Textarea: (props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) => <textarea {...props} />,+ Textarea: (props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) => (+ <textarea {...props} />+ ),}));// eslint-disable-next-line @typescript-eslint/no-explicit-any@@ -512,6 +690,18 @@ async function act(callback: () => void | Promise<void>) {await result;}+function createTooltipRoot(container: Element): Root {+ const root = createRoot(container);+ return {+ render(children) {+ root.render(<TooltipProvider>{children}</TooltipProvider>);+ },+ unmount() {+ root.unmount();+ },+ };+}+function createDeferred<T>() {let resolve!: (value: T) => void;const promise = new Promise<T>((innerResolve) => {@@ -569,7 +759,9 @@ function createIssue(overrides: Partial<Issue> = {}): Issue {} as Issue;}-function createIssueComment(overrides: Partial<IssueComment> = {}): IssueComment {+function createIssueComment(+ overrides: Partial<IssueComment> = {},+): IssueComment {return {id: "comment-1",companyId: "company-1",@@ -586,7 +778,29 @@ function createIssueComment(overrides: Partial<IssueComment> = {}): IssueComment};}-function createAttachment(overrides: Partial<IssueAttachment> & { id: string }): IssueAttachment {+function createQueuedCommentQueue(+ overrides: Partial<IssueQueuedCommentQueue> = {},+): IssueQueuedCommentQueue {+ const comment = createIssueComment({+ id: "queued-comment-1",+ body: "Queued through the handoff",+ });+ return {+ issueId: "issue-1",+ queueId: "wake-queue-1",+ state: "deferred",+ targetRunId: "run-active-1",+ revision: "queue-revision-1",+ protocol: "paperclip_runner_v1",+ steeringDisposition: "available",+ entries: [{ comment, position: 0, canEdit: true, canDiscard: true }],+ ...overrides,+ };+}++function createAttachment(+ overrides: Partial<IssueAttachment> & { id: string },+): IssueAttachment {const { id, ...attachmentOverrides } = overrides;return {id,@@ -606,7 +820,8 @@ function createAttachment(overrides: Partial<IssueAttachment> & { id: string }):updatedAt: new Date("2026-04-21T00:00:00.000Z"),contentPath: overrides.contentPath ?? `/api/attachments/${id}/content`,openPath: overrides.openPath ?? `/api/attachments/${id}/content`,- downloadPath: overrides.downloadPath ?? `/api/attachments/${id}/content?download=1`,+ downloadPath:+ overrides.downloadPath ?? `/api/attachments/${id}/content?download=1`,...attachmentOverrides,};}@@ -619,7 +834,13 @@ function createArtifactWorkProduct(originalFilename: string;},): IssueWorkProduct {- const { id, attachmentId, contentType, originalFilename, ...workProductOverrides } = overrides;+ const {+ id,+ attachmentId,+ contentType,+ originalFilename,+ ...workProductOverrides+ } = overrides;const contentPath = `/api/attachments/${attachmentId}/content`;return {id,@@ -682,7 +903,9 @@ function createAgent(overrides: Partial<Agent> = {}): Agent {};}-function createPauseHold(overrides: Partial<IssueTreeHold> = {}): IssueTreeHold {+function createPauseHold(+ overrides: Partial<IssueTreeHold> = {},+): IssueTreeHold {const now = new Date("2026-04-21T00:00:00.000Z");return {id: "hold-1",@@ -1031,7 +1254,7 @@ describe("IssueDetail", () => {mockSidebarState.isMobile = false;container = document.createElement("div");document.body.appendChild(container);- root = createRoot(container);+ root = createTooltipRoot(container);queryClient = new QueryClient({defaultOptions: {queries: { retry: false },@@ -1050,10 +1273,39 @@ describe("IssueDetail", () => {mockIssuesApi.listAttachments.mockResolvedValue([]);mockIssuesApi.listWorkProducts.mockResolvedValue([]);mockIssuesApi.listFeedbackVotes.mockResolvedValue([]);- mockIssuesApi.markRead.mockResolvedValue({ id: "issue-1", lastReadAt: new Date().toISOString() });- mockIssuesApi.archiveFromInbox.mockResolvedValue({ id: "issue-1", archivedAt: new Date() });+ mockIssuesApi.listInteractions.mockResolvedValue([]);+ mockIssuesApi.getQueuedComments.mockResolvedValue(+ createQueuedCommentQueue({+ queueId: null,+ state: null,+ targetRunId: null,+ entries: [],+ }),+ );+ mockIssuesApi.editQueuedComment.mockResolvedValue(+ createQueuedCommentQueue(),+ );+ mockIssuesApi.reorderQueuedComments.mockResolvedValue(+ createQueuedCommentQueue(),+ );+ mockIssuesApi.steerQueuedComment.mockResolvedValue(+ createQueuedCommentQueue(),+ );+ mockIssuesApi.discardQueuedComment.mockResolvedValue(+ createQueuedCommentQueue({ entries: [] }),+ );+ mockIssuesApi.markRead.mockResolvedValue({+ id: "issue-1",+ lastReadAt: new Date().toISOString(),+ });+ mockIssuesApi.archiveFromInbox.mockResolvedValue({+ id: "issue-1",+ archivedAt: new Date(),+ });mockIssuesApi.unarchiveFromInbox.mockResolvedValue({ ok: true });- mockIssuesApi.getTreeControlState.mockResolvedValue({ activePauseHold: null });+ mockIssuesApi.getTreeControlState.mockResolvedValue({+ activePauseHold: null,+ });mockIssuesApi.listTreeHolds.mockResolvedValue([]);mockActivityApi.forIssue.mockResolvedValue([]);mockActivityApi.runsForIssue.mockResolvedValue([]);@@ -1087,6 +1339,7 @@ describe("IssueDetail", () => {mockClosePanel.mockClear();mockSetPanelVisible.mockClear();mockIssuePropertiesRender.mockClear();+ mockTaskSidePanelRender.mockClear();mockIssuesListRender.mockClear();mockIssueChatThreadRender.mockClear();mockImageGalleryRender.mockClear();@@ -1095,6 +1348,7 @@ describe("IssueDetail", () => {mockOpenNewIssue.mockClear();mockOpenNewProject.mockClear();mockOpenNewGoal.mockClear();+ mockPushToast.mockClear();mockLocation.pathname = "/issues/PAP-1";mockLocation.search = "";mockLocation.hash = "";@@ -1131,12 +1385,74 @@ describe("IssueDetail", () => {expect(container.textContent).toContain("Task chat thread");expect(consoleErrorSpy.mock.calls.some((call: unknown[]) =>- String(call[0]).includes("React has detected a change in the order of Hooks"),+ String(call[0]).includes(+ "React has detected a change in the order of Hooks",+ ),),).toBe(false);});- it("opens a closed desktop pane and routes an ordinary document to Artifacts on direct load", async () => {+ it("lifts the redesigned desktop thread into the side-panel header band", async () => {+ mockIssuesApi.get.mockResolvedValue(createIssue());++ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <IssueDetail />+ </QueryClientProvider>,+ );+ });+ await waitForAssertion(() => {+ const content = container.querySelector(+ '[data-testid="issue-detail-content"]',+ );+ expect(content).not.toBeNull();+ expect(content!.className).toContain("-mt-4");+ expect(content!.className).toContain("md:-mt-6");+ });+ });++ it("registers the persistent breadcrumb side-panel toggle only while the panel is closed", async () => {+ mockIssuesApi.get.mockResolvedValue(createIssue());++ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <IssueDetail />+ </QueryClientProvider>,+ );+ });+ await flushReact();+ expect(+ container.querySelector('button[aria-label="Toggle side panel"]'),+ ).toBeNull();+ expect(mockSetBreadcrumbToolbar.mock.calls.at(-1)?.[0]).toBeNull();++ mockSetBreadcrumbToolbar.mockClear();+ mockPanelState.panelVisible = false;+ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <IssueDetail />+ </QueryClientProvider>,+ );+ });+ await flushReact();+ expect(+ container.querySelector('button[aria-label="Toggle side panel"]'),+ ).toBeNull();++ const toolbar = mockSetBreadcrumbToolbar.mock.calls+ .map(([node]) => node)+ .find((node) => node !== null) as ReactElement<{+ children: ReactElement<{ onToggle: () => void }>;+ }>;+ expect(toolbar).toBeDefined();+ toolbar.props.children.props.onToggle();+ expect(mockSetPanelVisible).toHaveBeenCalledWith(true);+ });++ it("opens a closed desktop pane and routes an ordinary document to its own tab on direct load", async () => {mockPanelState.panelVisible = false;mockLocation.hash = "#document-qa-evidence";mockIssuesApi.get.mockResolvedValue(createIssue());@@ -1151,9 +1467,10 @@ describe("IssueDetail", () => {await waitForAssertion(() => {expect(mockSetPanelVisible).toHaveBeenCalledWith(true);- const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as { props?: Record<string, unknown> } | undefined;+ const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as+ { props?: Record<string, unknown> } | undefined;expect(panel?.props?.documentDeepLink).toMatchObject({- tab: "artifacts",+ tab: "document",documentKey: "qa-evidence",});});@@ -1179,9 +1496,12 @@ describe("IssueDetail", () => {});await waitForAssertion(() => {- expect(container.querySelector('[data-testid="issue-chat-thread"]')).not.toBeNull();+ expect(+ container.querySelector('[data-testid="issue-chat-thread"]'),+ ).not.toBeNull();expect(mockSetPanelVisible).not.toHaveBeenCalled();- const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as { props?: Record<string, unknown> } | undefined;+ const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as+ { props?: Record<string, unknown> } | undefined;expect(panel?.props?.documentDeepLink).toBeNull();});});@@ -1198,8 +1518,11 @@ describe("IssueDetail", () => {);});await waitForAssertion(() => {- const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as { props?: Record<string, unknown> } | undefined;- expect(panel?.props?.documentDeepLink).toMatchObject({ documentKey: "qa-evidence" });+ const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as+ { props?: Record<string, unknown> } | undefined;+ expect(panel?.props?.documentDeepLink).toMatchObject({+ documentKey: "qa-evidence",+ });});mockLocation.hash = "#work-product-1";@@ -1212,7 +1535,8 @@ describe("IssueDetail", () => {});await waitForAssertion(() => {- const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as { props?: Record<string, unknown> } | undefined;+ const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as+ { props?: Record<string, unknown> } | undefined;expect(panel?.props?.documentDeepLink).toBeNull();});});@@ -1230,8 +1554,12 @@ describe("IssueDetail", () => {);});await waitForAssertion(() => {- const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as { props?: Record<string, unknown> } | undefined;- expect(panel?.props?.documentDeepLink).toMatchObject({ tab: "plans", documentKey: "plan" });+ const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as+ { props?: Record<string, unknown> } | undefined;+ expect(panel?.props?.documentDeepLink).toMatchObject({+ tab: "plans",+ documentKey: "plan",+ });});mockSetPanelVisible.mockClear();@@ -1245,7 +1573,8 @@ describe("IssueDetail", () => {});expect(mockSetPanelVisible).not.toHaveBeenCalled();await waitForAssertion(() => {- const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as { props?: Record<string, unknown> } | undefined;+ const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as+ { props?: Record<string, unknown> } | undefined;expect(panel?.props?.documentDeepLink).toBeNull();});});@@ -1261,8 +1590,12 @@ describe("IssueDetail", () => {);});await waitForAssertion(() => {- const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as { props?: Record<string, unknown> } | undefined;- expect((panel?.props?.documentDeepLink as { requestId?: number } | null)?.requestId).toBe(1);+ const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as+ { props?: Record<string, unknown> } | undefined;+ expect(+ (panel?.props?.documentDeepLink as { requestId?: number } | null)+ ?.requestId,+ ).toBe(1);});const link = document.createElement("a");@@ -1272,8 +1605,12 @@ describe("IssueDetail", () => {await act(async () => link.click());await waitForAssertion(() => {- const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as { props?: Record<string, unknown> } | undefined;- expect((panel?.props?.documentDeepLink as { requestId?: number } | null)?.requestId).toBe(2);+ const panel = mockOpenPanel.mock.calls.at(-1)?.[0] as+ { props?: Record<string, unknown> } | undefined;+ expect(+ (panel?.props?.documentDeepLink as { requestId?: number } | null)+ ?.requestId,+ ).toBe(2);});});@@ -1291,17 +1628,53 @@ describe("IssueDetail", () => {});await waitForAssertion(() => {- expect(mockIssuePropertiesRender).toHaveBeenCalledWith(expect.objectContaining({- inline: true,- documentDeepLink: expect.objectContaining({- tab: "artifacts",- documentKey: "qa-evidence",+ expect(mockTaskSidePanelRender).toHaveBeenCalledWith(+ expect.objectContaining({+ inline: true,+ documentDeepLink: expect.objectContaining({+ tab: "document",+ documentKey: "qa-evidence",+ }),}),- }));+ );});expect(mockSetPanelVisible).not.toHaveBeenCalled();});+ it("opens a plan deep link in the shared mobile side-panel sheet", async () => {+ mockSidebarState.isMobile = true;+ mockLocation.hash = "#document-plan";+ mockIssuesApi.get.mockResolvedValue(createIssue());++ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <IssueDetail />+ </QueryClientProvider>,+ );+ });++ await waitForAssertion(() => {+ expect(mockTaskSidePanelRender).toHaveBeenCalledWith(+ expect.objectContaining({+ inline: true,+ documentDeepLink: expect.objectContaining({+ tab: "plans",+ documentKey: "plan",+ }),+ }),+ );+ });++ const panel = document.querySelector(+ '[data-testid="mobile-task-side-panel"]',+ );+ expect(panel).not.toBeNull();+ expect(panel?.className).toContain("max-h-(--sz-85dvh)");+ expect(panel?.textContent).toContain("Task side panel");+ expect(panel?.querySelector('[data-slot="sheet-close"]')).not.toBeNull();+ });+it("renders the full sub-task tree below the title in the chat center pane", async () => {mockIssuesApi.get.mockResolvedValue(createIssue());mockIssuesApi.list.mockResolvedValue([@@ -1332,7 +1705,10 @@ describe("IssueDetail", () => {);expect(title).toBeDefined();expect(subTasks).toBeDefined();- expect(title!.compareDocumentPosition(subTasks!) & Node.DOCUMENT_POSITION_FOLLOWING).not.toBe(0);+ expect(+ title!.compareDocumentPosition(subTasks!) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ).not.toBe(0);expect(mockIssuesListRender).toHaveBeenCalledWith(expect.objectContaining({createIssueLabel: "Sub-task",@@ -1430,22 +1806,24 @@ describe("IssueDetail", () => {});it("does not load or render decision sections in the issue header", async () => {- mockIssuesApi.get.mockResolvedValue(createIssue({- status: "in_review",- reviewAttention: {- state: "covered",- reason: "Review has a maintained action path.",- paths: [- {- kind: "interaction",- label: "Pending request confirmation",- responder: "Board",- since: "2026-04-21T00:00:00.000Z",- ref: "interaction-1",- },- ],- },- }));+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_review",+ reviewAttention: {+ state: "covered",+ reason: "Review has a maintained action path.",+ paths: [+ {+ kind: "interaction",+ label: "Pending request confirmation",+ responder: "Board",+ since: "2026-04-21T00:00:00.000Z",+ ref: "interaction-1",+ },+ ],+ },+ }),+ );await act(async () => {root.render(@@ -1458,17 +1836,21 @@ describe("IssueDetail", () => {await flushReact();expect(container.textContent).toContain("Issue detail smoke");- expect(container.querySelector('[data-testid="issue-review-panel"]')).toBeNull();+ expect(+ container.querySelector('[data-testid="issue-review-panel"]'),+ ).toBeNull();expect(mockDecisionsApi.list).not.toHaveBeenCalled();});it("updates status from the task header control and hides the priority control (PAP-411)", async () => {const issue = createIssue({ status: "todo", priority: "medium" });mockIssuesApi.get.mockResolvedValue(issue);- mockIssuesApi.update.mockImplementation(async (_issueId: string, data: Record<string, unknown>) => ({- ...issue,- ...data,- }));+ mockIssuesApi.update.mockImplementation(+ async (_issueId: string, data: Record<string, unknown>) => ({+ ...issue,+ ...data,+ }),+ );await act(async () => {root.render(@@ -1492,10 +1874,14 @@ describe("IssueDetail", () => {expect(priorityButton).toBeNull();await act(async () => {- statusButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));+ statusButton!.dispatchEvent(+ new MouseEvent("click", { bubbles: true, cancelable: true }),+ );});await waitForAssertion(() => {- expect(mockIssuesApi.update).toHaveBeenCalledWith(issue.identifier, { status: "done" });+ expect(mockIssuesApi.update).toHaveBeenCalledWith(issue.identifier, {+ status: "done",+ });});expect(mockIssuesApi.update).not.toHaveBeenCalledWith(issue.identifier,@@ -1505,11 +1891,68 @@ describe("IssueDetail", () => {mockIssuesApi.update.mockReset();});+ it("moves a blocked task back to todo when the no-live-path notice tries again", async () => {+ const activeRecoveryAction = {+ id: "recovery-action-1",+ } as NonNullable<Issue["activeRecoveryAction"]>;+ const issue = createIssue({+ status: "blocked",+ assigneeAgentId: "agent-1",+ activeRecoveryAction,+ });+ mockIssuesApi.get.mockResolvedValue(issue);+ mockIssuesApi.resolveRecoveryAction.mockResolvedValue({+ issue: { ...issue, status: "todo", activeRecoveryAction: null },+ recoveryAction: { ...activeRecoveryAction, status: "resolved" },+ });++ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <IssueDetail />+ </QueryClientProvider>,+ );+ });+ await flushReact();+ await flushReact();++ const tryAgain = container.querySelector<HTMLButtonElement>(+ '[data-testid="mock-no-live-path-try-again"]',+ );+ expect(tryAgain).not.toBeNull();++ await act(async () => {+ tryAgain!.click();+ });++ await waitForAssertion(() => {+ expect(mockIssuesApi.resolveRecoveryAction).toHaveBeenCalledWith(issue.identifier, {+ actionId: activeRecoveryAction.id,+ outcome: "restored",+ sourceIssueStatus: "todo",+ });+ });++ mockIssuesApi.resolveRecoveryAction.mockReset();+ });+it("removes an inbox-origin archived issue and restores it when the toast Undo action is pressed", async () => {- const issue = createIssue({ id: "issue-1", identifier: "PAP-1", title: "Archive me from detail" });- const otherIssue = createIssue({ id: "issue-2", identifier: "PAP-2", title: "Keep me in inbox" });+ const issue = createIssue({+ id: "issue-1",+ identifier: "PAP-1",+ title: "Archive me from detail",+ });+ const otherIssue = createIssue({+ id: "issue-2",+ identifier: "PAP-2",+ title: "Keep me in inbox",+ });const archiveRequest = createDeferred<{ id: string; archivedAt: Date }>();- mockLocation.state = createIssueDetailLocationState("Inbox", "/inbox/mine", "inbox");+ mockLocation.state = createIssueDetailLocationState(+ "Inbox",+ "/inbox/mine",+ "inbox",+ );mockIssuesApi.get.mockResolvedValue(issue);mockIssuesApi.archiveFromInbox.mockReturnValue(archiveRequest.promise);@@ -1551,14 +1994,24 @@ describe("IssueDetail", () => {expect(archiveButton).not.toBeNull();await act(async () => {- archiveButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));+ archiveButton!.dispatchEvent(+ new MouseEvent("click", { bubbles: true, cancelable: true }),+ );});await waitForAssertion(() => {- expect(queryClient.getQueryData<Issue[]>(mineKey)?.map((item) => item.id)).toEqual(["issue-2"]);- expect(queryClient.getQueryData<Issue[]>(compactKey)?.map((item) => item.id)).toEqual(["issue-2"]);- expect(queryClient.getQueryData<Issue[]>(touchedKey)?.map((item) => item.id)).toEqual(["issue-2"]);- expect(queryClient.getQueryData<Issue[]>(unreadKey)?.map((item) => item.id)).toEqual(["issue-2"]);+ expect(+ queryClient.getQueryData<Issue[]>(mineKey)?.map((item) => item.id),+ ).toEqual(["issue-2"]);+ expect(+ queryClient.getQueryData<Issue[]>(compactKey)?.map((item) => item.id),+ ).toEqual(["issue-2"]);+ expect(+ queryClient.getQueryData<Issue[]>(touchedKey)?.map((item) => item.id),+ ).toEqual(["issue-2"]);+ expect(+ queryClient.getQueryData<Issue[]>(unreadKey)?.map((item) => item.id),+ ).toEqual(["issue-2"]);expect(mockNavigate).not.toHaveBeenCalled();});@@ -1579,15 +2032,19 @@ describe("IssueDetail", () => {expect(archiveToast?.action?.onClick).toEqual(expect.any(Function));const staleInboxFetch = createDeferred<Issue[]>();- const staleInboxRequest = queryClient.fetchQuery({- queryKey: mineKey,- queryFn: () => staleInboxFetch.promise,- }).catch(() => undefined);+ const staleInboxRequest = queryClient+ .fetchQuery({+ queryKey: mineKey,+ queryFn: () => staleInboxFetch.promise,+ })+ .catch(() => undefined);const staleCompactFetch = createDeferred<Issue[]>();- const staleCompactRequest = queryClient.fetchQuery({- queryKey: compactKey,- queryFn: () => staleCompactFetch.promise,- }).catch(() => undefined);+ const staleCompactRequest = queryClient+ .fetchQuery({+ queryKey: compactKey,+ queryFn: () => staleCompactFetch.promise,+ })+ .catch(() => undefined);await waitForAssertion(() => {expect(queryClient.isFetching({ queryKey: mineKey })).toBe(1);expect(queryClient.isFetching({ queryKey: compactKey })).toBe(1);@@ -1603,19 +2060,40 @@ describe("IssueDetail", () => {await staleCompactRequest;await waitForAssertion(() => {expect(mockIssuesApi.unarchiveFromInbox).toHaveBeenCalledWith("issue-1");- expect(queryClient.getQueryData<Issue[]>(mineKey)?.map((item) => item.id)).toEqual(["issue-1", "issue-2"]);- expect(queryClient.getQueryData<Issue[]>(compactKey)?.map((item) => item.id)).toEqual(["issue-1", "issue-2"]);- expect(queryClient.getQueryData<Issue[]>(touchedKey)?.map((item) => item.id)).toEqual(["issue-1", "issue-2"]);- expect(queryClient.getQueryData<Issue[]>(unreadKey)?.map((item) => item.id)).toEqual(["issue-1", "issue-2"]);- expect(mockPushToast).toHaveBeenCalledWith({ title: "Task restored to inbox", tone: "success" });+ expect(+ queryClient.getQueryData<Issue[]>(mineKey)?.map((item) => item.id),+ ).toEqual(["issue-1", "issue-2"]);+ expect(+ queryClient.getQueryData<Issue[]>(compactKey)?.map((item) => item.id),+ ).toEqual(["issue-1", "issue-2"]);+ expect(+ queryClient.getQueryData<Issue[]>(touchedKey)?.map((item) => item.id),+ ).toEqual(["issue-1", "issue-2"]);+ expect(+ queryClient.getQueryData<Issue[]>(unreadKey)?.map((item) => item.id),+ ).toEqual(["issue-1", "issue-2"]);+ expect(mockPushToast).toHaveBeenCalledWith({+ title: "Task restored to inbox",+ tone: "success",+ });});});it("keeps an archived task hidden and reports an error when toast Undo fails", async () => {- const issue = createIssue({ id: "issue-1", identifier: "PAP-1", title: "Archive me from detail" });- mockLocation.state = createIssueDetailLocationState("Inbox", "/inbox/mine", "inbox");+ const issue = createIssue({+ id: "issue-1",+ identifier: "PAP-1",+ title: "Archive me from detail",+ });+ mockLocation.state = createIssueDetailLocationState(+ "Inbox",+ "/inbox/mine",+ "inbox",+ );mockIssuesApi.get.mockResolvedValue(issue);- mockIssuesApi.unarchiveFromInbox.mockRejectedValue(new Error("Inbox policy denied"));+ mockIssuesApi.unarchiveFromInbox.mockRejectedValue(+ new Error("Inbox policy denied"),+ );const mineKey = [...queryKeys.issues.listMineByMe("company-1"),@@ -1639,7 +2117,9 @@ describe("IssueDetail", () => {);expect(archiveButton).not.toBeNull();await act(async () => {- archiveButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));+ archiveButton!.dispatchEvent(+ new MouseEvent("click", { bubbles: true, cancelable: true }),+ );});await waitForAssertion(() => {expect(queryClient.getQueryData<Issue[]>(mineKey)).toEqual([]);@@ -1666,19 +2146,28 @@ describe("IssueDetail", () => {});it("shows assignee and originating avatars in the issue header metadata", async () => {- mockIssuesApi.get.mockResolvedValue(createIssue({- assigneeAgentId: "agent-1",- projectId: "project-1",- createdByUserId: "user-1",- }));+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ assigneeAgentId: "agent-1",+ projectId: "project-1",+ createdByUserId: "user-1",+ }),+ );mockAgentsApi.list.mockResolvedValue([createAgent({ name: "CodexCoder" })]);- mockProjectsApi.list.mockResolvedValue([{ id: "project-1", name: "Core Product", color: "#2563eb" }]);+ mockProjectsApi.list.mockResolvedValue([+ { id: "project-1", name: "Core Product", color: "#2563eb" },+ ]);mockAccessApi.listUserDirectory.mockResolvedValue({users: [{principalId: "user-1",status: "active",- user: { id: "user-1", name: "Dotta", email: "[email protected]", image: null },+ user: {+ id: "user-1",+ name: "Dotta",+ email: "[email protected]",+ image: null,+ },},],});@@ -1698,14 +2187,24 @@ describe("IssueDetail", () => {await flushReact();await waitForAssertion(() => {- const avatarStack = container.querySelector('[data-testid="issue-attribution-avatar-stack"]');- const assigneeAvatar = container.querySelector('[data-testid="issue-assignee-avatar"]');- const originatingAvatar = container.querySelector('[data-testid="issue-originating-avatar"]');+ const avatarStack = container.querySelector(+ '[data-testid="issue-attribution-avatar-stack"]',+ );+ const assigneeAvatar = container.querySelector(+ '[data-testid="issue-assignee-avatar"]',+ );+ const originatingAvatar = container.querySelector(+ '[data-testid="issue-originating-avatar"]',+ );expect(container.textContent).toContain("Core Product");expect(avatarStack).toBeTruthy();- expect(assigneeAvatar?.getAttribute("aria-label")).toBe("Assignee: CodexCoder");- expect(originatingAvatar?.getAttribute("aria-label")).toBe("Originating: Dotta");+ expect(assigneeAvatar?.getAttribute("aria-label")).toBe(+ "Assignee: CodexCoder",+ );+ expect(originatingAvatar?.getAttribute("aria-label")).toBe(+ "Originating: Dotta",+ );expect(assigneeAvatar?.getAttribute("title")).toBeNull();expect(originatingAvatar?.getAttribute("title")).toBeNull();expect(avatarStack?.textContent).not.toContain("Assignee");@@ -1715,42 +2214,61 @@ describe("IssueDetail", () => {});const pointerEvent = window.PointerEvent ?? MouseEvent;- const assigneeAvatar = container.querySelector('[data-testid="issue-assignee-avatar"]');- const originatingAvatar = container.querySelector('[data-testid="issue-originating-avatar"]');+ const assigneeAvatar = container.querySelector(+ '[data-testid="issue-assignee-avatar"]',+ );+ const originatingAvatar = container.querySelector(+ '[data-testid="issue-originating-avatar"]',+ );await act(async () => {- assigneeAvatar?.dispatchEvent(new pointerEvent("pointermove", { bubbles: true }));+ assigneeAvatar?.dispatchEvent(+ new pointerEvent("pointermove", { bubbles: true }),+ );});await waitForAssertion(() => {- const tooltip = document.body.querySelector('[data-testid="issue-assignee-tooltip"]');+ const tooltip = document.body.querySelector(+ '[data-testid="issue-assignee-tooltip"]',+ );expect(tooltip?.textContent).toContain("Assignee");expect(tooltip?.textContent).toContain("CodexCoder");});await act(async () => {- originatingAvatar?.dispatchEvent(new pointerEvent("pointermove", { bubbles: true }));+ originatingAvatar?.dispatchEvent(+ new pointerEvent("pointermove", { bubbles: true }),+ );});await waitForAssertion(() => {- const tooltip = document.body.querySelector('[data-testid="issue-originating-tooltip"]');+ const tooltip = document.body.querySelector(+ '[data-testid="issue-originating-tooltip"]',+ );expect(tooltip?.textContent).toContain("Originating");expect(tooltip?.textContent).toContain("Dotta");});});it("attributes an agent-created issue to the transitive responsible user with a via affordance", async () => {- mockIssuesApi.get.mockResolvedValue(createIssue({- assigneeAgentId: "agent-1",- createdByAgentId: "agent-1",- createdByUserId: null,- responsibleUserId: "user-1",- }));+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ assigneeAgentId: "agent-1",+ createdByAgentId: "agent-1",+ createdByUserId: null,+ responsibleUserId: "user-1",+ }),+ );mockAgentsApi.list.mockResolvedValue([createAgent({ name: "CodexCoder" })]);mockAccessApi.listUserDirectory.mockResolvedValue({users: [{principalId: "user-1",status: "active",- user: { id: "user-1", name: "Dotta", email: "[email protected]", image: null },+ user: {+ id: "user-1",+ name: "Dotta",+ email: "[email protected]",+ image: null,+ },},],});@@ -1770,29 +2288,41 @@ describe("IssueDetail", () => {await flushReact();await waitForAssertion(() => {- const originatingAvatar = container.querySelector('[data-testid="issue-originating-avatar"]');- expect(originatingAvatar?.getAttribute("aria-label")).toBe("Originating: Dotta · via CodexCoder");+ const originatingAvatar = container.querySelector(+ '[data-testid="issue-originating-avatar"]',+ );+ expect(originatingAvatar?.getAttribute("aria-label")).toBe(+ "Originating: Dotta · via CodexCoder",+ );});const pointerEvent = window.PointerEvent ?? MouseEvent;- const originatingAvatar = container.querySelector('[data-testid="issue-originating-avatar"]');+ const originatingAvatar = container.querySelector(+ '[data-testid="issue-originating-avatar"]',+ );await act(async () => {- originatingAvatar?.dispatchEvent(new pointerEvent("pointermove", { bubbles: true }));+ originatingAvatar?.dispatchEvent(+ new pointerEvent("pointermove", { bubbles: true }),+ );});await waitForAssertion(() => {- const tooltip = document.body.querySelector('[data-testid="issue-originating-tooltip"]');+ const tooltip = document.body.querySelector(+ '[data-testid="issue-originating-tooltip"]',+ );expect(tooltip?.textContent).toContain("Dotta");expect(tooltip?.textContent).toContain("via CodexCoder");});});it("does not mark the wake comment for the current live run as queued when active-run cache is stale", async () => {- mockIssuesApi.get.mockResolvedValue(createIssue({- status: "in_progress",- executionRunId: "run-stale",- }));- mockIssuesApi.listComments.mockResolvedValue([- createIssueComment({+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_progress",+ executionRunId: "run-stale",+ }),+ );+ mockIssuesApi.listComments.mockResolvedValue([+ createIssueComment({id: "comment-fresh",createdAt: new Date("2026-04-21T00:00:05.000Z"),updatedAt: new Date("2026-04-21T00:00:05.000Z"),@@ -1841,17 +2371,255 @@ describe("IssueDetail", () => {await flushReact();await flushReact();- const props = mockIssueChatThreadRender.mock.calls.at(-1)?.[0] as { comments?: Array<{ id: string; queueState?: string }> };- const freshComment = props.comments?.find((comment) => comment.id === "comment-fresh");+ const props = mockIssueChatThreadRender.mock.calls.at(-1)?.[0] as {+ comments?: Array<{ id: string; queueState?: string }>;+ };+ const freshComment = props.comments?.find(+ (comment) => comment.id === "comment-fresh",+ );expect(freshComment?.queueState).toBeUndefined();});+ it("keeps acknowledged question answers at their submission time while recording successor delivery", async () => {+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_progress",+ assigneeAgentId: "agent-1",+ executionRunId: "run-successor",+ }),+ );+ mockIssuesApi.listInteractions.mockResolvedValue([+ {+ id: "interaction-answers",+ companyId: "company-1",+ issueId: "issue-1",+ kind: "ask_user_questions",+ status: "answered",+ continuationPolicy: "wake_assignee",+ resolverPolicy: "anyone",+ requestedResolverPolicy: "anyone",+ effectiveResolverPolicy: "anyone",+ resolverPolicyProvenance: "inherited",+ effectiveResolverPolicySource: "requested",+ legacyResolverPolicyAliases: { requested: null, effective: null },+ sourceRunId: "run-source",+ resolvedByUserId: "user-1",+ createdAt: "2026-04-21T00:00:01.000Z",+ updatedAt: "2026-04-21T00:00:04.000Z",+ resolvedAt: "2026-04-21T00:00:04.000Z",+ payload: {+ version: 1,+ questions: [+ {+ id: "runtime",+ prompt: "Which runtime?",+ selectionMode: "single",+ options: [{ id: "node", label: "Node.js" }],+ },+ ],+ questionSet: {+ schema: "paperclip.question_set.v1",+ questions: [+ {+ id: "runtime",+ header: "Runtime",+ prompt: "Which runtime?",+ required: true,+ answerMode: "single_select",+ options: [{ id: "node", label: "Node.js" }],+ },+ ],+ },+ },+ result: {+ version: 1,+ answers: [{ questionId: "runtime", optionIds: ["node"] }],+ },+ },+ ]);+ mockActivityApi.forIssue.mockResolvedValue([+ {+ id: "activity-answer-delivered",+ companyId: "company-1",+ actorType: "system",+ actorId: "question-response-delivery",+ agentId: null,+ runId: "run-successor",+ action: "issue.question_response_delivered",+ entityType: "issue",+ entityId: "issue-1",+ details: {+ interactionId: "interaction-answers",+ sourceRunId: "run-source",+ targetRunId: "run-successor",+ targetTurnId: "turn-successor",+ deliveryMode: "steered",+ },+ createdAt: "2026-04-21T00:00:04.000Z",+ },+ ]);+ mockActivityApi.runsForIssue.mockResolvedValue([+ {+ runId: "run-successor",+ agentId: "agent-1",+ agentName: "Runner",+ adapterType: "codex_local",+ status: "running",+ createdAt: "2026-04-21T00:00:02.000Z",+ startedAt: "2026-04-21T00:00:02.000Z",+ finishedAt: null,+ wakeCommentId: "comment-queued",+ wakeCommentIds: ["comment-queued"],+ contextCommentId: "comment-queued",+ logBytes: 1,+ },+ ]);++ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <IssueDetail />+ </QueryClientProvider>,+ );+ });+ await flushReact();+ await flushReact();++ await waitForAssertion(() => {+ const props = mockIssueChatThreadRender.mock.calls.at(-1)?.[0] as {+ comments?: Array<Record<string, unknown>>;+ interactions?: Array<Record<string, unknown>>;+ };+ const delivered = props.comments?.find(+ (comment) => comment.id === "interaction-response:interaction-answers",+ );+ expect(delivered).toMatchObject({+ body: "Answered questions\n\n- Runtime — Which runtime?: Node.js",+ createdAt: new Date("2026-04-21T00:00:04.000Z"),+ updatedAt: new Date("2026-04-21T00:00:04.000Z"),+ consumedByRunId: "run-successor",+ steeredIntoRunId: "run-successor",+ conversationAnchorAt: new Date("2026-04-21T00:00:04.000Z"),+ });+ expect(+ props.comments?.filter((comment) =>+ String(comment.id).startsWith("interaction-response:"),+ ),+ ).toHaveLength(1);+ expect(+ props.interactions?.find(+ (interaction) => interaction.id === "interaction-answers",+ ),+ ).toMatchObject({+ status: "answered",+ sourceRunId: "run-source",+ });+ });+ });++ it.each(["acpx_local", "claude_local", "codex_local"])(+ "projects a resolved plan decision as queued for an active %s legacy run",+ async (adapterType) => {+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_progress",+ assigneeAgentId: "agent-1",+ executionRunId: "run-source",+ }),+ );+ mockIssuesApi.listInteractions.mockResolvedValue([+ {+ id: "interaction-plan",+ companyId: "company-1",+ issueId: "issue-1",+ kind: "request_confirmation",+ status: "accepted",+ continuationPolicy: "wake_assignee",+ resolverPolicy: "anyone",+ requestedResolverPolicy: "anyone",+ effectiveResolverPolicy: "anyone",+ resolverPolicyProvenance: "inherited",+ effectiveResolverPolicySource: "requested",+ legacyResolverPolicyAliases: { requested: null, effective: null },+ sourceRunId: "run-source",+ resolvedByUserId: "user-1",+ createdAt: "2026-04-21T00:00:01.000Z",+ updatedAt: "2026-04-21T00:00:04.000Z",+ resolvedAt: "2026-04-21T00:00:04.000Z",+ payload: {+ version: 1,+ prompt: "Approve this plan?",+ target: {+ type: "issue_document",+ issueId: "issue-1",+ documentId: "document-plan",+ key: "plan",+ revisionId: "revision-1",+ revisionNumber: 1,+ label: "Plan revision 1",+ },+ },+ result: { outcome: "accepted" },+ },+ ]);+ const activeRun = {+ id: "run-source",+ status: "running",+ invocationSource: "issue",+ triggerDetail: null,+ contextCommentId: null,+ contextWakeCommentId: null,+ startedAt: "2026-04-21T00:00:00.000Z",+ finishedAt: null,+ createdAt: "2026-04-21T00:00:00.000Z",+ agentId: "agent-1",+ agentName: "Coder",+ adapterType,+ issueId: "issue-1",+ };+ mockHeartbeatsApi.activeRunForIssue.mockResolvedValue(activeRun);+ mockHeartbeatsApi.liveRunsForIssue.mockResolvedValue([activeRun]);++ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <IssueDetail />+ </QueryClientProvider>,+ );+ });+ await flushReact();+ await flushReact();++ await waitForAssertion(() => {+ const props = mockIssueChatThreadRender.mock.calls.at(-1)?.[0] as {+ comments?: Array<Record<string, unknown>>;+ };+ expect(+ props.comments?.find(+ (comment) => comment.id === "interaction-response:interaction-plan",+ ),+ ).toMatchObject({+ authorType: "user",+ authorUserId: "user-1",+ body: "Approved plan",+ createdAt: new Date("2026-04-21T00:00:04.000Z"),+ conversationAnchorAt: new Date("2026-04-21T00:00:04.000Z"),+ queueState: "queued",+ queueTargetRunId: "run-source",+ queueReason: "active_run",+ });+ });+ },+ );+it("queues messages against a queued live run and interrupts that exact run", async () => {const postedComment = createDeferred<IssueComment>();- mockIssuesApi.get.mockResolvedValue(createIssue({- status: "in_progress",- executionRunId: "run-queued",- }));+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_progress",+ executionRunId: "run-queued",+ }),+ );mockIssuesApi.addComment.mockReturnValue(postedComment.promise);mockHeartbeatsApi.cancel.mockResolvedValue({});mockHeartbeatsApi.liveRunsForIssue.mockResolvedValue([@@ -1900,7 +2668,9 @@ describe("IssueDetail", () => {}>;onInterruptQueued: (runId: string) => Promise<void>;};- const optimisticComment = queuedProps.comments?.find((comment) => comment.body === "Queued run message");+ const optimisticComment = queuedProps.comments?.find(+ (comment) => comment.body === "Queued run message",+ );expect(optimisticComment).toMatchObject({clientStatus: "queued",queueState: "queued",@@ -1921,14 +2691,18 @@ describe("IssueDetail", () => {}>;onInterruptQueued: (runId: string) => Promise<void>;};- const persistedComment = persistedProps.comments?.find((comment) => comment.body === "Queued run message");+ const persistedComment = persistedProps.comments?.find(+ (comment) => comment.body === "Queued run message",+ );expect(persistedComment).toMatchObject({queueState: "queued",queueTargetRunId: "run-queued",});await act(async () => {- await persistedProps.onInterruptQueued(persistedComment!.queueTargetRunId!);+ await persistedProps.onInterruptQueued(+ persistedComment!.queueTargetRunId!,+ );});expect(mockHeartbeatsApi.cancel).toHaveBeenCalledWith("run-queued");@@ -1937,10 +2711,12 @@ describe("IssueDetail", () => {it("does not rebind a queued message when another run becomes live before its request settles", async () => {const postedComment = createDeferred<IssueComment>();- mockIssuesApi.get.mockResolvedValue(createIssue({- status: "in_progress",- executionRunId: "run-original",- }));+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_progress",+ executionRunId: "run-original",+ }),+ );mockIssuesApi.addComment.mockReturnValue(postedComment.promise);mockHeartbeatsApi.cancel.mockResolvedValue({});mockHeartbeatsApi.liveRunsForIssue.mockResolvedValue([@@ -1996,12 +2772,19 @@ describe("IssueDetail", () => {issueId: "issue-1",};await act(async () => {- queryClient.setQueryData(queryKeys.issues.liveRuns("issue-1"), [replacementRun]);- queryClient.setQueryData(queryKeys.issues.activeRun("issue-1"), replacementRun);+ queryClient.setQueryData(queryKeys.issues.liveRuns("issue-1"), [+ replacementRun,+ ]);+ queryClient.setQueryData(+ queryKeys.issues.activeRun("issue-1"),+ replacementRun,+ );});await flushReact();- const replacementProps = mockIssueChatThreadRender.mock.calls.at(-1)?.[0] as {+ const replacementProps = mockIssueChatThreadRender.mock.calls.at(+ -1,+ )?.[0] as {comments?: Array<{body: string;clientStatus?: string;@@ -2019,13 +2802,19 @@ describe("IssueDetail", () => {});await act(async () => {- await replacementProps.onInterruptQueued(optimisticComment!.queueTargetRunId!);+ await replacementProps.onInterruptQueued(+ optimisticComment!.queueTargetRunId!,+ );});expect(mockHeartbeatsApi.cancel).toHaveBeenCalledWith("run-original");- expect(mockHeartbeatsApi.cancel).not.toHaveBeenCalledWith("run-replacement");+ expect(mockHeartbeatsApi.cancel).not.toHaveBeenCalledWith(+ "run-replacement",+ );await act(async () => {- postedComment.resolve(createIssueComment({ body: "Keep this bound to the original run" }));+ postedComment.resolve(+ createIssueComment({ body: "Keep this bound to the original run" }),+ );});await flushReact();mockHeartbeatsApi.cancel.mockClear();@@ -2033,10 +2822,12 @@ describe("IssueDetail", () => {it("does not optimistically queue a fresh comment from an unlocked stale active-run cache", async () => {const postedComment = createDeferred<IssueComment>();- mockIssuesApi.get.mockResolvedValue(createIssue({- status: "todo",- executionRunId: null,- }));+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "todo",+ executionRunId: null,+ }),+ );mockIssuesApi.addComment.mockReturnValue(postedComment.promise);queryClient.setQueryData(queryKeys.issues.activeRun("PAP-1"), {id: "run-stale",@@ -2066,7 +2857,11 @@ describe("IssueDetail", () => {const props = mockIssueChatThreadRender.mock.calls.at(-1)?.[0] as {onAdd: (body: string) => Promise<void>;- comments?: Array<{ body: string; clientStatus?: string; queueState?: string }>;+ comments?: Array<{+ body: string;+ clientStatus?: string;+ queueState?: string;+ }>;};await act(async () => {void props.onAdd("Fresh comment");@@ -2075,9 +2870,15 @@ describe("IssueDetail", () => {await flushReact();const nextProps = mockIssueChatThreadRender.mock.calls.at(-1)?.[0] as {- comments?: Array<{ body: string; clientStatus?: string; queueState?: string }>;+ comments?: Array<{+ body: string;+ clientStatus?: string;+ queueState?: string;+ }>;};- const optimisticComment = nextProps.comments?.find((comment) => comment.body === "Fresh comment");+ const optimisticComment = nextProps.comments?.find(+ (comment) => comment.body === "Fresh comment",+ );expect(optimisticComment).toMatchObject({ clientStatus: "pending" });expect(optimisticComment?.queueState).toBeUndefined();@@ -2119,7 +2920,9 @@ describe("IssueDetail", () => {await flushReact();await flushReact();- expect(container.querySelector('[aria-label="Open file in this issue"]')).toBeNull();+ expect(+ container.querySelector('[aria-label="Open file in this issue"]'),+ ).toBeNull();});it("shows file viewer entry points when the experimental flag is enabled", async () => {@@ -2140,7 +2943,9 @@ describe("IssueDetail", () => {await flushReact();await flushReact();- expect(container.querySelector('[aria-label="Open file in this issue"]')).not.toBeNull();+ expect(+ container.querySelector('[aria-label="Open file in this issue"]'),+ ).not.toBeNull();});it("hides the properties sidebar on the first onboarding task until a plan document exists", async () => {@@ -2172,7 +2977,69 @@ describe("IssueDetail", () => {expect(mockClosePanel).toHaveBeenCalled();});+ it("starts a planning-mode task as chat-only until its plan document exists", async () => {+ mockSetBreadcrumbToolbar.mockClear();+ mockInstanceSettingsApi.getExperimental.mockResolvedValue({+ enableIssuePlanDecompositions: false,+ enableExperimentalFileViewer: false,+ enableExternalObjects: false,+ });+ mockIssuesApi.get.mockResolvedValue(createIssue({+ originKind: "manual",+ workMode: "planning",+ }));+ mockIssuesApi.getDocument.mockResolvedValue(null);++ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <IssueDetail />+ </QueryClientProvider>,+ );+ });++ await flushReact();+ await flushReact();++ expect(mockOpenPanel).not.toHaveBeenCalled();+ expect(mockClosePanel).toHaveBeenCalled();+ expect(+ container.querySelector('button[aria-label="Toggle side panel"]'),+ ).toBeNull();+ const toolbar = [...mockSetBreadcrumbToolbar.mock.calls]+ .reverse()+ .map(([node]) => node)+ .find((node) => node !== null);+ expect(toolbar).toBeDefined();+ });++ it("reveals the planning-mode task sidebar when its plan document exists", async () => {+ mockInstanceSettingsApi.getExperimental.mockResolvedValue({+ enableIssuePlanDecompositions: false,+ enableExperimentalFileViewer: false,+ enableExternalObjects: false,+ });+ mockIssuesApi.get.mockResolvedValue(createIssue({+ originKind: "manual",+ workMode: "planning",+ }));+ mockIssuesApi.getDocument.mockResolvedValue({ id: "doc-1", key: "plan" });++ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <IssueDetail />+ </QueryClientProvider>,+ );+ });++ await waitForAssertion(() => {+ expect(mockOpenPanel).toHaveBeenCalled();+ });+ });+it("keeps the Show properties button clickable on the first task and reveals the sidebar on demand", async () => {+ mockSetBreadcrumbToolbar.mockClear();mockInstanceSettingsApi.getExperimental.mockResolvedValue({enableIssuePlanDecompositions: false,enableExperimentalFileViewer: false,@@ -2196,16 +3063,18 @@ describe("IssueDetail", () => {await flushReact();expect(mockOpenPanel).not.toHaveBeenCalled();- // Even though panelVisible is true, the suppressed first task keeps the- // opt-in button visible instead of fading it out.- const showPropertiesButton = container.querySelector<HTMLButtonElement>(- 'button[title="Show properties"]',- );- expect(showPropertiesButton).toBeTruthy();- expect(showPropertiesButton!.className).not.toContain("pointer-events-none");+ // Even though panelVisible is true, the suppressed first task registers+ // the persistent top-row opt-in launcher.+ const toolbar = [...mockSetBreadcrumbToolbar.mock.calls]+ .reverse()+ .map(([node]) => node)+ .find((node) => node !== null) as ReactElement<{+ children: ReactElement<{ onToggle: () => void }>;+ }>;+ expect(toolbar).toBeDefined();await act(async () => {- showPropertiesButton!.click();+ toolbar.props.children.props.onToggle();});await flushReact();@@ -2261,19 +3130,21 @@ describe("IssueDetail", () => {});it("passes blocker attention to the issue detail header status icon", async () => {- mockIssuesApi.get.mockResolvedValue(createIssue({- status: "blocked",- blockerAttention: {- state: "covered",- reason: "active_child",- unresolvedBlockerCount: 1,- coveredBlockerCount: 1,- stalledBlockerCount: 0,- attentionBlockerCount: 0,- sampleBlockerIdentifier: "PAP-2",- sampleStalledBlockerIdentifier: null,- },- }));+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "blocked",+ blockerAttention: {+ state: "covered",+ reason: "active_child",+ unresolvedBlockerCount: 1,+ coveredBlockerCount: 1,+ stalledBlockerCount: 0,+ attentionBlockerCount: 0,+ sampleBlockerIdentifier: "PAP-2",+ sampleStalledBlockerIdentifier: null,+ },+ }),+ );await act(async () => {root.render(@@ -2284,7 +3155,10 @@ describe("IssueDetail", () => {});await flushReact();- expect(container.querySelector('[data-status-icon-state="covered"]')?.textContent).toBe("blocked");+ expect(+ container.querySelector('[data-status-icon-state="covered"]')+ ?.textContent,+ ).toBe("blocked");});it("refreshes subtree pause state after resuming a hold", async () => {@@ -2311,7 +3185,10 @@ describe("IssueDetail", () => {isRoot: boolean;mode: "pause";reason: string | null;- releasePolicy: { strategy: "manual" | "after_active_runs_finish"; note?: string | null } | null;+ releasePolicy: {+ strategy: "manual" | "after_active_runs_finish";+ note?: string | null;+ } | null;} = {holdId: "hold-1",rootIssueId: "issue-1",@@ -2323,8 +3200,11 @@ describe("IssueDetail", () => {};mockIssuesApi.get.mockResolvedValue(createIssue());- mockIssuesApi.list.mockImplementation((_companyId, filters?: { descendantOf?: string }) =>- Promise.resolve(filters?.descendantOf === "issue-1" ? [childIssue] : []),+ mockIssuesApi.list.mockImplementation(+ (_companyId, filters?: { descendantOf?: string }) =>+ Promise.resolve(+ filters?.descendantOf === "issue-1" ? [childIssue] : [],+ ),);mockIssuesApi.getTreeControlState.mockImplementation(() =>Promise.resolve({ activePauseHold: activePauseHoldState }),@@ -2355,8 +3235,9 @@ describe("IssueDetail", () => {expect(container.textContent).toContain("Subtree pause is active.");});- const resumeButton = Array.from(container.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Resume subtree");+ const resumeButton = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.trim() === "Resume subtree",+ );expect(resumeButton).toBeTruthy();await act(async () => {@@ -2376,15 +3257,23 @@ describe("IssueDetail", () => {await flushReact();await flushReact();- expect(mockIssuesApi.releaseTreeHold).toHaveBeenCalledWith("PAP-1", "hold-1", {- reason: null,- metadata: { wakeAgents: true },- });- expect(mockIssuesApi.getTreeControlState.mock.calls.length).toBeGreaterThanOrEqual(2);- expect(mockPushToast).toHaveBeenCalledWith(expect.objectContaining({- title: "Subtree resumed",- body: "Ready to continue",- }));+ expect(mockIssuesApi.releaseTreeHold).toHaveBeenCalledWith(+ "PAP-1",+ "hold-1",+ {+ reason: null,+ metadata: { wakeAgents: true },+ },+ );+ expect(+ mockIssuesApi.getTreeControlState.mock.calls.length,+ ).toBeGreaterThanOrEqual(2);+ expect(mockPushToast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Subtree resumed",+ body: "Ready to continue",+ }),+ );await waitForAssertion(() => {expect(container.textContent).not.toContain("Subtree pause is active.");});@@ -2408,11 +3297,17 @@ describe("IssueDetail", () => {});mockIssuesApi.get.mockResolvedValue(createIssue());- mockIssuesApi.list.mockImplementation((_companyId, filters?: { descendantOf?: string }) =>- Promise.resolve(filters?.descendantOf === "issue-1" ? [childIssue] : []),+ mockIssuesApi.list.mockImplementation(+ (_companyId, filters?: { descendantOf?: string }) =>+ Promise.resolve(+ filters?.descendantOf === "issue-1" ? [childIssue] : [],+ ),);mockIssuesApi.previewTreeControl.mockResolvedValue(pausePreview);- mockIssuesApi.createTreeHold.mockResolvedValue({ hold: pauseHold, preview: pausePreview });+ mockIssuesApi.createTreeHold.mockResolvedValue({+ hold: pauseHold,+ preview: pausePreview,+ });mockAuthApi.getSession.mockResolvedValue({session: { userId: "user-1" },user: { id: "user-1" },@@ -2428,16 +3323,21 @@ describe("IssueDetail", () => {await flushReact();await flushReact();- const moreButton = container.querySelector('button[aria-label="More task actions"]') as HTMLButtonElement | null;+ const moreButton = container.querySelector(+ 'button[aria-label="More task actions"]',+ ) as HTMLButtonElement | null;expect(moreButton).toBeTruthy();await act(async () => {- moreButton!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ moreButton!.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true }),+ );});await flushReact();- const pauseMenuButton = Array.from(container.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Pause subtree...");+ const pauseMenuButton = Array.from(+ container.querySelectorAll("button"),+ ).find((button) => button.textContent?.trim() === "Pause subtree...");expect(pauseMenuButton).toBeTruthy();await act(async () => {@@ -2458,8 +3358,9 @@ describe("IssueDetail", () => {expect(container.textContent).toContain("Completed child");expect(container.textContent).toContain("Complete");- const pauseApplyButton = Array.from(container.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Pause and stop work");+ const pauseApplyButton = Array.from(+ container.querySelectorAll("button"),+ ).find((button) => button.textContent?.trim() === "Pause and stop work");expect(pauseApplyButton).toBeTruthy();await act(async () => {@@ -2493,13 +3394,18 @@ describe("IssueDetail", () => {members: [],});- mockIssuesApi.get.mockResolvedValue(createIssue({- status: "in_progress",- assigneeAgentId: "agent-1",- executionRunId: "run-active-1",- }));+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_progress",+ assigneeAgentId: "agent-1",+ executionRunId: "run-active-1",+ }),+ );mockIssuesApi.previewTreeControl.mockResolvedValue(pausePreview);- mockIssuesApi.createTreeHold.mockResolvedValue({ hold: pauseHold, preview: pausePreview });+ mockIssuesApi.createTreeHold.mockResolvedValue({+ hold: pauseHold,+ preview: pausePreview,+ });mockAgentsApi.list.mockResolvedValue([createAgent()]);mockAuthApi.getSession.mockResolvedValue({session: { userId: "user-1" },@@ -2522,8 +3428,9 @@ describe("IssueDetail", () => {issueWorkMode: "standard",});- const chatPauseButton = Array.from(container.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Pause work");+ const chatPauseButton = Array.from(+ container.querySelectorAll("button"),+ ).find((button) => button.textContent?.trim() === "Pause work");expect(chatPauseButton).toBeTruthy();await act(async () => {@@ -2538,29 +3445,38 @@ describe("IssueDetail", () => {metadata: { source: "issue_active_run_control", runId: "run-active-1" },});- const moreButton = container.querySelector('button[aria-label="More task actions"]') as HTMLButtonElement | null;+ const moreButton = container.querySelector(+ 'button[aria-label="More task actions"]',+ ) as HTMLButtonElement | null;expect(moreButton).toBeTruthy();await act(async () => {- moreButton!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ moreButton!.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true }),+ );});await flushReact();- const pauseMenuButton = Array.from(container.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Pause work...");+ const pauseMenuButton = Array.from(+ container.querySelectorAll("button"),+ ).find((button) => button.textContent?.trim() === "Pause work...");expect(pauseMenuButton).toBeTruthy();});it("routes live-run finalization actions through run cancellation before issue status update", async () => {- mockIssuesApi.get.mockResolvedValue(createIssue({- status: "in_progress",- assigneeAgentId: "agent-1",- executionRunId: "run-active-1",- }));- mockIssuesApi.update.mockImplementation((_id, data) =>- Promise.resolve(createIssue({- status: data.status as Issue["status"],+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_progress",assigneeAgentId: "agent-1",- })),+ executionRunId: "run-active-1",+ }),+ );+ mockIssuesApi.update.mockImplementation((_id, data) =>+ Promise.resolve(+ createIssue({+ status: data.status as Issue["status"],+ assigneeAgentId: "agent-1",+ }),+ ),);mockHeartbeatsApi.cancel.mockResolvedValue(undefined);mockAgentsApi.list.mockResolvedValue([createAgent()]);@@ -2578,8 +3494,9 @@ describe("IssueDetail", () => {});await flushReact();- const stopAndDoneButton = Array.from(container.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Stop and done");+ const stopAndDoneButton = Array.from(+ container.querySelectorAll("button"),+ ).find((button) => button.textContent?.trim() === "Stop and done");expect(stopAndDoneButton).toBeTruthy();await act(async () => {@@ -2588,12 +3505,16 @@ describe("IssueDetail", () => {await flushReact();expect(mockHeartbeatsApi.cancel).toHaveBeenCalledWith("run-active-1");- expect(mockIssuesApi.update).toHaveBeenCalledWith("PAP-1", { status: "done" });- expect(mockHeartbeatsApi.cancel.mock.invocationCallOrder[0])- .toBeLessThan(mockIssuesApi.update.mock.invocationCallOrder[0]);+ expect(mockIssuesApi.update).toHaveBeenCalledWith("PAP-1", {+ status: "done",+ });+ expect(mockHeartbeatsApi.cancel.mock.invocationCallOrder[0]).toBeLessThan(+ mockIssuesApi.update.mock.invocationCallOrder[0],+ );- const stopAndCancelButton = Array.from(container.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Stop and cancel");+ const stopAndCancelButton = Array.from(+ container.querySelectorAll("button"),+ ).find((button) => button.textContent?.trim() === "Stop and cancel");expect(stopAndCancelButton).toBeTruthy();await act(async () => {@@ -2601,18 +3522,23 @@ describe("IssueDetail", () => {});await flushReact();- expect(mockIssuesApi.update).toHaveBeenLastCalledWith("PAP-1", { status: "cancelled" });+ expect(mockIssuesApi.update).toHaveBeenLastCalledWith("PAP-1", {+ status: "cancelled",+ });expect(mockHeartbeatsApi.cancel).toHaveBeenCalledTimes(2);- expect(mockHeartbeatsApi.cancel.mock.invocationCallOrder[1])- .toBeLessThan(mockIssuesApi.update.mock.invocationCallOrder[1]);+ expect(mockHeartbeatsApi.cancel.mock.invocationCallOrder[1]).toBeLessThan(+ mockIssuesApi.update.mock.invocationCallOrder[1],+ );});it("reports partial success when run finalization stops the run but task status update fails", async () => {- mockIssuesApi.get.mockResolvedValue(createIssue({- status: "in_progress",- assigneeAgentId: "agent-1",- executionRunId: "run-active-1",- }));+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_progress",+ assigneeAgentId: "agent-1",+ executionRunId: "run-active-1",+ }),+ );mockIssuesApi.update.mockRejectedValue(new Error("Status write failed"));mockHeartbeatsApi.cancel.mockResolvedValue(undefined);mockAgentsApi.list.mockResolvedValue([createAgent()]);@@ -2630,8 +3556,9 @@ describe("IssueDetail", () => {});await flushReact();- const stopAndDoneButton = Array.from(container.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Stop and done");+ const stopAndDoneButton = Array.from(+ container.querySelectorAll("button"),+ ).find((button) => button.textContent?.trim() === "Stop and done");expect(stopAndDoneButton).toBeTruthy();await act(async () => {@@ -2640,11 +3567,13 @@ describe("IssueDetail", () => {await flushReact();expect(mockHeartbeatsApi.cancel).toHaveBeenCalledWith("run-active-1");- expect(mockPushToast).toHaveBeenCalledWith(expect.objectContaining({- title: "Run stopped; task update failed",- body: "Run was stopped, but updating the task failed: Status write failed",- tone: "error",- }));+ expect(mockPushToast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Run stopped; task update failed",+ body: "Run was stopped, but updating the task failed: Status write failed",+ tone: "error",+ }),+ );});it("passes planning work mode to the issue chat thread", async () => {@@ -2684,9 +3613,18 @@ describe("IssueDetail", () => {throw new Error("Clipboard API blocked");});const execCommand = vi.fn(() => true);- const originalClipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard");- const originalExecCommand = Object.getOwnPropertyDescriptor(document, "execCommand");- const originalSecureContext = Object.getOwnPropertyDescriptor(window, "isSecureContext");+ const originalClipboard = Object.getOwnPropertyDescriptor(+ navigator,+ "clipboard",+ );+ const originalExecCommand = Object.getOwnPropertyDescriptor(+ document,+ "execCommand",+ );+ const originalSecureContext = Object.getOwnPropertyDescriptor(+ window,+ "isSecureContext",+ );Object.defineProperty(window, "isSecureContext", {configurable: true,value: false,@@ -2699,11 +3637,13 @@ describe("IssueDetail", () => {configurable: true,value: execCommand,});- mockIssuesApi.get.mockResolvedValue(createIssue({- identifier: "PAP-1",- title: "Copy me",- description: "Task body",- }));+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ identifier: "PAP-1",+ title: "Copy me",+ description: "Task body",+ }),+ );try {await act(async () => {@@ -2715,8 +3655,9 @@ describe("IssueDetail", () => {});await flushReact();- const copyButton = Array.from(container.querySelectorAll("button"))- .find((button) => button.getAttribute("title") === "Copy task as markdown");+ const copyButton = Array.from(container.querySelectorAll("button")).find(+ (button) => button.getAttribute("title") === "Copy task as markdown",+ );expect(copyButton).toBeTruthy();await act(async () => {@@ -2726,10 +3667,12 @@ describe("IssueDetail", () => {expect(clipboardWrite).not.toHaveBeenCalled();expect(execCommand).toHaveBeenCalledWith("copy");- expect(mockPushToast).toHaveBeenCalledWith(expect.objectContaining({- title: "Copied to clipboard",- tone: "success",- }));+ expect(mockPushToast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Copied to clipboard",+ tone: "success",+ }),+ );} finally {if (originalClipboard) {Object.defineProperty(navigator, "clipboard", originalClipboard);@@ -2764,7 +3707,9 @@ describe("IssueDetail", () => {});await flushReact();- expect(container.querySelector('[data-testid="task-chat-thread"]')).not.toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-thread"]'),+ ).not.toBeNull();expect(mockIssueChatThreadRender).toHaveBeenCalled();});@@ -2776,6 +3721,35 @@ describe("IssueDetail", () => {enableClassicTaskInterface: true,});mockIssuesApi.get.mockResolvedValue(createIssue());+ mockIssuesApi.listInteractions.mockResolvedValue([+ {+ id: "classic-question",+ companyId: "company-1",+ issueId: "issue-1",+ kind: "ask_user_questions",+ status: "answered",+ sourceRunId: "legacy-run",+ resolvedByUserId: "user-1",+ resolvedAt: "2026-04-21T00:00:04.000Z",+ createdAt: "2026-04-21T00:00:01.000Z",+ updatedAt: "2026-04-21T00:00:04.000Z",+ payload: {+ version: 1,+ questions: [+ {+ id: "runtime",+ prompt: "Which runtime?",+ selectionMode: "single",+ options: [{ id: "node", label: "Node.js" }],+ },+ ],+ },+ result: {+ version: 1,+ answers: [{ questionId: "runtime", optionIds: ["node"] }],+ },+ },+ ]);await act(async () => {root.render(@@ -2787,9 +3761,21 @@ describe("IssueDetail", () => {await flushReact();await flushReact();- expect(container.querySelector('[data-testid="issue-chat-thread"]')).not.toBeNull();- expect(container.querySelector('[data-testid="task-chat-thread"]')).toBeNull();+ expect(+ container.querySelector('[data-testid="issue-chat-thread"]'),+ ).not.toBeNull();+ expect(+ container.querySelector('[data-testid="task-chat-thread"]'),+ ).toBeNull();expect(mockIssueChatThreadRender).toHaveBeenCalled();+ const classicProps = mockIssueChatThreadRender.mock.calls.at(-1)?.[0] as {+ comments?: Array<{ id: string }>;+ };+ expect(+ classicProps.comments?.some(+ (comment) => comment.id === "interaction-response:classic-question",+ ),+ ).toBe(false);});it("passes @task mention options to the thread by default", async () => {@@ -2801,7 +3787,9 @@ describe("IssueDetail", () => {};mockIssuesApi.list.mockImplementation((_companyId: string, filters?: { sortField?: string }) =>- Promise.resolve(filters?.sortField === "updated" ? [mentionPoolIssue] : []),+ Promise.resolve(+ filters?.sortField === "updated" ? [mentionPoolIssue] : [],+ ),);mockIssuesApi.get.mockResolvedValue(createIssue());@@ -2817,7 +3805,9 @@ describe("IssueDetail", () => {await waitForAssertion(() => {expect(mockIssueChatThreadRender.mock.calls.at(-1)?.[0].mentions).toEqual(- expect.arrayContaining([expect.objectContaining({ kind: "issue", issueIdentifier: "PAP-9" })]),+ expect.arrayContaining([+ expect.objectContaining({ kind: "issue", issueIdentifier: "PAP-9" }),+ ]),);});expect(mockIssuesApi.list).toHaveBeenCalledWith(@@ -2842,8 +3832,13 @@ describe("IssueDetail", () => {uploadedAt: new Date("2026-04-21T00:02:00.000Z"),},]);- localStorage.setItem("paperclip:issue-comment-draft:issue-1", "Draft follow-up message");- mockIssuesApi.update.mockResolvedValue(createIssue({ workMode: "planning" }));+ localStorage.setItem(+ "paperclip:issue-comment-draft:issue-1",+ "Draft follow-up message",+ );+ mockIssuesApi.update.mockResolvedValue(+ createIssue({ workMode: "planning" }),+ );await act(async () => {root.render(@@ -2855,7 +3850,8 @@ describe("IssueDetail", () => {await flushReact();await flushReact();- const lastChatThreadProps = mockIssueChatThreadRender.mock.calls.at(-1)?.[0];+ const lastChatThreadProps =+ mockIssueChatThreadRender.mock.calls.at(-1)?.[0];expect(lastChatThreadProps?.issueWorkMode).toBe("standard");expect(typeof lastChatThreadProps?.onWorkModeChange).toBe("function");@@ -2864,8 +3860,12 @@ describe("IssueDetail", () => {});await flushReact();- expect(mockIssuesApi.update).toHaveBeenCalledWith(issue.identifier, { workMode: "ask" });- expect(localStorage.getItem("paperclip:issue-comment-draft:issue-1")).toBe("Draft follow-up message");+ expect(mockIssuesApi.update).toHaveBeenCalledWith(issue.identifier, {+ workMode: "ask",+ });+ expect(localStorage.getItem("paperclip:issue-comment-draft:issue-1")).toBe(+ "Draft follow-up message",+ );localStorage.removeItem("paperclip:issue-comment-draft:issue-1");});@@ -2880,10 +3880,12 @@ describe("IssueDetail", () => {updatedAt: new Date("2026-04-21T00:01:00.000Z"),});- mockIssuesApi.get.mockResolvedValue(createIssue({- status: "in_review",- assigneeAgentId: "agent-1",- }));+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_review",+ assigneeAgentId: "agent-1",+ }),+ );mockIssuesApi.getTreeControlState.mockResolvedValue({activePauseHold: {holdId: "hold-1",@@ -2920,8 +3922,9 @@ describe("IssueDetail", () => {expect(container.textContent).not.toContain("Subtree pause is active.");});- const resumeButton = Array.from(container.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Resume work");+ const resumeButton = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.trim() === "Resume work",+ );expect(resumeButton).toBeTruthy();await act(async () => {@@ -2930,7 +3933,9 @@ describe("IssueDetail", () => {await flushReact();await flushReact();- const wakeCheckbox = container.querySelector('input[type="checkbox"]') as HTMLInputElement | null;+ const wakeCheckbox = container.querySelector(+ 'input[type="checkbox"]',+ ) as HTMLInputElement | null;expect(wakeCheckbox?.checked).toBe(true);const applyResumeButton = Array.from(container.querySelectorAll("button"))@@ -2943,10 +3948,14 @@ describe("IssueDetail", () => {});await flushReact();- expect(mockIssuesApi.releaseTreeHold).toHaveBeenCalledWith("PAP-1", "hold-1", {- reason: null,- metadata: { wakeAgents: true },- });+ expect(mockIssuesApi.releaseTreeHold).toHaveBeenCalledWith(+ "PAP-1",+ "hold-1",+ {+ reason: null,+ metadata: { wakeAgents: true },+ },+ );});it("exposes restore subtree from the issue actions menu", async () => {@@ -2977,14 +3986,21 @@ describe("IssueDetail", () => {});mockIssuesApi.get.mockResolvedValue(createIssue());- mockIssuesApi.list.mockImplementation((_companyId, filters?: { descendantOf?: string }) =>- Promise.resolve(filters?.descendantOf === "issue-1" ? [childIssue] : []),+ mockIssuesApi.list.mockImplementation(+ (_companyId, filters?: { descendantOf?: string }) =>+ Promise.resolve(+ filters?.descendantOf === "issue-1" ? [childIssue] : [],+ ),);- mockIssuesApi.listTreeHolds.mockImplementation((_issueId, filters?: { mode?: string }) =>- Promise.resolve(filters?.mode === "cancel" ? [cancelHold] : []),+ mockIssuesApi.listTreeHolds.mockImplementation(+ (_issueId, filters?: { mode?: string }) =>+ Promise.resolve(filters?.mode === "cancel" ? [cancelHold] : []),);mockIssuesApi.previewTreeControl.mockResolvedValue(restorePreview);- mockIssuesApi.createTreeHold.mockResolvedValue({ hold: restoreHold, preview: restorePreview });+ mockIssuesApi.createTreeHold.mockResolvedValue({+ hold: restoreHold,+ preview: restorePreview,+ });mockAuthApi.getSession.mockResolvedValue({session: { userId: "user-1" },user: { id: "user-1" },@@ -3000,16 +4016,21 @@ describe("IssueDetail", () => {await flushReact();await flushReact();- const moreButton = container.querySelector('button[aria-label="More task actions"]') as HTMLButtonElement | null;+ const moreButton = container.querySelector(+ 'button[aria-label="More task actions"]',+ ) as HTMLButtonElement | null;expect(moreButton).toBeTruthy();await act(async () => {- moreButton!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ moreButton!.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true }),+ );});await flushReact();- const restoreMenuButton = Array.from(container.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Restore subtree...");+ const restoreMenuButton = Array.from(+ container.querySelectorAll("button"),+ ).find((button) => button.textContent?.trim() === "Restore subtree...");expect(restoreMenuButton).toBeTruthy();await act(async () => {@@ -3022,11 +4043,14 @@ describe("IssueDetail", () => {mode: "restore",releasePolicy: { strategy: "manual" },});- expect(container.textContent).toContain("Restore tasks cancelled by this subtree operation so work can resume.");+ expect(container.textContent).toContain(+ "Restore tasks cancelled by this subtree operation so work can resume.",+ );expect(container.textContent).toContain("Cancelled child");- const restoreApplyButton = Array.from(container.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Restore 1 tasks");+ const restoreApplyButton = Array.from(+ container.querySelectorAll("button"),+ ).find((button) => button.textContent?.trim() === "Restore 1 tasks");expect(restoreApplyButton).toBeTruthy();await act(async () => {@@ -3052,8 +4076,11 @@ describe("IssueDetail", () => {});mockIssuesApi.get.mockResolvedValue(createIssue());- mockIssuesApi.list.mockImplementation((_companyId, filters?: { descendantOf?: string }) =>- Promise.resolve(filters?.descendantOf === "issue-1" ? [childIssue] : []),+ mockIssuesApi.list.mockImplementation(+ (_companyId, filters?: { descendantOf?: string }) =>+ Promise.resolve(+ filters?.descendantOf === "issue-1" ? [childIssue] : [],+ ),);mockIssuesApi.previewTreeControl.mockResolvedValue(createCancelPreview(24));mockAuthApi.getSession.mockResolvedValue({@@ -3071,8 +4098,9 @@ describe("IssueDetail", () => {await flushReact();await flushReact();- const cancelMenuButton = Array.from(container.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Cancel subtree...");+ const cancelMenuButton = Array.from(+ container.querySelectorAll("button"),+ ).find((button) => button.textContent?.trim() === "Cancel subtree...");expect(cancelMenuButton).toBeTruthy();await act(async () => {@@ -3086,27 +4114,35 @@ describe("IssueDetail", () => {releasePolicy: { strategy: "manual" },});- const dialogContent = container.querySelector('[data-slot="dialog-content"]') as HTMLDivElement | null;+ const dialogContent = container.querySelector(+ '[data-slot="dialog-content"]',+ ) as HTMLDivElement | null;expect(dialogContent).toBeTruthy();expect(dialogContent!.className).toContain("max-h-(--sz-calc-18)");expect(dialogContent!.className).toContain("overflow-hidden");expect(dialogContent!.className).toContain("flex-col");- const bodyScrollRegion = Array.from(dialogContent!.querySelectorAll("div"))- .find((element) =>- typeof element.className === "string"- && element.className.includes("overflow-y-auto")- && element.textContent?.includes("Reason (optional)"),- );+ const bodyScrollRegion = Array.from(+ dialogContent!.querySelectorAll("div"),+ ).find(+ (element) =>+ typeof element.className === "string" &&+ element.className.includes("overflow-y-auto") &&+ element.textContent?.includes("Reason (optional)"),+ );expect(bodyScrollRegion?.className).toContain("min-h-0");expect(bodyScrollRegion?.className).toContain("overscroll-contain");- const cancelApplyButton = Array.from(dialogContent!.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Cancel 24 tasks") as HTMLButtonElement | undefined;+ const cancelApplyButton = Array.from(+ dialogContent!.querySelectorAll("button"),+ ).find((button) => button.textContent?.trim() === "Cancel 24 tasks") as+ HTMLButtonElement | undefined;expect(cancelApplyButton).toBeTruthy();expect(cancelApplyButton!.disabled).toBe(true);- const confirmationCheckbox = dialogContent!.querySelector('input[type="checkbox"]') as HTMLInputElement | null;+ const confirmationCheckbox = dialogContent!.querySelector(+ 'input[type="checkbox"]',+ ) as HTMLInputElement | null;expect(confirmationCheckbox).toBeTruthy();await act(async () => {confirmationCheckbox!.click();@@ -3114,14 +4150,319 @@ describe("IssueDetail", () => {await flushReact();expect(cancelApplyButton!.disabled).toBe(false);- const footer = Array.from(dialogContent!.querySelectorAll("div"))- .find((element) =>- typeof element.className === "string"- && element.className.includes("border-t")- && element.textContent?.includes("Close"),- );+ const footer = Array.from(dialogContent!.querySelectorAll("div")).find(+ (element) =>+ typeof element.className === "string" &&+ element.className.includes("border-t") &&+ element.textContent?.includes("Close"),+ );expect(footer?.className).toContain("bg-background");});++ it("keeps the authoritative Paperclip queue mounted after handoff promotion", async () => {+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_progress",+ assigneeAgentId: "agent-1",+ executionRunId: "run-promoted-1",+ }),+ );+ mockAgentsApi.list.mockResolvedValue([+ createAgent({ adapterType: "paperclip_runner" }),+ ]);+ mockIssuesApi.getQueuedComments.mockResolvedValue(+ createQueuedCommentQueue({+ state: "queued",+ targetRunId: null,+ }),+ );++ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <IssueDetail />+ </QueryClientProvider>,+ );+ });+ await waitForAssertion(() => {+ const props = mockIssueChatThreadRender.mock.calls.at(-1)?.[0] as+ | {+ queuedCommentQueue?: IssueQueuedCommentQueue | null;+ }+ | undefined;+ expect(mockIssuesApi.getQueuedComments).toHaveBeenCalledWith("issue-1");+ expect(props?.queuedCommentQueue).toMatchObject({+ queueId: "wake-queue-1",+ state: "queued",+ targetRunId: null,+ });+ });+ });++ it.each(DIRECT_ADAPTER_TYPES)(+ "does not load runner controls for an active %s run after reassignment",+ async (adapterType) => {+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_progress",+ assigneeAgentId: "agent-1",+ executionRunId: "run-direct-1",+ }),+ );+ mockAgentsApi.list.mockResolvedValue([+ createAgent({ adapterType: "paperclip_runner" }),+ ]);+ const directRun = {+ id: "run-direct-1",+ runtimeMode: "legacy" as const,+ status: "running",+ invocationSource: "issue",+ triggerDetail: null,+ contextCommentId: null,+ contextWakeCommentId: null,+ startedAt: "2026-04-21T00:00:00.000Z",+ finishedAt: null,+ createdAt: "2026-04-21T00:00:00.000Z",+ agentId: "agent-1",+ agentName: "Coder",+ adapterType,+ issueId: "issue-1",+ };+ mockHeartbeatsApi.activeRunForIssue.mockResolvedValue(directRun);+ mockHeartbeatsApi.liveRunsForIssue.mockResolvedValue([directRun]);+ mockIssuesApi.getQueuedComments.mockClear();++ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <IssueDetail />+ </QueryClientProvider>,+ );+ });+ await flushReact();+ await flushReact();++ expect(mockIssuesApi.getQueuedComments).not.toHaveBeenCalled();+ const props = mockIssueChatThreadRender.mock.calls.at(-1)?.[0] as {+ queuedCommentQueue?: IssueQueuedCommentQueue | null;+ runFinalizationActions?: readonly { id: string; label: string }[];+ };+ expect(props.queuedCommentQueue).toBeNull();+ expect(props.runFinalizationActions).toEqual([+ expect.objectContaining({ id: "cancel", label: "Stop and cancel" }),+ expect.objectContaining({ id: "done", label: "Stop and done" }),+ ]);+ },+ );++ it("keeps a steered message queued until its durable timeline position refreshes", async () => {+ const queue = createQueuedCommentQueue();+ const steeredQueue = createQueuedCommentQueue({+ entries: [],+ revision: "queue-revision-2",+ });+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_progress",+ assigneeAgentId: "agent-1",+ executionRunId: "run-active-1",+ }),+ );+ mockAgentsApi.list.mockResolvedValue([+ createAgent({ adapterType: "paperclip_runner" }),+ ]);+ mockIssuesApi.listComments.mockResolvedValue([queue.entries[0].comment]);+ mockIssuesApi.getQueuedComments.mockResolvedValue(queue);+ mockHeartbeatsApi.activeRunForIssue.mockResolvedValue({+ id: "run-active-1",+ runtimeMode: "native",+ status: "running",+ invocationSource: "issue",+ triggerDetail: null,+ contextCommentId: null,+ contextWakeCommentId: null,+ startedAt: "2026-04-21T00:00:00.000Z",+ finishedAt: null,+ createdAt: "2026-04-21T00:00:00.000Z",+ agentId: "agent-1",+ agentName: "Runner",+ adapterType: "paperclip_runner",+ issueId: "issue-1",+ });+ mockIssuesApi.steerQueuedComment.mockResolvedValue(steeredQueue);++ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <IssueDetail />+ </QueryClientProvider>,+ );+ });++ let steer!: (commentId: string, revision: string) => Promise<void>;+ await waitForAssertion(() => {+ const props = mockIssueChatThreadRender.mock.calls.at(-1)?.[0] as {+ onSteerQueuedComment?: typeof steer;+ queuedCommentQueue?: IssueQueuedCommentQueue | null;+ };+ expect(props.queuedCommentQueue?.entries).toHaveLength(1);+ expect(props.onSteerQueuedComment).toBeTypeOf("function");+ steer = props.onSteerQueuedComment!;+ });++ let releaseActivity!: (value: unknown[]) => void;+ const activityRefresh = new Promise<unknown[]>((resolve) => {+ releaseActivity = resolve;+ });+ mockActivityApi.forIssue.mockReturnValue(activityRefresh);++ let steeringPromise!: Promise<void>;+ await act(async () => {+ steeringPromise = steer("queued-comment-1", queue.revision);+ await Promise.resolve();+ });+ await waitForAssertion(() => {+ expect(mockIssuesApi.steerQueuedComment).toHaveBeenCalled();+ expect(mockActivityApi.forIssue.mock.calls.length).toBeGreaterThan(1);+ });++ const whileRefreshing = mockIssueChatThreadRender.mock.calls.at(+ -1,+ )?.[0] as {+ queuedCommentQueue?: IssueQueuedCommentQueue | null;+ };+ expect(whileRefreshing.queuedCommentQueue?.entries).toHaveLength(1);++ releaseActivity([+ {+ id: "activity-steer-1",+ companyId: "company-1",+ issueId: "issue-1",+ action: "issue.queued_comment_steered",+ createdAt: new Date("2026-04-21T00:00:06.000Z"),+ details: {+ commentId: "queued-comment-1",+ targetRunId: "run-active-1",+ duplicate: false,+ },+ },+ ]);+ await act(async () => {+ await steeringPromise;+ });++ await waitForAssertion(() => {+ const props = mockIssueChatThreadRender.mock.calls.at(-1)?.[0] as {+ comments?: Array<{+ id: string;+ steeredIntoRunId?: string | null;+ conversationAnchorAt?: Date | string | null;+ }>;+ queuedCommentQueue?: IssueQueuedCommentQueue | null;+ };+ expect(props.queuedCommentQueue?.entries).toHaveLength(0);+ expect(+ props.comments?.find((comment) => comment.id === "queued-comment-1"),+ ).toMatchObject({+ steeredIntoRunId: "run-active-1",+ conversationAnchorAt: "2026-04-21T00:00:06.000Z",+ });+ });+ });++ it("withholds destructive queue controls until the server supplies a queue id", async () => {+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_progress",+ assigneeAgentId: "agent-1",+ }),+ );+ mockAgentsApi.list.mockResolvedValue([+ createAgent({ adapterType: "paperclip_runner" }),+ ]);+ mockIssuesApi.getQueuedComments.mockResolvedValue(+ createQueuedCommentQueue({+ queueId: null,+ state: null,+ }),+ );++ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <IssueDetail />+ </QueryClientProvider>,+ );+ });+ await waitForAssertion(() => {+ const props = mockIssueChatThreadRender.mock.calls.at(-1)?.[0] as+ | {+ queuedCommentQueue?: IssueQueuedCommentQueue | null;+ }+ | undefined;+ expect(mockIssuesApi.getQueuedComments).toHaveBeenCalled();+ expect(props?.queuedCommentQueue).toBeNull();+ });+ });++ it("uses queue identity for discard and surfaces a persistent too-late error", async () => {+ const queue = createQueuedCommentQueue();+ mockIssuesApi.get.mockResolvedValue(+ createIssue({+ status: "in_progress",+ assigneeAgentId: "agent-1",+ executionRunId: "run-active-1",+ }),+ );+ mockAgentsApi.list.mockResolvedValue([+ createAgent({ adapterType: "paperclip_runner" }),+ ]);+ mockIssuesApi.getQueuedComments.mockResolvedValue(queue);+ mockIssuesApi.discardQueuedComment.mockRejectedValue(+ new ApiError("The queued message is already being dispatched", 409, {+ details: { code: "queued_comment_already_dispatching" },+ }),+ );++ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <IssueDetail />+ </QueryClientProvider>,+ );+ });+ let discard!: (commentId: string, revision: string) => Promise<void>;+ await waitForAssertion(() => {+ const props = mockIssueChatThreadRender.mock.calls.at(-1)?.[0] as+ | {+ onDiscardQueuedComment?: typeof discard;+ queuedCommentQueue?: IssueQueuedCommentQueue | null;+ }+ | undefined;+ expect(props?.onDiscardQueuedComment).toBeTypeOf("function");+ expect(props?.queuedCommentQueue?.queueId).toBe("wake-queue-1");+ discard = props!.onDiscardQueuedComment!;+ });++ await expect(discard("queued-comment-1", queue.revision)).rejects.toThrow(+ "already being dispatched",+ );+ expect(mockIssuesApi.discardQueuedComment).toHaveBeenCalledWith(+ "issue-1",+ "queued-comment-1",+ {+ queueId: "wake-queue-1",+ revision: "queue-revision-1",+ },+ );+ expect(mockPushToast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Message is already being sent",+ tone: "error",+ ttlMs: 15_000,+ }),+ );+ });});describe("canBoardResolveRecoveryAction", () => {@@ -3217,8 +4558,13 @@ describe("canBoardManageRuntime", () => {});describe("readRecoveryReconcileWorkspaceId", () => {- const makeAction = (evidence: Record<string, unknown>, kind = "workspace_validation") =>- ({ kind, evidence } as unknown as Parameters<typeof readRecoveryReconcileWorkspaceId>[0]);+ const makeAction = (+ evidence: Record<string, unknown>,+ kind = "workspace_validation",+ ) =>+ ({ kind, evidence }) as unknown as Parameters<+ typeof readRecoveryReconcileWorkspaceId+ >[0];it("returns null when the action is missing", () => {expect(readRecoveryReconcileWorkspaceId(null)).toBeNull();@@ -3267,7 +4613,9 @@ describe("readRecoveryReconcileWorkspaceId", () => {expect(readRecoveryReconcileWorkspaceId(makeAction({}))).toBeNull();expect(readRecoveryReconcileWorkspaceId(- makeAction({ workspaceValidation: { reason: "git_worktree_branch_incoherence" } }),+ makeAction({+ workspaceValidation: { reason: "git_worktree_branch_incoherence" },+ }),),).toBeNull();});@@ -3275,12 +4623,16 @@ describe("readRecoveryReconcileWorkspaceId", () => {it("ignores non-string / empty workspace ids", () => {expect(readRecoveryReconcileWorkspaceId(- makeAction({ workspaceValidation: { persistedExecutionWorkspaceId: "" } }),+ makeAction({+ workspaceValidation: { persistedExecutionWorkspaceId: "" },+ }),),).toBeNull();expect(readRecoveryReconcileWorkspaceId(- makeAction({ workspaceValidation: { persistedExecutionWorkspaceId: 42 } }),+ makeAction({+ workspaceValidation: { persistedExecutionWorkspaceId: 42 },+ }),),).toBeNull();});@@ -3288,26 +4640,32 @@ describe("readRecoveryReconcileWorkspaceId", () => {describe("shouldScrollIssueDetailToTopOnNavigation", () => {it("does not scroll when only URL search params changed for the same issue", () => {- expect(shouldScrollIssueDetailToTopOnNavigation({- previousIssueId: "PAP-10306",- nextIssueId: "PAP-10306",- navigationType: NavigationType.Push,- })).toBe(false);+ expect(+ shouldScrollIssueDetailToTopOnNavigation({+ previousIssueId: "PAP-10306",+ nextIssueId: "PAP-10306",+ navigationType: NavigationType.Push,+ }),+ ).toBe(false);});it("scrolls on forward navigation to a different issue", () => {- expect(shouldScrollIssueDetailToTopOnNavigation({- previousIssueId: "PAP-1",- nextIssueId: "PAP-2",- navigationType: NavigationType.Push,- })).toBe(true);+ expect(+ shouldScrollIssueDetailToTopOnNavigation({+ previousIssueId: "PAP-1",+ nextIssueId: "PAP-2",+ navigationType: NavigationType.Push,+ }),+ ).toBe(true);});it("does not scroll on browser back or forward restoration", () => {- expect(shouldScrollIssueDetailToTopOnNavigation({- previousIssueId: "PAP-1",- nextIssueId: "PAP-2",- navigationType: NavigationType.Pop,- })).toBe(false);+ expect(+ shouldScrollIssueDetailToTopOnNavigation({+ previousIssueId: "PAP-1",+ nextIssueId: "PAP-2",+ navigationType: NavigationType.Pop,+ }),+ ).toBe(false);});});diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsxindex fcc4afa846..df0c15c31c 100644--- a/ui/src/pages/IssueDetail.tsx+++ b/ui/src/pages/IssueDetail.tsx@@ -1,13 +1,45 @@-import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ChangeEvent, type DragEvent, type ReactNode, type Ref } from "react";+import {+ memo,+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+ type ChangeEvent,+ type DragEvent,+ type ReactNode,+ type Ref,+} from "react";import { pickTextColorForPillBg } from "@/lib/color-contrast";-import { Link, useLocation, useNavigate, useNavigationType, useParams } from "@/lib/router";-import { useInfiniteQuery, useQuery, useMutation, useQueryClient, type InfiniteData, type QueryClient } from "@tanstack/react-query";-import { usePublishSharedQueryData, useSharedPollingQuery } from "@/hooks/useSharedPolling";+import {+ Link,+ useLocation,+ useNavigate,+ useNavigationType,+ useParams,+} from "@/lib/router";+import {+ useInfiniteQuery,+ useQuery,+ useMutation,+ useQueryClient,+ type InfiniteData,+ type QueryClient,+} from "@tanstack/react-query";+import {+ usePublishSharedQueryData,+ useSharedPollingQuery,+} from "@/hooks/useSharedPolling";import { ApiError } from "../api/client";import { issuesApi } from "../api/issues";import { approvalsApi } from "../api/approvals";import { activityApi, type RunForIssue } from "../api/activity";-import { heartbeatsApi, type ActiveRunForIssue, type LiveRunForIssue } from "../api/heartbeats";+import {+ heartbeatsApi,+ type ActiveRunForIssue,+ type LiveRunForIssue,+} from "../api/heartbeats";import { instanceSettingsApi } from "../api/instanceSettings";import { accessApi, type CurrentBoardAccess } from "../api/access";import {@@ -24,11 +56,26 @@ import { usePanel } from "../context/PanelContext";import { useSidebar } from "../context/SidebarContext";import { useToastActions } from "../context/ToastContext";import { useBreadcrumbs } from "../context/BreadcrumbContext";-import { assigneeValueFromSelection, formatAssigneeUserLabel, formatUserLabel, suggestedCommentAssigneeValue } from "../lib/assignees";-import { buildCompanyUserInlineOptions, buildCompanyUserLabelMap, buildCompanyUserProfileMap, buildMarkdownMentionOptions, isAgentTaskTarget } from "../lib/company-members";-import { extractIssueTimelineEvents, extractIssueWorkModeChanges } from "../lib/issue-timeline-events";+import {+ assigneeValueFromSelection,+ formatAssigneeUserLabel,+ formatUserLabel,+ suggestedCommentAssigneeValue,+} from "../lib/assignees";+import {+ buildCompanyUserInlineOptions,+ buildCompanyUserLabelMap,+ buildCompanyUserProfileMap,+ buildMarkdownMentionOptions,+ isAgentTaskTarget,+} from "../lib/company-members";+import {+ extractIssueTimelineEvents,+ extractIssueWorkModeChanges,+} from "../lib/issue-timeline-events";import { queryKeys } from "../lib/queryKeys";import { keepPreviousDataForSameQueryTail } from "../lib/query-placeholder-data";+import { normalizeIssueQueuedCommentQueue } from "../lib/issue-queued-comment-queue";import { collectLiveIssueIds } from "../lib/liveIssueIds";import {hasLegacyIssueDetailQuery,@@ -38,7 +85,10 @@ import {readIssueDetailHeaderSeed,rememberIssueDetailLocationState,} from "../lib/issueDetailBreadcrumb";-import { resolveIssueActiveRun, shouldTrackIssueActiveRun } from "../lib/issueActiveRun";+import {+ resolveIssueActiveRun,+ shouldTrackIssueActiveRun,+} from "../lib/issueActiveRun";import { getIssueDetailQueryOptions } from "../lib/issueDetailCache";import {beginIssueDetailNavigation,@@ -87,9 +137,19 @@ import {type IssueCommentReassignment,type OptimisticIssueComment,} from "../lib/optimistic-issue-comments";-import { clearIssueExecutionRun, removeLiveRunById, upsertInterruptedRun } from "../lib/optimistic-issue-runs";+import {+ clearIssueExecutionRun,+ removeLiveRunById,+ upsertInterruptedRun,+} from "../lib/optimistic-issue-runs";import { useProjectOrder } from "../hooks/useProjectOrder";-import { relativeTime, cn, formatDurationMs, formatTokens, visibleRunCostUsd } from "../lib/utils";+import {+ relativeTime,+ cn,+ formatDurationMs,+ formatTokens,+ visibleRunCostUsd,+} from "../lib/utils";import { liveBlueBadge } from "../lib/status-colors";import { ApprovalCard } from "../components/ApprovalCard";import { ProjectTile } from "../components/ProjectTile";@@ -130,7 +190,12 @@ import {hasVisibleMonitorSurface,} from "../components/IssueMonitorBanner";import { IssueScheduledRetryCard } from "../components/IssueScheduledRetryCard";-import { IssueProperties, type IssuePropertiesDocumentDeepLink } from "../components/IssueProperties";+import {+ IssueProperties,+ type IssuePropertiesDocumentDeepLink,+} from "../components/IssueProperties";+import { TaskSidePanel } from "../components/task-side-panel";+import { SidePanelToggleButton } from "../components/side-panel";import { PauseAffectsSummaryView } from "../components/interrupt-handoff/InterruptHandoffViews";import { computePauseAffectsSummary } from "../lib/interrupt-handoff";import { useIssueExternalObjects } from "../hooks/useIssueExternalObjects";@@ -138,8 +203,14 @@ import { useIssuePlanDocument } from "../hooks/useIssuePlanDocument";import { IssueRunLedger } from "../components/IssueRunLedger";import { IssueWorkspaceCard } from "../components/IssueWorkspaceCard";import type { MentionOption } from "../components/MarkdownEditor";-import { ImageGalleryModal, type GalleryMediaItem } from "../components/ImageGalleryModal";-import { FileViewerProvider, useRequiredFileViewer } from "../context/FileViewerContext";+import {+ ImageGalleryModal,+ type GalleryMediaItem,+} from "../components/ImageGalleryModal";+import {+ FileViewerProvider,+ useRequiredFileViewer,+} from "../context/FileViewerContext";import { FileViewerSheet } from "../components/FileViewerSheet";import { ArtifactFileChip } from "../components/ArtifactFileChip";import { ScrollToBottom } from "../components/ScrollToBottom";@@ -148,15 +219,38 @@ import { PriorityIcon } from "../components/PriorityIcon";import { SHOW_TASK_PRIORITY_UI } from "../lib/ui-flags";import { ProductivityReviewBadge } from "../components/ProductivityReviewBadge";import { Identity } from "../components/Identity";-import { PluginSlotMount, PluginSlotOutlet, usePluginSlots } from "@/plugins/slots";+import {+ PluginSlotMount,+ PluginSlotOutlet,+ usePluginSlots,+} from "@/plugins/slots";import { PluginLauncherOutlet } from "@/plugins/launchers";import { Separator } from "@/components/ui/separator";-import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";+import {+ Popover,+ PopoverTrigger,+ PopoverContent,+} from "@/components/ui/popover";import { Button } from "@/components/ui/button";-import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";+import {+ Sheet,+ SheetContent,+ SheetHeader,+ SheetTitle,+} from "@/components/ui/sheet";import { Skeleton } from "@/components/ui/skeleton";-import { Avatar, AvatarFallback, AvatarGroup, AvatarImage } from "@/components/ui/avatar";-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";+import {+ Avatar,+ AvatarFallback,+ AvatarGroup,+ AvatarImage,+} from "@/components/ui/avatar";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/components/ui/tooltip";import { ScrollArea } from "@/components/ui/scroll-area";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import {@@ -171,8 +265,12 @@ import { Textarea } from "@/components/ui/textarea";import { formatIssueActivityAction } from "@/lib/activity-format";import { copyTextToClipboard } from "../lib/clipboard";import { buildIssuePropertiesPanelKey } from "../lib/issue-properties-panel-key";+import { buildAnsweredQuestionsDeliveryText } from "../lib/issue-thread-interactions";import { resolveIssueDocumentDeepLink } from "../lib/issue-document-deep-link";-import { buildIssueSiblingNavigation, shouldRenderRichSubIssuesSection } from "../lib/issue-detail-subissues";+import {+ buildIssueSiblingNavigation,+ shouldRenderRichSubIssuesSection,+} from "../lib/issue-detail-subissues";import { filterIssueDescendants } from "../lib/issue-tree";import { buildSubIssueDefaultsForViewer } from "../lib/subIssueDefaults";import {@@ -221,6 +319,7 @@ import {type IssueRecoveryAction,type IssueAttachment,type IssueComment,+ type IssueDocumentSummary,type IssueWorkProduct,type IssueWorkMode,type IssueThreadInteraction,@@ -244,18 +343,26 @@ type StopAndFinalizeRunError = Error & {runCancelledBeforeStatusUpdateFailed?: boolean;};-function createRunCancelledStatusUpdateError(err: unknown): StopAndFinalizeRunError {- const message = err instanceof Error- ? `Run was stopped, but updating the task failed: ${err.message}`- : "Run was stopped, but updating the task failed. Retry the task status update.";+function createRunCancelledStatusUpdateError(+ err: unknown,+): StopAndFinalizeRunError {+ const message =+ err instanceof Error+ ? `Run was stopped, but updating the task failed: ${err.message}`+ : "Run was stopped, but updating the task failed. Retry the task status update.";const error = new Error(message) as StopAndFinalizeRunError;error.runCancelledBeforeStatusUpdateFailed = true;return error;}-function didRunCancelBeforeStatusUpdateFail(err: unknown): err is StopAndFinalizeRunError {- return err instanceof Error &&- (err as StopAndFinalizeRunError).runCancelledBeforeStatusUpdateFailed === true;+function didRunCancelBeforeStatusUpdateFail(+ err: unknown,+): err is StopAndFinalizeRunError {+ return (+ err instanceof Error &&+ (err as StopAndFinalizeRunError).runCancelledBeforeStatusUpdateFailed ===+ true+ );}type CommentReassignment = IssueCommentReassignment;@@ -263,7 +370,8 @@ type ActionableIssueThreadInteraction =| SuggestTasksInteraction| RequestConfirmationInteraction| RequestCheckboxConfirmationInteraction;-type ResolveRecoveryActionOutcome = "restored" | "false_positive" | "blocked" | "cancelled";+type ResolveRecoveryActionOutcome =+ "restored" | "false_positive" | "blocked" | "cancelled";type IssueDetailComment = (IssueComment | OptimisticIssueComment) & {runId?: string | null;runAgentId?: string | null;@@ -271,9 +379,33 @@ type IssueDetailComment = (IssueComment | OptimisticIssueComment) & {queueState?: "queued";queueTargetRunId?: string | null;queueReason?: "hold" | "active_run" | "other";+ consumedByRunId?: string | null;+ steeredIntoRunId?: string | null;+ conversationAnchorAt?: Date | string | null;+ conversationAnchorSequence?: number;};-const FEEDBACK_TERMS_URL = import.meta.env.VITE_FEEDBACK_TERMS_URL?.trim() || "https://paperclip.ing/tos";+function isPlanConfirmationInteraction(+ interaction: IssueThreadInteraction,+): interaction is RequestConfirmationInteraction {+ return (+ interaction.kind === "request_confirmation" &&+ interaction.payload.target?.type === "issue_document" &&+ interaction.payload.target.key === "plan"+ );+}++function buildPlanDecisionResponseText(+ interaction: RequestConfirmationInteraction,+) {+ if (interaction.status === "accepted") return "Approved plan";+ const reason = interaction.result?.reason?.trim();+ return reason ? `Requested changes\n\n${reason}` : "Requested changes";+}++const FEEDBACK_TERMS_URL =+ import.meta.env.VITE_FEEDBACK_TERMS_URL?.trim() ||+ "https://paperclip.ing/tos";const ISSUE_COMMENT_AUTOLOAD_LIMIT = ISSUE_COMMENT_PAGE_SIZE * 3;const JUMP_TO_LATEST_MAX_COMMENT_PAGES = 10;const TREE_CONTROL_MODE_LABEL: Record<IssueTreeControlMode, string> = {@@ -282,37 +414,54 @@ const TREE_CONTROL_MODE_LABEL: Record<IssueTreeControlMode, string> = {cancel: "Cancel subtree",restore: "Restore subtree",};-const LEAF_WORK_CONTROL_MODE_LABEL: Partial<Record<IssueTreeControlMode, string>> = {+const LEAF_WORK_CONTROL_MODE_LABEL: Partial<+ Record<IssueTreeControlMode, string>+> = {pause: "Pause work",resume: "Resume work",};const TREE_CONTROL_MODE_HELP_TEXT: Record<IssueTreeControlMode, string> = {- pause: "Pause active execution in this task subtree until an explicit resume.",+ pause:+ "Pause active execution in this task subtree until an explicit resume.",resume: "Release the active subtree pause hold so held work can continue.",- cancel: "Cancel non-terminal tasks in this subtree and stop queued/running work where possible.",- restore: "Restore tasks cancelled by this subtree operation so work can resume.",+ cancel:+ "Cancel non-terminal tasks in this subtree and stop queued/running work where possible.",+ restore:+ "Restore tasks cancelled by this subtree operation so work can resume.",};-const LEAF_WORK_CONTROL_MODE_HELP_TEXT: Partial<Record<IssueTreeControlMode, string>> = {+const LEAF_WORK_CONTROL_MODE_HELP_TEXT: Partial<+ Record<IssueTreeControlMode, string>+> = {pause: "Pause active execution on this task until an explicit resume.",resume: "Release the active pause hold so this task can continue.",};-function issueTreeControlLabel(mode: IssueTreeControlMode, scope: "leaf" | "subtree") {+function issueTreeControlLabel(+ mode: IssueTreeControlMode,+ scope: "leaf" | "subtree",+) {return scope === "leaf"- ? LEAF_WORK_CONTROL_MODE_LABEL[mode] ?? TREE_CONTROL_MODE_LABEL[mode]+ ? (LEAF_WORK_CONTROL_MODE_LABEL[mode] ?? TREE_CONTROL_MODE_LABEL[mode]): TREE_CONTROL_MODE_LABEL[mode];}-function issueTreeControlHelpText(mode: IssueTreeControlMode, scope: "leaf" | "subtree") {+function issueTreeControlHelpText(+ mode: IssueTreeControlMode,+ scope: "leaf" | "subtree",+) {return scope === "leaf"- ? LEAF_WORK_CONTROL_MODE_HELP_TEXT[mode] ?? TREE_CONTROL_MODE_HELP_TEXT[mode]+ ? (LEAF_WORK_CONTROL_MODE_HELP_TEXT[mode] ??+ TREE_CONTROL_MODE_HELP_TEXT[mode]): TREE_CONTROL_MODE_HELP_TEXT[mode];}function treeControlPreviewErrorCopy(error: unknown): string {if (error instanceof ApiError) {- if (error.status === 403) return "Only board users can preview subtree controls.";- if (error.status === 409) return "Preview is stale because subtree hold state changed. Retry to refresh.";- if (error.status === 422) return "This subtree action is currently invalid for the selected tasks.";+ if (error.status === 403)+ return "Only board users can preview subtree controls.";+ if (error.status === 409)+ return "Preview is stale because subtree hold state changed. Retry to refresh.";+ if (error.status === 422)+ return "This subtree action is currently invalid for the selected tasks.";}return error instanceof Error ? error.message : "Unable to load preview.";}@@ -322,7 +471,8 @@ export function canBoardResolveRecoveryAction(boardAccess: CurrentBoardAccess | undefined,) {if (!companyId || !boardAccess) return false;- if (boardAccess.source === "local_implicit" || boardAccess.isInstanceAdmin) return true;+ if (boardAccess.source === "local_implicit" || boardAccess.isInstanceAdmin)+ return true;if (!boardAccess.memberships || boardAccess.memberships.length === 0) {return boardAccess.companyIds.includes(companyId);}@@ -331,7 +481,9 @@ export function canBoardResolveRecoveryAction((item) => item.companyId === companyId && item.status === "active",);if (!membership) return false;- return membership.membershipRole !== "viewer" && membership.membershipRole !== null;+ return (+ membership.membershipRole !== "viewer" && membership.membershipRole !== null+ );}// `canBoardManageRuntime` and `readRecoveryReconcileWorkspaceId` moved to `@/lib/recovery-reconcile`@@ -357,10 +509,11 @@ function resolveInterruptibleIssueRun((liveRuns ?? []).find((run) => run.status === "running") ??(liveRuns ?? []).find((run) => run.status === "queued") ??null;- return issueLiveRun ?? (- activeRun?.status === "running" || activeRun?.status === "queued"+ return (+ issueLiveRun ??+ (activeRun?.status === "running" || activeRun?.status === "queued"? activeRun- : null+ : null));}@@ -390,22 +543,27 @@ function readIssueRunStateFromCache(const activeRunMatchesIssueLock = Boolean(activeRun && issue?.executionRunId && activeRun.id === issue.executionRunId,);- const resolvedActiveRun = activeRunIsLive || activeRunMatchesIssueLock ? activeRun : null;+ const resolvedActiveRun =+ activeRunIsLive || activeRunMatchesIssueLock ? activeRun : null;return {liveRuns,activeRun: resolvedActiveRun,- interruptibleIssueRun: resolveInterruptibleIssueRun(resolvedActiveRun, liveRuns),+ interruptibleIssueRun: resolveInterruptibleIssueRun(+ resolvedActiveRun,+ liveRuns,+ ),};}function asRecord(value: unknown): Record<string, unknown> | null {- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;+ if (typeof value !== "object" || value === null || Array.isArray(value))+ return null;return value as Record<string, unknown>;}-function extractWorkspaceFileRefFromWorkProduct(- workProduct: { metadata: Record<string, unknown> | null },-): WorkspaceFileRef | null {+function extractWorkspaceFileRefFromWorkProduct(workProduct: {+ metadata: Record<string, unknown> | null;+}): WorkspaceFileRef | null {const metadata = asRecord(workProduct.metadata);if (!metadata) return null;const parsed = workspaceFileRefSchema.safeParse(metadata.resourceRef);@@ -513,7 +671,18 @@ function mergeOptimisticFeedbackVote(];}-function ActorIdentity({ evt, agentMap, userProfileMap }: { evt: ActivityEvent; agentMap: Map<string, Agent>; userProfileMap?: Map<string, import("../lib/company-members").CompanyUserProfile> }) {+function ActorIdentity({+ evt,+ agentMap,+ userProfileMap,+}: {+ evt: ActivityEvent;+ agentMap: Map<string, Agent>;+ userProfileMap?: Map<+ string,+ import("../lib/company-members").CompanyUserProfile+ >;+}) {const id = evt.actorId;if (evt.actorType === "agent") {const agent = agentMap.get(id);@@ -522,7 +691,13 @@ function ActorIdentity({ evt, agentMap, userProfileMap }: { evt: ActivityEvent;if (evt.actorType === "system") return <Identity name="System" size="sm" />;if (evt.actorType === "user") {const profile = userProfileMap?.get(id);- return <Identity name={profile?.label ?? "Board"} avatarUrl={profile?.image} size="sm" />;+ return (+ <Identity+ name={profile?.label ?? "Board"}+ avatarUrl={profile?.image}+ size="sm"+ />+ );}return <Identity name={id || "Unknown"} size="sm" />;}@@ -536,7 +711,8 @@ export type AttributionActor = {function attributionInitials(name: string): string {const parts = name.trim().split(/\s+/);- if (parts.length >= 2) return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();+ if (parts.length >= 2)+ return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();return name.slice(0, 2).toUpperCase();}@@ -549,7 +725,9 @@ function AttributionAvatar({actor: AttributionActor;via?: string | null;}) {- const accessibleLabel = via ? `${label}: ${actor.name} · via ${via}` : `${label}: ${actor.name}`;+ const accessibleLabel = via+ ? `${label}: ${actor.name} · via ${via}`+ : `${label}: ${actor.name}`;const testIdLabel = label.toLowerCase();return (@@ -562,27 +740,40 @@ function AttributionAvatar({data-testid={`issue-${testIdLabel}-avatar`}className="ring-2 ring-background">- {actor.avatarUrl ? <AvatarImage src={actor.avatarUrl} alt="" /> : null}+ {actor.avatarUrl ? (+ <AvatarImage src={actor.avatarUrl} alt="" />+ ) : null}<AvatarFallback>{attributionInitials(actor.name)}</AvatarFallback></Avatar></TooltipTrigger><TooltipContent side="top" sideOffset={6} className="px-2 py-1.5">- <div className="flex items-center gap-2" data-testid={`issue-${testIdLabel}-tooltip`}>+ <div+ className="flex items-center gap-2"+ data-testid={`issue-${testIdLabel}-tooltip`}+ ><Avatarsize="sm"shape={actor.kind === "agent" ? "square" : "circle"}className="ring-1 ring-background/30">- {actor.avatarUrl ? <AvatarImage src={actor.avatarUrl} alt="" /> : null}+ {actor.avatarUrl ? (+ <AvatarImage src={actor.avatarUrl} alt="" />+ ) : null}<AvatarFallback className="bg-background/20 text-background">{attributionInitials(actor.name)}</AvatarFallback></Avatar><div className="min-w-0">- <div className="text-(length:--text-nano) font-medium uppercase leading-none text-background/70">{label}</div>- <div className="max-w-48 truncate text-xs font-medium leading-4 text-background">{actor.name}</div>+ <div className="text-(length:--text-nano) font-medium uppercase leading-none text-background/70">+ {label}+ </div>+ <div className="max-w-48 truncate text-xs font-medium leading-4 text-background">+ {actor.name}+ </div>{via ? (- <div className="max-w-48 truncate text-(length:--text-nano) leading-3 text-background/60">via {via}</div>+ <div className="max-w-48 truncate text-(length:--text-nano) leading-3 text-background/60">+ via {via}+ </div>) : null}</div></div>@@ -599,22 +790,28 @@ function IssueAttributionByline({}: {issue: Issue;agentMap: Map<string, Agent>;- userProfileMap: ReadonlyMap<string, import("../lib/company-members").CompanyUserProfile>;+ userProfileMap: ReadonlyMap<+ string,+ import("../lib/company-members").CompanyUserProfile+ >;userLabelMap: ReadonlyMap<string, string>;}) {const assignee: AttributionActor | null = issue.assigneeAgentId? {kind: "agent",id: issue.assigneeAgentId,- name: agentMap.get(issue.assigneeAgentId)?.name ?? issue.assigneeAgentId.slice(0, 8),+ name:+ agentMap.get(issue.assigneeAgentId)?.name ??+ issue.assigneeAgentId.slice(0, 8),}: issue.assigneeUserId? {kind: "user",id: issue.assigneeUserId,- name: formatUserLabel(issue.assigneeUserId, userLabelMap)- ?? userProfileMap.get(issue.assigneeUserId)?.label- ?? "User",+ name:+ formatUserLabel(issue.assigneeUserId, userLabelMap) ??+ userProfileMap.get(issue.assigneeUserId)?.label ??+ "User",avatarUrl: userProfileMap.get(issue.assigneeUserId)?.image ?? null,}: null;@@ -624,28 +821,44 @@ function IssueAttributionByline({? {kind: "agent",id: originatingActor.id,- name: agentMap.get(originatingActor.id)?.name ?? originatingActor.id.slice(0, 8),+ name:+ agentMap.get(originatingActor.id)?.name ??+ originatingActor.id.slice(0, 8),}: {kind: "user",id: originatingActor.id,- name: formatUserLabel(originatingActor.id, userLabelMap)- ?? userProfileMap.get(originatingActor.id)?.label- ?? "User",+ name:+ formatUserLabel(originatingActor.id, userLabelMap) ??+ userProfileMap.get(originatingActor.id)?.label ??+ "User",avatarUrl: userProfileMap.get(originatingActor.id)?.image ?? null,}: null;const originatorVia =originatingActor?.kind === "user" && originatingActor.viaAgentId- ? agentMap.get(originatingActor.viaAgentId)?.name ?? originatingActor.viaAgentId.slice(0, 8)+ ? (agentMap.get(originatingActor.viaAgentId)?.name ??+ originatingActor.viaAgentId.slice(0, 8)): null;if (!assignee && !originator) return null;return (<TooltipProvider>- <AvatarGroup className="-space-x-1.5" aria-label="Task people" data-testid="issue-attribution-avatar-stack">- {assignee ? <AttributionAvatar label="Assignee" actor={assignee} /> : null}- {originator ? <AttributionAvatar label="Originating" actor={originator} via={originatorVia} /> : null}+ <AvatarGroup+ className="-space-x-1.5"+ aria-label="Task people"+ data-testid="issue-attribution-avatar-stack"+ >+ {assignee ? (+ <AttributionAvatar label="Assignee" actor={assignee} />+ ) : null}+ {originator ? (+ <AttributionAvatar+ label="Originating"+ actor={originator}+ via={originatorVia}+ />+ ) : null}</AvatarGroup></TooltipProvider>);@@ -685,7 +898,12 @@ function ChatBubbleSkeleton({}) {const isHuman = side === "human";return (- <div className={cn("flex w-full flex-col gap-1", isHuman ? "items-end" : "items-start")}>+ <div+ className={cn(+ "flex w-full flex-col gap-1",+ isHuman ? "items-end" : "items-start",+ )}+ >{isHuman ? null : (<span className="flex items-center gap-2 px-1"><Skeleton className="h-6 w-6 rounded-full" />@@ -749,8 +967,10 @@ function IssueDetailLoadingState({}: {headerSeed: ReturnType<typeof readIssueDetailHeaderSeed>;}) {- const identifier = headerSeed?.identifier ?? headerSeed?.id.slice(0, 8) ?? null;- const { enabled: classicTaskInterfaceEnabled } = useClassicTaskInterfaceEnabled();+ const identifier =+ headerSeed?.identifier ?? headerSeed?.id.slice(0, 8) ?? null;+ const { enabled: classicTaskInterfaceEnabled } =+ useClassicTaskInterfaceEnabled();const taskChatShellEnabled = !classicTaskInterfaceEnabled;return (@@ -767,14 +987,23 @@ function IssueDetailLoadingState({<div className="flex items-center gap-2 min-w-0 flex-wrap">{headerSeed ? (<>- <StatusIcon status={headerSeed.status} blockerAttention={headerSeed.blockerAttention} />+ <StatusIcon+ status={headerSeed.status}+ blockerAttention={headerSeed.blockerAttention}+ />{/* PAP-411: priority UI hidden behind SHOW_TASK_PRIORITY_UI. */}- {SHOW_TASK_PRIORITY_UI && <PriorityIcon priority={headerSeed.priority} />}+ {SHOW_TASK_PRIORITY_UI && (+ <PriorityIcon priority={headerSeed.priority} />+ )}{identifier ? (- <span className="text-sm font-mono text-muted-foreground shrink-0">{identifier}</span>+ <span className="text-sm font-mono text-muted-foreground shrink-0">+ {identifier}+ </span>) : null}- {headerSeed.originKind === "routine_execution" && headerSeed.originId ? (- <Badge variant="outline"+ {headerSeed.originKind === "routine_execution" &&+ headerSeed.originId ? (+ <Badge+ variant="outline"className="border-violet-500/30 bg-violet-500/10 text-(length:--text-nano) text-violet-600 dark:text-violet-400"title={`Routine execution from routine ${headerSeed.originId}`}>@@ -810,7 +1039,9 @@ function IssueDetailLoadingState({{headerSeed ? (<>- <h2 className="text-xl font-bold leading-tight">{headerSeed.title}</h2>+ <h2 className="text-xl font-bold leading-tight">+ {headerSeed.title}+ </h2><div className="space-y-2"><Skeleton className="h-4 w-full max-w-xl" /><Skeleton className="h-4 w-(--pct-72)" />@@ -917,14 +1148,20 @@ function InboxMobileToolbar({<PopoverContent className="w-44 p-1" align="end"><buttonclassName="flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50"- onClick={() => { onCopy(); setMenuOpen(false); }}+ onClick={() => {+ onCopy();+ setMenuOpen(false);+ }}><Copy className="h-3 w-3" />Copy as markdown</button><buttonclassName="flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50"- onClick={() => { onProperties(); setMenuOpen(false); }}+ onClick={() => {+ onProperties();+ setMenuOpen(false);+ }}><SlidersHorizontal className="h-3 w-3" />Properties@@ -932,7 +1169,10 @@ function InboxMobileToolbar({{issueIdProp && (<buttonclassName="flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-destructive"- onClick={() => { onHide(); setMenuOpen(false); }}+ onClick={() => {+ onHide();+ setMenuOpen(false);+ }}><EyeOff className="h-3 w-3" />Hide this task@@ -960,8 +1200,12 @@ type IssueDetailChatTabProps = {successfulRunHandoff: Issue["successfulRunHandoff"] | null;scheduledRetry: Issue["scheduledRetry"] | null;recoveryAction: Issue["activeRecoveryAction"];- onResolveRecoveryAction?: (outcome: import("../components/IssueRecoveryActionCard").RecoveryResolveOutcome) => void;- onReissueIsolatedRecoveryAction?: (request: import("../components/IssueRecoveryActionCard").RecoveryReissueRequest) => void;+ onResolveRecoveryAction?: (+ outcome: import("../components/IssueRecoveryActionCard").RecoveryResolveOutcome,+ ) => void;+ onReissueIsolatedRecoveryAction?: (+ request: import("../components/IssueRecoveryActionCard").RecoveryReissueRequest,+ ) => void;reissueIsolatedRecoveryActionPending?: boolean;onReconcileForwardRecoveryAction?: () => void;onBreakGlassOverrideRecoveryAction?: (reason: string) => void;@@ -979,6 +1223,9 @@ type IssueDetailChatTabProps = {commentsInitialLoading?: boolean;locallyQueuedCommentRunIds: ReadonlyMap<string, string>;interactions: IssueThreadInteraction[];+ documents: IssueDocumentSummary[];+ workProducts: IssueWorkProduct[];+ attachments: IssueAttachment[];hasOlderComments: boolean;commentsLoadingOlder: boolean;onLoadOlderComments: () => void;@@ -1005,7 +1252,10 @@ type IssueDetailChatTabProps = {agentMap: Map<string, Agent>;currentUserId: string | null;userLabelMap: ReadonlyMap<string, string> | null;- userProfileMap: ReadonlyMap<string, import("../lib/company-members").CompanyUserProfile> | null;+ userProfileMap: ReadonlyMap<+ string,+ import("../lib/company-members").CompanyUserProfile+ > | null;draftKey: string;reassignOptions: Array<{ id: string; label: string; searchText?: string }>;currentAssigneeValue: string;@@ -1019,7 +1269,11 @@ type IssueDetailChatTabProps = {vote: "up" | "down",options?: { allowSharing?: boolean; reason?: string },) => Promise<void>;- onAdd: (body: string, reopen?: boolean, reassignment?: CommentReassignment) => Promise<void>;+ onAdd: (+ body: string,+ reopen?: boolean,+ reassignment?: CommentReassignment,+ ) => Promise<void>;onImageUpload: (file: File) => Promise<string>;onAttachImage: (file: File) => Promise<IssueAttachment | void>;onInterruptQueued: (runId: string) => Promise<void>;@@ -1035,21 +1289,33 @@ type IssueDetailChatTabProps = {selectedClientKeys?: string[],selectedOptionIds?: string[],) => Promise<void>;- onRejectInteraction: (interaction: ActionableIssueThreadInteraction, reason?: string) => Promise<void>;+ onRejectInteraction: (+ interaction: ActionableIssueThreadInteraction,+ reason?: string,+ ) => Promise<void>;onSubmitInteractionAnswers: (interaction: IssueThreadInteraction,answers: AskUserQuestionsAnswer[],) => Promise<void>;- onCancelInteraction: (interaction: AskUserQuestionsInteraction) => Promise<void>;+ onCancelInteraction: (+ interaction: AskUserQuestionsInteraction,+ ) => Promise<void>;+ onSkipInteraction: (interaction: IssueThreadInteraction) => Promise<void>;onSubmitInteractionVerdicts: (interaction: RequestItemVerdictsInteraction,- verdicts: { id: string; verdict: RequestItemVerdictValue; reason?: string }[],+ verdicts: {+ id: string;+ verdict: RequestItemVerdictValue;+ reason?: string;+ }[],) => Promise<void>;assigneeUserId: string | null;onResumeFromBacklog?: () => Promise<void> | void;resumeFromBacklogPending?: boolean;onResumeAssignee?: () => Promise<void> | void;resumeAssigneePending?: boolean;+ onTryAgainNoLiveExecutionPath?: () => Promise<void> | void;+ tryAgainNoLiveExecutionPathPending?: boolean;externalReferences?: MarkdownExternalReferenceMap;linkCaseReferences?: boolean;};@@ -1083,6 +1349,9 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({commentsInitialLoading = false,locallyQueuedCommentRunIds,interactions,+ documents,+ workProducts,+ attachments,hasOlderComments,commentsLoadingOlder,onLoadOlderComments,@@ -1124,12 +1393,15 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({onRejectInteraction,onSubmitInteractionAnswers,onCancelInteraction,+ onSkipInteraction,onSubmitInteractionVerdicts,assigneeUserId,onResumeFromBacklog,resumeFromBacklogPending,onResumeAssignee,resumeAssigneePending,+ onTryAgainNoLiveExecutionPath,+ tryAgainNoLiveExecutionPathPending,externalReferences,linkCaseReferences,}: IssueDetailChatTabProps) {@@ -1137,37 +1409,92 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({// Flag ON renders the legacy IssueChatThread verbatim; flag OFF (the// default) renders the chat-style TaskChatThread. Both components share one// prop type, so no cast is needed.- const { enabled: classicTaskInterfaceEnabled } = useClassicTaskInterfaceEnabled();- const ThreadComponent = classicTaskInterfaceEnabled ? IssueChatThread : TaskChatThread;+ const { enabled: classicTaskInterfaceEnabled } =+ useClassicTaskInterfaceEnabled();+ const ThreadComponent = classicTaskInterfaceEnabled+ ? IssueChatThread+ : TaskChatThread;+ const queryClient = useQueryClient();+ const { pushToast } = useToastActions();const { data: activity } = useQuery({queryKey: queryKeys.issues.activity(issueId),queryFn: () => activityApi.forIssue(issueId),placeholderData: keepPreviousDataForSameQueryTail<ActivityEvent[]>(issueId),});- const { data: liveRuns } = useQuery({+ const { data: liveRuns, isFetched: liveRunsFetched } = useQuery({queryKey: queryKeys.issues.liveRuns(issueId),queryFn: () => heartbeatsApi.liveRunsForIssue(issueId),- refetchInterval: 3000,- placeholderData: keepPreviousDataForSameQueryTail<LiveRunForIssue[]>(issueId),+ refetchInterval: 1000,+ placeholderData:+ keepPreviousDataForSameQueryTail<LiveRunForIssue[]>(issueId),});const resolvedLiveRuns = liveRuns ?? [];const liveRunCount = resolvedLiveRuns.length;- const { data: activeRun = null } = useQuery({+ const activeRunQueryEnabled = !!executionRunId || issueStatus === "in_progress";+ const { data: activeRun = null, isFetched: activeRunFetched } = useQuery({queryKey: queryKeys.issues.activeRun(issueId),queryFn: () => heartbeatsApi.activeRunForIssue(issueId),- enabled: !!executionRunId || issueStatus === "in_progress",- refetchInterval: liveRunCount > 0 ? false : 3000,- placeholderData: keepPreviousDataForSameQueryTail<ActiveRunForIssue | null>(issueId),+ enabled: activeRunQueryEnabled,+ refetchInterval: liveRunCount > 0 ? false : 1000,+ placeholderData: keepPreviousDataForSameQueryTail<ActiveRunForIssue | null>(+ issueId,+ ),});const resolvedActiveRun = useMemo(- () => resolveIssueActiveRun({ status: issueStatus, executionRunId }, activeRun),+ () =>+ resolveIssueActiveRun({ status: issueStatus, executionRunId }, activeRun),[activeRun, executionRunId, issueStatus],);+ const assigneeUsesPaperclipRunner = Boolean(+ issueAssigneeAgentId &&+ agentMap.get(issueAssigneeAgentId)?.adapterType === "paperclip_runner",+ );+ const liveRuntimeRun =+ resolvedActiveRun ??+ resolvedLiveRuns.find(+ (run) => run.status === "running" || run.status === "queued",+ ) ??+ null;+ // Do not briefly enable runner-only queue traffic from the current assignee+ // while the authoritative active-run lookup is still loading. A task can be+ // reassigned to a Paperclip Runner agent while an existing direct-adapter+ // run remains active; that legacy run must never create or poll native queue+ // state.+ const runtimeSelectionKnown =+ liveRunsFetched && (!activeRunQueryEnabled || activeRunFetched);+ const paperclipQueueEnabled =+ !classicTaskInterfaceEnabled &&+ runtimeSelectionKnown &&+ (liveRuntimeRun+ ? liveRuntimeRun.runtimeMode === "native" &&+ liveRuntimeRun.adapterType === "paperclip_runner"+ : assigneeUsesPaperclipRunner);+ const { data: authoritativeQueuedCommentQueue } = useQuery({+ queryKey: queryKeys.issues.queuedComments(issueId),+ queryFn: async () =>+ normalizeIssueQueuedCommentQueue(+ await issuesApi.getQueuedComments(issueId),+ issueId,+ ),+ enabled: paperclipQueueEnabled,+ refetchInterval: paperclipQueueEnabled ? 1000 : false,+ });+ const [consumedQueuedCommentIds, setConsumedQueuedCommentIds] = useState<+ ReadonlySet<string>+ >(() => new Set());+ const [discardedQueuedCommentIds, setDiscardedQueuedCommentIds] = useState<+ ReadonlySet<string>+ >(() => new Set());+ useEffect(() => {+ setConsumedQueuedCommentIds(new Set());+ setDiscardedQueuedCommentIds(new Set());+ }, [authoritativeQueuedCommentQueue?.queueId, issueId]);const hasLiveRuns = liveRunCount > 0 || !!resolvedActiveRun;const { data: linkedRuns } = useQuery({queryKey: queryKeys.issues.runs(issueId),queryFn: () => activityApi.runsForIssue(issueId),- refetchInterval: hasLiveRuns ? 5000 : false,+ refetchInterval:+ hasLiveRuns || issueStatus === "in_progress" ? 1000 : false,placeholderData: keepPreviousDataForSameQueryTail<RunForIssue[]>(issueId),});const resolvedActivity = activity ?? [];@@ -1184,9 +1511,10 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({return ids;}, [resolvedActiveRun, resolvedLiveRuns]);const timelineRuns = useMemo(() => {- const historicalRuns = liveRunIds.size === 0- ? resolvedLinkedRuns- : resolvedLinkedRuns.filter((run) => !liveRunIds.has(run.runId));+ const historicalRuns =+ liveRunIds.size === 0+ ? resolvedLinkedRuns+ : resolvedLinkedRuns.filter((run) => !liveRunIds.has(run.runId));return historicalRuns.map((run) => ({...run,adapterType: run.adapterType,@@ -1194,21 +1522,110 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({}));}, [liveRunIds, resolvedLinkedRuns]);const commentsWithRunMeta = useMemo<IssueDetailComment[]>(() => {- const activeRunStartedAt = interruptibleIssueRun?.startedAt ?? interruptibleIssueRun?.createdAt ?? null;- const runMetaByCommentId = new Map<string, { runId: string; runAgentId: string | null; interruptedRunId: string | null }>();+ const activeRunStartedAt =+ interruptibleIssueRun?.startedAt ??+ interruptibleIssueRun?.createdAt ??+ null;+ const runMetaByCommentId = new Map<+ string,+ {+ runId: string;+ runAgentId: string | null;+ interruptedRunId: string | null;+ }+ >();const followUpCommentIds = new Set<string>();const agentIdByRunId = new Map<string, string>();+ const inputPlacementByCommentId = new Map<+ string,+ {+ runId: string;+ anchorAt: string;+ sequence: number;+ anchorMs: number;+ kind: "run_start" | "steer";+ }+ >();for (const run of resolvedLinkedRuns) {agentIdByRunId.set(run.runId, run.agentId);+ const batchedIds = Array.isArray(run.wakeCommentIds)+ ? run.wakeCommentIds.filter(+ (value): value is string =>+ typeof value === "string" && value.length > 0,+ )+ : [];+ const fallbackId =+ typeof run.wakeCommentId === "string" && run.wakeCommentId.length > 0+ ? run.wakeCommentId+ : typeof run.contextCommentId === "string" &&+ run.contextCommentId.length > 0+ ? run.contextCommentId+ : null;+ const inputIds =+ batchedIds.length > 0 ? batchedIds : fallbackId ? [fallbackId] : [];+ const anchorAt = run.startedAt ?? run.createdAt;+ const anchorMs = new Date(anchorAt).getTime();+ inputIds.forEach((commentId, sequence) => {+ const existing = inputPlacementByCommentId.get(commentId);+ if (existing && existing.anchorMs <= anchorMs) return;+ inputPlacementByCommentId.set(commentId, {+ runId: run.runId,+ anchorAt,+ sequence,+ anchorMs,+ kind: "run_start",+ });+ });+ }+ // Same-turn steering has a durable PRP acknowledgement and a matching+ // activity fact keyed by commentId/targetRunId. Its acknowledgement time,+ // not the comment submission time, is the causal conversation slot. Use+ // only the first acknowledgement; an idempotent replay emits a diagnostic+ // activity row with duplicate=true but must not move the message later.+ const steeringEvents = resolvedActivity+ .filter((evt) => evt.action === "issue.queued_comment_steered")+ .sort(+ (a, b) =>+ new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),+ );+ const steeringSequenceByRunId = new Map<string, number>();+ for (const evt of steeringEvents) {+ const details = evt.details ?? {};+ if (details["duplicate"] === true) continue;+ const commentId =+ typeof details["commentId"] === "string" ? details["commentId"] : null;+ const targetRunId =+ typeof details["targetRunId"] === "string"+ ? details["targetRunId"]+ : null;+ if (!commentId || !targetRunId) continue;+ const anchorAt =+ evt.createdAt instanceof Date+ ? evt.createdAt.toISOString()+ : evt.createdAt;+ const anchorMs = new Date(anchorAt).getTime();+ if (!Number.isFinite(anchorMs)) continue;+ const sequence = steeringSequenceByRunId.get(targetRunId) ?? 0;+ steeringSequenceByRunId.set(targetRunId, sequence + 1);+ inputPlacementByCommentId.set(commentId, {+ runId: targetRunId,+ anchorAt,+ sequence,+ anchorMs,+ kind: "steer",+ });}for (const evt of resolvedActivity) {if (evt.action !== "issue.comment_added" || !evt.runId) continue;const details = evt.details ?? {};- const commentId = typeof details["commentId"] === "string" ? details["commentId"] : null;+ const commentId =+ typeof details["commentId"] === "string" ? details["commentId"] : null;if (!commentId || runMetaByCommentId.has(commentId)) continue;const interruptedRunId =- typeof details["interruptedRunId"] === "string" ? details["interruptedRunId"] : null;+ typeof details["interruptedRunId"] === "string"+ ? details["interruptedRunId"]+ : null;runMetaByCommentId.set(commentId, {runId: evt.runId,runAgentId: evt.agentId ?? agentIdByRunId.get(evt.runId) ?? null,@@ -1218,29 +1635,57 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({for (const evt of resolvedActivity) {if (evt.action !== "issue.comment_added") continue;const details = evt.details ?? {};- const commentId = typeof details["commentId"] === "string" ? details["commentId"] : null;+ const commentId =+ typeof details["commentId"] === "string" ? details["commentId"] : null;if (!commentId) continue;- if (details["followUpRequested"] === true || details["resumeIntent"] === true) {+ if (+ details["followUpRequested"] === true ||+ details["resumeIntent"] === true+ ) {followUpCommentIds.add(commentId);}}- return comments.map((comment) => {+ const projectedComments = comments.map((comment) => {const meta = runMetaByCommentId.get(comment.id);- const nextComment: IssueDetailComment = meta ? { ...comment, ...meta } : { ...comment };+ const inputPlacement = inputPlacementByCommentId.get(comment.id);+ const nextComment: IssueDetailComment = {+ ...comment,+ ...(meta ?? {}),+ ...(inputPlacement+ ? {+ consumedByRunId: inputPlacement.runId,+ ...(inputPlacement.kind === "steer"+ ? { steeredIntoRunId: inputPlacement.runId }+ : {}),+ conversationAnchorAt: inputPlacement.anchorAt,+ conversationAnchorSequence: inputPlacement.sequence,+ }+ : {}),+ };if (followUpCommentIds.has(comment.id)) {nextComment.followUpRequested = true;}const queuedTargetRunId =- locallyQueuedCommentRunIds.get(comment.id) ?? nextComment.queueTargetRunId ?? null;- const locallyQueuedComment = applyLocalQueuedIssueCommentState(nextComment, {- queuedTargetRunId,- targetRunIsLive: queuedTargetRunId ? liveRunIds.has(queuedTargetRunId) : false,- runningRunId: interruptibleIssueRun?.id ?? null,- });+ locallyQueuedCommentRunIds.get(comment.id) ??+ nextComment.queueTargetRunId ??+ null;+ const locallyQueuedComment = applyLocalQueuedIssueCommentState(+ nextComment,+ {+ queuedTargetRunId,+ targetRunIsLive: queuedTargetRunId+ ? liveRunIds.has(queuedTargetRunId)+ : false,+ runningRunId: interruptibleIssueRun?.id ?? null,+ },+ );if (locallyQueuedComment !== nextComment) {return locallyQueuedComment;}+ if (inputPlacement?.kind === "steer") {+ return nextComment;+ }// A queued target is fixed when the message is submitted. If that run// settles while the request is still in flight, do not rebind the// message's Interrupt action to an unrelated run that became live later.@@ -1253,9 +1698,11 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({activeRunStartedAt,activeRunAgentId: interruptibleIssueRun?.agentId ?? null,activeRunCommentId: interruptibleIssueRun?.contextCommentId ?? null,- activeRunWakeCommentId: interruptibleIssueRun?.contextWakeCommentId ?? null,+ activeRunWakeCommentId:+ interruptibleIssueRun?.contextWakeCommentId ?? null,runId: meta?.runId ?? nextComment.runId ?? null,- interruptedRunId: meta?.interruptedRunId ?? nextComment.interruptedRunId ?? null,+ interruptedRunId:+ meta?.interruptedRunId ?? nextComment.interruptedRunId ?? null,})) {return {@@ -1267,8 +1714,109 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({}return nextComment;});+ const questionDeliveryByInteractionId = new Map<+ string,+ { targetRunId: string; deliveryMode: string | null }+ >();+ for (const event of resolvedActivity) {+ if (event.action !== "issue.question_response_delivered") continue;+ const details = event.details ?? {};+ const interactionId =+ typeof details["interactionId"] === "string"+ ? details["interactionId"]+ : null;+ const targetRunId =+ typeof details["targetRunId"] === "string"+ ? details["targetRunId"]+ : null;+ if (+ !interactionId ||+ !targetRunId ||+ questionDeliveryByInteractionId.has(interactionId)+ ) {+ continue;+ }+ questionDeliveryByInteractionId.set(interactionId, {+ targetRunId,+ deliveryMode:+ typeof details["deliveryMode"] === "string"+ ? details["deliveryMode"]+ : null,+ });+ }+ const responseComments = classicTaskInterfaceEnabled+ ? []+ : interactions.flatMap(+ (interaction): IssueDetailComment[] => {+ const answeredQuestions =+ interaction.kind === "ask_user_questions" &&+ interaction.status === "answered";+ const resolvedPlanDecision =+ isPlanConfirmationInteraction(interaction) &&+ (interaction.status === "accepted" ||+ interaction.status === "rejected");+ if (+ (!answeredQuestions && !resolvedPlanDecision) ||+ !interaction.resolvedAt+ ) {+ return [];+ }+ const resolvedAt =+ interaction.resolvedAt instanceof Date+ ? interaction.resolvedAt+ : new Date(interaction.resolvedAt);+ if (Number.isNaN(resolvedAt.getTime())) return [];+ const delivery = answeredQuestions+ ? (questionDeliveryByInteractionId.get(interaction.id) ?? null)+ : null;+ const queuedTargetRunId =+ interaction.sourceRunId &&+ interruptibleIssueRun?.id === interaction.sourceRunId &&+ interruptibleIssueRun.adapterType !== "paperclip_runner"+ ? interaction.sourceRunId+ : null;+ const body =+ interaction.kind === "ask_user_questions"+ ? buildAnsweredQuestionsDeliveryText(interaction)+ : isPlanConfirmationInteraction(interaction)+ ? buildPlanDecisionResponseText(interaction)+ : "";+ return [+ {+ id: `interaction-response:${interaction.id}`,+ companyId: interaction.companyId,+ issueId: interaction.issueId,+ authorType: interaction.resolvedByAgentId ? "agent" : "user",+ authorAgentId: interaction.resolvedByAgentId ?? null,+ authorUserId: interaction.resolvedByUserId ?? null,+ createdByRunId: interaction.resolvedByRunId ?? null,+ body,+ presentation: null,+ metadata: null,+ createdAt: resolvedAt,+ updatedAt: resolvedAt,+ consumedByRunId: delivery?.targetRunId ?? null,+ ...(delivery?.deliveryMode === "steered"+ ? { steeredIntoRunId: delivery.targetRunId }+ : {}),+ conversationAnchorAt: resolvedAt,+ conversationAnchorSequence: 0,+ ...(queuedTargetRunId+ ? {+ queueState: "queued" as const,+ queueTargetRunId: queuedTargetRunId,+ queueReason: queuedCommentReason,+ }+ : {}),+ },+ ];+ },+ );+ return [...projectedComments, ...responseComments];}, [comments,+ classicTaskInterfaceEnabled,+ interactions,liveRunIds,locallyQueuedCommentRunIds,queuedCommentReason,@@ -1276,6 +1824,232 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({resolvedLinkedRuns,interruptibleIssueRun,]);+ const effectiveQueuedCommentQueue = useMemo(() => {+ if (!paperclipQueueEnabled || !authoritativeQueuedCommentQueue?.queueId)+ return null;+ return {+ ...authoritativeQueuedCommentQueue,+ entries: authoritativeQueuedCommentQueue.entries+ .filter(+ (entry) =>+ !consumedQueuedCommentIds.has(entry.comment.id) &&+ !discardedQueuedCommentIds.has(entry.comment.id),+ )+ .map((entry, position) => ({ ...entry, position })),+ };+ }, [+ authoritativeQueuedCommentQueue,+ consumedQueuedCommentIds,+ discardedQueuedCommentIds,+ paperclipQueueEnabled,+ ]);+ const commentsForThread = useMemo(+ () =>+ commentsWithRunMeta.flatMap((comment) => {+ if (discardedQueuedCommentIds.has(comment.id)) return [];+ if (!consumedQueuedCommentIds.has(comment.id)) return [comment];+ return [+ {+ ...comment,+ queueState: undefined,+ queueTargetRunId: null,+ queueReason: undefined,+ },+ ];+ }),+ [commentsWithRunMeta, consumedQueuedCommentIds, discardedQueuedCommentIds],+ );++ const storeQueuedCommentQueue = useCallback(+ (value: unknown) => {+ const queue = normalizeIssueQueuedCommentQueue(value, issueId);+ queryClient.setQueryData(queryKeys.issues.queuedComments(issueId), queue);+ return queue;+ },+ [issueId, queryClient],+ );++ const refreshQueueAfterConflict = useCallback(+ async (error: unknown) => {+ if (error instanceof ApiError && error.status === 409) {+ await queryClient.invalidateQueries({+ queryKey: queryKeys.issues.queuedComments(issueId),+ });+ }+ throw error;+ },+ [issueId, queryClient],+ );++ const editQueuedComment = useCallback(+ async (commentId: string, body: string, revision: string) => {+ const queueId = effectiveQueuedCommentQueue?.queueId;+ if (!queueId)+ throw new Error(+ "The queued message is awaiting server acknowledgement.",+ );+ try {+ storeQueuedCommentQueue(+ await issuesApi.editQueuedComment(issueId, commentId, {+ body,+ queueId,+ revision,+ }),+ );+ await queryClient.invalidateQueries({+ queryKey: queryKeys.issues.comments(issueId),+ });+ } catch (error) {+ await refreshQueueAfterConflict(error);+ }+ },+ [+ effectiveQueuedCommentQueue?.queueId,+ issueId,+ queryClient,+ refreshQueueAfterConflict,+ storeQueuedCommentQueue,+ ],+ );++ const reorderQueuedComments = useCallback(+ async (orderedCommentIds: string[], revision: string) => {+ const queueId = effectiveQueuedCommentQueue?.queueId;+ if (!queueId)+ throw new Error(+ "The queued messages are awaiting server acknowledgement.",+ );+ try {+ storeQueuedCommentQueue(+ await issuesApi.reorderQueuedComments(issueId, {+ orderedCommentIds,+ queueId,+ revision,+ }),+ );+ } catch (error) {+ await refreshQueueAfterConflict(error);+ }+ },+ [+ effectiveQueuedCommentQueue?.queueId,+ issueId,+ refreshQueueAfterConflict,+ storeQueuedCommentQueue,+ ],+ );++ const steerQueuedComment = useCallback(+ async (commentId: string, revision: string) => {+ const queueId = effectiveQueuedCommentQueue?.queueId;+ const targetRunId = effectiveQueuedCommentQueue?.targetRunId;+ if (!queueId || !targetRunId)+ throw new Error(+ "The queued message no longer has an active run target.",+ );+ try {+ const nextQueue = await issuesApi.steerQueuedComment(+ issueId,+ commentId,+ {+ queueId,+ targetRunId,+ revision,+ },+ );+ // Keep the message in the composer queue until its durable steering+ // acknowledgement has refreshed. Removing it first briefly projects the+ // comment as an ordinary historical bubble above one unsplit live turn;+ // the later activity refresh then re-sorts it into the middle. Publish+ // the queue removal only after comment + activity placement are ready so+ // the blue bubble enters the timeline once, at its final causal slot.+ await Promise.all([+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.comments(issueId),+ }),+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.activity(issueId),+ }),+ ]);+ storeQueuedCommentQueue(nextQueue);+ setConsumedQueuedCommentIds((current) =>+ new Set(current).add(commentId),+ );+ } catch (error) {+ await refreshQueueAfterConflict(error);+ }+ },+ [+ effectiveQueuedCommentQueue?.queueId,+ effectiveQueuedCommentQueue?.targetRunId,+ issueId,+ queryClient,+ refreshQueueAfterConflict,+ storeQueuedCommentQueue,+ ],+ );++ const discardQueuedComment = useCallback(+ async (commentId: string, revision: string) => {+ const queueId = effectiveQueuedCommentQueue?.queueId;+ if (!queueId)+ throw new Error(+ "The queued message is awaiting server acknowledgement.",+ );+ try {+ storeQueuedCommentQueue(+ await issuesApi.discardQueuedComment(issueId, commentId, {+ queueId,+ revision,+ }),+ );+ setDiscardedQueuedCommentIds((current) =>+ new Set(current).add(commentId),+ );+ await queryClient.invalidateQueries({+ queryKey: queryKeys.issues.comments(issueId),+ });+ } catch (error) {+ const responseBody =+ error instanceof ApiError &&+ typeof error.body === "object" &&+ error.body !== null+ ? (error.body as { code?: unknown; details?: unknown })+ : null;+ const details =+ responseBody &&+ typeof responseBody.details === "object" &&+ responseBody.details !== null+ ? (responseBody.details as { code?: unknown })+ : null;+ const code =+ typeof details?.code === "string"+ ? details.code+ : typeof responseBody?.code === "string"+ ? responseBody.code+ : null;+ if (code === "queued_comment_already_dispatching") {+ pushToast({+ title: "Message is already being sent",+ body: "The continuation started before the discard was confirmed, so Paperclip could not unsend it.",+ tone: "error",+ ttlMs: 15_000,+ dedupeKey: `queued-comment-already-dispatching:${issueId}:${commentId}`,+ });+ }+ await refreshQueueAfterConflict(error);+ }+ },+ [+ effectiveQueuedCommentQueue?.queueId,+ issueId,+ pushToast,+ queryClient,+ refreshQueueAfterConflict,+ storeQueuedCommentQueue,+ ],+ );+const timelineEvents = useMemo(() => extractIssueTimelineEvents(resolvedActivity),[resolvedActivity],@@ -1294,17 +2068,27 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({disabled={commentsLoadingOlder}onClick={onLoadOlderComments}>- {commentsLoadingOlder ? "Loading earlier comments..." : "Load earlier comments"}+ {commentsLoadingOlder+ ? "Loading earlier comments..."+ : "Load earlier comments"}</Button></div>) : null;return (- <div className={classicTaskInterfaceEnabled ? "space-y-3" : "flex min-h-0 flex-1 flex-col"}>+ <div+ className={+ classicTaskInterfaceEnabled+ ? "space-y-3"+ : "flex min-h-0 flex-1 flex-col"+ }+ >{/* Chat-style: the button rides inside the thread's scroll viewport withthe header so nothing sits above the thread in the page flow. */}{classicTaskInterfaceEnabled ? loadOlderButton : null}- {commentsInitialLoading && commentsWithRunMeta.length === 0 && interactions.length === 0 ? (+ {commentsInitialLoading &&+ commentsWithRunMeta.length === 0 &&+ interactions.length === 0 ? (classicTaskInterfaceEnabled ? (<IssueChatSkeleton />) : (@@ -1316,101 +2100,123 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({</div>)) : (- <ThreadComponent- composerRef={composerRef}- composerAccessory={composerAccessory}- threadHeader={- !classicTaskInterfaceEnabled && (threadHeader || loadOlderButton) ? (- <>- {threadHeader}- {loadOlderButton}- </>- ) : undefined- }- issueBrief={issueBrief}- comments={commentsWithRunMeta}- interactions={interactions}- feedbackVotes={feedbackVotes}- feedbackDataSharingPreference={feedbackDataSharingPreference}- feedbackTermsUrl={feedbackTermsUrl}- linkedRuns={timelineRuns}- timelineEvents={timelineEvents}- workModeChanges={workModeChanges}- liveRuns={resolvedLiveRuns}- activeRun={resolvedActiveRun}- issueId={issueId}- blockedBy={blockedBy ?? []}- liveIssueIds={liveIssueIds}- blockerAttention={blockerAttention}- successfulRunHandoff={successfulRunHandoff}- scheduledRetry={scheduledRetry}- recoveryAction={recoveryAction ?? null}- onResolveRecoveryAction={onResolveRecoveryAction}- onReissueIsolatedRecoveryAction={onReissueIsolatedRecoveryAction}- reissueIsolatedRecoveryActionPending={reissueIsolatedRecoveryActionPending}- onReconcileForwardRecoveryAction={onReconcileForwardRecoveryAction}- onBreakGlassOverrideRecoveryAction={onBreakGlassOverrideRecoveryAction}- onQuarantineRestoreRecoveryAction={onQuarantineRestoreRecoveryAction}- quarantineRestoreRecoveryActionPending={quarantineRestoreRecoveryActionPending}- canBreakGlassRecoveryAction={canBreakGlassRecoveryAction}- reconcileRecoveryActionPending={reconcileRecoveryActionPending}- canFalsePositiveRecoveryAction={canFalsePositiveRecoveryAction}- legacyRecoverySourceIssue={legacyRecoverySourceIssue ?? null}- companyId={companyId}- projectId={projectId}- issueStatus={issueStatus}- issueAssigneeAgentId={issueAssigneeAgentId}- agentMap={agentMap}- currentUserId={currentUserId}- userLabelMap={userLabelMap}- userProfileMap={userProfileMap}- draftKey={draftKey}- enableReassign- reassignOptions={reassignOptions}- currentAssigneeValue={currentAssigneeValue}- suggestedAssigneeValue={suggestedAssigneeValue}- mentions={mentions}- composerDisabledReason={composerDisabledReason}- composerHint={composerHint}- onVote={onVote}- onAdd={onAdd}- imageUploadHandler={onImageUpload}- onAttachImage={onAttachImage}- onInterruptQueued={onInterruptQueued}- onDeleteComment={onDeleteComment}- onCancelQueued={onCancelQueued}- interruptingQueuedRunId={interruptingQueuedRunId}- stoppingRunId={pausingWorkRunId}- onStopRun={onPauseWorkRun}- stopRunLabel="Pause work"- stoppingRunLabel="Pausing..."- stopRunVariant="pause"- runFinalizationActions={runFinalizationActions}- onAcceptInteraction={onAcceptInteraction}- onRejectInteraction={onRejectInteraction}- onSubmitInteractionAnswers={(interaction, answers) =>- onSubmitInteractionAnswers(interaction, answers)- }- onCancelInteraction={onCancelInteraction}- onSubmitInteractionVerdicts={onSubmitInteractionVerdicts}- issueWorkMode={issueWorkMode}- onWorkModeChange={onWorkModeChange}- onCancelRun={interruptibleIssueRun && onPauseWorkRun- ? async () => {- await onPauseWorkRun(interruptibleIssueRun.id);- }- : undefined}- onImageClick={onImageClick}- onRefreshLatestComments={onRefreshLatestComments}- assigneeUserId={assigneeUserId}- onResumeFromBacklog={onResumeFromBacklog}- resumeFromBacklogPending={resumeFromBacklogPending}- onResumeAssignee={onResumeAssignee}- resumeAssigneePending={resumeAssigneePending}- footer={footer}- externalReferences={externalReferences}- linkCaseReferences={linkCaseReferences}- />+ <ThreadComponent+ composerRef={composerRef}+ composerAccessory={composerAccessory}+ threadHeader={+ !classicTaskInterfaceEnabled &&+ (threadHeader || loadOlderButton) ? (+ <>+ {threadHeader}+ {loadOlderButton}+ </>+ ) : undefined+ }+ issueBrief={issueBrief}+ comments={commentsForThread}+ interactions={interactions}+ documents={documents}+ workProducts={workProducts}+ attachments={attachments}+ feedbackVotes={feedbackVotes}+ feedbackDataSharingPreference={feedbackDataSharingPreference}+ feedbackTermsUrl={feedbackTermsUrl}+ linkedRuns={timelineRuns}+ timelineEvents={timelineEvents}+ workModeChanges={workModeChanges}+ liveRuns={resolvedLiveRuns}+ activeRun={resolvedActiveRun}+ issueId={issueId}+ blockedBy={blockedBy ?? []}+ liveIssueIds={liveIssueIds}+ blockerAttention={blockerAttention}+ successfulRunHandoff={successfulRunHandoff}+ scheduledRetry={scheduledRetry}+ recoveryAction={recoveryAction ?? null}+ onResolveRecoveryAction={onResolveRecoveryAction}+ onReissueIsolatedRecoveryAction={onReissueIsolatedRecoveryAction}+ reissueIsolatedRecoveryActionPending={+ reissueIsolatedRecoveryActionPending+ }+ onReconcileForwardRecoveryAction={onReconcileForwardRecoveryAction}+ onBreakGlassOverrideRecoveryAction={+ onBreakGlassOverrideRecoveryAction+ }+ onQuarantineRestoreRecoveryAction={onQuarantineRestoreRecoveryAction}+ quarantineRestoreRecoveryActionPending={+ quarantineRestoreRecoveryActionPending+ }+ canBreakGlassRecoveryAction={canBreakGlassRecoveryAction}+ reconcileRecoveryActionPending={reconcileRecoveryActionPending}+ canFalsePositiveRecoveryAction={canFalsePositiveRecoveryAction}+ legacyRecoverySourceIssue={legacyRecoverySourceIssue ?? null}+ companyId={companyId}+ projectId={projectId}+ issueStatus={issueStatus}+ issueAssigneeAgentId={issueAssigneeAgentId}+ agentMap={agentMap}+ currentUserId={currentUserId}+ userLabelMap={userLabelMap}+ userProfileMap={userProfileMap}+ draftKey={draftKey}+ enableReassign+ reassignOptions={reassignOptions}+ currentAssigneeValue={currentAssigneeValue}+ suggestedAssigneeValue={suggestedAssigneeValue}+ mentions={mentions}+ composerDisabledReason={composerDisabledReason}+ composerHint={composerHint}+ onVote={onVote}+ onAdd={onAdd}+ imageUploadHandler={onImageUpload}+ onAttachImage={onAttachImage}+ onInterruptQueued={onInterruptQueued}+ queuedCommentQueue={effectiveQueuedCommentQueue}+ onEditQueuedComment={editQueuedComment}+ onReorderQueuedComments={reorderQueuedComments}+ onSteerQueuedComment={steerQueuedComment}+ onDiscardQueuedComment={discardQueuedComment}+ onDeleteComment={onDeleteComment}+ onCancelQueued={onCancelQueued}+ interruptingQueuedRunId={interruptingQueuedRunId}+ stoppingRunId={pausingWorkRunId}+ onStopRun={onPauseWorkRun}+ stopRunLabel="Pause work"+ stoppingRunLabel="Pausing..."+ stopRunVariant="pause"+ runFinalizationActions={runFinalizationActions}+ onAcceptInteraction={onAcceptInteraction}+ onRejectInteraction={onRejectInteraction}+ onSubmitInteractionAnswers={(interaction, answers) =>+ onSubmitInteractionAnswers(interaction, answers)+ }+ onCancelInteraction={onCancelInteraction}+ onSkipInteraction={onSkipInteraction}+ onSubmitInteractionVerdicts={onSubmitInteractionVerdicts}+ issueWorkMode={issueWorkMode}+ onWorkModeChange={onWorkModeChange}+ onCancelRun={+ interruptibleIssueRun && onPauseWorkRun+ ? async () => {+ await onPauseWorkRun(interruptibleIssueRun.id);+ }+ : undefined+ }+ onImageClick={onImageClick}+ onRefreshLatestComments={onRefreshLatestComments}+ assigneeUserId={assigneeUserId}+ onResumeFromBacklog={onResumeFromBacklog}+ resumeFromBacklogPending={resumeFromBacklogPending}+ onResumeAssignee={onResumeAssignee}+ resumeAssigneePending={resumeAssigneePending}+ onTryAgainNoLiveExecutionPath={onTryAgainNoLiveExecutionPath}+ tryAgainNoLiveExecutionPathPending={+ tryAgainNoLiveExecutionPathPending+ }+ footer={footer}+ externalReferences={externalReferences}+ linkCaseReferences={linkCaseReferences}+ />)}</div>);@@ -1425,8 +2231,14 @@ type IssueDetailActivityTabProps = {agentMap: Map<string, Agent>;hasLiveRuns: boolean;currentUserId: string | null;- userProfileMap: Map<string, import("../lib/company-members").CompanyUserProfile>;- pendingApprovalAction: { approvalId: string; action: "approve" | "reject" } | null;+ userProfileMap: Map<+ string,+ import("../lib/company-members").CompanyUserProfile+ >;+ pendingApprovalAction: {+ approvalId: string;+ action: "approve" | "reject";+ } | null;onApprovalAction: (approvalId: string, action: "approve" | "reject") => void;handoffFocusSignal?: number;externalReferences?: MarkdownExternalReferenceMap;@@ -1460,31 +2272,43 @@ function IssueDetailActivityTab({const { data: linkedApprovals } = useQuery({queryKey: queryKeys.issues.approvals(issueId),queryFn: () => issuesApi.listApprovals(issueId),- placeholderData: keepPreviousDataForSameQueryTail<Awaited<ReturnType<typeof issuesApi.listApprovals>>>(issueId),+ placeholderData:+ keepPreviousDataForSameQueryTail<+ Awaited<ReturnType<typeof issuesApi.listApprovals>>+ >(issueId),});const { data: continuationHandoff } = useQuery({- queryKey: queryKeys.issues.document(issueId, ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY),+ queryKey: queryKeys.issues.document(+ issueId,+ ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,+ ),queryFn: async () => {try {- return await issuesApi.getDocument(issueId, ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY);+ return await issuesApi.getDocument(+ issueId,+ ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,+ );} catch (error) {if (error instanceof ApiError && error.status === 404) return null;throw error;}},retry: false,- placeholderData: keepPreviousDataForSameQueryTail<Awaited<ReturnType<typeof issuesApi.getDocument>> | null>(- issueId,- ),+ placeholderData: keepPreviousDataForSameQueryTail<Awaited<+ ReturnType<typeof issuesApi.getDocument>+ > | null>(issueId),});const { data: issueTreeCostSummary } = useQuery({queryKey: queryKeys.issues.costSummary(issueId),queryFn: () => issuesApi.getCostSummary(issueId),- placeholderData: keepPreviousDataForSameQueryTail<Awaited<ReturnType<typeof issuesApi.getCostSummary>>>(issueId),+ placeholderData:+ keepPreviousDataForSameQueryTail<+ Awaited<ReturnType<typeof issuesApi.getCostSummary>>+ >(issueId),});const initialLoading =- (activityLoading && activity === undefined)- || (linkedRunsLoading && linkedRuns === undefined);+ (activityLoading && activity === undefined) ||+ (linkedRunsLoading && linkedRuns === undefined);const issueCostSummary = useMemo(() => {let input = 0;let output = 0;@@ -1517,8 +2341,14 @@ function IssueDetailActivityTab({if (run.startedAt) {const startMs = new Date(run.startedAt).getTime();- const endMs = run.finishedAt ? new Date(run.finishedAt).getTime() : nowMs;- if (Number.isFinite(startMs) && Number.isFinite(endMs) && endMs >= startMs) {+ const endMs = run.finishedAt+ ? new Date(run.finishedAt).getTime()+ : nowMs;+ if (+ Number.isFinite(startMs) &&+ Number.isFinite(endMs) &&+ endMs >= startMs+ ) {runtimeMs += endMs - startMs;runCount += 1;}@@ -1539,14 +2369,15 @@ function IssueDetailActivityTab({};}, [linkedRuns]);const issueTreeCostTokens =- (issueTreeCostSummary?.inputTokens ?? 0) + (issueTreeCostSummary?.outputTokens ?? 0);+ (issueTreeCostSummary?.inputTokens ?? 0) ++ (issueTreeCostSummary?.outputTokens ?? 0);const hasIssueTreeCost =- !!issueTreeCostSummary- && (issueTreeCostSummary.costCents > 0- || issueTreeCostTokens > 0- || issueTreeCostSummary.cachedInputTokens > 0- || issueTreeCostSummary.runtimeMs > 0- || issueTreeCostSummary.issueCount > 1);+ !!issueTreeCostSummary &&+ (issueTreeCostSummary.costCents > 0 ||+ issueTreeCostTokens > 0 ||+ issueTreeCostSummary.cachedInputTokens > 0 ||+ issueTreeCostSummary.runtimeMs > 0 ||+ issueTreeCostSummary.issueCount > 1);const shouldShowCostSummary =(linkedRuns && linkedRuns.length > 0) || hasIssueTreeCost;@@ -1558,9 +2389,15 @@ function IssueDetailActivityTab({<>{shouldShowCostSummary && (<div className="mb-3 px-3 py-2 rounded-lg border border-border">- <div className="text-sm font-medium text-muted-foreground mb-1">Cost Summary</div>- {!issueCostSummary.hasCost && !issueCostSummary.hasTokens && !hasIssueTreeCost ? (- <div className="text-xs text-muted-foreground">No cost data yet.</div>+ <div className="text-sm font-medium text-muted-foreground mb-1">+ Cost Summary+ </div>+ {!issueCostSummary.hasCost &&+ !issueCostSummary.hasTokens &&+ !hasIssueTreeCost ? (+ <div className="text-xs text-muted-foreground">+ No cost data yet.+ </div>) : (<div className="space-y-1 text-xs text-muted-foreground tabular-nums"><div className="flex flex-wrap gap-3">@@ -1584,19 +2421,25 @@ function IssueDetailActivityTab({{` (${issueCostSummary.runCount} run${issueCostSummary.runCount === 1 ? "" : "s"})`}</span>) : null}- {!issueCostSummary.hasCost && !issueCostSummary.hasTokens && !issueCostSummary.hasRuntime ? (+ {!issueCostSummary.hasCost &&+ !issueCostSummary.hasTokens &&+ !issueCostSummary.hasRuntime ? (<span>No direct cost data.</span>) : null}</div>{hasIssueTreeCost && issueTreeCostSummary ? (<div className="flex flex-wrap gap-3"><span className="font-medium text-foreground">- Including sub-tasks {(issueTreeCostSummary.costCents / 100).toLocaleString(undefined, {- style: "currency",- currency: "USD",- minimumFractionDigits: 4,- maximumFractionDigits: 4,- })}+ Including sub-tasks{" "}+ {(issueTreeCostSummary.costCents / 100).toLocaleString(+ undefined,+ {+ style: "currency",+ currency: "USD",+ minimumFractionDigits: 4,+ maximumFractionDigits: 4,+ },+ )}</span><span>Tokens {formatTokens(issueTreeCostTokens)}@@ -1610,7 +2453,10 @@ function IssueDetailActivityTab({{` (${issueTreeCostSummary.runCount} run${issueTreeCostSummary.runCount === 1 ? "" : "s"})`}</span>) : null}- <span>{issueTreeCostSummary.issueCount} task{issueTreeCostSummary.issueCount === 1 ? "" : "s"}</span>+ <span>+ {issueTreeCostSummary.issueCount} task+ {issueTreeCostSummary.issueCount === 1 ? "" : "s"}+ </span></div>) : null}</div>@@ -1626,39 +2472,74 @@ function IssueDetailActivityTab({agentMap={agentMap}hasLiveRuns={hasLiveRuns}activityEvents={activity ?? []}- resolveUserLabel={(userId) => userProfileMap.get(userId)?.label ?? null}+ resolveUserLabel={(userId) =>+ userProfileMap.get(userId)?.label ?? null+ }renderActivityEvent={(evt) => {const tone = successfulRunHandoffActivityTone(evt.action);const isHandoffWarning =- evt.action === SUCCESSFUL_RUN_HANDOFF_REQUIRED_ACTION- || evt.action === SUCCESSFUL_RUN_HANDOFF_ESCALATED_ACTION;+ evt.action === SUCCESSFUL_RUN_HANDOFF_REQUIRED_ACTION ||+ evt.action === SUCCESSFUL_RUN_HANDOFF_ESCALATED_ACTION;return (- <div className={cn("space-y-1.5 rounded-lg border px-3 py-2 text-xs", tone.className)}>+ <div+ className={cn(+ "space-y-1.5 rounded-lg border px-3 py-2 text-xs",+ tone.className,+ )}+ ><div className="flex items-center gap-1.5">{isHandoffWarning ? (- <AlertTriangle className={cn("h-3.5 w-3.5 shrink-0", tone.iconClassName)} />+ <AlertTriangle+ className={cn("h-3.5 w-3.5 shrink-0", tone.iconClassName)}+ />) : null}- <ActorIdentity evt={evt} agentMap={agentMap} userProfileMap={userProfileMap} />- <span>{formatIssueActivityAction(evt.action, evt.details, { agentMap, userProfileMap, currentUserId })}</span>- <span className="ml-auto shrink-0">{relativeTime(evt.createdAt)}</span>+ <ActorIdentity+ evt={evt}+ agentMap={agentMap}+ userProfileMap={userProfileMap}+ />+ <span>+ {formatIssueActivityAction(evt.action, evt.details, {+ agentMap,+ userProfileMap,+ currentUserId,+ })}+ </span>+ <span className="ml-auto shrink-0">+ {relativeTime(evt.createdAt)}+ </span></div><IssueReferenceActivitySummary event={evt} />{/* Field-level who/what/why receipt for agent and board edits alike. */}<IssueFieldChangeReceiptevent={evt}- resolveAgentLabel={(agentId) => agentMap.get(agentId)?.name ?? null}- resolveUserLabel={(userId) => userProfileMap.get(userId)?.label ?? null}+ resolveAgentLabel={(agentId) =>+ agentMap.get(agentId)?.name ?? null+ }+ resolveUserLabel={(userId) =>+ userProfileMap.get(userId)?.label ?? null+ }/>{/* A refused write explains itself here, not just in the API error. */}{(() => {- const denial = issueWriteDenialForActivity(evt.action, evt.details, {- actorLabel: evt.agentId ? agentMap.get(evt.agentId)?.name ?? null : null,- responsibleUserName: evt.responsibleUserId- ? userProfileMap.get(evt.responsibleUserId)?.label ?? null- : null,- });+ const denial = issueWriteDenialForActivity(+ evt.action,+ evt.details,+ {+ actorLabel: evt.agentId+ ? (agentMap.get(evt.agentId)?.name ?? null)+ : null,+ responsibleUserName: evt.responsibleUserId+ ? (userProfileMap.get(evt.responsibleUserId)?.label ??+ null)+ : null,+ },+ );return denial ? (- <IssueWriteDenialNotice code={denial.code} context={denial.context} />+ <IssueWriteDenialNotice+ code={denial.code}+ context={denial.context}+ />) : null;})()}</div>@@ -1677,7 +2558,11 @@ function IssueDetailActivityTab({<ApprovalCardkey={approval.id}approval={approval}- requesterAgent={approval.requestedByAgentId ? agentMap.get(approval.requestedByAgentId) ?? null : null}+ requesterAgent={+ approval.requestedByAgentId+ ? (agentMap.get(approval.requestedByAgentId) ?? null)+ : null+ }onApprove={() => onApprovalAction(approval.id, "approve")}onReject={() => onApprovalAction(approval.id, "reject")}detailLink={`/approvals/${approval.id}`}@@ -1691,7 +2576,10 @@ function IssueDetailActivityTab({))}</div>)}- <IssueScheduledRetryCard issueId={issue.id} scheduledRetry={issue.scheduledRetry ?? null} />+ <IssueScheduledRetryCard+ issueId={issue.id}+ scheduledRetry={issue.scheduledRetry ?? null}+ />{/* Waiting-monitor state now lives in the pinned top banner (IssueMonitorBanner) — PAP-14557 decision 1. */}</>);@@ -1718,7 +2606,8 @@ export function IssueDetail() {: undefined;const { openNewIssue } = useDialogActions();const { openPanel, closePanel, panelVisible, setPanelVisible } = usePanel();- const { setBreadcrumbs, setMobileToolbar } = useBreadcrumbs();+ const { setBreadcrumbs, setBreadcrumbToolbar, setMobileToolbar } =+ useBreadcrumbs();const queryClient = useQueryClient();const navigate = useNavigate();const navigationType = useNavigationType();@@ -1746,33 +2635,50 @@ export function IssueDetail() {const [galleryOpen, setGalleryOpen] = useState(false);const [galleryIndex, setGalleryIndex] = useState(0);const [treeControlOpen, setTreeControlOpen] = useState(false);- const [treeControlMode, setTreeControlMode] = useState<IssueTreeControlMode>("pause");+ const [treeControlMode, setTreeControlMode] =+ useState<IssueTreeControlMode>("pause");const [treeControlReason, setTreeControlReason] = useState("");- const [treeControlWakeAgentsOnResume, setTreeControlWakeAgentsOnResume] = useState(false);- const [treeControlCancelConfirmed, setTreeControlCancelConfirmed] = useState(false);- const [optimisticComments, setOptimisticComments] = useState<OptimisticIssueComment[]>([]);- const [locallyQueuedCommentRunIds, setLocallyQueuedCommentRunIds] = useState<Map<string, string>>(() => new Map());- const [pendingCommentComposerFocusKey, setPendingCommentComposerFocusKey] = useState(0);+ const [treeControlWakeAgentsOnResume, setTreeControlWakeAgentsOnResume] =+ useState(false);+ const [treeControlCancelConfirmed, setTreeControlCancelConfirmed] =+ useState(false);+ const [optimisticComments, setOptimisticComments] = useState<+ OptimisticIssueComment[]+ >([]);+ const [locallyQueuedCommentRunIds, setLocallyQueuedCommentRunIds] = useState<+ Map<string, string>+ >(() => new Map());+ const [pendingCommentComposerFocusKey, setPendingCommentComposerFocusKey] =+ useState(0);const fileInputRef = useRef<HTMLInputElement | null>(null);const lastMarkedReadIssueIdRef = useRef<string | null>(null);const lastScrollIssueIdRef = useRef<string | undefined>(undefined);const commentComposerRef = useRef<IssueChatComposerHandle | null>(null);const cancelledQueuedOptimisticCommentIdsRef = useRef(new Set<string>());const resolvedIssueDetailState = useMemo(- () => readIssueDetailLocationState(issueId, location.state, location.search),+ () =>+ readIssueDetailLocationState(issueId, location.state, location.search),[issueId, location.state, location.search],);const issueHeaderSeed = useMemo(- () => readIssueDetailHeaderSeed(location.state) ?? readIssueDetailHeaderSeed(resolvedIssueDetailState),+ () =>+ readIssueDetailHeaderSeed(location.state) ??+ readIssueDetailHeaderSeed(resolvedIssueDetailState),[location.state, resolvedIssueDetailState],);- const { data: issue, isLoading, error } = useQuery({+ const {+ data: issue,+ isLoading,+ error,+ } = useQuery({...getIssueDetailQueryOptions(queryClient, issueId!, {- placeholderIssue: issueHeaderSeed ? {- id: issueHeaderSeed.id,- identifier: issueHeaderSeed.identifier,- } : null,+ placeholderIssue: issueHeaderSeed+ ? {+ id: issueHeaderSeed.id,+ identifier: issueHeaderSeed.identifier,+ }+ : null,}),enabled: !!issueId,});@@ -1782,10 +2688,11 @@ export function IssueDetail() {// the workspace when the next comment or resume arrives, so the composer stays// enabled and a hint tells the user what happens.const closedIsolatedWorkspaceReopenPending = useMemo(- () => Boolean(- issue?.currentExecutionWorkspace- && isClosedIsolatedExecutionWorkspace(issue.currentExecutionWorkspace),- ),+ () =>+ Boolean(+ issue?.currentExecutionWorkspace &&+ isClosedIsolatedExecutionWorkspace(issue.currentExecutionWorkspace),+ ),[issue?.currentExecutionWorkspace],);@@ -1808,7 +2715,9 @@ export function IssueDetail() {initialPageParam: null as string | null,getNextPageParam: (lastPage) =>getNextIssueCommentPageParam(lastPage, ISSUE_COMMENT_PAGE_SIZE),- placeholderData: keepPreviousDataForSameQueryTail<InfiniteData<IssueComment[], string | null>>(issueId ?? "pending"),+ placeholderData: keepPreviousDataForSameQueryTail<+ InfiniteData<IssueComment[], string | null>+ >(issueId ?? "pending"),});const comments = useMemo(() => flattenIssueCommentPages(commentPages?.pages),@@ -1826,12 +2735,18 @@ export function IssueDetail() {useEffect(() => {if (!issue) return;- scheduleIssueDetailPaintMeasure(ISSUE_DETAIL_HEADER_PAINT_MARK, ISSUE_DETAIL_HEADER_MEASURE);+ scheduleIssueDetailPaintMeasure(+ ISSUE_DETAIL_HEADER_PAINT_MARK,+ ISSUE_DETAIL_HEADER_MEASURE,+ );}, [issue?.id]);useEffect(() => {if (!issue || commentsLoading) return;- scheduleIssueDetailPaintMeasure(ISSUE_DETAIL_CONTENT_PAINT_MARK, ISSUE_DETAIL_CONTENT_MEASURE);+ scheduleIssueDetailPaintMeasure(+ ISSUE_DETAIL_CONTENT_PAINT_MARK,+ ISSUE_DETAIL_CONTENT_MEASURE,+ );}, [commentsLoading, issue?.id]);const shouldPrefetchOlderComments = useMemo(() =>@@ -1843,47 +2758,72 @@ export function IssueDetail() {olderPageLoading: commentsLoadingOlder,autoLoadLimit: ISSUE_COMMENT_AUTOLOAD_LIMIT,}),- [comments.length, commentsLoading, commentsLoadingOlder, detailTab, hasOlderComments],+ [+ comments.length,+ commentsLoading,+ commentsLoadingOlder,+ detailTab,+ hasOlderComments,+ ],);const { data: interactions = [] } = useQuery({queryKey: queryKeys.issues.interactions(issueId!),queryFn: () => issuesApi.listInteractions(issueId!),enabled: !!issueId,- placeholderData: keepPreviousDataForSameQueryTail<IssueThreadInteraction[]>(issueId ?? "pending"),+ placeholderData: keepPreviousDataForSameQueryTail<IssueThreadInteraction[]>(+ issueId ?? "pending",+ ),});const { data: attachments, isLoading: attachmentsLoading } = useQuery({queryKey: queryKeys.issues.attachments(issueId!),queryFn: () => issuesApi.listAttachments(issueId!),enabled: !!issueId,- placeholderData: keepPreviousDataForSameQueryTail<IssueAttachment[]>(issueId ?? "pending"),+ placeholderData: keepPreviousDataForSameQueryTail<IssueAttachment[]>(+ issueId ?? "pending",+ ),});const { data: workProducts } = useQuery({queryKey: queryKeys.issues.workProducts(issueId!),queryFn: () => issuesApi.listWorkProducts(issueId!),enabled: !!issueId,- placeholderData: keepPreviousDataForSameQueryTail<IssueWorkProduct[]>(issueId ?? "pending"),+ placeholderData: keepPreviousDataForSameQueryTail<IssueWorkProduct[]>(+ issueId ?? "pending",+ ),});- const { data: liveRunCount = 0 } = useQuery<LiveRunForIssue[], Error, number>({- queryKey: queryKeys.issues.liveRuns(issueId!),- queryFn: () => heartbeatsApi.liveRunsForIssue(issueId!),- enabled: !!issueId,- refetchInterval: 3000,- select: (runs) => runs.length,- placeholderData: keepPreviousDataForSameQueryTail<LiveRunForIssue[]>(issueId ?? "pending"),- });+ const { data: liveRunCount = 0 } = useQuery<LiveRunForIssue[], Error, number>(+ {+ queryKey: queryKeys.issues.liveRuns(issueId!),+ queryFn: () => heartbeatsApi.liveRunsForIssue(issueId!),+ enabled: !!issueId,+ refetchInterval: 3000,+ select: (runs) => runs.length,+ placeholderData: keepPreviousDataForSameQueryTail<LiveRunForIssue[]>(+ issueId ?? "pending",+ ),+ },+ );- const { data: hasActiveRun = false } = useQuery<ActiveRunForIssue | null, Error, boolean>({+ const { data: hasActiveRun = false } = useQuery<+ ActiveRunForIssue | null,+ Error,+ boolean+ >({queryKey: queryKeys.issues.activeRun(issueId!),queryFn: () => heartbeatsApi.activeRunForIssue(issueId!),- enabled: !!issueId && (!!issue?.executionRunId || issue?.status === "in_progress"),+ enabled:+ !!issueId && (!!issue?.executionRunId || issue?.status === "in_progress"),refetchInterval: liveRunCount > 0 ? false : 3000,select: (run) => !!run,- placeholderData: keepPreviousDataForSameQueryTail<ActiveRunForIssue | null>(issueId ?? "pending"),+ placeholderData: keepPreviousDataForSameQueryTail<ActiveRunForIssue | null>(+ issueId ?? "pending",+ ),});- const resolvedHasActiveRun = issue ? shouldTrackIssueActiveRun(issue) && hasActiveRun : hasActiveRun;+ const resolvedHasActiveRun = issue+ ? shouldTrackIssueActiveRun(issue) && hasActiveRun+ : hasActiveRun;const hasLiveRuns = liveRunCount > 0 || resolvedHasActiveRun;useEffect(() => {if (!hasLiveRuns && locallyQueuedCommentRunIds.size > 0) {@@ -1891,7 +2831,11 @@ export function IssueDetail() {}}, [hasLiveRuns, locallyQueuedCommentRunIds.size]);const sourceBreadcrumb = useMemo(- () => readIssueDetailBreadcrumb(issueId, location.state, location.search) ?? { label: "Tasks", href: "/issues" },+ () =>+ readIssueDetailBreadcrumb(issueId, location.state, location.search) ?? {+ label: "Tasks",+ href: "/issues",+ },[issueId, location.state, location.search],);@@ -1900,9 +2844,15 @@ export function IssueDetail() {issue?.id && resolvedCompanyId? queryKeys.issues.listByDescendantRoot(resolvedCompanyId, issue.id): ["issues", "parent", "pending"],- queryFn: () => issuesApi.list(resolvedCompanyId!, { descendantOf: issue!.id, includeBlockedBy: true }),+ queryFn: () =>+ issuesApi.list(resolvedCompanyId!, {+ descendantOf: issue!.id,+ includeBlockedBy: true,+ }),enabled: !!resolvedCompanyId && !!issue?.id,- placeholderData: keepPreviousDataForSameQueryTail<Issue[]>(issue?.id ?? "pending"),+ placeholderData: keepPreviousDataForSameQueryTail<Issue[]>(+ issue?.id ?? "pending",+ ),});const rawChildIssues: Issue[] = rawChildIssuesData ?? EMPTY_ISSUES;const {@@ -1914,11 +2864,17 @@ export function IssueDetail() {issue?.parentId && resolvedCompanyId? queryKeys.issues.listByParent(resolvedCompanyId, issue.parentId): ["issues", "siblings", "pending"],- queryFn: () => issuesApi.list(resolvedCompanyId!, { parentId: issue!.parentId!, includeBlockedBy: true }),+ queryFn: () =>+ issuesApi.list(resolvedCompanyId!, {+ parentId: issue!.parentId!,+ includeBlockedBy: true,+ }),enabled: !!resolvedCompanyId && !!issue?.parentId,});const rawSiblingIssues: Issue[] = rawSiblingIssuesData ?? EMPTY_ISSUES;- const companyLiveRunsQueryKey = resolvedCompanyId ? queryKeys.liveRuns(resolvedCompanyId) : ["live-runs", "pending"] as const;+ const companyLiveRunsQueryKey = resolvedCompanyId+ ? queryKeys.liveRuns(resolvedCompanyId)+ : (["live-runs", "pending"] as const);const sharedCompanyLiveRuns = useSharedPollingQuery<LiveRunForIssue[]>({companyId: resolvedCompanyId,resourceKey: "live-runs",@@ -1928,14 +2884,21 @@ export function IssueDetail() {refetchInterval: false,leaderOnly: true,});- const { data: companyLiveRuns, dataUpdatedAt: companyLiveRunsUpdatedAt } = useQuery({- queryKey: companyLiveRunsQueryKey,- queryFn: () => heartbeatsApi.liveRunsForCompany(resolvedCompanyId!),- enabled: sharedCompanyLiveRuns.enabled,- refetchInterval: sharedCompanyLiveRuns.refetchInterval,- placeholderData: keepPreviousDataForSameQueryTail<LiveRunForIssue[]>(resolvedCompanyId ?? "pending"),- });- usePublishSharedQueryData(sharedCompanyLiveRuns, companyLiveRuns, companyLiveRunsUpdatedAt);+ const { data: companyLiveRuns, dataUpdatedAt: companyLiveRunsUpdatedAt } =+ useQuery({+ queryKey: companyLiveRunsQueryKey,+ queryFn: () => heartbeatsApi.liveRunsForCompany(resolvedCompanyId!),+ enabled: sharedCompanyLiveRuns.enabled,+ refetchInterval: sharedCompanyLiveRuns.refetchInterval,+ placeholderData: keepPreviousDataForSameQueryTail<LiveRunForIssue[]>(+ resolvedCompanyId ?? "pending",+ ),+ });+ usePublishSharedQueryData(+ sharedCompanyLiveRuns,+ companyLiveRuns,+ companyLiveRunsUpdatedAt,+ );const { data: agents } = useQuery({queryKey: queryKeys.agents.list(selectedCompanyId!),@@ -1950,11 +2913,20 @@ export function IssueDetail() {// Bounded pool of recently-updated issues to back the `@task` reference picker.// The picker filters this list client-side by identifier/title.const { data: mentionIssues = [] } = useQuery({- queryKey: resolvedCompanyId ? queryKeys.issues.mentionPool(resolvedCompanyId) : ["issues", "mention-pool", "pending"],- queryFn: () => issuesApi.list(resolvedCompanyId!, { limit: 100, sortField: "updated", sortDir: "desc" }),+ queryKey: resolvedCompanyId+ ? queryKeys.issues.mentionPool(resolvedCompanyId)+ : ["issues", "mention-pool", "pending"],+ queryFn: () =>+ issuesApi.list(resolvedCompanyId!, {+ limit: 100,+ sortField: "updated",+ sortDir: "desc",+ }),enabled: !!resolvedCompanyId,staleTime: 60_000,- placeholderData: keepPreviousDataForSameQueryTail<Issue[]>(resolvedCompanyId ?? "pending"),+ placeholderData: keepPreviousDataForSameQueryTail<Issue[]>(+ resolvedCompanyId ?? "pending",+ ),});const { data: session } = useQuery({@@ -1975,13 +2947,18 @@ export function IssueDetail() {retry: false,});const canManageTreeControl = Boolean(- selectedCompanyId- && boardAccess?.companyIds?.includes(selectedCompanyId),+ selectedCompanyId && boardAccess?.companyIds?.includes(selectedCompanyId),+ );+ const canResolveBoardRecoveryAction = canBoardResolveRecoveryAction(+ selectedCompanyId,+ boardAccess,);- const canResolveBoardRecoveryAction = canBoardResolveRecoveryAction(selectedCompanyId, boardAccess);// The break-glass override reconcile is `runtime:manage`-gated server-side, not gated on the// recovery-resolution permission — so hide its affordance behind the matching client check.- const canManageBoardRuntime = canBoardManageRuntime(selectedCompanyId, boardAccess);+ const canManageBoardRuntime = canBoardManageRuntime(+ selectedCompanyId,+ boardAccess,+ );const { data: feedbackVotes } = useQuery({queryKey: queryKeys.issues.feedbackVotes(issueId!),queryFn: () => issuesApi.listFeedbackVotes(issueId!),@@ -1999,13 +2976,16 @@ export function IssueDetail() {enabled: !!issueId,retry: false,});- const keyboardShortcutsEnabled = instanceGeneralSettings?.keyboardShortcuts === true;+ const keyboardShortcutsEnabled =+ instanceGeneralSettings?.keyboardShortcuts === true;// Experimental Cases: linkify `PAP-C7` chips in this issue's comment bodies.const casesChipsEnabled = instanceExperimentalSettings?.enableCases === true;- const feedbackDataSharingPreference = instanceGeneralSettings?.feedbackDataSharingPreference ?? "prompt";+ const feedbackDataSharingPreference =+ instanceGeneralSettings?.feedbackDataSharingPreference ?? "prompt";const showPlanDecompositionsSection =instanceExperimentalSettings?.enableIssuePlanDecompositions === true;- const fileViewerEnabled = instanceExperimentalSettings?.enableExperimentalFileViewer === true;+ const fileViewerEnabled =+ instanceExperimentalSettings?.enableExperimentalFileViewer === true;const { orderedProjects } = useProjectOrder({projects: projects ?? [],companyId: selectedCompanyId,@@ -2018,14 +2998,16 @@ export function IssueDetail() {enabled: !!resolvedCompanyId,});const issuePluginTabItems = useMemo(- () => issuePluginDetailSlots.map((slot) => ({- value: `plugin:${slot.pluginKey}:${slot.id}`,- label: slot.displayName,- slot,- })),+ () =>+ issuePluginDetailSlots.map((slot) => ({+ value: `plugin:${slot.pluginKey}:${slot.id}`,+ label: slot.displayName,+ slot,+ })),[issuePluginDetailSlots],);- const activePluginTab = issuePluginTabItems.find((item) => item.value === detailTab) ?? null;+ const activePluginTab =+ issuePluginTabItems.find((item) => item.value === detailTab) ?? null;const {data: treeControlPreview,isFetching: treeControlPreviewLoading,@@ -2056,7 +3038,12 @@ export function IssueDetail() {retry: false,});const { data: activeRootPauseHolds = [] } = useQuery({- queryKey: ["issues", "tree-holds", issueId ?? "pending", "active-pause-with-members"],+ queryKey: [+ "issues",+ "tree-holds",+ issueId ?? "pending",+ "active-pause-with-members",+ ],queryFn: () =>issuesApi.listTreeHolds(issueId!, {status: "active",@@ -2098,72 +3085,103 @@ export function IssueDetail() {}, [agents, companyMembers?.users, orderedProjects, mentionIssues]);const resolvedProject = useMemo(- () => (issue?.projectId ? orderedProjects.find((project) => project.id === issue.projectId) ?? issue.project ?? null : null),+ () =>+ issue?.projectId+ ? (orderedProjects.find((project) => project.id === issue.projectId) ??+ issue.project ??+ null)+ : null,[issue?.project, issue?.projectId, orderedProjects],);- const childIssues = useMemo(- () => {- const descendants = issue?.id ? filterIssueDescendants(issue.id, rawChildIssues) : rawChildIssues;- return [...descendants].sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());- },- [issue?.id, rawChildIssues],- );+ const childIssues = useMemo(() => {+ const descendants = issue?.id+ ? filterIssueDescendants(issue.id, rawChildIssues)+ : rawChildIssues;+ return [...descendants].sort(+ (a, b) =>+ new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),+ );+ }, [issue?.id, rawChildIssues]);const liveIssueIds = useMemo(- () => collectLiveIssueIds(companyLiveRuns, issue ? [issue, ...childIssues] : childIssues),+ () =>+ collectLiveIssueIds(+ companyLiveRuns,+ issue ? [issue, ...childIssues] : childIssues,+ ),[childIssues, companyLiveRuns, issue],);const issuePanelKey = useMemo(() => buildIssuePropertiesPanelKey(issue ?? null, childIssues),[childIssues, issue],);- const panelIssue = useMemo(- () => issue ?? null,- [issue?.id, issuePanelKey],- );- const panelChildIssues = useMemo(- () => childIssues,- [issuePanelKey],- );- // Onboarding first task only: hide the Properties sidebar until a plan exists,- // then reveal it already on the Plan tab. We gate the panel *mount* (withhold+ const panelIssue = useMemo(() => issue ?? null, [issue?.id, issuePanelKey]);+ const panelChildIssues = useMemo(() => childIssues, [issuePanelKey]);+ // Planning tasks start as chat-only until a plan exists, then reveal the+ // sidebar already on the Plan tab. The onboarding first task keeps the same+ // behavior even if its work mode changes. We gate the panel *mount* (withhold// the panel content) rather than flipping the global `panelVisible` preference// — that preference persists to localStorage and would leak "hidden" into every- // other task. Every non-first task has originKind !== onboarding_first_task, so- // `suppressPanelForFirstTask` stays false and behavior is unchanged. The user- // can still opt in early via the "Show properties" header button, which sets a- // per-issue override (keyed on the issue id so it resets across navigations).+ // other task. The user can still opt in early via the "Show properties" header+ // button, which sets a per-issue override (keyed on the issue id so it resets+ // across navigations).const isOnboardingFirstTask =taskChatShellEnabled &&issue?.originKind === ONBOARDING_FIRST_TASK_ORIGIN_KIND;- const { data: firstTaskPlanDoc } = useIssuePlanDocument(- isOnboardingFirstTask ? issue?.id : null,+ const shouldDeferPanelUntilPlan =+ taskChatShellEnabled &&+ (isOnboardingFirstTask || issue?.workMode === "planning");+ const { data: deferredPanelPlanDoc } = useIssuePlanDocument(+ shouldDeferPanelUntilPlan ? issue?.id : null,+ );+ const [panelBeforePlanOverrideIssueId, setPanelBeforePlanOverrideIssueId] =+ useState<string | null>(null);+ const panelBeforePlanOverride =+ panelBeforePlanOverrideIssueId !== null &&+ panelBeforePlanOverrideIssueId === issue?.id;+ const suppressPanelUntilPlan =+ shouldDeferPanelUntilPlan &&+ !deferredPanelPlanDoc &&+ !panelBeforePlanOverride;+ const openTaskSidePanel = useCallback(() => {+ if (suppressPanelUntilPlan && issue?.id) {+ setPanelBeforePlanOverrideIssueId(issue.id);+ }+ setPanelVisible(true);+ }, [issue?.id, setPanelVisible, suppressPanelUntilPlan]);+ const showRichSubIssuesSection = shouldRenderRichSubIssuesSection(+ childIssuesLoading,+ childIssues.length,);- const [firstTaskPanelOverrideIssueId, setFirstTaskPanelOverrideIssueId] = useState<- string | null- >(null);- const firstTaskPanelOverride =- firstTaskPanelOverrideIssueId !== null && firstTaskPanelOverrideIssueId === issue?.id;- const suppressPanelForFirstTask =- isOnboardingFirstTask && !firstTaskPlanDoc && !firstTaskPanelOverride;- const showRichSubIssuesSection = shouldRenderRichSubIssuesSection(childIssuesLoading, childIssues.length);const siblingNavigation = useMemo(- () => issue && !childIssuesLoading && !siblingIssuesLoading && !siblingIssuesError- ? buildIssueSiblingNavigation(issue, rawSiblingIssues, childIssues)- : null,- [childIssues, childIssuesLoading, issue, rawSiblingIssues, siblingIssuesError, siblingIssuesLoading],+ () =>+ issue &&+ !childIssuesLoading &&+ !siblingIssuesLoading &&+ !siblingIssuesError+ ? buildIssueSiblingNavigation(issue, rawSiblingIssues, childIssues)+ : null,+ [+ childIssues,+ childIssuesLoading,+ issue,+ rawSiblingIssues,+ siblingIssuesError,+ siblingIssuesLoading,+ ],);const openNewSubIssue = useCallback(() => {if (!issue) return;openNewIssue(buildSubIssueDefaultsForViewer(issue, currentUserId));- }, [- currentUserId,- issue,- openNewIssue,- ]);+ }, [currentUserId, issue, openNewIssue]);const commentReassignOptions = useMemo(() => {- const options: Array<{ id: string; label: string; searchText?: string }> = [];- options.push(...buildCompanyUserInlineOptions(companyMembers?.users, { excludeUserIds: [currentUserId] }));+ const options: Array<{ id: string; label: string; searchText?: string }> =+ [];+ options.push(+ ...buildCompanyUserInlineOptions(companyMembers?.users, {+ excludeUserIds: [currentUserId],+ }),+ );const activeAgents = [...(agents ?? [])].filter(isAgentTaskTarget).sort((a, b) => a.name.localeCompare(b.name));@@ -2196,7 +3214,8 @@ export function IssueDetail() {[comments, optimisticComments],);const breadcrumbTitle = issue?.title ?? issueId ?? "Task";- const breadcrumbIdentifier = issue?.identifier ?? issueHeaderSeed?.identifier ?? undefined;+ const breadcrumbIdentifier =+ issue?.identifier ?? issueHeaderSeed?.identifier ?? undefined;const breadcrumbStatus = issue?.status;const breadcrumbBlockerAttention = issue?.blockerAttention;// Stable identity for the breadcrumb status glyph. The glyph's shape/colour@@ -2209,7 +3228,11 @@ export function IssueDetail() {const breadcrumbStatusLeading = useMemo(() =>breadcrumbStatus ? (- <StatusIcon status={breadcrumbStatus} size="lg" blockerAttention={breadcrumbBlockerAttention} />+ <StatusIcon+ status={breadcrumbStatus}+ size="lg"+ blockerAttention={breadcrumbBlockerAttention}+ />) : undefined,// `breadcrumbStatusKey` is a complete signature of the inputs below.// eslint-disable-next-line react-hooks/exhaustive-deps@@ -2226,61 +3249,97 @@ export function IssueDetail() {const invalidateIssueDetail = useCallback(() => {for (const ref of issueCacheRefs) {queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(ref) });- queryClient.invalidateQueries({ queryKey: queryKeys.issues.activity(ref) });- queryClient.invalidateQueries({ queryKey: queryKeys.issues.interactions(ref) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.activity(ref),+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.interactions(ref),+ });}}, [issueCacheRefs, queryClient]);const invalidateIssueThreadLazily = useCallback(() => {for (const ref of issueCacheRefs) {- queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(ref), refetchType: "inactive" });- queryClient.invalidateQueries({ queryKey: queryKeys.issues.activity(ref), refetchType: "inactive" });- queryClient.invalidateQueries({ queryKey: queryKeys.issues.interactions(ref), refetchType: "inactive" });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.detail(ref),+ refetchType: "inactive",+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.activity(ref),+ refetchType: "inactive",+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.interactions(ref),+ refetchType: "inactive",+ });}}, [issueCacheRefs, queryClient]);const invalidateIssueRunState = useCallback(() => {for (const ref of issueCacheRefs) {queryClient.invalidateQueries({ queryKey: queryKeys.issues.runs(ref) });- queryClient.invalidateQueries({ queryKey: queryKeys.issues.liveRuns(ref) });- queryClient.invalidateQueries({ queryKey: queryKeys.issues.activeRun(ref) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.liveRuns(ref),+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.activeRun(ref),+ });}}, [issueCacheRefs, queryClient]);const invalidateIssueDocumentAnnotationState = useCallback(() => {- queryClient.invalidateQueries({ queryKey: ["issues", "document-annotations", issueId!] });- queryClient.invalidateQueries({ queryKey: queryKeys.issues.documents(issueId!) });+ queryClient.invalidateQueries({+ queryKey: ["issues", "document-annotations", issueId!],+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.documents(issueId!),+ });}, [issueId, queryClient]);- const removeCommentFromCache = useCallback((commentId: string) => {- queryClient.setQueryData<InfiniteData<IssueComment[], string | null> | undefined>(- queryKeys.issues.comments(issueId!),- (current) => {+ const removeCommentFromCache = useCallback(+ (commentId: string) => {+ queryClient.setQueryData<+ InfiniteData<IssueComment[], string | null> | undefined+ >(queryKeys.issues.comments(issueId!), (current) => {if (!current) return current;return {...current,pages: removeIssueCommentFromPages(current.pages, commentId),};- },- );- }, [issueId, queryClient]);-- const clearCommentHashIfCurrent = useCallback((commentId: string) => {- if (typeof window === "undefined") return;- if (window.location.hash !== `#comment-${commentId}`) return;- window.history.replaceState(null, "", `${location.pathname}${location.search}`);- }, [location.pathname, location.search]);+ });+ },+ [issueId, queryClient],+ );- const upsertCommentInCache = useCallback((comment: IssueComment) => {- for (const ref of issueCacheRefs) {- queryClient.setQueryData<InfiniteData<IssueComment[], string | null> | undefined>(- queryKeys.issues.comments(ref),- (current) => current ? {- ...current,- pages: upsertIssueCommentInPages(current.pages, comment),- } : current,+ const clearCommentHashIfCurrent = useCallback(+ (commentId: string) => {+ if (typeof window === "undefined") return;+ if (window.location.hash !== `#comment-${commentId}`) return;+ window.history.replaceState(+ null,+ "",+ `${location.pathname}${location.search}`,);- }- }, [issueCacheRefs, queryClient]);+ },+ [location.pathname, location.search],+ );++ const upsertCommentInCache = useCallback(+ (comment: IssueComment) => {+ for (const ref of issueCacheRefs) {+ queryClient.setQueryData<+ InfiniteData<IssueComment[], string | null> | undefined+ >(queryKeys.issues.comments(ref), (current) =>+ current+ ? {+ ...current,+ pages: upsertIssueCommentInPages(current.pages, comment),+ }+ : current,+ );+ }+ },+ [issueCacheRefs, queryClient],+ );const restoreQueuedCommentDraft = useCallback((body: string) => {commentComposerRef.current?.restoreDraft(body);@@ -2288,147 +3347,221 @@ export function IssueDetail() {const invalidateIssueCollections = useCallback(() => {if (selectedCompanyId) {- queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(selectedCompanyId) });- queryClient.invalidateQueries({ queryKey: queryKeys.issues.listMineByMe(selectedCompanyId) });- queryClient.invalidateQueries({ queryKey: queryKeys.issues.listTouchedByMe(selectedCompanyId) });- queryClient.invalidateQueries({ queryKey: queryKeys.issues.listUnreadTouchedByMe(selectedCompanyId) });- queryClient.invalidateQueries({ queryKey: queryKeys.sidebarBadges(selectedCompanyId) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.list(selectedCompanyId),+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.listMineByMe(selectedCompanyId),+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.listTouchedByMe(selectedCompanyId),+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.listUnreadTouchedByMe(selectedCompanyId),+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.sidebarBadges(selectedCompanyId),+ });}}, [queryClient, selectedCompanyId]);- const undoInboxArchive = useCallback(async (- id: string,- companyId: string | undefined,- previousData: InboxIssueCacheSnapshot,- ) => {- if (companyId) {- await cancelInboxIssueQueries(queryClient, companyId);- clearLocalInboxArchive(companyId, id);- restoreIssueToInboxCaches(queryClient, previousData, id);- }-- try {- await issuesApi.unarchiveFromInbox(id);- pushToast({ title: "Task restored to inbox", tone: "success" });- } catch (error) {- if (companyId) {- beginLocalInboxArchive(companyId, id);- removeIssueFromInboxCaches(queryClient, companyId, id);- boundLocalInboxArchive(companyId, id);- }- pushToast({- title: "Undo failed",- body: error instanceof Error ? error.message : "Unable to restore this task to the inbox",- tone: "error",- });- } finally {+ const undoInboxArchive = useCallback(+ async (+ id: string,+ companyId: string | undefined,+ previousData: InboxIssueCacheSnapshot,+ ) => {if (companyId) {- await invalidateInboxIssueQueries(queryClient, companyId);+ await cancelInboxIssueQueries(queryClient, companyId);+ clearLocalInboxArchive(companyId, id);+ restoreIssueToInboxCaches(queryClient, previousData, id);}- }- }, [pushToast, queryClient]);- const upsertInteractionInCache = useCallback((interaction: IssueThreadInteraction) => {- queryClient.setQueryData<IssueThreadInteraction[] | undefined>(- queryKeys.issues.interactions(issueId!),- (current) => {- const existing = current ?? [];- const next = existing.filter((entry) => entry.id !== interaction.id);- next.push(interaction);- next.sort((left, right) => {- const createdAtDelta =- new Date(left.createdAt).getTime() - new Date(right.createdAt).getTime();- return createdAtDelta === 0 ? left.id.localeCompare(right.id) : createdAtDelta;++ try {+ await issuesApi.unarchiveFromInbox(id);+ pushToast({ title: "Task restored to inbox", tone: "success" });+ } catch (error) {+ if (companyId) {+ beginLocalInboxArchive(companyId, id);+ removeIssueFromInboxCaches(queryClient, companyId, id);+ boundLocalInboxArchive(companyId, id);+ }+ pushToast({+ title: "Undo failed",+ body:+ error instanceof Error+ ? error.message+ : "Unable to restore this task to the inbox",+ tone: "error",});- return next;- },- );- }, [issueId, queryClient]);+ } finally {+ if (companyId) {+ await invalidateInboxIssueQueries(queryClient, companyId);+ }+ }+ },+ [pushToast, queryClient],+ );+ const upsertInteractionInCache = useCallback(+ (interaction: IssueThreadInteraction) => {+ queryClient.setQueryData<IssueThreadInteraction[] | undefined>(+ queryKeys.issues.interactions(issueId!),+ (current) => {+ const existing = current ?? [];+ const next = existing.filter((entry) => entry.id !== interaction.id);+ next.push(interaction);+ next.sort((left, right) => {+ const createdAtDelta =+ new Date(left.createdAt).getTime() -+ new Date(right.createdAt).getTime();+ return createdAtDelta === 0+ ? left.id.localeCompare(right.id)+ : createdAtDelta;+ });+ return next;+ },+ );+ },+ [issueId, queryClient],+ );- const applyOptimisticIssueCacheUpdate = useCallback((refs: Iterable<string>, data: Record<string, unknown>) => {- queryClient.setQueriesData<Issue>(- { queryKey: ["issues", "detail"] },- (cached) => (cached && matchesIssueRef(cached, refs) ? applyOptimisticIssueFieldUpdate(cached, data) : cached),- );+ const applyOptimisticIssueCacheUpdate = useCallback(+ (refs: Iterable<string>, data: Record<string, unknown>) => {+ queryClient.setQueriesData<Issue>(+ { queryKey: ["issues", "detail"] },+ (cached) =>+ cached && matchesIssueRef(cached, refs)+ ? applyOptimisticIssueFieldUpdate(cached, data)+ : cached,+ );- if (!selectedCompanyId) return;- queryClient.setQueryData<Issue[] | undefined>(- queryKeys.issues.list(selectedCompanyId),- (cached) => applyOptimisticIssueFieldUpdateToCollection(cached, refs, data),- );- }, [queryClient, selectedCompanyId]);+ if (!selectedCompanyId) return;+ queryClient.setQueryData<Issue[] | undefined>(+ queryKeys.issues.list(selectedCompanyId),+ (cached) =>+ applyOptimisticIssueFieldUpdateToCollection(cached, refs, data),+ );+ },+ [queryClient, selectedCompanyId],+ );- const mergeIssueResponseIntoCaches = useCallback((refs: Iterable<string>, nextIssue: Issue) => {- queryClient.setQueriesData<Issue>(- { queryKey: ["issues", "detail"] },- (cached) => (cached && matchesIssueRef(cached, refs) ? { ...cached, ...nextIssue } : cached),- );+ const mergeIssueResponseIntoCaches = useCallback(+ (refs: Iterable<string>, nextIssue: Issue) => {+ queryClient.setQueriesData<Issue>(+ { queryKey: ["issues", "detail"] },+ (cached) =>+ cached && matchesIssueRef(cached, refs)+ ? { ...cached, ...nextIssue }+ : cached,+ );- if (!selectedCompanyId) return;- queryClient.setQueryData<Issue[] | undefined>(- queryKeys.issues.list(selectedCompanyId),- (cached) => cached?.map((item) => (matchesIssueRef(item, refs) ? { ...item, ...nextIssue } : item)),- );- }, [queryClient, selectedCompanyId]);+ if (!selectedCompanyId) return;+ queryClient.setQueryData<Issue[] | undefined>(+ queryKeys.issues.list(selectedCompanyId),+ (cached) =>+ cached?.map((item) =>+ matchesIssueRef(item, refs) ? { ...item, ...nextIssue } : item,+ ),+ );+ },+ [queryClient, selectedCompanyId],+ );const markIssueRead = useMutation({mutationFn: (id: string) => issuesApi.markRead(id),onSuccess: () => {if (selectedCompanyId) {- queryClient.invalidateQueries({ queryKey: queryKeys.issues.listMineByMe(selectedCompanyId) });- queryClient.invalidateQueries({ queryKey: queryKeys.issues.listTouchedByMe(selectedCompanyId) });- queryClient.invalidateQueries({ queryKey: queryKeys.issues.listUnreadTouchedByMe(selectedCompanyId) });- queryClient.invalidateQueries({ queryKey: queryKeys.sidebarBadges(selectedCompanyId) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.listMineByMe(selectedCompanyId),+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.listTouchedByMe(selectedCompanyId),+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.listUnreadTouchedByMe(selectedCompanyId),+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.sidebarBadges(selectedCompanyId),+ });}},});const updateIssue = useMutation({- mutationFn: (data: Record<string, unknown>) => issuesApi.update(issueId!, data),+ mutationFn: (data: Record<string, unknown>) =>+ issuesApi.update(issueId!, data),onMutate: async (data) => {- await queryClient.cancelQueries({ queryKey: queryKeys.issues.detail(issueId!) });+ await queryClient.cancelQueries({+ queryKey: queryKeys.issues.detail(issueId!),+ });if (selectedCompanyId) {- await queryClient.cancelQueries({ queryKey: queryKeys.issues.list(selectedCompanyId) });+ await queryClient.cancelQueries({+ queryKey: queryKeys.issues.list(selectedCompanyId),+ });}- const previousIssue = queryClient.getQueryData<Issue>(queryKeys.issues.detail(issueId!));+ const previousIssue = queryClient.getQueryData<Issue>(+ queryKeys.issues.detail(issueId!),+ );const issueRefs = new Set<string>([issueId!]);if (previousIssue?.id) issueRefs.add(previousIssue.id);if (previousIssue?.identifier) issueRefs.add(previousIssue.identifier);const previousDetailQueries = queryClient.getQueriesData<Issue>({ queryKey: ["issues", "detail"] })- .filter(([, cachedIssue]) => cachedIssue && matchesIssueRef(cachedIssue, issueRefs));+ .filter(+ ([, cachedIssue]) =>+ cachedIssue && matchesIssueRef(cachedIssue, issueRefs),+ );const previousList = selectedCompanyId- ? queryClient.getQueryData<Issue[]>(queryKeys.issues.list(selectedCompanyId))+ ? queryClient.getQueryData<Issue[]>(+ queryKeys.issues.list(selectedCompanyId),+ ): undefined;applyOptimisticIssueCacheUpdate(issueRefs, data);return { previousDetailQueries, previousList, selectedCompanyId };},- onSuccess: ({ comment: _comment, changes: _changes, blockedByIssueIds: _blockedByIssueIds, ...nextIssue }) => {+ onSuccess: ({+ comment: _comment,+ changes: _changes,+ blockedByIssueIds: _blockedByIssueIds,+ ...nextIssue+ }) => {const issueRefs = new Set<string>([issueId!, nextIssue.id]);if (nextIssue.identifier) issueRefs.add(nextIssue.identifier);mergeIssueResponseIntoCaches(issueRefs, nextIssue);- queryClient.invalidateQueries({ queryKey: queryKeys.issues.activity(issueId!) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.activity(issueId!),+ });invalidateIssueCollections();},onError: (err, _variables, context) => {- for (const [queryKey, previousIssue] of context?.previousDetailQueries ?? []) {+ for (const [queryKey, previousIssue] of context?.previousDetailQueries ??+ []) {queryClient.setQueryData(queryKey, previousIssue);}if (context?.selectedCompanyId) {- queryClient.setQueryData(queryKeys.issues.list(context.selectedCompanyId), context.previousList);+ queryClient.setQueryData(+ queryKeys.issues.list(context.selectedCompanyId),+ context.previousList,+ );}pushToast({title: "Task update failed",- body: err instanceof Error ? err.message : "Unable to save task changes",+ body:+ err instanceof Error ? err.message : "Unable to save task changes",tone: "error",});},onSettled: () => {- queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(issueId!) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.detail(issueId!),+ });if (selectedCompanyId) {- queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(selectedCompanyId) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.list(selectedCompanyId),+ });}},});@@ -2443,20 +3576,29 @@ export function IssueDetail() {const issueRefs = new Set<string>([issueId!, nextIssue.id]);if (nextIssue.identifier) issueRefs.add(nextIssue.identifier);mergeIssueResponseIntoCaches(issueRefs, nextIssue);- queryClient.invalidateQueries({ queryKey: queryKeys.issues.activity(issueId!) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.activity(issueId!),+ });invalidateIssueCollections();},onError: (err) => {pushToast({title: "Recovery resolution failed",- body: err instanceof Error ? err.message : "Unable to resolve recovery action",+ body:+ err instanceof Error+ ? err.message+ : "Unable to resolve recovery action",tone: "error",});},onSettled: () => {- queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(issueId!) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.detail(issueId!),+ });if (selectedCompanyId) {- queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(selectedCompanyId) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.list(selectedCompanyId),+ });}},});@@ -2465,14 +3607,20 @@ export function IssueDetail() {if (treeControlMode === "resume") {const pauseHoldId = treeControlState?.activePauseHold?.holdId;if (!pauseHoldId) {- throw new Error("No active subtree pause hold is available to resume.");+ throw new Error(+ "No active subtree pause hold is available to resume.",+ );}- const releasedHold = await issuesApi.releaseTreeHold(issueId!, pauseHoldId, {- reason: treeControlReason.trim() || null,- metadata: {- wakeAgents: treeControlWakeAgentsOnResume,+ const releasedHold = await issuesApi.releaseTreeHold(+ issueId!,+ pauseHoldId,+ {+ reason: treeControlReason.trim() || null,+ metadata: {+ wakeAgents: treeControlWakeAgentsOnResume,+ },},- });+ );return { kind: "release" as const, hold: releasedHold };}const created = await issuesApi.createTreeHold(issueId!, {@@ -2480,54 +3628,102 @@ export function IssueDetail() {reason: treeControlReason.trim() || null,releasePolicy: {strategy: "manual",- ...(treeControlMode === "pause" ? { note: treeControlScope === "leaf" ? "leaf_pause" : "full_pause" } : {}),+ ...(treeControlMode === "pause"+ ? {+ note: treeControlScope === "leaf" ? "leaf_pause" : "full_pause",+ }+ : {}),},...(treeControlMode === "restore"? { metadata: { wakeAgents: treeControlWakeAgentsOnResume } }: {}),});- return { kind: "create" as const, hold: created.hold, preview: created.preview };+ return {+ kind: "create" as const,+ hold: created.hold,+ preview: created.preview,+ };},onSuccess: async (result) => {- const modeLabel = issueTreeControlLabel(result.hold.mode, treeControlScope);+ const modeLabel = issueTreeControlLabel(+ result.hold.mode,+ treeControlScope,+ );const cancelCount = result.preview?.totals.activeRuns ?? 0;pushToast({- title: result.kind === "release"- ? treeControlScope === "leaf" ? "Work resumed" : "Subtree resumed"- : result.hold.mode === "pause"- ? treeControlScope === "leaf" ? "Work paused" : "Subtree paused"- : `${modeLabel} applied`,- body: result.kind === "release"- ? (result.hold.releaseReason?.trim() || (treeControlScope === "leaf" ? "Active task pause released." : "Active subtree pause released."))- : result.hold.mode === "pause"+ title:+ result.kind === "release"? treeControlScope === "leaf"- ? `Work paused. ${cancelCount} run${cancelCount === 1 ? "" : "s"} cancelled.`- : `Subtree paused. ${cancelCount} run${cancelCount === 1 ? "" : "s"} cancelled.`- : result.hold.reason?.trim()- ? result.hold.reason- : "Subtree control applied.",+ ? "Work resumed"+ : "Subtree resumed"+ : result.hold.mode === "pause"+ ? treeControlScope === "leaf"+ ? "Work paused"+ : "Subtree paused"+ : `${modeLabel} applied`,+ body:+ result.kind === "release"+ ? result.hold.releaseReason?.trim() ||+ (treeControlScope === "leaf"+ ? "Active task pause released."+ : "Active subtree pause released.")+ : result.hold.mode === "pause"+ ? treeControlScope === "leaf"+ ? `Work paused. ${cancelCount} run${cancelCount === 1 ? "" : "s"} cancelled.`+ : `Subtree paused. ${cancelCount} run${cancelCount === 1 ? "" : "s"} cancelled.`+ : result.hold.reason?.trim()+ ? result.hold.reason+ : "Subtree control applied.",});setTreeControlOpen(false);setTreeControlReason("");setTreeControlWakeAgentsOnResume(false);setTreeControlCancelConfirmed(false);await Promise.all([- queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(issueId!) }),- queryClient.invalidateQueries({ queryKey: queryKeys.issues.activity(issueId!) }),- queryClient.invalidateQueries({ queryKey: queryKeys.issues.liveRuns(issueId!) }),- queryClient.invalidateQueries({ queryKey: queryKeys.issues.activeRun(issueId!) }),- queryClient.invalidateQueries({ queryKey: queryKeys.issues.runs(issueId!) }),- queryClient.invalidateQueries({ queryKey: ["issues", "tree-control-state", issueId ?? "pending"] }),- queryClient.invalidateQueries({ queryKey: ["issues", "tree-holds", issueId ?? "pending"] }),- queryClient.invalidateQueries({ queryKey: ["issues", "tree-control-preview", issueId ?? "pending"] }),+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.detail(issueId!),+ }),+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.activity(issueId!),+ }),+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.liveRuns(issueId!),+ }),+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.activeRun(issueId!),+ }),+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.runs(issueId!),+ }),+ queryClient.invalidateQueries({+ queryKey: ["issues", "tree-control-state", issueId ?? "pending"],+ }),+ queryClient.invalidateQueries({+ queryKey: ["issues", "tree-holds", issueId ?? "pending"],+ }),+ queryClient.invalidateQueries({+ queryKey: ["issues", "tree-control-preview", issueId ?? "pending"],+ }),]);if (selectedCompanyId) {await Promise.all([- queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(selectedCompanyId) }),+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.list(selectedCompanyId),+ }),...(issue?.id? [- queryClient.invalidateQueries({ queryKey: queryKeys.issues.listByParent(selectedCompanyId, issue.id) }),- queryClient.invalidateQueries({ queryKey: queryKeys.issues.listByDescendantRoot(selectedCompanyId, issue.id) }),+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.listByParent(+ selectedCompanyId,+ issue.id,+ ),+ }),+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.listByDescendantRoot(+ selectedCompanyId,+ issue.id,+ ),+ }),]: []),]);@@ -2542,11 +3738,20 @@ export function IssueDetail() {},});const pauseIssueWorkRun = useMutation({- mutationFn: async ({ runId, scope }: { runId: string; scope: "leaf" | "subtree" }) => {+ mutationFn: async ({+ runId,+ scope,+ }: {+ runId: string;+ scope: "leaf" | "subtree";+ }) => {const created = await issuesApi.createTreeHold(issueId!, {mode: "pause",reason: "Paused from active run controls.",- releasePolicy: { strategy: "manual", note: scope === "leaf" ? "leaf_pause" : "full_pause" },+ releasePolicy: {+ strategy: "manual",+ note: scope === "leaf" ? "leaf_pause" : "full_pause",+ },metadata: { source: "issue_active_run_control", runId },});return created;@@ -2555,20 +3760,37 @@ export function IssueDetail() {const cancelCount = result.preview?.totals.activeRuns ?? 0;pushToast({title: "Work paused",- body: cancelCount > 0- ? `Work paused. ${cancelCount} run${cancelCount === 1 ? "" : "s"} cancelled.`- : "Work paused. This task is held until resume.",+ body:+ cancelCount > 0+ ? `Work paused. ${cancelCount} run${cancelCount === 1 ? "" : "s"} cancelled.`+ : "Work paused. This task is held until resume.",tone: "success",});await Promise.all([- queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(issueId!) }),- queryClient.invalidateQueries({ queryKey: queryKeys.issues.activity(issueId!) }),- queryClient.invalidateQueries({ queryKey: queryKeys.issues.liveRuns(issueId!) }),- queryClient.invalidateQueries({ queryKey: queryKeys.issues.activeRun(issueId!) }),- queryClient.invalidateQueries({ queryKey: queryKeys.issues.runs(issueId!) }),- queryClient.invalidateQueries({ queryKey: ["issues", "tree-control-state", issueId ?? "pending"] }),- queryClient.invalidateQueries({ queryKey: ["issues", "tree-holds", issueId ?? "pending"] }),- queryClient.invalidateQueries({ queryKey: ["issues", "tree-control-preview", issueId ?? "pending"] }),+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.detail(issueId!),+ }),+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.activity(issueId!),+ }),+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.liveRuns(issueId!),+ }),+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.activeRun(issueId!),+ }),+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.runs(issueId!),+ }),+ queryClient.invalidateQueries({+ queryKey: ["issues", "tree-control-state", issueId ?? "pending"],+ }),+ queryClient.invalidateQueries({+ queryKey: ["issues", "tree-holds", issueId ?? "pending"],+ }),+ queryClient.invalidateQueries({+ queryKey: ["issues", "tree-control-preview", issueId ?? "pending"],+ }),]);invalidateIssueCollections();},@@ -2581,7 +3803,13 @@ export function IssueDetail() {},});const stopAndFinalizeRun = useMutation({- mutationFn: async ({ runId, status }: { runId: string; status: "cancelled" | "done" }) => {+ mutationFn: async ({+ runId,+ status,+ }: {+ runId: string;+ status: "cancelled" | "done";+ }) => {await heartbeatsApi.cancel(runId);try {return await issuesApi.update(issueId!, { status });@@ -2593,11 +3821,16 @@ export function IssueDetail() {const issueRefs = new Set<string>([issueId!, nextIssue.id]);if (nextIssue.identifier) issueRefs.add(nextIssue.identifier);mergeIssueResponseIntoCaches(issueRefs, nextIssue);- queryClient.invalidateQueries({ queryKey: queryKeys.issues.activity(issueId!) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.activity(issueId!),+ });invalidateIssueRunState();invalidateIssueCollections();pushToast({- title: status === "done" ? "Run stopped and task done" : "Run stopped and task cancelled",+ title:+ status === "done"+ ? "Run stopped and task done"+ : "Run stopped and task cancelled",tone: "success",});},@@ -2606,42 +3839,65 @@ export function IssueDetail() {pushToast({title: runWasStopped? "Run stopped; task update failed"- : status === "done" ? "Stop and done failed" : "Stop and cancel failed",- body: err instanceof Error ? err.message : "Unable to stop the run and update the task",+ : status === "done"+ ? "Stop and done failed"+ : "Stop and cancel failed",+ body:+ err instanceof Error+ ? err.message+ : "Unable to stop the run and update the task",tone: "error",});},onSettled: (_data, err) => {- queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(issueId!) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.detail(issueId!),+ });if (err) invalidateIssueRunState();if (selectedCompanyId) {- queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(selectedCompanyId) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.list(selectedCompanyId),+ });}},});- const handleIssuePropertiesUpdate = useCallback((data: Record<string, unknown>) => {- updateIssue.mutate(data);- }, [updateIssue.mutate]);+ const handleIssuePropertiesUpdate = useCallback(+ (data: Record<string, unknown>) => {+ updateIssue.mutate(data);+ },+ [updateIssue.mutate],+ );const updateChildIssue = useMutation({- mutationFn: ({ id, data }: { id: string; data: Record<string, unknown> }) => issuesApi.update(id, data),+ mutationFn: ({ id, data }: { id: string; data: Record<string, unknown> }) =>+ issuesApi.update(id, data),onSuccess: () => {if (resolvedCompanyId) {- queryClient.invalidateQueries({ queryKey: ["issues", resolvedCompanyId] });- queryClient.invalidateQueries({ queryKey: queryKeys.sidebarBadges(resolvedCompanyId) });+ queryClient.invalidateQueries({+ queryKey: ["issues", resolvedCompanyId],+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.sidebarBadges(resolvedCompanyId),+ });}},onError: (err) => {pushToast({title: "Task update failed",- body: err instanceof Error ? err.message : "Unable to save sub-task changes",+ body:+ err instanceof Error+ ? err.message+ : "Unable to save sub-task changes",tone: "error",});},});- const handleChildIssueUpdate = useCallback((id: string, data: Record<string, unknown>) => {- updateChildIssue.mutate({ id, data });- }, [updateChildIssue.mutate]);+ const handleChildIssueUpdate = useCallback(+ (id: string, data: Record<string, unknown>) => {+ updateChildIssue.mutate({ id, data });+ },+ [updateChildIssue.mutate],+ );// PAP-496: the chat shell keeps the full sub-task tree directly below the// title in the center column. This is the tree's single chat-shell home; the@@ -2661,7 +3917,10 @@ export function IssueDetail() {issueLinkState={resolvedIssueDetailState ?? location.state}searchFilters={{ descendantOf: issue.id, includeBlockedBy: true }}searchWithinLoadedIssues- baseCreateIssueDefaults={buildSubIssueDefaultsForViewer(issue, currentUserId)}+ baseCreateIssueDefaults={buildSubIssueDefaultsForViewer(+ issue,+ currentUserId,+ )}createIssueLabel="Sub-task"defaultSortField="workflow"showProgressSummary@@ -2699,14 +3958,23 @@ export function IssueDetail() {onError: (err) => {pushToast({title: "Monitor check failed",- body: err instanceof Error ? err.message : "Unable to trigger the monitor right now",+ body:+ err instanceof Error+ ? err.message+ : "Unable to trigger the monitor right now",tone: "error",});},});const approvalDecision = useMutation({- mutationFn: async ({ approvalId, action }: { approvalId: string; action: "approve" | "reject" }) => {+ mutationFn: async ({+ approvalId,+ action,+ }: {+ approvalId: string;+ action: "approve" | "reject";+ }) => {if (action === "approve") {return approvalsApi.approve(approvalId);}@@ -2717,20 +3985,32 @@ export function IssueDetail() {},onSuccess: (_approval, variables) => {invalidateIssueDetail();- queryClient.invalidateQueries({ queryKey: queryKeys.issues.approvals(issueId!) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.approvals(issueId!),+ });invalidateIssueCollections();- queryClient.invalidateQueries({ queryKey: queryKeys.approvals.detail(variables.approvalId) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.approvals.detail(variables.approvalId),+ });if (resolvedCompanyId) {- queryClient.invalidateQueries({ queryKey: queryKeys.approvals.list(resolvedCompanyId) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.approvals.list(resolvedCompanyId),+ });}pushToast({- title: variables.action === "approve" ? "Approval approved" : "Approval rejected",+ title:+ variables.action === "approve"+ ? "Approval approved"+ : "Approval rejected",tone: "success",});},onError: (err, variables) => {pushToast({- title: variables.action === "approve" ? "Approval failed" : "Rejection failed",+ title:+ variables.action === "approve"+ ? "Approval failed"+ : "Rejection failed",body: err instanceof Error ? err.message : "Unable to update approval",tone: "error",});@@ -2741,15 +4021,33 @@ export function IssueDetail() {});const addComment = useMutation({- mutationFn: ({ body, reopen, interrupt }: { body: string; reopen?: boolean; interrupt?: boolean }) =>- issuesApi.addComment(issueId!, body, reopen, interrupt),+ mutationFn: ({+ body,+ reopen,+ interrupt,+ }: {+ body: string;+ reopen?: boolean;+ interrupt?: boolean;+ }) => issuesApi.addComment(issueId!, body, reopen, interrupt),onMutate: async ({ body, reopen, interrupt }) => {- await queryClient.cancelQueries({ queryKey: queryKeys.issues.comments(issueId!) });- await queryClient.cancelQueries({ queryKey: queryKeys.issues.detail(issueId!) });+ // Start cache cancellation immediately but do not put it in front of the+ // optimistic echo. The new-runner startup placeholder must paint in the+ // same frame as send, even when an in-flight comments query is slow to+ // cancel.+ const cancelComments = queryClient.cancelQueries({+ queryKey: queryKeys.issues.comments(issueId!),+ });+ const cancelIssue = queryClient.cancelQueries({+ queryKey: queryKeys.issues.detail(issueId!),+ });- const previousIssue = queryClient.getQueryData<Issue>(queryKeys.issues.detail(issueId!));+ const previousIssue = queryClient.getQueryData<Issue>(+ queryKeys.issues.detail(issueId!),+ );const queuedComment = !interrupt- ? readIssueRunStateFromCache(queryClient, issueId!, issue).interruptibleIssueRun+ ? readIssueRunStateFromCache(queryClient, issueId!, issue)+ .interruptibleIssueRun: null;const optimisticComment = issue? createOptimisticIssueComment({@@ -2772,6 +4070,8 @@ export function IssueDetail() {);}+ await Promise.all([cancelComments, cancelIssue]);+return {optimisticCommentId: optimisticComment?.clientId ?? null,queuedCommentTargetRunId: queuedComment?.id ?? null,@@ -2779,13 +4079,20 @@ export function IssueDetail() {};},onSuccess: async (comment, _variables, context) => {- if (context?.optimisticCommentId) {+ if (+ context?.optimisticCommentId &&+ cancelledQueuedOptimisticCommentIdsRef.current.has(+ context.optimisticCommentId,+ )+ ) {+ cancelledQueuedOptimisticCommentIdsRef.current.delete(+ context.optimisticCommentId,+ );setOptimisticComments((current) =>- current.filter((entry) => entry.clientId !== context.optimisticCommentId),+ current.filter(+ (entry) => entry.clientId !== context.optimisticCommentId,+ ),);- }- if (context?.optimisticCommentId && cancelledQueuedOptimisticCommentIdsRef.current.has(context.optimisticCommentId)) {- cancelledQueuedOptimisticCommentIdsRef.current.delete(context.optimisticCommentId);try {await issuesApi.cancelComment(issueId!, comment.id);invalidateIssueDetail();@@ -2795,7 +4102,10 @@ export function IssueDetail() {} catch (err) {pushToast({title: "Cancel failed",- body: err instanceof Error ? err.message : "Unable to cancel the queued comment",+ body:+ err instanceof Error+ ? err.message+ : "Unable to cancel the queued comment",tone: "error",});}@@ -2809,23 +4119,38 @@ export function IssueDetail() {}queryClient.setQueryData<InfiniteData<IssueComment[], string | null>>(queryKeys.issues.comments(issueId!),- (current) => current ? {- ...current,- pages: upsertIssueCommentInPages(current.pages, comment),- } : {- pageParams: [null],- pages: upsertIssueCommentInPages(undefined, comment),- },+ (current) =>+ current+ ? {+ ...current,+ pages: upsertIssueCommentInPages(current.pages, comment),+ }+ : {+ pageParams: [null],+ pages: upsertIssueCommentInPages(undefined, comment),+ },);+ if (context?.optimisticCommentId) {+ setOptimisticComments((current) =>+ current.filter(+ (entry) => entry.clientId !== context.optimisticCommentId,+ ),+ );+ }},onError: (err, _variables, context) => {if (context?.optimisticCommentId) {setOptimisticComments((current) =>- current.filter((entry) => entry.clientId !== context.optimisticCommentId),+ current.filter(+ (entry) => entry.clientId !== context.optimisticCommentId,+ ),);}if (context?.previousIssue) {- queryClient.setQueryData(queryKeys.issues.detail(issueId!), context.previousIssue);+ queryClient.setQueryData(+ queryKeys.issues.detail(issueId!),+ context.previousIssue,+ );}pushToast({title: "Comment failed",@@ -2852,55 +4177,82 @@ export function IssueDetail() {interaction: ActionableIssueThreadInteraction;selectedClientKeys?: string[];selectedOptionIds?: string[];- }) => issuesApi.acceptInteraction(issueId!, interaction.id, { selectedClientKeys, selectedOptionIds }),+ }) =>+ issuesApi.acceptInteraction(issueId!, interaction.id, {+ selectedClientKeys,+ selectedOptionIds,+ }),onSuccess: (interaction) => {upsertInteractionInCache(interaction);- if (interaction.kind === "suggest_tasks" && resolvedCompanyId && issue?.id) {- queryClient.invalidateQueries({ queryKey: queryKeys.issues.listByParent(resolvedCompanyId, issue.id) });+ if (+ interaction.kind === "suggest_tasks" &&+ resolvedCompanyId &&+ issue?.id+ ) {+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.listByParent(resolvedCompanyId, issue.id),+ });}invalidateIssueDetail();invalidateIssueCollections();- const createdCount = interaction.kind === "suggest_tasks"- ? interaction.result?.createdTasks?.length ?? 0- : 0;- const skippedCount = interaction.kind === "suggest_tasks"- ? interaction.result?.skippedClientKeys?.length ?? 0- : 0;+ const createdCount =+ interaction.kind === "suggest_tasks"+ ? (interaction.result?.createdTasks?.length ?? 0)+ : 0;+ const skippedCount =+ interaction.kind === "suggest_tasks"+ ? (interaction.result?.skippedClientKeys?.length ?? 0)+ : 0;pushToast({- title: interaction.kind === "request_confirmation"- ? "Request confirmed"- : interaction.kind === "request_checkbox_confirmation"- ? "Selection confirmed"- : skippedCount > 0- ? `Accepted ${createdCount} draft${createdCount === 1 ? "" : "s"} and skipped ${skippedCount}`- : "Suggested tasks accepted",+ title:+ interaction.kind === "request_confirmation"+ ? "Request confirmed"+ : interaction.kind === "request_checkbox_confirmation"+ ? "Selection confirmed"+ : skippedCount > 0+ ? `Accepted ${createdCount} draft${createdCount === 1 ? "" : "s"} and skipped ${skippedCount}`+ : "Suggested tasks accepted",tone: "success",});},onError: (err) => {pushToast({title: "Accept failed",- body: err instanceof Error ? err.message : "Unable to accept the suggested tasks",+ body:+ err instanceof Error+ ? err.message+ : "Unable to accept the suggested tasks",tone: "error",});},});const rejectInteraction = useMutation({- mutationFn: ({ interaction, reason }: { interaction: ActionableIssueThreadInteraction; reason?: string }) =>- issuesApi.rejectInteraction(issueId!, interaction.id, reason),+ mutationFn: ({+ interaction,+ reason,+ }: {+ interaction: ActionableIssueThreadInteraction;+ reason?: string;+ }) => issuesApi.rejectInteraction(issueId!, interaction.id, reason),onSuccess: (interaction) => {upsertInteractionInCache(interaction);invalidateIssueDetail();invalidateIssueCollections();pushToast({- title: interaction.kind === "request_confirmation" ? "Request declined" : "Suggestion rejected",+ title:+ interaction.kind === "request_confirmation"+ ? "Request declined"+ : "Suggestion rejected",tone: "success",});},onError: (err) => {pushToast({title: "Reject failed",- body: err instanceof Error ? err.message : "Unable to reject the suggested tasks",+ body:+ err instanceof Error+ ? err.message+ : "Unable to reject the suggested tasks",tone: "error",});},@@ -2937,16 +4289,22 @@ export function IssueDetail() {verdicts,}: {interaction: RequestItemVerdictsInteraction;- verdicts: { id: string; verdict: RequestItemVerdictValue; reason?: string }[];- }) => issuesApi.submitInteractionVerdicts(issueId!, interaction.id, verdicts),+ verdicts: {+ id: string;+ verdict: RequestItemVerdictValue;+ reason?: string;+ }[];+ }) =>+ issuesApi.submitInteractionVerdicts(issueId!, interaction.id, verdicts),onSuccess: (interaction, variables) => {upsertInteractionInCache(interaction);invalidateIssueDetail();invalidateIssueCollections();const applied = variables.verdicts.length;- const complete = interaction.kind === "request_item_verdicts"- ? interaction.result?.complete ?? false- : false;+ const complete =+ interaction.kind === "request_item_verdicts"+ ? (interaction.result?.complete ?? false)+ : false;pushToast({title: complete? "All verdicts applied"@@ -2957,15 +4315,19 @@ export function IssueDetail() {onError: (err) => {pushToast({title: "Apply failed",- body: err instanceof Error ? err.message : "Unable to apply the verdicts",+ body:+ err instanceof Error ? err.message : "Unable to apply the verdicts",tone: "error",});},});const cancelInteraction = useMutation({- mutationFn: ({ interaction }: { interaction: AskUserQuestionsInteraction }) =>- issuesApi.cancelInteraction(issueId!, interaction.id),+ mutationFn: ({+ interaction,+ }: {+ interaction: AskUserQuestionsInteraction;+ }) => issuesApi.cancelInteraction(issueId!, interaction.id),onSuccess: (interaction) => {upsertInteractionInCache(interaction);invalidateIssueDetail();@@ -2978,22 +4340,41 @@ export function IssueDetail() {onError: (err) => {pushToast({title: "Cancel failed",- body: err instanceof Error ? err.message : "Unable to cancel the question",+ body:+ err instanceof Error ? err.message : "Unable to cancel the question",tone: "error",});},});- const addCommentAndReassign = useMutation({- mutationFn: ({- body,- reopen,- interrupt,- reassignment,- }: {- body: string;- reopen?: boolean;- interrupt?: boolean;+ const skipInteraction = useMutation({+ mutationFn: ({ interaction }: { interaction: IssueThreadInteraction }) =>+ issuesApi.skipInteraction(issueId!, interaction.id),+ onSuccess: (interaction) => {+ upsertInteractionInCache(interaction);+ invalidateIssueDetail();+ invalidateIssueCollections();+ },+ onError: (err) => {+ pushToast({+ title: "Skip failed",+ body:+ err instanceof Error ? err.message : "Unable to skip this request",+ tone: "error",+ });+ },+ });++ const addCommentAndReassign = useMutation({+ mutationFn: ({+ body,+ reopen,+ interrupt,+ reassignment,+ }: {+ body: string;+ reopen?: boolean;+ interrupt?: boolean;reassignment: CommentReassignment;}) =>issuesApi.update(issueId!, {@@ -3004,12 +4385,22 @@ export function IssueDetail() {...(interrupt ? { interrupt } : {}),}),onMutate: async ({ body, reopen, reassignment, interrupt }) => {- await queryClient.cancelQueries({ queryKey: queryKeys.issues.comments(issueId!) });- await queryClient.cancelQueries({ queryKey: queryKeys.issues.detail(issueId!) });+ // Cache cancellation can wait on an active request for several seconds.+ // Start it now, but paint the optimistic echo before awaiting it so a+ // reassignment never clears the composer into an empty thread.+ const cancelComments = queryClient.cancelQueries({+ queryKey: queryKeys.issues.comments(issueId!),+ });+ const cancelIssue = queryClient.cancelQueries({+ queryKey: queryKeys.issues.detail(issueId!),+ });- const previousIssue = queryClient.getQueryData<Issue>(queryKeys.issues.detail(issueId!));+ const previousIssue = queryClient.getQueryData<Issue>(+ queryKeys.issues.detail(issueId!),+ );const queuedComment = !interrupt- ? readIssueRunStateFromCache(queryClient, issueId!, issue).interruptibleIssueRun+ ? readIssueRunStateFromCache(queryClient, issueId!, issue)+ .interruptibleIssueRun: null;const optimisticComment = issue? createOptimisticIssueComment({@@ -3028,10 +4419,15 @@ export function IssueDetail() {if (previousIssue) {queryClient.setQueryData(queryKeys.issues.detail(issueId!),- applyOptimisticIssueCommentUpdate(previousIssue, { reopen, reassignment }),+ applyOptimisticIssueCommentUpdate(previousIssue, {+ reopen,+ reassignment,+ }),);}+ await Promise.all([cancelComments, cancelIssue]);+return {optimisticCommentId: optimisticComment?.clientId ?? null,queuedCommentTargetRunId: queuedComment?.id ?? null,@@ -3039,16 +4435,23 @@ export function IssueDetail() {};},onSuccess: async (result, _variables, context) => {- if (context?.optimisticCommentId) {- setOptimisticComments((current) =>- current.filter((entry) => entry.clientId !== context.optimisticCommentId),- );- }-const { comment, ...nextIssue } = result;queryClient.setQueryData(queryKeys.issues.detail(issueId!), nextIssue);- if (comment && context?.optimisticCommentId && cancelledQueuedOptimisticCommentIdsRef.current.has(context.optimisticCommentId)) {- cancelledQueuedOptimisticCommentIdsRef.current.delete(context.optimisticCommentId);+ if (+ comment &&+ context?.optimisticCommentId &&+ cancelledQueuedOptimisticCommentIdsRef.current.has(+ context.optimisticCommentId,+ )+ ) {+ cancelledQueuedOptimisticCommentIdsRef.current.delete(+ context.optimisticCommentId,+ );+ setOptimisticComments((current) =>+ current.filter(+ (entry) => entry.clientId !== context.optimisticCommentId,+ ),+ );try {await issuesApi.cancelComment(issueId!, comment.id);invalidateIssueDetail();@@ -3058,7 +4461,10 @@ export function IssueDetail() {} catch (err) {pushToast({title: "Cancel failed",- body: err instanceof Error ? err.message : "Unable to cancel the queued comment",+ body:+ err instanceof Error+ ? err.message+ : "Unable to cancel the queued comment",tone: "error",});}@@ -3073,24 +4479,39 @@ export function IssueDetail() {if (comment) {queryClient.setQueryData<InfiniteData<IssueComment[], string | null>>(queryKeys.issues.comments(issueId!),- (current) => current ? {- ...current,- pages: upsertIssueCommentInPages(current.pages, comment),- } : {- pageParams: [null],- pages: upsertIssueCommentInPages(undefined, comment),- },+ (current) =>+ current+ ? {+ ...current,+ pages: upsertIssueCommentInPages(current.pages, comment),+ }+ : {+ pageParams: [null],+ pages: upsertIssueCommentInPages(undefined, comment),+ },+ );+ }+ if (context?.optimisticCommentId) {+ setOptimisticComments((current) =>+ current.filter(+ (entry) => entry.clientId !== context.optimisticCommentId,+ ),);}},onError: (err, _variables, context) => {if (context?.optimisticCommentId) {setOptimisticComments((current) =>- current.filter((entry) => entry.clientId !== context.optimisticCommentId),+ current.filter(+ (entry) => entry.clientId !== context.optimisticCommentId,+ ),);}if (context?.previousIssue) {- queryClient.setQueryData(queryKeys.issues.detail(issueId!), context.previousIssue);+ queryClient.setQueryData(+ queryKeys.issues.detail(issueId!),+ context.previousIssue,+ );}pushToast({title: "Comment failed",@@ -3110,38 +4531,59 @@ export function IssueDetail() {const interruptQueuedComment = useMutation({mutationFn: (runId: string) => heartbeatsApi.cancel(runId),onMutate: async (runId) => {- await Promise.all(issueCacheRefs.flatMap((ref) => [- queryClient.cancelQueries({ queryKey: queryKeys.issues.runs(ref) }),- queryClient.cancelQueries({ queryKey: queryKeys.issues.liveRuns(ref) }),- queryClient.cancelQueries({ queryKey: queryKeys.issues.activeRun(ref) }),- queryClient.cancelQueries({ queryKey: queryKeys.issues.detail(ref) }),- ]));+ await Promise.all(+ issueCacheRefs.flatMap((ref) => [+ queryClient.cancelQueries({ queryKey: queryKeys.issues.runs(ref) }),+ queryClient.cancelQueries({+ queryKey: queryKeys.issues.liveRuns(ref),+ }),+ queryClient.cancelQueries({+ queryKey: queryKeys.issues.activeRun(ref),+ }),+ queryClient.cancelQueries({ queryKey: queryKeys.issues.detail(ref) }),+ ]),+ );const previousRunState = issueCacheRefs.map((ref) => ({ref,- runs: queryClient.getQueryData<RunForIssue[]>(queryKeys.issues.runs(ref)),- liveRuns: queryClient.getQueryData<LiveRunForIssue[]>(queryKeys.issues.liveRuns(ref)),- activeRun: queryClient.getQueryData<ActiveRunForIssue | null>(queryKeys.issues.activeRun(ref)),+ runs: queryClient.getQueryData<RunForIssue[]>(+ queryKeys.issues.runs(ref),+ ),+ liveRuns: queryClient.getQueryData<LiveRunForIssue[]>(+ queryKeys.issues.liveRuns(ref),+ ),+ activeRun: queryClient.getQueryData<ActiveRunForIssue | null>(+ queryKeys.issues.activeRun(ref),+ ),issue: queryClient.getQueryData<Issue>(queryKeys.issues.detail(ref)),}));const previousLocalQueuedCommentRunIds = locallyQueuedCommentRunIds;const cachedActiveRun =- previousRunState.find((state) => state.activeRun?.id === runId)?.activeRun ??+ previousRunState.find((state) => state.activeRun?.id === runId)+ ?.activeRun ??previousRunState.find((state) => state.activeRun)?.activeRun ??null;- const liveRunList = dedupeLiveRunsById(previousRunState.flatMap((state) => state.liveRuns ?? []));- const interruptibleIssueRun = resolveInterruptibleIssueRun(cachedActiveRun, liveRunList);+ const liveRunList = dedupeLiveRunsById(+ previousRunState.flatMap((state) => state.liveRuns ?? []),+ );+ const interruptibleIssueRun = resolveInterruptibleIssueRun(+ cachedActiveRun,+ liveRunList,+ );const targetRun =cachedActiveRun?.id === runId? cachedActiveRun- : liveRunList?.find((run) => run.id === runId) ?? interruptibleIssueRun ?? null;+ : (liveRunList?.find((run) => run.id === runId) ??+ interruptibleIssueRun ??+ null);if (targetRun) {const interruptedAt = new Date().toISOString();for (const ref of issueCacheRefs) {queryClient.setQueryData<RunForIssue[] | undefined>(queryKeys.issues.runs(ref),- (current) => upsertInterruptedRun(current, targetRun, interruptedAt),+ (current) =>+ upsertInterruptedRun(current, targetRun, interruptedAt),);}}@@ -3149,19 +4591,24 @@ export function IssueDetail() {for (const ref of issueCacheRefs) {queryClient.setQueryData(queryKeys.issues.liveRuns(ref),- (current: LiveRunForIssue[] | undefined) => removeLiveRunById(current, runId),+ (current: LiveRunForIssue[] | undefined) =>+ removeLiveRunById(current, runId),);queryClient.setQueryData(queryKeys.issues.activeRun(ref),- (current: ActiveRunForIssue | null | undefined) => (current?.id === runId ? null : current),+ (current: ActiveRunForIssue | null | undefined) =>+ current?.id === runId ? null : current,);queryClient.setQueryData(queryKeys.issues.detail(ref),- (current: Issue | undefined) => clearIssueExecutionRun(current, runId),+ (current: Issue | undefined) =>+ clearIssueExecutionRun(current, runId),);}setLocallyQueuedCommentRunIds((current) => {- const next = new Map([...current].filter(([, targetRunId]) => targetRunId !== runId));+ const next = new Map(+ [...current].filter(([, targetRunId]) => targetRunId !== runId),+ );return next.size === current.size ? current : next;});@@ -3182,23 +4629,36 @@ export function IssueDetail() {onError: (err, _runId, context) => {for (const state of context?.previousRunState ?? []) {queryClient.setQueryData(queryKeys.issues.runs(state.ref), state.runs);- queryClient.setQueryData(queryKeys.issues.liveRuns(state.ref), state.liveRuns);- queryClient.setQueryData(queryKeys.issues.activeRun(state.ref), state.activeRun);- queryClient.setQueryData(queryKeys.issues.detail(state.ref), state.issue);+ queryClient.setQueryData(+ queryKeys.issues.liveRuns(state.ref),+ state.liveRuns,+ );+ queryClient.setQueryData(+ queryKeys.issues.activeRun(state.ref),+ state.activeRun,+ );+ queryClient.setQueryData(+ queryKeys.issues.detail(state.ref),+ state.issue,+ );}if (context?.previousLocalQueuedCommentRunIds) {setLocallyQueuedCommentRunIds(context.previousLocalQueuedCommentRunIds);}pushToast({title: "Interrupt failed",- body: err instanceof Error ? err.message : "Unable to interrupt the active run",+ body:+ err instanceof Error+ ? err.message+ : "Unable to interrupt the active run",tone: "error",});},});const cancelQueuedComment = useMutation({- mutationFn: async ({ commentId }: { commentId: string }) => issuesApi.cancelComment(issueId!, commentId),+ mutationFn: async ({ commentId }: { commentId: string }) =>+ issuesApi.cancelComment(issueId!, commentId),onSuccess: (comment) => {setLocallyQueuedCommentRunIds((current) => {if (!current.has(comment.id)) return current;@@ -3220,14 +4680,18 @@ export function IssueDetail() {onError: (err) => {pushToast({title: "Cancel failed",- body: err instanceof Error ? err.message : "Unable to cancel the queued comment",+ body:+ err instanceof Error+ ? err.message+ : "Unable to cancel the queued comment",tone: "error",});},});const deleteComment = useMutation({- mutationFn: async ({ commentId }: { commentId: string }) => issuesApi.deleteComment(issueId!, commentId),+ mutationFn: async ({ commentId }: { commentId: string }) =>+ issuesApi.deleteComment(issueId!, commentId),onSuccess: (comment) => {upsertCommentInCache(comment);clearCommentHashIfCurrent(comment.id);@@ -3244,34 +4708,38 @@ export function IssueDetail() {onError: (err) => {pushToast({title: "Delete failed",- body: err instanceof Error ? err.message : "Unable to delete the comment",+ body:+ err instanceof Error ? err.message : "Unable to delete the comment",tone: "error",});},});- const handleCancelQueuedComment = useCallback((commentId: string) => {- if (commentId.startsWith("optimistic-")) {- cancelledQueuedOptimisticCommentIdsRef.current.add(commentId);- let cancelledCommentBody: string | null = null;- setOptimisticComments((current) => {- const next = takeOptimisticIssueComment(current, commentId);- cancelledCommentBody = next.comment?.body ?? null;- return next.comments;- });- if (cancelledCommentBody) {- restoreQueuedCommentDraft(cancelledCommentBody);- pushToast({- title: "Queued comment canceled",- body: "The queued message was restored to the composer.",- tone: "success",+ const handleCancelQueuedComment = useCallback(+ (commentId: string) => {+ if (commentId.startsWith("optimistic-")) {+ cancelledQueuedOptimisticCommentIdsRef.current.add(commentId);+ let cancelledCommentBody: string | null = null;+ setOptimisticComments((current) => {+ const next = takeOptimisticIssueComment(current, commentId);+ cancelledCommentBody = next.comment?.body ?? null;+ return next.comments;});+ if (cancelledCommentBody) {+ restoreQueuedCommentDraft(cancelledCommentBody);+ pushToast({+ title: "Queued comment canceled",+ body: "The queued message was restored to the composer.",+ tone: "success",+ });+ }+ return;}- return;- }- void cancelQueuedComment.mutateAsync({ commentId });- }, [cancelQueuedComment, restoreQueuedCommentDraft, pushToast]);+ void cancelQueuedComment.mutateAsync({ commentId });+ },+ [cancelQueuedComment, restoreQueuedCommentDraft, pushToast],+ );const feedbackVoteMutation = useMutation({mutationFn: (variables: {@@ -3290,7 +4758,9 @@ export function IssueDetail() {...(variables.allowSharing ? { allowSharing: true } : {}),}),onMutate: async (variables) => {- await queryClient.cancelQueries({ queryKey: queryKeys.issues.feedbackVotes(issueId!) });+ await queryClient.cancelQueries({+ queryKey: queryKeys.issues.feedbackVotes(issueId!),+ });const previousVotes = queryClient.getQueryData<FeedbackVote[]>(queryKeys.issues.feedbackVotes(issueId!),);@@ -3311,9 +4781,13 @@ export function IssueDetail() {return { previousVotes };},onSuccess: (_savedVote, variables) => {- queryClient.invalidateQueries({ queryKey: queryKeys.issues.feedbackVotes(issueId!) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.feedbackVotes(issueId!),+ });queryClient.invalidateQueries({ queryKey: queryKeys.companies.all });- queryClient.invalidateQueries({ queryKey: queryKeys.instance.generalSettings });+ queryClient.invalidateQueries({+ queryKey: queryKeys.instance.generalSettings,+ });pushToast({title:variables.sharingPreferenceAtSubmit === "prompt"@@ -3328,7 +4802,10 @@ export function IssueDetail() {},onError: (err, _variables, context) => {if (context?.previousVotes) {- queryClient.setQueryData(queryKeys.issues.feedbackVotes(issueId!), context.previousVotes);+ queryClient.setQueryData(+ queryKeys.issues.feedbackVotes(issueId!),+ context.previousVotes,+ );}pushToast({title: "Failed to save feedback",@@ -3345,7 +4822,9 @@ export function IssueDetail() {},onSuccess: () => {setAttachmentError(null);- queryClient.invalidateQueries({ queryKey: queryKeys.issues.attachments(issueId!) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.attachments(issueId!),+ });invalidateIssueDetail();},onError: (err) => {@@ -3357,7 +4836,8 @@ export function IssueDetail() {mutationFn: async (file: File) => {const baseName = fileBaseName(file.name);const key = slugifyDocumentKey(baseName);- const existing = (issue?.documentSummaries ?? []).find((doc) => doc.key === key) ?? null;+ const existing =+ (issue?.documentSummaries ?? []).find((doc) => doc.key === key) ?? null;const body = await file.text();const inferredTitle = titleizeFilename(baseName);const nextTitle = existing?.title ?? inferredTitle ?? null;@@ -3371,18 +4851,25 @@ export function IssueDetail() {onSuccess: () => {setAttachmentError(null);invalidateIssueDetail();- queryClient.invalidateQueries({ queryKey: queryKeys.issues.documents(issueId!) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.documents(issueId!),+ });},onError: (err) => {- setAttachmentError(err instanceof Error ? err.message : "Document import failed");+ setAttachmentError(+ err instanceof Error ? err.message : "Document import failed",+ );},});const deleteAttachment = useMutation({- mutationFn: (attachmentId: string) => issuesApi.deleteAttachment(attachmentId),+ mutationFn: (attachmentId: string) =>+ issuesApi.deleteAttachment(attachmentId),onSuccess: () => {setAttachmentError(null);- queryClient.invalidateQueries({ queryKey: queryKeys.issues.attachments(issueId!) });+ queryClient.invalidateQueries({+ queryKey: queryKeys.issues.attachments(issueId!),+ });invalidateIssueDetail();},onError: (err) => {@@ -3393,10 +4880,14 @@ export function IssueDetail() {const archiveFromInbox = useMutation({mutationFn: (id: string) => issuesApi.archiveFromInbox(id),onMutate: async (id) => {- if (!selectedCompanyId) return { previousData: [] as InboxIssueCacheSnapshot };+ if (!selectedCompanyId)+ return { previousData: [] as InboxIssueCacheSnapshot };beginLocalInboxArchive(selectedCompanyId, id);await cancelInboxIssueQueries(queryClient, selectedCompanyId);- const previousData = snapshotInboxIssueCaches(queryClient, selectedCompanyId);+ const previousData = snapshotInboxIssueCaches(+ queryClient,+ selectedCompanyId,+ );removeIssueFromInboxCaches(queryClient, selectedCompanyId, id);return { companyId: selectedCompanyId, previousData };},@@ -3405,14 +4896,23 @@ export function IssueDetail() {removeIssueFromInboxCaches(queryClient, selectedCompanyId, id);}invalidateIssueCollections();- navigate(sourceBreadcrumb.href.startsWith("/inbox") ? sourceBreadcrumb.href : "/inbox", { replace: true });+ navigate(+ sourceBreadcrumb.href.startsWith("/inbox")+ ? sourceBreadcrumb.href+ : "/inbox",+ { replace: true },+ );pushToast({title: "Task archived from inbox",tone: "success",action: {label: "Undo",onClick: () => {- void undoInboxArchive(id, context?.companyId, context?.previousData ?? []);+ void undoInboxArchive(+ id,+ context?.companyId,+ context?.previousData ?? [],+ );},},});@@ -3424,7 +4924,10 @@ export function IssueDetail() {}pushToast({title: "Archive failed",- body: err instanceof Error ? err.message : "Unable to archive this task from the inbox",+ body:+ err instanceof Error+ ? err.message+ : "Unable to archive this task from the inbox",tone: "error",});},@@ -3433,8 +4936,13 @@ export function IssueDetail() {if (!error) boundLocalInboxArchive(context.companyId, id);await invalidateInboxIssueQueries(queryClient, context.companyId);if (!error) {- const presence = getIssuePresenceInActiveInboxCaches(queryClient, context.companyId, id);- if (presence !== "unknown") confirmLocalInboxArchive(context.companyId, id);+ const presence = getIssuePresenceInActiveInboxCaches(+ queryClient,+ context.companyId,+ id,+ );+ if (presence !== "unknown")+ confirmLocalInboxArchive(context.companyId, id);}},});@@ -3462,6 +4970,37 @@ export function IssueDetail() {breadcrumbStatusKey,]);+ useEffect(() => {+ const showTaskPanelLauncher =+ taskChatShellEnabled &&+ !isMobile &&+ Boolean(issue?.id) &&+ (!panelVisible || suppressPanelUntilPlan);++ setBreadcrumbToolbar(+ showTaskPanelLauncher ? (+ <TooltipProvider>+ <SidePanelToggleButton+ open={false}+ onToggle={openTaskSidePanel}+ shortcut="]"+ className="shrink-0"+ />+ </TooltipProvider>+ ) : null,+ );++ return () => setBreadcrumbToolbar(null);+ }, [+ isMobile,+ issue?.id,+ openTaskSidePanel,+ panelVisible,+ setBreadcrumbToolbar,+ suppressPanelUntilPlan,+ taskChatShellEnabled,+ ]);+const isFromInbox = resolvedIssueDetailState?.issueDetailSource === "inbox";// Scroll to top on forward navigation (PUSH/REPLACE) so issue doesn't@@ -3469,7 +5008,14 @@ export function IssueDetail() {useEffect(() => {const previousIssueId = lastScrollIssueIdRef.current;lastScrollIssueIdRef.current = issueId;- if (!shouldScrollIssueDetailToTopOnNavigation({ previousIssueId, nextIssueId: issueId, navigationType })) return;+ if (+ !shouldScrollIssueDetailToTopOnNavigation({+ previousIssueId,+ nextIssueId: issueId,+ navigationType,+ })+ )+ return;window.scrollTo({ top: 0, left: 0, behavior: "auto" });const main = document.getElementById("main-content");if (main) main.scrollTop = 0;@@ -3479,7 +5025,11 @@ export function IssueDetail() {useEffect(() => {const nextState = resolvedIssueDetailState ?? location.state;if (issue?.identifier && issueId !== issue.identifier) {- rememberIssueDetailLocationState(issue.identifier, nextState, location.search);+ rememberIssueDetailLocationState(+ issue.identifier,+ nextState,+ location.search,+ );navigate(createIssueDetailPath(issue.identifier), {replace: true,state: nextState,@@ -3494,7 +5044,14 @@ export function IssueDetail() {state: nextState,});}- }, [issue, issueId, navigate, location.state, location.search, resolvedIssueDetailState]);+ }, [+ issue,+ issueId,+ navigate,+ location.state,+ location.search,+ resolvedIssueDetailState,+ ]);useEffect(() => {if (!issue?.id) return;@@ -3504,26 +5061,46 @@ export function IssueDetail() {}, [issue?.id]); // eslint-disable-line react-hooks/exhaustive-depsuseEffect(() => {- if (!panelIssue || suppressPanelForFirstTask) {+ if (!panelIssue || suppressPanelUntilPlan) {closePanel();return;}- openPanel(- <IssueProperties- issue={panelIssue}- childIssues={panelChildIssues}- onAddSubIssue={openNewSubIssue}- onUpdate={handleIssuePropertiesUpdate}- hasActiveRun={resolvedHasActiveRun}- externalObjects={externalObjectsState.isEnabled ? externalObjectsState.groups : undefined}- externalObjectsLoading={externalObjectsState.isEnabled ? externalObjectsState.isLoading : undefined}- externalObjectsError={externalObjectsState.isEnabled ? externalObjectsState.isError : undefined}- onRetryExternalObjects={externalObjectsState.isEnabled ? externalObjectsState.refetch : undefined}- onCheckMonitorNow={() => checkIssueMonitorNow.mutate()}- checkingMonitorNow={checkIssueMonitorNow.isPending}- documentDeepLink={documentDeepLink?.issueId === panelIssue.id ? documentDeepLink : null}- />- );+ const sharedProps = {+ issue: panelIssue,+ childIssues: panelChildIssues,+ onAddSubIssue: openNewSubIssue,+ onUpdate: handleIssuePropertiesUpdate,+ hasActiveRun: resolvedHasActiveRun,+ externalObjects: externalObjectsState.isEnabled+ ? externalObjectsState.groups+ : undefined,+ externalObjectsLoading: externalObjectsState.isEnabled+ ? externalObjectsState.isLoading+ : undefined,+ externalObjectsError: externalObjectsState.isEnabled+ ? externalObjectsState.isError+ : undefined,+ onRetryExternalObjects: externalObjectsState.isEnabled+ ? externalObjectsState.refetch+ : undefined,+ onCheckMonitorNow: () => checkIssueMonitorNow.mutate(),+ checkingMonitorNow: checkIssueMonitorNow.isPending,+ documentDeepLink:+ documentDeepLink?.issueId === panelIssue.id ? documentDeepLink : null,+ };+ if (taskChatShellEnabled) {+ openPanel(+ <TaskSidePanel+ key={panelIssue.id}+ {...sharedProps}+ accountScope={currentUserId ?? "anonymous"}+ fileTabsEnabled={fileViewerEnabled}+ />,+ { contentMode: "full-bleed" },+ );+ } else {+ openPanel(<IssueProperties {...sharedProps} />);+ }return () => closePanel();}, [closePanel,@@ -3533,7 +5110,7 @@ export function IssueDetail() {openPanel,panelChildIssues,panelIssue,- suppressPanelForFirstTask,+ suppressPanelUntilPlan,resolvedHasActiveRun,checkIssueMonitorNow.isPending,checkIssueMonitorNow.mutate,@@ -3543,13 +5120,14 @@ export function IssueDetail() {externalObjectsState.isError,externalObjectsState.refetch,documentDeepLink,+ taskChatShellEnabled,+ currentUserId,+ fileViewerEnabled,]);const goToInboxShortcutArmedRef = useRef(false);const goToInboxShortcutTimeoutRef = useRef<number | null>(null);- const canQuickArchiveFromInbox =- keyboardShortcutsEnabled &&- !issue?.hiddenAt;+ const canQuickArchiveFromInbox = keyboardShortcutsEnabled && !issue?.hiddenAt;useEffect(() => {if (!issue?.id || !canQuickArchiveFromInbox) return;@@ -3615,7 +5193,10 @@ export function IssueDetail() {};const handleFocusIn = (event: FocusEvent) => {- if (event.target instanceof HTMLElement && event.target !== document.body) {+ if (+ event.target instanceof HTMLElement &&+ event.target !== document.body+ ) {disarm();}};@@ -3642,7 +5223,11 @@ export function IssueDetail() {if (action === "navigate_inbox") {event.preventDefault();event.stopPropagation();- navigate(sourceBreadcrumb.href.startsWith("/inbox") ? sourceBreadcrumb.href : "/inbox");+ navigate(+ sourceBreadcrumb.href.startsWith("/inbox")+ ? sourceBreadcrumb.href+ : "/inbox",+ );return;}if (action === "focus_comment") {@@ -3668,48 +5253,57 @@ export function IssueDetail() {document.removeEventListener("focusin", handleFocusIn, true);document.removeEventListener("keydown", handleKeyDown, true);};- }, [fileViewerEnabled, keyboardShortcutsEnabled, navigate, sourceBreadcrumb.href]);+ }, [+ fileViewerEnabled,+ keyboardShortcutsEnabled,+ navigate,+ sourceBreadcrumb.href,+ ]);- const routeIssueDocumentDeepLink = useCallback((hash: string) => {- const route = resolveIssueDocumentDeepLink(hash);- if (!route) return false;+ const routeIssueDocumentDeepLink = useCallback(+ (hash: string) => {+ const route = resolveIssueDocumentDeepLink(hash);+ if (!route) return false;- if (route.kind === "continuation-summary") {- setDocumentDeepLink(null);- setDetailTab("activity");- setHandoffFocusSignal((current) => current + 1);- return true;- }+ if (route.kind === "continuation-summary") {+ setDocumentDeepLink(null);+ setDetailTab("activity");+ setHandoffFocusSignal((current) => current + 1);+ return true;+ }- // The classic interface owns document links in its center-column- // Documents section. Do not open its tab-less properties panel.- if (!classicTaskInterfaceLoaded || !taskChatShellEnabled) return false;+ // The classic interface owns document links in its center-column+ // Documents section. Do not open its tab-less properties panel.+ if (!classicTaskInterfaceLoaded || !taskChatShellEnabled) return false;- if (isMobile) {- setMobilePropsOpen(true);- } else {- if (suppressPanelForFirstTask && issue?.id) {- setFirstTaskPanelOverrideIssueId(issue.id);+ if (isMobile) {+ setMobilePropsOpen(true);+ } else {+ if (suppressPanelUntilPlan && issue?.id) {+ setPanelBeforePlanOverrideIssueId(issue.id);+ }+ setPanelVisible(true);}- setPanelVisible(true);- }- const targetIssueId = issue?.id ?? issueId ?? "";- setDocumentDeepLink((current) => ({- issueId: targetIssueId,- tab: route.tab,- documentKey: route.documentKey,- requestId: current?.issueId === targetIssueId ? current.requestId + 1 : 1,- }));- return true;- }, [- classicTaskInterfaceLoaded,- isMobile,- issue?.id,- issueId,- setPanelVisible,- suppressPanelForFirstTask,- taskChatShellEnabled,- ]);+ const targetIssueId = issue?.id ?? issueId ?? "";+ setDocumentDeepLink((current) => ({+ issueId: targetIssueId,+ tab: route.tab,+ documentKey: route.documentKey,+ requestId:+ current?.issueId === targetIssueId ? current.requestId + 1 : 1,+ }));+ return true;+ },+ [+ classicTaskInterfaceLoaded,+ isMobile,+ issue?.id,+ issueId,+ setPanelVisible,+ suppressPanelUntilPlan,+ taskChatShellEnabled,+ ],+ );useEffect(() => {if (!routeIssueDocumentDeepLink(location.hash)) {@@ -3722,7 +5316,14 @@ export function IssueDetail() {// collapsed document reopens and scrolls back into view.useEffect(() => {const handleSameHashDocumentClick = (event: MouseEvent) => {- if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;+ if (+ event.button !== 0 ||+ event.metaKey ||+ event.ctrlKey ||+ event.shiftKey ||+ event.altKey+ )+ return;const target = event.target;if (!(target instanceof Element)) return;const anchor = target.closest<HTMLAnchorElement>("a[href]");@@ -3736,15 +5337,23 @@ export function IssueDetail() {} catch {return;}- const sameIssue = rawHref.startsWith("#")- || (targetUrl.pathname === location.pathname && targetUrl.search === location.search);+ const sameIssue =+ rawHref.startsWith("#") ||+ (targetUrl.pathname === location.pathname &&+ targetUrl.search === location.search);if (!sameIssue || targetUrl.hash !== location.hash) return;routeIssueDocumentDeepLink(targetUrl.hash);};document.addEventListener("click", handleSameHashDocumentClick, true);- return () => document.removeEventListener("click", handleSameHashDocumentClick, true);- }, [location.hash, location.pathname, location.search, routeIssueDocumentDeepLink]);+ return () =>+ document.removeEventListener("click", handleSameHashDocumentClick, true);+ }, [+ location.hash,+ location.pathname,+ location.search,+ routeIssueDocumentDeepLink,+ ]);// Scroll + briefly highlight work-product / direct-attachment anchors so the// company Artifacts page (PAP-10359) can deep-link to a specific artifact in@@ -3768,7 +5377,15 @@ export function IssueDetail() {}element.scrollIntoView({ behavior: "smooth", block: "center" });element.classList.add("ring-2", "ring-primary/50", "transition-shadow");- timer = setTimeout(() => element.classList.remove("ring-2", "ring-primary/50", "transition-shadow"), 3000);+ timer = setTimeout(+ () =>+ element.classList.remove(+ "ring-2",+ "ring-primary/50",+ "transition-shadow",+ ),+ 3000,+ );};tryScroll();return () => {@@ -3788,7 +5405,10 @@ export function IssueDetail() {const handleOpenFileViewer = () => {setFileViewerPromptOpen(true);};- window.addEventListener("paperclip:open-file-viewer", handleOpenFileViewer as EventListener);+ window.addEventListener(+ "paperclip:open-file-viewer",+ handleOpenFileViewer as EventListener,+ );return () => {window.removeEventListener("paperclip:open-file-viewer",@@ -3797,27 +5417,39 @@ export function IssueDetail() {};}, [fileViewerEnabled]);- const promotedOutputAttachmentIds = useMemo(() => getPromotedOutputAttachmentIds(workProducts), [workProducts]);+ const promotedOutputAttachmentIds = useMemo(+ () => getPromotedOutputAttachmentIds(workProducts),+ [workProducts],+ );const attachmentList = useMemo(- () => (attachments ?? []).filter((attachment) => !promotedOutputAttachmentIds.has(attachment.id)),+ () =>+ (attachments ?? []).filter(+ (attachment) => !promotedOutputAttachmentIds.has(attachment.id),+ ),[attachments, promotedOutputAttachmentIds],);const mediaGalleryItems = useMemo<GalleryMediaItem[]>(() => {const items: GalleryMediaItem[] = [];const seen = new Set<string>();- const mark = (attachmentId: string | null | undefined, contentPath: string) => {+ const mark = (+ attachmentId: string | null | undefined,+ contentPath: string,+ ) => {if (attachmentId) seen.add(`attachment:${attachmentId}`);seen.add(`content:${contentPath}`);};- const hasSeen = (attachmentId: string | null | undefined, contentPath: string) => (+ const hasSeen = (+ attachmentId: string | null | undefined,+ contentPath: string,+ ) =>Boolean(attachmentId && seen.has(`attachment:${attachmentId}`)) ||- seen.has(`content:${contentPath}`)- );+ seen.has(`content:${contentPath}`);for (const attachment of attachments ?? []) {- if (!isImageAttachment(attachment) && !isVideoAttachment(attachment)) continue;+ if (!isImageAttachment(attachment) && !isVideoAttachment(attachment))+ continue;items.push(attachment);mark(attachment.id, attachment.contentPath);}@@ -3825,7 +5457,8 @@ export function IssueDetail() {for (const item of getIssueOutputs(workProducts).items) {const meta = item.metadata;if (!meta) continue;- const isMedia = isImageContentType(meta.contentType) ||+ const isMedia =+ isImageContentType(meta.contentType) ||isVideoLikeOutput(meta.contentType, meta.originalFilename);if (!isMedia || hasSeen(meta.attachmentId, meta.contentPath)) continue;items.push({@@ -3850,7 +5483,9 @@ export function IssueDetail() {// Try matching by asset ID extracted from /api/assets/{assetId}/content URLsconst assetMatch = src.match(/\/api\/assets\/([^/]+)\/content/);if (assetMatch) {- idx = mediaGalleryItems.findIndex((a) => "assetId" in a && a.assetId === assetMatch[1]);+ idx = mediaGalleryItems.findIndex(+ (a) => "assetId" in a && a.assetId === assetMatch[1],+ );}}if (idx >= 0) {@@ -3882,7 +5517,10 @@ export function IssueDetail() {} catch (error) {pushToast({title: "Copy failed",- body: error instanceof Error ? error.message : "Unable to copy task markdown",+ body:+ error instanceof Error+ ? error.message+ : "Unable to copy task markdown",tone: "error",});}@@ -3894,7 +5532,8 @@ export function IssueDetail() {// non-memoized functions change identity every render).const inboxToolbarCallbacksRef = useRef({onArchive: () => {- if (!archiveFromInbox.isPending && issue?.id) archiveFromInbox.mutate(issue.id);+ if (!archiveFromInbox.isPending && issue?.id)+ archiveFromInbox.mutate(issue.id);},onCopy: () => copyIssueToClipboard(),onProperties: () => setMobilePropsOpen(true),@@ -3907,7 +5546,8 @@ export function IssueDetail() {});inboxToolbarCallbacksRef.current = {onArchive: () => {- if (!archiveFromInbox.isPending && issue?.id) archiveFromInbox.mutate(issue.id);+ if (!archiveFromInbox.isPending && issue?.id)+ archiveFromInbox.mutate(issue.id);},onCopy: () => copyIssueToClipboard(),onProperties: () => setMobilePropsOpen(true),@@ -3945,9 +5585,17 @@ export function IssueDetail() {);return () => setMobileToolbar(null);- }, [showInboxToolbar, backHref, issue?.id, issueHidden, archivePending, setMobileToolbar]);+ }, [+ showInboxToolbar,+ backHref,+ issue?.id,+ issueHidden,+ archivePending,+ setMobileToolbar,+ ]);- const attachmentsInitialLoading = attachmentsLoading && attachments === undefined;+ const attachmentsInitialLoading =+ attachmentsLoading && attachments === undefined;const loadOlderComments = useCallback(() => {void fetchOlderComments();}, [fetchOlderComments]);@@ -3959,7 +5607,8 @@ export function IssueDetail() {const refreshed = await refetchComments();const loaded = await loadRemainingIssueCommentPages<IssueComment>({pages: refreshed.data?.pages,- pageParams: refreshed.data?.pageParams as Array<string | null> | undefined,+ pageParams: refreshed.data?.pageParams as+ Array<string | null> | undefined,pageSize: ISSUE_COMMENT_PAGE_SIZE,maxPages: JUMP_TO_LATEST_MAX_COMMENT_PAGES,fetchPage: (afterCommentId) =>@@ -3985,87 +5634,152 @@ export function IssueDetail() {if (!shouldPrefetchOlderComments) return;void fetchOlderComments();}, [fetchOlderComments, shouldPrefetchOlderComments]);- const handleCommentVote = useCallback(async (commentId: string, vote: "up" | "down", options?: { allowSharing?: boolean; reason?: string }) => {- await feedbackVoteMutation.mutateAsync({- targetType: "issue_comment",- targetId: commentId,- vote,- reason: options?.reason,- allowSharing: options?.allowSharing,- sharingPreferenceAtSubmit: feedbackDataSharingPreference,- });- }, [feedbackDataSharingPreference, feedbackVoteMutation]);- const handleChatAdd = useCallback(async (body: string, reopen?: boolean, reassignment?: CommentReassignment) => {- if (reassignment) {- await addCommentAndReassign.mutateAsync({ body, reopen, reassignment });- return;- }- await addComment.mutateAsync({ body, reopen });- }, [addComment, addCommentAndReassign]);- const handleCommentImageUpload = useCallback(async (file: File) => {- const attachment = await uploadAttachment.mutateAsync(file);- return attachment.contentPath;- }, [uploadAttachment]);- const handleCommentAttachImage = useCallback(async (file: File) => {- return uploadAttachment.mutateAsync(file);- }, [uploadAttachment]);- const handleInterruptQueuedRun = useCallback(async (runId: string) => {- await interruptQueuedComment.mutateAsync(runId);- }, [interruptQueuedComment]);- const runFinalizationActions = useMemo<readonly IssueChatRunFinalizationAction[]>(() => [- {- id: "cancel",- label: "Stop and cancel",- pendingLabel: "Stopping and cancelling...",- isPending:- stopAndFinalizeRun.isPending &&- stopAndFinalizeRun.variables?.status === "cancelled",- disabled: stopAndFinalizeRun.isPending,- onSelect: (runId) =>- stopAndFinalizeRun.mutateAsync({ runId, status: "cancelled" }).then(() => undefined, () => undefined),+ const handleCommentVote = useCallback(+ async (+ commentId: string,+ vote: "up" | "down",+ options?: { allowSharing?: boolean; reason?: string },+ ) => {+ await feedbackVoteMutation.mutateAsync({+ targetType: "issue_comment",+ targetId: commentId,+ vote,+ reason: options?.reason,+ allowSharing: options?.allowSharing,+ sharingPreferenceAtSubmit: feedbackDataSharingPreference,+ });},- {- id: "done",- label: "Stop and done",- pendingLabel: "Stopping and marking done...",- isPending:- stopAndFinalizeRun.isPending &&- stopAndFinalizeRun.variables?.status === "done",- disabled: stopAndFinalizeRun.isPending,- onSelect: (runId) =>- stopAndFinalizeRun.mutateAsync({ runId, status: "done" }).then(() => undefined, () => undefined),+ [feedbackDataSharingPreference, feedbackVoteMutation],+ );+ const handleChatAdd = useCallback(+ async (+ body: string,+ reopen?: boolean,+ reassignment?: CommentReassignment,+ ) => {+ if (reassignment) {+ await addCommentAndReassign.mutateAsync({ body, reopen, reassignment });+ return;+ }+ await addComment.mutateAsync({ body, reopen });},- ], [- stopAndFinalizeRun.isPending,- stopAndFinalizeRun.mutateAsync,- stopAndFinalizeRun.variables?.status,- ]);- const handleAcceptInteraction = useCallback(async (- interaction: ActionableIssueThreadInteraction,- selectedClientKeys?: string[],- selectedOptionIds?: string[],- ) => {- await acceptInteraction.mutateAsync({ interaction, selectedClientKeys, selectedOptionIds });- }, [acceptInteraction]);- const handleRejectInteraction = useCallback(async (interaction: ActionableIssueThreadInteraction, reason?: string) => {- await rejectInteraction.mutateAsync({ interaction, reason });- }, [rejectInteraction]);- const handleSubmitInteractionAnswers = useCallback(async (- interaction: IssueThreadInteraction,- answers: AskUserQuestionsAnswer[],- ) => {- await answerInteraction.mutateAsync({ interaction, answers });- }, [answerInteraction]);- const handleCancelInteraction = useCallback(async (interaction: AskUserQuestionsInteraction) => {- await cancelInteraction.mutateAsync({ interaction });- }, [cancelInteraction]);- const handleSubmitInteractionVerdicts = useCallback(async (- interaction: RequestItemVerdictsInteraction,- verdicts: { id: string; verdict: RequestItemVerdictValue; reason?: string }[],- ) => {- await submitInteractionVerdicts.mutateAsync({ interaction, verdicts });- }, [submitInteractionVerdicts]);- const canResumeFromBacklog = issue?.status === "backlog" && Boolean(issue.assigneeAgentId || issue.assigneeUserId);+ [addComment, addCommentAndReassign],+ );+ const handleCommentImageUpload = useCallback(+ async (file: File) => {+ const attachment = await uploadAttachment.mutateAsync(file);+ return attachment.contentPath;+ },+ [uploadAttachment],+ );+ const handleCommentAttachImage = useCallback(+ async (file: File) => {+ return uploadAttachment.mutateAsync(file);+ },+ [uploadAttachment],+ );+ const handleInterruptQueuedRun = useCallback(+ async (runId: string) => {+ await interruptQueuedComment.mutateAsync(runId);+ },+ [interruptQueuedComment],+ );+ const runFinalizationActions = useMemo<+ readonly IssueChatRunFinalizationAction[]+ >(+ () => [+ {+ id: "cancel",+ label: "Stop and cancel",+ pendingLabel: "Stopping and cancelling...",+ isPending:+ stopAndFinalizeRun.isPending &&+ stopAndFinalizeRun.variables?.status === "cancelled",+ disabled: stopAndFinalizeRun.isPending,+ onSelect: (runId) =>+ stopAndFinalizeRun.mutateAsync({ runId, status: "cancelled" }).then(+ () => undefined,+ () => undefined,+ ),+ },+ {+ id: "done",+ label: "Stop and done",+ pendingLabel: "Stopping and marking done...",+ isPending:+ stopAndFinalizeRun.isPending &&+ stopAndFinalizeRun.variables?.status === "done",+ disabled: stopAndFinalizeRun.isPending,+ onSelect: (runId) =>+ stopAndFinalizeRun.mutateAsync({ runId, status: "done" }).then(+ () => undefined,+ () => undefined,+ ),+ },+ ],+ [+ stopAndFinalizeRun.isPending,+ stopAndFinalizeRun.mutateAsync,+ stopAndFinalizeRun.variables?.status,+ ],+ );+ const handleAcceptInteraction = useCallback(+ async (+ interaction: ActionableIssueThreadInteraction,+ selectedClientKeys?: string[],+ selectedOptionIds?: string[],+ ) => {+ await acceptInteraction.mutateAsync({+ interaction,+ selectedClientKeys,+ selectedOptionIds,+ });+ },+ [acceptInteraction],+ );+ const handleRejectInteraction = useCallback(+ async (interaction: ActionableIssueThreadInteraction, reason?: string) => {+ await rejectInteraction.mutateAsync({ interaction, reason });+ },+ [rejectInteraction],+ );+ const handleSubmitInteractionAnswers = useCallback(+ async (+ interaction: IssueThreadInteraction,+ answers: AskUserQuestionsAnswer[],+ ) => {+ await answerInteraction.mutateAsync({ interaction, answers });+ },+ [answerInteraction],+ );+ const handleCancelInteraction = useCallback(+ async (interaction: AskUserQuestionsInteraction) => {+ await cancelInteraction.mutateAsync({ interaction });+ },+ [cancelInteraction],+ );+ const handleSkipInteraction = useCallback(+ async (interaction: IssueThreadInteraction) => {+ await skipInteraction.mutateAsync({ interaction });+ },+ [skipInteraction],+ );+ const handleSubmitInteractionVerdicts = useCallback(+ async (+ interaction: RequestItemVerdictsInteraction,+ verdicts: {+ id: string;+ verdict: RequestItemVerdictValue;+ reason?: string;+ }[],+ ) => {+ await submitInteractionVerdicts.mutateAsync({ interaction, verdicts });+ },+ [submitInteractionVerdicts],+ );+ const canResumeFromBacklog =+ issue?.status === "backlog" &&+ Boolean(issue.assigneeAgentId || issue.assigneeUserId);const handleResumeFromBacklog = useCallback(async () => {await updateIssue.mutateAsync({ status: "todo" });}, [updateIssue.mutateAsync]);@@ -4079,19 +5793,29 @@ export function IssueDetail() {const resumeAssigneeAgent = useMutation({mutationFn: async () => {if (!issueAssigneeAgentIdForResume) throw new Error("No assignee agent");- await agentsApi.resume(issueAssigneeAgentIdForResume, issueCompanyIdForResume ?? undefined);+ await agentsApi.resume(+ issueAssigneeAgentIdForResume,+ issueCompanyIdForResume ?? undefined,+ );// The pause silently dropped this issue's assignment wake, so resuming// alone would leave the task idle until some other trigger fires.// Re-issue the wake for executable statuses; best-effort — the agent is// resumed either way and the next comment or timer also wakes it.- if (issueIdForResume && (issueStatusForResume === "todo" || issueStatusForResume === "in_progress")) {+ if (+ issueIdForResume &&+ (issueStatusForResume === "todo" ||+ issueStatusForResume === "in_progress")+ ) {try {await agentsApi.wakeup(issueAssigneeAgentIdForResume,{source: "assignment",reason: "Assignee resumed from the task page",- payload: { issueId: issueIdForResume, mutation: "assignee_resumed" },+ payload: {+ issueId: issueIdForResume,+ mutation: "assignee_resumed",+ },},issueCompanyIdForResume ?? undefined,);@@ -4102,7 +5826,9 @@ export function IssueDetail() {},onSuccess: async () => {if (issueCompanyIdForResume) {- await queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(issueCompanyIdForResume) });+ await queryClient.invalidateQueries({+ queryKey: queryKeys.agents.list(issueCompanyIdForResume),+ });}},});@@ -4111,29 +5837,54 @@ export function IssueDetail() {}, [resumeAssigneeAgent.mutateAsync]);const activeRecoveryActionId = issue?.activeRecoveryAction?.id;const handleResolveRecoveryAction = useCallback(- (outcome: import("../components/IssueRecoveryActionCard").RecoveryResolveOutcome) => {+ (+ outcome: import("../components/IssueRecoveryActionCard").RecoveryResolveOutcome,+ ) => {const actionId = activeRecoveryActionId;if (!actionId) return;switch (outcome) {case "todo":- void resolveRecoveryAction.mutateAsync({ actionId, outcome: "restored", sourceIssueStatus: "todo" });+ void resolveRecoveryAction.mutateAsync({+ actionId,+ outcome: "restored",+ sourceIssueStatus: "todo",+ });return;case "done":- void resolveRecoveryAction.mutateAsync({ actionId, outcome: "restored", sourceIssueStatus: "done" });+ void resolveRecoveryAction.mutateAsync({+ actionId,+ outcome: "restored",+ sourceIssueStatus: "done",+ });return;case "in_review":- void resolveRecoveryAction.mutateAsync({ actionId, outcome: "restored", sourceIssueStatus: "in_review" });+ void resolveRecoveryAction.mutateAsync({+ actionId,+ outcome: "restored",+ sourceIssueStatus: "in_review",+ });return;case "false_positive_done":- void resolveRecoveryAction.mutateAsync({ actionId, outcome: "false_positive", sourceIssueStatus: "done" });+ void resolveRecoveryAction.mutateAsync({+ actionId,+ outcome: "false_positive",+ sourceIssueStatus: "done",+ });return;case "false_positive_in_review":- void resolveRecoveryAction.mutateAsync({ actionId, outcome: "false_positive", sourceIssueStatus: "in_review" });+ void resolveRecoveryAction.mutateAsync({+ actionId,+ outcome: "false_positive",+ sourceIssueStatus: "in_review",+ });return;}},[activeRecoveryActionId, resolveRecoveryAction.mutateAsync],);+ const handleTryAgainNoLiveExecutionPath = useCallback(() => {+ handleResolveRecoveryAction("todo");+ }, [handleResolveRecoveryAction]);// Action 3 (workspace_validation): one-click re-issue of the stalled task on a fresh isolated// git worktree based on the live (diverged) branch. Composes the existing safe issue-creation@@ -4148,7 +5899,9 @@ export function IssueDetail() {`Re-issued from ${sourceLabel} on an isolated git worktree after a workspace branch divergence.`,"",`- Base ref (live branch): \`${request.baseRef}\``,- ...(request.expectedBranch ? [`- Recorded branch: \`${request.expectedBranch}\``] : []),+ ...(request.expectedBranch+ ? [`- Recorded branch: \`${request.expectedBranch}\``]+ : []),"","---","",@@ -4188,13 +5941,18 @@ export function IssueDetail() {onError: (err) => {pushToast({title: "Re-issue failed",- body: err instanceof Error ? err.message : "Unable to create an isolated re-issue.",+ body:+ err instanceof Error+ ? err.message+ : "Unable to create an isolated re-issue.",tone: "error",});},});const handleReissueIsolatedRecoveryAction = useCallback(- (request: import("../components/IssueRecoveryActionCard").RecoveryReissueRequest) => {+ (+ request: import("../components/IssueRecoveryActionCard").RecoveryReissueRequest,+ ) => {void reissueIsolatedRecoveryAction.mutateAsync(request);},[reissueIsolatedRecoveryAction.mutateAsync],@@ -4240,7 +5998,10 @@ export function IssueDetail() {onError: (err) => {pushToast({title: "Reconcile failed",- body: err instanceof Error ? err.message : "Unable to reconcile the workspace branch.",+ body:+ err instanceof Error+ ? err.message+ : "Unable to reconcile the workspace branch.",tone: "error",});},@@ -4252,7 +6013,9 @@ export function IssueDetail() {// issue to a new workspace) while the card still shows the older action. Fall back to the// page-level id only when the action carries no workspace reference.const reconcileExecutionWorkspaceId =- readRecoveryReconcileWorkspaceId(issue?.activeRecoveryAction) ?? issue?.executionWorkspaceId ?? null;+ readRecoveryReconcileWorkspaceId(issue?.activeRecoveryAction) ??+ issue?.executionWorkspaceId ??+ null;const handleReconcileForwardRecoveryAction = useCallback(() => {if (!reconcileExecutionWorkspaceId) {pushToast({@@ -4266,7 +6029,11 @@ export function IssueDetail() {workspaceId: reconcileExecutionWorkspaceId,mode: "forward",});- }, [reconcileExecutionWorkspaceId, reconcileRecoveryAction.mutateAsync, pushToast]);+ }, [+ reconcileExecutionWorkspaceId,+ reconcileRecoveryAction.mutateAsync,+ pushToast,+ ]);const handleBreakGlassOverrideRecoveryAction = useCallback((reason: string) => {if (!reconcileExecutionWorkspaceId) {@@ -4283,7 +6050,11 @@ export function IssueDetail() {reason,});},- [reconcileExecutionWorkspaceId, reconcileRecoveryAction.mutateAsync, pushToast],+ [+ reconcileExecutionWorkspaceId,+ reconcileRecoveryAction.mutateAsync,+ pushToast,+ ],);// Repair action (workspace_validation, dirty divergence): quarantine the dirty worktree onto a// rescue branch and restore the recorded branch. Lossless — no reason required.@@ -4300,10 +6071,17 @@ export function IssueDetail() {workspaceId: reconcileExecutionWorkspaceId,mode: "quarantine_restore",});- }, [reconcileExecutionWorkspaceId, reconcileRecoveryAction.mutateAsync, pushToast]);+ }, [+ reconcileExecutionWorkspaceId,+ reconcileRecoveryAction.mutateAsync,+ pushToast,+ ]);const treePreviewAffectedIssues = useMemo(- () => (treeControlPreview?.issues ?? []).filter((candidate) => !candidate.skipped),+ () =>+ (treeControlPreview?.issues ?? []).filter(+ (candidate) => !candidate.skipped,+ ),[treeControlPreview],);// "What this affects" buckets for the pause/hold dialog (design surface 4).@@ -4311,19 +6089,19 @@ export function IssueDetail() {() => computePauseAffectsSummary(treeControlPreview?.issues ?? []),[treeControlPreview],);- const treePreviewDisplayIssues = useMemo(- () => {- const previewIssues = treeControlPreview?.issues ?? [];- if (treeControlMode !== "pause") {- return previewIssues.filter((candidate) => !candidate.skipped);- }- return previewIssues.filter((candidate) => !candidate.skipped || candidate.skipReason === "terminal_status");- },- [treeControlMode, treeControlPreview],- );+ const treePreviewDisplayIssues = useMemo(() => {+ const previewIssues = treeControlPreview?.issues ?? [];+ if (treeControlMode !== "pause") {+ return previewIssues.filter((candidate) => !candidate.skipped);+ }+ return previewIssues.filter(+ (candidate) =>+ !candidate.skipped || candidate.skipReason === "terminal_status",+ );+ }, [treeControlMode, treeControlPreview]);const activePauseHold = treeControlState?.activePauseHold ?? null;const activeRootPauseHoldsForDisplay = useMemo(- () => activePauseHold?.isRoot === true ? activeRootPauseHolds : [],+ () => (activePauseHold?.isRoot === true ? activeRootPauseHolds : []),[activePauseHold?.isRoot, activeRootPauseHolds],);const heldIssueIds = useMemo(() => {@@ -4354,14 +6132,22 @@ export function IssueDetail() {const activePauseHoldRoot = useMemo(() => {if (!activePauseHold) return null;if (activePauseHold.rootIssueId === issue?.id) return issue ?? null;- return issue?.ancestors?.find((ancestor) => ancestor.id === activePauseHold.rootIssueId) ?? null;+ return (+ issue?.ancestors?.find(+ (ancestor) => ancestor.id === activePauseHold.rootIssueId,+ ) ?? null+ );}, [activePauseHold, issue]);const activeRootPauseHold = useMemo(- () => activeRootPauseHoldsForDisplay.find((hold) => hold.id === activePauseHold?.holdId) ?? null,+ () =>+ activeRootPauseHoldsForDisplay.find(+ (hold) => hold.id === activePauseHold?.holdId,+ ) ?? null,[activePauseHold?.holdId, activeRootPauseHoldsForDisplay],);- if (isLoading) return <IssueDetailLoadingState headerSeed={issueHeaderSeed} />;+ if (isLoading)+ return <IssueDetailLoadingState headerSeed={issueHeaderSeed} />;if (error) return <p className="text-sm text-destructive">{error.message}</p>;if (!issue) return null;@@ -4414,18 +6200,33 @@ export function IssueDetail() {const hasAttachments = attachmentList.length > 0;const treePreviewWarnings = treeControlPreview?.warnings ?? [];- const heldDescendantCount = activeRootPauseHold?.members?.filter((member) => member.depth > 0 && !member.skipped).length- ?? Math.max(heldIssueIds.size - 1, 0);+ const heldDescendantCount =+ activeRootPauseHold?.members?.filter(+ (member) => member.depth > 0 && !member.skipped,+ ).length ?? Math.max(heldIssueIds.size - 1, 0);const canShowSubtreeControls = canManageTreeControl && childIssues.length > 0;- const canResumeSubtree = canShowSubtreeControls && activePauseHold?.isRoot === true;- const canRestoreSubtree = canShowSubtreeControls && activeCancelHolds.length > 0;- const isTerminalIssue = issue.status === "done" || issue.status === "cancelled";- const isAgentOwnedNonTerminalIssue = Boolean(issue.assigneeAgentId) && !isTerminalIssue;- const canPauseLeafWork = canManageTreeControl && childIssues.length === 0 && !activePauseHold && !isTerminalIssue;- const canResumeLeafWork = canManageTreeControl && childIssues.length === 0 && activePauseHold?.isRoot === true;- const treeControlScope: "leaf" | "subtree" = childIssues.length === 0 ? "leaf" : "subtree";+ const canResumeSubtree =+ canShowSubtreeControls && activePauseHold?.isRoot === true;+ const canRestoreSubtree =+ canShowSubtreeControls && activeCancelHolds.length > 0;+ const isTerminalIssue =+ issue.status === "done" || issue.status === "cancelled";+ const isAgentOwnedNonTerminalIssue =+ Boolean(issue.assigneeAgentId) && !isTerminalIssue;+ const canPauseLeafWork =+ canManageTreeControl &&+ childIssues.length === 0 &&+ !activePauseHold &&+ !isTerminalIssue;+ const canResumeLeafWork =+ canManageTreeControl &&+ childIssues.length === 0 &&+ activePauseHold?.isRoot === true;+ const treeControlScope: "leaf" | "subtree" =+ childIssues.length === 0 ? "leaf" : "subtree";const previewAffectedIssueCount = treePreviewAffectedIssues.length;- const previewAffectedAgentCount = treeControlPreview?.totals.affectedAgents ?? 0;+ const previewAffectedAgentCount =+ treeControlPreview?.totals.affectedAgents ?? 0;const treeControlPrimaryButtonLabel =treeControlMode === "pause"? treeControlScope === "leaf"@@ -4433,47 +6234,53 @@ export function IssueDetail() {: "Pause and stop work": treeControlMode === "cancel"? `Cancel ${previewAffectedIssueCount} tasks`- : treeControlMode === "restore"+ : treeControlMode === "restore"? `Restore ${previewAffectedIssueCount} tasks`: treeControlScope === "leaf"? "Resume work": "Resume subtree";- const treePreviewAffectedIssueRows = treePreviewDisplayIssues.map((candidate) => ({- candidate,- issue: {- ...issue,- id: candidate.id,- identifier: candidate.identifier,- title: candidate.title,- status: candidate.status,- parentId: candidate.parentId,- assigneeAgentId: candidate.assigneeAgentId,- assigneeUserId: candidate.assigneeUserId,- executionRunId: candidate.activeRun?.id ?? null,- } satisfies Issue,- }));- const treePreviewAffectedAgentRows = (treeControlPreview?.affectedAgents ?? [])+ const treePreviewAffectedIssueRows = treePreviewDisplayIssues.map(+ (candidate) => ({+ candidate,+ issue: {+ ...issue,+ id: candidate.id,+ identifier: candidate.identifier,+ title: candidate.title,+ status: candidate.status,+ parentId: candidate.parentId,+ assigneeAgentId: candidate.assigneeAgentId,+ assigneeUserId: candidate.assigneeUserId,+ executionRunId: candidate.activeRun?.id ?? null,+ } satisfies Issue,+ }),+ );+ const treePreviewAffectedAgentRows = (+ treeControlPreview?.affectedAgents ?? []+ ).map((previewAgent) => ({...previewAgent,agent: agentMap.get(previewAgent.agentId) ?? null,}))- .sort((a, b) => (a.agent?.name ?? a.agentId).localeCompare(b.agent?.name ?? b.agentId));+ .sort((a, b) =>+ (a.agent?.name ?? a.agentId).localeCompare(b.agent?.name ?? b.agentId),+ );const pausedComposerHint = activePauseHold- ? (- issue.assigneeAgentId- ? `Sending this comment will wake ${agentMap.get(issue.assigneeAgentId)?.name ?? "the assignee"} for triage while the subtree remains paused.`- : "Assign an agent to wake them for triage while the subtree remains paused."- )+ ? issue.assigneeAgentId+ ? `Sending this comment will wake ${agentMap.get(issue.assigneeAgentId)?.name ?? "the assignee"} for triage while the subtree remains paused.`+ : "Assign an agent to wake them for triage while the subtree remains paused.": null;const reopenComposerHint = closedIsolatedWorkspaceReopenPending? "This issue's isolated workspace was archived. Your next comment or resume reopens it and rebuilds the worktree.": null;const composerHint = pausedComposerHint ?? reopenComposerHint;- const queuedCommentReason: "hold" | "active_run" | "other" = activePauseHold ? "hold" : "active_run";+ const queuedCommentReason: "hold" | "active_run" | "other" = activePauseHold+ ? "hold"+ : "active_run";const canApplyTreeControl =- Boolean(treeControlPreview)- && !treeControlPreviewLoading- && (treeControlMode !== "cancel" || treeControlCancelConfirmed);+ Boolean(treeControlPreview) &&+ !treeControlPreviewLoading &&+ (treeControlMode !== "cancel" || treeControlCancelConfirmed);const attachmentUploadButton = (<><input@@ -4487,14 +6294,18 @@ export function IssueDetail() {variant="outline"size="sm"onClick={() => fileInputRef.current?.click()}- disabled={uploadAttachment.isPending || importMarkdownDocument.isPending}+ disabled={+ uploadAttachment.isPending || importMarkdownDocument.isPending+ }className={cn("shadow-none",attachmentDragActive && "border-primary bg-primary/5",)}><Paperclip className="h-3.5 w-3.5 mr-1.5" />- {uploadAttachment.isPending || importMarkdownDocument.isPending ? "Uploading..." : (+ {uploadAttachment.isPending || importMarkdownDocument.isPending ? (+ "Uploading..."+ ) : (<><span className="hidden sm:inline">Upload attachment</span><span className="sm:hidden">Upload</span>@@ -4510,269 +6321,303 @@ export function IssueDetail() {// stays near the viewport bottom. Flag OFF renders the same nodes in the// page flow, in their original order relative to the alert banners.const ancestorsNav = ancestors.length > 0 && (- <nav className={cn("flex items-center gap-1 text-xs text-muted-foreground flex-wrap", shellSectionClass)}>- {[...ancestors].reverse().map((ancestor, i) => (- <span key={ancestor.id} className="flex items-center gap-1">- {i > 0 && <ChevronRight className="h-3 w-3 shrink-0" />}- <Link- to={createIssueDetailPath(ancestor.identifier ?? ancestor.id)}- state={resolvedIssueDetailState ?? location.state}- onClickCapture={() =>- rememberIssueDetailLocationState(- ancestor.identifier ?? ancestor.id,- resolvedIssueDetailState ?? location.state,- location.search,- )}- className="hover:text-foreground transition-colors truncate max-w-(--sz-200px)"- title={ancestor.title}- >- {ancestor.title}- </Link>- </span>- ))}- <ChevronRight className="h-3 w-3 shrink-0" />- <span className="text-foreground/60 truncate max-w-(--sz-200px)">{issue.title}</span>- </nav>+ <nav+ className={cn(+ "flex items-center gap-1 text-xs text-muted-foreground flex-wrap",+ shellSectionClass,+ )}+ >+ {[...ancestors].reverse().map((ancestor, i) => (+ <span key={ancestor.id} className="flex items-center gap-1">+ {i > 0 && <ChevronRight className="h-3 w-3 shrink-0" />}+ <Link+ to={createIssueDetailPath(ancestor.identifier ?? ancestor.id)}+ state={resolvedIssueDetailState ?? location.state}+ onClickCapture={() =>+ rememberIssueDetailLocationState(+ ancestor.identifier ?? ancestor.id,+ resolvedIssueDetailState ?? location.state,+ location.search,+ )+ }+ className="hover:text-foreground transition-colors truncate max-w-(--sz-200px)"+ title={ancestor.title}+ >+ {ancestor.title}+ </Link>+ </span>+ ))}+ <ChevronRight className="h-3 w-3 shrink-0" />+ <span className="text-foreground/60 truncate max-w-(--sz-200px)">+ {issue.title}+ </span>+ </nav>);const issueHeaderBlock = (- <div- data-testid="issue-detail-header"- className={cn("space-y-3", shellSectionClass)}- >- <div className="flex items-center gap-2 min-w-0 flex-wrap">- <StatusIcon- status={issue.status}- size="lg"- blockerAttention={issue.blockerAttention}- onChange={(status) => updateIssue.mutate({ status })}- />- {/* PAP-411: priority UI hidden behind SHOW_TASK_PRIORITY_UI. */}- {SHOW_TASK_PRIORITY_UI && (- <PriorityIcon- priority={issue.priority}- onChange={(priority) => updateIssue.mutate({ priority })}- />- )}- <span className="text-sm font-mono text-muted-foreground shrink-0">{issue.identifier ?? issue.id.slice(0, 8)}</span>-- {hasLiveRuns && (- <Badge variant="outline" className={cn("gap-1.5 text-(length:--text-nano)", liveBlueBadge)}>- <span className="relative flex h-1.5 w-1.5">- <span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75" />- <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-blue-500" />- </span>- Live- </Badge>- )}+ <div+ data-testid="issue-detail-header"+ className={cn("space-y-3", shellSectionClass)}+ >+ <div className="flex items-center gap-2 min-w-0 flex-wrap">+ <StatusIcon+ status={issue.status}+ size="lg"+ blockerAttention={issue.blockerAttention}+ onChange={(status) => updateIssue.mutate({ status })}+ />+ {/* PAP-411: priority UI hidden behind SHOW_TASK_PRIORITY_UI. */}+ {SHOW_TASK_PRIORITY_UI && (+ <PriorityIcon+ priority={issue.priority}+ onChange={(priority) => updateIssue.mutate({ priority })}+ />+ )}+ <span className="text-sm font-mono text-muted-foreground shrink-0">+ {issue.identifier ?? issue.id.slice(0, 8)}+ </span>- {issue.originKind === "routine_execution" && issue.originId && (- <Link- to={`/routines/${issue.originId}`}- className="inline-flex items-center gap-1 rounded-full bg-violet-500/10 border border-violet-500/30 px-2 py-0.5 text-(length:--text-nano) font-medium text-violet-600 dark:text-violet-400 shrink-0 hover:bg-violet-500/20 transition-colors"- title={`Routine execution from routine ${issue.originId}`}- >- <Repeat className="h-3 w-3" />- Routine- </Link>- )}+ {hasLiveRuns && (+ <Badge+ variant="outline"+ className={cn("gap-1.5 text-(length:--text-nano)", liveBlueBadge)}+ >+ <span className="relative flex h-1.5 w-1.5">+ <span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75" />+ <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-blue-500" />+ </span>+ Live+ </Badge>+ )}- {issue.productivityReview ? (- <ProductivityReviewBadge review={issue.productivityReview} />- ) : null}+ {issue.originKind === "routine_execution" && issue.originId && (+ <Link+ to={`/routines/${issue.originId}`}+ className="inline-flex items-center gap-1 rounded-full bg-violet-500/10 border border-violet-500/30 px-2 py-0.5 text-(length:--text-nano) font-medium text-violet-600 dark:text-violet-400 shrink-0 hover:bg-violet-500/20 transition-colors"+ title={`Routine execution from routine ${issue.originId}`}+ >+ <Repeat className="h-3 w-3" />+ Routine+ </Link>+ )}- {issue.originKind === "issue_productivity_review" ? (- <Badge variant="outline"- className="border-amber-500/40 bg-amber-500/10 text-(length:--text-nano) text-amber-700 dark:text-amber-300"- title="This task is a productivity review."- >- <Eye className="h-3 w-3" />- Productivity review- </Badge>- ) : null}+ {issue.productivityReview ? (+ <ProductivityReviewBadge review={issue.productivityReview} />+ ) : null}- {issue.originKind === "task_watchdog" ? (- <Badge variant="outline"- className="border-sky-500/40 bg-sky-500/10 text-(length:--text-nano) text-sky-700 dark:text-sky-300"- title="This task is a generated watchdog task. It verifies whether stopped work in the watched task tree is legitimate."- >- <ScanEye className="h-3 w-3" />- Watchdog- </Badge>- ) : null}+ {issue.originKind === "issue_productivity_review" ? (+ <Badge+ variant="outline"+ className="border-amber-500/40 bg-amber-500/10 text-(length:--text-nano) text-amber-700 dark:text-amber-300"+ title="This task is a productivity review."+ >+ <Eye className="h-3 w-3" />+ Productivity review+ </Badge>+ ) : null}++ {issue.originKind === "task_watchdog" ? (+ <Badge+ variant="outline"+ className="border-sky-500/40 bg-sky-500/10 text-(length:--text-nano) text-sky-700 dark:text-sky-300"+ title="This task is a generated watchdog task. It verifies whether stopped work in the watched task tree is legitimate."+ >+ <ScanEye className="h-3 w-3" />+ Watchdog+ </Badge>+ ) : null}- {/* Task Chat Redesign: no mode chip in the header — mode is a+ {/* Task Chat Redesign: no mode chip in the header — mode is aper-request choice made in the composer, and each agent replycarries its own mode chip; a header chip would misread as atask-global setting. Flag OFF keeps the legacy badge. */}- {!taskChatShellEnabled && (issue.workMode === "ask" || issue.workMode === "planning") ? (() => {- const workModeMeta = workModeMetaFor(issue.workMode);- const WorkModeIcon = workModeMeta.icon;- return (- <Badge variant="outline"- className={cn("text-(length:--text-nano)", workModeMeta.classes.badge)}- title={`This task is in ${workModeMeta.label.toLowerCase()}.`}- >- <WorkModeIcon className="h-3 w-3" aria-hidden />- {workModeMeta.label}- </Badge>- );- })() : null}-- {hasAssignedBacklogBlocker(issue.blockedBy) ? (- <Badge variant="outline"- data-testid="issue-detail-parked-blocker"- className="border-amber-500/60 bg-amber-500/15 text-(length:--text-nano) text-amber-700 dark:text-amber-300"- title="Blocked by parked work — at least one assigned blocker is in backlog and will not wake its assignee."- >- <Flag className="h-3 w-3" />- Blocked by parked work- </Badge>- ) : null}+ {!taskChatShellEnabled &&+ (issue.workMode === "ask" || issue.workMode === "planning")+ ? (() => {+ const workModeMeta = workModeMetaFor(issue.workMode);+ const WorkModeIcon = workModeMeta.icon;+ return (+ <Badge+ variant="outline"+ className={cn(+ "text-(length:--text-nano)",+ workModeMeta.classes.badge,+ )}+ title={`This task is in ${workModeMeta.label.toLowerCase()}.`}+ >+ <WorkModeIcon className="h-3 w-3" aria-hidden />+ {workModeMeta.label}+ </Badge>+ );+ })()+ : null}++ {hasAssignedBacklogBlocker(issue.blockedBy) ? (+ <Badge+ variant="outline"+ data-testid="issue-detail-parked-blocker"+ className="border-amber-500/60 bg-amber-500/15 text-(length:--text-nano) text-amber-700 dark:text-amber-300"+ title="Blocked by parked work — at least one assigned blocker is in backlog and will not wake its assignee."+ >+ <Flag className="h-3 w-3" />+ Blocked by parked work+ </Badge>+ ) : null}- {/* Project reads as a tile plus a name, matching the project rows in+ {/* Project reads as a tile plus a name, matching the project rows inthe sidebar and the Projects list rather than a bare outlineglyph. The tile stays neutral here on purpose: the eyebrow alreadycarries the status glyph's colour, and a second tinted swatchbeside it competes with the one signal that means something.Project colour still identifies the project on project-nativesurfaces. */}- {issue.projectId ? (- <Link- to={`/projects/${issue.projectId}`}- className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors rounded px-1 -mx-1 py-0.5 min-w-0"- >- <ProjectTile size="xs" icon={resolvedProject?.icon ?? issue.project?.icon} />- <span className="truncate">{resolvedProject?.name ?? issue.project?.name ?? issue.projectId.slice(0, 8)}</span>- </Link>- ) : (- <span className="inline-flex items-center gap-1 text-xs text-muted-foreground opacity-50 px-1 -mx-1 py-0.5">- <ProjectTile size="xs" />- No project+ {issue.projectId ? (+ <Link+ to={`/projects/${issue.projectId}`}+ className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors rounded px-1 -mx-1 py-0.5 min-w-0"+ >+ <ProjectTile+ size="xs"+ icon={resolvedProject?.icon ?? issue.project?.icon}+ />+ <span className="truncate">+ {resolvedProject?.name ??+ issue.project?.name ??+ issue.projectId.slice(0, 8)}</span>- )}-- <IssueAttributionByline- issue={issue}- agentMap={agentMap}- userProfileMap={userProfileMap}- userLabelMap={userLabelMap}- />-- {(issue.labels ?? []).length > 0 && (- <div className="hidden sm:flex items-center gap-1">- {(issue.labels ?? []).slice(0, 4).map((label) => (- <Badge variant="outline"- key={label.id}- className="text-(length:--text-nano)"- style={{- borderColor: label.color,- color: pickTextColorForPillBg(label.color, 0.12),- backgroundColor: `${label.color}1f`,- }}- >- {label.name}- </Badge>- ))}- {(issue.labels ?? []).length > 4 && (- <span className="text-(length:--text-nano) text-muted-foreground">+{(issue.labels ?? []).length - 4}</span>- )}- </div>- )}+ </Link>+ ) : (+ <span className="inline-flex items-center gap-1 text-xs text-muted-foreground opacity-50 px-1 -mx-1 py-0.5">+ <ProjectTile size="xs" />+ No project+ </span>+ )}- {!(isMobile && isFromInbox) && (- <div className="ml-auto flex items-center gap-0.5 md:hidden shrink-0">- <Button- variant="ghost"- size="icon-xs"- onClick={copyIssueToClipboard}- title="Copy task as markdown"- >- {copied ? <Check className="h-4 w-4 text-green-500" /> : <Copy className="h-4 w-4" />}- </Button>- <Button- variant="ghost"- size="icon-xs"- onClick={() => setMobilePropsOpen(true)}- title="Properties"- >- <SlidersHorizontal className="h-4 w-4" />- </Button>- </div>- )}+ <IssueAttributionByline+ issue={issue}+ agentMap={agentMap}+ userProfileMap={userProfileMap}+ userLabelMap={userLabelMap}+ />- <div className="hidden md:flex items-center md:ml-auto shrink-0">- {canArchiveFromInbox && (- <Button- variant="ghost"- size="icon-xs"- onClick={() => {- if (!archivePending && issue?.id) archiveFromInbox.mutate(issue.id);+ {(issue.labels ?? []).length > 0 && (+ <div className="hidden sm:flex items-center gap-1">+ {(issue.labels ?? []).slice(0, 4).map((label) => (+ <Badge+ variant="outline"+ key={label.id}+ className="text-(length:--text-nano)"+ style={{+ borderColor: label.color,+ color: pickTextColorForPillBg(label.color, 0.12),+ backgroundColor: `${label.color}1f`,}}- disabled={archivePending}- title="Archive from inbox"- aria-label="Archive from inbox">- <Archive className="h-4 w-4" />- </Button>+ {label.name}+ </Badge>+ ))}+ {(issue.labels ?? []).length > 4 && (+ <span className="text-(length:--text-nano) text-muted-foreground">+ +{(issue.labels ?? []).length - 4}+ </span>)}- {fileViewerEnabled ? (- <Button- variant="ghost"- size="icon-xs"- onClick={() => setFileViewerPromptOpen(true)}- title="Open file... (g f)"- aria-label="Open file in this issue"- >- <FileCode2 className="h-4 w-4" />- </Button>- ) : null}+ </div>+ )}++ {!(isMobile && isFromInbox) && (+ <div className="ml-auto flex items-center gap-0.5 md:hidden shrink-0"><Buttonvariant="ghost"size="icon-xs"onClick={copyIssueToClipboard}title="Copy task as markdown">- {copied ? <Check className="h-4 w-4 text-green-500" /> : <Copy className="h-4 w-4" />}+ {copied ? (+ <Check className="h-4 w-4 text-green-500" />+ ) : (+ <Copy className="h-4 w-4" />+ )}+ </Button>+ <Button+ variant="ghost"+ size="icon-xs"+ onClick={() => setMobilePropsOpen(true)}+ title="Properties"+ >+ <SlidersHorizontal className="h-4 w-4" /></Button>+ </div>+ )}++ <div className="hidden md:flex items-center md:ml-auto shrink-0">+ {canArchiveFromInbox && (<Buttonvariant="ghost"size="icon-xs"- className={cn(- "shrink-0 transition-opacity duration-200",- panelVisible && !suppressPanelForFirstTask- ? "opacity-0 pointer-events-none w-0 overflow-hidden"- : "opacity-100",- )}onClick={() => {- if (suppressPanelForFirstTask && issue?.id) {- setFirstTaskPanelOverrideIssueId(issue.id);- }- setPanelVisible(true);+ if (!archivePending && issue?.id)+ archiveFromInbox.mutate(issue.id);}}- title="Show properties"+ disabled={archivePending}+ title="Archive from inbox"+ aria-label="Archive from inbox">- <SlidersHorizontal className="h-4 w-4" />+ <Archive className="h-4 w-4" /></Button>+ )}+ {fileViewerEnabled ? (+ <Button+ variant="ghost"+ size="icon-xs"+ onClick={() => setFileViewerPromptOpen(true)}+ title="Open file... (g f)"+ aria-label="Open file in this issue"+ >+ <FileCode2 className="h-4 w-4" />+ </Button>+ ) : null}+ <Button+ variant="ghost"+ size="icon-xs"+ onClick={copyIssueToClipboard}+ title="Copy task as markdown"+ >+ {copied ? (+ <Check className="h-4 w-4 text-green-500" />+ ) : (+ <Copy className="h-4 w-4" />+ )}+ </Button>+ {taskChatShellEnabled ||+ (panelVisible && !suppressPanelUntilPlan) ? null : (+ <TooltipProvider>+ <SidePanelToggleButton+ open={false}+ onToggle={openTaskSidePanel}+ shortcut="]"+ className="shrink-0"+ />+ </TooltipProvider>+ )}- <Popover open={moreOpen} onOpenChange={setMoreOpen}>- <PopoverTrigger asChild>- <Button- variant="ghost"- size="icon-xs"- className="shrink-0"- aria-label="More task actions"- title="More task actions"- onKeyDown={(event) => {- if (event.key === "Enter" || event.key === " ") {- event.preventDefault();- setMoreOpen(true);- }- }}- >- <MoreHorizontal className="h-4 w-4" />- </Button>- </PopoverTrigger>+ <Popover open={moreOpen} onOpenChange={setMoreOpen}>+ <PopoverTrigger asChild>+ <Button+ variant="ghost"+ size="icon-xs"+ className="shrink-0"+ aria-label="More task actions"+ title="More task actions"+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ setMoreOpen(true);+ }+ }}+ >+ <MoreHorizontal className="h-4 w-4" />+ </Button>+ </PopoverTrigger><PopoverContent className="w-52 p-1" align="end">{canPauseLeafWork ? (<button@@ -4793,7 +6638,9 @@ export function IssueDetail() {className="flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50"onClick={() => {setTreeControlMode("resume");- setTreeControlWakeAgentsOnResume(isAgentOwnedNonTerminalIssue);+ setTreeControlWakeAgentsOnResume(+ isAgentOwnedNonTerminalIssue,+ );setTreeControlOpen(true);setMoreOpen(false);}}@@ -4873,46 +6720,52 @@ export function IssueDetail() {Hide this task</button></PopoverContent>- </Popover>- </div>+ </Popover></div>+ </div>- <InlineEditor- value={issue.title}- onSave={(title) => updateIssue.mutateAsync({ title })}- as="h2"- className={taskChatShellEnabled ? "text-base font-semibold" : "text-xl font-bold"}- />+ <InlineEditor+ value={issue.title}+ onSave={(title) => updateIssue.mutateAsync({ title })}+ as="h2"+ className={+ taskChatShellEnabled ? "text-base font-semibold" : "text-xl font-bold"+ }+ />- {taskChatShellEnabled ? subTasksTree : null}+ {taskChatShellEnabled ? subTasksTree : null}- <IssueMonitorBanner- issue={issue}- onCheckNow={() => checkIssueMonitorNow.mutate()}- checkingNow={checkIssueMonitorNow.isPending}- />+ <IssueMonitorBanner+ issue={issue}+ onCheckNow={() => checkIssueMonitorNow.mutate()}+ checkingNow={checkIssueMonitorNow.isPending}+ />- {taskChatShellEnabled ? null : (- <InlineEditor- value={issue.description ?? ""}- onSave={(description) => updateIssue.mutateAsync({ description })}- as="p"- className="text-sm leading-7 text-foreground"- placeholder="Add a description..."- multiline- foldable- mentions={mentionOptions}- externalReferences={externalObjectsState.isEnabled ? externalObjectsState.markdownReferences : undefined}- imageUploadHandler={async (file) => {- const attachment = await uploadAttachment.mutateAsync(file);- return attachment.contentPath;- }}- onDropFile={async (file) => {- await uploadAttachment.mutateAsync(file);- }}- />- )}- </div>+ {taskChatShellEnabled ? null : (+ <InlineEditor+ value={issue.description ?? ""}+ onSave={(description) => updateIssue.mutateAsync({ description })}+ as="p"+ className="text-sm leading-7 text-foreground"+ placeholder="Add a description..."+ multiline+ foldable+ mentions={mentionOptions}+ externalReferences={+ externalObjectsState.isEnabled+ ? externalObjectsState.markdownReferences+ : undefined+ }+ imageUploadHandler={async (file) => {+ const attachment = await uploadAttachment.mutateAsync(file);+ return attachment.contentPath;+ }}+ onDropFile={async (file) => {+ await uploadAttachment.mutateAsync(file);+ }}+ />+ )}+ </div>);const pluginOutletsBlock = (@@ -4970,695 +6823,1002 @@ export function IssueDetail() {return (<FileViewerProvider issueId={issue.id} enabled={fileViewerEnabled}>- <div- data-task-chat-shell={taskChatShellEnabled ? "" : undefined}- className={- taskChatShellEnabled- ? isMobile- ? // Mobile shell scrolls the DOCUMENT (main is overflow-visible,- // auto height) — the thread renders in normal flow (PAP-360).- "flex w-full flex-col gap-6"- : // Fill main exactly so the outer page never scrolls — the- // thread's own viewport is the only scroll surface.- "flex h-full min-h-0 w-full flex-col gap-6"- : "max-w-3xl space-y-6"- }- >- {/* Parent chain breadcrumb (redesign: rendered inside the thread viewport) */}- {taskChatShellEnabled ? null : ancestorsNav}-- {issue.hiddenAt && (- <div className={cn("flex items-center gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive", shellSectionClass)}>- <EyeOff className="h-4 w-4 shrink-0" />- This task is hidden- </div>- )}- {activePauseHold && (- <div className={cn("rounded-md border border-amber-500/35 bg-amber-500/10 p-3 text-sm text-amber-800 dark:text-amber-200", shellSectionClass)}>- {activePauseHold.isRoot ? (- <div className="space-y-2">- <div className="flex flex-wrap items-center gap-2">- <span className="font-medium">- {childIssues.length === 0 ? "Paused by board." : "Subtree pause is active."}- </span>- <span className="text-xs text-amber-900/80 dark:text-amber-100/80">- {childIssues.length === 0- ? "Task execution is held until resume. Human comments can still wake the assignee for triage."- : "Root and descendant execution is held until resume. Human comments can still wake assignee agents for triage."}- </span>- </div>- <div className="text-xs text-amber-900/80 dark:text-amber-100/80">- {childIssues.length === 0- ? "1 task held"- : `${heldDescendantCount} descendant${heldDescendantCount === 1 ? "" : "s"} held`}- {activeRootPauseHold?.createdAt ? ` · started ${relativeTime(activeRootPauseHold.createdAt)}` : ""}- </div>- {canShowSubtreeControls || canResumeLeafWork ? (+ <div+ data-task-chat-shell={taskChatShellEnabled ? "" : undefined}+ className={+ taskChatShellEnabled+ ? isMobile+ ? // Mobile shell scrolls the DOCUMENT (main is overflow-visible,+ // auto height) — the thread renders in normal flow (PAP-360).+ "flex w-full flex-col gap-6"+ : // Fill main exactly so the outer page never scrolls — the+ // thread's own viewport is the only scroll surface.+ "flex h-full min-h-0 w-full flex-col gap-6"+ : "max-w-3xl space-y-6"+ }+ >+ {/* Parent chain breadcrumb (redesign: rendered inside the thread viewport) */}+ {taskChatShellEnabled ? null : ancestorsNav}++ {issue.hiddenAt && (+ <div+ className={cn(+ "flex items-center gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",+ shellSectionClass,+ )}+ >+ <EyeOff className="h-4 w-4 shrink-0" />+ This task is hidden+ </div>+ )}+ {activePauseHold && (+ <div+ className={cn(+ "rounded-md border border-amber-500/35 bg-amber-500/10 p-3 text-sm text-amber-800 dark:text-amber-200",+ shellSectionClass,+ )}+ >+ {activePauseHold.isRoot ? (+ <div className="space-y-2"><div className="flex flex-wrap items-center gap-2">- <Button- size="sm"- onClick={() => {- setTreeControlMode("resume");- setTreeControlWakeAgentsOnResume(isAgentOwnedNonTerminalIssue || canShowSubtreeControls);- setTreeControlOpen(true);- }}- >- {childIssues.length === 0 ? "Resume work" : "Resume subtree"}- </Button>- <Button- variant="outline"- size="sm"- onClick={() => {- setTreeControlMode("resume");- setTreeControlWakeAgentsOnResume(isAgentOwnedNonTerminalIssue || canShowSubtreeControls);- setTreeControlOpen(true);- }}- >- View affected ({childIssues.length === 0 ? 1 : heldDescendantCount})- </Button>- {canShowSubtreeControls ? (+ <span className="font-medium">+ {childIssues.length === 0+ ? "Paused by board."+ : "Subtree pause is active."}+ </span>+ <span className="text-xs text-amber-900/80 dark:text-amber-100/80">+ {childIssues.length === 0+ ? "Task execution is held until resume. Human comments can still wake the assignee for triage."+ : "Root and descendant execution is held until resume. Human comments can still wake assignee agents for triage."}+ </span>+ </div>+ <div className="text-xs text-amber-900/80 dark:text-amber-100/80">+ {childIssues.length === 0+ ? "1 task held"+ : `${heldDescendantCount} descendant${heldDescendantCount === 1 ? "" : "s"} held`}+ {activeRootPauseHold?.createdAt+ ? ` · started ${relativeTime(activeRootPauseHold.createdAt)}`+ : ""}+ </div>+ {canShowSubtreeControls || canResumeLeafWork ? (+ <div className="flex flex-wrap items-center gap-2"><Button- variant="ghost"size="sm"- className="text-destructive hover:text-destructive"onClick={() => {- setTreeControlMode("cancel");- setTreeControlCancelConfirmed(false);+ setTreeControlMode("resume");+ setTreeControlWakeAgentsOnResume(+ isAgentOwnedNonTerminalIssue ||+ canShowSubtreeControls,+ );setTreeControlOpen(true);}}>- Cancel subtree...+ {childIssues.length === 0+ ? "Resume work"+ : "Resume subtree"}</Button>- ) : null}- </div>- ) : null}- </div>- ) : (- <div className="text-xs">- This task is paused by ancestor{" "}- {activePauseHoldRoot?.identifier ? (- <Link to={createIssueDetailPath(activePauseHoldRoot.identifier)} className="underline">- {activePauseHoldRoot.identifier}- </Link>- ) : (- activePauseHold.rootIssueId.slice(0, 8)- )}- . Resume from the root task to deliver deferred work.- </div>- )}- </div>- )}+ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ setTreeControlMode("resume");+ setTreeControlWakeAgentsOnResume(+ isAgentOwnedNonTerminalIssue ||+ canShowSubtreeControls,+ );+ setTreeControlOpen(true);+ }}+ >+ View affected (+ {childIssues.length === 0 ? 1 : heldDescendantCount})+ </Button>+ {canShowSubtreeControls ? (+ <Button+ variant="ghost"+ size="sm"+ className="text-destructive hover:text-destructive"+ onClick={() => {+ setTreeControlMode("cancel");+ setTreeControlCancelConfirmed(false);+ setTreeControlOpen(true);+ }}+ >+ Cancel subtree...+ </Button>+ ) : null}+ </div>+ ) : null}+ </div>+ ) : (+ <div className="text-xs">+ This task is paused by ancestor{" "}+ {activePauseHoldRoot?.identifier ? (+ <Link+ to={createIssueDetailPath(activePauseHoldRoot.identifier)}+ className="underline"+ >+ {activePauseHoldRoot.identifier}+ </Link>+ ) : (+ activePauseHold.rootIssueId.slice(0, 8)+ )}+ . Resume from the root task to deliver deferred work.+ </div>+ )}+ </div>+ )}- {taskChatShellEnabled ? null : issueHeaderBlock}+ {taskChatShellEnabled ? null : issueHeaderBlock}- {taskChatShellEnabled ? null : pluginOutletsBlock}+ {taskChatShellEnabled ? null : pluginOutletsBlock}- {taskChatShellEnabled ? null : showRichSubIssuesSection ? (- <div className="space-y-3">- <div className="flex items-center justify-between gap-2">- <h3 className="text-sm font-medium text-muted-foreground">Sub-tasks</h3>+ {taskChatShellEnabled ? null : showRichSubIssuesSection ? (+ <div className="space-y-3">+ <div className="flex items-center justify-between gap-2">+ <h3 className="text-sm font-medium text-muted-foreground">+ Sub-tasks+ </h3>+ </div>+ <IssuesList+ issues={childIssues}+ isLoading={childIssuesLoading}+ agents={agents}+ projects={projects}+ liveIssueIds={liveIssueIds}+ mutedIssueIds={mutedChildIssueIds}+ issueBadgeById={childPauseBadgeById}+ projectId={issue.projectId ?? undefined}+ viewStateKey={`paperclip:issue-detail:${issue.id}:subissues-view`}+ issueLinkState={resolvedIssueDetailState ?? location.state}+ searchFilters={{ descendantOf: issue.id, includeBlockedBy: true }}+ searchWithinLoadedIssues+ baseCreateIssueDefaults={buildSubIssueDefaultsForViewer(+ issue,+ currentUserId,+ )}+ createIssueLabel="Sub-task"+ defaultSortField="workflow"+ showProgressSummary+ parentIssueIdForCostSummary={issue.id}+ onUpdateIssue={handleChildIssueUpdate}+ /></div>- <IssuesList- issues={childIssues}- isLoading={childIssuesLoading}- agents={agents}- projects={projects}- liveIssueIds={liveIssueIds}- mutedIssueIds={mutedChildIssueIds}- issueBadgeById={childPauseBadgeById}- projectId={issue.projectId ?? undefined}- viewStateKey={`paperclip:issue-detail:${issue.id}:subissues-view`}- issueLinkState={resolvedIssueDetailState ?? location.state}- searchFilters={{ descendantOf: issue.id, includeBlockedBy: true }}- searchWithinLoadedIssues- baseCreateIssueDefaults={buildSubIssueDefaultsForViewer(issue, currentUserId)}- createIssueLabel="Sub-task"- defaultSortField="workflow"- showProgressSummary- parentIssueIdForCostSummary={issue.id}- onUpdateIssue={handleChildIssueUpdate}- />- </div>- ) : (- <div className="flex flex-wrap items-center justify-end gap-2 min-w-0">- <Button variant="outline" size="sm" onClick={openNewSubIssue} className="shrink-0 shadow-none">- <Plus className="mr-1.5 h-3.5 w-3.5" />- New Sub-task- </Button>- </div>- )}+ ) : (+ <div className="flex flex-wrap items-center justify-end gap-2 min-w-0">+ <Button+ variant="outline"+ size="sm"+ onClick={openNewSubIssue}+ className="shrink-0 shadow-none"+ >+ <Plus className="mr-1.5 h-3.5 w-3.5" />+ New Sub-task+ </Button>+ </div>+ )}- {!taskChatShellEnabled && showPlanDecompositionsSection ? (- <IssuePlanDecompositionsSection- issueId={issue.id}- issueIdentifier={issue.identifier}- agentMap={agentMap}- />- ) : null}+ {!taskChatShellEnabled && showPlanDecompositionsSection ? (+ <IssuePlanDecompositionsSection+ issueId={issue.id}+ issueIdentifier={issue.identifier}+ agentMap={agentMap}+ />+ ) : null}- {/* Flag ON: attachments/work products/workspace live in the properties+ {/* Flag ON: attachments/work products/workspace live in the propertiespane (Artifacts tab) — the center column belongs to the thread. */}- {taskChatShellEnabled ? null : (- <IssueDocumentsSection- issue={issue}- canDeleteDocuments={Boolean(session?.user?.id)}- canManageDocumentLocks={Boolean(session?.user?.id)}- feedbackVotes={feedbackVotes}- feedbackDataSharingPreference={feedbackDataSharingPreference}- feedbackTermsUrl={FEEDBACK_TERMS_URL}- mentions={mentionOptions}- externalReferences={externalObjectsState.isEnabled ? externalObjectsState.markdownReferences : undefined}- imageUploadHandler={async (file) => {- const attachment = await uploadAttachment.mutateAsync(file);- return attachment.contentPath;- }}- onVote={async (revisionId, vote, options) => {- await feedbackVoteMutation.mutateAsync({- targetType: "issue_document_revision",- targetId: revisionId,- vote,- reason: options?.reason,- allowSharing: options?.allowSharing,- sharingPreferenceAtSubmit: feedbackDataSharingPreference,- });- }}- extraActions={!hasAttachments ? attachmentUploadButton : null}- agentMap={agentMap}- userProfileMap={userProfileMap}- />- )}+ {taskChatShellEnabled ? null : (+ <IssueDocumentsSection+ issue={issue}+ canDeleteDocuments={Boolean(session?.user?.id)}+ canManageDocumentLocks={Boolean(session?.user?.id)}+ feedbackVotes={feedbackVotes}+ feedbackDataSharingPreference={feedbackDataSharingPreference}+ feedbackTermsUrl={FEEDBACK_TERMS_URL}+ mentions={mentionOptions}+ externalReferences={+ externalObjectsState.isEnabled+ ? externalObjectsState.markdownReferences+ : undefined+ }+ imageUploadHandler={async (file) => {+ const attachment = await uploadAttachment.mutateAsync(file);+ return attachment.contentPath;+ }}+ onVote={async (revisionId, vote, options) => {+ await feedbackVoteMutation.mutateAsync({+ targetType: "issue_document_revision",+ targetId: revisionId,+ vote,+ reason: options?.reason,+ allowSharing: options?.allowSharing,+ sharingPreferenceAtSubmit: feedbackDataSharingPreference,+ });+ }}+ extraActions={!hasAttachments ? attachmentUploadButton : null}+ agentMap={agentMap}+ userProfileMap={userProfileMap}+ />+ )}- {taskChatShellEnabled ? null : (- <IssueOutputSection- workProducts={workProducts}- onMediaClick={(item) => {- const meta = item.metadata;- if (!meta) return;- const idx = mediaGalleryItems.findIndex((galleryItem) => (- galleryItem.contentPath === meta.contentPath ||- galleryItem.id === `work-product-${item.id}` ||- galleryItem.id === meta.attachmentId- ));- setGalleryIndex(idx >= 0 ? idx : 0);- setGalleryOpen(true);- }}- />- )}+ {taskChatShellEnabled ? null : (+ <IssueOutputSection+ workProducts={workProducts}+ onMediaClick={(item) => {+ const meta = item.metadata;+ if (!meta) return;+ const idx = mediaGalleryItems.findIndex(+ (galleryItem) =>+ galleryItem.contentPath === meta.contentPath ||+ galleryItem.id === `work-product-${item.id}` ||+ galleryItem.id === meta.attachmentId,+ );+ setGalleryIndex(idx >= 0 ? idx : 0);+ setGalleryOpen(true);+ }}+ />+ )}- {taskChatShellEnabled ? null : attachmentsInitialLoading ? (- <IssueSectionSkeleton titleWidth="w-24" rows={2} />- ) : hasAttachments ? (- <IssueAttachmentsSection- attachments={attachmentList}- uploadButton={attachmentUploadButton}- error={attachmentError}- dragActive={attachmentDragActive}- deletePending={deleteAttachment.isPending}- onDelete={(attachmentId) => deleteAttachment.mutate(attachmentId)}- onImageClick={(attachment) => {- const idx = mediaGalleryItems.findIndex((a) => a.id === attachment.id);- setGalleryIndex(idx >= 0 ? idx : 0);- setGalleryOpen(true);- }}- onDragEnter={(evt) => {- evt.preventDefault();- setAttachmentDragActive(true);- }}- onDragOver={(evt) => {- evt.preventDefault();- setAttachmentDragActive(true);- }}- onDragLeave={(evt) => {- if (evt.currentTarget.contains(evt.relatedTarget as Node | null)) return;- setAttachmentDragActive(false);- }}- onDrop={(evt) => void handleAttachmentDrop(evt)}- />- ) : null}+ {taskChatShellEnabled ? null : attachmentsInitialLoading ? (+ <IssueSectionSkeleton titleWidth="w-24" rows={2} />+ ) : hasAttachments ? (+ <IssueAttachmentsSection+ attachments={attachmentList}+ uploadButton={attachmentUploadButton}+ error={attachmentError}+ dragActive={attachmentDragActive}+ deletePending={deleteAttachment.isPending}+ onDelete={(attachmentId) => deleteAttachment.mutate(attachmentId)}+ onImageClick={(attachment) => {+ const idx = mediaGalleryItems.findIndex(+ (a) => a.id === attachment.id,+ );+ setGalleryIndex(idx >= 0 ? idx : 0);+ setGalleryOpen(true);+ }}+ onDragEnter={(evt) => {+ evt.preventDefault();+ setAttachmentDragActive(true);+ }}+ onDragOver={(evt) => {+ evt.preventDefault();+ setAttachmentDragActive(true);+ }}+ onDragLeave={(evt) => {+ if (evt.currentTarget.contains(evt.relatedTarget as Node | null))+ return;+ setAttachmentDragActive(false);+ }}+ onDrop={(evt) => void handleAttachmentDrop(evt)}+ />+ ) : null}- <ImageGalleryModal- items={mediaGalleryItems}- initialIndex={galleryIndex}- open={galleryOpen}- onOpenChange={setGalleryOpen}- />+ <ImageGalleryModal+ items={mediaGalleryItems}+ initialIndex={galleryIndex}+ open={galleryOpen}+ onOpenChange={setGalleryOpen}+ />- {taskChatShellEnabled ? null : (- <IssueWorkspaceCard- issue={issue}- project={resolvedProject}- onUpdate={(data) => updateIssue.mutate(data)}- onBrowseFiles={fileViewerEnabled ? () => setFileViewerPromptOpen(true) : undefined}- onOpenFileByPath={fileViewerEnabled ? () => setFileViewerPromptOpen(true) : undefined}- />- )}+ {taskChatShellEnabled ? null : (+ <IssueWorkspaceCard+ issue={issue}+ project={resolvedProject}+ onUpdate={(data) => updateIssue.mutate(data)}+ onBrowseFiles={+ fileViewerEnabled+ ? () => setFileViewerPromptOpen(true)+ : undefined+ }+ onOpenFileByPath={+ fileViewerEnabled+ ? () => setFileViewerPromptOpen(true)+ : undefined+ }+ />+ )}- {!taskChatShellEnabled && fileViewerEnabled && issue.workProducts && issue.workProducts.length > 0 && (() => {- const workProductsWithFileRefs = issue.workProducts- .map((product) => ({ product, fileRef: extractWorkspaceFileRefFromWorkProduct(product) }))- .filter(({ fileRef }) => fileRef !== null);+ {!taskChatShellEnabled &&+ fileViewerEnabled &&+ issue.workProducts &&+ issue.workProducts.length > 0 &&+ (() => {+ const workProductsWithFileRefs = issue.workProducts+ .map((product) => ({+ product,+ fileRef: extractWorkspaceFileRefFromWorkProduct(product),+ }))+ .filter(({ fileRef }) => fileRef !== null);- if (workProductsWithFileRefs.length === 0) return null;+ if (workProductsWithFileRefs.length === 0) return null;- return (- <div className="space-y-3">- <div className="flex items-center justify-between gap-2">- <h3 className="text-sm font-medium text-muted-foreground">Artifacts</h3>- </div>- <div className="flex flex-wrap gap-2">- {workProductsWithFileRefs.map(({ product, fileRef }) => (- <ArtifactFileChip- key={product.id}- workspaceFileRef={fileRef!}- title={product.title}- />- ))}- </div>- </div>- );- })()}-- {taskChatShellEnabled ? null : <Separator className={shellSectionClass} />}+ return (+ <div className="space-y-3">+ <div className="flex items-center justify-between gap-2">+ <h3 className="text-sm font-medium text-muted-foreground">+ Artifacts+ </h3>+ </div>+ <div className="flex flex-wrap gap-2">+ {workProductsWithFileRefs.map(({ product, fileRef }) => (+ <ArtifactFileChip+ key={product.id}+ workspaceFileRef={fileRef!}+ title={product.title}+ />+ ))}+ </div>+ </div>+ );+ })()}- <Tabs- value={resolvedDetailTab}- onValueChange={setDetailTab}- className={taskChatShellEnabled ? (isMobile ? undefined : "min-h-0 flex-1") : "space-y-3"}- >- {/* Redesign: the chat IS the page — the Chat/Activity/Related-work tab- strip is hidden and the thread renders as the only surface. */}{taskChatShellEnabled ? null : (- <TabsList variant="line" className={cn("w-full justify-start gap-1", shellSectionClass)}>- <TabsTrigger value="chat" className="gap-1.5">- <MessageSquare className="h-3.5 w-3.5" />- Chat- </TabsTrigger>- <TabsTrigger value="activity" className="gap-1.5">- <ActivityIcon className="h-3.5 w-3.5" />- Activity- </TabsTrigger>- <TabsTrigger value="related-work" className="gap-1.5">- <ListTree className="h-3.5 w-3.5" />- Related work- </TabsTrigger>- {issuePluginTabItems.map((item) => (- <TabsTrigger key={item.value} value={item.value}>- {item.label}- </TabsTrigger>- ))}- </TabsList>+ <Separator className={shellSectionClass} />)}- {/* Flag ON the thread viewport extends under main's horizontal padding- (symmetric, so the centered column keeps the same axis) and the- scrollbar sits flush against the properties-pane border. */}- <TabsContent- data-testid="issue-detail-content"- value="chat"+ <Tabs+ value={resolvedDetailTab}+ onValueChange={setDetailTab}className={taskChatShellEnabled? isMobile- ? "-mx-4"- : "-mx-4 md:-mx-6 flex min-h-0 flex-col"- : undefined+ ? undefined+ : "min-h-0 flex-1"+ : "space-y-3"}>- {resolvedDetailTab === "chat" ? (- <IssueDetailChatTab- threadHeader={taskChatThreadHeader}- issueBrief={- // Suppress the seeded-description bubble for the onboarding first- // task: its description is agent instructions, not something the- // user typed. The user lands on a seeded agent greeting instead.- taskChatShellEnabled &&- issue.originKind !== ONBOARDING_FIRST_TASK_ORIGIN_KIND- ? {- description: issue.description ?? "",- author: issue.createdByAgentId ? "agent" : "human",- authorName: issue.createdByAgentId- ? agentMap.get(issue.createdByAgentId)?.name ?? "Agent"- : undefined,- agentIcon: issue.createdByAgentId- ? agentMap.get(issue.createdByAgentId)?.icon- : undefined,- createdAt: issue.createdAt,- onSave: (description) => updateIssue.mutateAsync({ description }),- mentions: mentionOptions,- externalReferences: externalObjectsState.isEnabled- ? externalObjectsState.markdownReferences- : undefined,- imageUploadHandler: async (file) => {- const attachment = await uploadAttachment.mutateAsync(file);- return attachment.contentPath;- },- onDropFile: async (file) => {- await uploadAttachment.mutateAsync(file);- },- }+ {/* Redesign: the chat IS the page — the Chat/Activity/Related-work tab+ strip is hidden and the thread renders as the only surface. */}+ {taskChatShellEnabled ? null : (+ <TabsList+ variant="line"+ className={cn("w-full justify-start gap-1", shellSectionClass)}+ >+ <TabsTrigger value="chat" className="gap-1.5">+ <MessageSquare className="h-3.5 w-3.5" />+ Chat+ </TabsTrigger>+ <TabsTrigger value="activity" className="gap-1.5">+ <ActivityIcon className="h-3.5 w-3.5" />+ Activity+ </TabsTrigger>+ <TabsTrigger value="related-work" className="gap-1.5">+ <ListTree className="h-3.5 w-3.5" />+ Related work+ </TabsTrigger>+ {issuePluginTabItems.map((item) => (+ <TabsTrigger key={item.value} value={item.value}>+ {item.label}+ </TabsTrigger>+ ))}+ </TabsList>+ )}++ {/* Flag ON the thread viewport extends under main's horizontal padding+ (symmetric, so the centered column keeps the same axis) and its top+ padding, placing task metadata in the side-panel tab header band. */}+ <TabsContent+ data-testid="issue-detail-content"+ value="chat"+ className={+ taskChatShellEnabled+ ? isMobile+ ? "-mx-4"+ : "-mx-4 -mt-4 md:-mx-6 md:-mt-6 flex min-h-0 flex-col"+ : undefined+ }+ >+ {resolvedDetailTab === "chat" ? (+ <IssueDetailChatTab+ threadHeader={taskChatThreadHeader}+ issueBrief={+ // Suppress the seeded-description bubble for the onboarding first+ // task: its description is agent instructions, not something the+ // user typed. The user lands on a seeded agent greeting instead.+ taskChatShellEnabled &&+ issue.originKind !== ONBOARDING_FIRST_TASK_ORIGIN_KIND+ ? {+ description: issue.description ?? "",+ author: issue.createdByAgentId ? "agent" : "human",+ authorName: issue.createdByAgentId+ ? (agentMap.get(issue.createdByAgentId)?.name ??+ "Agent")+ : undefined,+ agentIcon: issue.createdByAgentId+ ? agentMap.get(issue.createdByAgentId)?.icon+ : undefined,+ createdAt: issue.createdAt,+ onSave: (description) =>+ updateIssue.mutateAsync({ description }),+ mentions: mentionOptions,+ externalReferences: externalObjectsState.isEnabled+ ? externalObjectsState.markdownReferences+ : undefined,+ imageUploadHandler: async (file) => {+ const attachment =+ await uploadAttachment.mutateAsync(file);+ return attachment.contentPath;+ },+ onDropFile: async (file) => {+ await uploadAttachment.mutateAsync(file);+ },+ }+ : undefined+ }+ issueId={issue.id}+ companyId={issue.companyId}+ projectId={issue.projectId ?? null}+ issueStatus={issue.status}+ issueAssigneeAgentId={issue.assigneeAgentId}+ issueWorkMode={issue.workMode ?? "standard"}+ executionRunId={issue.executionRunId ?? null}+ blockedBy={issue.blockedBy ?? []}+ liveIssueIds={liveIssueIds}+ blockerAttention={issue.blockerAttention ?? null}+ successfulRunHandoff={issue.successfulRunHandoff ?? null}+ scheduledRetry={issue.scheduledRetry ?? null}+ recoveryAction={issue.activeRecoveryAction ?? null}+ onResolveRecoveryAction={handleResolveRecoveryAction}+ onReissueIsolatedRecoveryAction={+ handleReissueIsolatedRecoveryAction+ }+ reissueIsolatedRecoveryActionPending={+ reissueIsolatedRecoveryAction.isPending+ }+ onReconcileForwardRecoveryAction={+ handleReconcileForwardRecoveryAction+ }+ onBreakGlassOverrideRecoveryAction={+ handleBreakGlassOverrideRecoveryAction+ }+ onQuarantineRestoreRecoveryAction={+ handleQuarantineRestoreRecoveryAction+ }+ quarantineRestoreRecoveryActionPending={+ reconcileRecoveryAction.isPending+ }+ canBreakGlassRecoveryAction={canManageBoardRuntime}+ reconcileRecoveryActionPending={+ reconcileRecoveryAction.isPending+ }+ canFalsePositiveRecoveryAction={canResolveBoardRecoveryAction}+ legacyRecoverySourceIssue={legacyRecoverySourceIssue}+ comments={threadComments}+ commentsInitialLoading={commentsLoading}+ locallyQueuedCommentRunIds={locallyQueuedCommentRunIds}+ interactions={interactions}+ documents={issue.documentSummaries ?? []}+ workProducts={workProducts ?? []}+ attachments={attachments ?? []}+ hasOlderComments={hasOlderComments}+ commentsLoadingOlder={commentsLoadingOlder}+ onLoadOlderComments={loadOlderComments}+ onRefreshLatestComments={refetchLatestComments}+ composerRef={commentComposerRef}+ composerAccessory={+ hasVisibleMonitorSurface(issue) ? (+ <IssueMonitorComposerStrip+ issue={issue}+ onCheckNow={() => checkIssueMonitorNow.mutate()}+ checkingNow={checkIssueMonitorNow.isPending}+ />+ ) : null+ }+ footer={+ !taskChatShellEnabled && siblingNavigation ? (+ <IssueSiblingNavigation+ navigation={siblingNavigation}+ linkState={resolvedIssueDetailState ?? location.state}+ />+ ) : null+ }+ feedbackVotes={feedbackVotes}+ feedbackDataSharingPreference={feedbackDataSharingPreference}+ feedbackTermsUrl={FEEDBACK_TERMS_URL}+ agentMap={agentMap}+ currentUserId={currentUserId}+ userLabelMap={userLabelMap}+ userProfileMap={userProfileMap}+ draftKey={`paperclip:issue-comment-draft:${issue.id}`}+ reassignOptions={commentReassignOptions}+ currentAssigneeValue={actualAssigneeValue}+ suggestedAssigneeValue={suggestedAssigneeValue}+ mentions={mentionOptions}+ composerDisabledReason={null}+ composerHint={composerHint}+ queuedCommentReason={queuedCommentReason}+ onVote={handleCommentVote}+ onAdd={handleChatAdd}+ onImageUpload={handleCommentImageUpload}+ onAttachImage={handleCommentAttachImage}+ onInterruptQueued={handleInterruptQueuedRun}+ onDeleteComment={(commentId) =>+ deleteComment.mutateAsync({ commentId }).then(() => undefined)+ }+ onPauseWorkRun={+ canManageTreeControl+ ? (runId) =>+ pauseIssueWorkRun+ .mutateAsync({ runId, scope: treeControlScope })+ .then(() => undefined)+ : undefined+ }+ runFinalizationActions={runFinalizationActions}+ onWorkModeChange={(nextMode) => {+ const currentMode: IssueWorkMode =+ issue.workMode ?? "standard";+ if (currentMode === nextMode) return;+ return updateIssue+ .mutateAsync({ workMode: nextMode })+ .then(() => undefined);+ }}+ onCancelQueued={handleCancelQueuedComment}+ interruptingQueuedRunId={+ interruptQueuedComment.isPending+ ? (interruptQueuedComment.variables ?? null)+ : null+ }+ pausingWorkRunId={+ pauseIssueWorkRun.isPending+ ? (pauseIssueWorkRun.variables?.runId ?? null)+ : null+ }+ onImageClick={handleChatImageClick}+ onAcceptInteraction={handleAcceptInteraction}+ onRejectInteraction={handleRejectInteraction}+ onSubmitInteractionAnswers={handleSubmitInteractionAnswers}+ onCancelInteraction={handleCancelInteraction}+ onSkipInteraction={handleSkipInteraction}+ onSubmitInteractionVerdicts={handleSubmitInteractionVerdicts}+ assigneeUserId={issue.assigneeUserId ?? null}+ onResumeFromBacklog={+ canResumeFromBacklog ? handleResumeFromBacklog : undefined+ }+ resumeFromBacklogPending={+ updateIssue.isPending &&+ updateIssue.variables?.status === "todo"+ }+ onResumeAssignee={+ issue.assigneeAgentId ? handleResumeAssignee : undefined+ }+ resumeAssigneePending={resumeAssigneeAgent.isPending}+ onTryAgainNoLiveExecutionPath={+ issue.status === "blocked" && issue.activeRecoveryAction+ ? handleTryAgainNoLiveExecutionPath+ : undefined+ }+ tryAgainNoLiveExecutionPathPending={+ resolveRecoveryAction.isPending &&+ resolveRecoveryAction.variables?.sourceIssueStatus === "todo"+ }+ externalReferences={+ externalObjectsState.isEnabled+ ? externalObjectsState.markdownReferences+ : undefined+ }+ linkCaseReferences={casesChipsEnabled}+ />+ ) : null}+ </TabsContent>++ <TabsContent value="activity" className={shellSectionClass}>+ {detailTab === "activity" ? (+ <IssueDetailActivityTab+ issue={issue}+ issueId={issue.id}+ companyId={issue.companyId}+ issueStatus={issue.status}+ childIssues={childIssues}+ agentMap={agentMap}+ hasLiveRuns={hasLiveRuns}+ currentUserId={currentUserId}+ userProfileMap={userProfileMap}+ pendingApprovalAction={pendingApprovalAction}+ handoffFocusSignal={handoffFocusSignal}+ onApprovalAction={(approvalId, action) => {+ approvalDecision.mutate({ approvalId, action });+ }}+ externalReferences={+ externalObjectsState.isEnabled+ ? externalObjectsState.markdownReferences+ : undefined+ }+ />+ ) : null}+ </TabsContent>++ <TabsContent value="related-work" className={shellSectionClass}>+ <IssueRelatedWorkPanel+ relatedWork={issue.relatedWork}+ externalObjectsEnabled={externalObjectsState.isEnabled}+ externalObjects={+ externalObjectsState.isEnabled+ ? externalObjectsState.groups: undefined}- issueId={issue.id}- companyId={issue.companyId}- projectId={issue.projectId ?? null}- issueStatus={issue.status}- issueAssigneeAgentId={issue.assigneeAgentId}- issueWorkMode={issue.workMode ?? "standard"}- executionRunId={issue.executionRunId ?? null}- blockedBy={issue.blockedBy ?? []}- liveIssueIds={liveIssueIds}- blockerAttention={issue.blockerAttention ?? null}- successfulRunHandoff={issue.successfulRunHandoff ?? null}- scheduledRetry={issue.scheduledRetry ?? null}- recoveryAction={issue.activeRecoveryAction ?? null}- onResolveRecoveryAction={handleResolveRecoveryAction}- onReissueIsolatedRecoveryAction={handleReissueIsolatedRecoveryAction}- reissueIsolatedRecoveryActionPending={reissueIsolatedRecoveryAction.isPending}- onReconcileForwardRecoveryAction={handleReconcileForwardRecoveryAction}- onBreakGlassOverrideRecoveryAction={handleBreakGlassOverrideRecoveryAction}- onQuarantineRestoreRecoveryAction={handleQuarantineRestoreRecoveryAction}- quarantineRestoreRecoveryActionPending={reconcileRecoveryAction.isPending}- canBreakGlassRecoveryAction={canManageBoardRuntime}- reconcileRecoveryActionPending={reconcileRecoveryAction.isPending}- canFalsePositiveRecoveryAction={canResolveBoardRecoveryAction}- legacyRecoverySourceIssue={legacyRecoverySourceIssue}- comments={threadComments}- commentsInitialLoading={commentsLoading}- locallyQueuedCommentRunIds={locallyQueuedCommentRunIds}- interactions={interactions}- hasOlderComments={hasOlderComments}- commentsLoadingOlder={commentsLoadingOlder}- onLoadOlderComments={loadOlderComments}- onRefreshLatestComments={refetchLatestComments}- composerRef={commentComposerRef}- composerAccessory={- hasVisibleMonitorSurface(issue) ? (- <IssueMonitorComposerStrip- issue={issue}- onCheckNow={() => checkIssueMonitorNow.mutate()}- checkingNow={checkIssueMonitorNow.isPending}- />- ) : null+ externalObjectsLoading={+ externalObjectsState.isEnabled+ ? externalObjectsState.isLoading+ : undefined}- footer={- !taskChatShellEnabled && siblingNavigation ? (- <IssueSiblingNavigation- navigation={siblingNavigation}- linkState={resolvedIssueDetailState ?? location.state}- />- ) : null+ externalObjectsError={+ externalObjectsState.isEnabled+ ? externalObjectsState.isError+ : undefined}- feedbackVotes={feedbackVotes}- feedbackDataSharingPreference={feedbackDataSharingPreference}- feedbackTermsUrl={FEEDBACK_TERMS_URL}- agentMap={agentMap}- currentUserId={currentUserId}- userLabelMap={userLabelMap}- userProfileMap={userProfileMap}- draftKey={`paperclip:issue-comment-draft:${issue.id}`}- reassignOptions={commentReassignOptions}- currentAssigneeValue={actualAssigneeValue}- suggestedAssigneeValue={suggestedAssigneeValue}- mentions={mentionOptions}- composerDisabledReason={null}- composerHint={composerHint}- queuedCommentReason={queuedCommentReason}- onVote={handleCommentVote}- onAdd={handleChatAdd}- onImageUpload={handleCommentImageUpload}- onAttachImage={handleCommentAttachImage}- onInterruptQueued={handleInterruptQueuedRun}- onDeleteComment={(commentId) => deleteComment.mutateAsync({ commentId }).then(() => undefined)}- onPauseWorkRun={canManageTreeControl- ? (runId) => pauseIssueWorkRun.mutateAsync({ runId, scope: treeControlScope }).then(() => undefined)- : undefined}- runFinalizationActions={runFinalizationActions}- onWorkModeChange={(nextMode) => {- const currentMode: IssueWorkMode = issue.workMode ?? "standard";- if (currentMode === nextMode) return;- return updateIssue.mutateAsync({ workMode: nextMode }).then(() => undefined);- }}- onCancelQueued={handleCancelQueuedComment}- interruptingQueuedRunId={interruptQueuedComment.isPending ? interruptQueuedComment.variables ?? null : null}- pausingWorkRunId={pauseIssueWorkRun.isPending ? pauseIssueWorkRun.variables?.runId ?? null : null}- onImageClick={handleChatImageClick}- onAcceptInteraction={handleAcceptInteraction}- onRejectInteraction={handleRejectInteraction}- onSubmitInteractionAnswers={handleSubmitInteractionAnswers}- onCancelInteraction={handleCancelInteraction}- onSubmitInteractionVerdicts={handleSubmitInteractionVerdicts}- assigneeUserId={issue.assigneeUserId ?? null}- onResumeFromBacklog={canResumeFromBacklog ? handleResumeFromBacklog : undefined}- resumeFromBacklogPending={- updateIssue.isPending && updateIssue.variables?.status === "todo"+ onRetryExternalObjects={+ externalObjectsState.isEnabled+ ? externalObjectsState.refetch+ : undefined}- onResumeAssignee={issue.assigneeAgentId ? handleResumeAssignee : undefined}- resumeAssigneePending={resumeAssigneeAgent.isPending}- externalReferences={externalObjectsState.isEnabled ? externalObjectsState.markdownReferences : undefined}- linkCaseReferences={casesChipsEnabled}- />- ) : null}- </TabsContent>-- <TabsContent value="activity" className={shellSectionClass}>- {detailTab === "activity" ? (- <IssueDetailActivityTab- issue={issue}- issueId={issue.id}- companyId={issue.companyId}- issueStatus={issue.status}- childIssues={childIssues}- agentMap={agentMap}- hasLiveRuns={hasLiveRuns}- currentUserId={currentUserId}- userProfileMap={userProfileMap}- pendingApprovalAction={pendingApprovalAction}- handoffFocusSignal={handoffFocusSignal}- onApprovalAction={(approvalId, action) => {- approvalDecision.mutate({ approvalId, action });- }}- externalReferences={externalObjectsState.isEnabled ? externalObjectsState.markdownReferences : undefined}- />- ) : null}- </TabsContent>-- <TabsContent value="related-work" className={shellSectionClass}>- <IssueRelatedWorkPanel- relatedWork={issue.relatedWork}- externalObjectsEnabled={externalObjectsState.isEnabled}- externalObjects={externalObjectsState.isEnabled ? externalObjectsState.groups : undefined}- externalObjectsLoading={externalObjectsState.isEnabled ? externalObjectsState.isLoading : undefined}- externalObjectsError={externalObjectsState.isEnabled ? externalObjectsState.isError : undefined}- onRetryExternalObjects={externalObjectsState.isEnabled ? externalObjectsState.refetch : undefined}- />- </TabsContent>-- {activePluginTab && (- <TabsContent value={activePluginTab.value} className={shellSectionClass}>- <PluginSlotMount- slot={activePluginTab.slot}- context={{- companyId: issue.companyId,- projectId: issue.projectId ?? null,- entityId: issue.id,- entityType: "issue",- }}- missingBehavior="placeholder"/></TabsContent>- )}- </Tabs>-- <Dialog open={treeControlOpen} onOpenChange={setTreeControlOpen}>- <DialogContent className="flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 sm:max-w-(--sz-560px)">- <DialogHeader className="border-b border-border/60 px-6 pb-4 pr-12 pt-6">- <DialogTitle>{issueTreeControlLabel(treeControlMode, treeControlScope)}</DialogTitle>- <DialogDescription>- {issueTreeControlHelpText(treeControlMode, treeControlScope)}- </DialogDescription>- </DialogHeader>- <div className="min-h-0 flex-1 space-y-4 overflow-y-auto overscroll-contain px-6 py-4">- {treeControlMode === "cancel" ? (- <div className="rounded-md border border-destructive/30 bg-destructive/10 p-3 text-xs text-destructive">- Cancelling a subtree is destructive. Non-terminal tasks will be marked cancelled, and running or queued work will be interrupted where possible.- </div>- ) : null}- <div className="space-y-1.5">- <label className="text-xs text-muted-foreground">- Reason (optional)- </label>- <Textarea- value={treeControlReason}- onChange={(event) => setTreeControlReason(event.target.value)}- placeholder="Explain why this subtree control is being applied..."- className="min-h-(--sz-88px)"+ {activePluginTab && (+ <TabsContent+ value={activePluginTab.value}+ className={shellSectionClass}+ >+ <PluginSlotMount+ slot={activePluginTab.slot}+ context={{+ companyId: issue.companyId,+ projectId: issue.projectId ?? null,+ entityId: issue.id,+ entityType: "issue",+ }}+ missingBehavior="placeholder"/>- </div>+ </TabsContent>+ )}+ </Tabs>++ <Dialog open={treeControlOpen} onOpenChange={setTreeControlOpen}>+ <DialogContent className="flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 sm:max-w-(--sz-560px)">+ <DialogHeader className="border-b border-border/60 px-6 pb-4 pr-12 pt-6">+ <DialogTitle>+ {issueTreeControlLabel(treeControlMode, treeControlScope)}+ </DialogTitle>+ <DialogDescription>+ {issueTreeControlHelpText(treeControlMode, treeControlScope)}+ </DialogDescription>+ </DialogHeader>+ <div className="min-h-0 flex-1 space-y-4 overflow-y-auto overscroll-contain px-6 py-4">+ {treeControlMode === "cancel" ? (+ <div className="rounded-md border border-destructive/30 bg-destructive/10 p-3 text-xs text-destructive">+ Cancelling a subtree is destructive. Non-terminal tasks will+ be marked cancelled, and running or queued work will be+ interrupted where possible.+ </div>+ ) : null}- {(treeControlMode === "resume" || treeControlMode === "restore") ? (- <div className="space-y-2">- <label className="flex items-start gap-2 text-sm">+ <div className="space-y-1.5">+ <label className="text-xs text-muted-foreground">+ Reason (optional)+ </label>+ <Textarea+ value={treeControlReason}+ onChange={(event) => setTreeControlReason(event.target.value)}+ placeholder="Explain why this subtree control is being applied..."+ className="min-h-(--sz-88px)"+ />+ </div>++ {treeControlMode === "resume" || treeControlMode === "restore" ? (+ <div className="space-y-2">+ <label className="flex items-start gap-2 text-sm">+ <input+ type="checkbox"+ className="mt-0.5"+ disabled={previewAffectedAgentCount === 0}+ checked={treeControlWakeAgentsOnResume}+ onChange={(event) =>+ setTreeControlWakeAgentsOnResume(event.target.checked)+ }+ />+ <span>+ <span className="block font-medium">+ Wake affected agents ({previewAffectedAgentCount})+ </span>+ <span className="text-xs text-muted-foreground">+ {previewAffectedAgentCount === 0+ ? "No assignee agents are eligible to wake from this preview."+ : "Wake assignee agents after this operation completes."}+ </span>+ </span>+ </label>+ {treeControlWakeAgentsOnResume &&+ treePreviewAffectedAgentRows.length > 0 ? (+ <div className="max-h-32 space-y-1 overflow-y-auto overscroll-contain">+ {treePreviewAffectedAgentRows.map(+ ({ agentId, agent }) => (+ <div+ key={agentId}+ className="flex items-center gap-2 rounded-sm px-1 py-1 text-sm hover:bg-accent/50"+ >+ <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border bg-background">+ <AgentIcon+ icon={agent?.icon}+ className="h-3.5 w-3.5 text-muted-foreground"+ />+ </span>+ <span className="min-w-0 flex-1 truncate">+ {agent?.name ?? agentId.slice(0, 8)}+ </span>+ </div>+ ),+ )}+ </div>+ ) : null}+ </div>+ ) : null}++ {treeControlMode === "cancel" ? (+ <label className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 p-2 text-sm"><inputtype="checkbox"className="mt-0.5"- disabled={previewAffectedAgentCount === 0}- checked={treeControlWakeAgentsOnResume}- onChange={(event) => setTreeControlWakeAgentsOnResume(event.target.checked)}+ checked={treeControlCancelConfirmed}+ onChange={(event) =>+ setTreeControlCancelConfirmed(event.target.checked)+ }/><span>- <span className="block font-medium">Wake affected agents ({previewAffectedAgentCount})</span>- <span className="text-xs text-muted-foreground">- {previewAffectedAgentCount === 0- ? "No assignee agents are eligible to wake from this preview."- : "Wake assignee agents after this operation completes."}- </span>+ I understand this will cancel {previewAffectedIssueCount}{" "}+ tasks.</span></label>- {treeControlWakeAgentsOnResume && treePreviewAffectedAgentRows.length > 0 ? (- <div className="max-h-32 space-y-1 overflow-y-auto overscroll-contain">- {treePreviewAffectedAgentRows.map(({ agentId, agent }) => (- <div key={agentId} className="flex items-center gap-2 rounded-sm px-1 py-1 text-sm hover:bg-accent/50">- <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border bg-background">- <AgentIcon icon={agent?.icon} className="h-3.5 w-3.5 text-muted-foreground" />- </span>- <span className="min-w-0 flex-1 truncate">{agent?.name ?? agentId.slice(0, 8)}</span>+ ) : null}++ <div className="space-y-2">+ {treeControlPreviewLoading ? (+ <div className="space-y-2">+ <Skeleton className="h-4 w-40" />+ <Skeleton className="h-3 w-full" />+ <Skeleton className="h-3 w-4/5" />+ <Skeleton className="h-3 w-2/3" />+ </div>+ ) : treeControlPreviewError ? (+ <div className="space-y-2">+ <p className="text-xs text-destructive">+ {treeControlPreviewErrorCopy(treeControlPreviewError)}+ </p>+ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ void refetchTreeControlPreview();+ }}+ >+ Retry preview+ </Button>+ </div>+ ) : treeControlPreview ? (+ <div className="space-y-2">+ {treeControlMode === "pause" ? (+ <PauseAffectsSummaryView summary={pauseAffectsSummary} />+ ) : null}+ {treePreviewWarnings.length > 0 ? (+ <div className="space-y-1">+ {treePreviewWarnings.map((warning) => (+ <p+ key={warning.code}+ className="text-xs text-amber-700 dark:text-amber-300"+ >+ {warning.message}+ </p>+ ))}</div>- ))}+ ) : null}+ {treePreviewAffectedIssueRows.length > 0 ? (+ <div className="max-h-56 overflow-y-auto overscroll-contain">+ {treePreviewAffectedIssueRows.map(+ ({ candidate, issue: previewIssue }) => (+ <div+ key={candidate.id}+ style={+ candidate.depth > 0+ ? {+ paddingLeft: `${Math.min(candidate.depth, 6) * 14}px`,+ }+ : undefined+ }+ >+ <Link+ to={createIssueDetailPath(+ candidate.identifier ?? candidate.id,+ )}+ issuePrefetch={previewIssue}+ className={cn(+ "group flex items-start gap-2 border-b border-border py-2 pl-1 pr-2 text-sm no-underline text-inherit transition-colors last:border-b-0 hover:bg-accent/50 sm:items-center",+ candidate.skipped && "opacity-60",+ )}+ >+ <StatusIcon status={candidate.status} />+ <span className="shrink-0 font-mono text-xs text-muted-foreground">+ {candidate.identifier ??+ candidate.id.slice(0, 8)}+ </span>+ <span className="min-w-0 flex-1 truncate">+ {candidate.title}+ </span>+ {candidate.skipped &&+ candidate.skipReason === "terminal_status" ? (+ <span className="shrink-0 text-xs text-muted-foreground">+ Complete+ </span>+ ) : null}+ </Link>+ </div>+ ),+ )}+ </div>+ ) : null}</div>- ) : null}+ ) : (+ <p className="text-xs text-muted-foreground">+ Preview unavailable.+ </p>+ )}</div>- ) : null}-- {treeControlMode === "cancel" ? (- <label className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 p-2 text-sm">- <input- type="checkbox"- className="mt-0.5"- checked={treeControlCancelConfirmed}- onChange={(event) => setTreeControlCancelConfirmed(event.target.checked)}- />- <span>I understand this will cancel {previewAffectedIssueCount} tasks.</span>- </label>- ) : null}-- <div className="space-y-2">- {treeControlPreviewLoading ? (- <div className="space-y-2">- <Skeleton className="h-4 w-40" />- <Skeleton className="h-3 w-full" />- <Skeleton className="h-3 w-4/5" />- <Skeleton className="h-3 w-2/3" />- </div>- ) : treeControlPreviewError ? (- <div className="space-y-2">- <p className="text-xs text-destructive">{treeControlPreviewErrorCopy(treeControlPreviewError)}</p>- <Button- variant="outline"- size="sm"- onClick={() => {- void refetchTreeControlPreview();- }}- >- Retry preview- </Button>- </div>- ) : treeControlPreview ? (- <div className="space-y-2">- {treeControlMode === "pause" ? (- <PauseAffectsSummaryView summary={pauseAffectsSummary} />- ) : null}- {treePreviewWarnings.length > 0 ? (- <div className="space-y-1">- {treePreviewWarnings.map((warning) => (- <p key={warning.code} className="text-xs text-amber-700 dark:text-amber-300">- {warning.message}- </p>- ))}- </div>- ) : null}- {treePreviewAffectedIssueRows.length > 0 ? (- <div className="max-h-56 overflow-y-auto overscroll-contain">- {treePreviewAffectedIssueRows.map(({ candidate, issue: previewIssue }) => (- <div key={candidate.id} style={candidate.depth > 0 ? { paddingLeft: `${Math.min(candidate.depth, 6) * 14}px` } : undefined}>- <Link- to={createIssueDetailPath(candidate.identifier ?? candidate.id)}- issuePrefetch={previewIssue}- className={cn(- "group flex items-start gap-2 border-b border-border py-2 pl-1 pr-2 text-sm no-underline text-inherit transition-colors last:border-b-0 hover:bg-accent/50 sm:items-center",- candidate.skipped && "opacity-60",- )}- >- <StatusIcon status={candidate.status} />- <span className="shrink-0 font-mono text-xs text-muted-foreground">- {candidate.identifier ?? candidate.id.slice(0, 8)}- </span>- <span className="min-w-0 flex-1 truncate">{candidate.title}</span>- {candidate.skipped && candidate.skipReason === "terminal_status" ? (- <span className="shrink-0 text-xs text-muted-foreground">Complete</span>- ) : null}- </Link>- </div>- ))}- </div>- ) : null}- </div>- ) : (- <p className="text-xs text-muted-foreground">Preview unavailable.</p>- )}- </div>- </div>- <DialogFooter className="border-t border-border/60 bg-background px-6 py-4">- <Button variant="outline" onClick={() => setTreeControlOpen(false)} disabled={executeTreeControl.isPending}>- Close- </Button>- <Button- onClick={() => executeTreeControl.mutate()}- disabled={executeTreeControl.isPending || !canApplyTreeControl}- variant={treeControlMode === "cancel" ? "destructive" : "default"}- >- {executeTreeControl.isPending ? "Applying..." : treeControlPrimaryButtonLabel}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>-- {/* Mobile properties drawer */}- <Sheet open={mobilePropsOpen} onOpenChange={setMobilePropsOpen}>- <SheetContent side="bottom" className="max-h-(--sz-85dvh) pb-(--sz-safe-bottom)">- <SheetHeader>- <SheetTitle className="text-sm">Properties</SheetTitle>- </SheetHeader>- <ScrollArea className="flex-1 overflow-y-auto">- <div className="px-4 pb-4">- <IssueProperties- issue={issue}- childIssues={childIssues}- onAddSubIssue={openNewSubIssue}- onUpdate={(data) => updateIssue.mutate(data)}- inline- hasActiveRun={resolvedHasActiveRun}- externalObjects={externalObjectsState.isEnabled ? externalObjectsState.groups : undefined}- externalObjectsLoading={externalObjectsState.isEnabled ? externalObjectsState.isLoading : undefined}- externalObjectsError={externalObjectsState.isEnabled ? externalObjectsState.isError : undefined}- onRetryExternalObjects={externalObjectsState.isEnabled ? externalObjectsState.refetch : undefined}- onCheckMonitorNow={() => checkIssueMonitorNow.mutate()}- checkingMonitorNow={checkIssueMonitorNow.isPending}- documentDeepLink={documentDeepLink?.issueId === issue.id ? documentDeepLink : null}- /></div>- </ScrollArea>- </SheetContent>- </Sheet>- {fileViewerEnabled ? (- <IssueFileViewer- issueId={issue.id}- companyId={issue.companyId}- promptOpen={fileViewerPromptOpen}- onPromptOpenChange={setFileViewerPromptOpen}- />- ) : null}- <ScrollToBottom />- </div>+ <DialogFooter className="border-t border-border/60 bg-background px-6 py-4">+ <Button+ variant="outline"+ onClick={() => setTreeControlOpen(false)}+ disabled={executeTreeControl.isPending}+ >+ Close+ </Button>+ <Button+ onClick={() => executeTreeControl.mutate()}+ disabled={executeTreeControl.isPending || !canApplyTreeControl}+ variant={+ treeControlMode === "cancel" ? "destructive" : "default"+ }+ >+ {executeTreeControl.isPending+ ? "Applying..."+ : treeControlPrimaryButtonLabel}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {/* Mobile properties drawer */}+ <Sheet open={mobilePropsOpen} onOpenChange={setMobilePropsOpen}>+ <SheetContent+ side={+ taskChatShellEnabled+ ? "bottom"+ : documentDeepLink?.documentKey === "plan"+ ? "right"+ : "bottom"+ }+ showCloseButton={!taskChatShellEnabled}+ className={cn(+ taskChatShellEnabled+ ? "h-(--sz-85dvh) max-h-(--sz-85dvh) gap-0 p-0 pb-(--sz-safe-bottom)"+ : documentDeepLink?.documentKey === "plan"+ ? "inset-0 h-dvh w-screen max-w-none gap-0 border-0 p-0 sm:max-w-none"+ : "max-h-(--sz-85dvh) pb-(--sz-safe-bottom)",+ )}+ data-testid={+ taskChatShellEnabled+ ? "mobile-task-side-panel"+ : documentDeepLink?.documentKey === "plan"+ ? "mobile-plan-panel"+ : undefined+ }+ >+ {taskChatShellEnabled ? (+ <>+ <SheetHeader className="sr-only">+ <SheetTitle>Task side panel</SheetTitle>+ </SheetHeader>+ <TaskSidePanel+ key={`${issue.id}:mobile`}+ issue={issue}+ accountScope={currentUserId ?? "anonymous"}+ childIssues={childIssues}+ onAddSubIssue={openNewSubIssue}+ onUpdate={(data) => updateIssue.mutate(data)}+ inline+ hasActiveRun={resolvedHasActiveRun}+ externalObjects={+ externalObjectsState.isEnabled+ ? externalObjectsState.groups+ : undefined+ }+ externalObjectsLoading={+ externalObjectsState.isEnabled+ ? externalObjectsState.isLoading+ : undefined+ }+ externalObjectsError={+ externalObjectsState.isEnabled+ ? externalObjectsState.isError+ : undefined+ }+ onRetryExternalObjects={+ externalObjectsState.isEnabled+ ? externalObjectsState.refetch+ : undefined+ }+ onCheckMonitorNow={() => checkIssueMonitorNow.mutate()}+ checkingMonitorNow={checkIssueMonitorNow.isPending}+ fileTabsEnabled={fileViewerEnabled}+ documentDeepLink={+ documentDeepLink?.issueId === issue.id+ ? documentDeepLink+ : null+ }+ onRequestClose={() => setMobilePropsOpen(false)}+ />+ </>+ ) : (+ <>+ <SheetHeader>+ <SheetTitle className="text-sm">+ {documentDeepLink?.documentKey === "plan"+ ? "Plan"+ : "Properties"}+ </SheetTitle>+ </SheetHeader>+ <ScrollArea className="flex-1 overflow-y-auto">+ <div className="px-4 pb-4">+ <IssueProperties+ issue={issue}+ childIssues={childIssues}+ onAddSubIssue={openNewSubIssue}+ onUpdate={(data) => updateIssue.mutate(data)}+ inline+ hasActiveRun={resolvedHasActiveRun}+ externalObjects={+ externalObjectsState.isEnabled+ ? externalObjectsState.groups+ : undefined+ }+ externalObjectsLoading={+ externalObjectsState.isEnabled+ ? externalObjectsState.isLoading+ : undefined+ }+ externalObjectsError={+ externalObjectsState.isEnabled+ ? externalObjectsState.isError+ : undefined+ }+ onRetryExternalObjects={+ externalObjectsState.isEnabled+ ? externalObjectsState.refetch+ : undefined+ }+ onCheckMonitorNow={() => checkIssueMonitorNow.mutate()}+ checkingMonitorNow={checkIssueMonitorNow.isPending}+ documentDeepLink={+ documentDeepLink?.issueId === issue.id+ ? documentDeepLink+ : null+ }+ />+ </div>+ </ScrollArea>+ </>+ )}+ </SheetContent>+ </Sheet>+ {fileViewerEnabled ? (+ <IssueFileViewer+ issueId={issue.id}+ companyId={issue.companyId}+ promptOpen={fileViewerPromptOpen}+ onPromptOpenChange={setFileViewerPromptOpen}+ useSidePanel={taskChatShellEnabled}+ />+ ) : null}+ <ScrollToBottom />+ </div></FileViewerProvider>);}@@ -5668,21 +7828,40 @@ function IssueFileViewer({companyId,promptOpen,onPromptOpenChange,+ useSidePanel = false,}: {issueId: string;companyId: string;promptOpen: boolean;onPromptOpenChange: (next: boolean) => void;+ useSidePanel?: boolean;}) {const viewer = useRequiredFileViewer();++ useEffect(() => {+ if (!useSidePanel || !promptOpen) return;+ viewer.openBrowse();+ onPromptOpenChange(false);+ }, [onPromptOpenChange, promptOpen, useSidePanel, viewer]);+const open = viewer.state !== null || viewer.browse || promptOpen;- const showPromptWhenEmpty = (promptOpen || viewer.browse) && viewer.state === null;+ const showPromptWhenEmpty =+ (promptOpen || viewer.browse) && viewer.state === null;useEffect(() => {+ if (useSidePanel) return;if (!promptOpen) return;if (viewer.state === null && !viewer.browse) return;onPromptOpenChange(false);- }, [onPromptOpenChange, promptOpen, viewer.browse, viewer.state]);+ }, [+ onPromptOpenChange,+ promptOpen,+ useSidePanel,+ viewer.browse,+ viewer.state,+ ]);++ if (useSidePanel) return null;return (<FileViewerSheet