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(transcript): unify turn folding and command preferences
TioitWang8f4285fd2f25
diff --git a/apps/desktop/electron/main/bootstrap/shutdown.ts b/apps/desktop/electron/main/bootstrap/shutdown.tsindex b531b9a95..c7f6e2a6d 100644--- a/apps/desktop/electron/main/bootstrap/shutdown.ts+++ b/apps/desktop/electron/main/bootstrap/shutdown.ts@@ -46,7 +46,7 @@ export type ShutdownDependencies = {mcpOAuth?: Pick<McpOAuthManager, "disposeAll">;browserHost: Pick<BrowserHost, "dispose">;pluginViews: Pick<PluginViewHost, "dispose">;- /** Composer suggestions still waiting for an answer at quit (ADR 0332). */+ /** Composer suggestions still waiting for an answer at quit (ADR 0333). */composerSuggestion?: Pick<ComposerSuggestionRelay, "dispose">;updater: Pick<AppUpdaterController, "dispose" | "isInstallingUpdate">;logger: Pick<Logger, "app">;diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 7e5520299..7de4796d4 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -642,7 +642,7 @@ const sessionCoordination = createSessionCoordination({onTurnStarted: (sessionId: string, turnId: string) => {pluginServices.pluginSession.noteTurnStarted(sessionId, turnId);// A new turn owns the composer now, so a suggestion about the previous one- // stops being shown and stops being showable (ADR 0332).+ // stops being shown and stops being showable (ADR 0333).pluginServices.composerSuggestion.noteTurnStarted(sessionId, turnId);},});diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.tsindex 756c03913..e165aff04 100644--- a/apps/desktop/electron/main/ipc/register.ts+++ b/apps/desktop/electron/main/ipc/register.ts@@ -65,7 +65,7 @@ export type RegisterIpcDependencies = {setActivePluginSession: (next: { sessionId: string; projectPath: string | null } | null,) => void;- /** The shell's answer to a composer suggestion it was offered (ADR 0332). */+ /** The shell's answer to a composer suggestion it was offered (ADR 0333). */settleComposerSuggestion: (answer: ComposerSuggestionAnswer) => boolean;activeUserSubagentDocuments: (...args: any[]) => Promise<any>;disabledBuiltinSubagents: () => Promise<string[]>;diff --git a/apps/desktop/electron/main/plugin-host-process.mjs b/apps/desktop/electron/main/plugin-host-process.mjsindex 889a75146..89c91c41d 100644--- a/apps/desktop/electron/main/plugin-host-process.mjs+++ b/apps/desktop/electron/main/plugin-host-process.mjs@@ -253,7 +253,7 @@ function buildApi() {requestNotificationPermission: () => call("ui.requestNotificationPermission"),showNativeNotification: (input) => call("ui.showNativeNotification", [input]),},- // One line into the session's composer placeholder (ADR 0332). The shell+ // One line into the session's composer placeholder (ADR 0333). The shell// answers whether it went on screen, so a plugin never has to guess before// spending another completion.composer: {diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.tsindex cd2ded1b5..437d1455e 100644--- a/apps/desktop/electron/main/plugin-runtime.ts+++ b/apps/desktop/electron/main/plugin-runtime.ts@@ -4616,7 +4616,7 @@ export class PluginRuntime {}/*** `pi.composer.suggest`: one line into the composer of the session the user- * is looking at (`composer.suggest`, ADR 0332).+ * is looking at (`composer.suggest`, ADR 0333).** The plugin names the session and the turn its text answers. Nothing here* can fail the plugin for a place that will not show it: the text is shaped@@ -5584,7 +5584,7 @@ export class PluginRuntime {composer: {/*** One dismissible line in the placeholder layer of the composer the- * user is looking at (`composer.suggest`, ADR 0332).+ * user is looking at (`composer.suggest`, ADR 0333).*/suggest: async (input?: PluginComposerSuggestInput) =>this.suggestComposer(loaded, input),diff --git a/apps/desktop/electron/main/services/composer-suggestion.ts b/apps/desktop/electron/main/services/composer-suggestion.tsindex 0e92d0c15..0545f3250 100644--- a/apps/desktop/electron/main/services/composer-suggestion.ts+++ b/apps/desktop/electron/main/services/composer-suggestion.ts@@ -1,5 +1,5 @@/**- * The main-process half of `pi.composer.suggest` (ADR 0332).+ * The main-process half of `pi.composer.suggest` (ADR 0333).** A suggestion is produced by a plugin process, long after the turn it answers* ended, so by the time it arrives the user may have typed, switched session,diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.tsindex 33251db00..dcd0e1e43 100644--- a/apps/desktop/electron/main/services/plugin-services.ts+++ b/apps/desktop/electron/main/services/plugin-services.ts@@ -639,7 +639,7 @@ export function createPluginServices({announce: broadcastSessionEvent,});/**- * `pi.composer.suggest` (ADR 0332): the main process refuses a suggestion+ * `pi.composer.suggest` (ADR 0333): the main process refuses a suggestion* that names another session or an overtaken turn, and the shell answers* whether the composer can take it. The composer owns its own state, so this* only ever relays — nothing here writes the draft.diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsxindex 05d9fa922..ccb335817 100644--- a/apps/desktop/src/components/Composer.tsx+++ b/apps/desktop/src/components/Composer.tsx@@ -497,7 +497,7 @@ export function Composer({// Plugin draft and attachment actions reach this composer while it takes input.usePluginComposerBridge({ ...draft, inputBlocked, enabled: localToolsAllowed });// A plugin may have offered one line for this empty draft; it shows in the- // placeholder layer and `Tab` takes it (ADR 0332).+ // placeholder layer and `Tab` takes it (ADR 0333).const suggestion = useComposerSuggestion();// Keep the transcript's bottom reserve in sync with the composer's realdiff --git a/apps/desktop/src/components/settings/KeepCommandsExpandedRow.tsx b/apps/desktop/src/components/settings/KeepCommandsExpandedRow.tsxnew file mode 100644index 000000000..c32f47e61--- /dev/null+++ b/apps/desktop/src/components/settings/KeepCommandsExpandedRow.tsx@@ -0,0 +1,28 @@+import { useTranslation } from "react-i18next";+import type { AppSettings } from "@pi-desktop/shared";+import { resolveKeepCommandsExpanded } from "../../lib/command-folding";+import { SettingsRow } from "../../features/settings/primitives";+import { SettingsToggle } from "../ui";++export function KeepCommandsExpandedRow({+ settings,+ saveSettings,+}: {+ settings: AppSettings;+ saveSettings: (patch: Partial<AppSettings>) => Promise<void>;+}) {+ const { t } = useTranslation();+ const expanded = resolveKeepCommandsExpanded(settings);+ return (+ <SettingsRow+ title={t("settings.keepCommandsExpanded")}+ description={t("settings.keepCommandsExpandedDesc")}+ >+ <SettingsToggle+ checked={expanded}+ label={t("settings.keepCommandsExpanded")}+ onChange={() => void saveSettings({ keepCommandsExpanded: !expanded })}+ />+ </SettingsRow>+ );+}diff --git a/apps/desktop/src/features/chat/composer/ComposerInput.tsx b/apps/desktop/src/features/chat/composer/ComposerInput.tsxindex dcacf7487..434172183 100644--- a/apps/desktop/src/features/chat/composer/ComposerInput.tsx+++ b/apps/desktop/src/features/chat/composer/ComposerInput.tsx@@ -28,7 +28,7 @@ export type ComposerInputProps = {runActive: boolean;composerAc: CompletionController;/**- * The plugin suggestion on screen, if any (ADR 0332). It is drawn in the+ * The plugin suggestion on screen, if any (ADR 0333). It is drawn in the* placeholder layer while the draft is empty, and `Tab` / `Esc` act on it only* when nothing else claims those keys.*/diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerSuggestion.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerSuggestion.tsindex 2786277f8..b53e3c741 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerSuggestion.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerSuggestion.ts@@ -1,5 +1,5 @@/**- * The composer's view of the plugin suggestion slot (ADR 0332).+ * The composer's view of the plugin suggestion slot (ADR 0333).** The state itself lives in `../plugins/suggestion-bridge.ts`, outside React, so* a suggestion that arrives while the composer is unmounted is refused oncediff --git a/apps/desktop/src/features/chat/composer/plugins/suggestion-bridge.ts b/apps/desktop/src/features/chat/composer/plugins/suggestion-bridge.tsindex 1faedf3a4..76bb0b5b2 100644--- a/apps/desktop/src/features/chat/composer/plugins/suggestion-bridge.ts+++ b/apps/desktop/src/features/chat/composer/plugins/suggestion-bridge.ts@@ -1,5 +1,5 @@/**- * The renderer end of `pi.composer.suggest` (ADR 0332).+ * The renderer end of `pi.composer.suggest` (ADR 0333).** A plugin process offers one line, the shell decides whether the composer can* take it, and the user takes it with Tab, drops it with Esc, or drops it bydiff --git a/apps/desktop/src/features/chat/composer/plugins/suggestion-keys.ts b/apps/desktop/src/features/chat/composer/plugins/suggestion-keys.tsindex 9111cdb73..1e0761888 100644--- a/apps/desktop/src/features/chat/composer/plugins/suggestion-keys.ts+++ b/apps/desktop/src/features/chat/composer/plugins/suggestion-keys.ts@@ -1,5 +1,5 @@/**- * Which key, if any, acts on the composer's plugin suggestion (ADR 0332).+ * Which key, if any, acts on the composer's plugin suggestion (ADR 0333).** The composer already has owners for both keys and they keep them: a `@` / `/`* completion list takes `Tab` (and `Enter`), and its own `Escape` closes itdiff --git a/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx b/apps/desktop/src/features/chat/transcript/ActivityGroup.tsxindex 338dd06fc..b8c11ab63 100644--- a/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx+++ b/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx@@ -60,22 +60,6 @@ type Translate = (key: string, options?: Record<string, unknown>) => string;type ActivityItem = AssistantActivityItem;-export function activityItemDetail(item: ActivityItem): string {- if (item.kind === "hostedSearch") return item.round.query ?? "";- if (item.kind === "thinking") {- // Latest thought line, so a collapsed header reads like a live ticker.- const lines = thinkingText(item.message)- .split("\n")- .map((line) => line.replace(/^#+\s*|\*\*/g, "").trim())- .filter(Boolean);- return lines[lines.length - 1] || "";- }- if (lifecycleKindOf(item.message)) {- return delegationRosterSummary(delegationRoster(item.message));- }- return getToolSummary(item.message.toolName, item.message.toolArgs);-}-function waitingSubagentActionLabel(agent: AgentActivityAgent,@@ -260,6 +244,10 @@ export const ActivityGroup = memo(function ActivityGroup({disclosureKey("activity", first?.message.id ?? "", first?.kind ?? "", first?.kind === "hostedSearch" ? first.round.id : ""),);const { open, toggle: toggleDisclosure, collapse: collapseDisclosure, claim: claimDisclosure, titleRef } = disclosure;+ // A subagent card is its own disclosure, so it reads the same parent gate the+ // group does: below a collapsed whole-turn process it stays shut, and+ // reopening the process restores the card's own choice.+ const cardShut = hasSubagentTopology && !open;const [now, setNow] = useState(Date.now);const [finishedAt, setFinishedAt] = useState<number | null>(null);const wasActiveRef = useRef(live);@@ -308,14 +296,10 @@ export const ActivityGroup = memo(function ActivityGroup({: // History reloads keep no end timestamp for pure-thinking groups.t("chat.thinking", { defaultValue: "Thinking" }): t("chat.processedFor", { time: elapsed });- const runtimeStatus = runtimeActivity- ? runActivityLabel(runtimeActivity, t as Translate)- : "";- const currentDetail = useMemo(() =>- live && !runtimeStatus && lastItem && !(hideThinking && lastItem.kind === "thinking")- ? activityItemDetail(lastItem) : "",- [live, runtimeStatus, lastItem, hideThinking]);- const tail = live && !open ? currentDetail : "";+ // The header states outcome, counts and elapsed time; it never echoes the item+ // it is working on. A shell command or a search query can be arbitrarily long,+ // and repeating it here pushed the counts off the row while adding nothing a+ // reader cannot get by opening the item.useEffect(() => {if (wasActiveRef.current && !live) setFinishedAt(Date.now());@@ -392,17 +376,13 @@ export const ActivityGroup = memo(function ActivityGroup({</button><SubagentStopButton running={topologyLive} /></div>- {tail ? (- <div className="tool-activity-preview" aria-hidden>- {tail}- </div>- ) : null}<divref={disclosure.bodyRef}{...disclosure.bodyEvents}className="tool-activity-collapse"- aria-hidden={!open}- inert={!open}+ aria-hidden={!open || cardShut}+ inert={!open || cardShut}+ hidden={cardShut}><div className="tool-activity-collapse-inner"><div className="tool-activity-body" id={detailsId}>diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsxindex 8e99645cb..7e47519fe 100644--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx@@ -24,6 +24,9 @@ import {type TurnProcessRunSegment,} from "../../../lib/turn-process";import { sessionAllows } from "../../../lib/remote-session-safety";+import { resolveShowThinking } from "../../../lib/thinking-visibility";+import { resolveKeepCommandsExpanded } from "../../../lib/command-folding";+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";@@ -281,6 +284,10 @@ 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@@ -344,7 +351,24 @@ export const AssistantTurn = memo(function AssistantTurn({statusesRef.current = turnDelegationStatuses;timingsRef.current = turnDelegationTimings;const { process, responses } = summary;- const segments = useMemo(() => segmentTurnProcess(process), [process]);+ // 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 keepCommandsExpanded = useAppStore((state) => resolveKeepCommandsExpanded(state.settings));+ const segments = useMemo(+ () => segmentTurnProcess(process, keepCommandsExpanded),+ [process, keepCommandsExpanded],+ );+ // 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@@ -362,25 +386,29 @@ export const AssistantTurn = memo(function AssistantTurn({aria-label={t("chat.assistantMessage")}><div className="message-col">- {segments.map((segment) => {- if (segment.kind === "run") {- return <StandaloneRunRow key={`run-${segment.key}`} segment={segment} />;- }- const ownsActiveTail =- activePart !== undefined && segment.parts.includes(activePart);- return (- <TurnProcess- key={`process-${segment.key}`}- turnId={segment.key}- processParts={segment.parts}- turnParts={entry.parts}- isActive={isActive && ownsActiveTail}- delegationStatuses={turnDelegationStatuses}- >- <AssistantTurnParts parts={segment.parts} {...partContext} />- </TurnProcess>- );- })}+ {process.length > 0 ? (+ <TurnProcess+ turnId={entry.id}+ processParts={process}+ turnParts={entry.parts}+ visibleSteps={visibleSteps}+ isActive={isActive}+ delegationStatuses={turnDelegationStatuses}+ 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}{!isActive && metaMessage ? (diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsxindex 876e36b7d..89f607f9c 100644--- a/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx+++ b/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx@@ -37,6 +37,26 @@ function partKey(part: AssistantTurnPart) {return `activity-${first.message.id}-${first.kind}${first.kind === "hostedSearch" ? `-${first.round.id}` : ""}`;}+/**+ * Whether a rendered part owns the active tail.+ *+ * A command-folding segment may coalesce contiguous activity parts into a new+ * part object while keeping the source rows. The active tail is the last entry+ * part, so the coalesced part's last row is the same row object; no id fallback+ * or nested scan is needed.+ */+function partOwnsActivePart(+ part: AssistantTurnPart,+ activePart: AssistantTurnPart,+): boolean {+ if (part === activePart) return true;+ if (part.kind !== "activity" || activePart.kind !== "activity") {+ return false;+ }+ const activeRow = activePart.items.at(-1);+ return activeRow !== undefined && part.items.at(-1) === activeRow;+}+type PartContext = {isActive: boolean;activePart?: AssistantTurnPart;@@ -73,8 +93,14 @@ export const AssistantTurnParts = memo(function AssistantTurnParts({ parts, ...cparts: readonly AssistantTurnPart[];}) {const blocks = useRenderBlocks(parts, partKey);+ const activeSourcePart = context.activePart;return <>{blocks.map((block) => {- const activePart = context.activePart && block.items.includes(context.activePart) ? context.activePart : undefined;+ // The active tail is an entry part, but an off-mode segment may wrap its+ // rows in a new merged part. Match by source row so the group that owns the+ // live step still gets its active defaults.+ const activePart = activeSourcePart+ ? block.items.find((part) => partOwnsActivePart(part, activeSourcePart))+ : undefined;return <TurnPartBlockkey={block.key}block={block}diff --git a/apps/desktop/src/features/chat/transcript/ProcessActivityGroup.tsx b/apps/desktop/src/features/chat/transcript/ProcessActivityGroup.tsxindex 804faff24..5ca62c78a 100644--- a/apps/desktop/src/features/chat/transcript/ProcessActivityGroup.tsx+++ b/apps/desktop/src/features/chat/transcript/ProcessActivityGroup.tsx@@ -21,7 +21,11 @@ export function ProcessActivityGroup({const { t } = useTranslation();const detailsId = useId();const grouped = items.length > 1;- const open = !grouped || disclosure.open;+ // A group below a collapsed whole-turn process is not expanded even when the+ // user left it open: `disclosure.open` already folds in that gate, and the+ // choice itself survives so reopening the process restores it.+ const parentVisible = disclosure.parentVisible;+ const open = (!grouped || disclosure.open) && parentVisible;const summary = useMemo(() => cachedActivitySummary(items), [items]);if (items.length === 0) return null;return (diff --git a/apps/desktop/src/features/chat/transcript/TurnProcess.tsx b/apps/desktop/src/features/chat/transcript/TurnProcess.tsxindex 488ed2924..dfb83ab75 100644--- a/apps/desktop/src/features/chat/transcript/TurnProcess.tsx+++ b/apps/desktop/src/features/chat/transcript/TurnProcess.tsx@@ -1,42 +1,83 @@import type { SubagentOutcome } from "../../../lib/subagent-topology";import { useContext, useEffect, useId, useMemo, useState, type ReactNode } from "react";import { useTranslation } from "react-i18next";+import type { AgentActivity } from "@pi-desktop/shared";import type { AssistantTurnPart } from "../../../lib/assistant-turns";import { formatToolDuration } from "../../../lib/tool-display";-import { cachedActivitySummary, cachedVisibleProcessSteps } from "../../../lib/transcript-activity-summary";+import { cachedActivitySummary } from "../../../lib/transcript-activity-summary";import { TranscriptSearchContext } from "../../../lib/transcript-search-context";import {isTurnThinking,processContainsMessage,+ turnProcessPhase,turnProcessTiming,} from "../../../lib/turn-process";-import { resolveShowThinking } from "../../../lib/thinking-visibility";-import { useAppStore } from "../../../stores/app-store";import {IconChevronRight,IconCircleAlert,IconSparkles,} from "../../../components/icons";import { DisclosureCollapseRail } from "./shared";-import { DisclosureScope, disclosureKey, useAutomaticDisclosure } from "./disclosure";+import {+ disclosureKey,+ useAutomaticDisclosure,+ type DisclosureScopeValue,+} from "./disclosure";+import { ScopeContext } from "./disclosure-scope";++/**+ * Live stages that rate their own wording.+ *+ * Only stages a reader can sit in front of for a while are listed: compaction+ * and recovery both move real work and both look like a stall without a name.+ * `starting`, `waiting-model` and `preparing` are momentary, so they read as+ * plain running rather than flickering between labels.+ */+const LIVE_PHASE_KEYS: Partial<Record<AgentActivity["phase"], string>> = {+ compacting: "chat.compactingContext",+ recovering: "chat.recoveringTurn",+ retrying: "chat.processRunning",+ "waiting-subagents": "chat.processRunning",+};+/**+ * The whole turn's process, as one disclosure.+ *+ * Every row the turn produced before its answer lives here: the activity groups+ * and the standalone `Bash` run rows alike. That is one top-level collapse for+ * the turn, with the groups and run calls at the level below it, so a long+ * turn reads as "what the agent did" plus the answer instead of a scrolling+ * stack of sibling disclosures.+ *+ * The levels below read this disclosure's scope rather than its choice: closing+ * the process here closes every group under it, and reopening restores the+ * groups the user had opened (see `disclosure.tsx`).+ */export function TurnProcess({turnId,processParts,turnParts,+ visibleSteps,delegationStatuses,isActive,+ failed,+ activity,children,}: {turnId: string;processParts: readonly AssistantTurnPart[];turnParts: readonly AssistantTurnPart[];+ /** Visible steps the process reveals; `0` draws no disclosure. */+ visibleSteps: number;isActive: boolean;+ /** The turn recorded a failure of its own, so the header must not claim success. */+ failed: boolean;+ /** Live runtime stage, when the runtime reports one. */+ activity?: AgentActivity;delegationStatuses?: ReadonlyMap<string, SubagentOutcome>;children: ReactNode;}) {const { t } = useTranslation();- const showThinking = useAppStore((state) => resolveShowThinking(state.settings));const search = useContext(TranscriptSearchContext);const revealRequest = useMemo(() => search && processContainsMessage(processParts, search.messageId)? search.requestId : undefined, [processParts, search]);@@ -44,7 +85,6 @@ export function TurnProcess({processParts.flatMap((part) => part.kind === "activity" ? part.items : []), delegationStatuses,), [processParts, delegationStatuses]);const thinkingNow = useMemo(() => isTurnThinking(turnParts, isActive), [turnParts, isActive]);- const visibleSteps = useMemo(() => cachedVisibleProcessSteps(processParts, !showThinking, isActive), [processParts, showThinking, isActive]);// Active processes start open and untouched completed ones close by default;// an explicit user choice stays authoritative. This does not depend on the// thinking preference, and a recorded failure keeps an untouched active@@ -63,10 +103,44 @@ export function TurnProcess({const timer = window.setInterval(() => setNow(Date.now()), 1000);return () => window.clearInterval(timer);}, [isActive]);- if (visibleSteps === 0) return null;+ const scope = useMemo<DisclosureScopeValue>(+ () => ({ claim: disclosure.claim, visible: disclosure.open }),+ [disclosure.claim, disclosure.open],+ );+ // With nothing to reveal there is no disclosure - but the rows still have to+ // render. Hidden reasoning superseded by a separate answer is exactly this+ // case: the reader gets the answer, and the process does not exist.+ if (visibleSteps === 0) return <>{children}</>;const seconds = startedAt === undefined ? 0 : Math.max(0, Math.floor(((isActive ? now : (endedAt ?? startedAt)) - startedAt) / 1000),);+ const elapsed = formatToolDuration(seconds);+ // The header states the turn's outcome and nothing else: a shell command can+ // be arbitrarily long, so echoing the current one would push the counts off+ // the row. `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 label = (() => {+ if (phase.kind === "failed") {+ return hasTiming ? t("chat.processFailedFor", { time: elapsed }) : t("chat.processFailed");+ }+ if (phase.kind === "stopped") {+ return hasTiming ? t("chat.processStoppedFor", { time: elapsed }) : t("chat.processStopped");+ }+ if (phase.kind === "completed") {+ return hasTiming ? t("chat.processCompletedFor", { time: elapsed }) : t("chat.processCompleted");+ }+ // Live: only stages with their own settled wording get their own label. The+ // rest describe an instant at the start of a request, and naming them would+ // make the row flicker instead of telling the reader anything.+ const runningPhase = phase.kind === "running" ? phase.phase : undefined;+ const phaseKey = runningPhase ? LIVE_PHASE_KEYS[runningPhase] : undefined;+ return t(phaseKey ?? (thinkingNow ? "chat.thinking" : "chat.processRunning"));+ })();+ // The summary already counts every activity item it was given, run rows+ // included, so the header must not add them again.+ const toolCount = summary.tools;return (<section className={`turn-process${disclosure.open ? " open" : ""}${isActive ? " active" : ""}`}><button@@ -77,20 +151,20 @@ export function TurnProcess({aria-controls={detailsId}onClick={disclosure.toggle}>- <span className="tool-activity-icon" aria-hidden><IconSparkles size={14} /></span>+ <span className="tool-activity-icon" aria-hidden>+ {phase.kind === "failed" ? <IconCircleAlert size={14} /> : <IconSparkles size={14} />}+ </span><span className={`tool-activity-label${isActive ? " running" : ""}`}>- {t(isActive ? thinkingNow ? "chat.thinkingFor" : "chat.processingFor" : "chat.processedFor", {- time: formatToolDuration(seconds),- })}+ {label}</span>- {summary.issues > 0 ? (+ {summary.issues > 0 && phase.kind !== "failed" ? (<span className="turn-process-error"><IconCircleAlert size={14} aria-hidden />{t("chat.activityFailures", { count: summary.issues })}</span>) : null}- {summary.tools > 0 ? (- <span className="tool-activity-count">{t("chat.processTools", { count: summary.tools })}</span>+ {toolCount > 0 ? (+ <span className="tool-activity-count">{t("chat.processTools", { count: toolCount })}</span>) : null}<span className="tool-activity-caret" aria-hidden><IconChevronRight size={12} /></span></button>@@ -100,10 +174,11 @@ export function TurnProcess({className="turn-process-body"hidden={!disclosure.open}inert={!disclosure.open}+ aria-hidden={!disclosure.open}{...disclosure.bodyEvents}>- <DisclosureCollapseRail label={t("chat.collapseProcess")} onCollapse={disclosure.collapse} />- <DisclosureScope disclosure={disclosure}>{children}</DisclosureScope>+ <DisclosureCollapseRail label={t("chat.collapseTurnProcess")} onCollapse={disclosure.collapse} />+ <ScopeContext.Provider value={scope}>{children}</ScopeContext.Provider></div></section>);diff --git a/apps/desktop/src/features/chat/transcript/disclosure-scope.ts b/apps/desktop/src/features/chat/transcript/disclosure-scope.tsnew file mode 100644index 000000000..7e725c5dd--- /dev/null+++ b/apps/desktop/src/features/chat/transcript/disclosure-scope.ts@@ -0,0 +1,22 @@+import { createContext } from "react";++/**+ * The scope one disclosure level presents to the levels it reveals.+ *+ * Kept in its own module so a level that *provides* a scope (the turn's process+ * disclosure) and the module that *consumes* it (`useAutomaticDisclosure`) do+ * not import each other. `disclosure.tsx` owns the consumer side and re-exports+ * the type.+ */+export type DisclosureScopeValue = {+ /** Claim interaction for this level and, through it, for every ancestor. */+ claim: () => void;+ /** Whether this level's contents are currently shown at all. */+ visible: boolean;+};++/** The implicit root scope: nothing above the transcript owns it. */+export const ScopeContext = createContext<DisclosureScopeValue>({+ claim: () => {},+ visible: true,+});diff --git a/apps/desktop/src/features/chat/transcript/disclosure.tsx b/apps/desktop/src/features/chat/transcript/disclosure.tsxindex acb2159b2..8f30f50c0 100644--- a/apps/desktop/src/features/chat/transcript/disclosure.tsx+++ b/apps/desktop/src/features/chat/transcript/disclosure.tsx@@ -12,6 +12,7 @@ import {} from "react";import { useDisclosureAnchorNotifier } from "../../../lib/disclosure-anchor-context";import { sessionReadingState, type TranscriptDisclosureChoice } from "../../../lib/transcript-reading-position";+import { ScopeContext, type DisclosureScopeValue } from "./disclosure-scope";type Choice = TranscriptDisclosureChoice;@@ -45,10 +46,14 @@ class DisclosureChoices {}const ChoicesContext = createContext<DisclosureChoices | null>(null);-const ParentContext = createContext<{ claim: () => void; visible: boolean }>({- claim: () => {},- visible: true,-});++/*+ * A level's own visibility is a second gate beside the stored choice, so a+ * collapsed parent closes everything it reveals without erasing - or even+ * overriding - a child's explicit choice. Reopening the parent restores the+ * rows the user had opened, which is what a nested disclosure should do.+ */+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 }) {@@ -81,52 +86,58 @@ export function useAutomaticDisclosure(const choices = sharedChoices ?? localChoices;const fallbackId = useId();const key = identity ?? fallbackId;- const parent = useContext(ParentContext);const subscribe = useCallback((listener: () => void) => choices.subscribe(key, listener), [choices, key]);const snapshot = useCallback(() => choices.get(key), [choices, key]);const choice = useSyncExternalStore(subscribe, snapshot, snapshot);// A pending reveal is the derived default, so the first paint (and SSR)// already shows the row the transcript search asked to open.- const open = choice?.open ?? (+ const requestedOpen = choice?.open ?? (revealRequest !== undefined && choice?.revealRequest !== revealRequest? true: automaticOpen);+ const scope = useContext(ScopeContext);+ // A level below a collapsed parent renders nothing, whatever its own choice+ // says. The choice is left untouched so reopening the parent restores it.+ const open = requestedOpen && scope.visible;+const titleRef = useRef<HTMLButtonElement | null>(null);const bodyRef = useRef<HTMLDivElement | null>(null);const notifyAnchor = useDisclosureAnchorNotifier();const currentOpen = useRef(open);currentOpen.current = open;+ // The claim goes to the level that owns this one, not to the root: opening a+ // row inside a process disclosure has to keep that process open too.const claim = useCallback(() => {if (!choices.get(key)) choices.set(key, { open: currentOpen.current });- parent.claim();- }, [choices, key, parent.claim]);+ scope.claim();+ }, [choices, key, scope.claim]);useLayoutEffect(() => {if (revealRequest === undefined || choices.get(key)?.revealRequest === revealRequest) return;choices.set(key, { open: true, revealRequest });- parent.claim();- }, [choices, key, parent.claim, revealRequest]);+ scope.claim();+ }, [choices, key, scope.claim, revealRequest]);const previousOpen = useRef(open);useLayoutEffect(() => {// Completion must not hide keyboard focus or an active text selection.if (previousOpen.current && !open && !choice && ownsReadingPosition(bodyRef.current)) {choices.set(key, { open: true });- parent.claim();+ scope.claim();}previousOpen.current = open;- }, [choice, choices, key, open, parent.claim]);+ }, [choice, choices, key, open, scope.claim]);const setManualOpen = useCallback((next: boolean) => {- parent.claim();+ scope.claim();notifyAnchor?.(titleRef.current);if (!next && bodyRef.current?.contains(document.activeElement)) {titleRef.current?.focus({ preventScroll: true });}choices.set(key, { ...choices.get(key), open: next });- }, [choices, key, notifyAnchor, parent.claim]);+ }, [choices, key, notifyAnchor, scope.claim]);const toggle = useCallback(() => setManualOpen(!currentOpen.current), [setManualOpen]);const collapse = useCallback(() => setManualOpen(false), [setManualOpen]);@@ -137,13 +148,23 @@ export function useAutomaticDisclosure(claim,titleRef,bodyRef,- parentVisible: parent.visible,+ // Kept for callers that read the parent's visibility directly; the scope+ // itself already folded it into `open`.+ parentVisible: scope.visible,// Pointer selection and keyboard interaction establish ownership before// a streaming update can apply an automatic close.bodyEvents: { onPointerDownCapture: claim, onFocusCapture: claim },};}+/**+ * Reveal a level's contents to the disclosures nested inside it.+ *+ * The scope states both who owns this level's reveals and whether they are+ * currently shown, so a nested level needs no knowledge of its ancestors: a+ * collapsed whole-turn process closes every group under it, while each group+ * keeps the choice the user made for it.+ */export function DisclosureScope({disclosure,open = disclosure.open,@@ -153,9 +174,9 @@ export function DisclosureScope({open?: boolean;children: ReactNode;}) {- const value = useMemo(() => ({+ const value = useMemo<DisclosureScopeValue>(() => ({claim: disclosure.claim,- visible: disclosure.parentVisible && open,- }), [disclosure.claim, disclosure.parentVisible, open]);- return <ParentContext.Provider value={value}>{children}</ParentContext.Provider>;+ visible: open,+ }), [disclosure.claim, open]);+ return <ScopeContext.Provider value={value}>{children}</ScopeContext.Provider>;}diff --git a/apps/desktop/src/features/settings/SettingsPage.tsx b/apps/desktop/src/features/settings/SettingsPage.tsxindex a81190936..90c453740 100644--- a/apps/desktop/src/features/settings/SettingsPage.tsx+++ b/apps/desktop/src/features/settings/SettingsPage.tsx@@ -37,6 +37,7 @@ import { ModelConfigPage } from "../../components/settings/ModelConfigPage";import { KeyboardShortcutsSection } from "../../components/settings/KeyboardShortcutsSection";import { FontFamilyRow } from "../../components/settings/FontFamilyRow";import { ShowThinkingRow } from "../../components/settings/ShowThinkingRow";+import { KeepCommandsExpandedRow } from "../../components/settings/KeepCommandsExpandedRow";import { FontSizeRow } from "../../components/settings/FontSizeRow";import { LanguageRow } from "../../components/settings/LanguageRow";import { SettingsMenuSelect } from "../../components/settings/SettingsMenuSelect";@@ -546,6 +547,7 @@ export function SettingsPage() {<CommandShellRow settings={settings} saveSettings={saveSettings} /><LinkOpenTargetRow settings={settings} saveSettings={saveSettings} /><ShowThinkingRow settings={settings} saveSettings={saveSettings} />+ <KeepCommandsExpandedRow settings={settings} saveSettings={saveSettings} /><ContextUsageDisplayRowsettings={settings}saveSettings={saveSettings}diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex 982a10cb0..a6ed89649 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -424,6 +424,7 @@ export function normalizeSettings(settings: AppSettings): AppSettings {sidebarRunningIndicators: settings.sidebarRunningIndicators !== false,sidebarRunningBadge: settings.sidebarRunningBadge !== false,sidebarRunningRail: settings.sidebarRunningRail === true,+ keepCommandsExpanded: settings.keepCommandsExpanded !== false,defaultMode: normalizeMode((settings as { defaultMode?: unknown }).defaultMode),infiniteProviderRetry:(settings as { infiniteProviderRetry?: unknown }).infiniteProviderRetry === true,@@ -545,6 +546,7 @@ export function validateSettingsWrite(settings: AppSettings): AppSettings {"sidebarRunningRail","sidebarSessionTime","macosWindowTranslucency",+ "keepCommandsExpanded",] as const) {if (Object.prototype.hasOwnProperty.call(value, key) &&@@ -1781,7 +1783,7 @@ export const api = {},/*** A plugin offered one line for the composer, or the main process ordered- * whatever is on screen dropped (`pi.composer.suggest`, ADR 0332).+ * whatever is on screen dropped (`pi.composer.suggest`, ADR 0333).** The shell answers every offer over `pluginComposerSuggestionResult`, because* only the renderer knows whether the draft can take it. A malformed messagediff --git a/apps/desktop/src/lib/assistant-turns.ts b/apps/desktop/src/lib/assistant-turns.tsindex e7b3ae0d9..420c41d0b 100644--- a/apps/desktop/src/lib/assistant-turns.ts+++ b/apps/desktop/src/lib/assistant-turns.ts@@ -86,10 +86,11 @@ function isDelegationStartActivity(item: AssistantActivityItem): boolean {}/**- * A `Bash` call or a run alias renders as a standalone row outside any process- * or activity-group disclosure (ADR turn-process-and-thinking-display).- * Adjacent Bash rows each stay standalone, so a run item neither joins the- * preceding segment nor absorbs the next one.+ * A `Bash` call or a run alias is a run row (ADR+ * turn-process-and-thinking-display). With commands expanded it renders as its+ * own row inside the turn's process disclosure; with commands folded it stays in+ * the activity group it ran among. Adjacent calls are still built as separate+ * activity parts, so entry topology does not depend on the preference.*/export function isStandaloneRunActivity(item: AssistantActivityItem,diff --git a/apps/desktop/src/lib/command-folding.ts b/apps/desktop/src/lib/command-folding.tsnew file mode 100644index 000000000..e64c68177--- /dev/null+++ b/apps/desktop/src/lib/command-folding.ts@@ -0,0 +1,19 @@+import type { AppSettings } from "@pi-desktop/shared";++/**+ * Resolve whether shell calls stay outside the tool groups they run among.+ *+ * `keepCommandsExpanded` is the preference; an absent value means `true`, so an+ * existing install keeps the scannable command rows it has today. This is a+ * presentation preference only: it never changes what a tool received, what it+ * returned, stored history, export, or the copy payload.+ *+ * It also never decides whether a turn renders a process disclosure. Both+ * values render exactly one, and only the placement of run rows inside it+ * changes.+ */+export function resolveKeepCommandsExpanded(+ settings: Pick<AppSettings, "keepCommandsExpanded"> | null | undefined,+): boolean {+ return settings?.keepCommandsExpanded !== false;+}diff --git a/apps/desktop/src/lib/settings-search.ts b/apps/desktop/src/lib/settings-search.tsindex 2395133a0..77c6b3319 100644--- a/apps/desktop/src/lib/settings-search.ts+++ b/apps/desktop/src/lib/settings-search.ts@@ -120,6 +120,8 @@ export const SETTINGS_NAV: SettingsNavEntry[] = ["settings.smoothStreamingDesc","settings.showThinking","settings.showThinkingDesc",+ "settings.keepCommandsExpanded",+ "settings.keepCommandsExpandedDesc","settings.contextUsageDisplay","settings.contextUsageDisplayRemaining","settings.contextUsageDisplayUsed",diff --git a/apps/desktop/src/lib/turn-process.ts b/apps/desktop/src/lib/turn-process.tsindex 6dbdfb13c..1a87885ee 100644--- a/apps/desktop/src/lib/turn-process.ts+++ b/apps/desktop/src/lib/turn-process.ts@@ -1,10 +1,11 @@-import type { UiMessage } from "@pi-desktop/shared";+import type { AgentActivity, UiMessage } from "@pi-desktop/shared";import type {AssistantActivityItem,AssistantTurnEntry,AssistantTurnPart,} from "./assistant-turns";import { isStandaloneRunActivity } from "./assistant-turns";+import { isDelegationStartTool } from "./tool-display";export function isThinkingActive(message: UiMessage, active: boolean): boolean {return active && message.status === "streaming" && !message.content.trim();@@ -39,14 +40,17 @@ export function processContainsMessage(});}-/** A `Bash`/run call rendered as its own row outside any process disclosure. */+/**+ * A run call rendered as its own row beside the nested activity groups inside+ * the turn's process disclosure.+ */export type TurnProcessRunSegment = {kind: "run";key: string;item: Extract<AssistantActivityItem, { kind: "tool" }>;};-/** One chronological chunk of non-run process content between run calls. */+/** One chronological process chunk; ON mode splits it at run calls. */export type TurnProcessBodySegment = {kind: "process";key: string;@@ -55,21 +59,114 @@ export type TurnProcessBodySegment = {export type TurnProcessSegment = TurnProcessRunSegment | TurnProcessBodySegment;+/** A `Task` fan-out group is its own topology, never ordinary work. */+function isDelegationGroupPart(+ part: Extract<AssistantTurnPart, { kind: "activity" }>,+): boolean {+ return part.items.some(+ (item) => item.kind === "tool" && isDelegationStartTool(item.message.toolName),+ );+}++/**+ * Coalesce the activity chunks one folded process shows.+ *+ * Turn entries isolate every run row in its own activity part, so rendering the+ * parts as built would still put a command beside the group it ran among. Folding+ * means one group around the whole contiguous ordinary stretch: build a new part+ * with the source items in order, keeping their identity, and let progress text+ * and a `Task` fan-out stay hard boundaries. The new part ends where its last+ * source part ended; the cached parts are never mutated.+ */+function coalesceProcessActivityParts(+ parts: readonly AssistantTurnPart[],+): AssistantTurnPart[] {+ const coalesced: AssistantTurnPart[] = [];+ let pending:+ | {+ delegation: boolean;+ source: Extract<AssistantTurnPart, { kind: "activity" }>;+ items: AssistantActivityItem[];+ merged: boolean;+ endedAt?: string;+ }+ | undefined;+ const flush = () => {+ if (!pending) return;+ // A group with nothing to join keeps its cached part identity, so an+ // unchanged singleton group does not remount on every preference read.+ coalesced.push(+ pending.merged+ ? {+ kind: "activity",+ items: pending.items,+ ...(pending.endedAt === undefined ? {} : { endedAt: pending.endedAt }),+ }+ : pending.source,+ );+ pending = undefined;+ };+ for (const part of parts) {+ if (part.kind === "message") {+ flush();+ coalesced.push(part);+ continue;+ }+ const delegation = isDelegationGroupPart(part);+ if (pending && pending.delegation === delegation) {+ pending.items.push(...part.items);+ pending.merged = true;+ pending.endedAt = part.endedAt;+ continue;+ }+ flush();+ pending = {+ delegation,+ source: part,+ items: [...part.items],+ merged: false,+ endedAt: part.endedAt,+ };+ }+ flush();+ return coalesced;+}+/*** Split one turn's process into the order it renders (ADR* turn-process-and-thinking-display).*- * `Bash` and run aliases are pulled out of the process flow entirely: each is- * its own `run` segment rendered as a standalone row with no process or group- * ancestor, and adjacent calls stay separate. The remaining tools, thinking,- * hosted searches and progress text keep their original order and are grouped- * into `process` chunks between the run calls. Segment parts are the same part- * objects as the input, so downstream reveal and active-tail identity still- * hold.+ * With `keepCommandsExpanded` the `Bash` and run aliases are pulled out of the+ * process flow: each is its own `run` segment, rendered as a standalone row+ * beside the nested groups rather than inside one, and adjacent calls stay+ * separate. The remaining tools, thinking, hosted searches and progress text+ * keep their original order and are grouped into `process` chunks between the+ * run calls.+ *+ * Without it the run rows keep their place in the flow, so a command is just+ * another row of the group it ran among - the layout before commands were+ * separated at all. Because the entry builder keeps every run row in its own+ * activity part, folding coalesces contiguous ordinary parts into one rendered+ * group here, at render time. Progress messages remain paragraph boundaries and+ * a `Task`/delegation group never absorbs ordinary work around it. The+ * coalesced group is a new part whose end is the last source group's end; the+ * source parts and their items are not mutated.+ *+ * Either way the turn renders one top-level disclosure; only the placement of+ * run rows inside it changes. ON-mode segment parts are the same part objects+ * as the input, so downstream reveal and active-tail identity still hold.*/export function segmentTurnProcess(parts: readonly AssistantTurnPart[],+ keepCommandsExpanded: boolean,): TurnProcessSegment[] {+ if (!keepCommandsExpanded) {+ const first = parts[0];+ if (!first) return [];+ const key =+ first.kind === "activity" ? first.items[0].message.id : first.message.id;+ return [{ kind: "process", key, parts: coalesceProcessActivityParts(parts) }];+ }const segments: TurnProcessSegment[] = [];let pending: AssistantTurnPart[] = [];const flushProcess = () => {@@ -95,6 +192,60 @@ export function segmentTurnProcess(return segments;}+/**+ * What the turn's process header says about the turn as a whole.+ *+ * One line, and it only answers "how did this turn end up" - never what it is+ * working on, because a shell command can be arbitrarily long and would push+ * the counts off the row.+ *+ * Precedence is deliberate: failure, stop, running, completed. A recorded+ * failure outranks everything: the turn produced no answer, and a header+ * reading "Processed" over a failed run hid that. A user stop outranks a live+ * run and completion alike - the work was interrupted, not finished - and it is+ * read from the turn's own aborted rows because the turn result only+ * distinguishes completed from failed. Both assistant message rows and activity+ * item rows count; a Stop while a tool or reasoning row is in flight settles+ * there rather than in a trailing text. Delegate child rows are deliberately+ * not scanned: a failed child is not a failed or stopped turn.+ */+export type TurnProcessPhase =+ | { kind: "failed" }+ | { kind: "stopped" }+ /** Live work; `phase` names the runtime stage when one is known. */+ | { kind: "running"; phase?: AgentActivity["phase"] }+ | { kind: "completed" };++export function turnProcessPhase({+ parts,+ isActive,+ failed,+ activity,+}: {+ parts: readonly AssistantTurnPart[];+ isActive: boolean;+ /** The turn recorded a failure of its own. */+ failed: boolean;+ /** Runtime phase while the turn is live, when the runtime reports one. */+ activity?: AgentActivity;+}): TurnProcessPhase {+ if (failed) return { kind: "failed" };+ // The turn result cannot say "stopped": the runtime records only completed or+ // failed, and a user stop settles as an aborted row. Reading the aborted row+ // is therefore the most precise signal available, whether it is the turn's+ // 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) =>+ part.kind === "message"+ ? part.message.status === "aborted"+ : part.items.some((item) => item.message.status === "aborted"),+ );+ if (stopped) return { kind: "stopped" };+ if (isActive) return { kind: "running", phase: activity?.phase };+ return { kind: "completed" };+}+/*** Only a trailing assistant text can be the answer: text followed by tools is* progress. The stream carries no final-answer marker, so a live trailing text@@ -117,39 +268,6 @@ export function projectTurnProcess(entry: AssistantTurnEntry) {return { process, responses };}-/**- * Steps a process body renders under the thinking preference.- *- * `hideThinking` is `!showThinking`: completed reasoning rows and excerpts are- * hidden, while the live reasoning indicator still counts as a visible step so- * a thinking-only process keeps its indicator. The helper counts exactly the- * parts it is given; Bash and run aliases are segmented out before rendering- * and never reach a process chunk, so they are never counted here.- */-export function visibleProcessSteps(- parts: readonly AssistantTurnPart[],- hideThinking: boolean,- active: boolean,-): number {- let count = 0;- for (const part of parts) {- if (part.kind === "message") {- if (part.message.content.trim()) count += 1;- continue;- }- for (const item of part.items) {- if (- item.kind !== "thinking" ||- !hideThinking ||- isThinkingActive(item.message, active)- ) {- count += 1;- }- }- }- return count;-}-/** Use recorded message/tool timing for history; elapsed live time is UI-only. */export function turnProcessTiming(parts: readonly AssistantTurnPart[]) {const messages = parts.flatMap((part) =>diff --git a/apps/desktop/src/styles/composer.css b/apps/desktop/src/styles/composer.cssindex 569295a3a..04cd62fbd 100644--- a/apps/desktop/src/styles/composer.css+++ b/apps/desktop/src/styles/composer.css@@ -225,7 +225,7 @@}/*- * A plugin suggestion (`pi.composer.suggest`, ADR 0332) rides in the same+ * A plugin suggestion (`pi.composer.suggest`, ADR 0333) rides in the same* placeholder layer, so it can never cover a message. It reads brighter than* the shell's own placeholder because it is text a person can take with Tab,* not a hint about the box; the hint beside it stays quiet and never wraps.diff --git a/apps/desktop/src/styles/messages.css b/apps/desktop/src/styles/messages.cssindex 6e0cb0e62..7e6ff2e2a 100644--- a/apps/desktop/src/styles/messages.css+++ b/apps/desktop/src/styles/messages.css@@ -12,13 +12,12 @@content-visibility: auto;contain-intrinsic-size: auto 140px;/* Paint containment clips descendants to the padding box, which squared off- the deliberate bleed of the disclosure row chrome: the activity header- pulls its hover fill 3px past the column edge and a run row's head 4px, so- the icon can sit on the text's alignment line while the fill keeps its- padding, and the focus ring reaches 3.5px beyond its own box. 8px covers- the widest of them. .tool-activity-group clips the same chrome and carries- the same margin. */- overflow-clip-margin: 8px;+ the deliberate bleed of the disclosure row chrome: both disclosure headers+ pull their hover fill 4px past the column edge, and the two collapse-rail+ controls occupy separate 14px lanes in the gutter. 34px covers the outer+ lane. .tool-activity-group keeps its own clip for the subagent card+ chrome. */+ overflow-clip-margin: 34px;}.message-row.user {@@ -1997,8 +1996,10 @@align-items: center;gap: 5px;border-radius: var(--radius-sm);- margin: 0 -3px;- padding: 2px 5px;+ /* Same inline geometry as a tool row's header: the icon and label sit on the+ prose edge, while the hover fill bleeds 4px into the gutter. */+ margin: 0 -4px;+ padding: 2px 4px;color: var(--ds-text-secondary);font-size: var(--text-sm-plus);text-align: left;@@ -2034,17 +2035,6 @@white-space: nowrap;}-/* Live tail while running: last thought line / current tool, single line. */-.tool-activity-preview {- max-width: min(100%, var(--chat-prose-max-width, 720px));- margin: 1px 0 0 26px;- overflow: hidden;- color: var(--ds-text-muted);- font-size: var(--text-xs-plus);- text-overflow: ellipsis;- white-space: nowrap;-}-/* The caret closes the row, so a short label keeps it at the trailing edge. */.tool-activity-caret {display: inline-flex;@@ -2122,10 +2112,6 @@white-space: normal;}-.tool-activity-group.has-subagents .tool-activity-preview {- margin: -3px 38px 8px;-}-.tool-activity-group.has-subagents .tool-activity-body {margin: 0;border-left: 0;@@ -2565,6 +2551,11 @@padding: 2px 0;}+/* Leaf commands sit one step below the turn and group titles. */+.tool-row-head.is-run .tool-row-name {+ font-size: var(--text-sm);+}+.tool-row-head.is-run .tool-row-header:hover {background: transparent;}@@ -2839,6 +2830,30 @@outline-offset: -2px;}+/* These bodies carry no content indent, so each rail keeps its own gutter lane+ and stops at the header fill. The turn's control is the outer lane and the+ nested group's is the inner lane: expanding a group never puts two hit+ targets on the same pixels. Tool-row detail rails keep their tighter inset. */+.turn-process-body > .disclosure-collapse-rail {+ left: -32px;+ width: 14px;+ min-width: 14px;+}++.process-activity-body > .disclosure-collapse-rail {+ left: -18px;+ width: 14px;+ min-width: 14px;+}++/* Keep the visible bar next to the content while the hit target extends into+ the gutter. */+.turn-process-body > .disclosure-collapse-rail::before,+.process-activity-body > .disclosure-collapse-rail::before {+ right: 0;+ left: auto;+}+/** What a delegate did, one level inside its `Task` row. The tile marks the* boundary: everything inside it happened in the delegate's own context.@@ -3357,7 +3372,11 @@.turn-process-body {position: relative;- padding-left: 18px;+ /* The turn's process and the levels it reveals share one left edge: a nested+ group header or a run row starts exactly where the turn header does, so the+ transcript reads as one column instead of an indenting staircase. Levels+ stay distinguishable by type size and colour, not by indentation. */+ padding-left: 0;}.turn-process-body[hidden],@@ -3376,6 +3395,18 @@margin-block: 6px;}+/* The turn's own title is the strongest level; a nested group is smaller and+ quieter, while leaf run rows keep tool-row secondary text. Indentation is+ not carrying this hierarchy. */+.process-activity-group > .tool-activity-header {+ color: var(--ds-text-muted);+ font-size: var(--text-sm);+}++.process-activity-group > .tool-activity-header:hover {+ color: var(--ds-text-primary);+}+.process-activity-body {position: relative;min-width: 0;@@ -3383,7 +3414,9 @@.process-activity-group.grouped > .process-activity-body {margin-block: 3px 6px;- padding-inline-start: 12px;+ /* Same left edge as the turn header above it. The smaller type is what marks+ this as the nested level. */+ padding-inline-start: 0;}/* The nested process levels share the base header row: no level-specificdiff --git a/apps/desktop/test/command-folding-settings.test.mjs b/apps/desktop/test/command-folding-settings.test.mjsnew file mode 100644index 000000000..cce05f996--- /dev/null+++ b/apps/desktop/test/command-folding-settings.test.mjs@@ -0,0 +1,54 @@+import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";++register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));++const { SETTINGS_NAV, searchSettings } = await import(+ "../src/lib/settings-search.ts"+);+const { en } = await import(+ "../../../packages/i18n/src/locales/en/index.ts"+);+const { flattenCatalog } = await import(+ "../../../packages/i18n/src/locale-info.ts"+);++const copy = flattenCatalog(en);+const t = (key) => copy[key] ?? key;++test("command folding is searchable from the AI preferences beside show thinking", () => {+ const ai = SETTINGS_NAV.find((entry) => entry.id === "ai");+ assert.ok(ai, "AI settings entry is registered");+ const showThinkingAt = ai.keywordKeys.indexOf("settings.showThinking");+ assert.ok(showThinkingAt >= 0, "show thinking remains indexed");+ assert.deepEqual(+ ai.keywordKeys.slice(showThinkingAt, showThinkingAt + 4),+ [+ "settings.showThinking",+ "settings.showThinkingDesc",+ "settings.keepCommandsExpanded",+ "settings.keepCommandsExpandedDesc",+ ],+ );++ const titleHits = searchSettings("collapse commands", t, {+ developerMode: false,+ includeDevelopmentOnly: false,+ }).filter((hit) => hit.tab === "ai");+ assert.ok(+ titleHits.some((hit) => hit.rowKey === "settings.keepCommandsExpanded"),+ "the command-folding title is searchable",+ );++ const descriptionHits = searchSettings("shell calls", t, {+ developerMode: false,+ includeDevelopmentOnly: false,+ }).filter((hit) => hit.tab === "ai");+ assert.ok(+ descriptionHits.some(+ (hit) => hit.rowKey === "settings.keepCommandsExpandedDesc",+ ),+ "the command-folding description is searchable",+ );+});diff --git a/apps/desktop/test/composer-suggestion-relay.test.mjs b/apps/desktop/test/composer-suggestion-relay.test.mjsindex 820857e60..3bee91ce2 100644--- a/apps/desktop/test/composer-suggestion-relay.test.mjs+++ b/apps/desktop/test/composer-suggestion-relay.test.mjs@@ -4,7 +4,7 @@ import test from "node:test";register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));/*- * The main-process half of `pi.composer.suggest` (ADR 0332): which offers never+ * The main-process half of `pi.composer.suggest` (ADR 0333): which offers never* reach the window, which one may answer, and what happens to a suggestion when* the turn or the plugin behind it ends first.*/diff --git a/apps/desktop/test/composer-suggestion-state.test.mjs b/apps/desktop/test/composer-suggestion-state.test.mjsindex 15d98a5db..8335a3d03 100644--- a/apps/desktop/test/composer-suggestion-state.test.mjs+++ b/apps/desktop/test/composer-suggestion-state.test.mjs@@ -4,7 +4,7 @@ import test from "node:test";register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));/*- * The renderer half of `pi.composer.suggest` (ADR 0332): whether an offer can go+ * The renderer half of `pi.composer.suggest` (ADR 0333): whether an offer can go* on screen, what takes it down, and which key acts on it while the completion* list still owns Tab and the first Escape.*/diff --git a/apps/desktop/test/macos-window-translucency.test.mjs b/apps/desktop/test/macos-window-translucency.test.mjsindex 8b1eb6a51..c71aefb4a 100644--- a/apps/desktop/test/macos-window-translucency.test.mjs+++ b/apps/desktop/test/macos-window-translucency.test.mjs@@ -97,7 +97,8 @@ test("the switch is macOS-only and says when a restart is needed", async () => {test("both settings write paths reject a non-boolean translucency value", async () => {const rendererApi = await read("../src/lib/api.ts");const mainCatalog = await readMainModule("runtime/provider-catalog.ts");- assert.match(rendererApi, /"macosWindowTranslucency",\s*\] as const\) \{/);+ const booleanKeys = rendererApi.match(/for \(const key of \[([\s\S]*?)\] as const\) \{/)?.[1];+ assert.match(booleanKeys ?? "", /"macosWindowTranslucency"/);assert.match(rendererApi, /typeof value\[key\] !== "boolean"/);assert.match(mainCatalog,diff --git a/apps/desktop/test/settings-roundtrip.test.mjs b/apps/desktop/test/settings-roundtrip.test.mjsindex 3c391a2fb..b1e901f45 100644--- a/apps/desktop/test/settings-roundtrip.test.mjs+++ b/apps/desktop/test/settings-roundtrip.test.mjs@@ -1,6 +1,7 @@import assert from "node:assert/strict";import { register } from "node:module";import test from "node:test";+import { IPC } from "@pi-desktop/shared";register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));const renderer = await import("../src/lib/api.ts");const { createProviderCatalogRuntime } = await import("../electron/main/runtime/provider-catalog.ts");@@ -10,7 +11,12 @@ test("settings read-modify-write preserves disabled retry and unrelated preferenconst previousWindow = globalThis.window;globalThis.window = { piDesktop: { platform: "win32" } };try {- for (const stored of [{}, { infiniteProviderRetry: false }, { infiniteProviderRetry: true }]) {+ for (const stored of [+ {},+ { infiniteProviderRetry: false },+ { infiniteProviderRetry: true },+ { keepCommandsExpanded: false },+ ]) {const original = { defaultMode: "agent", theme: "light", ...stored };const received = structuredClone(main.normalizeSettings(original));const displayed = renderer.normalizeSettings(received);@@ -18,6 +24,11 @@ test("settings read-modify-write preserves disabled retry and unrelated preferenconst outgoing = renderer.validateSettingsWrite(edited);const persisted = main.validateSettingsWrite(structuredClone(outgoing));assert.equal(persisted.infiniteProviderRetry, stored.infiniteProviderRetry === true);+ // Absent means on; an explicit false survives both boundaries.+ assert.equal(+ persisted.keepCommandsExpanded,+ stored.keepCommandsExpanded !== false,+ );assert.equal(persisted.theme, "light");assert.deepEqual(persisted.imageGeneration, edited.imageGeneration);}@@ -34,3 +45,92 @@ test("invalid retry writes stay rejected at both boundaries", () => {assert.throws(() => main.validateSettingsWrite(settings), /infiniteProviderRetry is invalid/);}});++test("command folding defaults on and rejects non-boolean writes before IPC", () => {+ const previousWindow = globalThis.window;+ let invoked = 0;+ globalThis.window = {+ piDesktop: {+ platform: "win32",+ invoke: async () => {+ invoked += 1;+ return { ok: true, data: undefined };+ },+ },+ };+ try {+ const base = { defaultMode: "agent", theme: "light", enterToSend: true };+ assert.equal(+ renderer.normalizeSettings(base).keepCommandsExpanded,+ true,+ );+ assert.equal(+ renderer.normalizeSettings({ ...base, keepCommandsExpanded: false })+ .keepCommandsExpanded,+ false,+ );+ assert.equal(+ main.normalizeSettings({ ...base, keepCommandsExpanded: false })+ .keepCommandsExpanded,+ false,+ );+ for (const value of ["yes", 0, null, undefined, {}]) {+ assert.throws(+ () => renderer.validateSettingsWrite({ keepCommandsExpanded: value }),+ /keepCommandsExpanded is invalid/,+ );+ assert.throws(+ () => renderer.api.setSettings({ keepCommandsExpanded: value }),+ /keepCommandsExpanded is invalid/,+ );+ }+ assert.equal(invoked, 0, "invalid writes must not reach the preload bridge");+ } finally {+ if (previousWindow === undefined) delete globalThis.window;+ else globalThis.window = previousWindow;+ }+});++test("settings write round-trips command folding through the preload boundary", async () => {+ const previousWindow = globalThis.window;+ const calls = [];+ let stored = {+ defaultMode: "agent",+ theme: "light",+ enterToSend: true,+ onboardingDismissed: false,+ };+ globalThis.window = {+ piDesktop: {+ platform: "win32",+ invoke: async (channel, payload) => {+ calls.push({ channel, payload });+ if (channel === IPC.invoke.settingsGet) {+ return { ok: true, data: structuredClone(stored) };+ }+ if (channel === IPC.invoke.settingsSet) {+ stored = { ...stored, ...structuredClone(payload) };+ return { ok: true, data: undefined };+ }+ throw new Error(`Unexpected settings IPC: ${channel}`);+ },+ },+ };+ try {+ const initial = await renderer.api.getSettings();+ assert.equal(initial.keepCommandsExpanded, true);++ await renderer.api.setSettings({ ...initial, keepCommandsExpanded: false });++ const write = calls.find(({ channel }) => channel === IPC.invoke.settingsSet);+ assert.ok(write, "settings write must cross the preload boundary");+ assert.equal(write.payload.keepCommandsExpanded, false);+ assert.equal(stored.keepCommandsExpanded, false);++ const reread = await renderer.api.getSettings();+ assert.equal(reread.keepCommandsExpanded, false);+ } finally {+ if (previousWindow === undefined) delete globalThis.window;+ else globalThis.window = previousWindow;+ }+});diff --git a/apps/desktop/test/thinking-ui.test.mjs b/apps/desktop/test/thinking-ui.test.mjsindex 824438583..04dfcbfb9 100644--- a/apps/desktop/test/thinking-ui.test.mjs+++ b/apps/desktop/test/thinking-ui.test.mjs@@ -243,8 +243,7 @@ test("transcript keeps assistant thinking in a separate disclosure", () => {assert.match(transcriptSource, /tool-row thinking/);assert.match(transcriptSource, /className="tool-row-header"/);assert.match(transcriptSource, /aria-expanded=\{open\}/);- assert.match(transcriptSource, /aria-hidden=\{!open\}/);- assert.match(transcriptSource, /inert=\{!open\}/);+ assert.match(transcriptSharedSource, /\{open \? \(\s*<div className="tool-row-body"/);assert.match(transcriptSource, /IconSparkles/);assert.match(transcriptSource, /messageThinking as thinkingText/);assert.match(transcriptSource, /thinking-prose[\s\S]*?Markdown source=\{text\}/);@@ -292,7 +291,7 @@ test("tool and search rows stay collapsed while thinking keeps its leaf default"assert.match(transcriptSource, /onClick=\{toggleDisclosure\}/);assert.match(transcriptSource, /onCollapse=\{collapseDisclosure\}/);assert.match(transcriptSource, /onUserInteraction=\{claimDisclosure\}/);- assert.match(transcriptSource, /const tail = live && !open \? currentDetail : ""/);+ assert.doesNotMatch(transcriptActivityGroupSource, /const tail =|tool-activity-preview/);});test("activity headers omit the redundant status capsule", () => {diff --git a/apps/desktop/test/transcript-disclosure-reading.test.mjs b/apps/desktop/test/transcript-disclosure-reading.test.mjsindex 69edc59b4..cc62a7d8b 100644--- a/apps/desktop/test/transcript-disclosure-reading.test.mjs+++ b/apps/desktop/test/transcript-disclosure-reading.test.mjs@@ -29,7 +29,7 @@ test("automatic disclosure does not claim a reading position", () => {// the scroll anchor notifier reserved for direct user interaction.assert.match(disclosure, /if \(previousOpen\.current && !open && !choice && ownsReadingPosition/);const revealEffect = disclosure.match(- /useLayoutEffect\(\(\) => \{\s*if \(revealRequest === undefined[\s\S]*?\n \}, \[choices, key, parent\.claim, revealRequest\]\);/,+ /useLayoutEffect\(\(\) => \{\s*if \(revealRequest === undefined[\s\S]*?\n \}, \[choices, key, scope\.claim, revealRequest\]\);/,)?.[0];assert.ok(revealEffect, "the automatic reveal effect is missing");assert.doesNotMatch(revealEffect, /notifyAnchor/);diff --git a/apps/desktop/test/transcript-style.test.mjs b/apps/desktop/test/transcript-style.test.mjsindex 13a8b7d13..595503058 100644--- a/apps/desktop/test/transcript-style.test.mjs+++ b/apps/desktop/test/transcript-style.test.mjs@@ -128,6 +128,68 @@ test("tool details do not add a second visual indent", () => {assert.match(stylesSource, /\.subagent-topology-node > \.tool-row-body,[\s\S]*?margin-left:\s*38px;/);});++test("the turn process and the levels it reveals share one left edge", () => {+ // A nested group header sits on the same vertical line as the turn header that+ // reveals it. Indentation used to carry that hierarchy; it is now carried by+ // type size and colour, so a stray padding here would silently bring the+ // staircase back.+ const turnBody = stylesSource.match(/\.turn-process-body \{([^}]*)\}/)?.[1];+ assert.ok(turnBody);+ assert.match(turnBody, /padding-left:\s*0;/);+ const groupedBody = stylesSource.match(+ /\.process-activity-group\.grouped > \.process-activity-body \{([^}]*)\}/,+ )?.[1];+ assert.ok(groupedBody);+ assert.match(groupedBody, /padding-inline-start:\s*0;/);+ // Both disclosure headers use the tool-row inline geometry: content at the+ // prose edge, fill four pixels into the gutter.+ const activityHeader = stylesSource.match(/\n\.tool-activity-header \{([^}]*)\}/)?.[1];+ assert.ok(activityHeader);+ assert.match(activityHeader, /margin:\s*0 -4px;/);+ assert.match(activityHeader, /padding:\s*2px 4px;/);+});++test("nested process levels keep a subtle type and colour hierarchy", () => {+ // The turn title stays at the base size; the nested group is smaller and+ // quieter, and a run row uses the leaf size while keeping readable colour.+ const nested = stylesSource.match(+ /\.process-activity-group > \.tool-activity-header \{([^}]*)\}/,+ )?.[1];+ assert.ok(nested);+ assert.match(nested, /font-size:\s*var\(--text-sm\);/);+ assert.match(nested, /color:\s*var\(--ds-text-muted\);/);+ const runName = stylesSource.match(+ /\.tool-row-head\.is-run \.tool-row-name \{([^}]*)\}/,+ )?.[1];+ assert.ok(runName);+ assert.match(runName, /font-size:\s*var\(--text-sm\);/);+});++test("collapse rails keep separate zero-padding gutter lanes", () => {+ const turnRail = stylesSource.match(+ /\.turn-process-body > \.disclosure-collapse-rail \{([^}]*)\}/,+ )?.[1];+ assert.ok(turnRail);+ assert.match(turnRail, /left:\s*-32px;/);+ assert.match(turnRail, /width:\s*14px;/);+ const groupRail = stylesSource.match(+ /\.process-activity-body > \.disclosure-collapse-rail \{([^}]*)\}/,+ )?.[1];+ assert.ok(groupRail);+ assert.match(groupRail, /left:\s*-18px;/);+ assert.match(groupRail, /width:\s*14px;/);+ const messageRow = stylesSource.match(/\.message-row \{([^}]*)\}/)?.[1];+ assert.ok(messageRow);+ assert.match(messageRow, /overflow-clip-margin:\s*34px;/);+});++test("the header never echoes the item it is working on", () => {+ // Long shell commands and search queries pushed the counts off the row when the+ // header previewed them, so the live tail preview is gone entirely.+ assert.doesNotMatch(stylesSource, /\.tool-activity-preview/);+});+/** The width regression this guards: a content-sized `inline-flex` disclosure* header stopped at its own label, so a tool call never used the conversationdiff --git a/apps/desktop/test/transcript-summary.test.mjs b/apps/desktop/test/transcript-summary.test.mjsindex 50322ca52..4062790ae 100644--- a/apps/desktop/test/transcript-summary.test.mjs+++ b/apps/desktop/test/transcript-summary.test.mjs@@ -8,7 +8,7 @@ const {assistantTurnResponseOutputIsEstimated, assistantTurnTools,} = await import("../src/lib/assistant-turns.ts");const { getAssistantTurnSummary, getAssistantTurnContent, messageContentFacts, reuseReferences } = await import("../src/lib/transcript-summary.ts");-const { projectTurnProcess, visibleProcessSteps } = await import("../src/lib/turn-process.ts");+const { projectTurnProcess } = await import("../src/lib/turn-process.ts");const { activitySummary, visibleActivityItems } = await import("../src/lib/activity-summary.ts");const { cachedActivitySummary, cachedVisibleActivityItems, cachedVisibleProcessSteps, activityTimingInputs } = await import("../src/lib/transcript-activity-summary.ts");const { collectDelegationStatuses, collectDelegationTimings, delegationTimingBounds } = await import("../src/lib/subagent-topology.ts");@@ -113,7 +113,10 @@ test("activity summary and compact visibility preserve error, search and thinkinfor (const compact of [false, true]) for (const active of [false, true]) {assert.deepEqual(cachedVisibleActivityItems(subset, compact, active), visibleActivityItems(subset, compact, active));const parts = [{ kind: "activity", items: subset }, { kind: "message", message: message("progress", "progress") }];- assert.equal(cachedVisibleProcessSteps(parts, compact, active), visibleProcessSteps(parts, compact, active));+ assert.equal(+ cachedVisibleProcessSteps(parts, compact, active),+ 1 + cachedVisibleActivityItems(subset, compact, active).length,+ );}}});diff --git a/apps/desktop/test/turn-process.test.mjs b/apps/desktop/test/turn-process.test.mjsindex 1a3bb25b1..c2fb32b68 100644--- a/apps/desktop/test/turn-process.test.mjs+++ b/apps/desktop/test/turn-process.test.mjs@@ -8,9 +8,12 @@ const { buildTranscriptEntries, isStandaloneRunActivity } = await import(const {projectTurnProcess,segmentTurnProcess,- visibleProcessSteps,turnProcessTiming,+ turnProcessPhase,} = await import("../src/lib/turn-process.ts");+const { cachedActivitySummary, cachedVisibleProcessSteps } = await import(+ "../src/lib/transcript-activity-summary.ts"+);const message = (id, role, content, extra = {}) => ({id,@@ -40,8 +43,8 @@ test("one turn groups thinking, tools and progress while retaining only the traiprojected.responses.map((part) => part.message.id),["final"],);- assert.equal(visibleProcessSteps(projected.process, false, false), 5);- assert.equal(visibleProcessSteps(projected.process, true, false), 4);+ assert.equal(cachedVisibleProcessSteps(projected.process, false, false), 5);+ assert.equal(cachedVisibleProcessSteps(projected.process, true, false), 4);});test("streamed text stays readable until later work establishes it as progress", () => {@@ -83,11 +86,11 @@ test("hidden thinking disappears after reasoning ends without removing stored dastatus: "streaming",});const entry = turn([thinking]);- assert.equal(visibleProcessSteps(entry.parts, true, true), 1);- assert.equal(visibleProcessSteps(entry.parts, true, false), 0);+ assert.equal(cachedVisibleProcessSteps(entry.parts, true, true), 1);+ assert.equal(cachedVisibleProcessSteps(entry.parts, true, false), 0);const withAnswer = turn([{ ...thinking, content: "Answer" }]);assert.equal(- visibleProcessSteps(projectTurnProcess(withAnswer).process, true, true),+ cachedVisibleProcessSteps(projectTurnProcess(withAnswer).process, true, true),0,);assert.equal(thinking.thinking, "Private reasoning");@@ -151,7 +154,7 @@ test("process segments pull every Bash row out and keep chronological chunks", (tool("bash", "Bash", { toolArgs: { command: "ls" } }),tool("edit", "Edit", { toolResult: "c" }),]);- const segments = segmentTurnProcess(projectTurnProcess(entry).process);+ const segments = segmentTurnProcess(projectTurnProcess(entry).process, true);assert.deepEqual(segments.map((segment) => segment.kind),["process", "run", "process"],@@ -174,7 +177,7 @@ test("a Bash-only turn has no process segment at all", () => {tool("bash1", "Bash", { toolArgs: { command: "a" } }),tool("bash2", "Bash", { toolArgs: { command: "b" } }),]);- const segments = segmentTurnProcess(projectTurnProcess(entry).process);+ const segments = segmentTurnProcess(projectTurnProcess(entry).process, true);assert.deepEqual(segments.map((segment) => segment.kind),["run", "run"],@@ -187,7 +190,7 @@ test("a turn without Bash keeps one process segment", () => {tool("read", "Read", { toolResult: "a" }),tool("grep", "Grep", { toolResult: "b" }),]);- const segments = segmentTurnProcess(projectTurnProcess(entry).process);+ const segments = segmentTurnProcess(projectTurnProcess(entry).process, true);assert.deepEqual(segments.map((segment) => segment.kind),["process"],@@ -230,6 +233,331 @@ test("user boundaries retain independent processes and delegation details stay aassert.equal(projectTurnProcess(entries[1]).process.length, 0);});+test("a turn's process is one disclosure that owns every run row", () => {+ // The transcript renders exactly one process disclosure per assistant turn and+ // puts the run rows inside it, so a turn collapses in one gesture instead of+ // leaving a column of sibling disclosures above the answer.+ const entry = turn([+ message("user", "user", "Run"),+ tool("read1", "Read", { toolResult: "a" }),+ tool("bash1", "Bash", { toolArgs: { command: "a" } }),+ tool("grep1", "Grep", { toolResult: "b" }),+ tool("bash2", "Bash", { toolArgs: { command: "b" } }),+ message("final", "assistant", "Done"),+ ]);+ const process = projectTurnProcess(entry).process;+ // Every part of the process belongs to that one disclosure, and the answer+ // stays outside it.+ assert.ok(process.every((part) => entry.parts.includes(part)));+ assert.equal(projectTurnProcess(entry).responses.length, 1);+});++test("folding commands coalesces mixed work across run rows without mutating entry parts", () => {+ // The preference only decides where run rows sit. Both values keep exactly one+ // segment, so the turn still renders one disclosure; off joins the ordinary+ // activity chunks around a run row into one rendered group.+ const entry = turn([+ message("user", "user", "Run"),+ message("intro", "assistant", "Inspecting"),+ tool("read", "Read", { toolResult: "a" }),+ tool("grep", "Grep", { toolResult: "b" }),+ tool("bash", "Bash", { toolArgs: { command: "pnpm test" } }),+ tool("edit", "Edit", { toolResult: "c" }),+ tool("write", "Write", { toolResult: "d" }),+ message("progress", "assistant", "Still working", {+ createdAt: "2026-09-17T00:00:05.000Z",+ }),+ tool("read2", "Read", { toolResult: "e" }),+ message("final", "assistant", "Done", {+ createdAt: "2026-09-17T00:00:06.000Z",+ }),+ ]);+ const process = projectTurnProcess(entry).process;+ const sourceActivities = process.filter((part) => part.kind === "activity");+ const sourceItems = sourceActivities.flatMap((part) => part.items);+ const sourceEnds = sourceActivities.map((part) => part.endedAt);+ // Freeze the cached projection so an in-place merge throws instead of quietly+ // rewriting the entry.+ for (const part of process) {+ if (part.kind !== "activity") continue;+ Object.freeze(part.items);+ Object.freeze(part);+ }+ Object.freeze(process);+ const [segment] = segmentTurnProcess(process, false);+ assert.equal(segment.kind, "process");+ // Progress text stays a paragraph boundary, so the run joins the group before+ // it rather than the one after it.+ assert.deepEqual(+ segment.parts.map((part) => part.kind),+ ["message", "activity", "message", "activity"],+ );+ const merged = segment.parts[1];+ assert.notEqual(merged, process[1]);+ assert.deepEqual(+ merged.items.map((item) => item.message.id),+ ["read", "grep", "bash", "edit", "write"],+ );+ // The coalesced group keeps every source item identity.+ assert.ok(merged.items.every((item, index) => item === sourceItems[index]));+ // Its end is the last source group's end, not the first one's, and the source+ // parts keep the ends the entry builder gave them.+ assert.equal(merged.endedAt, "2026-09-17T00:00:05.000Z");+ assert.deepEqual(sourceActivities.map((part) => part.endedAt), sourceEnds);+ // A group with nothing to join keeps its cached source part identity.+ assert.equal(segment.parts[0], process[0]);+ assert.equal(segment.parts[3], process[5]);+ assert.deepEqual(+ segment.parts[3].items.map((item) => item.message.id),+ ["read2"],+ );+ // ON is unchanged: the original chunks are still separate and the run row is+ // still a standalone segment with its original item identity.+ const on = segmentTurnProcess(process, true);+ assert.deepEqual(on.map((part) => part.kind), ["process", "run", "process"]);+ assert.equal(on[0].parts[0], process[0]);+ assert.equal(on[0].parts[1], process[1]);+ assert.equal(on[1].item, sourceActivities[1].items[0]);+ const again = segmentTurnProcess(process, true);+ assert.deepEqual(again.map((part) => part.kind), on.map((part) => part.kind));+ assert.equal(again[0].parts[0], process[0]);+});++test("folding commands keeps Task topology and progress text as group boundaries", () => {+ const entry = turn([+ message("user", "user", "Run"),+ tool("read", "Read", { toolResult: "a" }),+ tool("bash1", "Bash", { toolArgs: { command: "a" } }),+ tool("task", "Task", { toolCallId: "call", toolResult: "started" }),+ message("nested", "assistant", "Delegate answer", {+ parentToolCallId: "call",+ }),+ tool("bash2", "Bash", { toolArgs: { command: "b" } }),+ tool("edit", "Edit", { toolResult: "c" }),+ message("progress", "assistant", "Progress"),+ tool("write", "Write", { toolResult: "d" }),+ ]);+ const [segment] = segmentTurnProcess(+ projectTurnProcess(entry).process,+ false,+ );+ const activityIds = segment.parts.flatMap((part) =>+ part.kind === "activity"+ ? [part.items.map((item) => item.message.id)]+ : [],+ );+ // Ordinary work across the first run coalesces, but no ordinary row joins a+ // Task group on either side. The progress paragraph then starts a new group.+ assert.deepEqual(activityIds, [+ ["read", "bash1"],+ ["task"],+ ["bash2", "edit"],+ ["write"],+ ]);+ const task = segment.parts[1];+ assert.equal(task.kind, "activity");+ assert.equal(task.items[0].delegate.items[0].message.id, "nested");+});++test("a Bash-only turn keeps one segment whether commands are expanded or not", () => {+ const entry = turn([+ message("user", "user", "Run"),+ tool("bash1", "Bash", { toolArgs: { command: "a" } }),+ tool("bash2", "Bash", { toolArgs: { command: "b" } }),+ ]);+ const process = projectTurnProcess(entry).process;+ assert.deepEqual(segmentTurnProcess(process, true).map((s) => s.kind), ["run", "run"]);+ assert.deepEqual(segmentTurnProcess(process, false).map((s) => s.kind), ["process"]);+});++test("an empty process segments to nothing in either mode", () => {+ assert.deepEqual(segmentTurnProcess([], false), []);+ assert.deepEqual(segmentTurnProcess([], true), []);+});++test("the turn header reports failure, stop, live and completion in that order", () => {+ const abortedMessage = {+ kind: "message",+ message: message("a", "assistant", "partial", { status: "aborted" }),+ };+ const abortedBash = {+ kind: "activity",+ items: [{+ kind: "tool",+ message: message("bash", "tool", "", {+ toolName: "Bash",+ status: "aborted",+ }),+ }],+ };+ const abortedThinking = {+ kind: "activity",+ items: [{+ kind: "thinking",+ message: message("think", "assistant", "", {+ thinking: "reasoning",+ status: "aborted",+ }),+ }],+ };+ for (const aborted of [abortedMessage, abortedBash, abortedThinking]) {+ // A recorded failure outranks a stop: the turn still ended without an answer.+ assert.deepEqual(+ turnProcessPhase({ parts: [aborted], isActive: false, failed: true }),+ { kind: "failed" },+ );+ assert.deepEqual(+ turnProcessPhase({ parts: [aborted], isActive: false, failed: false }),+ { kind: "stopped" },+ );+ // A stop also outranks a live runtime phase: the work was interrupted, not+ // still running.+ assert.deepEqual(+ turnProcessPhase({+ parts: [aborted],+ isActive: true,+ failed: false,+ activity: { phase: "compacting", since: 0 },+ }),+ { kind: "stopped" },+ );+ }+ assert.deepEqual(+ turnProcessPhase({+ parts: [{ kind: "message", message: message("b", "assistant", "done", { status: "complete" }) }],+ isActive: false,+ failed: false,+ }),+ { kind: "completed" },+ );+ // Running carries the runtime stage when the turn is live and not stopped.+ assert.deepEqual(+ turnProcessPhase({+ parts: [],+ isActive: true,+ failed: false,+ activity: { phase: "compacting", since: 0 },+ }),+ { kind: "running", phase: "compacting" },+ );+});++test("a failed child never turns a completed turn into failed or stopped", () => {+ const task = {+ kind: "activity",+ items: [{+ kind: "tool",+ message: message("task", "tool", "", {+ toolName: "Task",+ toolCallId: "call",+ status: "complete",+ }),+ delegate: {+ items: [{+ kind: "answer",+ message: message("child", "assistant", "", {+ parentToolCallId: "call",+ status: "aborted",+ error: { code: "TURN_ABORTED", message: "stopped" },+ }),+ }],+ },+ }],+ };+ assert.deepEqual(+ turnProcessPhase({ parts: [task], isActive: false, failed: false }),+ { kind: "completed" },+ );+ // A failed turn is still failed, independent of the child.+ assert.deepEqual(+ turnProcessPhase({ parts: [task], isActive: false, failed: true }),+ { kind: "failed" },+ );+ // The turn's own Task row being aborted is its own stop signal.+ const ownAborted = {+ ...task,+ items: [{ ...task.items[0], message: { ...task.items[0].message, status: "aborted" } }],+ };+ assert.deepEqual(+ turnProcessPhase({ parts: [ownAborted], isActive: false, failed: false }),+ { kind: "stopped" },+ );+});++test("the header count comes from the production activity summary", () => {+ const entry = turn([+ message("user", "user", "Run"),+ tool("read", "Read", { toolResult: "a" }),+ tool("bash1", "Bash", { toolArgs: { command: "a" } }),+ tool("bash2", "Bash", { toolArgs: { command: "b" } }),+ tool("grep", "Grep", { toolResult: "b" }),+ ]);+ const process = projectTurnProcess(entry).process;+ const items = process.flatMap((part) =>+ part.kind === "activity" ? part.items : [],+ );+ const summary = cachedActivitySummary(items);+ assert.equal(summary.tools, 4);+ assert.equal(summary.count, 4);+ assert.equal(summary.issues, 0);+ assert.equal(summary.label, "chat.activityTools");+ const bashOnly = turn([+ message("user", "user", "Run"),+ tool("bash1", "Bash", { toolArgs: { command: "a" } }),+ tool("bash2", "Bash", { toolArgs: { command: "b" } }),+ ]);+ const bashItems = projectTurnProcess(bashOnly).process.flatMap((part) =>+ part.kind === "activity" ? part.items : [],+ );+ assert.equal(cachedActivitySummary(bashItems).tools, 2);+ assert.equal(cachedActivitySummary(bashItems).label, "chat.activityCommands");+});++test("the shared process-step helper counts message rows and hides content-backed thinking", () => {+ const progress = {+ kind: "message",+ message: message("progress", "assistant", "Inspecting"),+ };+ // A message-only process is still visible: the disclosure needs a non-zero+ // step count even when no activity item exists.+ assert.equal(cachedVisibleProcessSteps([progress], true, false), 1);+ assert.equal(cachedVisibleProcessSteps([progress], true, true), 1);+ // A streaming assistant row with content counts its content only. The+ // reasoning beside it is hidden by the preference, so it adds no step.+ const streamingContentAndThinking = {+ kind: "message",+ message: message("answer", "assistant", "Visible answer", {+ thinking: "Reasoning with content",+ status: "streaming",+ }),+ };+ assert.equal(+ cachedVisibleProcessSteps([streamingContentAndThinking], true, true),+ 1,+ );+ // A live reasoning-only row keeps its indicator; completed reasoning does not.+ const thinkingItem = {+ kind: "thinking",+ message: message("think", "assistant", "", {+ thinking: "Reasoning",+ status: "streaming",+ }),+ };+ assert.equal(+ cachedVisibleProcessSteps([{ kind: "activity", items: [thinkingItem] }], true, true),+ 1,+ );+ assert.equal(+ cachedVisibleProcessSteps(+ [{ kind: "activity", items: [{ ...thinkingItem, message: { ...thinkingItem.message, status: "complete" } }] }],+ true,+ false,+ ),+ 0,+ );+});++test("settings writes validate the thinking preference without changing other preferences", async () => {const { validateSettingsWrite } = await import("../src/lib/api.ts");const settings = {diff --git a/crates/host-core/src/config_sync/domains.rs b/crates/host-core/src/config_sync/domains.rsindex 2336e23d2..076441bee 100644--- a/crates/host-core/src/config_sync/domains.rs+++ b/crates/host-core/src/config_sync/domains.rs@@ -35,6 +35,7 @@ pub(crate) const PORTABLE_APPLICATION_FIELDS: &[&str] = &["fontScale","showThinking","thinkingDisplayMode",+ "keepCommandsExpanded","enterToSend","largePasteThreshold","defaultProviderId",@@ -101,6 +102,7 @@ pub const DOMAIN_ADAPTERS: &[DomainAdapterSpec] = &["showThinking","thinkingDisplayMode","enterToSend",+ "keepCommandsExpanded","keybindings","display bindings","provider/model bindings",@@ -626,15 +628,20 @@ mod tests {fn adapter_registry_covers_every_portable_domain() {assert_eq!(DOMAIN_ADAPTERS.len(), ALL_DOMAINS.len());assert!(!PORTABLE_APPLICATION_FIELDS.contains(&"defaultPermissionMode"));- // The explicit reasoning-display boolean and its legacy fallback are- // both portable, and both are advertised by the application adapter.+ // The explicit reasoning-display boolean, its legacy fallback, and the+ // command-folding preference are portable, and each is advertised by the+ // application adapter.assert!(PORTABLE_APPLICATION_FIELDS.contains(&"showThinking"));assert!(PORTABLE_APPLICATION_FIELDS.contains(&"thinkingDisplayMode"));+ assert!(PORTABLE_APPLICATION_FIELDS.contains(&"keepCommandsExpanded"));let application = adapter_for(DOMAIN_APPLICATION).expect("application adapter");assert!(application.exportable_fields.contains(&"showThinking"));assert!(application.exportable_fields.contains(&"thinkingDisplayMode"));+ assert!(application+ .exportable_fields+ .contains(&"keepCommandsExpanded"));for domain in ALL_DOMAINS {let adapter = adapter_for(domain).expect("portable domain adapter");assert_eq!(adapter.schema_version, 1);diff --git a/crates/host-core/src/config_sync/engine_s3_tests.rs b/crates/host-core/src/config_sync/engine_s3_tests.rsindex a9882ad52..b5ad1b539 100644--- a/crates/host-core/src/config_sync/engine_s3_tests.rs+++ b/crates/host-core/src/config_sync/engine_s3_tests.rs@@ -120,15 +120,17 @@ async fn application_show_thinking_roundtrips_and_keeps_local_only_settings() ->let directory_b = tempfile::tempdir()?;let device_a = configure_test_device(directory_a.path(), &fixture.endpoint).await?;let device_b = configure_test_device(directory_b.path(), &fixture.endpoint).await?;- // The source device carries the explicit reasoning-display boolean (a- // false value must stay false), the legacy display mode, and a device-local- // permission mode that must never travel through a revision.+ // The source device carries the explicit reasoning-display boolean and the+ // command-folding preference (false values must stay false), the legacy+ // display mode, and a device-local permission mode that must never travel+ // through a revision.device_a.lock().await.db.set_setting("app",&json!({"theme": "light","showThinking": false,"thinkingDisplayMode": "detailed",+ "keepCommandsExpanded": false,"defaultPermissionMode": "accept-edits",}),)?;@@ -142,6 +144,7 @@ async fn application_show_thinking_roundtrips_and_keeps_local_only_settings() ->assert_eq!(settings["theme"], "light");// A false boolean survives capture and apply instead of reading as absent.assert_eq!(settings["showThinking"], false);+ assert_eq!(settings["keepCommandsExpanded"], false);// The legacy field is still exported so older readers keep working.assert_eq!(settings["thinkingDisplayMode"], "detailed");// Local-only settings do not travel: the source value never appears.@@ -154,6 +157,7 @@ async fn application_show_thinking_roundtrips_and_keeps_local_only_settings() ->"theme": "light","showThinking": false,"thinkingDisplayMode": "detailed",+ "keepCommandsExpanded": false,"defaultPermissionMode": "ask",}),)?;@@ -164,6 +168,7 @@ async fn application_show_thinking_roundtrips_and_keeps_local_only_settings() ->"theme": "light","showThinking": true,"thinkingDisplayMode": "detailed",+ "keepCommandsExpanded": true,"defaultPermissionMode": "accept-edits",}),)?;@@ -173,6 +178,7 @@ async fn application_show_thinking_roundtrips_and_keeps_local_only_settings() ->let settings = app_settings(&state)?;assert_eq!(settings["showThinking"], true);assert_eq!(settings["thinkingDisplayMode"], "detailed");+ assert_eq!(settings["keepCommandsExpanded"], true);assert_eq!(settings["defaultPermissionMode"], "ask");Ok(())}diff --git a/docs/adr/0332-plugin-composer-suggestion.md b/docs/adr/0333-plugin-composer-suggestion.mdsimilarity index 99%rename from docs/adr/0332-plugin-composer-suggestion.mdrename to docs/adr/0333-plugin-composer-suggestion.mdindex 676cab0c9..872eef5e4 100644--- a/docs/adr/0332-plugin-composer-suggestion.md+++ b/docs/adr/0333-plugin-composer-suggestion.md@@ -1,4 +1,4 @@-# ADR 0332: A plugin-owned suggestion in the Composer placeholder+# ADR 0333: A plugin-owned suggestion in the Composer placeholder- Status: Accepted- Date: 2026-10-24diff --git a/docs/adr/README.md b/docs/adr/README.mdindex bb90e9f67..eba1586a0 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -378,7 +378,7 @@ Each ADR includes:| 0329 | [Isolate parallel sessions of one project in git worktrees](0329-session-worktree-isolation.md) | Accepted (Windows E2E pending) || 0330 | [Open scoped HTML files in the work-panel Browser from plugins](0330-open-html-files-in-work-panel-browser-from-plugins.md) | Accepted || 0331 | [Plugin session follow and host-owned work-panel reveal](0331-plugin-session-follow-and-work-panel-reveal.md) | Accepted |-| 0332 | [A plugin-owned suggestion in the Composer placeholder](0332-plugin-composer-suggestion.md) | Accepted |+| 0333 | [A plugin-owned suggestion in the Composer placeholder](0333-plugin-composer-suggestion.md) | Accepted || plugin-fetch-redirect-policy | [Host-enforced plugin fetch redirect policy](plugin-fetch-redirect-policy.md) | Accepted (implementation candidate for #1475) || local-agent-remote-workspace-tools | [Local Agent and model requests for remote workspaces](local-agent-remote-workspace-tools.md) | Accepted for implementation |diff --git a/docs/adr/turn-process-and-thinking-display.md b/docs/adr/turn-process-and-thinking-display.mdindex ce0c90bef..09613bb79 100644--- a/docs/adr/turn-process-and-thinking-display.md+++ b/docs/adr/turn-process-and-thinking-display.md@@ -2,7 +2,7 @@- Status: Accepted- Date: 2026-09-17-- Amended: 2026-10-16+- Amended: 2026-10-21- Issues: #510, #461- Amends: D071, [ADR 0242](0242-delta-only-streaming-updates.md)@@ -17,36 +17,59 @@ readers also need a thinking indicator without rapidly changing reasoning text.## DecisionOne unified turn-process presentation applies to every loaded assistant-turn-entry: it projects the entry into chronological collapsible process segments plus-its trailing answer. Thinking, tools and intermediate assistant text keep their-original order across those segments. A trailing assistant text stays visible+entry: it projects the entry into one collapsible process disclosure plus its+trailing answer. Thinking, tools, intermediate assistant text and the turn's+`Bash` run rows keep their original order inside that disclosure. A trailing+assistant text stays visiblewhile streaming; if later tool or thinking activity follows, that text moves intothe process without changing the stored message. There is no semanticfinal-answer marker in `UiMessage`, so the renderer does not guess intent fromwording. User/system messages and compaction dividers retain their existing turnboundaries.-The process is segmented rather than one flat container. Non-Bash activity forms-ordinary activity groups: one contiguous tool/search/thinking segment between-progress paragraphs or Bash rows, appearing only when at least two items are-visible under the current thinking preference. A singleton uses its item-disclosure directly; hidden thinking does not create a redundant wrapper.-Existing Task topology remains its segment's container and is not duplicated-inside an ordinary activity group.--Bash and run aliases are excluded from every process disclosure — neither a-turn-level process disclosure nor an ordinary activity group — and render as-standalone rows that stay visible even when every group is collapsed. Adjacent-Bash rows each remain standalone, and a Bash row's detail stays closed until the-user opens it. Other operations between progress paragraphs still form-chronological collapsible activity groups.--Group folding defaults are unified and do not depend on the thinking preference.-The ordinary activity group that owns the active execution segment starts open,-then closes on completion only while untouched. Other completed groups start-closed. An untouched active group containing any recorded failed or denied tool-stays open through later recovery and closes on turn completion if still-untouched. Bash rows remain visible regardless of any group's collapsed state.+One turn renders exactly one process disclosure. Every row the turn produced+before its answer lives inside it — the activity groups and the `Bash` run rows+alike — so a long turn collapses in one gesture instead of leaving a column of+sibling disclosures above the answer. The answer itself stays outside it.++Inside that disclosure, non-Bash activity forms ordinary activity groups: one+contiguous tool/search/thinking segment between progress paragraphs or run rows,+appearing only when at least two items are visible under the current thinking+preference. A singleton uses its item disclosure directly; hidden thinking does+not create a redundant wrapper. Existing Task topology remains its segment's+container and is not duplicated inside an ordinary activity group.++Whether a run row sits *inside* its group or *beside* it is the+`keepCommandsExpanded` preference, which defaults to on. When on, `Bash` and run+aliases are lifted out of the groups they ran among: each becomes its own row at+the disclosure's top level, adjacent calls stay separate, and the row's detail+stays closed until the user opens it. When off, a run row keeps its place in the+flow, so a command reads as another line of the group around it — the layout+before commands were separated. The preference never changes how many+disclosures a turn renders: both values render exactly one.++Group folding defaults are unified and do not depend on either preference. The+ordinary activity group that owns the active execution segment starts open, then+closes on completion only while untouched. Other completed groups start closed.+An untouched active group containing any recorded failed or denied tool stays+open through later recovery and closes on turn completion if still untouched.++The turn's disclosure header states the turn's outcome and never echoes the item+it is working on, because a shell command or search query can be arbitrarily+long. It reads `failed`, `stopped`, `running`, or finished, in that precedence:+a recorded failure outranks a stop, because the turn produced no answer and a+normal-looking header hid that. A stop is read from an aborted message, the only+signal the runtime records — the turn result distinguishes completed from failed+only. Aborted activity rows also record a stop while a tool or reasoning step is+in flight; delegated child rows do not determine the parent turn's outcome.+While running, stages a reader can sit in front of (compaction, recovery)+name themselves; a live reasoning step reads `Thinking`, and momentary stages+read as plain running. Durations are dropped when the transcript recorded no+timing rather than shown as zero, and issue counts sit beside the label.++The disclosure and the levels it reveals share one left edge. Hierarchy is+carried by type size and colour, not by indentation, so a nested group header and+a run row start exactly where the turn header does.The thinking preference is a boolean `showThinking`. When it is false, the livethinking indicator stays visible, while completed thinking rows and excerpts are@@ -71,7 +94,7 @@ group, and row remounts while the owning retained session pane remains alive.Pane eviction, session deletion, or renderer restart releases this presentationmemory; it is not stored in messages or host settings.-Search/navigation reveals the ancestor path its target needs: the process segment+Search/navigation reveals the ancestor path its target needs: the turn processand the activity group that own the named message. Item-level targeting is notpart of this change, so each row's own details stay behind its own disclosure.Replaying the same request does not repeatedly override a later manual close.@@ -87,24 +110,31 @@ reasoning while `detailed`, an unknown value, or an absent field shows it. Thelegacy field is retained for persisted-settings compatibility and is no longerexposed in the UI. The preference changes presentation only; it does not alterprovider thinking levels, runtime/model context, stored reasoning, export,-permissions, execution, or copy payloads, and it does not control process-segment+permissions, execution, or copy payloads, and it does not control turn-processor activity-group folding. Process headers use recorded timing, direct tool/searchcounts, running state, and issue counts; they do not double-count delegated childwork or treat a failed child as a failed assistant turn.## Consequences-- Chronological collapsible process segments keep the final answer and actionable- interruptions reachable, and Bash/run rows stay visible even when every group is- collapsed.+- One disclosure per turn keeps the final answer and actionable interruptions+ reachable, and makes a long turn collapsible in a single gesture.- Group folding defaults are unified: active work stays visible, untouchedcompleted groups fold by default, and explicit disclosure choices are preserved- regardless of the thinking preference.+ regardless of the thinking preference. Closing the turn's disclosure closes the+ groups under it, and reopening restores the groups the user had opened.- When `showThinking` is false, the live indicator stays visible while completedreasoning rows and excerpts are hidden. The stored reasoning is retained andreappears when the preference is turned back on.-- Bash and run aliases stay standalone rows outside every process disclosure, so- shell-heavy turns remain scannable without folding adjacent commands together.+- With `keepCommandsExpanded` on (the default), run aliases render as their own+ rows so shell-heavy turns stay scannable; turning it off restores the older+ layout where a command reads as another line of its group. Neither value+ changes the number of disclosures, and because the preference is read while+ rendering rather than while building entries, toggling it repaints the+ transcript immediately instead of waiting for new messages.+- The header answers "how did this turn end up" in one short line. Echoing the+ current command was removed: it pushed the counts off the row and duplicated+ what opening the item already shows.- Disclosure memory is pane-owned presentation state with stable turn, group,and item identities; it is neither a persisted transcript contract nor acentral workflow-store concern.@@ -126,3 +156,9 @@ covers the `showThinking`/legacy `thinkingDisplayMode` resolver precedence, andthe i18n catalog tests cover the new `settings.showThinking` copy. The UI,resolver, and E2E scenarios are validated on the integration candidate; seeE2E-CHAT-turn-process-and-thinking-display for the synchronized scenario text.+For the 2026-10-21 amendment, `apps/desktop/test/turn-process.test.mjs` covers+one-disclosure segmentation, command-folding on and off, and header phase+precedence; `apps/desktop/test/transcript-style.test.mjs` covers the shared left+edge and the removed live item echo. The interactive transcript probes cover the+rendered disclosure count, command placement, and header labels. See+E2E-CHAT-turn-process-and-thinking-display for the synchronized scenario text.diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 6d3f413bd..66d44cfb4 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -415,8 +415,12 @@ reasoning visibility. It is a portable application preference and synchronizesacross devices like the legacy field. Missing values fall back to the legacy`thinkingDisplayMode` field (`compact` hides, `detailed`/unknown/absent shows),which is retained only for persisted-settings compatibility and as that-fallback. These additive display preferences neither rewrite stored reasoning-nor change the database schema.+fallback. The app settings JSON optionally stores `keepCommandsExpanded`+(boolean) for command-row placement inside a turn's process disclosure: absent+means on, so `Bash` and run aliases stay on their own rows beside the activity+groups; `false` folds them into their groups. It is a portable application+preference and changes presentation only. These additive display preferences+neither rewrite stored reasoning nor change the database schema.The settings blob may still contain legacy prompt-enhancement keys from anearlier release. They are retained for rollback and downgrade compatibility,diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.mdindex 3b3126aa4..060541c06 100644--- a/docs/spec/04-ux/06-settings-ia.md+++ b/docs/spec/04-ux/06-settings-ia.md@@ -318,6 +318,14 @@ Settings is a **full-window page** that replaces the app sidebar + main chrome (persisted-settings compatibility and is no longer exposed; an absent orunknown value shows reasoning and an explicit `compact` hides it. Settingssearch indexes the row.+- **Don't collapse commands** is a toggle that persists as the optional+ `keepCommandsExpanded` boolean in host-owned settings, defaulting to on when+ absent. On keeps shell calls on their own rows beside the tool groups they ran+ among; off folds them back into those groups, the layout used before commands+ were separated. It affects presentation only — neither value changes how many+ process disclosures a turn renders (always one), what a tool received, or what+ is stored — and it is read at render time, so toggling repaints the transcript+ immediately. Settings search indexes the row.- The **Command shell** row in Defaults uses the host-discovered catalog of nativePowerShell 5.1, PowerShell 7, cmd, Git Bash, and Bash with IDs`windows-powershell`, `windows-pwsh`, `cmd`, `git-bash`, anddiff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 5115e5630..aca6e3a8e 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -863,33 +863,56 @@ reading surface of the workstation.### Turn process and thinking display-One unified turn-process presentation projects each loaded assistant turn into-chronological collapsible process segments plus its trailing answer. Reasoning,-tools, hosted searches and intermediate assistant text keep their transcript order-across those segments. The trailing answer streams outside the process; later-activity can reclassify provisional answer text into the process without changing-the stored message. Assistant errors and stopped trailing partial answers also-stay outside it. User/system messages and compaction boundaries are unchanged.+One unified turn-process presentation projects each loaded assistant turn into a+single collapsible process disclosure plus its trailing answer. Reasoning, tools,+hosted searches and intermediate assistant text keep their transcript order inside+that disclosure. The trailing answer streams outside the process; later activity+can reclassify provisional answer text into the process without changing the+stored message. Assistant errors and stopped trailing partial answers also stay+outside it. User/system messages and compaction boundaries are unchanged.++The disclosure owns every row the turn produced before its answer: ordinary+activity groups and `Bash` run rows alike. A turn therefore renders exactly one+top-level process disclosure, including a Bash-only turn; no run row is a sibling+of it, and a long turn collapses in one gesture. The answer, assistant errors,+stopped trailing partial text and pending action cards remain outside, reachable+without expanding the process.Within the process, an ordinary activity group represents one contiguous-tool/search/thinking segment between progress paragraphs or Bash rows. It renders a+tool/search/thinking segment between progress paragraphs or run rows. It renders agroup header only when at least two items are visible under the current thinkingpreference. A singleton uses its item disclosure directly, hidden thinking nevercreates an empty wrapper, and the existing Task topology remains the container for-delegated work. Bash and run aliases are excluded from every process disclosure —-neither a turn-level process disclosure nor an ordinary activity group — and render-as standalone rows that stay visible even when every group is collapsed. Adjacent-Bash rows each remain standalone, and a Bash row's detail stays closed until the-user opens it.+delegated work.++`keepCommandsExpanded` decides where a run row sits inside that disclosure and+defaults to on. When on, `Bash` and run aliases are lifted out of the groups they+ran among and render as their own rows at the disclosure's top level; adjacent+calls stay separate and a row's detail stays closed until the user opens it. When+off, a run row keeps its place in the flow and reads as another line of the group+around it. Neither value changes the disclosure count, what a tool received, or+what is stored.The ordinary group owning the active execution segment starts open while a turn isactive, then closes on completion only if untouched; other completed groups startclosed. An untouched active group remains open when any failed or denied tool hasbeen recorded, through later successful recovery, and closes on completion if still-untouched. These group defaults are unified and do not depend on the thinking+untouched. These group defaults are unified and do not depend on eitherpreference. Group headers summarize count, running state and issue count withouttreating a failed child as a failed turn.+The turn disclosure header states the turn's outcome and never echoes the item it+is working on, because a shell command or search query can be arbitrarily long. It+reads `Failed`, `Stopped`, `Running`, or `Finished`, with failure outranking stop,+stop outranking completion, and a live turn reporting running. While running,+stages a reader can sit in front of (compaction, recovery) name themselves; a+live reasoning step reads `Thinking`, and momentary stages read as plain running.+Elapsed time is omitted when the+transcript recorded no timing rather than shown as zero, and issue counts sit+beside the label. The disclosure and the levels it reveals share one left edge;+hierarchy is carried by type size and colour, not by indentation, so a nested+group header and a run row start exactly where the turn header does.+No item payload opens itself: a tool, hosted-search or plan call stays a header rowuntil the user opens its disclosure, including a Bash row, whose detail stays closeduntil the user opens it. The activity groups keep their automatic open defaults, so@@ -898,16 +921,17 @@ live thinking indicator stays visible while completed reasoning rows and excerptare suppressed and empty thinking-only containers are omitted; the stored reasoningis retained and reappears when the preference is turned back on.-Group and item are independent controls. Closing an ancestor keeps descendant-choices and reopening restores them; opening a parent never expands all children.-User interaction with a child claims its containing group without toggling it, so-completion cannot close around opened, focused or selected content. Choices use-stable turn/group/item identities and remain while the retained session pane lives,-including preference changes and row remounts; pane eviction, deletion or renderer-restart reapplies defaults rather than persisting disclosure state to messages or-settings.--Search/navigation reveals the process segment and the activity group that own the+Group, run row and item are independent controls. Closing an ancestor keeps+descendant choices and reopening restores them; closing the turn's disclosure hides+every row under it, and reopening restores the groups the user had opened. Opening+a parent never expands all children. User interaction with a child claims its+containing group without toggling it, so completion cannot close around opened,+focused or selected content. Choices use stable turn/group/item identities and+remain while the retained session pane lives, including preference changes and row+remounts; pane eviction, deletion or renderer restart reapplies defaults rather+than persisting disclosure state to messages or settings.++Search/navigation reveals the turn process and the activity group that own thenamed message, and applies each reveal request once. Item-level targeting is notpart of this change. Reasoning hidden by the preference stays hidden until the userturns `Show thinking` on. Permission, question, plan/goal approval and other@@ -2263,18 +2287,20 @@ Lightweight inline disclosure row showing a semantic tool action, its primaryargument hint, status, and a readable rendering of the result. It follows D071and is intentionally not an elevated card.-One contiguous tool/search/thinking segment between progress paragraphs or Bash-rows becomes an ordinary processing group only when it has two or more visible-items under the current thinking preference. A singleton uses its item disclosure-directly, and Task topology keeps its existing container. Bash and run aliases are-excluded from every process disclosure — neither a turn-level process disclosure-nor an ordinary group — and render as standalone rows that stay visible even when-every group is collapsed; adjacent Bash rows each remain standalone. While the-turn is active, the ordinary group owning the execution segment opens; when it-settles, an untouched group closes. These group defaults do not depend on the-thinking preference. No item payload opens itself: a tool, hosted-search or plan-row stays a header row until the user opens it, whichever item of the group it is,-including a Bash row whose detail stays closed until opened.+The turn's process is one disclosure. Inside it, one contiguous+tool/search/thinking segment between progress paragraphs or run rows becomes an+ordinary processing group only when it has two or more visible items under the+current thinking preference. A singleton uses its item disclosure directly, and+Task topology keeps its existing container. `Bash` and run aliases stay inside the+turn's disclosure: with `keepCommandsExpanded` on (the default) each renders as+its own row beside the groups, and adjacent calls remain separate; with it off a+run row stays in the flow of its group. A Bash-only turn still has its one+disclosure. While the turn is active, the ordinary group owning the execution+segment opens; when it settles, an untouched group closes. These group defaults do+not depend on the thinking preference. No item payload opens itself: a tool,+hosted-search or plan row stays a header row until the user opens it, whichever+item of the group it is, including a Bash row whose detail stays closed until+opened.The group header shows `Processing · 12s` while active or `Processed for 12s`after completion, plus bounded item and issue counts. Expanding it reveals the@@ -2311,8 +2337,11 @@ seconds when non-zero) from one hour onward. Zero-value units are omitted, soauto-opens, so a final thinking item never selects an earlier tool. Livethinking follows its own indicator/disclosure policy and never opens siblingpayloads.-- Bash and run rows render standalone outside every process disclosure and stay- visible even when every group is collapsed; adjacent Bash rows remain separate.+- `Bash` and run rows are revealed by the turn's process disclosure. With+ `keepCommandsExpanded` on they sit at its top level beside the groups and+ adjacent rows stay separate; with it off they render inside their group. They+ are never siblings of the turn's process, and their details stay closed until+ opened.- The processing group spans the full available assistant column, so expandedresult details keep a usable width even when the header or payload is short.- The visible label is a natural-language action (`Read`, `Ran`, `Searched`),diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex ff4d89818..1dcdfe453 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -917,23 +917,31 @@ may be retained while exactly one workspace supplies the visible shell context.- Tool activity starts as a lightweight collapsed item row. Failed and deniedcalls keep their issue in the row header and do not auto-expand their payload.-- One unified presentation gives each loaded assistant turn chronological- collapsible process segments. They contain thinking, tools, hosted searches and- intermediate progress text; the trailing answer, assistant errors and stopped- trailing text remain outside them.+- One unified presentation gives each loaded assistant turn a single collapsible+ process disclosure. It contains thinking, tools, hosted searches, intermediate+ progress text and the turn's `Bash`/run rows; the trailing answer, assistant+ errors and stopped trailing text remain outside it.- A contiguous activity segment receives a group disclosure only when it has atleast two visible items under the current thinking preference. Progress text or a- Bash row ends the segment, a singleton uses its item disclosure directly, and+ run row ends the segment, a singleton uses its item disclosure directly, andhidden thinking does not create a redundant group. Existing Task topology remains- separate. Bash and run aliases are excluded from every process disclosure —- neither a turn-level process disclosure nor a group — and stay standalone rows- that remain visible even when every group is collapsed; adjacent Bash rows each- remain standalone.+ separate. `keepCommandsExpanded` (default on) decides only where a run row sits+ inside the turn's disclosure: on lifts `Bash` and run aliases out of their groups+ into their own top-level rows, with adjacent calls remaining separate; off keeps+ a run row in the flow of its group. Neither value adds another disclosure or+ leaves a run row outside the process.- The active ordinary group starts open and closes when it completes only ifuntouched; completed groups otherwise start closed, and an untouched active groupwith any recorded failed/denied tool remains open through recovery. These group- defaults do not depend on the thinking preference. Bash rows stay visible- regardless of any group's collapsed state.+ defaults do not depend on either preference. Closing the turn's disclosure hides+ every group and run row under it without erasing their choices; reopening+ restores the groups the user had opened.+- The turn header reports `Failed`, `Stopped`, `Running`, or `Finished` in that+ precedence, names compaction and recovery while those stages are live, reads+ `Thinking` while the live step is reasoning, omits the duration when the+ transcript recorded none, and never echoes the current command or query. A+ nested group header and a run row share its left edge; hierarchy is carried by+ type size and colour rather than indentation.- No item payload opens itself: a tool, hosted-search or plan call stays a headerrow until the user opens it, including the literal final item of the lastactivity group. Group defaults are unchanged, so a final thinking item never@@ -949,7 +957,7 @@ may be retained while exactly one workspace supplies the visible shell context.content the user opened, focused or selected. Choices survive preferencechanges, singleton-to-group growth and remounts while the retained session panelives.-- Search/navigation opens the process segment and activity group that own the named+- Search/navigation opens the turn process and activity group that own the namedmessage, once per reveal request. Item-level targeting is not part of thischange. Reasoning hidden by the preference stays hidden until the user turns`Show thinking` on. Closing search does not collapse the revealed path.@@ -1464,7 +1472,7 @@ Project drag/drop follows these patterns:a multi-line draft: the bottom reserve is padding on the transcript content, sothe content is observed on its border box and the newest turn moves up withthe composer instead of sliding behind it (D287).-- A manual disclosure — process segment, activity group, tool/search/thinking item,+- A manual disclosure — turn process, activity group, tool/search/thinking item,delegate brief, or error detail — holds the reading position of the scrollerthat owns it (issue #324). Only the initiating level claims the anchor; markingthe containing group user-owned does not claim its scroll position. The title isdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex a3ffd74f7..c6989e987 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -3367,21 +3367,33 @@ identify the platform validation still needed.- **Steps**: 1) Stream progress paragraph A, a multi-item search segment,progress paragraph B, and a multi-item command segment with adjacent Bash rows.2) Inspect the open active group; manually close it while more output arrives.- 3) Complete the turn and inspect untouched versus user-owned groups, and confirm- the Bash rows stay visible with every group collapsed. 4) Open one completed- group and one item, copy its output, close and reopen the group, then open a- sibling group independently. 5) Repeat with a singleton item and with the last- activity group's literal final item set to a tool/search, thinking, failed tool,- and denied tool. 6) Toggle `Show thinking` off and on and inspect the- active-thinking, failure/recovery and completed states. 7) Remount rows within- the retained pane, then reload the renderer and reopen the session.-- **Expected**: Chronological collapsible process segments keep the trailing answer- outside them. The active group opens, then closes on completion only if- untouched; completed groups otherwise start closed. Bash/run aliases are excluded- from every process disclosure and stay visible even when every group is collapsed.- A singleton has no group wrapper. No item payload opens itself: a tool/search row- stays a header until the user opens it, while a final thinking item keeps its own- leaf default and never selects an earlier tool. When `Show thinking` is off, the+ 3) Complete the turn and confirm exactly one process disclosure owns every+ pre-answer row; close it and confirm the groups and run rows close with it, then+ reopen and confirm the group choice returns. 4) Open one completed group and one+ item, copy its output, close and reopen the group, then open a sibling group+ independently. 5) Toggle `Don't collapse commands` off and on and inspect where+ the run rows render while the disclosure count stays one. 6) Repeat with a+ singleton item and with the last activity group's literal final item set to a+ tool/search, thinking, failed tool, and denied tool. 7) Toggle `Show thinking`+ off and on and inspect the active-thinking, failure/recovery and completed+ states. 8) Remount rows within the retained pane, then reload the renderer and+ reopen the session.+- **Expected**: A turn renders exactly one process disclosure containing every+ pre-answer row, the `Bash`/run rows included; the trailing answer, assistant+ errors and stopped trailing text stay outside it, as do pending actions. The+ active group opens, then closes on completion only if untouched; completed+ groups otherwise start closed. Closing the turn's disclosure closes the groups+ and run rows under it, and reopening restores the user's group choices. With+ `Don't collapse commands` on (default), run rows render as their own top-level+ rows beside the groups, adjacent calls stay separate, and a row's detail stays+ closed until opened; with it off they fold into their groups. Neither value+ changes the disclosure count. A singleton has no group wrapper. No item payload+ opens itself: a tool/search row stays a header until the user opens it, while a+ final thinking item keeps its own leaf default and never selects an earlier+ tool. The header reports `Running`, `Finished`, `Stopped`, or `Failed` with+ failure and stop outranking a normal finish, reads `Thinking` while the live+ step is reasoning, never repeats the current command, and omits the duration+ when none was recorded. When `Show thinking` is off, thelive thinking indicator stays visible while completed reasoning text and excerptsare hidden and empty thinking-only containers are omitted; turning it back onrestores them. Parent, child and sibling choices are independent;@@ -3395,9 +3407,9 @@ identify the platform validation still needed.`04-ux/09-interaction-patterns.md`- **Acceptance**: C (chat stream), E (tools), F (persistence)- **Milestone**: M3-- **Status**: Draft. For the 2026-09-20 nested-disclosure change, this scenario is- intended behavior for static source/design review only; no unit, component,- integration, browser, Electron or E2E test is added or run by that scoped task.+- **Status**: Draft. Unit and style checks cover the one-disclosure,+ command-folding and header rules; this scenario remains the intended manual+ transcript-reload behavior.#### E2E-041: Conversation minimap navigates long transcripts@@ -17168,34 +17180,48 @@ plugin-form fixtures in an isolated temporary directory at runtime.- **Preconditions:** A turn with progress paragraph A, multiple searches plusthinking, progress paragraph B, multiple commands plus thinking, and a final- answer; the `Show thinking` preference on and off; legacy message-level- transcript search targets.+ answer; the `Show thinking` preference on and off; the `Don't collapse+ commands` preference on and off; legacy message-level transcript search+ targets.- **Steps:** Confirm a live active group starts open, let that same turn finish- without interacting, and confirm the group collapses. On a second turn, explicitly- open a completed group and confirm the choice survives subsequent updates. Turn- `Show thinking` off and confirm the live thinking indicator remains while- completed reasoning rows and excerpts disappear and no empty thinking-only- container is left; turn it back on and confirm the completed rows return. Collapse- every group and confirm the Bash/run rows stay visible. Review the nested path,- including independent group/item toggles, parent close/reopen, a singleton- segment, literal-final-item leaf selection, failure/denial/recovery, retained-pane- remounts, Bash rows staying standalone (including adjacent Bash rows) with their- details closed until opened, and a legacy search reveal.-- **Expected:** Chronological collapsible process segments leave the final answer,- assistant errors, stopped trailing text and pending actions outside them. The- active group starts open; untouched groups collapse at completion, while explicit- user choices persist. These group defaults do not depend on the `Show thinking`- preference. Bash/run aliases are excluded from every process disclosure and stay- standalone rows visible even when every group is collapsed; adjacent Bash rows- each remain standalone and a Bash row's detail stays closed until the user opens- it. When `Show thinking` is off, the live thinking indicator stays visible,+ without interacting, and confirm the group collapses. On a second turn,+ explicitly open a completed group and confirm the choice survives subsequent+ updates; then close the turn's disclosure and confirm the group closes with it,+ and reopen to confirm the group choice is restored. Turn `Show thinking` off+ and confirm the live thinking indicator remains while completed reasoning rows+ and excerpts disappear and no empty thinking-only container is left; turn it+ back on and confirm the completed rows return. Turn `Don't collapse commands`+ off and confirm the run rows fold into their groups while the turn still+ renders exactly one disclosure, then turn it on and confirm the standalone rows+ return. Confirm the header reads running, finished, stopped, or failed for each+ case, names compaction and recovery while those stages are live, omits the+ duration when none was recorded, and never repeats the current command. Review+ the nested path, including independent group/item toggles, a singleton segment,+ literal-final-item leaf selection, failure/denial/recovery, retained-pane+ remounts, run rows keeping their details closed until opened, and a legacy search+ reveal.+- **Expected:** A turn renders exactly one process disclosure containing every+ pre-answer row, leaving the final answer, assistant errors, stopped trailing+ text and pending actions outside it. The active group starts open; untouched+ groups collapse at completion, while explicit user choices persist and are+ restored when the enclosing disclosure is reopened. These group defaults do not+ depend on the `Show thinking` preference. With `Don't collapse commands` on,+ run aliases render as their own rows beside the groups, adjacent rows stay+ separate and a row's detail stays closed until opened; with it off they fold+ into their groups. Neither value changes the disclosure count. The header+ reports running, finished, stopped, or failed with failure and stop outranking+ a normal finish, reads `Thinking` while the live step is reasoning, names+ compaction and recovery while those stages are live, omits a duration the+ transcript did not record, and never repeats the current command. Nested group+ headers and run rows share the turn header's left edge.+ When `Show thinking` is off, the live thinking indicator stays visible,completed reasoning rows and excerpts are hidden, and empty thinking-onlycontainers are omitted; turning it back on restores them. Singletons have nogroup. No item payload opens itself: a tool/search row stays closed until the useropens it, while a final thinking item keeps its own leaf default.Parent/child/sibling states remain independent, pane-owned user choices surviveupdates, preference changes and remounts, and renderer restart reapplies defaults.- Search reveals the process segment and activity group that own the named message+ Search reveals the turn process and activity group that own the named messageonce per request; item-level targeting is not part of this change, and reasoninghidden by the preference stays hidden until the user turns `Show thinking` on.Saved `showThinking` survives restart; an absent value falls back to the legacy@@ -18374,7 +18400,7 @@ host-created files. The full app's file-preview viewer is covered separately.offer answers `{ shown: false, reason }` and shows nothing. No transcript row,toast, or overlay appears, and the plugin's call is audited.- **Specs linked**: `07-plugins/03-plugin-api.md`,- `07-plugins/13-plugin-permissions-matrix.md`, ADR 0332.+ `07-plugins/13-plugin-permissions-matrix.md`, ADR 0333.- **Acceptance**: A (Composer entry path), Security (permission-gated, neversent by the plugin).- **Milestone**: M6+diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 1ea52e8ff..2c432fe69 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -52,7 +52,7 @@ This log freezes previously open questions into concrete decisions.| D656 | Quarantine appends the host keeps refusing instead of stalling the outbox | **Amend ADR 0041 / D318 / D444 / D597: an append whose `session.appendMessage` or `session.recordUsage` call fails with an error the outbox cannot classify as a duplicate message id, a `PERMISSION_DENIED:` poison row, or a foreign-key orphan is retried on a bounded backoff (5s, doubling to a 60s cap) instead of ending the flush. The fifth consecutive failure on that head moves it into an application-owned dead-letter file, `session-message-outbox.dead-letter.json`, with its payload, session id, quarantine timestamp, and host error; only the newest 256 quarantined appends are kept, and the oldest is discarded with a warn. The flush then continues with the next entry, so one refused append can no longer hold the FIFO head, fill the 1024-entry cap, or fail every session's writes. Quarantined appends are never replayed automatically, and `session.delete` drops that session's quarantined appends too. No protocol version, storage schema, or queued-outbox format change.** | A `stream did not contain valid UTF-8` append stayed at the FIFO head for 14.8 hours while `session.persistence.outbox.is.full` fired 5990 times, so every session's appends failed until restart. Only three error classes had a drain, and every other error was treated as transient forever (#1560). || D657 | Let the embedded Browser open local files outside the workspace | **Amend ADR 0170: an explicit absolute path or `file:` URL may load any existing regular local file, and a local-file page may navigate to other existing local files. Relative inputs remain workspace-rooted; HTTP(S) pages retain only the prior in-workspace file-link allowance. Missing files, directories, and remote file authorities remain blocked. `BrowserPreview` and the sidecar keep their workspace-rooted resolver. The public `pi.browser.navigate` API follows this policy under the high-risk `browser.cdp` permission. See ADR 0328, E2E-059, `04-ux/08-component-spec.md`, and `05-security/01-security.md`.** | Users need to inspect local HTML outside a project, while workspace-scoped agent file tools and remote-page navigation must retain their existing boundary (#1627). || D659 | Reopen archived projects in the sidebar | **Amend D093 / D455: successful explicit project activation clears the normalized path's renderer-local archived flag and persists it, so Open from Project archive, reopening the same folder through Add project, and opening a project session reveal the project in the home sidebar. Selecting a row for inspection and ordinary session refreshes do not alter archive state. No host/project/session storage or protocol change. See ADR 0294, E2E-264, and issue #1653.** | Reopening a project changed the active workspace but left its path-keyed archived presentation flag set, hiding it from the sidebar after the user explicitly reopened it. |-| D661 | Segmented turn process and independent thinking preference | **Supersede the `Detailed` / `Compact` display-mode behavior and the single whole-process disclosure recorded by D633 / D651 and the `turn-process-and-thinking-display` ADR: a turn renders as chronological collapsible process segments, Bash and run aliases stay outside every folded container (the turn-level process disclosure and any ordinary activity group) and remain visible even when every group is collapsed, and process/group folding defaults are independent of the thinking preference. The preference is the optional boolean `AppSettings.showThinking`; absent or non-boolean values fall back to the legacy `thinkingDisplayMode` field (`compact` hides, `detailed`/unknown/absent shows), which is retained only for persisted-settings compatibility. `showThinking` joins the portable application fields so it synchronizes like the legacy field; no other host protocol, persistence schema, permission, or plugin contract change. See the amended ADR, `04-ux/06-settings-ia.md`, `04-ux/08-component-spec.md`, `04-ux/09-interaction-patterns.md`, and E2E-CHAT-turn-process-and-thinking-display.** | One flat container left long tool/search runs hard to scan and forced reasoning visibility and process folding into the same two-valued switch; an independent boolean plus always-visible Bash rows keeps shell-heavy turns readable without hiding the answer. |+| D661 | Segmented turn process and independent thinking preference *(amended by D668)* | **Supersede the `Detailed` / `Compact` display-mode behavior and the single whole-process disclosure recorded by D633 / D651 and the `turn-process-and-thinking-display` ADR: a turn renders as chronological collapsible process segments, Bash and run aliases stay outside every folded container (the turn-level process disclosure and any ordinary activity group) and remain visible even when every group is collapsed, and process/group folding defaults are independent of the thinking preference. The preference is the optional boolean `AppSettings.showThinking`; absent or non-boolean values fall back to the legacy `thinkingDisplayMode` field (`compact` hides, `detailed`/unknown/absent shows), which is retained only for persisted-settings compatibility. `showThinking` joins the portable application fields so it synchronizes like the legacy field; no other host protocol, persistence schema, permission, or plugin contract change. See the amended ADR, `04-ux/06-settings-ia.md`, `04-ux/08-component-spec.md`, `04-ux/09-interaction-patterns.md`, and E2E-CHAT-turn-process-and-thinking-display.** | One flat container left long tool/search runs hard to scan and forced reasoning visibility and process folding into the same two-valued switch; an independent boolean plus always-visible Bash rows keeps shell-heavy turns readable without hiding the answer. || D662 | Open scoped HTML files in the work-panel Browser from plugins | **Add `pi.fs.openInBrowser(pathFromRoot)` under `fs.read`. The host applies the plugin's normal read containment, protected-path, credential deny-list, declared scope, and registered project-folder checks; only existing `.html`, `.htm`, and `.xhtml` files qualify. After validation, Main asks the renderer to create a Browser resource tab for the active local session. The Browser plugin must be enabled. This grants no `browser.cdp`, changes no BrowserPreview or local-file navigation policy, and adds no host-core protocol or persisted-state change. See ADR 0330, `07-plugins/03-plugin-api.md`, `07-plugins/13-plugin-permissions-matrix.md`, `04-ux/08-component-spec.md`, and E2E-153.** | The File Manager needs an in-app HTML preview, while granting its plugin `browser.cdp` would also expose unrelated page inspection and control. |## B. Secondary implementation defaults@@ -332,6 +332,7 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.| D602 | Crash dumps stay in the data directory | **Electron's Crashpad reporter starts local-only (`uploadToServer: false`) before `ready`. Dumps live under `<data_dir>/crash-dumps`, not the default Electron `userData` crashDumps path, so a `PI_DESKTOP_DATA_DIR` profile does not share dumps. The next lock-holding launch writes one `diagnostics` line for dumps newer than `crash-dumps.json`, classified by Crashpad `ptype`: `error` if any new dump is the browser/main process, `warn` for recovered renderer/GPU/utility crashes. Host-core and sidecar crashes stay on the supervisor path. No upload, no IPC, no schema change.** | A crash left a minidump nobody read. Crashpad also records recovered renderer crashes, so a next-launch `error` that said the previous run died was a lie; and dumps outside the data directory escaped `PI_DESKTOP_DATA_DIR` isolation. || D619 | A copied formula is its TeX source | **Renderer only: a copy whose selection covers rendered math writes `text/plain` from the MathML `annotation` — `$…$` inline, `$$…$$` on its own lines, the delimiters `lib/latex-math.ts` normalizes `\(…\)` and `\[…\]` to, each run widened past any run inside the formula as a code span's fence is — instead of the two trees KaTeX paints. A cut that lands inside a formula grows to the whole formula. Only the formulas are rewritten: the reduced clone is read back through `Selection.toString()`, the serializer a copy itself runs, so prose, lists, tables and code blocks sharing the selection keep the platform's own reading — `user-select: none` chrome left behind included, which `innerText` would have written out. A selection with no formula in it, and a copy raised where the selection does not live, are left to the platform entirely. One flavour is written, `text/plain`: taking the event over drops the platform's `text/html` too and none is written back, because the reduced clone is app markup that would carry the `user-select: none` chrome the text reading drops, and because carrying the rendering instead would paste every formula twice — KaTeX's stylesheet is the only thing hiding the MathML tree and no stylesheet travels on the clipboard. One document `copy` listener owned by the shell, and the transcript's right-click Copy reads the same selection through the same module.** | A formula pasted as its glyphs, once per rendered tree, so it could not be carried into a LaTeX document or another Markdown editor (issue #414). ADR 0268 removed quoting on the grounds that the OS clipboard was the substitute; the clipboard had to actually carry the source. || D620 | pi-ai built-in API-key services are named presets | **Add fifteen named endpoint presets — Ant Ling, Baseten, Cerebras, Hugging Face, Meta (`responses`), MiniMax (International), Moonshot AI (International), NVIDIA, OpenCode Zen, Vercel AI Gateway, Qwen Token Plan (`alibaba-token-plan`), Qwen Token Plan (China), Xiaomi Token Plan (China / Europe / Singapore) — to `NAMED_ENDPOINT_PRESETS`, each at its published host, with the pi-ai provider id kept as an alias wherever the models.dev key differs. Eight built-in providers remain exceptions with a recorded reason: Amazon Bedrock, Azure OpenAI, Cloudflare AI Gateway, Cloudflare Workers AI, Google Vertex AI (account- or region-scoped URLs), GitHub Copilot and OpenAI Codex (vendor-account rows), and Radius (`pi_messages` is account-only here). `packages/agent-runtime/src/pi-ai-provider-sync.test.ts` fails on a pi-ai upgrade that leaves a provider neither covered nor excepted. No protocol, storage, or IPC change.** | Every other pi-ai capability was already reachable, but the API-key half of the service catalog was hand-maintained and had drifted from the library's own provider list (ADR 0307). |+| D668 | One process disclosure per turn, with a command-folding preference | **Amend D661 / the `turn-process-and-thinking-display` ADR. A turn renders exactly one top-level process disclosure holding every pre-answer row, the run rows included; the answer stays outside it. `Bash` and run aliases are no longer excluded from every folded container. Inside that disclosure, the optional boolean `AppSettings.keepCommandsExpanded` (absent means on) decides whether run rows are lifted beside the groups they ran among or stay inside them; both values render exactly one disclosure. The preference is read while rendering, not while building transcript entries, so toggling it repaints immediately - the projection cache is keyed by messages and compactions only. The disclosure header reports failed / stopped / running / finished with precedence in that order and never echoes the current item, and the disclosure shares one left edge with the levels it reveals. `keepCommandsExpanded` joins the portable application fields. No host protocol, persistence schema, permission, or plugin contract change. See the amended ADR, `04-ux/06-settings-ia.md`, `04-ux/08-component-spec.md`, `04-ux/09-interaction-patterns.md`, and E2E-CHAT-turn-process-and-thinking-display.** | Chronological segmentation split one turn into several sibling disclosures above the answer, and always-visible command rows could not be turned off by readers who preferred the older grouped layout; one disclosure plus a presentation-only preference satisfies both without changing what a tool received or stored. |## M0. Model catalog decisions@@ -7847,3 +7848,25 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.keeps the opaque choice a user already made. See ADR 0332, ADR 0248,`04-ux/06-settings-ia.md`, `04-ux/08-component-spec.md`, and`apps/desktop/test/macos-window-translucency.test.mjs`.++## 2026-10-21 — One process disclosure per turn, with command folding (D668)++- D668 amends D661 / the `turn-process-and-thinking-display` ADR: a turn now+ renders exactly one top-level process disclosure containing every pre-answer+ row, the `Bash`/run rows included. No run row is a sibling of that disclosure;+ the trailing answer, assistant errors, stopped trailing text, and pending action+ surfaces stay outside it.+- `AppSettings.keepCommandsExpanded` (absent means on) decides whether run rows are+ lifted beside the groups they ran among or stay inside them. The preference is+ read while rendering, not while building transcript entries, so toggling it+ repaints immediately; both values render exactly one disclosure.+- The disclosure header reports failed / stopped / running / finished in that+ order, names compaction and recovery while those stages are live, drops an+ unavailable duration instead of showing zero, and never echoes the current item.+ The disclosure and the levels it reveals share one left edge.+- `keepCommandsExpanded` joins the portable application fields. Covered by+ `apps/desktop/test/turn-process.test.mjs`,+ `apps/desktop/test/transcript-style.test.mjs`, and the interactive transcript+ probes. See the amended ADR, `04-ux/06-settings-ia.md`,+ `04-ux/08-component-spec.md`, `04-ux/09-interaction-patterns.md`, and+ E2E-CHAT-turn-process-and-thinking-display.diff --git a/docs/zh-CN/adr/turn-process-and-thinking-display.md b/docs/zh-CN/adr/turn-process-and-thinking-display.mdindex afc0f3194..b1bc0832c 100644--- a/docs/zh-CN/adr/turn-process-and-thinking-display.md+++ b/docs/zh-CN/adr/turn-process-and-thinking-display.md@@ -4,7 +4,7 @@- 状态:已接受- 日期:2026-09-17-- 修订:2026-10-16+- 修订:2026-10-21- Issues:#510、#461- 修订对象:D071、[ADR 0242](/adr/0242-delta-only-streaming-updates)@@ -17,26 +17,40 @@## 决策-所有已加载的助手回合条目都使用同一套回合过程展示:投影为按时间顺序排列、可折叠的-过程片段,以及其后的最终回答。思考、工具和中间进度文字跨这些片段按原顺序保留。流式-输出时,暂定为回答的末尾助手文字保持可见;如果随后出现工具或思考活动,该文字会移入-过程,但不会改写已存消息。`UiMessage` 没有语义化的最终回答标记,因此渲染器不根据-措辞猜测。用户消息、系统消息和压缩分隔线继续保留原有回合边界。+所有已加载的助手回合条目都使用同一套回合过程展示:投影为一个可折叠的过程披露,+以及其后的最终回答。思考、工具、中间进度文字以及该回合的 `Bash` 命令行都按转录顺序+保留在这个披露内。流式输出时,暂定为回答的末尾助手文字保持可见;如果随后出现工具或+思考活动,该文字会移入过程,但不会改写已存消息。`UiMessage` 没有语义化的最终回答标记,+因此渲染器不根据措辞猜测。用户消息、系统消息和压缩分隔线继续保留原有回合边界。-过程是分段的,而不是一个扁平容器。非 Bash 活动形成普通活动组:两个进度段落或 Bash 行-之间的一段连续工具、搜索或思考活动,并且仅在当前思考偏好下至少有两个可见项时出现。-单项活动直接使用自身披露;被隐藏的思考不会制造多余的组包装。现有 Task 拓扑仍是其片段-的容器,不会在普通活动组中重复渲染。+每个回合只渲染一个过程披露。回合在给出答案之前产生的所有行都位于其中——活动组与 `Bash`+命令行同样如此——因此长回合可以用一次操作收起,而不会在答案上方留下一列并列披露。答案本身+位于披露之外。-Bash 和 run 别名被排除在所有过程披露之外——既不属于回合级过程披露,也不属于普通活动组-——而是作为独立行渲染,即使所有组都收起也保持可见。相邻的 Bash 行各自保持独立,且-Bash 行的详情在用户手动打开之前保持收起。进度段落之间的其他操作仍会形成可按时间顺序-折叠的活动组。+在该披露内部,非 Bash 活动形成普通活动组:两个进度段落或命令行之间的一段连续工具、搜索或+思考活动,并且仅在当前思考偏好下至少有两个可见项时出现。单项活动直接使用自身披露;被隐藏的+思考不会制造多余的组包装。现有 Task 拓扑仍是其片段的容器,不会在普通活动组中重复渲染。-活动组的折叠默认值是统一的,不依赖思考偏好。拥有当前执行片段的普通活动组默认展开,+命令行位于其组内还是组旁,由 `keepCommandsExpanded` 偏好决定,默认开启。开启时,`Bash`+和 run 别名会从所处的组中提取出来:各自成为披露顶层的独立行,相邻调用保持分离,详情在用户+打开之前保持收起。关闭时,命令行保留在流程中的原位置,读起来就是所在组的另一行——即命令尚未+被分离之前的布局。该偏好不会改变回合渲染的披露数量:两种取值都只渲染一个。++活动组的折叠默认值是统一的,不依赖思考偏好或上述偏好。拥有当前执行片段的普通活动组默认展开,仅在用户未操作时于完成后收起;其他已完成组默认收起。只要活动组中记录过失败或被拒工具,-尚未被用户接管的活动组就会在后续恢复期间保持展开,并在回合完成后收起。无论任何组是否-收起,Bash 行都保持可见。+尚未被用户接管的活动组就会在后续恢复期间保持展开,并在回合完成后收起。关闭回合披露会一并+关闭其下的组,重新展开则恢复用户此前展开过的组。++回合披露的标题只陈述回合的结果,绝不回显正在处理的具体项,因为一条 shell 命令或搜索词可能+任意长。其取值优先级依次为失败、已停止、执行中、已完成:已记录的失败优先于停止,因为该回合+没有产出答案,而看起来正常的标题会掩盖这一点。停止取自被中止的消息,这是运行时唯一记录的信+号——回合结果只区分完成与失败。工具或思考仍在执行时,被中止的活动行同样记录停止;委派子任务+的行不决定父回合结果。执行期间,用户可能长时间停留的阶段(压缩上下文、恢复)会各自+命名;当前步骤为推理时显示 `Thinking`,瞬时阶段则显示为普通执行中。转录未记录时间时不显示+时长,而不是显示为零;问题计数与标签并列显示。++披露与它展开的层级共用同一条左边缘。层级由字号与颜色表达,而不是缩进,因此嵌套的组标题与+命令行起始位置与回合标题完全一致。思考偏好是一个布尔值 `showThinking`。当它为 false 时,活动思考指示器保持可见,而已完成的思考行和摘要会被隐藏,空的纯思考容器会被省略;已存推理仍会保留,因此重新打开该偏好@@ -52,7 +66,7 @@ Bash 行的详情在用户手动打开之前保持收起。进度段落之间的窗格仍存在,手动选择就跨流式更新、完成、偏好切换、单项变组和行重新挂载保留。窗格淘汰、会话删除或渲染器重启会释放这些展示状态;它们不写入消息或宿主设置。-搜索和导航只展开目标所需的祖先路径:拥有该消息的过程片段和活动组。条目级精确定位不在+搜索和导航只展开目标所需的祖先路径:拥有该消息的回合过程和活动组。条目级精确定位不在本次范围内,各行详情仍由各自的折叠控制。同一请求重新渲染时,不会反复覆盖用户之后的手动收起。被偏好隐藏的推理会保持隐藏,直到用户打开 `showThinking`。助手错误、中止后的末尾部分回答、权限/提问/计划/目标决策及其他待处理操作面必须位于隐藏过程之外,@@ -62,20 +76,22 @@ Bash 行的详情在用户手动打开之前保持收起。进度段落之间的`AppSettings` 字段持久化。缺失或非布尔值会回退到旧版 `thinkingDisplayMode` 字段:显式 `compact` 隐藏推理,而 `detailed`、未知值或缺失值都显示推理。旧字段为持久化设置的兼容性而保留,不再在界面中暴露。该偏好只改变展示,不改变提供商思考级别、运行时或模型-上下文、已存推理、导出、权限、执行或复制载荷,也不控制过程片段或活动组的折叠。过程标题+上下文、已存推理、导出、权限、执行或复制载荷,也不控制回合过程或活动组的折叠。过程标题使用已记录的计时、直接工具/搜索计数、运行状态和问题计数;不会重复计算委派子任务,也不会把单个失败工具误报为整个助手回合失败。## 结果-- 按时间顺序排列的可折叠过程片段让最终回答和待处理操作保持可达,并且即使所有组都收起,- Bash/run 行也保持可见。-- 活动组的折叠默认值统一:运行中的工作保持可见,未操作的已完成组默认收起,- 无论思考偏好如何都保留用户明确的披露选择。+- 每个回合一个披露,让最终回答与待处理操作保持可达,并使长回合可以用一次操作收起。+- 活动组的折叠默认值统一:运行中的工作保持可见,未操作的已完成组默认收起,无论思考偏好如何+ 都保留用户明确的披露选择。关闭回合披露会关闭其下的组,重新展开则恢复用户此前展开过的组。- 当 `showThinking` 为 false 时,活动指示器保持可见,而已完成的推理行和摘要被隐藏。已存推理仍会保留,重新打开偏好时重新出现。-- Bash 和 run 别名作为独立行位于所有过程披露之外,因此命令密集的回合无需把相邻命令- 折叠在一起即可浏览。+- 当 `keepCommandsExpanded` 开启(默认)时,run 别名作为独立行渲染,命令密集的回合保持易读;+ 关闭时恢复较早的布局,命令行读起来就是所在组的另一行。两种取值都不改变披露数量;该偏好+ 在渲染时读取而非在构建条目时读取,因此切换后立即重绘,而无需等待新消息。+- 标题用一行说明回合的结果。回显当前命令的做法已被移除:它会把计数挤出该行,并且与打开该项+ 已经能看到的内容重复。- 披露记忆是以稳定回合、组和条目标识为键的窗格展示状态,不是持久化转录契约,也不属于中央工作流 store。- 只对已加载的转录条目分组;不会重建未加载历史,也不会跨压缩边界合并回合。@@ -92,3 +108,7 @@ Bash 行的详情在用户手动打开之前保持收起。进度段落之间的`showThinking`/旧版 `thinkingDisplayMode` 的解析优先级,并由 i18n 目录测试覆盖新增的`settings.showThinking` 文案。界面、解析器与 E2E 场景在集成候选上验证;同步后的场景文本见E2E-CHAT-turn-process-and-thinking-display。+2026-10-21 修订由 `apps/desktop/test/turn-process.test.mjs` 覆盖单披露分段、+命令折叠开关与标题阶段优先级,由 `apps/desktop/test/transcript-style.test.mjs` 覆盖共享+左边缘与已移除的实时条目回显;交互式转录探针覆盖实际渲染的披露数量、命令行位置和标题+文案。同步后的场景文本见 E2E-CHAT-turn-process-and-thinking-display。diff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.mdindex 5b8bc49f7..98cab0296 100644--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md@@ -1232,7 +1232,10 @@ outbox 排空。渲染器侧的停止绝不重写已有已开始回复的转录应用设置 JSON 还可选存储布尔值 `showThinking`,用于转录中的推理可见性。它是可移植的应用偏好,会像旧字段一样跨设备同步。缺失值回退到旧版 `thinkingDisplayMode` 字段(`compact` 隐藏,`detailed`/未知/缺失显示);该旧字段仅为持久化设置兼容性保留,-并作为该回退来源。这些新增展示偏好既不重写已存推理,也不改变数据库 schema。+并作为该回退来源。应用设置 JSON 还可选存储布尔值 `keepCommandsExpanded`,用于回合+过程披露中的命令行位置:缺失即开启,`Bash` 与 run 别名保留在活动组旁的独立行;+`false` 折回所属组。它是可移植的应用偏好,只改变展示。这些新增展示偏好既不重写+已存推理,也不改变数据库 schema。应用设置 JSON 可能仍包含旧版本写入的提示词增强键。为支持回退和降级,宿主保留这些值,但不会再把它们作为有效偏好读取或写入。用户安装并授权独立的diff --git a/docs/zh-CN/spec/04-ux/06-settings-ia.md b/docs/zh-CN/spec/04-ux/06-settings-ia.mdindex 39a02e805..9e903d272 100644--- a/docs/zh-CN/spec/04-ux/06-settings-ia.md+++ b/docs/zh-CN/spec/04-ux/06-settings-ia.md@@ -129,6 +129,11 @@`thinkingDisplayMode` 字段(`detailed` / `compact`)仅为持久化设置兼容性保留,不再在界面暴露;缺失或未知值显示推理,显式 `compact` 隐藏推理。设置搜索会索引该行。+- **不折叠命令**是一个开关,以可选的 `keepCommandsExpanded` 布尔值持久化到宿主设置,+ 缺失时默认开启。开启时,shell 调用保留在它们所运行的工具组旁,作为独立行;关闭时+ 折回这些组,即命令被分离之前的布局。它只影响展示——两种取值都不改变回合渲染的过程+ 披露数量(始终为一个),也不改变工具收到的内容或持久化内容——并且在渲染时读取,+ 因此切换后会立即重绘转录。设置搜索会索引该行。- 语音绑定(`AppSettings.speech`)**不属于设置页面**(ADR 0291)。宿主仍保留语音能力与`speech/*` IPC,供插件和已存绑定使用;这里不再提供转写/朗读的服务、协议、模型或音色选择,设置搜索也不再索引语音相关键。diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 07d75aa4e..d6d89adca 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -1057,22 +1057,38 @@ SESSIONS [msg+][↕]### 回合过程与思考展示-所有已加载的助手回合都使用同一套回合过程展示,投影为按时间顺序排列、可折叠的过程片段,-以及其后的最终回答。推理、工具、托管搜索和中间进度文字跨这些片段按转录顺序保留。末尾-回答在过程之外流式显示;后续活动可以把暂定回答重新归入过程,但不会改写已存消息。助手-错误和中止后的末尾部分回答也留在过程之外。用户/系统消息及压缩边界不变。--过程内的普通活动组表示两个进度段落或 Bash 行之间的一段连续工具、搜索或思考活动。只有在-当前思考偏好下至少有两个可见项时才显示组标题。单项活动直接使用自身披露,被隐藏的思考-不会制造空包装,委派工作继续使用现有 Task 拓扑作为容器。Bash 和 run 别名被排除在所有-过程披露之外——既不属于回合级过程披露,也不属于普通活动组——而是作为独立行渲染,即使-所有组都收起也保持可见;相邻的 Bash 行各自保持独立,其详情在用户打开之前保持收起。--拥有当前执行片段的普通活动组在回合运行时默认展开,完成时仅在用户未操作的情况下收起;-其他已完成组默认收起。若活动组记录过失败或被拒工具,尚未被用户接管的活动组会在后续成功-恢复期间保持展开,并在回合完成后收起。这些组默认值统一,不依赖思考偏好。无论任何组是否-收起,Bash 行都保持可见。组标题显示计数、运行状态和问题计数,但不会把失败子项当作整个-回合失败。+所有已加载的助手回合都使用同一套回合过程展示:投影为一个可折叠的过程披露,以及其后的+最终回答。推理、工具、托管搜索和中间进度文字按转录顺序保留在该披露内。末尾回答在过程+之外流式显示;后续活动可以把暂定回答重新归入过程,但不会改写已存消息。助手错误和中止+后的末尾部分回答也留在披露之外。用户/系统消息及压缩边界不变。++该披露包含回合在给出回答之前产生的所有行:普通活动组与 `Bash` 命令行都在其中。因此+每个回合只渲染一个顶层过程披露,只有 Bash 调用的回合也一样;任何命令行都不是该披露的+同级,长回合可以用一次操作收起。末尾回答、助手错误、中止后的末尾部分文字和待处理操作+卡留在披露之外,无需展开过程即可访问。++在披露内部,普通活动组表示两个进度段落或命令行之间的一段连续工具、搜索或思考活动。+只有在当前思考偏好下至少有两个可见项时才显示组标题。单项活动直接使用自身披露,被隐藏+的思考不会制造空包装,委派工作继续使用现有 Task 拓扑作为容器。++`keepCommandsExpanded` 决定命令行在该披露内的位置,默认开启。开启时,`Bash` 和 run+别名会从所处的组中提取出来,作为披露顶层的独立行渲染;相邻调用保持分离,详情在用户+打开之前保持收起。关闭时,命令行保留在流程中的原位置,读起来就是所在组的另一行。两种+取值都不改变披露数量、工具实际收到的内容或持久化内容。++活动组的折叠默认值统一,不依赖任一偏好。拥有当前执行片段的普通活动组在回合运行时默认+展开,完成时仅在用户未操作的情况下收起;其他已完成组默认收起。若活动组记录过失败或被+拒工具,尚未被用户接管的活动组会在后续成功恢复期间保持展开,并在回合完成后收起。组+标题汇总计数、运行状态和问题计数,但不会把失败子项当作整个回合失败。++回合披露的标题只陈述回合结果,绝不回显正在处理的具体项,因为 shell 命令或搜索词可能+任意长。它显示 `Failed`、`Stopped`、`Running` 或 `Finished`,优先级依次为失败、停止、+运行中、已完成:已记录的失败优先于停止,停止优先于正常完成,运行中的回合显示为执行中。+执行期间,用户可能长时间停留的阶段(压缩上下文、恢复)会各自命名;当前步骤为推理时显示+`Thinking`,瞬时阶段显示为普通执行中。转录未记录时间时不显示时长,而不是显示为零;问题+计数与标签并列显示。披露与它+展开的层级共用同一条左边缘;层级由字号与颜色表达,而不是缩进,因此嵌套组标题与命令行+起始位置与回合标题完全一致。条目载荷都不会自动展开:工具调用、托管搜索或计划卡片行在用户打开其披露之前始终只是标题行,包括 Bash 行——其详情在用户打开之前保持收起。活动组保留各自的自动展开默认值,@@ -1080,14 +1096,15 @@ SESSIONS [msg+][↕]可见,而已完成的推理行和摘要被隐藏,空的纯思考容器被省略;已存推理仍会保留,重新打开偏好时重新出现。-活动组和条目是相互独立的控件。收起祖先会保留下级选择,重新展开时恢复;展开父级不会-展开所有后代。用户操作子项时会接管其所属组但不切换该组,因此完成事件不能收起包含已-展开、聚焦或选中内容的容器。选择以稳定回合/组/条目标识保存在会话窗格内,跨偏好切换-和行重新挂载保留;窗格淘汰、会话删除或渲染器重启后重新应用默认值,不会写入消息或设置。+活动组、命令行和条目是相互独立的控件。收起祖先会保留下级选择,重新展开时恢复;收起+回合披露会隐藏其下所有行,重新展开时恢复用户此前展开的组。展开父级不会展开所有后代。+用户操作子项时会接管其所属组但不切换该组,因此完成事件不能收起包含已展开、聚焦或选中+内容的容器。选择以稳定回合/组/条目标识保存在会话窗格内,跨偏好切换和行重新挂载保留;+窗格淘汰、会话删除或渲染器重启后重新应用默认值,不会写入消息或设置。-搜索和导航只展开拥有目标消息的过程片段和活动组,并且每个显示请求只应用一次。条目级精确-定位不在本次范围内。被偏好隐藏的推理会保持隐藏,直到用户打开 `Show thinking`。权限、-提问、计划/目标审批及其他待处理操作卡位于隐藏过程之外,始终可达。参见+搜索和导航只展开拥有目标消息的回合过程与活动组,并且每个显示请求只应用一次。条目级+精确定位不在本次范围内。被偏好隐藏的推理会保持隐藏,直到用户打开 `Show thinking`。+权限、提问、计划/目标审批及其他待处理操作卡位于隐藏过程之外,始终可达。参见[ADR turn-process-and-thinking-display](/zh-CN/adr/turn-process-and-thinking-display)。### 7.2 解剖学@@ -1523,13 +1540,14 @@ sorting, new settings, persistence, or host protocol is introduced.参数提示、状态和结果的可读呈现。遵循D071并且故意不是一张高级卡。-两个进度段落或 Bash 行之间的一段连续工具、搜索或思考活动,仅在当前思考偏好下有两个及-以上可见项时成为普通处理组。单项活动直接使用自身披露,Task 拓扑继续使用原有容器。-Bash 和 run 别名被排除在所有过程披露之外——既不属于回合级过程披露,也不属于普通组——-而是作为独立行渲染,即使所有组都收起也保持可见;相邻的 Bash 行各自保持独立。回合活动-期间,拥有当前执行片段的普通组默认展开;未操作的组在完成时自动收起。这些组默认值不依赖-思考偏好。条目载荷都不会自动展开:工具调用、托管搜索或计划行在用户打开之前始终只是-标题行,无论它位于活动组的哪一项,包括详情在打开前保持收起的 Bash 行。+回合过程是一个披露。在该披露内部,两个进度段落或命令行之间的一段连续工具、搜索或思考+活动,仅在当前思考偏好下有两个及以上可见项时成为普通处理组。单项活动直接使用自身披露,+Task 拓扑继续使用原有容器。`Bash` 和 run 别名保留在回合披露内:`keepCommandsExpanded`+开启(默认)时,每一项作为组旁的独立行渲染,相邻调用保持分离;关闭时,命令行留在所在组+的流程中。只有 Bash 调用的回合仍保留其唯一披露。回合活动期间,拥有当前执行片段的普通组+默认展开;未操作的组在完成时自动收起。这些组默认值不依赖思考偏好。条目载荷都不会自动+展开:工具调用、托管搜索或计划行在用户打开之前始终只是标题行,无论它位于活动组的哪一项,+包括详情在打开前保持收起的 Bash 行。组标题在活动时显示 `Processing · 12s`,完成后显示 `Processed for 12s`,并提供有界条目与问题计数。展开后显示有序活动行及其相互独立的结果披露。失败子项仍在自己的@@ -1559,8 +1577,9 @@ ToolCallRow 上显示错误,但不会让组或整个回合成为终端失败活动没有组标题。- 工具/搜索载荷保持收起,直到用户打开;没有任何行会自动展开,因此最后一项为思考时绝不会选择更早的工具。活动思考遵循自身披露策略,绝不会展开同级载荷。-- Bash 和 run 行作为独立行渲染,位于所有过程披露之外,即使所有组都收起也保持可见;- 相邻的 Bash 行保持独立。+- `Bash` 和 run 行由回合过程披露展开。`keepCommandsExpanded` 开启时,它们位于披露顶层、+ 组旁,相邻行保持独立;关闭时,它们渲染在所属组内。它们绝不是回合过程的同级,详情在+ 用户打开之前保持收起。- 处理组跨越完整可用的辅助列,因此扩展即使标头或有效负载很短,结果详细信息也会保持可用宽度。- 可见标签是自然语言操作(`Read`、`Ran`、`Searched`),diff --git a/docs/zh-CN/spec/04-ux/09-interaction-patterns.md b/docs/zh-CN/spec/04-ux/09-interaction-patterns.mdindex 4ddf2fee8..29f46e1f7 100644--- a/docs/zh-CN/spec/04-ux/09-interaction-patterns.md+++ b/docs/zh-CN/spec/04-ux/09-interaction-patterns.md@@ -701,15 +701,22 @@- 工具活动以轻量的收起条目开始。失败和被拒调用在行标题中保留问题状态,载荷不会自动展开。-- 统一的展示为每个已加载的助手回合提供按时间顺序排列的可折叠过程片段,其中包含思考、- 工具、托管搜索和中间进度文字;末尾回答、助手错误和中止后的末尾文字位于过程之外。-- 连续活动片段仅在当前思考偏好下至少有两个可见项时获得组披露。进度文字或 Bash 行结束+- 统一的展示为每个已加载的助手回合提供一个可折叠的过程披露。它包含思考、工具、托管搜索、+ 中间进度文字以及该回合的 `Bash`/run 行;末尾回答、助手错误和中止后的末尾文字留在+ 披露之外。+- 连续活动片段仅在当前思考偏好下至少有两个可见项时获得组披露。进度文字或命令行结束该片段,单项活动直接使用自身披露,被隐藏的思考不会制造多余组;Task 拓扑保持独立。- Bash 和 run 别名被排除在所有过程披露之外——既不属于回合级过程披露,也不属于组——- 而是作为独立行渲染,即使所有组都收起也保持可见;相邻的 Bash 行各自保持独立。+ `keepCommandsExpanded`(默认开启)只决定命令行在该披露内的位置:开启时把 `Bash` 和+ run 别名从组中提取为顶层独立行,相邻调用保持分离;关闭时命令行留在所在组的流程中。+ 两种取值都不会增加披露,也不会让命令行落在回合过程之外。- 活动普通组默认展开,完成时仅在用户未操作的情况下收起;其他已完成组默认收起,而记录过- 失败或被拒工具的未接管活动组会在恢复期间保持展开。这些组默认值不依赖思考偏好。无论- 任何组是否收起,Bash 行都保持可见。+ 失败或被拒工具的未接管活动组会在恢复期间保持展开。这些组默认值不依赖任一偏好。收起+ 回合披露会隐藏其下所有组与命令行,但不会清除它们的选择;重新展开时恢复用户此前展开+ 的组。+- 回合标题按失败、停止、执行中、已完成的优先级显示 `Failed`、`Stopped`、`Running` 或+ `Finished`;执行期间压缩上下文与恢复会各自命名,当前步骤为推理时显示 `Thinking`;+ 转录未记录时长时不显示时长;标题绝不回显当前命令或查询。嵌套组标题与命令行共用它的+ 左边缘,层级由字号和颜色而不是缩进表达。- 条目载荷都不会自动展开:工具调用、托管搜索或计划卡片行在用户打开之前始终只是标题行,包括最后一个活动组的字面最后一项。组的默认展开不变,因此最后一项为思考时绝不会向前回扫。当 `Show thinking` 关闭时,所有条目载荷保持关闭,已完成的推理正文与@@ -719,7 +726,7 @@- 手动操作条目会把所属组标记为用户接管,但不会切换该组。流式更新和完成不会重新打开手动收起,也不会收起包含用户已展开、聚焦或选中内容的容器。只要保留会话窗格仍存在,选择就跨偏好切换、单项变组和重新挂载保留。-- 搜索和导航只打开拥有目标消息的过程片段与活动组,每个显示请求仅应用一次;条目级精确定位不在本次范围内。被偏好隐藏的推理会保持隐藏,直到用户打开 `Show thinking`;关闭搜索不会收起已显示路径。+- 搜索和导航只打开拥有目标消息的回合过程与活动组,每个显示请求仅应用一次;条目级精确定位不在本次范围内。被偏好隐藏的推理会保持隐藏,直到用户打开 `Show thinking`;关闭搜索不会收起已显示路径。- 待处理权限、提问、计划/目标审批及其他操作卡位于隐藏过程之外,始终可达。- 每个披露使用独立按钮、`aria-expanded` 和 `aria-controls`;收起的后代离开 Tab 与无障碍遍历顺序。减少动态效果会禁用非必要标记和 V 形动画。diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 1bf5205a0..20fdd2d13 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -1355,27 +1355,35 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备- **先决条件**:已配置提供商并打开项目;回合可以包含进度文字、多个搜索/工具/思考条目,以及失败或被拒工具。- **步骤**:1) 流式输出进度段落 A、多项搜索片段、进度段落 B,以及带相邻 Bash 行的- 多项命令片段。2) 检查已展开的活动组;在更多输出到达时手动收起该组。3) 完成回合并- 比较未操作与用户接管的组,确认所有组都收起时 Bash 行仍保持可见。4) 展开一个已完成组- 和其中一个条目,复制输出,收起并重新展开该组,再独立打开同级组。5) 分别检查单项片段,- 以及最后一个活动组的字面最后一项为工具/搜索、思考、失败工具和被拒工具。6) 关闭并重新- 打开 `Show thinking`,检查活动思考、失败后恢复及完成状态。7) 在保留窗格内重新挂载行,+ 多项命令片段。2) 检查已展开的活动组;在更多输出到达时手动收起该组。3) 完成回合,+ 确认恰好一个过程披露拥有全部回答前的行;收起它并确认其下的组与命令行一并收起,再+ 重新展开并确认组选择恢复。4) 展开一个已完成组和其中一个条目,复制输出,收起并重新+ 展开该组,再独立打开同级组。5) 切换 `Don't collapse commands` 关闭与开启,检查命令行+ 的渲染位置,同时确认披露数量始终为一个。6) 分别检查单项片段,以及最后一个活动组的+ 字面最后一项为工具/搜索、思考、失败工具和被拒工具。7) 关闭并重新打开+ `Show thinking`,检查活动思考、失败后恢复及完成状态。8) 在保留窗格内重新挂载行,然后重载渲染器并重新打开会话。-- **预期**:按时间顺序排列的可折叠过程片段把末尾回答留在其外。活动组展开,并且只在用户- 未操作时于完成后收起;其他已完成组默认收起。Bash/run 别名被排除在所有过程披露之外,- 即使所有组都收起也保持可见。单项没有组包装。没有任何条目载荷会自动展开:工具/搜索行- 在用户打开之前保持标题行,最后一个活动组的字面最后一项也不例外,而思考项保留自身的- 叶子默认值。当 `Show thinking` 关闭时,活动思考指示器保持可见,已完成的推理正文与摘要- 被隐藏,空的纯思考容器被省略;重新打开时恢复。父级、子级和同级选择彼此独立;- 收起/重新展开父级会保留后代,流式更新和完成不会覆盖用户接管的选择。保留窗格中的重新- 挂载保留选择;渲染器重启重新应用默认值,但工具名称、参数、结果和状态仍会恢复。组标题- 显示有界运行和问题摘要,不会把整个回合标记为失败。+- **预期**:一个回合只渲染一个过程披露,其中包含全部回答前的行,`Bash`/run 行也不例外;+ 末尾回答、助手错误和中止后的末尾文字留在披露之外,待处理操作也一样。活动组默认展开,+ 并且只在用户未操作时于完成后收起;其他已完成组默认收起。收起回合披露会一并收起其下+ 的组与命令行,重新展开则恢复用户的组选择。`Don't collapse commands` 开启(默认)时,+ 命令行作为组旁的顶层独立行渲染,相邻调用保持分离,详情在打开前保持收起;关闭时它们+ 折回所属组。两种取值都不改变披露数量。单项没有组包装。没有任何条目载荷会自动展开:+ 工具/搜索行在用户打开之前保持标题行,最后一个活动组的字面最后一项也不例外,而思考项+ 保留自身的叶子默认值。回合标题按 `Running`、`Finished`、`Stopped` 或 `Failed` 报告+ 结果,失败与停止优先于正常完成,当前步骤为推理时显示 `Thinking`,绝不回显当前命令;+ 转录未记录时长时不显示时长。当 `Show thinking` 关闭时,活动思考指示器保持可见,已完成的+ 推理正文与摘要被隐藏,空的+ 纯思考容器被省略;重新打开时恢复。父级、子级和同级选择彼此独立;收起/重新展开父级+ 会保留后代,流式更新和完成不会覆盖用户接管的选择。保留窗格中的重新挂载保留选择;+ 渲染器重启重新应用默认值,但工具名称、参数、结果和状态仍会恢复。组标题显示有界运行+ 和问题摘要,不会把整个回合标记为失败。- **链接规格**:`04-ux/01-ui-ia.md`、`04-ux/07-ui-design-system.md`、`04-ux/08-component-spec.md`、`04-ux/09-interaction-patterns.md`- **验收**:C(聊天流)、E(工具)、F(持久性)- **里程碑**:M3-- **状态**:草案。2026-09-20 的嵌套披露变更仅把本场景作为静态源码/设计审查的- 预期行为;该范围不新增或运行单元、组件、集成、浏览器、Electron 或 E2E 测试。+- **状态**:草案。单元与样式检查覆盖单披露、命令折叠和标题规则;本场景仍是转录重新加载+ 的预期人工行为。#### E2E-TRANSCRIPT-invalid-utf8-window-remains-readable@@ -9196,26 +9204,33 @@ Follow the [current S3 acceptance scenario](/spec/06-delivery/04-e2e-test-plan#e### E2E-CHAT-turn-process-and-thinking-display- **先决条件:** 一个回合包含进度段落 A、多次搜索及思考、进度段落 B、多条命令及- 思考和最终回答;`Show thinking` 偏好开启与关闭两种状态;旧版消息级转录搜索目标。+ 思考和最终回答;`Show thinking` 偏好开启与关闭两种状态;`Don't collapse commands`+ 偏好开启与关闭两种状态;旧版消息级转录搜索目标。- **步骤:** 确认活动组默认展开,让同一回合在无人操作时完成,并确认组收起。另一个- 回合中,明确展开已完成组,并确认后续更新仍保留该选择。关闭 `Show thinking`,确认- 活动思考指示器仍然可见、已完成的推理行和摘要消失且不残留空的纯思考容器;再重新打开,- 确认已完成的推理行恢复。收起所有组,确认 Bash/run 行仍保持可见。检查嵌套路径,包括- 相互独立的组/条目切换、父级收起与恢复、单项片段、字面最后一项选择、失败/被拒/恢复、- 保留窗格重新挂载、Bash 行保持独立(包括相邻 Bash 行)且其详情在打开前保持收起,以及- 旧版搜索定位。-- **预期:** 按时间顺序排列的可折叠过程片段把最终回答、助手错误、中止后的末尾文字和待处理- 操作留在过程之外。活动组默认展开;未操作的组在回合完成时收起,用户明确选择的状态继续- 保留。这些组默认值不依赖 `Show thinking` 偏好。Bash/run 别名被排除在所有过程披露之外,- 作为独立行渲染,即使所有组都收起也保持可见;相邻 Bash 行各自独立,Bash 行的详情在用户- 打开前保持收起。`Show thinking` 关闭时,活动思考指示器保持可见,已完成的推理行和摘要- 被隐藏,空的纯思考容器被省略;重新打开时恢复。单项没有组。没有任何条目载荷会自动展开:- 工具/搜索行在用户打开之前保持收起,而思考项保留自身的叶子默认值。父级、子级和同级- 状态相互独立;窗格拥有的用户选择跨更新、偏好切换和重新挂载保留,渲染器重启后重新应用- 默认值。搜索只展开拥有目标消息的过程片段和活动组,每个请求应用一次;条目级精确定位不在- 本次范围内,被偏好隐藏的推理会保持隐藏,直到用户打开 `Show thinking`。已保存的- `showThinking` 跨重启保留;缺失值回退到旧版 `thinkingDisplayMode`(`compact` 隐藏,- `detailed`/未知/缺失显示)。+ 回合中,明确展开已完成组,并确认后续更新仍保留该选择;随后收起回合披露并确认组随之+ 收起,再重新展开并确认组选择恢复。关闭 `Show thinking`,确认活动思考指示器仍然可见、+ 已完成的推理行和摘要消失且不残留空的纯思考容器;再重新打开,确认已完成的推理行恢复。+ 关闭 `Don't collapse commands`,确认命令行折回所属组且回合仍只渲染一个披露;再开启,+ 确认独立行恢复。确认标题分别显示执行中、已完成、已停止或失败,执行期间压缩上下文与+ 恢复会各自命名,未记录时长时不显示时长,且绝不回显当前命令。检查嵌套路径,包括相互+ 独立的组/条目切换、父级收起与恢复、单项片段、字面最后一项选择、失败/被拒/恢复、+ 保留窗格重新挂载、命令行详情在打开前保持收起,以及旧版搜索定位。+- **预期:** 一个回合只渲染一个过程披露,包含全部回答前的行,命令行也不例外;最终回答、+ 助手错误、中止后的末尾文字和待处理操作留在披露之外。活动组默认展开;未操作的组在回合+ 完成时收起,用户明确选择的状态继续保留,并在外层披露重新展开时恢复。这些组默认值不+ 依赖 `Show thinking` 偏好。`Don't collapse commands` 开启时,命令行作为组旁的顶层独立+ 行渲染,相邻行保持独立,详情在用户打开前保持收起;关闭时它们折回所属组。两种取值都+ 不改变披露数量。回合标题按执行中、已完成、已停止、失败的顺序报告,失败与停止优先于+ 正常完成,当前步骤为推理时显示 `Thinking`,执行期间压缩上下文和恢复会各自命名,未记录+ 时长时不显示时长,且绝不回显当前命令。嵌套组标题与命令行共用回合标题的左边缘。+ `Show thinking` 关闭时,活动思考指示器+ 保持可见,已完成的推理行和摘要被隐藏,空的纯思考容器被省略;重新打开时恢复。单项没有+ 组。没有任何条目载荷会自动展开:工具/搜索行在用户打开之前保持收起,而思考项保留自身+ 的叶子默认值。父级、子级和同级状态相互独立;窗格拥有的用户选择跨更新、偏好切换和重新+ 挂载保留,渲染器重启后重新应用默认值。搜索只展开拥有目标消息的回合过程和活动组,每个+ 请求应用一次;条目级精确定位不在本次范围内,被偏好隐藏的推理会保持隐藏,直到用户打开+ `Show thinking`。已保存的 `showThinking` 跨重启保留;缺失值回退到旧版+ `thinkingDisplayMode`(`compact` 隐藏,`detailed`/未知/缺失显示)。- **2026-09-20 变更的验证范围:** 本次变更只包含多级折叠与活动组呈现;精确转录搜索定位不在本次范围内,保持原有搜索行为。- **自动化:** `pnpm test:e2e:transcript` 覆盖默认及运行中到完成时的过程披露行为;diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex c5792d558..ab5cdb1f4 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -54,7 +54,7 @@| D656 | 隔离宿主持续拒绝的 outbox 追加,避免整队停摆 | **修订 ADR 0041 / D318 / D444 / D597:当 `session.appendMessage` 或 `session.recordUsage` 返回的错误无法归类为重复消息 ID、`PERMISSION_DENIED:` 毒行或外键孤立行时,不再结束本次 flush,而是在同一 Host 代内按有界退避重试(5 秒起、翻倍、上限 60 秒)。同一队头连续第五次失败后,该追加被移入应用自有的死信文件 `session-message-outbox.dead-letter.json`(保留载荷、sessionId、隔离时间与宿主错误;只保留最新 256 条,超出丢弃最旧并记 warn),随后继续排空后续条目,因此单条被拒追加不再长期占用 FIFO 队头、填满 1024 条上限或导致所有会话写入失败。Host 重启属于新代,会立即重试该队头。隔离条目永不自动重放,`session.delete` 会连同该会话的隔离条目一起删除。协议版本、存储架构与队列文件格式均不变。** | 一条 `stream did not contain valid UTF-8` 追加在队头滞留 14.8 小时,期间 `session.persistence.outbox.is.full` 触发 5990 次,导致所有会话的写入直到重启前全部失败;此前只有三类错误有排空出口,其余错误被永久当作瞬时错误(#1560)。 || D657 | 让内置浏览器打开工作区外的本地文件 | **修订 ADR 0170:通过绝对路径或 `file:` URL 可打开任意已存在的本地普通文件,本地文件页面也可导航到其他已存在的本地文件。相对输入仍以工作区为根;HTTP(S) 页面只保留此前工作区内文件链接的权限。缺失文件、目录与远程文件 authority 仍被阻止。`BrowserPreview` 与 sidecar 继续使用工作区根解析。公开的 `pi.browser.navigate` API 在高风险 `browser.cdp` 权限下采用相同策略。见 ADR 0328、E2E-059、`04-ux/08-component-spec.md` 与 `05-security/01-security.md`。** | 用户需要检查项目外的本地 HTML,而工作区范围内的 Agent 文件工具和远程页面导航仍须保留原有边界(#1627)。 || D659 | 重新打开归档项目后恢复侧栏显示 | **修订 D093 / D455:成功明确激活项目时,清除该规范化路径的渲染层归档标记并持久化,使用户从「项目归档」点击「打开」、通过「添加项目」再次选择同一目录,或打开项目会话后,都能在主页侧边栏看到该项目。仅选择归档详情行而未激活,以及普通会话刷新,都不改变归档状态。不更改 Host/项目/会话存储或协议。见 ADR 0294、E2E-264 与 issue #1653。** | 用户明确重新打开项目后,活动工作区虽已切换,但按路径存储的归档展示标记仍在,导致项目从侧栏隐藏。 |-| D661 | 分段回合过程与独立的思考偏好 | **取代 D633 / D651 与 `turn-process-and-thinking-display` ADR 中记录的 `Detailed` / `Compact` 显示模式行为与单一整体过程披露:回合渲染为按时间顺序排列的可折叠过程片段,Bash 与 run 别名位于所有折叠容器之外(回合级过程披露与任何普通活动组),即使所有组都收起也保持可见,且过程/组折叠默认值不依赖思考偏好。偏好为可选的布尔值 `AppSettings.showThinking`;缺失或非布尔值回退到旧版 `thinkingDisplayMode` 字段(`compact` 隐藏,`detailed`/未知/缺失显示),该旧字段仅为持久化设置兼容性保留。`showThinking` 加入可移植应用字段,因此会像旧字段一样同步;其余 Host 协议、持久化 schema、权限或插件契约不变。见修订后的 ADR、`04-ux/06-settings-ia.md`、`04-ux/08-component-spec.md`、`04-ux/09-interaction-patterns.md` 与 E2E-CHAT-turn-process-and-thinking-display。** | 单一扁平容器让较长的工具/搜索序列难以浏览,并把推理可见性与过程折叠挤进同一个二值开关;独立布尔值加上始终可见的 Bash 行,让命令密集的回合保持可读又不遮挡回答。 |+| D661 | 分段回合过程与独立的思考偏好 *(由 D668 修订)* | **取代 D633 / D651 与 `turn-process-and-thinking-display` ADR 中记录的 `Detailed` / `Compact` 显示模式行为与单一整体过程披露:回合渲染为按时间顺序排列的可折叠过程片段,Bash 与 run 别名位于所有折叠容器之外(回合级过程披露与任何普通活动组),即使所有组都收起也保持可见,且过程/组折叠默认值不依赖思考偏好。偏好为可选的布尔值 `AppSettings.showThinking`;缺失或非布尔值回退到旧版 `thinkingDisplayMode` 字段(`compact` 隐藏,`detailed`/未知/缺失显示),该旧字段仅为持久化设置兼容性保留。`showThinking` 加入可移植应用字段,因此会像旧字段一样同步;其余 Host 协议、持久化 schema、权限或插件契约不变。见修订后的 ADR、`04-ux/06-settings-ia.md`、`04-ux/08-component-spec.md`、`04-ux/09-interaction-patterns.md` 与 E2E-CHAT-turn-process-and-thinking-display。** | 单一扁平容器让较长的工具/搜索序列难以浏览,并把推理可见性与过程折叠挤进同一个二值开关;独立布尔值加上始终可见的 Bash 行,让命令密集的回合保持可读又不遮挡回答。 || D662 | 插件在工作面板 Browser 中打开受范围限制的 HTML | **在 `fs.read` 下新增 `pi.fs.openInBrowser(pathFromRoot)`。宿主执行插件常规的读取路径包含、受保护路径、凭据拒绝名单、声明范围与项目注册文件夹检查;仅接受已存在的 `.html`、`.htm`、`.xhtml` 文件。验证后,Main 请求渲染进程为当前本地会话创建 Browser 资源标签页。Browser 插件必须启用。此操作不授予 `browser.cdp`,不改变 BrowserPreview 或本地文件导航策略,也不新增 host-core 协议或持久化状态。见 ADR 0330、`07-plugins/03-plugin-api.md`、`07-plugins/13-plugin-permissions-matrix.md`、`04-ux/08-component-spec.md` 与 E2E-153。** | 文件管理器需要在应用内预览 HTML;如果授予插件 `browser.cdp`,也会暴露无关的页面检查与控制能力。 |## B. 辅助实现默认值@@ -335,6 +335,7 @@| D602 | 崩溃转储留在数据目录 | **Electron 的 Crashpad 报告器在 `ready` 之前以本地模式启动(`uploadToServer: false`)。转储放在 `<data_dir>/crash-dumps`,而不是 Electron 默认的 `userData` crashDumps 路径,因此 `PI_DESKTOP_DATA_DIR` profile 不会与其它安装共用转储。下一次持有单实例锁的启动会为新于 `crash-dumps.json` 的转储写一条 `diagnostics` 记录,按 Crashpad `ptype` 分类:任一新转储属于 browser/main 进程则为 `error`,已恢复的 renderer/GPU/utility 崩溃为 `warn`。host-core 与 sidecar 崩溃仍走监督器路径。不上传,不改 IPC,不改 schema。** | 崩溃留下的 minidump 无人读取。Crashpad 也会记录已恢复的渲染进程崩溃,因此下次启动用 `error` 声称上次运行已死是错的;而数据目录之外的转储会逃出 `PI_DESKTOP_DATA_DIR` 隔离。 || D619 | 复制公式得到的是它的 TeX 源码 | **仅渲染层:当选区覆盖到渲染出来的公式时,`text/plain` 从 MathML `annotation` 写出——行内 `$…$`,块级 `$$…$$` 独占行,也就是 `lib/latex-math.ts` 把 `\(…\)` 和 `\[…\]` 归一到的那组定界符,且每组定界符都像代码段的围栏那样加长到盖过公式内部出现的最长同字符串——而不是 KaTeX 画的那两棵树。落在公式内部的切口会扩展成整个公式。只有公式被改写:归约后的克隆经由 `Selection.toString()`——复制自己跑的那个序列化器——读回,因此同处一个选区的正文、列表、表格和代码块保留平台自己的读法,包括 `innerText` 会写出、而复制本就会略过的 `user-select: none` 界面零件。不含公式的选区,以及在选区所在位置之外触发的复制,整份交回平台。只写一种 flavour:`text/plain`。接管事件同时丢掉了平台的 `text/html`,且不再写回——归约后的克隆是应用自己的标记,写回去会带上文本读法已略过的 `user-select: none` 界面零件;而改为携带渲染结果则会把每个公式粘贴两遍,因为隐藏 MathML 树的只有 KaTeX 自己的样式表,样式表不会随剪贴板一起走。只有一个由外壳持有的文档级 `copy` 监听器,记录区的右键复制经由同一个模块读取同一个选区。** | 公式粘出来是它的字形,而且每棵渲染树各一份,无法带进 LaTeX 文档或别的 Markdown 编辑器(issue #414)。ADR 0268 当年移除「引用」的理由正是 OS 剪贴板可以替代,那剪贴板就得真的装着源码。 || D620 | pi-ai 内置的 API-key 服务成为命名预设 | **向 `NAMED_ENDPOINT_PRESETS` 新增十五条命名预设——Ant Ling、Baseten、Cerebras、Hugging Face、Meta(`responses`)、MiniMax(国际)、Moonshot AI(国际)、NVIDIA、OpenCode Zen、Vercel AI Gateway、Qwen Token 套餐(`alibaba-token-plan`)、Qwen Token 套餐(中国)、小米 Token 套餐(中国/欧洲/新加坡)——各自使用官方主机名;models.dev 键与 pi-ai 提供方 id 不同的那几条,把 pi-ai id 保留为别名。八个内置提供方仍作例外并写明原因:Amazon Bedrock、Azure OpenAI、Cloudflare AI Gateway、Cloudflare Workers AI、Google Vertex AI(URL 里带账户或区域),GitHub Copilot 与 OpenAI Codex(以厂商账号行提供),以及 Radius(这里的 `pi_messages` 仅限账号)。pi-ai 升级后若某提供方既未被覆盖也不在例外中,`packages/agent-runtime/src/pi-ai-provider-sync.test.ts` 会失败。不改协议、存储或 IPC。** | pi-ai 其他能力本就可达,但服务目录的 API-key 一半靠手工维护,已经跟库自带的提供方列表脱节(ADR 0307)。 |+| D668 | 每回合一个过程披露,并提供命令折叠偏好 | **修订 D661 / `turn-process-and-thinking-display` ADR:每个回合渲染一个顶层过程披露,包含回答前的全部行,`Bash`/run 行也不例外;回答留在披露之外。`Bash` 与 run 别名不再被排除在所有折叠容器之外。可选的布尔值 `AppSettings.keepCommandsExpanded`(缺失即开启)决定命令行是放在其运行所在的组旁,还是留在组内;两种取值都只渲染一个披露。该偏好在渲染时读取,而不是在构建转录条目时读取,因此切换后立即重绘——投影缓存只以消息和压缩为键。披露标题按失败/停止/执行中/已完成的优先级报告,且绝不回显当前条目;披露与它展开的层级共用一条左边缘。`keepCommandsExpanded` 加入可移植应用字段。无 Host 协议、持久化 schema、权限或插件契约变更。见修订后的 ADR、`04-ux/06-settings-ia.md`、`04-ux/08-component-spec.md`、`04-ux/09-interaction-patterns.md` 与 E2E-CHAT-turn-process-and-thinking-display。** | 按时间顺序的分段把同一回合拆成答案上方多个并列披露,而始终可见的命令行也无法被偏好旧分组布局的读者关闭;一个披露加上仅影响展示的偏好同时满足两种需求,且不改变工具收到的内容或持久化内容。 |## M0. 模型目录决策@@ -5488,3 +5489,18 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编- 数量徽标保留运行状态的可发现性,同时避免动画轨道成为默认界面。不需要更改持久化schema 或迁移。设置读取通过渲染层 API 规范化应用这些默认值。见`04-ux/01-ui-ia.md`、`04-ux/06-settings-ia.md` 与 E2E-266。++## 2026-10-21 —— 每回合一个过程披露与命令折叠偏好(D668)++- D668 修订 D661 / `turn-process-and-thinking-display` ADR:每个回合现在渲染一个顶层+ 过程披露,包含回答前的全部行,`Bash`/run 行也不例外。命令行不再是披露的同级;末尾+ 回答、助手错误、中止后的末尾文字和待处理操作面留在披露之外。+- `AppSettings.keepCommandsExpanded`(缺失即开启)决定命令行是提取到其运行所在的组旁,+ 还是留在组内。该偏好在渲染时读取,而不是在构建转录条目时读取,因此切换后立即重绘;+ 两种取值都只渲染一个披露。+- 披露标题按失败/停止/执行中/已完成的优先级报告,执行期间压缩上下文与恢复会各自+ 命名,未记录时长时不显示为零,且绝不回显当前条目。披露与它展开的层级共用一条左边缘。+- `keepCommandsExpanded` 加入可移植应用字段。已由 `apps/desktop/test/turn-process.test.mjs`、+ `apps/desktop/test/transcript-style.test.mjs` 与交互式转录探针覆盖。见修订后的 ADR、+ `04-ux/06-settings-ia.md`、`04-ux/08-component-spec.md`、+ `04-ux/09-interaction-patterns.md` 与 E2E-CHAT-turn-process-and-thinking-display。diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex a65c32271..a8de52988 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -604,6 +604,14 @@ export const de = {"processedFor": "Verarbeitet für {{time}}","thinkingFor": "Nachdenken · {{time}}","thoughtFor": "Nachgedacht für {{time}}",+ "processRunning": "Läuft",+ "processRunningFor": "Läuft · {{time}}",+ "processCompleted": "Abgeschlossen",+ "processCompletedFor": "Abgeschlossen in {{time}}",+ "processStopped": "Gestoppt",+ "processStoppedFor": "Gestoppt nach {{time}}",+ "processFailed": "Fehlgeschlagen",+ "processFailedFor": "Fehlgeschlagen nach {{time}}","waitingForModel": "Warten auf Modell","startingTurn": "Wird gestartet…","preparingNextRequest": "Nächste Anfrage wird vorbereitet…",@@ -628,6 +636,7 @@ export const de = {"activityIncludesThinking": "Enthält Denken","activityFailures": "{{count}} Problem","activityFailures_other": "{{count}} Probleme",+ "collapseTurnProcess": "Gesamten Turn-Prozess einklappen","collapseProcess": "Prozess einklappen","collapseActivityGroup": "Aktivitätsgruppe einklappen","collapseToolOutput": "Tool-Ausgabe einklappen",@@ -1446,6 +1455,8 @@ sklm: {"thinkingDisplayCompact": "Kompakt","showThinking": "Denkprozess anzeigen","showThinkingDesc": "Zeigt den Denkprozess des Modells. Wenn aus, bleibt die Live-Denk-Anzeige sichtbar und abgeschlossene Denkzeilen und Auszüge werden ausgeblendet.",+ "keepCommandsExpanded": "Befehle nicht einklappen",+ "keepCommandsExpandedDesc": "Shell-Aufrufe bleiben in eigenen Zeilen, statt in die umgebende Werkzeuggruppe eingeklappt zu werden.","contextUsageDisplay": "Kontextnutzung-Anzeige","contextUsageDisplayRemaining": "Verbleibend","contextUsageDisplayUsed": "Verwendet",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex c909a95c2..4cd59d3c2 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -616,6 +616,14 @@ export const en = {processedFor: "Processed for {{time}}",thinkingFor: "Thinking · {{time}}",thoughtFor: "Thought for {{time}}",+ processRunning: "Running",+ processRunningFor: "Running · {{time}}",+ processCompleted: "Finished",+ processCompletedFor: "Finished in {{time}}",+ processStopped: "Stopped",+ processStoppedFor: "Stopped after {{time}}",+ processFailed: "Failed",+ processFailedFor: "Failed after {{time}}",waitingForModel: "Waiting for model",startingTurn: "Starting…",preparingNextRequest: "Preparing next request…",@@ -640,6 +648,7 @@ export const en = {activityIncludesThinking: "Includes thinking",activityFailures: "{{count}} issue",activityFailures_other: "{{count}} issues",+ collapseTurnProcess: "Collapse the whole turn's process",collapseProcess: "Collapse process",collapseActivityGroup: "Collapse activity group",collapseToolOutput: "Collapse tool output",@@ -1460,6 +1469,8 @@ sklm: {thinkingDisplayCompact: "Compact",showThinking: "Show thinking",showThinkingDesc: "Show the model's reasoning. Off keeps the live thinking indicator visible and hides completed reasoning rows and excerpts.",+ keepCommandsExpanded: "Don't collapse commands",+ keepCommandsExpandedDesc: "Keep shell calls on their own rows instead of folding them into the surrounding tool group.",contextUsageDisplay: "Context usage readout",contextUsageDisplayRemaining: "Remaining",contextUsageDisplayUsed: "Used",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 7d64be7d7..e36c4cf05 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -604,6 +604,14 @@ export const es = {"processedFor": "Procesado durante {{time}}","thinkingFor": "Pensando · {{time}}","thoughtFor": "Pensado durante {{time}}",+ "processRunning": "Ejecutando",+ "processRunningFor": "Ejecutando · {{time}}",+ "processCompleted": "Completado",+ "processCompletedFor": "Completado en {{time}}",+ "processStopped": "Detenido",+ "processStoppedFor": "Detenido tras {{time}}",+ "processFailed": "Fallido",+ "processFailedFor": "Fallido tras {{time}}","waitingForModel": "Esperando modelo","startingTurn": "Iniciando…","preparingNextRequest": "Preparando la siguiente solicitud…",@@ -628,6 +636,7 @@ export const es = {"activityIncludesThinking": "Incluye razonamiento","activityFailures": "{{count}} problema","activityFailures_other": "{{count}} problemas",+ "collapseTurnProcess": "Contraer el proceso del turno completo","collapseProcess": "Contraer proceso","collapseActivityGroup": "Contraer grupo de actividad","collapseToolOutput": "Contraer salida de herramienta",@@ -1446,6 +1455,8 @@ sklm: {"thinkingDisplayCompact": "Compacto","showThinking": "Mostrar razonamiento","showThinkingDesc": "Muestra el razonamiento del modelo. Desactivado, el indicador de razonamiento en vivo sigue visible y las filas y extractos de razonamiento completados quedan ocultos.",+ "keepCommandsExpanded": "No plegar los comandos",+ "keepCommandsExpandedDesc": "Las llamadas de shell se mantienen en filas propias en lugar de plegarse en el grupo de herramientas contiguo.","contextUsageDisplay": "Lectura del uso del contexto","contextUsageDisplayRemaining": "Restante","contextUsageDisplayUsed": "Usado",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 2b6e2056f..c3f39ca01 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -604,6 +604,14 @@ export const fr = {"processedFor": "Traité pendant {{time}}","thinkingFor": "Réflexion · {{time}}","thoughtFor": "Pensé pendant {{time}}",+ "processRunning": "En cours",+ "processRunningFor": "En cours · {{time}}",+ "processCompleted": "Terminé",+ "processCompletedFor": "Terminé en {{time}}",+ "processStopped": "Arrêté",+ "processStoppedFor": "Arrêté après {{time}}",+ "processFailed": "Échec",+ "processFailedFor": "Échec après {{time}}","waitingForModel": "En attente du modèle","startingTurn": "Démarrage…","preparingNextRequest": "Préparation de la prochaine requête…",@@ -628,6 +636,7 @@ export const fr = {"activityIncludesThinking": "Inclut le raisonnement","activityFailures": "{{count}} problème","activityFailures_other": "{{count}} problèmes",+ "collapseTurnProcess": "Réduire le processus du tour complet","collapseProcess": "Réduire le processus","collapseActivityGroup": "Réduire le groupe d'activité","collapseToolOutput": "Réduire la sortie de l'outil",@@ -1446,6 +1455,8 @@ sklm: {"thinkingDisplayCompact": "Compact","showThinking": "Afficher le raisonnement","showThinkingDesc": "Affiche le raisonnement du modèle. Désactivé, l'indicateur de raisonnement en direct reste visible et les lignes et extraits de raisonnement terminés sont masqués.",+ "keepCommandsExpanded": "Ne pas replier les commandes",+ "keepCommandsExpandedDesc": "Les appels shell restent sur leurs propres lignes au lieu d'être repliés dans le groupe d'outils voisin.","contextUsageDisplay": "Affichage de l'usage du contexte","contextUsageDisplayRemaining": "Restant","contextUsageDisplayUsed": "Utilisé",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 6c9edfcb8..483452762 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -613,6 +613,14 @@ export const ko = {processedFor: "{{time}} 동안 처리됨",thinkingFor: "생각 중 · {{time}}",thoughtFor: "{{time}} 동안 생각함",+ processRunning: "실행 중",+ processRunningFor: "실행 중 · {{time}}",+ processCompleted: "실행 완료",+ processCompletedFor: "실행 완료, {{time}}",+ processStopped: "중지됨",+ processStoppedFor: "중지됨, {{time}}",+ processFailed: "실패",+ processFailedFor: "실패, {{time}}",waitingForModel: "모델 대기 중",startingTurn: "시작하는 중…",preparingNextRequest: "다음 요청 준비 중…",@@ -637,6 +645,7 @@ export const ko = {activityIncludesThinking: "생각 포함",activityFailures: "문제 {{count}}개",activityFailures_other: "문제 {{count}}개",+ collapseTurnProcess: "전체 턴 처리 과정 접기",collapseProcess: "처리 과정 접기",collapseActivityGroup: "활동 그룹 접기",collapseToolOutput: "도구 출력 접기",@@ -1456,6 +1465,8 @@ sklm: {thinkingDisplayCompact: "간결",showThinking: "사고 과정 표시",showThinkingDesc: "모델의 사고 과정을 표시합니다. 끄면 실시간 사고 표시기는 계속 보이고 완료된 사고 행과 발췌는 숨겨집니다.",+ keepCommandsExpanded: "명령 접지 않기",+ keepCommandsExpandedDesc: "셸 호출을 주변 도구 그룹에 접지 않고 자체 행으로 유지합니다.",contextUsageDisplay: "컨텍스트 사용량 표시",contextUsageDisplayRemaining: "남음",contextUsageDisplayUsed: "사용됨",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex e02ec85b1..e4d19e8e1 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -603,6 +603,14 @@ export const ptBR = {processedFor: "Processado durante {{time}}",thinkingFor: "Pensando · {{time}}",thoughtFor: "Pensado durante {{time}}",+ processRunning: "Executando",+ processRunningFor: "Executando · {{time}}",+ processCompleted: "Concluído",+ processCompletedFor: "Concluído em {{time}}",+ processStopped: "Interrompido",+ processStoppedFor: "Interrompido após {{time}}",+ processFailed: "Falhou",+ processFailedFor: "Falhou após {{time}}",waitingForModel: "Aguardando o modelo…",startingTurn: "Iniciando…",preparingNextRequest: "Preparando próxima solicitação…",@@ -627,6 +635,7 @@ export const ptBR = {activityIncludesThinking: "Inclui raciocínio",activityFailures: "{{count}} problema",activityFailures_other: "{{count}} problemas",+ collapseTurnProcess: "Recolher o processo do turno inteiro",collapseProcess: "Recolher processo",collapseActivityGroup: "Recolher grupo de atividades",collapseToolOutput: "Recolher saída da ferramenta",@@ -1419,6 +1428,8 @@ export const ptBR = {thinkingDisplayCompact: "Compacto",showThinking: "Mostrar raciocínio",showThinkingDesc: "Mostra o raciocínio do modelo. Quando desativado, o indicador de raciocínio ao vivo continua visível e as linhas e trechos de raciocínio concluídos ficam ocultos.",+ keepCommandsExpanded: "Não recolher comandos",+ keepCommandsExpandedDesc: "As chamadas de shell ficam em linhas próprias em vez de serem recolhidas no grupo de ferramentas ao redor.",contextUsageDisplay: "Indicador de uso do contexto",contextUsageDisplayRemaining: "Restante",contextUsageDisplayUsed: "Usado",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 8b2d02e32..4f3ef8364 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -613,6 +613,14 @@ export const tr = {processedFor: "{{time}} işlendi",thinkingFor: "Düşünülüyor · {{time}}",thoughtFor: "{{time}} düşünüldü",+ processRunning: "Çalışıyor",+ processRunningFor: "Çalışıyor · {{time}}",+ processCompleted: "Tamamlandı",+ processCompletedFor: "{{time}} içinde tamamlandı",+ processStopped: "Durduruldu",+ processStoppedFor: "{{time}} sonra durduruldu",+ processFailed: "Başarısız",+ processFailedFor: "{{time}} sonra başarısız",waitingForModel: "Model bekleniyor",startingTurn: "Başlatılıyor…",preparingNextRequest: "Sonraki istek hazırlanıyor…",@@ -637,6 +645,7 @@ export const tr = {activityIncludesThinking: "Düşünmeyi içerir",activityFailures: "{{count}} sorun",activityFailures_other: "{{count}} sorun",+ collapseTurnProcess: "Tüm tur işlemini daralt",collapseProcess: "İşlemi daralt",collapseActivityGroup: "Etkinlik grubunu daralt",collapseToolOutput: "Araç çıktısını daralt",@@ -1450,6 +1459,8 @@ sklm: {thinkingDisplayCompact: "Sade",showThinking: "Düşünmeyi göster",showThinkingDesc: "Modelin düşünmesini gösterir. Kapalıyken canlı düşünme göstergesi görünür kalır; tamamlanan düşünme satırları ve alıntılar gizlenir.",+ keepCommandsExpanded: "Komutları katlama",+ keepCommandsExpandedDesc: "Kabuk çağrıları, çevresindeki araç grubuna katlanmak yerine kendi satırlarında kalır.",contextUsageDisplay: "Bağlam kullanımı göstergesi",contextUsageDisplayRemaining: "Kalan",contextUsageDisplayUsed: "Kullanılan",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex cf25670f7..fe9dd50d8 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -609,6 +609,14 @@ export const zhCN = {processedFor: "已处理 {{time}}",thinkingFor: "思考中 · {{time}}",thoughtFor: "已思考 {{time}}",+ processRunning: "执行中",+ processRunningFor: "执行中 · {{time}}",+ processCompleted: "运行完成",+ processCompletedFor: "运行完成,{{time}}",+ processStopped: "已停止",+ processStoppedFor: "已停止,{{time}}",+ processFailed: "失败",+ processFailedFor: "失败,{{time}}",waitingForModel: "等待模型响应",startingTurn: "正在开始…",preparingNextRequest: "正在准备下一次请求…",@@ -633,6 +641,7 @@ export const zhCN = {activityIncludesThinking: "包含思考",activityFailures: "{{count}} 个问题",activityFailures_other: "{{count}} 个问题",+ collapseTurnProcess: "折叠整轮处理过程",collapseProcess: "折叠处理过程",collapseActivityGroup: "折叠活动分组",collapseToolOutput: "折叠工具输出",@@ -1440,6 +1449,8 @@ sklm: {thinkingDisplayCompact: "精简",showThinking: "显示思考",showThinkingDesc: "显示模型的推理内容。关闭后仍显示实时思考指示器,并隐藏已完成的推理行和摘要。",+ keepCommandsExpanded: "命令不折叠",+ keepCommandsExpandedDesc: "命令行单独成行显示,不并入上下文的工具分组。",contextUsageDisplay: "上下文用量读数",contextUsageDisplayRemaining: "剩余",contextUsageDisplayUsed: "已用",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex bd3286669..1f13023ed 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -609,6 +609,14 @@ export const zhTW = {processedFor: "已處理 {{time}}",thinkingFor: "思考中 · {{time}}",thoughtFor: "已思考 {{time}}",+ processRunning: "執行中",+ processRunningFor: "執行中 · {{time}}",+ processCompleted: "執行完成",+ processCompletedFor: "執行完成,{{time}}",+ processStopped: "已停止",+ processStoppedFor: "已停止,{{time}}",+ processFailed: "失敗",+ processFailedFor: "失敗,{{time}}",waitingForModel: "等待模型響應",startingTurn: "正在開始…",preparingNextRequest: "正在準備下一次請求…",@@ -633,6 +641,7 @@ export const zhTW = {activityIncludesThinking: "包含思考",activityFailures: "{{count}} 個問題",activityFailures_other: "{{count}} 個問題",+ collapseTurnProcess: "摺疊整輪處理過程",collapseProcess: "摺疊處理過程",collapseActivityGroup: "摺疊活動群組",collapseToolOutput: "摺疊工具輸出",@@ -1440,6 +1449,8 @@ sklm: {thinkingDisplayCompact: "精簡",showThinking: "顯示思考",showThinkingDesc: "顯示模型的推理內容。關閉後仍顯示即時思考指示器,並隱藏已完成的推理列和摘要。",+ keepCommandsExpanded: "指令不折疊",+ keepCommandsExpandedDesc: "指令列單獨成列顯示,不併入上下文的工具分組。",contextUsageDisplay: "上下文用量讀數",contextUsageDisplayRemaining: "剩餘",contextUsageDisplayUsed: "已用",diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.tsindex 133d21482..ce2f9040d 100644--- a/packages/shared/src/types/settings.ts+++ b/packages/shared/src/types/settings.ts@@ -106,6 +106,16 @@ export type AppSettings = {* export, or execution, and it does not control turn-process folding.*/showThinking?: boolean;+ /**+ * Keep shell calls (`Bash`, `exec`, `shell`, …) as their own rows instead of+ * folding them into the surrounding tool group. Absent means `true`, so an+ * existing install keeps today's scannable command rows.+ *+ * The turn's process disclosure itself is not affected: both values render+ * exactly one top-level disclosure per turn. This preference only decides+ * whether a run row sits inside a group or beside it.+ */+ keepCommandsExpanded?: boolean;/*** @deprecated Retained for persisted-settings compatibility. New writes use* `showThinking`; this field is read only as a fallback when `showThinking`diff --git a/scripts/e2e/transcript-disclosure-anchor.tsx b/scripts/e2e/transcript-disclosure-anchor.tsxindex 3aeed2de3..813e13e23 100644--- a/scripts/e2e/transcript-disclosure-anchor.tsx+++ b/scripts/e2e/transcript-disclosure-anchor.tsx@@ -69,11 +69,190 @@ function geometry(scroller: HTMLElement, title: HTMLElement): Geometry {};}-/** Two ticks: one for the observer-driven layout, one for the follow frame. */-async function settle() {- for (let tick = 0; tick < 3; tick += 1) {- await new Promise((resolve) => setTimeout(resolve, 40));- }+type LayoutDirection = "initial" | "grow" | "shrink" | "change";++type LayoutHistoryEntry = {+ phase: "baseline" | "resize" | "frame";+ at: number;+ contentHeight: number;+ expected: boolean;+ geometry: Geometry;+};++function contentHeight(content: HTMLElement): number {+ return content.getBoundingClientRect().height;+}++function observedBorderBoxHeight(entry: ResizeObserverEntry): number {+ const borderBox = entry.borderBoxSize?.[0];+ return borderBox ? borderBox.blockSize : entry.contentRect.height;+}++function geometrySnapshot(sample: Geometry): string {+ return [+ sample.scrollTop,+ sample.scrollHeight,+ sample.clientHeight,+ sample.titleTop,+ sample.distanceFromBottom,+ ]+ .map((value) => Math.round(value * 1000) / 1000)+ .join(",");+}++function layoutTransitioned(+ direction: LayoutDirection,+ baselineHeight: number,+ observedHeight: number,+): boolean {+ const delta = observedHeight - baselineHeight;+ if (direction === "initial") return observedHeight > 0;+ if (direction === "grow") return delta > 0.5;+ if (direction === "shrink") return delta < -0.5;+ return Math.abs(delta) > 0.5;+}++/**+ * A real layout barrier for one fixture action.+ *+ * It is armed before `trigger`, on the owning content's border box: the same+ * element the product observes. Once the delivered content resize matches the+ * expected disclosure state and direction, geometry is sampled in an animation+ * frame scheduled from that delivery, and must hold for two consecutive frames.+ * Any later resize cancels that window. The watchdog only bounds a hung+ * fixture; it never retries the product assertion, so a mismatch reported after+ * this returns is witnessed after the layout correction, not before it.+ */+async function waitForLayout({+ label,+ scroller,+ content,+ title,+ expected,+ direction,+ trigger,+ timeoutMs = 10_000,+}: {+ label: string;+ scroller: HTMLElement;+ content: HTMLElement;+ title: HTMLElement;+ expected: () => boolean;+ direction: LayoutDirection;+ trigger?: () => void;+ timeoutMs?: number;+}): Promise<void> {+ const baselineHeight = contentHeight(content);+ const history: LayoutHistoryEntry[] = [];+ const record = (phase: LayoutHistoryEntry["phase"], height: number) => {+ history.push({+ phase,+ at: Math.round(performance.now()),+ contentHeight: Math.round(height * 100) / 100,+ expected: expected(),+ geometry: geometry(scroller, title),+ });+ if (history.length > 48) history.splice(0, history.length - 48);+ };+ record("baseline", baselineHeight);++ let targetSeen = false;+ let stableFrames = 0;+ let lastSignature = "";+ let frame = 0;+ let watchdog = 0;+ let finished = false;+ let observer: ResizeObserver | null = null;++ const cleanup = () => {+ if (watchdog !== 0) window.clearTimeout(watchdog);+ watchdog = 0;+ cancelAnimationFrame(frame);+ frame = 0;+ observer?.disconnect();+ observer = null;+ };++ await new Promise<void>((resolve, reject) => {+ const fail = (reason: string) => {+ if (finished) return;+ finished = true;+ cleanup();+ let current: { contentHeight: number; geometry: Geometry } | null = null;+ try {+ current = {+ contentHeight: Math.round(contentHeight(content) * 100) / 100,+ geometry: geometry(scroller, title),+ };+ } catch {+ // Keep the history from before the owning elements disappeared.+ }+ reject(new Error(+ `${label}: ${reason}; ${JSON.stringify({+ direction,+ baselineHeight,+ targetSeen,+ expected: expected(),+ current,+ history,+ })}`,+ ));+ };++ const sample = () => {+ frame = 0;+ if (finished) return;+ const height = contentHeight(content);+ record("frame", height);+ const signature = geometrySnapshot(geometry(scroller, title));+ if (signature === lastSignature) {+ stableFrames += 1;+ } else {+ lastSignature = signature;+ stableFrames = 1;+ }+ if (stableFrames >= 2) {+ finished = true;+ cleanup();+ resolve();+ return;+ }+ frame = requestAnimationFrame(sample);+ };++ const instance = new ResizeObserver((entries) => {+ if (finished) return;+ const entry = entries[entries.length - 1];+ const height = observedBorderBoxHeight(entry);+ record("resize", height);+ stableFrames = 0;+ lastSignature = "";+ if (+ !targetSeen &&+ expected() &&+ layoutTransitioned(direction, baselineHeight, height)+ ) {+ targetSeen = true;+ }+ if (targetSeen && frame === 0) frame = requestAnimationFrame(sample);+ });+ observer = instance;++ watchdog = window.setTimeout(() => {+ fail(targetSeen+ ? "geometry did not hold for two consecutive frames after the resize"+ : `no ${direction} content resize was delivered`);+ }, timeoutMs);++ instance.observe(content, { box: "border-box" });+ try {+ trigger?.();+ } catch (error) {+ finished = true;+ cleanup();+ reject(error);+ }+ });}/**@@ -82,7 +261,17 @@ async function settle() {* viewport. Only the app's stylesheet is left out, so the geometry comes from* inline sizes and the real components' intrinsic height.*/-function TranscriptFixture({ messages, process = false, isActive = false }: { messages: UiMessage[]; process?: boolean; isActive?: boolean }) {+function TranscriptFixture({+ messages,+ process = false,+ isActive = false,+ sessionId = "fixture",+}: {+ messages: UiMessage[];+ process?: boolean;+ isActive?: boolean;+ sessionId?: string;+}) {const entry = process ? buildTranscriptEntries(messages).entries.find((item) => item.kind === "assistant-turn") : undefined;const {scrollRef,@@ -91,7 +280,7 @@ function TranscriptFixture({ messages, process = false, isActive = false }: { mehandleScroll,disclosureAnchorNotifier,} = useTranscriptScroll({- sessionId: "fixture",+ sessionId,messages,hasMoreBefore: false,isRunning: false,@@ -113,7 +302,7 @@ function TranscriptFixture({ messages, process = false, isActive = false }: { meclassName="thread-scroll"data-scroll-owner="transcript"onScroll={handleScroll}- style={{ height: "100%", overflowY: "auto" }}+ style={{ height: "100%", overflowY: "auto", overflowAnchor: "none" }}><div ref={contentRef} className="thread-content"><div style={{ height: 700 }} />@@ -139,9 +328,9 @@ function FollowFixture({ tool }: { tool: UiMessage }) {className="subagent-run-rows"data-scroll-owner="follow"onScroll={handleScroll}- style={{ height: "300px", overflowY: "auto" }}+ style={{ height: "300px", overflowY: "auto", overflowAnchor: "none" }}>- <div ref={contentRef}>+ <div ref={contentRef} data-layout-content="dock"><div style={{ height: 320 }} /><ToolRow message={tool} /><div style={{ height: 200 }} />@@ -192,11 +381,20 @@ globalThis.transcriptDisclosureProbe = async () => {/>,);const scroller = container.querySelector<HTMLElement>(".thread-scroll");+ const content = container.querySelector<HTMLElement>(".thread-content");const title = container.querySelector<HTMLElement>(".tool-row-header");assert(scroller, "the transcript scroller did not render");+ assert(content, "the transcript content did not render");assert(title, "the tool title did not render");- await settle();+ await waitForLayout({+ label: "transcript mount",+ scroller,+ content,+ title,+ expected: () => title.isConnected,+ direction: "initial",+ });const before = geometry(scroller, title);assert(Math.abs(before.distanceFromBottom) < 1,@@ -208,8 +406,15 @@ globalThis.transcriptDisclosureProbe = async () => {);// A plain click on the title, exactly as a reader expands a tool row.- title.click();- await settle();+ await waitForLayout({+ label: "transcript tool expansion",+ scroller,+ content,+ title,+ expected: () => title.getAttribute("aria-expanded") === "true",+ direction: "grow",+ trigger: () => title.click(),+ });const expanded = geometry(scroller, title);assert(expanded.scrollHeight > before.scrollHeight + 100,@@ -224,8 +429,15 @@ globalThis.transcriptDisclosureProbe = async () => {`expanding the tool re-bottomed the transcript: ${JSON.stringify({ before, expanded })}`,);- title.click();- await settle();+ await waitForLayout({+ label: "transcript tool collapse",+ scroller,+ content,+ title,+ expected: () => title.getAttribute("aria-expanded") === "false",+ direction: "shrink",+ trigger: () => title.click(),+ });const collapsed = geometry(scroller, title);assert(Math.abs(collapsed.titleTop - before.titleTop) < 2,@@ -243,16 +455,34 @@ globalThis.transcriptDisclosureProbe = async () => {const dockTitle = dockContainer.querySelector<HTMLElement>(".tool-row-header",);+ const dockContent = dockContainer.querySelector<HTMLElement>(+ "[data-layout-content='dock']",+ );assert(dockScroller, "the dock scroller did not render");+ assert(dockContent, "the dock content did not render");assert(dockTitle, "the dock tool title did not render");- await settle();+ await waitForLayout({+ label: "dock mount",+ scroller: dockScroller,+ content: dockContent,+ title: dockTitle,+ expected: () => dockTitle.isConnected,+ direction: "initial",+ });const dockBefore = geometry(dockScroller, dockTitle);assert(Math.abs(dockBefore.distanceFromBottom) < 1,`the dock did not start pinned to the bottom: ${JSON.stringify(dockBefore)}`,);- dockTitle.click();- await settle();+ await waitForLayout({+ label: "dock tool expansion",+ scroller: dockScroller,+ content: dockContent,+ title: dockTitle,+ expected: () => dockTitle.getAttribute("aria-expanded") === "true",+ direction: "grow",+ trigger: () => dockTitle.click(),+ });const dockExpanded = geometry(dockScroller, dockTitle);assert(dockExpanded.scrollHeight > dockBefore.scrollHeight + 100,@@ -282,23 +512,51 @@ globalThis.transcriptDisclosureProbe = async () => {const renderProcess = (isActive: boolean) => flushSync(() =>processRoot.render(<I18nextProvider i18n={i18n}>- <TranscriptFixture process isActive={isActive} messages={processMessages} />+ <TranscriptFixture+ process+ isActive={isActive}+ messages={processMessages}+ sessionId="process-fixture"+ /></I18nextProvider>,),);renderProcess(true);const processScroller = processContainer.querySelector<HTMLElement>(".thread-scroll");+ const processContent = processContainer.querySelector<HTMLElement>(".thread-content");const processTitle = processContainer.querySelector<HTMLElement>(".turn-process > button");- assert(processScroller && processTitle, "process fixture did not render");- await settle();+ assert(processScroller && processContent && processTitle, "process fixture did not render");+ await waitForLayout({+ label: "process mount",+ scroller: processScroller,+ content: processContent,+ title: processTitle,+ expected: () => processTitle.getAttribute("aria-expanded") === "true",+ direction: "initial",+ });const processBefore = geometry(processScroller, processTitle);assert(processTitle.getAttribute("aria-expanded") === "true","an active detailed process should start open",);- renderProcess(false);- await settle();+ assert(+ Math.abs(processBefore.distanceFromBottom) < 1,+ `the process fixture did not start pinned to the bottom: ${JSON.stringify(processBefore)}`,+ );+ await waitForLayout({+ label: "process automatic collapse",+ scroller: processScroller,+ content: processContent,+ title: processTitle,+ expected: () => processTitle.getAttribute("aria-expanded") === "false",+ direction: "shrink",+ trigger: () => renderProcess(false),+ });const processCollapsed = geometry(processScroller, processTitle);+ assert(+ processCollapsed.titleTop >= 0 && processCollapsed.titleTop < 600,+ `the process title is not on screen for the expansion test: ${JSON.stringify(processCollapsed)}`,+ );assert(processTitle.getAttribute("aria-expanded") === "false",`an untouched process should collapse when its turn completes (expanded=${processTitle.getAttribute("aria-expanded")}, active=${processContainer.querySelector(".turn-process")?.classList.contains("active") ?? false}, bodyHidden=${processContainer.querySelector<HTMLElement>(".turn-process-body")?.hidden ?? true}, focusInside=${processContainer.querySelector(".turn-process-body")?.contains(document.activeElement) ?? false}, selected=${window.getSelection()?.isCollapsed === false})`,@@ -307,8 +565,15 @@ globalThis.transcriptDisclosureProbe = async () => {processCollapsed.scrollHeight < processBefore.scrollHeight - 100,"completed process content remained visible",);- processTitle.click();- await settle();+ await waitForLayout({+ label: "process manual expansion",+ scroller: processScroller,+ content: processContent,+ title: processTitle,+ expected: () => processTitle.getAttribute("aria-expanded") === "true",+ direction: "grow",+ trigger: () => processTitle.click(),+ });const processExpanded = geometry(processScroller, processTitle);assert(processTitle.getAttribute("aria-expanded") === "true",@@ -322,19 +587,96 @@ globalThis.transcriptDisclosureProbe = async () => {// anchor has to compensate; the automatic collapse above may legitimately clamp.assert(Math.abs(processExpanded.titleTop - processCollapsed.titleTop) < 2,- "process expansion moved its title",+ `process expansion moved its title by ${processExpanded.titleTop - processCollapsed.titleTop}px: ${JSON.stringify({ processBefore, processCollapsed, processExpanded })}`,);+ // Both renders are flushSync commits and this check reads state only, so it+ // needs no layout barrier.renderProcess(true);renderProcess(false);- await settle();assert(processTitle.getAttribute("aria-expanded") === "true","a user-expanded process should stay open after completion",);++ // A fresh process starts active. Its automatic collapse and the reader's+ // immediate manual expansion commit in the same task, so the pending+ // collapse layout and follow work must not drag the clicked title away.+ const rapidContainer = document.createElement("div");+ rapidContainer.style.height = "600px";+ rapidContainer.style.width = "640px";+ host.append(rapidContainer);+ const rapidRoot = createRoot(rapidContainer, {+ onUncaughtError: (error) => renderErrors.push(error),+ });+ roots.push(rapidRoot);+ const renderRapid = (isActive: boolean) => flushSync(() =>+ rapidRoot.render(+ <I18nextProvider i18n={i18n}>+ <TranscriptFixture+ process+ isActive={isActive}+ messages={processMessages}+ sessionId="rapid-process-fixture"+ />+ </I18nextProvider>,+ ),+ );+ renderRapid(true);+ const rapidScroller = rapidContainer.querySelector<HTMLElement>(".thread-scroll");+ const rapidContent = rapidContainer.querySelector<HTMLElement>(".thread-content");+ const rapidTitle = rapidContainer.querySelector<HTMLElement>(".turn-process > button");+ assert(rapidScroller && rapidContent && rapidTitle, "rapid process fixture did not render");+ await waitForLayout({+ label: "rapid process mount",+ scroller: rapidScroller,+ content: rapidContent,+ title: rapidTitle,+ expected: () => rapidTitle.getAttribute("aria-expanded") === "true",+ direction: "initial",+ });+ const rapidBefore = geometry(rapidScroller, rapidTitle);+ assert(+ Math.abs(rapidBefore.distanceFromBottom) < 1,+ `the rapid process did not start pinned to the bottom: ${JSON.stringify(rapidBefore)}`,+ );+ const rapid = {+ collapsedHeight: 0,+ atExpansion: null as Geometry | null,+ };+ await waitForLayout({+ label: "rapid automatic collapse then immediate manual expansion",+ scroller: rapidScroller,+ content: rapidContent,+ title: rapidTitle,+ expected: () => rapidTitle.getAttribute("aria-expanded") === "true",+ direction: "change",+ trigger: () => {+ renderRapid(false);+ rapid.collapsedHeight = rapidScroller.scrollHeight;+ rapidTitle.click();+ rapid.atExpansion = geometry(rapidScroller, rapidTitle);+ },+ });+ const rapidExpanded = geometry(rapidScroller, rapidTitle);+ assert(+ rapidTitle.getAttribute("aria-expanded") === "true",+ "the immediate manual expansion should win over the automatic collapse",+ );+ assert(+ rapid.collapsedHeight > 0 && rapidExpanded.scrollHeight > rapid.collapsedHeight + 100,+ `the rapid manual expansion did not restore the process height: ${JSON.stringify({ rapidBefore, rapidExpanded, collapsedHeight: rapid.collapsedHeight })}`,+ );+ assert(rapid.atExpansion, "the rapid expansion did not record its click geometry");+ assert(+ Math.abs(rapidExpanded.titleTop - rapid.atExpansion.titleTop) < 2,+ `pending collapse work moved the rapidly expanded title by ${rapidExpanded.titleTop - rapid.atExpansion.titleTop}px: ${JSON.stringify({ rapidBefore, atExpansion: rapid.atExpansion, rapidExpanded })}`,+ );+assert(renderErrors.length === 0, `React render errors: ${renderErrors.map(String).join("; ")}`);return {ok: true,process: { before: processBefore, collapsed: processCollapsed, expanded: processExpanded },+ rapid: { before: rapidBefore, expanded: rapidExpanded },transcript: { before, expanded, collapsed },dock: { before: dockBefore, expanded: dockExpanded },};diff --git a/scripts/e2e/transcript-render.tsx b/scripts/e2e/transcript-render.tsxindex af9a818c9..d3ce4d7d8 100644--- a/scripts/e2e/transcript-render.tsx+++ b/scripts/e2e/transcript-render.tsx@@ -511,7 +511,7 @@ globalThis.transcriptRenderProbe = async () => {);// A standalone Bash row is not an activity group: it updates through its own- // rendered command, outside every process disclosure.+ // rendered command, as a row of the turn's single process disclosure.const bashMessages = (command: string): UiMessage[] => [message("bash-user", "user", "Run"),message("bash-row", "tool", "", {@@ -526,8 +526,11 @@ globalThis.transcriptRenderProbe = async () => {const bashRow = container.querySelector<HTMLElement>('[data-message-id="bash-row"]');assert(bashRow, "the standalone Bash row did not render");assert(- bashRow.closest(".turn-process") === null,- "the Bash row must render outside every process disclosure",+ bashRow.closest(".turn-process") !== null &&+ bashRow.closest(".turn-process") ===+ container.querySelector(".turn-process") &&+ bashRow.closest(".process-activity-group") === null,+ "the Bash row must render inside the turn's one process, outside every group",);assert(container.textContent?.includes("printf before"), "the Bash command did not render");globalThis.__activityGroupRenders = [];diff --git a/scripts/e2e/turn-process.tsx b/scripts/e2e/turn-process.tsxindex 81ac6af8d..98c5b10dd 100644--- a/scripts/e2e/turn-process.tsx+++ b/scripts/e2e/turn-process.tsx@@ -6,6 +6,7 @@ import { en } from "@pi-desktop/i18n";import type { AppSettings, UiMessage } from "@pi-desktop/shared";import { AssistantTurn } from "../../apps/desktop/src/features/chat/transcript/AssistantTurn";import { ShowThinkingRow } from "../../apps/desktop/src/components/settings/ShowThinkingRow";+import { KeepCommandsExpandedRow } from "../../apps/desktop/src/components/settings/KeepCommandsExpandedRow";import { buildTranscriptEntries } from "../../apps/desktop/src/lib/assistant-turns";import { TranscriptSearchContext } from "../../apps/desktop/src/lib/transcript-search-context";import type { TranscriptSearchTarget } from "../../apps/desktop/src/lib/transcript-reading";@@ -55,6 +56,10 @@ export async function turnProcessProbe() {interpolation: { escapeValue: false },});const container = document.createElement("div");+ // Keep the collapse rail's gutter inside the viewport, like the real+ // .thread-content padding does, so hit testing can address it.+ container.style.cssText =+ "width: 800px; max-width: 100%; padding-left: 32px; box-sizing: border-box;";document.body.append(container);const initialSettings = useAppStore.getState().settings;const baseSettings: AppSettings = {@@ -71,6 +76,7 @@ export async function turnProcessProbe() {onUncaughtError: (error) => errors.push(error),});const notes: string[] = [];+ const metrics: Record<string, unknown> = {};const check = (value: unknown, name: string) => {assert(value, name);notes.push(name);@@ -101,6 +107,44 @@ export async function turnProcessProbe() {const firstProcess = () => container.querySelector<HTMLElement>(".turn-process-body");const visible = (element: Element | null) =>Boolean(element?.getBoundingClientRect().height);+ const leftOf = (element: Element | null) =>+ element?.getBoundingClientRect().left;+ const nearLeft = (left: number | undefined, right: number | undefined) =>+ typeof left === "number" && typeof right === "number" &&+ Math.abs(left - right) < 0.75;+ const pointIn = (element: Element | null) => {+ if (!element) return null;+ const rect = element.getBoundingClientRect();+ return document.elementFromPoint(+ rect.left + Math.min(6, rect.width / 2),+ rect.top + rect.height / 2,+ );+ };+ const owns = (header: Element | null, target: Element | null) =>+ Boolean(header && target && header.contains(target));+ const railHit = (rail: Element | null) => {+ if (!rail) return null;+ const rect = rail.getBoundingClientRect();+ return document.elementFromPoint(+ rect.left + rect.width / 2,+ rect.top + rect.height / 2,+ );+ };+ const rectOf = (element: Element | null) => {+ if (!element) return null;+ const rect = element.getBoundingClientRect();+ return {+ left: rect.left,+ right: rect.right,+ width: rect.width,+ top: rect.top,+ bottom: rect.bottom,+ };+ };+ const fontSize = (element: Element | null) =>+ element ? Number.parseFloat(getComputedStyle(element).fontSize) : NaN;+ const color = (element: Element | null) =>+ element ? getComputedStyle(element).color : "";const click = (element: HTMLElement | null) => {assert(element, "missing click target");flushSync(() => element.click());@@ -136,18 +180,25 @@ export async function turnProcessProbe() {responseDurationMs: 1000,});const mixed = [intro, read, grep, bash1, bash2, edit, answer];+ // No progress paragraph between these rows: the folded group must be one+ // contiguous ordinary stretch around both run rows.+ const contiguous = [read, grep, bash1, bash2, edit, answer];try {- // Bash has no process ancestor and stays visible with every disclosure- // collapsed, even across adjacent calls.+ // One disclosure per turn: the Bash rows are rows inside the turn's process,+ // not siblings of it, so a long turn collapses in one gesture.render(mixed);const bash1Row = row("bash1");const bash2Row = row("bash2");check(Boolean(bash1Row) && Boolean(bash2Row), "both adjacent Bash rows render");check(- bash1Row?.closest(".turn-process") === null &&- bash2Row?.closest(".turn-process") === null,- "no Bash row is inside any turn-process disclosure",+ container.querySelectorAll(".turn-process").length === 1,+ "a turn renders exactly one process disclosure",+ );+ check(+ bash1Row?.closest(".turn-process") !== null &&+ bash2Row?.closest(".turn-process") !== null,+ "every Bash row lives inside that one disclosure",);check(bash1Row?.closest(".turn-run-row") !== null &&@@ -159,15 +210,116 @@ export async function turnProcessProbe() {bash1Row?.closest(".tool-activity-group") === null,"Bash rows are not folded into an activity group",);+ check(+ processHeaders()[0]?.querySelector(".tool-activity-count")?.textContent ===+ i18n.t("chat.processTools", { count: 5 }),+ "the process header counts every tool once",+ );check(allCollapsed(), "the completed process starts fully collapsed");check(- visible(bash1Row) && visible(bash2Row),- "Bash rows stay visible with every disclosure collapsed",+ !visible(bash1Row) && !visible(bash2Row),+ "Bash rows are revealed by the turn's process, not left outside it",);check(!visible(row("read")) && !visible(row("grep")),"non-run work stays inside its collapsed process",);+ // Opening the one top-level disclosure reveals the whole run: the groups and+ // the standalone Bash rows alike.+ click(processHeaders()[0] ?? null);+ check(+ visible(bash1Row) && visible(bash2Row),+ "opening the process reveals the Bash rows",+ );++ // Real geometry and hit testing: the turn title, a nested group title and a+ // Bash row share one left edge, and the collapse rail owns its gutter.+ const topHeader = processHeaders()[0] ?? null;+ const nestedHeader = container.querySelector<HTMLElement>(+ ".process-activity-group.grouped > .tool-activity-header",+ );+ const bashHeader = bash1Row?.querySelector<HTMLElement>(".tool-row-header") ?? null;+ const bashHead = bash1Row?.querySelector<HTMLElement>(".tool-row-head.is-run") ?? null;+ const topIcon = topHeader?.querySelector(".tool-activity-icon") ?? null;+ const nestedIcon = nestedHeader?.querySelector(".tool-activity-icon") ?? null;+ const bashIcon = bashHeader?.querySelector(".tool-row-icon") ?? null;+ const topLabel = topHeader?.querySelector(".tool-activity-label") ?? null;+ const nestedLabel = nestedHeader?.querySelector(".tool-activity-label") ?? null;+ const bashLabel = bashHeader?.querySelector(".tool-row-name") ?? null;+ check(+ nearLeft(leftOf(topIcon), leftOf(nestedIcon)) &&+ nearLeft(leftOf(nestedIcon), leftOf(bashIcon)),+ "turn, group and run icons share one left edge",+ );+ check(+ nearLeft(leftOf(topLabel), leftOf(nestedLabel)) &&+ nearLeft(leftOf(nestedLabel), leftOf(bashLabel)),+ "turn, group and run titles share one text line",+ );+ check(+ nearLeft(leftOf(topHeader), leftOf(nestedHeader)) &&+ nearLeft(leftOf(nestedHeader), leftOf(bashHead)),+ "turn, group and run header fills share one left edge",+ );+ check(+ owns(topHeader, pointIn(topIcon)) &&+ owns(nestedHeader, pointIn(nestedIcon)) &&+ owns(bashHeader, pointIn(bashIcon)),+ "each disclosure header owns its content hit target",+ );+ check(+ fontSize(topLabel) > fontSize(nestedLabel) &&+ fontSize(nestedLabel) === fontSize(bashLabel),+ "the nested group title is smaller than the turn title and matches run-row type",+ );+ check(+ color(topLabel) !== color(nestedLabel) &&+ color(nestedLabel) !== color(bashLabel),+ "the nested group title uses a quieter colour than the turn and run rows",+ );+ const topRail = firstProcess()?.querySelector<HTMLElement>(+ ":scope > .disclosure-collapse-rail",+ ) ?? null;+ check(+ topRail !== null && railHit(topRail) === topRail,+ "the turn collapse rail owns its gutter hit target",+ );+ click(nestedHeader);+ const nestedBody = nestedHeader?.parentElement?.querySelector<HTMLElement>(+ ":scope > .process-activity-body",+ ) ?? null;+ const nestedRail = nestedBody?.querySelector<HTMLElement>(+ ":scope > .disclosure-collapse-rail",+ ) ?? null;+ check(+ nestedRail !== null && railHit(nestedRail) === nestedRail,+ "the nested group collapse rail owns its gutter hit target",+ );+ metrics.desktop = {+ icons: [leftOf(topIcon), leftOf(nestedIcon), leftOf(bashIcon)],+ labels: [leftOf(topLabel), leftOf(nestedLabel), leftOf(bashLabel)],+ headers: [leftOf(topHeader), leftOf(nestedHeader), leftOf(bashHead)],+ turnRail: rectOf(topRail),+ groupRail: rectOf(nestedRail),+ };+ container.style.width = "420px";+ check(+ nearLeft(leftOf(topIcon), leftOf(nestedIcon)) &&+ nearLeft(leftOf(nestedIcon), leftOf(bashIcon)),+ "the shared left edge survives a narrow transcript",+ );+ check(+ topRail !== null && railHit(topRail) === topRail &&+ nestedRail !== null && railHit(nestedRail) === nestedRail,+ "both collapse rails stay usable in a narrow transcript",+ );+ metrics.narrow = {+ icons: [leftOf(topIcon), leftOf(nestedIcon), leftOf(bashIcon)],+ turnRail: rectOf(topRail),+ groupRail: rectOf(nestedRail),+ };+ container.style.width = "800px";+check(bash1Row?.classList.contains("open") !== true,"a Bash row keeps its detail closed until opened",@@ -178,15 +330,44 @@ export async function turnProcessProbe() {"a Bash row opens its own detail on request",);- // A turn of only Bash calls has no process disclosure at all.+ // A turn of only Bash calls still has its single process disclosure: the run+ // rows are what it reveals.render([run("only1", "echo 1"), run("only2", "echo 2")], false, null, "only-bash");check(- container.querySelectorAll(".turn-process").length === 0,- "a Bash-only turn renders no process disclosure",+ container.querySelectorAll(".turn-process").length === 1,+ "a Bash-only turn keeps its one process disclosure",+ );+ check(+ processHeaders()[0]?.getAttribute("aria-expanded") === "false",+ "a completed Bash-only process starts collapsed",+ );+ check(+ processHeaders()[0]?.querySelector(".tool-activity-count")?.textContent ===+ i18n.t("chat.processTools", { count: 2 }),+ "a Bash-only header counts its commands once",);+ click(processHeaders()[0] ?? null);check(visible(row("only1")) && visible(row("only2")),- "both Bash-only rows stay visible",+ "opening it reveals both Bash rows",+ );++ // Progress text without a tool still owns the turn's one process.+ const progressOnly = [+ message("progress-only", "assistant", "Inspecting the workspace", {+ status: "streaming",+ }),+ message("progress-final", "assistant", "Done", { status: "complete" }),+ ];+ render(progressOnly, false, null, "progress-only");+ check(+ container.querySelectorAll(".turn-process").length === 1,+ "a progress-only process keeps its one disclosure",+ );+ click(processHeaders()[0] ?? null);+ check(+ visible(row("progress-only")),+ "opening the progress-only disclosure reveals its text",);// Active process content opens while the turn runs and closes when it stops.@@ -212,12 +393,12 @@ export async function turnProcessProbe() {status: "streaming",});const bashLive = run("bash-live", "pnpm test");- const thinkingLabel = i18n.t("chat.thinkingFor", { time: "" });+ const thinkingLabel = i18n.t("chat.thinking");render([supersededThought, bashLive], true, null, "thinking-to-bash");check(- row("bash-live")?.closest(".turn-process") === null &&- visible(row("bash-live")),- "a Bash row that supersedes thinking stays standalone and visible",+ row("bash-live")?.closest(".turn-run-row") !== null &&+ row("bash-live")?.closest(".process-activity-group") === null,+ "a Bash row that supersedes thinking renders as a standalone run row",);check(!processHeaders().some((header) =>@@ -230,9 +411,9 @@ export async function turnProcessProbe() {setSettings({ showThinking: false });render([supersededThought, bashLive], true, null, "thinking-to-bash-hidden");check(- container.querySelectorAll(".turn-process").length === 0 &&+ container.querySelectorAll(".turn-process").length === 1 &&visible(row("bash-live")),- "hidden superseded thinking leaves no empty process and keeps the Bash row",+ "hidden superseded thinking leaves the run row in the live process",);setSettings();@@ -260,11 +441,15 @@ export async function turnProcessProbe() {);setSettings({ showThinking: false });render([supersededThought2, separateAnswer], true, null, "thinking-to-answer-hidden");+ // The live reasoning indicator is still a visible step of the turn's one+ // disclosure (that is what keeps the indicator), so the disclosure stays.+ // What must not happen is the answer being swallowed or hidden reasoning+ // leaving a row behind.check(- container.querySelectorAll(".turn-process").length === 0 &&+ container.querySelectorAll(".turn-process").length <= 1 &&!container.querySelector(".thinking") &&Boolean(row("stream-answer")),- "hidden thinking superseded by a separate answer leaves no empty process",+ "hidden thinking superseded by a separate answer stays out of the answer row",);setSettings();@@ -277,10 +462,13 @@ export async function turnProcessProbe() {setSettings({ showThinking: false });render([liveThought], true, null, "thought-off-live");const liveHeader = processHeaders()[0];+ // A live turn whose only row is reasoning still says so, even with completed+ // reasoning hidden: the header answers "what is happening", and hiding the+ // finished rows must not hide that the model is thinking right now.+ const liveLabel = () =>+ liveHeader?.querySelector(".tool-activity-label")?.textContent ?? "";check(- liveHeader?.querySelector(".tool-activity-label")?.textContent?.startsWith(- i18n.t("chat.thinkingFor", { time: "" }),- ),+ liveLabel() === i18n.t("chat.thinking"),"show thinking off keeps the live thinking indicator in the header",);check(@@ -289,10 +477,7 @@ export async function turnProcessProbe() {);click(liveHeader);check(- allCollapsed() &&- liveHeader?.querySelector(".tool-activity-label")?.textContent?.startsWith(- i18n.t("chat.thinkingFor", { time: "" }),- ),+ allCollapsed() && liveLabel() === i18n.t("chat.thinking"),"the live thinking indicator stays visible with the process closed",);render([{ ...liveThought, status: "complete" }], false, null, "thought-off-done");@@ -304,6 +489,22 @@ export async function turnProcessProbe() {liveThought.thinking === "Reasoning before the answer","hiding thinking never deletes stored reasoning",);+ // A streaming reasoning row that already has assistant content is hidden+ // like any completed reasoning row. It must not leave an empty disclosure+ // behind, and the answer must stay visible.+ const hiddenStreamingContent = message(+ "hidden-streaming-content",+ "assistant",+ "Visible answer",+ { thinking: "Reasoning with content", status: "streaming" },+ );+ render([hiddenStreamingContent], true, null, "hidden-streaming-content");+ check(+ !container.querySelector(".turn-process") &&+ !container.querySelector(".thinking") &&+ visible(row("hidden-streaming-content")),+ "hidden streaming reasoning with content leaves no empty process shell",+ );setSettings({ showThinking: true });render([{ ...liveThought, status: "complete" }], false, null, "thought-on-done");check(@@ -329,6 +530,132 @@ export async function turnProcessProbe() {"search reveals the process chunk that owns the target",);+ // Command folding is read at render time: toggling it on the mounted turn+ // must regroup the rows without remounting the transcript.+ setSettings();+ render(contiguous, false, null, "command-folding-toggle");+ click(processHeaders()[0] ?? null);+ check(+ visible(row("bash1")) &&+ container.querySelectorAll(".turn-run-row").length === 2,+ "the mounted turn starts with standalone command rows",+ );+ setSettings({ keepCommandsExpanded: false });+ check(+ container.querySelectorAll(".turn-process").length === 1 &&+ container.querySelectorAll(".turn-run-row").length === 0,+ "toggling command folding keeps one process and removes standalone rows",+ );+ const foldedBash1 = row("bash1");+ const foldedBash2 = row("bash2");+ const foldedGroup = foldedBash1?.closest(".process-activity-group.grouped");+ check(+ foldedGroup !== null &&+ foldedGroup === foldedBash2?.closest(".process-activity-group.grouped"),+ "folded commands share one grouped activity ancestor",+ );+ check(+ foldedGroup?.contains(row("read") ?? null) === true &&+ foldedGroup?.contains(row("edit") ?? null) === true,+ "the shared group contains the surrounding tools",+ );+ check(+ foldedGroup?.querySelector(".tool-activity-header") !== null,+ "the shared group keeps its group header",+ );+ check(+ processHeaders()[0]?.querySelector(".tool-activity-count")?.textContent ===+ i18n.t("chat.processTools", { count: 5 }),+ "folding commands does not change the header tool count",+ );+ setSettings();+ check(+ container.querySelectorAll(".turn-run-row").length === 2 &&+ row("bash1")?.closest(".process-activity-group") === null,+ "toggling command folding back restores standalone rows without a remount",+ );++ // The active tail may be wrapped in a merged off-mode part; the merged group+ // must still receive the live disclosure defaults.+ setSettings({ keepCommandsExpanded: false });+ render(+ [read, grep, run("live-folded-bash", "pnpm test")],+ true,+ null,+ "live-folded",+ );+ check(+ visible(row("live-folded-bash")) &&+ container.querySelector(".process-activity-group.grouped.open") !== null,+ "the merged group keeps its live disclosure default",+ );+ setSettings();++ // The header reports the turn's outcome, never the item it is working on.+ render(mixed, false, null, "completed-header");+ const completedLabel = i18n.t("chat.processCompleted");+ const completedText = processHeaders()[0]+ ?.querySelector(".tool-activity-label")+ ?.textContent ?? "";+ check(+ completedText.startsWith(completedLabel) &&+ !completedText.includes("pnpm test") &&+ !completedText.includes("pnpm build"),+ "a settled turn header reports completion without echoing a command",+ );+ render([intro, read, grep], true, null, "live-header");+ check(+ processHeaders()[0]+ ?.querySelector(".tool-activity-label")+ ?.textContent === i18n.t("chat.processRunning"),+ "a live turn header reports running",+ );++ // The store settles a Stop on the tool row itself: an aborted assistant row+ // is not written. The header must read the aborted activity row rather than+ // falling back to the tool's running/error state.+ const stoppedBash = [+ message("stopped-user", "user", "Run"),+ tool("stopped-bash", "Bash", {+ toolArgs: { command: "pnpm test" },+ status: "aborted",+ toolStatus: "error",+ }),+ ];+ render(stoppedBash, false, null, "stopped-bash");+ check(+ processHeaders()[0]+ ?.querySelector(".tool-activity-label")+ ?.textContent === i18n.t("chat.processStopped"),+ "an aborted running Bash row reports the turn stopped",+ );++ // The Settings row is a boolean command-folding toggle, defaulting to on.+ let foldSaved: Partial<AppSettings> | undefined;+ flushSync(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <KeepCommandsExpandedRow+ settings={{ ...baseSettings }}+ saveSettings={async (patch) => {+ foldSaved = patch;+ }}+ />+ </I18nextProvider>,+ ),+ );+ const foldToggle = container.querySelector<HTMLElement>('[role="switch"]');+ check(+ foldToggle?.getAttribute("aria-checked") === "true",+ "the command-folding row defaults to keeping commands expanded",+ );+ click(foldToggle);+ check(+ foldSaved?.keepCommandsExpanded === false,+ "the command-folding row saves the boolean preference",+ );++// The Settings row is a boolean Show thinking toggle.let saved: Partial<AppSettings> | undefined;const settings: AppSettings = { ...baseSettings, showThinking: false };@@ -355,7 +682,7 @@ export async function turnProcessProbe() {"the Show thinking row saves the boolean preference",);- return { ok: true, checks: notes };+ return { ok: true, checks: notes, metrics };} finally {flushSync(() => root.unmount());useAppStore.setState({ settings: initialSettings });