Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(chat): group turn process and add compact thinking display

zszz3832d65f04e38
diff --git a/apps/desktop/src/components/settings/ThinkingDisplayModeRow.tsx b/apps/desktop/src/components/settings/ThinkingDisplayModeRow.tsx
new file mode 100644
index 000000000..790908bf5
--- /dev/null
+++ b/apps/desktop/src/components/settings/ThinkingDisplayModeRow.tsx
@@ -0,0 +1,33 @@
+import { useTranslation } from "react-i18next";
+import type { AppSettings } from "@pi-desktop/shared";
+import { resolveThinkingDisplayMode } from "../../lib/turn-process";
+import { SettingsRow } from "../../features/settings/primitives";
+import { SettingsMenuSelect } from "./SettingsMenuSelect";
+
+export function ThinkingDisplayModeRow({
+ settings,
+ saveSettings,
+}: {
+ settings: AppSettings;
+ saveSettings: (patch: Partial<AppSettings>) => Promise<void>;
+}) {
+ const { t } = useTranslation();
+ return (
+ <SettingsRow
+ title={t("settings.thinkingDisplayMode")}
+ description={t("settings.thinkingDisplayModeDesc")}
+ >
+ <SettingsMenuSelect
+ label={t("settings.thinkingDisplayMode")}
+ value={resolveThinkingDisplayMode(settings.thinkingDisplayMode)}
+ options={[
+ { id: "detailed", label: t("settings.thinkingDisplayDetailed") },
+ { id: "compact", label: t("settings.thinkingDisplayCompact") },
+ ]}
+ onChange={(value) =>
+ void saveSettings({ thinkingDisplayMode: resolveThinkingDisplayMode(value) })
+ }
+ />
+ </SettingsRow>
+ );
+}
diff --git a/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx b/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx
index f2d5f5d70..4f34c45d0 100644
--- a/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx
+++ b/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx
@@ -54,6 +54,9 @@ import { SubagentTopology } from "./SubagentDetail";
import { ToolRow } from "./ToolRow";
import { TranscriptSearchContext } from "../../../lib/transcript-search-context";
+import { useAppStore } from "../../../stores/app-store";
+import { resolveThinkingDisplayMode } from "../../../lib/turn-process";
+
type Translate = (key: string, options?: Record<string, unknown>) => string;
type ActivityItem = AssistantActivityItem;
@@ -145,6 +148,7 @@ export function runActivityLabel(
type ActivityGroupProps = {
items: ActivityItem[];
+ embedded?: boolean;
isActive: boolean;
endedAt?: string;
/** Current runtime wait phase, when the group owns the live turn tail. */
@@ -174,6 +178,7 @@ function activityGroupPropsEqual(
next: ActivityGroupProps,
) {
if (
+ previous.embedded !== next.embedded ||
previous.isActive !== next.isActive ||
previous.endedAt !== next.endedAt ||
previous.runtimeActivity !== next.runtimeActivity ||
@@ -199,12 +204,14 @@ function activityGroupPropsEqual(
export const ActivityGroup = memo(function ActivityGroup({
items,
+ embedded = false,
isActive,
endedAt,
runtimeActivity,
turnDelegationStatuses,
turnDelegationTimings,
}: ActivityGroupProps) {
+ const compact = useAppStore((state) => resolveThinkingDisplayMode(state.settings?.thinkingDisplayMode) === "compact");
const { t } = useTranslation();
const detailsId = useId();
const delegateItems = items.filter(isDelegationActivityItem);
@@ -302,7 +309,8 @@ export const ActivityGroup = memo(function ActivityGroup({
? runActivityLabel(runtimeActivity, t as Translate)
: "";
const currentDetail =
- live && !runtimeStatus && lastItem ? activityItemDetail(lastItem) : "";
+ live && !runtimeStatus && lastItem && !(compact && lastItem.kind === "thinking")
+ ? activityItemDetail(lastItem) : "";
const tail = live && !open ? currentDetail : "";
useEffect(() => {
@@ -351,6 +359,11 @@ export const ActivityGroup = memo(function ActivityGroup({
});
};
+ if (compact && onlyThinking && !thinkingNow) return null;
+ if (embedded && !hasSubagentTopology) {
+ return <div className="turn-process-activity">{renderActivityItems()}</div>;
+ }
+
return (
<div
className={`tool-activity-group ${hasSubagentTopology ? "has-subagents" : ""} ${
diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
index b88fa133d..28448b660 100644
--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
@@ -35,6 +35,9 @@ import {
} from "./shared";
import { activityItemsEqual, ActivityGroup } from "./ActivityGroup";
import { MessageRow } from "./MessageRow";
+import { TurnProcess } from "./TurnProcess";
+import { projectTurnProcess } from "../../../lib/turn-process";
+import type { AssistantTurnPart } from "../../../lib/assistant-turns";
type AssistantTurnProps = {
entry: AssistantTurnEntry;
@@ -271,6 +274,44 @@ export const AssistantTurn = memo(function AssistantTurn({
);
statusesRef.current = turnDelegationStatuses;
timingsRef.current = turnDelegationTimings;
+ const { process, responses } = projectTurnProcess(entry);
+
+ const renderPart = (part: AssistantTurnPart) =>
+ part.kind === "activity" ? (
+ <ActivityGroup
+ embedded
+ key={`activity-${part.items[0].message.id}`}
+ items={part.items}
+ endedAt={part.endedAt}
+ isActive={isActive && part === entry.parts.at(-1)}
+ runtimeActivity={
+ isActive && part === entry.parts.at(-1)
+ ? runtimeActivity
+ : undefined
+ }
+ turnDelegationStatuses={turnDelegationStatuses}
+ turnDelegationTimings={turnDelegationTimings}
+ />
+ ) : (
+ <div
+ className={`message-bubble assistant-turn-fragment${
+ isActive && part.message.status === "streaming"
+ ? " streaming"
+ : ""
+ }`}
+ data-message-id={part.message.id}
+ key={part.message.id}
+ >
+ {part.message.content ? (
+ <div className="prose-chat">
+ <Markdown source={part.message.content} />
+ </div>
+ ) : null}
+ {part.message.error ? (
+ <AssistantErrorMessage message={part.message} />
+ ) : null}
+ </div>
+ );
return (
<div
@@ -281,42 +322,10 @@ export const AssistantTurn = memo(function AssistantTurn({
aria-label={t("chat.assistantMessage")}
>
<div className="message-col">
- {entry.parts.map((part, index) =>
- part.kind === "activity" ? (
- <ActivityGroup
- key={`activity-${part.items[0].message.id}`}
- items={part.items}
- endedAt={part.endedAt}
- isActive={isActive && index === entry.parts.length - 1}
- runtimeActivity={
- isActive && index === entry.parts.length - 1
- ? runtimeActivity
- : undefined
- }
- turnDelegationStatuses={turnDelegationStatuses}
- turnDelegationTimings={turnDelegationTimings}
- />
- ) : (
- <div
- className={`message-bubble assistant-turn-fragment${
- isActive && part.message.status === "streaming"
- ? " streaming"
- : ""
- }`}
- data-message-id={part.message.id}
- key={part.message.id}
- >
- {part.message.content ? (
- <div className="prose-chat">
- <Markdown source={part.message.content} />
- </div>
- ) : null}
- {part.message.error ? (
- <AssistantErrorMessage message={part.message} />
- ) : null}
- </div>
- ),
- )}
+ <TurnProcess parts={process} timingParts={entry.parts} isActive={isActive}>
+ {process.map(renderPart)}
+ </TurnProcess>
+ {responses.map(renderPart)}
{!isActive && metaMessage ? (
<MessageMeta
modelId={modelId}
diff --git a/apps/desktop/src/features/chat/transcript/TurnProcess.tsx b/apps/desktop/src/features/chat/transcript/TurnProcess.tsx
new file mode 100644
index 000000000..2b1dd78c4
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/TurnProcess.tsx
@@ -0,0 +1,140 @@
+import { useContext, useEffect, useId, useState, type ReactNode } from "react";
+import { useTranslation } from "react-i18next";
+import type { AssistantTurnPart } from "../../../lib/assistant-turns";
+import { formatToolDuration } from "../../../lib/tool-display";
+import { TranscriptSearchContext } from "../../../lib/transcript-search-context";
+import {
+ resolveThinkingDisplayMode,
+ turnProcessTiming,
+ visibleProcessSteps,
+} from "../../../lib/turn-process";
+import { useAppStore } from "../../../stores/app-store";
+import {
+ IconChevronRight,
+ IconCircleAlert,
+ IconSparkles,
+} from "../../../components/icons";
+import { DisclosureCollapseRail, useAutomaticDisclosure } from "./shared";
+
+export function TurnProcess({
+ parts,
+ timingParts,
+ isActive,
+ children,
+}: {
+ parts: readonly AssistantTurnPart[];
+ timingParts: readonly AssistantTurnPart[];
+ isActive: boolean;
+ children: ReactNode;
+}) {
+ const { t } = useTranslation();
+ const mode = useAppStore((state) =>
+ resolveThinkingDisplayMode(state.settings?.thinkingDisplayMode),
+ );
+ const search = useContext(TranscriptSearchContext);
+ const reveal =
+ search &&
+ parts.some((part) =>
+ part.kind === "message"
+ ? part.message.id === search.messageId
+ : part.items.some(
+ (item) =>
+ item.message.id === search.messageId ||
+ (item.kind === "tool" &&
+ item.delegate?.items.some(
+ (row) => row.message.id === search.messageId,
+ )),
+ ),
+ )
+ ? search.requestId
+ : undefined;
+ const failed = parts.some(
+ (part) =>
+ part.kind === "activity" &&
+ part.items.some(
+ (item) =>
+ item.kind === "tool" &&
+ (item.message.toolStatus === "error" ||
+ item.message.toolStatus === "denied" ||
+ item.message.isError),
+ ),
+ );
+ const thinkingOnly = parts.every(
+ (part) =>
+ part.kind === "activity" && part.items.every((item) => item.kind === "thinking"),
+ );
+ const disclosure = useAutomaticDisclosure(
+ isActive && (failed || mode === "detailed"),
+ reveal,
+ );
+ const detailsId = useId();
+ const [now, setNow] = useState(Date.now);
+ const { startedAt, endedAt } = turnProcessTiming(timingParts);
+ useEffect(() => {
+ if (!isActive) return;
+ setNow(Date.now());
+ const timer = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(timer);
+ }, [isActive]);
+ const count = visibleProcessSteps(parts, mode, isActive);
+ if (count === 0) return null;
+ const seconds =
+ startedAt === undefined
+ ? 0
+ : Math.max(
+ 0,
+ Math.floor(((isActive ? now : (endedAt ?? startedAt)) - startedAt) / 1000),
+ );
+ return (
+ <section
+ className={`turn-process${disclosure.open ? " open" : ""}${isActive ? " active" : ""}`}
+ >
+ <button
+ type="button"
+ ref={disclosure.titleRef}
+ className="tool-activity-header"
+ aria-expanded={disclosure.open}
+ aria-controls={detailsId}
+ onClick={disclosure.toggle}
+ >
+ <span className="tool-activity-icon" aria-hidden>
+ <IconSparkles size={14} />
+ </span>
+ <span className={`tool-activity-label${isActive ? " running" : ""}`}>
+ {t(
+ isActive
+ ? thinkingOnly
+ ? "chat.thinkingFor"
+ : "chat.processingFor"
+ : "chat.processedFor",
+ { time: formatToolDuration(seconds) },
+ )}
+ </span>
+ {failed ? (
+ <span className="turn-process-error" title={t("chat.toolFailed")}>
+ <IconCircleAlert size={14} aria-label={t("chat.toolFailed")} />
+ </span>
+ ) : null}
+ <span className="tool-activity-count">
+ {t("chat.processingSteps", { count })}
+ </span>
+ <span className="tool-activity-caret" aria-hidden>
+ <IconChevronRight size={12} />
+ </span>
+ </button>
+ <div
+ id={detailsId}
+ className="turn-process-body"
+ hidden={!disclosure.open}
+ inert={!disclosure.open}
+ onClickCapture={disclosure.claim}
+ >
+ <DisclosureCollapseRail
+ label={t("chat.collapseDetails")}
+ onCollapse={disclosure.collapse}
+ />
+ {children}
+ </div>
+ </section>
+ );
+}
diff --git a/apps/desktop/src/features/chat/transcript/shared.tsx b/apps/desktop/src/features/chat/transcript/shared.tsx
index f04976f39..feec84a6e 100644
--- a/apps/desktop/src/features/chat/transcript/shared.tsx
+++ b/apps/desktop/src/features/chat/transcript/shared.tsx
@@ -1,3 +1,4 @@
+import { isThinkingActive, resolveThinkingDisplayMode } from "../../../lib/turn-process";
import {
memo,
useCallback,
@@ -551,6 +552,15 @@ export const ThinkingRow = memo(function ThinkingRow({
onUserInteraction?.();
collapseDisclosure();
}, [collapseDisclosure, onUserInteraction]);
+ const compact = useAppStore((state) => resolveThinkingDisplayMode(state.settings?.thinkingDisplayMode) === "compact");
+ if (compact) {
+ return isThinkingActive(message, streaming) ? (
+ <div className="tool-row thinking thinking-compact" role="status">
+ <span className="tool-row-icon" aria-hidden><IconSparkles size={15} /></span>
+ <span className="tool-row-name running">{t("chat.thinking", { defaultValue: "Thinking" })}</span>
+ </div>
+ ) : null;
+ }
const text = thinkingText(message);
const summary = text.replace(/\s+/g, " ").trim();
return (
diff --git a/apps/desktop/src/features/settings/SettingsPage.tsx b/apps/desktop/src/features/settings/SettingsPage.tsx
index 9dfcbdeb2..a7af233ad 100644
--- a/apps/desktop/src/features/settings/SettingsPage.tsx
+++ b/apps/desktop/src/features/settings/SettingsPage.tsx
@@ -31,6 +31,7 @@ import { Button, cx } from "../../components/ui";
import { ModelConfigPage } from "../../components/settings/ModelConfigPage";
import { KeyboardShortcutsSection } from "../../components/settings/KeyboardShortcutsSection";
import { FontFamilyRow } from "../../components/settings/FontFamilyRow";
+import { ThinkingDisplayModeRow } from "../../components/settings/ThinkingDisplayModeRow";
import { FontSizeRow } from "../../components/settings/FontSizeRow";
import { LanguageRow } from "../../components/settings/LanguageRow";
import { SettingsMenuSelect } from "../../components/settings/SettingsMenuSelect";
@@ -396,6 +397,7 @@ export function SettingsPage() {
</SettingsRow>
<CommandShellRow settings={settings} saveSettings={saveSettings} />
<LinkOpenTargetRow settings={settings} saveSettings={saveSettings} />
+ <ThinkingDisplayModeRow settings={settings} saveSettings={saveSettings} />
<ContextUsageDisplayRow
settings={settings}
saveSettings={saveSettings}
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 31399ca28..54ce29d67 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -221,6 +221,10 @@ export function normalizeSettings(settings: AppSettings): AppSettings {
}
export function validateSettingsWrite(settings: AppSettings): AppSettings {
+ if (settings.thinkingDisplayMode !== undefined &&
+ settings.thinkingDisplayMode !== "detailed" && settings.thinkingDisplayMode !== "compact") {
+ throw Object.assign(new Error("thinkingDisplayMode is invalid"), { errorCode: "INVALID_PARAMS" });
+ }
const value = settings as AppSettings & {
defaultCommandShell?: unknown;
largePasteThreshold?: unknown;
diff --git a/apps/desktop/src/lib/settings-search.ts b/apps/desktop/src/lib/settings-search.ts
index b9918053a..3f821e97a 100644
--- a/apps/desktop/src/lib/settings-search.ts
+++ b/apps/desktop/src/lib/settings-search.ts
@@ -83,6 +83,9 @@ export const SETTINGS_NAV: SettingsNavEntry[] = [
"settings.commandShell",
"settings.linkOpenTarget",
"settings.enterToSend",
+ "settings.thinkingDisplayMode",
+ "settings.thinkingDisplayDetailed",
+ "settings.thinkingDisplayCompact",
"settings.contextUsageDisplay",
"settings.contextUsageDisplayRemaining",
"settings.contextUsageDisplayUsed",
diff --git a/apps/desktop/src/lib/turn-process.ts b/apps/desktop/src/lib/turn-process.ts
new file mode 100644
index 000000000..099a52863
--- /dev/null
+++ b/apps/desktop/src/lib/turn-process.ts
@@ -0,0 +1,83 @@
+import type { UiMessage } from "@pi-desktop/shared";
+import type { AssistantTurnEntry, AssistantTurnPart } from "./assistant-turns";
+
+export type ThinkingDisplayMode = "detailed" | "compact";
+
+export function resolveThinkingDisplayMode(value: unknown): ThinkingDisplayMode {
+ return value === "compact" ? "compact" : "detailed";
+}
+
+export function isThinkingActive(message: UiMessage, active: boolean): boolean {
+ return active && message.status === "streaming" && !message.content.trim();
+}
+
+/**
+ * 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
+ * remains visible until a later activity establishes that it was intermediate.
+ * Errors remain outside the disclosure even when more activity follows them.
+ */
+export function projectTurnProcess(entry: AssistantTurnEntry) {
+ const last = entry.parts.at(-1);
+ const answer =
+ last?.kind === "message" && last.message.content.trim() ? last : undefined;
+ const process: AssistantTurnPart[] = [];
+ const responses: Extract<AssistantTurnPart, { kind: "message" }>[] = [];
+ for (const part of entry.parts) {
+ if (part.kind === "message" && (part === answer || part.message.error)) {
+ responses.push(part);
+ } else {
+ process.push(part);
+ }
+ }
+ return { process, responses };
+}
+
+export function visibleProcessSteps(
+ parts: readonly AssistantTurnPart[],
+ mode: ThinkingDisplayMode,
+ active: boolean,
+): number {
+ return parts.reduce(
+ (count, part) =>
+ count +
+ (part.kind === "message"
+ ? Number(Boolean(part.message.content.trim()))
+ : part.items.filter(
+ (item) =>
+ item.kind === "tool" ||
+ mode === "detailed" ||
+ isThinkingActive(item.message, active),
+ ).length),
+ 0,
+ );
+}
+
+/** Use recorded message/tool timing for history; elapsed live time is UI-only. */
+export function turnProcessTiming(parts: readonly AssistantTurnPart[]) {
+ const messages = parts.flatMap((part) =>
+ part.kind === "message" ? [part.message] : part.items.map((item) => item.message),
+ );
+ const starts = messages
+ .map((message) => Date.parse(message.createdAt))
+ .filter(Number.isFinite);
+ if (starts.length === 0) return { startedAt: undefined, endedAt: undefined };
+ const startedAt = Math.min(...starts);
+ const endedAt = Math.max(
+ startedAt,
+ ...messages.map((message) => {
+ const createdAt = Date.parse(message.createdAt);
+ if (!Number.isFinite(createdAt)) return startedAt;
+ const duration =
+ message.role === "tool" ? message.toolDurationMs : message.responseDurationMs;
+ const recordedEnd = Date.parse(message.toolCompletedAt ?? "");
+ return Number.isFinite(recordedEnd)
+ ? recordedEnd
+ : createdAt +
+ (typeof duration === "number" && Number.isFinite(duration)
+ ? Math.max(0, duration)
+ : 0);
+ }),
+ );
+ return { startedAt, endedAt };
+}
diff --git a/apps/desktop/src/styles/messages.css b/apps/desktop/src/styles/messages.css
index 53ecd25e3..38cb624e1 100644
--- a/apps/desktop/src/styles/messages.css
+++ b/apps/desktop/src/styles/messages.css
@@ -2944,3 +2944,40 @@
color: var(--ds-text-muted);
font-size: var(--text-xs);
}
+
+/* One disclosure owns the process; tools retain their own detail controls. */
+.turn-process {
+ width: 100%;
+ margin: 0 0 8px;
+ min-width: 0;
+}
+
+.turn-process.open > .tool-activity-header > .tool-activity-caret {
+ transform: rotate(90deg);
+}
+
+.turn-process-body {
+ position: relative;
+ padding-left: 18px;
+}
+
+.turn-process-body[hidden] {
+ display: none;
+}
+
+.turn-process-body > .assistant-turn-fragment {
+ color: var(--ds-text-secondary);
+ margin-block: 8px;
+}
+
+.thinking-compact {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding-block: 6px;
+}
+
+.turn-process-error {
+ display: inline-flex;
+ color: var(--ds-error);
+}
diff --git a/apps/desktop/test/turn-process.test.mjs b/apps/desktop/test/turn-process.test.mjs
new file mode 100644
index 000000000..55bb696da
--- /dev/null
+++ b/apps/desktop/test/turn-process.test.mjs
@@ -0,0 +1,145 @@
+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 { buildTranscriptEntries } = await import("../src/lib/assistant-turns.ts");
+const {
+ projectTurnProcess,
+ visibleProcessSteps,
+ resolveThinkingDisplayMode,
+ turnProcessTiming,
+} = await import("../src/lib/turn-process.ts");
+
+const message = (id, role, content, extra = {}) => ({
+ id,
+ role,
+ content,
+ createdAt: "2026-09-17T00:00:00.000Z",
+ ...extra,
+});
+const turn = (messages) =>
+ buildTranscriptEntries(messages).entries.find(
+ (entry) => entry.kind === "assistant-turn",
+ );
+
+test("one turn groups thinking, tools and progress while retaining only the trailing answer", () => {
+ const entry = turn([
+ message("user", "user", "Inspect"),
+ message("intro", "assistant", "I will inspect", { thinking: "Plan" }),
+ message("read", "tool", "result", { toolName: "Read" }),
+ message("progress", "assistant", "I found the cause"),
+ message("edit", "tool", "updated", { toolName: "Edit" }),
+ message("final", "assistant", "Fixed"),
+ ]);
+ const projected = projectTurnProcess(entry);
+ assert.deepEqual(
+ projected.responses.map((part) => part.message.id),
+ ["final"],
+ );
+ assert.equal(visibleProcessSteps(projected.process, "detailed", false), 5);
+ assert.equal(visibleProcessSteps(projected.process, "compact", false), 4);
+});
+
+test("streamed text stays readable until later work establishes it as progress", () => {
+ const text = message("text", "assistant", "Inspecting", { status: "streaming" });
+ assert.equal(projectTurnProcess(turn([text])).responses[0].message, text);
+ const projected = projectTurnProcess(
+ turn([text, message("tool", "tool", "", { toolName: "Read" })]),
+ );
+ assert.equal(projected.responses.length, 0);
+ assert.equal(projected.process[0].message, text);
+});
+
+test("plain answers need no empty process disclosure", () => {
+ const projected = projectTurnProcess(turn([message("final", "assistant", "Answer")]));
+ assert.equal(projected.process.length, 0);
+ assert.equal(projected.responses.length, 1);
+});
+
+test("errors and aborted partial replies remain outside the process", () => {
+ const error = message("error", "assistant", "", {
+ status: "error",
+ error: { code: "INTERNAL", message: "failed" },
+ });
+ const partial = message("partial", "assistant", "Partial answer", {
+ status: "aborted",
+ });
+ const projected = projectTurnProcess(
+ turn([error, message("tool", "tool", "result"), partial]),
+ );
+ assert.deepEqual(
+ projected.responses.map((part) => part.message.id),
+ ["error", "partial"],
+ );
+});
+
+test("compact thinking disappears after reasoning ends without removing stored data", () => {
+ const thinking = message("think", "assistant", "", {
+ thinking: "Private reasoning",
+ status: "streaming",
+ });
+ const entry = turn([thinking]);
+ assert.equal(visibleProcessSteps(entry.parts, "compact", true), 1);
+ assert.equal(visibleProcessSteps(entry.parts, "compact", false), 0);
+ const withAnswer = turn([{ ...thinking, content: "Answer" }]);
+ assert.equal(
+ visibleProcessSteps(projectTurnProcess(withAnswer).process, "compact", true),
+ 0,
+ );
+ assert.equal(thinking.thinking, "Private reasoning");
+});
+
+test("missing and unknown display settings retain detailed mode", () => {
+ for (const value of [undefined, null, "hidden", false, "detailed"]) {
+ assert.equal(resolveThinkingDisplayMode(value), "detailed");
+ }
+ assert.equal(resolveThinkingDisplayMode("compact"), "compact");
+});
+
+test("history timing uses recorded ends and rejects invalid timestamps and durations", () => {
+ const entry = turn([
+ message("read", "tool", "", { toolCompletedAt: "2026-09-17T00:00:02.000Z" }),
+ message("answer", "assistant", "Done", {
+ createdAt: "2026-09-17T00:00:03.000Z",
+ responseDurationMs: 1000,
+ }),
+ ]);
+ const timing = turnProcessTiming(entry.parts);
+ assert.equal(timing.endedAt - timing.startedAt, 4000);
+ assert.deepEqual(
+ turnProcessTiming(
+ turn([message("bad", "assistant", "x", { createdAt: "bad" })]).parts,
+ ),
+ {
+ startedAt: undefined,
+ endedAt: undefined,
+ },
+ );
+});
+
+test("user boundaries retain independent processes and delegation details stay attached", () => {
+ const entries = buildTranscriptEntries([
+ message("u1", "user", "one"),
+ message("task", "tool", "started", { toolName: "Task", toolCallId: "call" }),
+ message("nested", "assistant", "Delegate answer", { parentToolCallId: "call" }),
+ message("a1", "assistant", "one done"),
+ message("u2", "user", "two"),
+ message("a2", "assistant", "two done"),
+ ]).entries.filter((entry) => entry.kind === "assistant-turn");
+ assert.equal(entries.length, 2);
+ const first = projectTurnProcess(entries[0]);
+ assert.equal(first.process[0].items[0].delegate.items[0].message.id, "nested");
+ assert.equal(projectTurnProcess(entries[1]).process.length, 0);
+});
+
+
+test("settings writes validate the mode without changing other preferences", async () => {
+ const { validateSettingsWrite } = await import("../src/lib/api.ts");
+ const settings = { defaultMode: "agent", theme: "dark", enterToSend: true, onboardingDismissed: false };
+ assert.equal(validateSettingsWrite(settings), settings);
+ for (const thinkingDisplayMode of ["detailed", "compact"]) {
+ const next = { ...settings, thinkingDisplayMode };
+ assert.equal(validateSettingsWrite(next), next);
+ }
+ assert.throws(() => validateSettingsWrite({ ...settings, thinkingDisplayMode: "unknown" }), /thinkingDisplayMode is invalid/);
+});
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 02afac254..c45b5653a 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -306,3 +306,4 @@ Each ADR includes:
| 0277 | [Draggable chat content width](0277-draggable-chat-content-width.md) | Accepted (D439) |
| 0278 | [Canonical application ID `net.aiuo.pi-desktop`](0278-canonical-application-id.md) | Accepted (D443; amends D141 / D371 / ADR 0204; issue #524) |
| 0279 | [Resumable subagent delegations](0279-resumable-subagent-delegations.md) | Accepted for implementation (amends ADR 0062; ADR 0089; issue #513) |
+| turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted |
diff --git a/docs/adr/turn-process-and-thinking-display.md b/docs/adr/turn-process-and-thinking-display.md
new file mode 100644
index 000000000..5c7abf51b
--- /dev/null
+++ b/docs/adr/turn-process-and-thinking-display.md
@@ -0,0 +1,66 @@
+# ADR turn-process-and-thinking-display: Turn process and thinking presentation
+
+- Status: Accepted
+- Date: 2026-09-17
+- Issues: #510, #461
+- Amends: D071, [ADR 0242](0242-delta-only-streaming-updates.md)
+
+## Context
+
+A model can alternate reasoning, tool calls and progress text many times before
+answering one user request. Separate activity groups leave those progress
+messages at the same visual level as the answer. Some readers also need a
+thinking indicator without rapidly changing reasoning text.
+
+## Decision
+
+The renderer projects each existing assistant-turn entry into one process
+area and its trailing answer. Thinking, tools and intermediate assistant text
+keep their original order inside the process. A trailing assistant text stays
+visible while streaming; if a later tool or thinking block follows, that text
+belongs to the process. There is no semantic final-answer marker in UiMessage,
+so the renderer does not guess intent from the wording. User/system messages
+and compaction dividers retain their existing turn boundaries.
+
+Completed process areas start collapsed. Detailed mode opens the active
+process automatically and retains the existing thinking-row disclosures.
+Manual disclosure choices survive streaming and completion. Search navigation
+opens the containing process. Tool failures open an unclaimed active process so the
+invocation error stays visible; that does not mark the whole turn as failed.
+Assistant errors and stopped trailing partial answers stay outside the process.
+Tool/delegation detail controls, permission cards, and transcript actions retain
+their existing behavior.
+
+Settings → AI → Defaults includes `thinkingDisplayMode`, an optional
+`detailed | compact` AppSettings field. Absent or unrecognized values display
+as detailed. Compact mode renders no reasoning text or excerpt: while a
+thinking-only message streams it shows a status indicator, and when reasoning
+ends the thinking row disappears. Answer text ends that indicator even while
+the assistant message is still streaming. A completed thinking-only process
+leaves no empty header. Tool rows and progress text remain expandable.
+Changing the setting updates mounted history and nested thinking rows.
+
+The field uses the existing host-owned settings JSON; no database migration or
+schema/protocol version change is required. It does not alter provider thinking
+levels, runtime/model context, stored reasoning, export, permissions, or copy
+payloads. Process durations use message/tool timestamps and recorded durations;
+a live UI clock adds no persisted fields. Step counts include rendered thinking,
+tool and intermediate-text items and omit hidden compact-mode thinking.
+
+## Consequences
+
+- One completed turn has one process disclosure plus its visible answer.
+- Reasoning remains available by switching back to detailed mode.
+- Unchanged activity groups keep their memoized boundary during text deltas;
+ the process wrapper does not move execution or persistence into the renderer.
+- This groups loaded transcript entries; it does not reconstruct history that
+ has not been loaded or join turns across compaction boundaries.
+
+## Validation
+
+`turn-process.test.mjs` covers projection, timing, partial/error answers and
+legacy settings. `test:e2e:transcript` exercises real React/Chromium disclosure,
+streaming, search, mode selection, mounted-history updates and the existing
+100-group render boundary. `test:e2e:transcript-disclosure` retains the scroll
+anchor gate; `test:e2e:theme-surfaces` checks the surrounding theme controls.
+See E2E-CHAT-turn-process-and-thinking-display.
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index f95382350..ef1cd9e7c 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -223,6 +223,10 @@ CREATE TABLE kv (
| `plugin:<id>` | per-plugin settings; uninstall = `DELETE WHERE ns = ?` |
| `projectMemory` | durable user-authored context keyed by canonical project path; structured values contain `format: "entries-v1"`, visual `entries`, derived `content`, and `updatedAt` |
+The app settings JSON optionally stores `thinkingDisplayMode` (`detailed` or
+`compact`). Missing values retain detailed presentation. This additive display
+preference neither rewrites stored reasoning nor changes the database schema.
+
New config domains (e.g. MCP servers) start as a namespace; they graduate to
tables only when they need relations or indexes.
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index d70f88c25..3177c71e2 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -139,7 +139,7 @@ Settings is a **full-window page** that replaces the app sidebar + main chrome (
control column.
- **Defaults** card: the host-backed default operating mode (Agent / Plan / Goal),
command shell selection, Link open destination, context usage display
- (remaining or used), Enter-to-send control, and the large text paste
+ (remaining or used), thinking display mode, Enter-to-send control, and the large text paste
threshold. Link open destination uses the Work panel browser by default
and can route plain HTTP(S) link clicks to the system browser. Context
usage display controls whether the composer toolbar context ring and its
@@ -147,6 +147,12 @@ Settings is a **full-window page** that replaces the app sidebar + main chrome (
is remaining. The threshold controls when a text-only paste becomes a
temporary session-scratch file; it defaults to 600 characters and accepts
integer values from 1 through 1,000,000.
+- **Thinking display mode** uses a menu select with Detailed (default) and
+ Compact. Detailed retains reasoning text; Compact shows only an active
+ thinking indicator and hides finished thought rows. The global preference
+ persists as `thinkingDisplayMode` in host-owned settings; missing values use
+ Detailed. It affects presentation only, not model reasoning configuration.
+ Settings search indexes the row and both mode names.
- The **Command shell** row in Defaults uses the host-discovered catalog of native
PowerShell 5.1, PowerShell 7, cmd, Git Bash, and Bash with IDs
`windows-powershell`, `windows-pwsh`, `cmd`, `git-bash`, and
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index f47b68c49..c1264120d 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -786,6 +786,29 @@ reading surface of the workstation.
the draft grows. `.jump-latest-btn` and `.minimap-rail` anchor to the same
variable so they stay just above the composer.
+### Turn process and thinking display
+
+Each assistant-turn entry has one process disclosure containing reasoning,
+tools and intermediate assistant text in transcript order. Its trailing answer
+streams outside the disclosure. Later activity moves a provisional answer into
+the process without altering the stored message. Assistant errors and trailing
+aborted partial replies stay visible. Compaction and user/system boundaries are
+unchanged.
+
+Completed process areas start collapsed; detailed mode opens the active process.
+Manual choices and search reveals own the disclosure until unmount. Failed tools
+open an unclaimed active process and keep their invocation-level error presentation.
+The header shows elapsed time and the visible process step count. Delegation
+cards and individual tool details remain available inside the process.
+
+`thinkingDisplayMode` defaults to `detailed`. In `compact`, reasoning text and
+excerpts are absent, active reasoning has a status indicator, and completed
+thinking rows disappear. Tools and intermediate text remain accessible; a
+thinking-only completed process has no empty header. The setting also applies
+to nested thinking rows and updates mounted history. It never removes stored
+reasoning or changes model thinking configuration. See
+[ADR turn-process-and-thinking-display](../../adr/turn-process-and-thinking-display.md).
+
### 4.4 States
| State | Behavior |
diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.md
index 32cd69429..862da2631 100644
--- a/docs/spec/04-ux/09-interaction-patterns.md
+++ b/docs/spec/04-ux/09-interaction-patterns.md
@@ -764,17 +764,19 @@ may be retained while exactly one workspace supplies the visible shell context.
- Tool activity starts as a lightweight collapsed row; failed calls open
automatically so the error remains local to its invocation.
-- Consecutive tool activity is wrapped in one processing group. Its header
- updates elapsed time once per second while active, freezes after the next
- transcript message, and exposes the number of contained steps. The latest
- action remains in the activity rows or dedicated runtime indicator; no
- additional status capsule is rendered.
-- While the turn is active, the latest processing group opens automatically so
- its activity list is visible, but tool-call details remain collapsed by
- default. The latest thinking row opens automatically while it streams. When
- the activity settles, only automatic thinking disclosures close. A click or
- keyboard activation on a group, row, or collapse rail makes that disclosure
- user-owned; stream updates and completion never override it.
+- One assistant turn has one process disclosure containing thinking, tool calls
+ and intermediate progress text. The trailing answer streams outside it;
+ later activity moves that text into the process. The header updates elapsed
+ time once per second while active and shows the visible step count.
+- Detailed mode opens the active process and retains the latest thinking row's
+ automatic disclosure. Completed process areas collapse unless a click,
+ keyboard activation or search reveal has taken ownership. Tool details keep
+ their individual controls. Failed tool calls open an unclaimed active process so
+ their errors stay visible.
+- Compact thinking mode shows only a status indicator while reasoning streams;
+ when answer text starts or reasoning ends, the thought row disappears. Tools
+ and progress text remain accessible, and a completed thinking-only process
+ leaves no header. Neither mode changes stored reasoning.
- A failed row is invocation-local truth and remains visible immediately. The
containing group reports processing duration only and settles as processed,
even when a later call recovers. Terminal turn failure is derived only from
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 3bd2dabfa..27739e6a6 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -12998,3 +12998,26 @@ plugin-form fixtures in an isolated temporary directory at runtime.
- **Acceptance**: G (remote marketplace source)
- **Milestone**: M6+
- **Status**: Draft
+
+### E2E-CHAT-turn-process-and-thinking-display
+
+- **Preconditions:** A turn with thinking, multiple tools, intermediate progress
+ and a final answer; detailed and compact display modes.
+- **Steps:** Stream the turn; finish it; expand/collapse its process; search an
+ intermediate message; switch display modes through Settings → AI → Defaults.
+ Repeat with a stopped partial answer, an assistant error and a failed tool.
+- **Expected:** Completed work has one collapsed process plus its final answer.
+ Manual choices survive updates; search reveals its target; live answer text
+ stays readable. Errors and stopped trailing text stay visible. Compact mode
+ exposes no reasoning text or excerpt, shows a live indicator, and leaves no
+ completed thinking-only header. Tools and progress remain accessible. Switching
+ to detailed restores reasoning from unchanged messages. Saved mode survives
+ application restart; an older settings blob without the field uses detailed.
+- **Automation:** `test:e2e:transcript` covers the mounted renderer interactions,
+ settings control and unchanged-group performance. `test:e2e:transcript-disclosure`
+ covers scroll anchoring; `test:e2e:theme-surfaces` covers the shared theme
+ controls. Isolated Host `settings.set/get` checks verify both modes across
+ process restart and preservation during unrelated partial settings writes.
+ Renderer fixtures alone do not prove settings persistence.
+- **Specs:** 04-ux/06-settings-ia, 04-ux/08-component-spec,
+ 04-ux/09-interaction-patterns; ADR turn-process-and-thinking-display.
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 179010b0b..54983e8bc 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -820,6 +820,10 @@ sklm: {
"linkOpenTarget": "Ziel für Link-Öffnung",
"linkOpenTargetWorkpanel": "Arbeitsbereich-Browser",
"linkOpenTargetExternal": "Standard-Betriebssystem-Browser",
+ "thinkingDisplayMode": "Denkprozess anzeigen",
+ "thinkingDisplayModeDesc": "Detailliert zeigt den Denktext. Kompakt zeigt während des Denkens einen Hinweis und blendet abgeschlossene Denkprozesse aus.",
+ "thinkingDisplayDetailed": "Detailliert (Standard)",
+ "thinkingDisplayCompact": "Kompakt",
"contextUsageDisplay": "Kontextnutzung-Anzeige",
"contextUsageDisplayRemaining": "Verbleibend",
"contextUsageDisplayUsed": "Verwendet",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 56e965eaa..a243fd8ba 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -829,6 +829,10 @@ sklm: {
linkOpenTarget: "Link open destination",
linkOpenTargetWorkpanel: "Work panel browser",
linkOpenTargetExternal: "Default OS browser",
+ thinkingDisplayMode: "Thinking display mode",
+ thinkingDisplayModeDesc: "Detailed shows reasoning text. Compact shows a thinking indicator while active and hides completed thinking.",
+ thinkingDisplayDetailed: "Detailed (default)",
+ thinkingDisplayCompact: "Compact",
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.ts
index 5b5987a52..29db2828e 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -820,6 +820,10 @@ sklm: {
"linkOpenTarget": "Destino al abrir enlaces",
"linkOpenTargetWorkpanel": "Navegador del panel de trabajo",
"linkOpenTargetExternal": "Navegador predeterminado del sistema",
+ "thinkingDisplayMode": "Visualización del razonamiento",
+ "thinkingDisplayModeDesc": "Detallado muestra el razonamiento. Compacto muestra un indicador mientras se razona y oculta el razonamiento al terminar.",
+ "thinkingDisplayDetailed": "Detallado (predeterminado)",
+ "thinkingDisplayCompact": "Compacto",
"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.ts
index ecfc17518..5543ff87a 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -820,6 +820,10 @@ sklm: {
"linkOpenTarget": "Destination d'ouverture des liens",
"linkOpenTargetWorkpanel": "Navigateur du panneau de travail",
"linkOpenTargetExternal": "Navigateur par défaut du système",
+ "thinkingDisplayMode": "Affichage du raisonnement",
+ "thinkingDisplayModeDesc": "Le mode détaillé affiche le raisonnement. Le mode compact affiche un indicateur pendant la réflexion, puis masque le raisonnement terminé.",
+ "thinkingDisplayDetailed": "Détaillé (par défaut)",
+ "thinkingDisplayCompact": "Compact",
"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.ts
index 47fe40a4f..f9bebd115 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -830,6 +830,10 @@ sklm: {
linkOpenTarget: "링크 열기 위치",
linkOpenTargetWorkpanel: "작업 패널 브라우저",
linkOpenTargetExternal: "시스템 기본 브라우저",
+ thinkingDisplayMode: "사고 과정 표시 모드",
+ thinkingDisplayModeDesc: "상세 모드는 사고 내용을 표시합니다. 간결 모드는 사고 중에 상태만 표시하고 완료된 사고 과정은 숨깁니다.",
+ thinkingDisplayDetailed: "상세 (기본값)",
+ thinkingDisplayCompact: "간결",
contextUsageDisplay: "컨텍스트 사용량 표시",
contextUsageDisplayRemaining: "남음",
contextUsageDisplayUsed: "사용됨",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 24c7e36fb..a49af9691 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -830,6 +830,10 @@ sklm: {
linkOpenTarget: "Bağlantı açma hedefi",
linkOpenTargetWorkpanel: "Çalışma paneli tarayıcısı",
linkOpenTargetExternal: "Varsayılan sistem tarayıcısı",
+ thinkingDisplayMode: "Düşünme görünümü",
+ thinkingDisplayModeDesc: "Ayrıntılı mod düşünme metnini gösterir. Sade mod düşünürken bir gösterge gösterir ve tamamlanan düşünmeyi gizler.",
+ thinkingDisplayDetailed: "Ayrıntılı (varsayılan)",
+ thinkingDisplayCompact: "Sade",
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.ts
index 8b6cdffca..7b5174e75 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -820,6 +820,10 @@ sklm: {
linkOpenTarget: "链接打开位置",
linkOpenTargetWorkpanel: "工作区浏览器",
linkOpenTargetExternal: "系统默认浏览器",
+ thinkingDisplayMode: "思考过程展示模式",
+ thinkingDisplayModeDesc: "详细模式显示思考文本;精简模式仅在思考时显示状态提示,结束后隐藏思考块。",
+ thinkingDisplayDetailed: "详细(默认)",
+ thinkingDisplayCompact: "精简",
contextUsageDisplay: "上下文用量读数",
contextUsageDisplayRemaining: "剩余",
contextUsageDisplayUsed: "已用",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 60d5af8c5..525c45b3b 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -820,6 +820,10 @@ sklm: {
linkOpenTarget: "連結開啟位置",
linkOpenTargetWorkpanel: "工作區瀏覽器",
linkOpenTargetExternal: "系統預設瀏覽器",
+ thinkingDisplayMode: "思考過程顯示模式",
+ thinkingDisplayModeDesc: "詳細模式顯示思考文字;精簡模式僅在思考時顯示狀態提示,結束後隱藏思考區塊。",
+ thinkingDisplayDetailed: "詳細(預設)",
+ thinkingDisplayCompact: "精簡",
contextUsageDisplay: "上下文用量讀數",
contextUsageDisplayRemaining: "剩餘",
contextUsageDisplayUsed: "已用",
diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.ts
index b3754d3ed..45d7ee55d 100644
--- a/packages/shared/src/types/settings.ts
+++ b/packages/shared/src/types/settings.ts
@@ -41,6 +41,8 @@ export type AppSettings = {
* Absent means 1. Range 0.8–1.5 in 0.025 steps. Window zoom is independent.
*/
fontScale?: number;
+ /** Transcript presentation only; absent means detailed. Reasoning is retained. */
+ thinkingDisplayMode?: "detailed" | "compact";
/**
* @deprecated Unreleased D343 px field. Reads migrate into `fontScale`
* as `px / 14`; new writes persist `fontScale` instead.
diff --git a/scripts/e2e/transcript-disclosure-anchor.tsx b/scripts/e2e/transcript-disclosure-anchor.tsx
index d472d156b..ee2bb5bdd 100644
--- a/scripts/e2e/transcript-disclosure-anchor.tsx
+++ b/scripts/e2e/transcript-disclosure-anchor.tsx
@@ -1,3 +1,5 @@
+import { AssistantTurn } from "../../apps/desktop/src/features/chat/transcript/AssistantTurn";
+import { buildTranscriptEntries } from "../../apps/desktop/src/lib/assistant-turns";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import { createInstance } from "i18next";
@@ -80,7 +82,8 @@ 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 }: { messages: UiMessage[] }) {
+function TranscriptFixture({ messages, process = false }: { messages: UiMessage[]; process?: boolean }) {
+ const entry = process ? buildTranscriptEntries(messages).entries.find((item) => item.kind === "assistant-turn") : undefined;
const {
scrollRef,
wrapRef,
@@ -114,7 +117,9 @@ function TranscriptFixture({ messages }: { messages: UiMessage[] }) {
>
<div ref={contentRef} className="thread-content">
<div style={{ height: 700 }} />
- <ToolRow message={messages[1]} />
+ {entry?.kind === "assistant-turn"
+ ? <AssistantTurn entry={entry} isActive={false} />
+ : <ToolRow message={messages[1]} />}
<div style={{ height: 300 }} />
</div>
</div>
@@ -261,8 +266,30 @@ globalThis.transcriptDisclosureProbe = async () => {
dockExpanded.scrollTop <= dockBefore.scrollTop + 2,
"expanding the dock re-bottomed the dock scroller",
);
+ const processContainer = mount(<TranscriptFixture process messages={[
+ message("process-user", "user", "Inspect"),
+ message("progress", "assistant", Array.from({ length: 50 }, (_, i) => `Progress paragraph ${i}.`).join("\n\n")),
+ toolRowMessage("process-tool"),
+ message("final", "assistant", "Finished."),
+ ]} />);
+ const processScroller = processContainer.querySelector<HTMLElement>(".thread-scroll");
+ const processTitle = processContainer.querySelector<HTMLElement>(".turn-process > button");
+ assert(processScroller && processTitle, "process fixture did not render");
+ await settle();
+ const processBefore = geometry(processScroller, processTitle);
+ processTitle.click();
+ await settle();
+ const processExpanded = geometry(processScroller, processTitle);
+ assert(processExpanded.scrollHeight > processBefore.scrollHeight + 100, "process did not expand");
+ assert(Math.abs(processExpanded.titleTop - processBefore.titleTop) < 2, "process expansion moved its title");
+ processTitle.click();
+ await settle();
+ const processCollapsed = geometry(processScroller, processTitle);
+ assert(Math.abs(processCollapsed.titleTop - processBefore.titleTop) < 2, "process collapse moved its title");
+ assert(renderErrors.length === 0, `React render errors: ${renderErrors.map(String).join("; ")}`);
return {
ok: true,
+ process: { before: processBefore, expanded: processExpanded, collapsed: processCollapsed },
transcript: { before, expanded, collapsed },
dock: { before: dockBefore, expanded: dockExpanded },
};
diff --git a/scripts/e2e/transcript-render.tsx b/scripts/e2e/transcript-render.tsx
index ab4e538da..36306a841 100644
--- a/scripts/e2e/transcript-render.tsx
+++ b/scripts/e2e/transcript-render.tsx
@@ -1,3 +1,4 @@
+import { turnProcessProbe } from "./turn-process";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import { createInstance } from "i18next";
@@ -225,6 +226,7 @@ globalThis.transcriptRenderProbe = async () => {
changedToolRenders: 1,
taskLifecycleUpdated: true,
taskTimingUpdated: true,
+ turnProcess: await turnProcessProbe(),
textUpdateDurationMs,
};
} finally {
diff --git a/scripts/e2e/turn-process.tsx b/scripts/e2e/turn-process.tsx
new file mode 100644
index 000000000..2d1407176
--- /dev/null
+++ b/scripts/e2e/turn-process.tsx
@@ -0,0 +1,299 @@
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import { createInstance } from "i18next";
+import { I18nextProvider } from "react-i18next";
+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 { ThinkingDisplayModeRow } from "../../apps/desktop/src/components/settings/ThinkingDisplayModeRow";
+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";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+
+function assert(value: unknown, message: string): asserts value {
+ if (!value) throw new Error(message);
+}
+
+const message = (
+ id: string,
+ role: UiMessage["role"],
+ content: string,
+ extra: Partial<UiMessage> = {},
+): UiMessage => ({
+ id,
+ role,
+ content,
+ createdAt: "2026-09-17T00:00:00.000Z",
+ ...extra,
+});
+
+/** Real mounted React components: disclosure ownership, preferences and search. */
+export async function turnProcessProbe() {
+ const i18n = createInstance();
+ await i18n.init({
+ lng: "en",
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+ });
+ const container = document.createElement("div");
+ document.body.append(container);
+ const initialSettings = useAppStore.getState().settings;
+ const settings: AppSettings = {
+ defaultMode: "agent",
+ theme: "light",
+ enterToSend: true,
+ onboardingDismissed: true,
+ };
+ flushSync(() => useAppStore.setState({ settings }));
+ const errors: unknown[] = [];
+ const root = createRoot(container, {
+ onUncaughtError: (error) => errors.push(error),
+ });
+ const notes: string[] = [];
+ const check = (value: unknown, name: string) => {
+ assert(value, name);
+ notes.push(name);
+ };
+ const render = (
+ messages: UiMessage[],
+ active = false,
+ search: TranscriptSearchTarget | null = null,
+ key = "turn",
+ ) => {
+ const entry = buildTranscriptEntries(messages).entries.find(
+ (item) => item.kind === "assistant-turn",
+ );
+ assert(entry?.kind === "assistant-turn", "missing turn");
+ flushSync(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <TranscriptSearchContext.Provider value={search}>
+ <AssistantTurn key={key} entry={entry} isActive={active} />
+ </TranscriptSearchContext.Provider>
+ </I18nextProvider>,
+ ),
+ );
+ assert(!errors.length, `React error: ${errors.map(String).join("; ")}`);
+ };
+ const header = () =>
+ container.querySelector<HTMLButtonElement>(".turn-process > button");
+ const process = () => container.querySelector<HTMLElement>(".turn-process-body");
+ const visible = (element: Element | null) =>
+ Boolean(element?.getBoundingClientRect().height);
+ const click = (element: HTMLElement | null) => {
+ assert(element, "missing click target");
+ flushSync(() => element.click());
+ };
+ const intro = message("intro", "assistant", "Inspecting the files", {
+ thinking: "reasoning detail",
+ status: "complete",
+ });
+ const read = message("read", "tool", "read output", {
+ toolName: "Read",
+ toolCallId: "read-call",
+ toolStatus: "success",
+ toolArgs: { path: "src/example.ts" },
+ });
+ const progress = message("progress", "assistant", "Found the problem");
+ const edit = message("edit", "tool", "edit output", {
+ toolName: "Edit",
+ toolCallId: "edit-call",
+ toolStatus: "success",
+ toolArgs: { path: "src/example.ts" },
+ });
+ const answer = message("answer", "assistant", "The fix is ready.", {
+ status: "complete",
+ createdAt: "2026-09-17T00:00:03.000Z",
+ responseDurationMs: 1000,
+ });
+ const messages = [intro, read, progress, edit, answer];
+ try {
+ render(messages);
+ check(
+ container.querySelectorAll(".turn-process").length === 1,
+ "one process per turn",
+ );
+ check(
+ header()?.getAttribute("aria-expanded") === "false" && !visible(process()),
+ "completed process starts collapsed",
+ );
+ check(
+ visible(container.querySelector('[data-message-id="answer"]')),
+ "final answer stays visible",
+ );
+ check(
+ header()?.textContent?.includes("5 steps"),
+ "process counts thought, tools and progress once",
+ );
+ click(header());
+ check(
+ visible(container.querySelector('[data-message-id="progress"]')),
+ "expanding reveals intermediate progress",
+ );
+ check(
+ process()?.querySelectorAll(".tool-row").length === 3,
+ "expanding retains thinking and both tools",
+ );
+ render(messages, true);
+ render(messages);
+ check(
+ header()?.getAttribute("aria-expanded") === "true",
+ "manual disclosure survives active-to-complete transition",
+ );
+
+ render([intro, read], true, null, "live");
+ check(
+ header()?.getAttribute("aria-expanded") === "true",
+ "detailed process opens while active",
+ );
+ render(messages, false, null, "live");
+ check(
+ header()?.getAttribute("aria-expanded") === "false",
+ "unclaimed process collapses on completion",
+ );
+ render(
+ messages,
+ false,
+ { sessionId: "s", messageId: "progress", query: "problem", requestId: 1 },
+ "live",
+ );
+ check(
+ visible(container.querySelector('[data-message-id="progress"]')),
+ "search reveals folded progress",
+ );
+
+ const streaming = message("stream", "assistant", "Live text", {
+ status: "streaming",
+ });
+ render([streaming], true, null, "stream");
+ check(
+ !header() && visible(container.querySelector('[data-message-id="stream"]')),
+ "streamed answer is never delayed behind disclosure",
+ );
+ render([streaming, read], true, null, "stream");
+ check(
+ process()?.querySelector('[data-message-id="stream"]'),
+ "later tool moves provisional text into process",
+ );
+ render([intro, read, { ...answer, status: "aborted" }], false, null, "aborted");
+ check(
+ visible(container.querySelector('[data-message-id="answer"]')),
+ "stopped partial answer remains visible",
+ );
+ render(
+ [
+ intro,
+ read,
+ message("failure", "assistant", "", {
+ error: { code: "INTERNAL", message: "Connection failed", retryable: true },
+ }),
+ ],
+ false,
+ null,
+ "error",
+ );
+ check(
+ visible(container.querySelector('[data-message-id="failure"]')),
+ "failure remains outside folded process",
+ );
+
+ render(
+ [intro, { ...read, toolStatus: "error", isError: true }, answer],
+ true,
+ null,
+ "tool-error",
+ );
+ check(
+ header()?.getAttribute("aria-expanded") === "true" && visible(process()),
+ "an active tool failure opens an unclaimed process",
+ );
+
+ let saved: Partial<AppSettings> | undefined;
+ flushSync(() =>
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <ThinkingDisplayModeRow
+ settings={settings}
+ saveSettings={async (patch) => {
+ saved = patch;
+ useAppStore.setState({ settings: { ...settings, ...patch } });
+ }}
+ />
+ </I18nextProvider>,
+ ),
+ );
+ click(container.querySelector('button[aria-haspopup="listbox"]'));
+ click(
+ Array.from(document.querySelectorAll<HTMLElement>('[role="option"]')).find(
+ (item) => item.textContent === "Compact",
+ ) ?? null,
+ );
+ check(
+ saved?.thinkingDisplayMode === "compact",
+ "settings control saves compact mode",
+ );
+
+ render(
+ [intro, { ...read, toolStatus: "error", isError: true }, answer],
+ true,
+ null,
+ "compact-error",
+ );
+ check(
+ header()?.getAttribute("aria-expanded") === "true" && visible(process()),
+ "compact mode reveals an active tool failure",
+ );
+
+ const thought = message("thought", "assistant", "", {
+ thinking: "hidden thinking words",
+ status: "streaming",
+ });
+ render([thought], true, null, "compact");
+ check(
+ Boolean(header()) && !container.textContent?.includes("hidden thinking words"),
+ "compact live thinking has status without reasoning text",
+ );
+ click(header());
+ check(
+ visible(container.querySelector(".thinking-compact")),
+ "compact live thinking remains indicator-only when expanded",
+ );
+ render([{ ...thought, status: "complete" }], false, null, "compact");
+ check(
+ !header() && !container.querySelector(".thinking"),
+ "completed compact thinking leaves no empty process or thought block",
+ );
+ render([{ ...thought, content: "Started answer" }], true, null, "compact");
+ check(
+ !container.querySelector(".thinking") &&
+ visible(container.querySelector('[data-message-id="thought"]')),
+ "compact thinking ends as soon as answer text starts",
+ );
+ render(messages, false, null, "compact-tools");
+ click(header());
+ check(
+ !container.querySelector(".thinking") &&
+ process()?.querySelectorAll(".tool-row").length === 2,
+ "compact keeps tools and progress accessible",
+ );
+ flushSync(() =>
+ useAppStore.setState({
+ settings: { ...settings, thinkingDisplayMode: "detailed" },
+ }),
+ );
+ check(
+ Boolean(container.querySelector(".thinking")),
+ "mode changes update mounted history",
+ );
+ check(
+ messages[0].thinking === "reasoning detail",
+ "presentation never deletes reasoning data",
+ );
+ return { ok: true, checks: notes };
+ } finally {
+ flushSync(() => root.unmount());
+ useAppStore.setState({ settings: initialSettings });
+ container.remove();
+ }
+}