Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(chat): align subagent tabs with the conversation display
v_wyxgwang9d25b7a991d7
diff --git a/apps/desktop/src/components/workpanel/SubagentTranscriptTab.tsx b/apps/desktop/src/components/workpanel/SubagentTranscriptTab.tsxindex 1ae8d06e9..6685b22b0 100644--- a/apps/desktop/src/components/workpanel/SubagentTranscriptTab.tsx+++ b/apps/desktop/src/components/workpanel/SubagentTranscriptTab.tsx@@ -1,89 +1,55 @@-import { toolResultPayload } from "../../lib/tool-presentation";-import { SubagentStopButton } from "../../features/chat/transcript/SubagentStopButton";-import { collectDelegationStatuses, subagentOutcome } from "../../lib/subagent-topology";import { Fragment, useLayoutEffect, useMemo } from "react";import { useTranslation } from "react-i18next";-import { useAppStore } from "../../stores/app-store";+import { AssistantTurnBody } from "../../features/chat/transcript/AssistantTurnBody";+import { SubagentStopButton } from "../../features/chat/transcript/SubagentStopButton";+import { TranscriptDisclosureProvider } from "../../features/chat/transcript/disclosure";+import { delegateModelId, delegateThinkingLevel } from "../../features/chat/transcript/model";import { useFollowScroll } from "../../hooks/use-follow-scroll";-import { useTranscriptView } from "../../hooks/use-transcript-view";import { useTranscriptSearchFocus } from "../../hooks/use-transcript-search-focus";-import { IconArrowDown, IconBot, IconChevronDown } from "../icons";-import { Textarea, TooltipButton } from "../ui";+import { useTranscriptView } from "../../hooks/use-transcript-view";import { DisclosureAnchorContext } from "../../lib/disclosure-anchor-context";-import { TranscriptDisclosureProvider } from "../../features/chat/transcript/disclosure";+import { delegationIdForMessage } from "../../lib/subagent-panel";+import { collectDelegationStatuses, delegationIsCreating, subagentOutcome } from "../../lib/subagent-topology";import { buildSubagentTranscript } from "../../lib/subagent-transcript";-import { reviewChangeFromMessage } from "../../lib/workspace-review";-import {- AssistantErrorMessage,- ThinkingRow,-} from "../../features/chat/transcript/shared";-import {- ReviewChangeCard,-} from "../ReviewChangeCard";-import { ToolRow } from "../../features/chat/transcript/ToolRow";-import { Markdown } from "../Markdown";-import { delegateModelId, delegateThinkingLevel } from "../../features/chat/transcript/model";+import { TranscriptSearchContext } from "../../lib/transcript-search-context";+import { SlotSessionProvider } from "../../plugins/renderer-slots/use-slots";+import { useAppStore } from "../../stores/app-store";+import { IconArrowDown } from "../icons";+import { TooltipButton } from "../ui";-/**- * The work-panel tab showing one delegation as a conversation (issue #917).- *- * Every `Task` call of the delegation chain opens a turn: the prompt the- * parent sent renders as a user row, and the rows the delegate produced under- * that call render with the main transcript's own message-list language —- * tool rows, thinking rows, and answer bubbles alike. Follow-up `Task` calls- * on the same delegation append further turns, so a resumed delegate reads as- * one continuing user/assistant exchange.- *- * The tab allows explicit cancellation; the composer at the foot is a disabled textarea- * whose placeholder says the delegate is driven by the main agent. There is- * deliberately no send path.- */export function SubagentTranscriptTab({ delegationId }: { delegationId: string }) {+ const sessionId = useAppStore((state) => state.activeSessionId);+ if (!sessionId) return null;return (- <TranscriptDisclosureProvider key={delegationId}>- <SubagentTranscriptSurface delegationId={delegationId} />- </TranscriptDisclosureProvider>+ <SlotSessionProvider sessionId={sessionId}>+ <TranscriptDisclosureProvider key={JSON.stringify([sessionId, delegationId])} sessionId={sessionId} delegationId={delegationId}>+ <SubagentTranscriptSurface sessionId={sessionId} delegationId={delegationId} />+ </TranscriptDisclosureProvider>+ </SlotSessionProvider>);}-function SubagentTranscriptSurface({ delegationId }: { delegationId: string }) {+function SubagentTranscriptSurface({ sessionId, delegationId }: { sessionId: string; delegationId: string }) {const { t } = useTranslation();- const activeSessionId = useAppStore((state) => state.activeSessionId);- // A tab only renders inside a presented panel, which always has a session;- // the empty key keeps the hook's contract while nothing is active.- const transcript = useTranscriptView(activeSessionId ?? "");- const { messages } = transcript;- const delegateRunning = useMemo(() => {- const items = messages- .filter(message => message.role === "tool")- .map(message => ({ kind: "tool" as const, message }));- const statuses = collectDelegationStatuses(items);- return items.some(({ message }) => {- const payload = toolResultPayload(message);- return payload && typeof payload === "object" &&- "delegationId" in payload && payload.delegationId === delegationId &&- subagentOutcome(message, statuses) === "running";- });- }, [messages, delegationId]);- const delegateSettings = useMemo(() => {- const result = messages.find((message) => {- if (message.role !== "tool") return false;- const payload = toolResultPayload(message);- return payload && typeof payload === "object" && !Array.isArray(payload) &&- "delegationId" in payload && payload.delegationId === delegationId;- });- return {- modelId: result ? delegateModelId(result) : "",- thinkingLevel: result ? delegateThinkingLevel(result) : undefined,- };- }, [messages, delegationId]);- const isRunning = useAppStore(- (state) => (activeSessionId ? state.runningSessions[activeSessionId] ?? false : false),- );+ const { messages, focus } = useTranscriptView(sessionId);+ const parentRunning = useAppStore((state) => state.runningSessions[sessionId] ?? false);const transcriptResult = useMemo(() => buildSubagentTranscript(messages, delegationId),[messages, delegationId],);+ const statuses = useMemo(() => collectDelegationStatuses(+ messages.filter((message) => message.role === "tool").map((message) => ({ kind: "tool", message })),+ { turnLive: parentRunning },+ ), [messages, parentRunning]);+ const latest = transcriptResult?.turns.at(-1)?.call;+ const running = Boolean(latest && parentRunning && subagentOutcome(latest, statuses) === "running");+ const stopId = latest && running && !delegationIsCreating(latest) ? delegationIdForMessage(latest) : undefined;+ const modelId = latest ? delegateModelId(latest) : "";+ const thinkingLevel = latest ? delegateThinkingLevel(latest) : undefined;+ const modelDetails = [+ modelId && `${t("chat.model")}: ${modelId}`,+ thinkingLevel && `${t("chat.reasoningLevel")}: ${thinkingLevel}`,+ ].filter(Boolean).join(" · ");const {scrollRef,contentRef,@@ -95,25 +61,17 @@ function SubagentTranscriptSurface({ delegationId }: { delegationId: string }) {disclosureAnchorNotifier,} = useFollowScroll();- // Several delegation tabs can be open at once, so an explicit search hit- // is claimed only by the tab whose own conversation contains the message;- // the other tabs stay where the reader left them.- const searchTarget = useMemo(() => {- const focus = transcript.focus;- if (!focus) return null;- const claimed = transcriptResult?.turns.some((turn) =>- turn.rows.some((row) => row.message.id === focus.messageId),- );- return claimed ? focus : null;- }, [transcript.focus, transcriptResult]);-+ // A search request is claimed only by the delegation that owns the hit.+ const searchMessage = useMemo(() => focus && transcriptResult?.turns+ .flatMap((turn) => turn.messages)+ .find((message) => message.id === focus.messageId), [focus, transcriptResult]);+ const searchTarget = searchMessage ? focus : null;useTranscriptSearchFocus({target: searchTarget,- source:- messages.find((message) => message.id === searchTarget?.messageId)?.content ?? "",+ source: searchMessage?.content ?? "",scrollRef,contentRef,- contentVersion: messages,+ contentVersion: transcriptResult,onNavigate: releaseFollow,});@@ -123,118 +81,82 @@ function SubagentTranscriptSurface({ delegationId }: { delegationId: string }) {useLayoutEffect(() => {scheduleFollowScroll();- }, [messages, scheduleFollowScroll]);+ }, [transcriptResult, scheduleFollowScroll]);return (- <DisclosureAnchorContext.Provider value={disclosureAnchorNotifier}>- <div className="subagent-transcript-tab" data-testid="subagent-transcript-tab">- <div- ref={scrollRef}- data-scroll-owner="follow"- className="subagent-transcript-scroll"- onScroll={handleScroll}- role="log"- aria-live="polite"- aria-label={t("panel.subagent")}- tabIndex={0}- >- <div ref={contentRef} className="subagent-transcript-list">- {transcriptResult ? (- transcriptResult.turns.map((turn, turnIndex) => (- <Fragment key={`turn-${turnIndex}`}>+ <TranscriptSearchContext.Provider value={searchTarget}>+ <DisclosureAnchorContext.Provider value={disclosureAnchorNotifier}>+ <div className="subagent-transcript-tab" data-testid="subagent-transcript-tab">+ <div+ ref={scrollRef}+ data-scroll-owner="follow"+ className="subagent-transcript-scroll"+ onScroll={handleScroll}+ role="log"+ aria-live="polite"+ aria-label={t("panel.subagent")}+ tabIndex={0}+ >+ <div ref={contentRef} className="subagent-transcript-list">+ {transcriptResult ? transcriptResult.turns.map(({ call, task, reply }) => (+ <Fragment key={reply.id}><div className="message-row user"><div className="message-col"><div className="message-bubble">- <div className="message-user-text selectable">- {turn.task || t("panel.subagentTaskEmpty")}- </div>+ <div className="message-user-text selectable">{task || t("panel.subagentTaskEmpty")}</div></div></div></div>- {turn.rows.map((row) =>- row.kind === "tool" ? (- reviewChangeFromMessage(row.message) ? (- <ReviewChangeCard- key={row.message.id}- message={row.message}- asToolRow+ {reply.parts.length > 0 ? (+ <div className="message-row assistant assistant-turn" role="article" aria-label={t("chat.assistantMessage")}>+ <div className="message-col">+ <AssistantTurnBody+ entry={reply}+ isActive={call === latest && running}+ outcome={subagentOutcome(call, statuses)}/>- ) : (- <ToolRow key={row.message.id} message={row.message} />- )- ) : row.kind === "thinking" ? (- <ThinkingRow- key={`thinking-${row.message.id}`}- message={row.message}- streaming={isRunning && row.message.status === "streaming"}- />- ) : (- <div- className="message-row assistant"- data-message-id={row.message.id}- key={`answer-${row.message.id}`}- >- <div className="message-col">- <div className="message-bubble">- {row.message.content ? (- <div className="prose-chat selectable">- <Markdown source={row.message.content} />- </div>- ) : null}- {row.message.error ? (- <AssistantErrorMessage message={row.message} />- ) : null}- </div>- </div></div>- ),- )}+ </div>+ ) : null}</Fragment>- ))- ) : (- <div className="subagent-transcript-empty" role="status">- {t("panel.subagentEmpty")}- </div>- )}+ )) : (+ <div className="subagent-transcript-empty" role="status">{t("panel.subagentEmpty")}</div>+ )}+ </div></div>- </div>- {showJump ? (- <TooltipButton- type="button"- className="jump-latest-btn subagent-transcript-jump"- tooltip={t("chat.scrollToBottom")}- ariaLabel={t("chat.scrollToBottom")}- onClick={jumpToLatest}- >- <IconArrowDown size={14} />- </TooltipButton>- ) : null}- <footer className="subagent-transcript-composer">- <Textarea- disabled- rows={2}- aria-label={t("panel.subagentReadOnly")}- placeholder={t("panel.subagentReadOnly")}- />- <div className="subagent-transcript-composer-controls">- <button+ {showJump ? (+ <TooltipButtontype="button"- className="icon-btn composer-model-thinking-chip subagent-transcript-model-picker"- disabled- aria-haspopup="listbox"- aria-label={`${t("chat.model")}: ${delegateSettings.modelId || "—"}. ${t("chat.reasoningLevel")}: ${delegateSettings.thinkingLevel || "—"}`}+ className="jump-latest-btn subagent-transcript-jump"+ tooltip={t("chat.scrollToBottom")}+ ariaLabel={t("chat.scrollToBottom")}+ onClick={jumpToLatest}>- <span className="composer-model-thinking-icon" aria-hidden="true"><IconBot size={14} /></span>- <span className="composer-model-thinking-model">{delegateSettings.modelId || "—"}</span>- <span className="composer-model-thinking-level">{delegateSettings.thinkingLevel || "—"}</span>- <IconChevronDown size={12} aria-hidden="true" className="composer-model-thinking-chevron" />- </button>- {delegateRunning ? (- <SubagentStopButton delegationId={delegationId} running compact />- ) : null}- </div>- </footer>- </div>- </DisclosureAnchorContext.Provider>+ <IconArrowDown size={14} />+ </TooltipButton>+ ) : null}+ <footer className="subagent-transcript-composer">+ <div className="composer-shell">+ <div className="composer-input-wrap">+ <div className="composer-input subagent-composer-notice">{t("panel.subagentReadOnly")}</div>+ </div>+ {modelDetails || stopId ? (+ <div className="composer-toolbar subagent-composer-toolbar">+ {modelDetails ? (+ <span className="subagent-composer-model" title={modelDetails}>+ {modelId ? <span className="composer-model-thinking-model">{modelId}</span> : null}+ {thinkingLevel ? <span className="composer-model-thinking-level">{thinkingLevel}</span> : null}+ </span>+ ) : null}+ {stopId ? (+ <SubagentStopButton delegationId={stopId} name={transcriptResult?.agentName} running compact />+ ) : null}+ </div>+ ) : null}+ </div>+ </footer>+ </div>+ </DisclosureAnchorContext.Provider>+ </TranscriptSearchContext.Provider>);}diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsxindex 8854ce2a4..77f69e7d0 100644--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx@@ -11,23 +11,10 @@ import type {} from "@pi-desktop/shared";import { formatCompactTokenCount } from "@pi-desktop/shared";import {- reuseReadonlyMap,type AssistantTurnEntry,type TranscriptEntry,} from "../../../lib/assistant-turns";-import {- collectDelegationStatuses,- collectDelegationTimings,-} from "../../../lib/subagent-topology";-import {- segmentTurnProcess,- type TurnProcessRunSegment,-} from "../../../lib/turn-process";import { sessionAllows } from "../../../lib/remote-session-safety";-import { resolveShowThinking } from "../../../lib/thinking-visibility";-import { resolveTranscriptDisplayMode } from "../../../lib/transcript-display-mode";-import { reviewChangeFromMessage } from "../../../lib/workspace-review";-import { cachedVisibleProcessSteps } from "../../../lib/transcript-activity-summary";import { useSlotSessionId } from "../../../plugins/renderer-slots/use-slots";import { useAppStore } from "../../../stores/app-store";import { IconBranch, IconReview } from "../../../components/icons";@@ -38,10 +25,7 @@ import {MessageTimestamp,} from "./shared";import { activityItemsEqual } from "./ActivityGroup";-import { GeneratedImages } from "./GeneratedImages";import { MessageRow } from "./MessageRow";-import { ReviewChangeCard } from "../../../components/ReviewChangeCard";-import { ToolRow } from "./ToolRow";import { assistantTurnMenuItems } from "./menu-items";import {useChatTextActions,@@ -52,8 +36,7 @@ import {getAssistantTurnContent,reuseReferences,} from "../../../lib/transcript-summary";-import { AssistantTurnParts } from "./AssistantTurnParts";-import { TurnProcess } from "./TurnProcess";+import { AssistantTurnBody } from "./AssistantTurnBody";import { ActionSlotSide } from "./ActionBarSlots";import { EntryExtraStack } from "./EntryExtraStack";import { TurnChangesCard } from "./TurnChangesCard";@@ -247,31 +230,6 @@ export const TranscriptTail = memo(function TranscriptTail({transcriptEntryEqual(previous.entry, next.entry));-/**- * A `Bash`/run call rendered on its own, outside every process and activity- * disclosure. It stays visible with all disclosures collapsed, and its own- * detail stays closed until the user opens it.- */-const StandaloneRunRow = memo(function StandaloneRunRow({- segment,-}: {- segment: TurnProcessRunSegment;-}) {- // A review-backed edit is one tool-level row. It cannot become a run row- // today, but keeping the branch here prevents a future alias from rendering- // both the file header and the generic tool header.- const reviewed = reviewChangeFromMessage(segment.item.message) !== null;- return (- <div className="turn-run-row" data-run-row="true">- {reviewed ? (- <ReviewChangeCard message={segment.item.message} asToolRow />- ) : (- <ToolRow imagesInTurn message={segment.item.message} />- )}- </div>- );-});-export const AssistantTurn = memo(function AssistantTurn({entry,isActive,@@ -302,10 +260,6 @@ export const AssistantTurn = memo(function AssistantTurn({? slotMessage("assistant", { ...actionMessage, content }) : undefined,[complete, actionMessage, content]);const streaming = isActive && summary.streaming;- // The same preference the nested levels read: hidden reasoning is not a- // visible step of the turn's process.- const showThinking = useAppStore((state) => resolveShowThinking(state.settings));- const hideThinking = !showThinking;/*The turn owns the menu for its whole subtree, the answer rows it rendersincluded: Regenerate and Branch act on the turn's answer message, so a menu@@ -335,65 +289,9 @@ export const AssistantTurn = memo(function AssistantTurn({});};- // Collect delegation statuses across ALL activity parts of this turn so that- // a TaskWait in one part can inform the Task cards in a different part.const toolsRef = useRef(summary.tools);const tools = reuseReferences(toolsRef.current, summary.tools);toolsRef.current = tools;- const generatedImages = useMemo(() => tools- .filter((message) => message.toolName === "GenerateImages")- .map((message) => <GeneratedImages key={message.id} message={message} />), [tools]);- // Delegation status/timing depends on actual tool messages, never on thinking- // or text and never on a Task's attached child transcript identity.- const delegationItems = useMemo(() => tools.map((message) => ({ kind: "tool" as const, message })), [tools]);- const rawDelegationStatuses = useMemo(- () => collectDelegationStatuses(delegationItems, { turnLive: isActive || delegationsLive === true }),- [delegationItems, isActive, delegationsLive],- );- const rawDelegationTimings = useMemo(- () => collectDelegationTimings(delegationItems),- [delegationItems],- );- const statusesRef = useRef(rawDelegationStatuses);- const timingsRef = useRef(rawDelegationTimings);- const turnDelegationStatuses = reuseReadonlyMap(- statusesRef.current,- rawDelegationStatuses,- );- const turnDelegationTimings = reuseReadonlyMap(- timingsRef.current,- rawDelegationTimings,- (left, right) =>- left.startedAt === right.startedAt && left.completedAt === right.completedAt,- );- statusesRef.current = turnDelegationStatuses;- timingsRef.current = turnDelegationTimings;- const { process, responses } = summary;- // Read at render time, never at entry-build time: the projection cache is keyed- // by messages and compactions only, so a grouping decision made there would- // stay stale until new messages arrived. Segmenting here makes the preference- // apply on the next paint.- const displayMode = useAppStore((state) => resolveTranscriptDisplayMode(state.settings));- const segments = useMemo(- () => segmentTurnProcess(process, displayMode),- [process, displayMode],- );- // The one disclosure exists if it reveals anything at all. This uses the same- // helper the activity rows use: progress text counts, completed thinking is- // hidden under the preference, and a live reasoning indicator still counts.- // Content facts come from the per-message cache, so a streaming delta reads- // only its own message body rather than every earlier one.- const visibleSteps = useMemo(- () => cachedVisibleProcessSteps(process, hideThinking, isActive),- [process, hideThinking, isActive],- );- // The live tail is the turn's actual last part. A process chunk opens and- // reports live state only while it owns that part, so a superseded thinking- // chunk cannot keep a false "Thinking" header once a Bash call or a separate- // streamed answer takes over the turn.- const activePart = isActive ? entry.parts.at(-1) : undefined;- const partContext = { isActive, activePart, runtimeActivity, turnDelegationStatuses, turnDelegationTimings };-return (<divclassName={`message-row assistant assistant-turn${streaming ? " streaming" : ""}`}@@ -404,30 +302,12 @@ export const AssistantTurn = memo(function AssistantTurn({aria-label={t("chat.assistantMessage")}><div className="message-col">- {process.length > 0 ? (- <TurnProcess- turnId={entry.id}- processParts={process}- turnParts={entry.parts}- visibleSteps={visibleSteps}- isActive={isActive}- failed={summary.hasError}- activity={runtimeActivity}- >- {segments.map((segment) => {- if (segment.kind === "run") {- return <StandaloneRunRow key={`run-${segment.key}`} segment={segment} />;- }- return (- <AssistantTurnParts key={`process-${segment.key}`} parts={segment.parts} {...partContext} />- );- })}- </TurnProcess>- ) : null}- {/* The answer stays outside the process disclosure: it is what the turn- produced, not part of what it did. */}- <AssistantTurnParts parts={responses} {...partContext} />- {generatedImages}+ <AssistantTurnBody+ entry={entry}+ isActive={isActive}+ delegationsLive={delegationsLive}+ runtimeActivity={runtimeActivity}+ />{/* Mounted with the reply slots, so a streaming turn never grows it;plugin entry extras stay beneath it. */}{slotReply ? <TurnChangesCard tools={tools} /> : null}diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurnBody.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurnBody.tsxnew file mode 100644index 000000000..2bf38d2f2--- /dev/null+++ b/apps/desktop/src/features/chat/transcript/AssistantTurnBody.tsx@@ -0,0 +1,148 @@+import { memo, useMemo, useRef } from "react";+import type { AgentActivity } from "@pi-desktop/shared";+import { reuseReadonlyMap, type AssistantTurnEntry } from "../../../lib/assistant-turns";+import {+ collectDelegationStatuses,+ collectDelegationTimings,+ type SubagentOutcome,+} from "../../../lib/subagent-topology";+import {+ segmentTurnProcess,+ type TurnProcessRunSegment,+} from "../../../lib/turn-process";+import { resolveShowThinking } from "../../../lib/thinking-visibility";+import { resolveTranscriptDisplayMode } from "../../../lib/transcript-display-mode";+import { cachedVisibleProcessSteps } from "../../../lib/transcript-activity-summary";+import { useAppStore } from "../../../stores/app-store";+import { ReviewChangeCard } from "../../../components/ReviewChangeCard";+import { GeneratedImages } from "./GeneratedImages";+import { ToolRow } from "./ToolRow";+import { AssistantTurnParts } from "./AssistantTurnParts";+import { TurnProcess } from "./TurnProcess";+import { getAssistantTurnSummary, reuseReferences } from "../../../lib/transcript-summary";+import { reviewChangeFromMessage } from "../../../lib/workspace-review";++/** A command beside the activity groups, inside the outer process. */+const StandaloneRunRow = memo(function StandaloneRunRow({+ segment,+}: {+ segment: TurnProcessRunSegment;+}) {+ // A review-backed edit is one tool-level row. It cannot become a run row+ // today, but keeping the branch here prevents a future alias from rendering+ // both the file header and the generic tool header.+ const reviewed = reviewChangeFromMessage(segment.item.message) !== null;+ return (+ <div className="turn-run-row" data-run-row="true">+ {reviewed ? (+ <ReviewChangeCard message={segment.item.message} asToolRow />+ ) : (+ <ToolRow imagesInTurn message={segment.item.message} />+ )}+ </div>+ );+});++/** Shared turn content; session actions and reply slots belong to the caller. */+export const AssistantTurnBody = memo(function AssistantTurnBody({+ entry, isActive, delegationsLive, runtimeActivity, outcome,+}: {+ entry: AssistantTurnEntry;+ isActive: boolean;+ delegationsLive?: boolean;+ runtimeActivity?: AgentActivity;+ outcome?: SubagentOutcome;+}) {+ const summary = getAssistantTurnSummary(entry);+ // The same preference the nested levels read: hidden reasoning is not a+ // visible step of the turn's process.+ const showThinking = useAppStore((state) => resolveShowThinking(state.settings));+ const hideThinking = !showThinking;+ // Collect delegation statuses across ALL activity parts of this turn so that+ // a TaskWait in one part can inform the Task cards in a different part.+ const toolsRef = useRef(summary.tools);+ const tools = reuseReferences(toolsRef.current, summary.tools);+ toolsRef.current = tools;+ // Delegation status/timing depends on actual tool messages, never on thinking+ // or text and never on a Task's attached child transcript identity.+ const delegationItems = useMemo(() => tools.map((message) => ({ kind: "tool" as const, message })), [tools]);+ const rawDelegationStatuses = useMemo(+ () => collectDelegationStatuses(delegationItems, { turnLive: isActive || delegationsLive === true }),+ [delegationItems, isActive, delegationsLive],+ );+ const rawDelegationTimings = useMemo(+ () => collectDelegationTimings(delegationItems),+ [delegationItems],+ );+ const statusesRef = useRef(rawDelegationStatuses);+ const timingsRef = useRef(rawDelegationTimings);+ const turnDelegationStatuses = reuseReadonlyMap(+ statusesRef.current,+ rawDelegationStatuses,+ );+ const turnDelegationTimings = reuseReadonlyMap(+ timingsRef.current,+ rawDelegationTimings,+ (left, right) =>+ left.startedAt === right.startedAt && left.completedAt === right.completedAt,+ );+ statusesRef.current = turnDelegationStatuses;+ timingsRef.current = turnDelegationTimings;+ const { process, responses } = summary;+ // Read at render time, never at entry-build time: the projection cache is keyed+ // by messages and compactions only, so a grouping decision made there would+ // stay stale until new messages arrived. Segmenting here makes the preference+ // apply on the next paint.+ const displayMode = useAppStore((state) => resolveTranscriptDisplayMode(state.settings));+ const segments = useMemo(+ () => segmentTurnProcess(process, displayMode),+ [process, displayMode],+ );+ // The one disclosure exists if it reveals anything at all. This uses the same+ // helper the activity rows use: progress text counts, completed thinking is+ // hidden under the preference, and a live reasoning indicator still counts.+ // Content facts come from the per-message cache, so a streaming delta reads+ // only its own message body rather than every earlier one.+ const visibleSteps = useMemo(+ () => cachedVisibleProcessSteps(process, hideThinking, isActive),+ [process, hideThinking, isActive],+ );+ // The live tail is the turn's actual last part. A process chunk opens and+ // reports live state only while it owns that part, so a superseded thinking+ // chunk cannot keep a false "Thinking" header once a Bash call or a separate+ // streamed answer takes over the turn.+ const activePart = isActive ? entry.parts.at(-1) : undefined;+ const generatedImages = useMemo(() => tools+ .filter((message) => message.toolName === "GenerateImages")+ .map((message) => <GeneratedImages key={message.id} message={message} />), [tools]);+ const partContext = { isActive, activePart, runtimeActivity, turnDelegationStatuses, turnDelegationTimings };+ return (+ <>+ {process.length > 0 ? (+ <TurnProcess+ turnId={entry.id}+ processParts={process}+ turnParts={entry.parts}+ visibleSteps={visibleSteps}+ isActive={isActive}+ failed={summary.hasError || outcome === "failed" || outcome === "timed_out" || outcome === "denied"}+ stopped={outcome === "stopped" || outcome === "aborted"}+ activity={runtimeActivity}+ >+ {segments.map((segment) => {+ if (segment.kind === "run") {+ return <StandaloneRunRow key={`run-${segment.key}`} segment={segment} />;+ }+ return (+ <AssistantTurnParts key={`process-${segment.key}`} parts={segment.parts} {...partContext} />+ );+ })}+ </TurnProcess>+ ) : null}+ {/* The answer stays outside the process disclosure: it is what the turn+ produced, not part of what it did. */}+ <AssistantTurnParts parts={responses} {...partContext} />+ {generatedImages}+ </>+ );+});diff --git a/apps/desktop/src/features/chat/transcript/TurnProcess.tsx b/apps/desktop/src/features/chat/transcript/TurnProcess.tsxindex 3b35ba130..8d8ea2fe1 100644--- a/apps/desktop/src/features/chat/transcript/TurnProcess.tsx+++ b/apps/desktop/src/features/chat/transcript/TurnProcess.tsx@@ -60,6 +60,7 @@ export function TurnProcess({visibleSteps,isActive,failed,+ stopped,activity,children,}: {@@ -71,6 +72,8 @@ export function TurnProcess({isActive: boolean;/** The turn recorded a failure of its own, so the header must not claim success. */failed: boolean;+ /** A delegation can settle as stopped without a final assistant row. */+ stopped?: boolean;/** Live runtime stage, when the runtime reports one. */activity?: AgentActivity;children: ReactNode;@@ -119,7 +122,7 @@ export function TurnProcess({// `startedAt` is absent for history that recorded no timing, and "0s" would be// a lie there, so the duration is dropped instead.const hasTiming = startedAt !== undefined && seconds > 0;- const phase = turnProcessPhase({ parts: turnParts, isActive, failed, activity });+ const phase = turnProcessPhase({ parts: turnParts, isActive, failed, stopped, activity });// The header's label is the status alone. Duration and tool count are separate// values so each can be omitted independently, and the caret can follow the// last one instead of being pushed to the far edge of the band.@@ -139,7 +142,7 @@ export function TurnProcess({// included, so the header must not add them again.const toolCount = summary.tools;return (- <section className={`turn-process${disclosure.open ? " open" : ""}${isActive ? " active" : ""}`}>+ <section className={`turn-process${disclosure.open ? " open" : ""}${isActive ? " active" : ""}`}><buttontype="button"ref={disclosure.titleRef}diff --git a/apps/desktop/src/features/chat/transcript/disclosure.tsx b/apps/desktop/src/features/chat/transcript/disclosure.tsxindex 6797e47bc..128cbd628 100644--- a/apps/desktop/src/features/chat/transcript/disclosure.tsx+++ b/apps/desktop/src/features/chat/transcript/disclosure.tsx@@ -12,7 +12,7 @@ import {type ReactNode,} from "react";import { useDisclosureAnchorNotifier } from "../../../lib/disclosure-anchor-context";-import { sessionReadingState, type TranscriptDisclosureChoice } from "../../../lib/transcript-reading-position";+import { transcriptDisclosureChoices, type TranscriptDisclosureChoice } from "../../../lib/transcript-reading-position";import { ScopeContext, type DisclosureScopeValue } from "./disclosure-scope";type Choice = TranscriptDisclosureChoice;@@ -56,9 +56,13 @@ const ChoicesContext = createContext<DisclosureChoices | null>(null);export type { DisclosureScopeValue } from "./disclosure-scope";/** Explicit choices survive pane eviction, but never persist to the host. */-export function TranscriptDisclosureProvider({ children, sessionId }: { children: ReactNode; sessionId?: string }) {+export function TranscriptDisclosureProvider({ children, sessionId, delegationId }: {+ children: ReactNode;+ sessionId?: string;+ delegationId?: string;+}) {const [choices] = useState(() => new DisclosureChoices(- sessionId ? sessionReadingState(sessionId).disclosures : undefined,+ sessionId ? transcriptDisclosureChoices(sessionId, delegationId) : undefined,));return <ChoicesContext.Provider value={choices}>{children}</ChoicesContext.Provider>;}diff --git a/apps/desktop/src/lib/assistant-turns.ts b/apps/desktop/src/lib/assistant-turns.tsindex ec8181d2f..144eef75c 100644--- a/apps/desktop/src/lib/assistant-turns.ts+++ b/apps/desktop/src/lib/assistant-turns.ts@@ -206,6 +206,83 @@ function chainLatestCalls(};}+function appendAssistantTurnMessage(+ current: AssistantTurnEntry,+ message: UiMessage,+ delegate?: SubagentRun,+) {+ const pushActivity = (item: AssistantActivityItem) => {+ const last = current.parts[current.parts.length - 1];+ const standalone = isStandaloneRunActivity(item);+ const lastStandalone =+ last?.kind === "activity" &&+ last.items.length === 1 &&+ isStandaloneRunActivity(last.items[0]);+ // A delegation card is only the Task fan-out. Mixing the parent's later+ // Read/Grep/thinking into that group painted them as subagent work (D319).+ // A standalone run row never merges with a neighbour, so adjacent Bash+ // calls each keep their own row.+ if (+ last?.kind === "activity" &&+ last.items.length > 0 &&+ !standalone &&+ !lastStandalone &&+ isDelegationStartActivity(last.items[0]) === isDelegationStartActivity(item)+ ) {+ last.items.push(item);+ return;+ }+ current.parts.push({ kind: "activity", items: [item] });+ };++ if (message.role === "tool") {+ pushActivity({+ kind: "tool",+ message,+ ...(delegate ? { delegate } : {}),+ });+ return;+ }+ const thinking = messageThinking(message);+ if (thinking) pushActivity({ kind: "thinking", message });+ for (const round of hostedSearchRounds(message.hostedSearch)) {+ pushActivity({ kind: "hostedSearch", message, round });+ }+ const hasContent = messageContentFacts(message).hasContent;+ if (hasContent || !thinking || message.error) {+ current.parts.push({ kind: "message", message });+ if (!current.anchorId && hasContent) {+ current.anchorId = message.id;+ }+ }+}++function finishAssistantTurn(entry: AssistantTurnEntry) {+ for (let index = 0; index < entry.parts.length; index += 1) {+ const part = entry.parts[index];+ const next = entry.parts[index + 1];+ if (+ part.kind === "activity" &&+ next?.kind === "message" &&+ !part.items.some((item) => item.message.id === next.message.id)+ ) {+ part.endedAt = next.message.createdAt;+ }+ }+}++/** Project the already scoped child messages of one Task call as one turn. */+export function buildDelegationReply(callId: string, messages: readonly UiMessage[]): AssistantTurnEntry {+ const entry: AssistantTurnEntry = { kind: "assistant-turn", id: callId, parts: [] };+ for (const message of messages) {+ if ((message.role === "assistant" || message.role === "tool") && isVisibleMessage(message)) {+ appendAssistantTurnMessage(entry, message);+ }+ }+ finishAssistantTurn(entry);+ return entry;+}+/*** Group provider-level assistant fragments and tool rows into user-level turns.* Providers end an assistant message before each tool call, but that transport@@ -249,31 +326,6 @@ export function buildTranscriptEntries(return turn;};- const pushActivity = (item: AssistantActivityItem) => {- const current = ensureTurn(item.message);- const last = current.parts[current.parts.length - 1];- const standalone = isStandaloneRunActivity(item);- const lastStandalone =- last?.kind === "activity" &&- last.items.length === 1 &&- isStandaloneRunActivity(last.items[0]);- // A delegation card is only the Task fan-out. Mixing the parent's later- // Read/Grep/thinking into that group painted them as subagent work (D319).- // A standalone run row never merges with a neighbour, so adjacent Bash- // calls each keep their own row.- if (- last?.kind === "activity" &&- last.items.length > 0 &&- !standalone &&- !lastStandalone &&- isDelegationStartActivity(last.items[0]) === isDelegationStartActivity(item)- ) {- last.items.push(item);- return;- }- current.parts.push({ kind: "activity", items: [item] });- };-const appendMessage = (message: UiMessage) => {if (message.role === "user" || message.role === "system") {turn = undefined;@@ -281,31 +333,9 @@ export function buildTranscriptEntries(return;}- if (message.role === "tool") {- const delegate = message.toolCallId- ? runs.get(message.toolCallId)- : undefined;- pushActivity({- kind: "tool",- message,- ...(delegate ? { delegate } : {}),- });- return;- }-- const current = ensureTurn(message);- const thinking = messageThinking(message);- if (thinking) pushActivity({ kind: "thinking", message });- for (const round of hostedSearchRounds(message.hostedSearch)) {- pushActivity({ kind: "hostedSearch", message, round });- }- const hasContent = messageContentFacts(message).hasContent;- if (hasContent || !thinking || message.error) {- current.parts.push({ kind: "message", message });- if (!current.anchorId && hasContent) {- current.anchorId = message.id;- }- }+ const delegate = message.role === "tool" && message.toolCallId+ ? runs.get(message.toolCallId) : undefined;+ appendAssistantTurnMessage(ensureTurn(message), message, delegate);};let previousRootTurnId: string | undefined;@@ -325,18 +355,7 @@ export function buildTranscriptEntries(}for (const entry of entries) {- if (entry.kind !== "assistant-turn") continue;- for (let index = 0; index < entry.parts.length; index += 1) {- const part = entry.parts[index];- const next = entry.parts[index + 1];- if (- part.kind === "activity" &&- next?.kind === "message" &&- !part.items.some((item) => item.message.id === next.message.id)- ) {- part.endedAt = next.message.createdAt;- }- }+ if (entry.kind === "assistant-turn") finishAssistantTurn(entry);}return { entries, visible };diff --git a/apps/desktop/src/lib/subagent-transcript.ts b/apps/desktop/src/lib/subagent-transcript.tsindex ca0877848..cf28d47ac 100644--- a/apps/desktop/src/lib/subagent-transcript.ts+++ b/apps/desktop/src/lib/subagent-transcript.ts@@ -1,14 +1,19 @@import type { UiMessage } from "@pi-desktop/shared";import {+ buildDelegationReply,delegationChainMaps,- messageThinking,- type SubagentRunItem,+ type AssistantTurnEntry,} from "./assistant-turns";import { isDelegationStartTool } from "./tool-display";import { delegationIdForMessage } from "./subagent-panel";-/** One user/assistant exchange of a delegate session. */-export type SubagentTranscriptTurn = { task: string; rows: SubagentRunItem[] };+/** One exchange of the delegation chain, keyed by its original Task call. */+export type SubagentTranscriptTurn = {+ task: string;+ call: UiMessage;+ messages: UiMessage[];+ reply: AssistantTurnEntry;+};/*** A delegate's conversation as alternating turns: each Task call of the@@ -65,10 +70,9 @@ function resumedCalls(* A Task call belongs to the delegation of `delegationId` when the call* identifies itself by that id — via its result payload, or via its own call* id when the runtime recorded none — or when it resumed another call of that- * chain. Turns appear in session order; each turn's rows are the messages- * whose `parentToolCallId` names that call, mapped exactly like the- * delegation card's run grouping. Returns null when no Task call matches, so- * the tab can show its unavailable state instead of an empty conversation.+ * this chain. Turns appear in session order; each turn owns the messages+ * whose `parentToolCallId` names that call. Returns null when it cannot be+ * located in the loaded window, so the tab can show its unavailable state.*/export function buildSubagentTranscript(messages: readonly UiMessage[],@@ -141,26 +145,20 @@ export function buildSubagentTranscript(.find(Boolean);const agentName = runAgentName || requestedName;+ const byCall = new Map<string, UiMessage[]>();+ for (const message of messages) {+ const owner = message.parentToolCallId;+ if (!owner || !chain.has(owner)) continue;+ const owned = byCall.get(owner);+ if (owned) owned.push(message);+ else byCall.set(owner, [message]);+ }const turns: SubagentTranscriptTurn[] = [];for (const call of calls) {- const callId = call.toolCallId as string;- if (!chain.has(callId)) continue;- const rows: SubagentRunItem[] = [];- for (const message of messages) {- if (message.parentToolCallId !== callId) continue;- if (message.role === "tool") {- rows.push({ kind: "tool", message });- continue;- }- // A delegate turn can carry reasoning and text at once, and both are- // worth showing: the text is the only place its narration and report- // exist.- if (messageThinking(message)) rows.push({ kind: "thinking", message });- if ((message.content || "").trim() || message.error) {- rows.push({ kind: "answer", message });- }- }- turns.push({ task: delegateTaskDescription(call), rows });+ const callId = call.toolCallId;+ if (!callId || !chain.has(callId)) continue;+ const owned = byCall.get(callId) ?? [];+ turns.push({ task: delegateTaskDescription(call), call, messages: owned, reply: buildDelegationReply(callId, owned) });}return {diff --git a/apps/desktop/src/lib/transcript-reading-position.ts b/apps/desktop/src/lib/transcript-reading-position.tsindex d754329c0..38aed4aac 100644--- a/apps/desktop/src/lib/transcript-reading-position.ts+++ b/apps/desktop/src/lib/transcript-reading-position.ts@@ -11,6 +11,7 @@ export type TranscriptDisclosureChoice = { open: boolean; revealRequest?: numbertype ReadingState = {position?: TranscriptReadingPosition;disclosures: Map<string, TranscriptDisclosureChoice>;+ delegationDisclosures?: Map<string, Map<string, TranscriptDisclosureChoice>>;};// Renderer-lifetime bookmarks, independent of the bounded DOM and message caches.@@ -24,6 +25,18 @@ export function sessionReadingState(sessionId: string): ReadingState {}return state;}++export function transcriptDisclosureChoices(sessionId: string, delegationId?: string) {+ const state = sessionReadingState(sessionId);+ if (delegationId === undefined) return state.disclosures;+ const tabs = state.delegationDisclosures ??= new Map();+ let choices = tabs.get(delegationId);+ if (!choices) {+ choices = new Map();+ tabs.set(delegationId, choices);+ }+ return choices;+}export function getTranscriptReadingPosition(sessionId: string | undefined) {return sessionId ? readingStates.get(sessionId)?.position : undefined;}diff --git a/apps/desktop/src/lib/turn-process.ts b/apps/desktop/src/lib/turn-process.tsindex a9f47d23d..9ec11a2f4 100644--- a/apps/desktop/src/lib/turn-process.ts+++ b/apps/desktop/src/lib/turn-process.ts@@ -224,12 +224,14 @@ export function turnProcessPhase({parts,isActive,failed,+ stopped,activity,}: {parts: readonly AssistantTurnPart[];isActive: boolean;/** The turn recorded a failure of its own. */failed: boolean;+ stopped?: boolean;/** Runtime phase while the turn is live, when the runtime reports one. */activity?: AgentActivity;}): TurnProcessPhase {@@ -240,12 +242,12 @@ export function turnProcessPhase({// text or an activity item (a tool, thinking, or hosted search) that was in// flight. A denied tool is not a stop - the run continued without that call -// so it stays a recorded issue.- const stopped = parts.some((part) =>+ const stoppedRow = parts.some((part) =>part.kind === "message"? part.message.status === "aborted": part.items.some((item) => item.message.status === "aborted"),);- if (stopped) return { kind: "stopped" };+ if (stopped || stoppedRow) return { kind: "stopped" };if (isActive) return { kind: "running", phase: activity?.phase };if (turnHasStreamingRows(parts)) return { kind: "unsettled" };return { kind: "completed" };diff --git a/apps/desktop/src/styles/work-panel.css b/apps/desktop/src/styles/work-panel.cssindex c9c75a098..0dcc93f8f 100644--- a/apps/desktop/src/styles/work-panel.css+++ b/apps/desktop/src/styles/work-panel.css@@ -428,38 +428,30 @@.subagent-transcript-composer {flex: none;- border-top: 1px solid var(--ds-border-subtle);- padding: 10px 14px;+ min-width: 0;+ padding: 0 14px 10px;}-.subagent-transcript-composer textarea {- font-size: var(--text-base);- line-height: var(--leading-chat);- display: block;- width: 100%;- min-height: calc(var(--leading-chat) * 2em);- resize: none;+.subagent-composer-notice {+ min-height: 2lh;+ max-height: none;+ color: var(--ds-text-secondary);+ cursor: default;}-.subagent-transcript-composer-controls {- display: flex;- align-items: center;- justify-content: space-between;- gap: 8px;- padding-top: 8px;+.subagent-composer-toolbar {+ justify-content: flex-end;}-.subagent-transcript-model-picker {- flex: 1 1 auto;- max-width: calc(100% - 36px);- justify-content: flex-start;- cursor: not-allowed;-}--.subagent-transcript-composer-controls > .stop-btn {- width: 26px;- height: 26px;- flex-basis: 26px;+.subagent-composer-model {+ display: inline-flex;+ align-items: center;+ min-width: 0;+ min-height: 28px;+ gap: 6px;+ font-size: var(--text-sm);+ padding-inline: 8px;+ color: var(--ds-text-secondary);}/* Shared per-tool empty state used by Files and plugin fallback surfaces. */.work-tab-empty {diff --git a/apps/desktop/test/subagent-conversation-user-path.test.mjs b/apps/desktop/test/subagent-conversation-user-path.test.mjsnew file mode 100644index 000000000..532024fac--- /dev/null+++ b/apps/desktop/test/subagent-conversation-user-path.test.mjs@@ -0,0 +1,207 @@+import assert from "node:assert/strict";+import { execFile } from "node:child_process";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { promisify } from "node:util";+import { build } from "esbuild";+import { repositoryRoot, resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";++const fixture = `+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import { createInstance } from "i18next";+import { I18nextProvider } from "react-i18next";+import { IPC } from "@pi-desktop/shared";+import { en } from "@pi-desktop/i18n/locales/en";+import { ConversationSettings } from "./features/settings/pages/ConversationSettings";+import { AssistantTurn } from "./features/chat/transcript/AssistantTurn";+import { TranscriptDisclosureProvider } from "./features/chat/transcript/disclosure";+import { SubagentTranscriptTab } from "./components/workpanel/SubagentTranscriptTab";+import { SlotSessionProvider } from "./plugins/renderer-slots/use-slots";+import { buildTranscriptEntries } from "./lib/assistant-turns";+import { useAppStore } from "./stores/app-store";+import "./styles/globals.css";++const sessionId = "fixture";+const message = (id, role, content, extra = {}) => ({+ id, role, content, createdAt: "2026-11-24T00:00:00.000Z", ...extra,+});+const tool = (id, toolName, content, extra = {}) => message(id, "tool", content, {+ toolName, toolCallId: id, toolStatus: "success", ...extra,+});+const task = (id, delegationId, description, status, modelId, resume) => tool(id, "Task", "", {+ toolArgs: { agent: "explorer", task: description, resume },+ toolResult: { details: { delegationId, status, modelId, thinkingLevel: "medium" } },+});+const first = task("task-first", "delegate-first", "Initial inspection", "completed", "earlier-model");+const latest = task("task-latest", "delegate-latest", "Follow-up inspection", "running", "latest-model", "delegate-first");+const child = { parentToolCallId: "task-first" };+const messages = [+ message("user", "user", "Inspect the project"),+ tool("main-read", "Read", "main read result"),+ tool("main-run", "Bash", "main output", { toolArgs: { command: "echo main" } }),+ first,+ message("thinking", "assistant", "", { ...child, thinking: "Delegate reasoning" }),+ tool("read", "Read", "delegate search needle", { ...child, toolResult: { content: [{ type: "text", text: "delegate search needle" }] } }),+ tool("run", "Bash", "delegate output", { ...child, toolArgs: { command: "echo delegate" } }),+ message("answer", "assistant", "Delegate final answer.", child),+ latest,+ task("task-other", "delegate-other", "Other delegate", "running", "other-model"),+ message("main-answer", "assistant", "Main answer."),+];+const entry = buildTranscriptEntries(messages).entries.find((item) => item.kind === "assistant-turn");+const requests = [];+const session = { id: sessionId, title: "Fixture", messages, navigationParent: first };+window.piDesktop = { invoke: async (channel, args) => {+ if (channel === IPC.invoke.sessionGet) return { ok: true, data: { session } };+ requests.push({ channel, args });+ return { ok: true, data: { pending: args.delegationIds } };+} };+const settings = { transcriptDisplayMode: "fully-folded", showThinking: true,+ autoCollapseSettledGroups: true, autoCollapseThinking: true };+useAppStore.setState({ activeSessionId: sessionId, retainedSessionIds: [sessionId],+ sessions: [session], settings, messages, runningSessions: { [sessionId]: true } });++function Harness() {+ const settings = useAppStore((state) => state.settings);+ const tabs = useAppStore((state) => state.workPanelTabs);+ const active = useAppStore((state) => state.activeWorkPanelTabId);+ const tab = tabs.find((item) => item.id === active);+ return <>+ <section id="settings"><ConversationSettings settings={settings} saveSettings={async (patch) => {+ useAppStore.setState({ settings: { ...useAppStore.getState().settings, ...patch } });+ }} /></section>+ <section id="main"><SlotSessionProvider sessionId={sessionId}>+ <TranscriptDisclosureProvider sessionId={sessionId}>+ <AssistantTurn entry={entry} isActive={false} delegationsLive />+ </TranscriptDisclosureProvider>+ </SlotSessionProvider></section>+ <aside id="panel" style={{ width: 340, height: 370, display: "flex" }}>+ {tab?.kind === "subagent" ? <SubagentTranscriptTab delegationId={tab.resource} /> : null}+ </aside>+ </>;+}++window.probe = async () => {+ const i18n = createInstance();+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });+ flushSync(() => createRoot(document.getElementById("root")).render(+ <I18nextProvider i18n={i18n}><Harness /></I18nextProvider>,+ ));+ const check = (ok, message) => { if (!ok) throw new Error(message); };+ const q = (selector) => document.querySelector(selector);+ const click = (item) => { check(item, "Missing click target"); flushSync(() => item.click()); };+ const radio = (label) => [...document.querySelectorAll('[role="radio"]')].find((item) => item.textContent.trim() === label);+ const toggle = (label) => q('[role="switch"][aria-label="' + label + '"]');+ const process = () => q("#panel .turn-process > button");+ const group = () => q("#panel .process-activity-group.grouped > button");+ const reasoning = () => q("#panel .thinking > button");+ const open = (item) => item?.getAttribute("aria-expanded") === "true";+ const unfold = (item) => { if (!open(item)) click(item); };+ const visible = (selector) => Boolean(q(selector) && !q(selector).closest("[hidden]"));+ const until = async (condition, message) => {+ const deadline = performance.now() + 3000;+ while (!condition()) {+ check(performance.now() < deadline, message);+ await new Promise(requestAnimationFrame);+ }+ };+ unfold(q("#main .turn-process > button"));+ const node = (id) => q('#main [data-message-id="' + id + '"] .subagent-topology-node-header');+ click(node("task-first"));+ check(q("#panel").textContent.includes("Initial inspection") && q("#panel").textContent.includes("Follow-up inspection"), "resume chain did not open as two prompts");+ check(!open(process()) && visible('#panel [data-message-id="answer"]'), "settled process must be closed while the answer stays visible");+ unfold(process());+ check(!open(group()), "settled group must default to folded");+ click(toggle("Fold finished groups"));+ check(open(group()), "disabling automatic group folding did not open a settled group");+ click(toggle("Fold finished thinking"));+ check(open(reasoning()), "disabling automatic thinking folding did not open settled reasoning");+ click(toggle("Fold finished thinking"));+ click(toggle("Fold finished groups"));+ check(!open(group()), "re-enabling automatic group folding did not close the group");+ unfold(group());+ check(!open(reasoning()), "settled reasoning must default to folded");+ unfold(reasoning());+ click(process());+ check(!visible("#panel .thinking-prose"), "folded process did not hide nested details");+ unfold(process());+ check(open(group()) && visible("#panel .thinking-prose"), "reopening process did not restore nested choices");+ click(node("task-other"));+ check(!q('#panel [data-message-id="answer"]'), "parallel delegate inherited another delegate’s answer");+ click(node("task-first"));+ check(open(process()) && open(group()), "returning to the tab lost its manual choices");++ click(radio("Flat"));+ check(!q("#main .process-activity-group.grouped") && !group() && process(), "Flat did not remove inner groups from both transcripts");+ click(radio("Commands first"));+ check(q("#main .turn-run-row") && q("#panel .turn-run-row"), "Commands first did not lift commands in both transcripts");+ click(radio("Fully folded"));+ check(!q("#main .turn-run-row") && !q("#panel .turn-run-row") && group(), "Fully folded did not group commands in both transcripts");+ click(toggle("Show thinking"));+ check(!reasoning(), "Show thinking did not hide completed reasoning");+ click(toggle("Show thinking"));+ check(reasoning(), "re-enabling thinking did not restore the row");+ if (open(group())) click(group());+ if (open(process())) click(process());+ await useAppStore.getState().navigateTranscript({ sessionId, messageId: "read", query: "search needle" });+ await until(() => open(process()), "search did not open the process");+ check(open(group()), "search did not open the activity group");+ const readButton = q('#panel [data-message-id="read"] .tool-row-header');+ check(open(readButton) && !readButton.disabled, "search did not open the tool result");+ check(q("#panel .transcript-search-target"), "search did not claim the delegate hit");++ const footer = q("#panel footer");+ check(footer.querySelector(".composer-shell") && footer.textContent.includes("input is unavailable"), "read-only composer shell or hint missing");+ check(footer.textContent.includes("latest-model") && footer.textContent.includes("medium") && !footer.textContent.includes("earlier-model"), "metadata was not read from the latest Task");+ check(!footer.querySelector("textarea,input,[contenteditable],[aria-haspopup],.send-btn") && footer.querySelectorAll("button").length === 1,+ "footer exposed an editor, picker, or extra action");+ click(footer.querySelector(".stop-btn"));+ check(JSON.stringify(requests) === JSON.stringify([{ channel: IPC.invoke.agentStopSubagents,+ args: { sessionId, delegationIds: ["delegate-latest"] } }]), "stop was not scoped to the latest delegate");+};+`;++const entry = `+const { app, BrowserWindow } = require("electron");+const { join } = require("node:path");+app.setPath("userData", join(__dirname, "profile"));+app.whenReady().then(async () => {+ const window = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: false } });+ window.webContents.on("console-message", (event) => console.error(event.message));+ await window.loadFile(join(__dirname, "index.html"));+ await window.webContents.executeJavaScript("window.probe()");+ console.log("PASS subagent conversation");+ app.exit(0);+}).catch((error) => { console.error(error); app.exit(1); });+`;++test("open a delegation and use the shared conversation display with a read-only composer", {+ skip: process.platform === "linux" && !process.env.DISPLAY,+}, async () => {+ const root = repositoryRoot();+ const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? tmpdir(), "pi-subagent-conversation-"));+ try {+ await build({+ stdin: { contents: fixture, resolveDir: join(root, "apps/desktop/src"), loader: "tsx" },+ bundle: true, jsx: "automatic", format: "esm", outfile: join(temp, "fixture.js"),+ conditions: ["style"],+ loader: { ".woff": "dataurl", ".woff2": "dataurl", ".ttf": "dataurl", ".svg": "dataurl" },+ define: { "process.env.NODE_ENV": '"production"', "import.meta.env.DEV": "false" },+ });+ await writeFile(join(temp, "index.html"), `<!doctype html>+ <meta charset="utf-8">+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data:">+ <link rel="stylesheet" href="fixture.css">+ <div id="root"></div><script type="module" src="fixture.js"></script>`);+ await writeFile(join(temp, "main.cjs"), entry);+ const env = { ...process.env };+ delete env.ELECTRON_RUN_AS_NODE;+ const { stdout } = await promisify(execFile)(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], { env, timeout: 30000 });+ assert.match(stdout, /PASS subagent conversation/);+ } finally {+ await rm(temp, { recursive: true, force: true, maxRetries: 5 });+ }+});diff --git a/apps/desktop/test/subagent-panel.test.mjs b/apps/desktop/test/subagent-panel.test.mjsindex 40de88b26..5ca47d6fb 100644--- a/apps/desktop/test/subagent-panel.test.mjs+++ b/apps/desktop/test/subagent-panel.test.mjs@@ -90,22 +90,14 @@ test("the delegation tab renders a message list with a read-only composer", () =assert.match(tabSource, /buildSubagentTranscript\(messages, delegationId\)/);assert.match(tabSource, /className="message-row user"/);assert.match(tabSource, /className="message-user-text selectable"/);- assert.match(tabSource, /className="message-row assistant"/);- assert.match(tabSource, /data-message-id=\{row\.message\.id\}/);- assert.match(tabSource, /<Textarea/);- assert.match(tabSource, /disabled/);- assert.match(tabSource, /rows=\{2\}/);- assert.match(tabSource, /placeholder=\{t\("panel\.subagentReadOnly"\)\}/);- assert.match(tabSource, /className="subagent-transcript-composer-controls"/);- assert.match(tabSource, /subagent-transcript-model-picker/);- assert.match(tabSource, /delegateModelId\(result\)/);- assert.match(tabSource, /delegateThinkingLevel\(result\)/);- assert.match(tabSource, /<SubagentStopButton delegationId=\{delegationId\} running compact \/>/);- assert.doesNotMatch(tabSource, /subagent-transcript-actions/);- assert.match(workPanelCss, /\.subagent-transcript-composer-controls \{/);- assert.match(workPanelCss, /\.subagent-transcript-model-picker \{/);- // Display-only: no send path may exist in the composer.- assert.doesNotMatch(tabSource, /onSubmit|onSend|api\.send/);+ assert.match(tabSource, /<AssistantTurnBody[\s\S]*entry=\{reply\}/);+ assert.match(tabSource, /<TranscriptSearchContext.Provider value=\{searchTarget\}>/);+ assert.match(tabSource, /className="composer-shell"/);+ assert.match(tabSource, /t\("panel\.subagentReadOnly"\)/);+ assert.match(tabSource, /delegateModelId\(latest\)/);+ assert.match(tabSource, /delegateThinkingLevel\(latest\)/);+ assert.match(tabSource, /delegationIdForMessage\(latest\)/);+ assert.doesNotMatch(tabSource, /<Textarea|contentEditable|<Composer|aria-haspopup|onSubmit|onSend/);});test("the tab owns one scroll surface and pins to the latest output", () => {diff --git a/apps/desktop/test/subagent-transcript-turns.test.mjs b/apps/desktop/test/subagent-transcript-turns.test.mjsindex 3e77ad7e3..894699da2 100644--- a/apps/desktop/test/subagent-transcript-turns.test.mjs+++ b/apps/desktop/test/subagent-transcript-turns.test.mjs@@ -9,6 +9,7 @@ register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));const { buildSubagentTranscript } = await import("../src/lib/subagent-transcript.ts");+const { projectTurnProcess, segmentTurnProcess } = await import("../src/lib/turn-process.ts");function message(id, content, extra = {}) {return { id, content, ...extra };@@ -47,7 +48,7 @@ test("one Task call becomes one user turn followed by the delegate's rows", () =assert.equal(transcript.turns.length, 1);assert.equal(transcript.turns[0].task, "Find all call sites of resize()");assert.deepEqual(- transcript.turns[0].rows.map((row) => row.kind),+ transcript.turns[0].reply.parts.flatMap((part) => part.kind === "activity" ? part.items.map((item) => item.kind) : ["answer"]),["tool", "thinking", "answer"],);});@@ -74,12 +75,12 @@ test("a resumed delegation renders follow-up prompts as further user turns", ()assert.equal(transcript.turns.length, 2);assert.equal(transcript.turns[0].task, "First prompt");assert.deepEqual(- transcript.turns[0].rows.map((row) => row.message.id),+ transcript.turns[0].messages.map((message) => message.id),["answer-1"],);assert.equal(transcript.turns[1].task, "Follow-up prompt");assert.deepEqual(- transcript.turns[1].rows.map((row) => row.message.id),+ transcript.turns[1].messages.map((message) => message.id),["answer-2"],);});@@ -126,12 +127,12 @@ test("parallel delegates never mix into each other's turns", () => {const b = buildSubagentTranscript(messages, "del-b");assert.equal(a.agentName, "explorer");assert.deepEqual(- a.turns.flatMap((turn) => turn.rows.map((row) => row.message.id)),+ a.turns.flatMap((turn) => turn.messages.map((message) => message.id)),["answer-a"],);assert.equal(b.agentName, "reviewer");assert.deepEqual(- b.turns.flatMap((turn) => turn.rows.map((row) => row.message.id)),+ b.turns.flatMap((turn) => turn.messages.map((message) => message.id)),["answer-b"],);});@@ -152,8 +153,8 @@ test("nested tools stay with their owning delegate, not their tool parent", () =];const transcript = buildSubagentTranscript(messages, "delegate-1");assert.equal(transcript.agentName, "reader");- assert.deepEqual(transcript.turns[0].rows.map((row) => row.message.id), ["code-1", "nested-read"]);- assert.equal(transcript.turns[0].rows[1].message.nestedParentToolCallId, "code-1");+ assert.deepEqual(transcript.turns[0].messages.map((message) => message.id), ["code-1", "nested-read"]);+ assert.equal(transcript.turns[0].messages[1].nestedParentToolCallId, "code-1");assert.equal(buildSubagentTranscript(messages, "root-code"), null);});@@ -178,3 +179,24 @@ test("a call with no task argument degrades to an empty prompt", () => {const transcript = buildSubagentTranscript(messages, "del-1");assert.equal(transcript.turns[0].task, "");});++test("a delegation turn uses the shared process layout and keeps its answer separate", () => {+ const child = { parentToolCallId: "task-1", turnId: "parent-turn" };+ const messages = [+ taskCall("task-1", "Inspect files", { toolResult: { delegationId: "delegate-1" } }),+ message("think", "", { ...child, role: "assistant", thinking: "Check the files." }),+ message("read", "a file", { ...child, role: "tool", toolName: "Read" }),+ message("run", "command output", { ...child, role: "tool", toolName: "Bash" }),+ message("progress", "One more check.", { ...child, role: "assistant" }),+ message("grep", "another file", { ...child, role: "tool", toolName: "Grep" }),+ message("answer", "Done.", { ...child, role: "assistant" }),+ ];+ const { turns: [turn] } = buildSubagentTranscript(messages, "delegate-1");+ assert.equal(turn.reply.id, "task-1");+ const { process, responses } = projectTurnProcess(turn.reply);+ assert.deepEqual(responses.map((part) => part.message.id), ["answer"]);+ assert.ok(process.some((part) => part.kind === "message" && part.message.id === "progress"));+ assert.deepEqual(segmentTurnProcess(process, "flat").map((segment) => segment.kind), ["process"]);+ assert.deepEqual(segmentTurnProcess(process, "command-first").map((segment) => segment.kind), ["process", "run", "process"]);+ assert.deepEqual(segmentTurnProcess(process, "fully-folded").map((segment) => segment.kind), ["process"]);+});diff --git a/apps/desktop/test/transcript-display-modes-ui.test.mjs b/apps/desktop/test/transcript-display-modes-ui.test.mjsindex 23f81b073..4899f1cc3 100644--- a/apps/desktop/test/transcript-display-modes-ui.test.mjs+++ b/apps/desktop/test/transcript-display-modes-ui.test.mjs@@ -6,7 +6,7 @@ import { loadStyles } from "./helpers/styles.mjs";const activityGroupSource = await readTranscriptModule("ActivityGroup.tsx");const activityItemsSource = await readTranscriptModule("ActivityItems.tsx");-const assistantTurnSource = await readTranscriptModule("AssistantTurn.tsx");+const assistantTurnSource = await readTranscriptModule("AssistantTurnBody.tsx");const thinkingRowSource = await readTranscriptModule("shared.tsx");const shimmerSource = await readFile(new URL("../src/features/chat/transcript/TextShimmer.tsx", import.meta.url),diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 360f30d28..1422e22a8 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -2828,14 +2828,18 @@ as a conversation:└──────────────────────────────────────────────┘```-- The tab is a message list, not a card: every `Task` call of the resume- chain renders its `task` argument as a user row (the main transcript's user- bubble), and the delegate's thinking, tool, and answer rows under that call- render with the same message-list language, so a follow-up prompt reads as- the next user turn.-- The composer at the foot is a disabled two-row textarea whose placeholder- says subagents are driven by the main agent and cannot take input; the tab- is display-only and has no send path.+- Every `Task` call in the resume chain starts its own turn: the task prompt+ is a user bubble, followed by the shared assistant process and answer.+ Settings → Conversation controls the same three layouts, thinking visibility,+ and automatic folding as in MainChat. A turn has at most one outer process,+ activity groups where the selected layout allows them, and individual tool+ and thinking details. The final answer stays outside the process. Search+ reveals the matching levels; manual choices are scoped to each tab and session.+- The footer reuses the main composer shell with a localized read-only notice.+ The latest Task’s recorded model and thinking level are passive labels,+ omitted when unknown. There is no editor, send path, composer slot, or mode,+ permission, or model picker. A running delegate can still be stopped without+ stopping the parent or any other delegate.- Tab labels carry the agent name captured when the tab opened, with astrip-order `#n` suffix when the same name occurs more than once; alocalization fallback covers a delegate with no name.diff --git a/docs/spec/06-delivery/e2e/plugins-and-extensions.md b/docs/spec/06-delivery/e2e/plugins-and-extensions.mdindex 1a5544731..6f33bc4f2 100644--- a/docs/spec/06-delivery/e2e/plugins-and-extensions.md+++ b/docs/spec/06-delivery/e2e/plugins-and-extensions.md@@ -639,12 +639,18 @@ window; opening a normal panel afterward must still work.3. Click the second (resumed) `explorer` node. Verify a second tab openslabeled `explorer#2`, both tabs coexist, and each can be activated,drag-reordered, and closed via ×, middle-click, or Delete.- 4. In the resumed tab, verify the conversation reads `user: first prompt`,- delegate rows, `user: follow-up prompt`, delegate rows — the same- message-list language as the main transcript (user bubbles, tool rows,- thinking rows, markdown answers).- 5. Verify the composer at the foot is a disabled two-row textarea whose- placeholder reads the read-only hint, in every supported locale.+ 4. In the resumed tab, verify that the two Task prompts each start a turn+ with its own process disclosure and visible answer. Switch among Flat,+ Commands first, and Fully folded in Settings → Conversation. Verify the+ same layout updates live in both transcripts, without a new response.+ Check reasoning visibility, automatic folding, and that reopening a+ process restores manually opened child rows. Search for a tool result+ in a collapsed group and verify its owning tab reveals the match.+ 5. Verify the footer matches the main composer shell, but offers only the+ localized read-only hint, recorded model/reasoning metadata when known,+ and Stop while the delegate is stoppable. It has no picker, editable+ field, plug-in slot, attachment control, or send action. Stop a running+ delegate and verify the request names only that delegate.6. Wait for the failed delegate to settle, open its tab, and verify theended tab persists until manually closed.7. Switch to another session and back. Verify the tabs are restored per@@ -652,13 +658,15 @@ window; opening a normal panel afterward must still work.- **Expected**: No auto-open on delegate start; N subagents = N coexistingclosable tabs with deduplicated `name#n` labels; the tab body is thedelegation's user/assistant message stream with follow-up prompts as user- turns; the composer is disabled with the in-field hint and has no send- path; ended delegates' tabs persist until closed; tabs are session-scoped.+ turns; the footer is display-only except for an explicitly scoped stop;+ ended delegates’ tabs persist until closed; tabs and disclosure choices+ are independent of the main transcript and of other delegates.- **Specs linked**: `04-ux/08-component-spec.md` (delegation tab),`04-ux/09-interaction-patterns.md` (work panel tabs)- **Acceptance**: Quality- **Milestone**: M6-- **Status**: Draft+- **Status**: Renderer user path automated in `apps/desktop/test/subagent-conversation-user-path.test.mjs`;+ full work-panel tab lifecycle remains a manual scenario.## E2E-119: Parallel subagents report back without entering the parent's context