Skip to content

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

fix(renderer): avoid full-history work while streaming

vastsa9845679aa831
diff --git a/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx b/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx
index 5f45267cd..8b725b69c 100644
--- a/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx
+++ b/apps/desktop/src/features/chat/transcript/ActivityGroup.tsx
@@ -1,12 +1,14 @@
-import { visibleActivityItems } from "../../../lib/activity-summary";
+import { activityTimingInputs, cachedVisibleActivityItems } from "../../../lib/transcript-activity-summary";
+import { reuseReferences } from "../../../lib/transcript-summary";
+import { ActivityItems } from "./ActivityItems";
import { DisclosureScope, disclosureKey } from "./disclosure";
import { ProcessActivityGroup } from "./ProcessActivityGroup";
import {
- Fragment,
memo,
useContext,
useEffect,
useId,
+ useMemo,
useRef,
useState,
} from "react";
@@ -43,20 +45,15 @@ import {
getToolAction,
getToolSummary,
} from "../../../lib/tool-display";
-import { ReviewChangeCard } from "../../../components/ReviewChangeCard";
import { IconChevronRight, IconCircleAlert, IconSparkles, IconWorkflow } from "../../../components/icons";
import {
DisclosureCollapseRail,
TOOL_RUNNING_KEYS,
- ThinkingRow,
useAutomaticDisclosure,
} from "./shared";
-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";
-import { HostedSearchRow } from "./HostedSearchRow";
type Translate = (key: string, options?: Record<string, unknown>) => string;
@@ -168,6 +165,7 @@ export function activityItemsEqual(
previous: ActivityItem,
next: ActivityItem,
): boolean {
+ if (previous === next) return true;
if (previous.kind !== next.kind || previous.message !== next.message) {
return false;
}
@@ -195,18 +193,19 @@ function activityGroupPropsEqual(
return false;
}
if (
+ previous.items !== next.items &&
!previous.items.every((item, index) =>
activityItemsEqual(item, next.items[index]),
)
) {
return false;
}
- // Text updates rebuild the turn's delegation maps. Only Task groups consume
- // those maps; ordinary completed work must retain its render boundary.
+ // Only Task groups consume the turn-wide delegation maps. Ordinary completed
+ // work must retain its render boundary when another group's tools update.
return (
- !previous.items.some(isDelegationActivityItem) ||
(previous.turnDelegationStatuses === next.turnDelegationStatuses &&
- previous.turnDelegationTimings === next.turnDelegationTimings)
+ previous.turnDelegationTimings === next.turnDelegationTimings) ||
+ !previous.items.some(isDelegationActivityItem)
);
}
@@ -225,7 +224,15 @@ export const ActivityGroup = memo(function ActivityGroup({
);
const { t } = useTranslation();
const detailsId = useId();
- const delegateItems = items.filter(isDelegationActivityItem);
+ const rawDelegateItems = useMemo(() => items.filter(isDelegationActivityItem), [items]);
+ const delegatesRef = useRef(rawDelegateItems);
+ const delegateItems = reuseReferences(delegatesRef.current, rawDelegateItems);
+ delegatesRef.current = delegateItems;
+ const rawTools = useMemo(() => items.flatMap((item) => item.kind === "tool" ? [item.message] : []), [items]);
+ const toolsRef = useRef(rawTools);
+ const tools = reuseReferences(toolsRef.current, rawTools);
+ toolsRef.current = tools;
+ const delegationItems = useMemo(() => tools.map((message) => ({ kind: "tool" as const, message })), [tools]);
// One delegation reads the same as five: the card is how a delegation is
// presented, not a treatment reserved for fan-out. A lone `Task` rendered as
// an ordinary tool row hid the outcome, runtime and step count that the card
@@ -236,21 +243,20 @@ export const ActivityGroup = memo(function ActivityGroup({
// tool is in a different activity part (the agent emitted text between Task
// and TaskWait), the turn-level statuses computed by the parent give us the
// cross-part view we need.
- const delegationStatuses = turnDelegationStatuses ?? collectDelegationStatuses(items);
- const delegationTimings =
- turnDelegationTimings ?? collectDelegationTimings(items);
- const subagentSummary = summarizeSubagentActivity(
+ const delegationStatuses = useMemo(() => turnDelegationStatuses ?? collectDelegationStatuses(delegationItems), [turnDelegationStatuses, delegationItems]);
+ const delegationTimings = useMemo(() => turnDelegationTimings ?? collectDelegationTimings(delegationItems), [turnDelegationTimings, delegationItems]);
+ const subagentSummary = useMemo(() => summarizeSubagentActivity(
delegateItems,
delegationStatuses,
- );
+ ), [delegateItems, delegationStatuses]);
// Parent tools after a Task fan-out live in a later activity part (D319), so
// this card is not the turn's live tail while its delegates are still running.
const topologyLive = hasSubagentTopology && subagentSummary.running > 0;
const live = isActive || topologyLive;
const searchTarget = useContext(TranscriptSearchContext);
- const revealRequest = searchTarget && items.some((item) => item.message.id === searchTarget.messageId)
- ? searchTarget.requestId : undefined;
- const visibleItems = visibleActivityItems(items, compact, isActive);
+ const revealRequest = useMemo(() => searchTarget && items.some((item) => item.message.id === searchTarget.messageId)
+ ? searchTarget.requestId : undefined, [items, searchTarget]);
+ const visibleItems = useMemo(() => cachedVisibleActivityItems(items, compact, isActive), [items, compact, isActive]);
const first = items[0];
const disclosure = useAutomaticDisclosure(
hasSubagentTopology ? live : visibleItems.length <= 1 || (!compact && live),
@@ -261,23 +267,12 @@ export const ActivityGroup = memo(function ActivityGroup({
const [now, setNow] = useState(Date.now);
const [finishedAt, setFinishedAt] = useState<number | null>(null);
const wasActiveRef = useRef(live);
- const messages = items.map((item) => item.message);
- const topologyTiming = hasSubagentTopology
- ? delegationTimingBounds(delegateItems, delegationTimings)
- : null;
- const startedAt =
- topologyTiming?.startedAt ??
- (Date.parse(messages[0]?.createdAt || "") || now);
- const fallbackEnd =
- Math.max(
- startedAt,
- ...messages.map(
- (message) =>
- Date.parse(message.toolCompletedAt || "") ||
- (Date.parse(message.createdAt) || startedAt) +
- (message.toolDurationMs || 0),
- ),
- );
+ const timingInputs = useMemo(() => activityTimingInputs(items), [items]);
+ const topologyTiming = useMemo(() => hasSubagentTopology
+ ? delegationTimingBounds(delegateItems, delegationTimings) : null,
+ [hasSubagentTopology, delegateItems, delegationTimings]);
+ const startedAt = topologyTiming?.startedAt ?? (timingInputs.startedAt || now);
+ const fallbackEnd = Math.max(startedAt, timingInputs.recordedEnd, startedAt + timingInputs.missingStartDuration);
const completedAt =
topologyTiming?.completedAt ??
(Date.parse(endedAt || "") ||
@@ -293,7 +288,7 @@ export const ActivityGroup = memo(function ActivityGroup({
isActive &&
lastItem?.kind === "thinking" &&
lastItem.message.status === "streaming";
- const onlyThinking = items.every((item) => item.kind === "thinking");
+ const onlyThinking = useMemo(() => items.every((item) => item.kind === "thinking"), [items]);
const label = hasSubagentTopology
? t(
live
@@ -320,10 +315,10 @@ export const ActivityGroup = memo(function ActivityGroup({
const runtimeStatus = runtimeActivity
? runActivityLabel(runtimeActivity, t as Translate)
: "";
- const currentDetail =
+ const currentDetail = useMemo(() =>
live && !runtimeStatus && lastItem && !(compact && lastItem.kind === "thinking")
- ? activityItemDetail(lastItem)
- : "";
+ ? activityItemDetail(lastItem) : "",
+ [live, runtimeStatus, lastItem, compact]);
const tail = live && !open ? currentDetail : "";
useEffect(() => {
@@ -335,66 +330,22 @@ export const ActivityGroup = memo(function ActivityGroup({
return () => window.clearInterval(id);
}, [live]);
- const renderActivityItems = () => {
- let renderedTopology = false;
- return items.map((item, itemIndex) => {
- if (hasSubagentTopology && isDelegationActivityItem(item)) {
- if (renderedTopology) return null;
- renderedTopology = true;
- return (
- <SubagentTopology
- key="subagent-topology"
- items={delegateItems}
- delegationStatuses={delegationStatuses}
- delegationTimings={delegationTimings}
- onUserInteraction={claimDisclosure}
- />
- );
- }
- const autoOpenLatest =
- !compact && isLast && itemIndex === items.length - 1;
- if (item.kind === "tool") {
- return (
- <Fragment key={item.message.id}>
- <ToolRow
- imagesInTurn
- message={item.message}
- autoOpen={autoOpenLatest}
- onUserInteraction={claimDisclosure}
- {...(item.delegate ? { delegate: item.delegate } : {})}
- />
- <ReviewChangeCard message={item.message} />
- </Fragment>
- );
- }
- if (item.kind === "hostedSearch") {
- return (
- <HostedSearchRow
- key={`hosted-search-${item.message.id}-${item.round.id}`}
- messageId={item.message.id}
- round={item.round}
- streaming={isActive && item.message.status === "streaming"}
- autoOpen={autoOpenLatest}
- onUserInteraction={claimDisclosure}
- />
- );
- }
- return (
- <ThinkingRow
- key={`thinking-${item.message.id}`}
- message={item.message}
- streaming={isActive && item.message.status === "streaming"}
- autoOpen={live && itemIndex === items.length - 1}
- onUserInteraction={claimDisclosure}
- />
- );
- });
- };
+ const renderedItems = <ActivityItems
+ items={items}
+ compact={compact}
+ isLast={isLast}
+ isActive={isActive}
+ live={live}
+ delegateItems={delegateItems}
+ delegationStatuses={delegationStatuses}
+ delegationTimings={delegationTimings}
+ onUserInteraction={claimDisclosure}
+ />;
if (!hasSubagentTopology) {
return (
<ProcessActivityGroup items={visibleItems} active={isActive} disclosure={disclosure}>
- {renderActivityItems()}
+ {renderedItems}
</ProcessActivityGroup>
);
}
@@ -462,7 +413,7 @@ export const ActivityGroup = memo(function ActivityGroup({
label={t("chat.collapseActivityGroup")}
onCollapse={collapseDisclosure}
/>
- <DisclosureScope disclosure={disclosure}>{renderActivityItems()}</DisclosureScope>
+ <DisclosureScope disclosure={disclosure}>{renderedItems}</DisclosureScope>
</div>
</div>
</div>
diff --git a/apps/desktop/src/features/chat/transcript/ActivityItems.tsx b/apps/desktop/src/features/chat/transcript/ActivityItems.tsx
new file mode 100644
index 000000000..6b88273d7
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/ActivityItems.tsx
@@ -0,0 +1,106 @@
+import { Fragment, memo } from "react";
+import type { AssistantActivityItem } from "../../../lib/assistant-turns";
+import { isDelegationActivityItem, type DelegationActivityItem, type SubagentOutcome, type SubagentTiming } from "../../../lib/subagent-topology";
+import { ReviewChangeCard } from "../../../components/ReviewChangeCard";
+import { ThinkingRow } from "./shared";
+import { HostedSearchRow } from "./HostedSearchRow";
+import { SubagentTopology } from "./SubagentDetail";
+import { ToolRow } from "./ToolRow";
+import { useRenderBlocks, type RenderBlock } from "./render-blocks";
+
+function itemKey(item: AssistantActivityItem) {
+ if (item.kind === "tool") return item.message.id;
+ if (item.kind === "hostedSearch") return `hosted-search-${item.message.id}-${item.round.id}`;
+ return `thinking-${item.message.id}`;
+}
+
+type ActivityItemsProps = {
+ items: readonly AssistantActivityItem[];
+ compact: boolean;
+ isLast: boolean;
+ isActive: boolean;
+ live: boolean;
+ delegateItems: DelegationActivityItem[];
+ delegationStatuses: ReadonlyMap<string, SubagentOutcome>;
+ delegationTimings: ReadonlyMap<string, SubagentTiming>;
+ onUserInteraction: () => void;
+};
+
+type ActivityItemBlockProps = Omit<ActivityItemsProps, "items" | "delegateItems" | "delegationStatuses" | "delegationTimings"> & {
+ block: RenderBlock<AssistantActivityItem>;
+ lastItem?: AssistantActivityItem;
+ topologyItem?: AssistantActivityItem;
+ delegateItems?: DelegationActivityItem[];
+ delegationStatuses?: ReadonlyMap<string, SubagentOutcome>;
+ delegationTimings?: ReadonlyMap<string, SubagentTiming>;
+};
+
+const ActivityItemBlock = memo(function ActivityItemBlock({
+ block, compact, isLast, isActive, live, lastItem, topologyItem,
+ delegateItems, delegationStatuses, delegationTimings, onUserInteraction,
+}: ActivityItemBlockProps) {
+ return <>{block.items.map((item) => {
+ // The topology predicate narrows to all tools, but a false result can still
+ // be an ordinary tool. Do not exclude tools from the remaining branches.
+ const delegation = Boolean(isDelegationActivityItem(item));
+ if (delegation) {
+ if (item !== topologyItem || !delegateItems) return null;
+ return <SubagentTopology
+ key="subagent-topology"
+ items={delegateItems}
+ delegationStatuses={delegationStatuses}
+ delegationTimings={delegationTimings}
+ onUserInteraction={onUserInteraction}
+ />;
+ }
+ // The literal last item of the last activity part owns this default,
+ // never the last item of an internal render block.
+ const autoOpenLatest = !compact && isLast && item === lastItem;
+ if (item.kind === "tool") return (
+ <Fragment key={item.message.id}>
+ <ToolRow imagesInTurn message={item.message} autoOpen={autoOpenLatest}
+ onUserInteraction={onUserInteraction} {...(item.delegate ? { delegate: item.delegate } : {})} />
+ <ReviewChangeCard message={item.message} />
+ </Fragment>
+ );
+ if (item.kind === "hostedSearch") return <HostedSearchRow
+ key={`hosted-search-${item.message.id}-${item.round.id}`}
+ messageId={item.message.id}
+ round={item.round}
+ streaming={isActive && item.message.status === "streaming"}
+ autoOpen={autoOpenLatest}
+ onUserInteraction={onUserInteraction}
+ />;
+ return <ThinkingRow
+ key={`thinking-${item.message.id}`}
+ message={item.message}
+ streaming={isActive && item.message.status === "streaming"}
+ autoOpen={live && item === lastItem}
+ onUserInteraction={onUserInteraction}
+ />;
+ })}</>;
+});
+
+export const ActivityItems = memo(function ActivityItems({ items, ...context }: ActivityItemsProps) {
+ const blocks = useRenderBlocks(items, itemKey);
+ const lastItem = items.at(-1);
+ const topologyItem = context.delegateItems[0];
+ return <>{blocks.map((block) => {
+ const ownsLast = lastItem !== undefined && block.items.includes(lastItem);
+ const ownsTopology = topologyItem !== undefined && block.items.includes(topologyItem);
+ return <ActivityItemBlock
+ key={block.key}
+ block={block}
+ compact={context.compact}
+ isLast={ownsLast && context.isLast}
+ isActive={context.isActive}
+ live={context.live}
+ lastItem={ownsLast ? lastItem : undefined}
+ topologyItem={ownsTopology ? topologyItem : undefined}
+ delegateItems={ownsTopology ? context.delegateItems : undefined}
+ delegationStatuses={ownsTopology ? context.delegationStatuses : undefined}
+ delegationTimings={ownsTopology ? context.delegationTimings : undefined}
+ onUserInteraction={context.onUserInteraction}
+ />;
+ })}</>;
+});
diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
index 717479e83..1657c9122 100644
--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
@@ -8,18 +8,11 @@ import { useTranslation } from "react-i18next";
import type {
AgentActivity,
ContextCompactionMark,
- UiMessage,
} from "@pi-desktop/shared";
import { formatCompactTokenCount } from "@pi-desktop/shared";
import {
- assistantTurnContent,
- assistantTurnMessages,
- assistantTurnResponseDuration,
- assistantTurnResponseOutputTokens,
- assistantTurnUsage,
reuseReadonlyMap,
type AssistantTurnEntry,
- type AssistantTurnPart,
type TranscriptEntry,
} from "../../../lib/assistant-turns";
import {
@@ -27,22 +20,18 @@ import {
collectDelegationTimings,
} from "../../../lib/subagent-topology";
import {
- isLastActivityPart,
- projectTurnProcess,
resolveThinkingDisplayMode,
shouldGroupTurnProcess,
} from "../../../lib/turn-process";
import { useAppStore } from "../../../stores/app-store";
-import { Markdown } from "../../../components/Markdown";
import { IconBranch, IconReview } from "../../../components/icons";
import { TooltipButton } from "../../../components/ui";
import {
- AssistantErrorMessage,
CopyButton,
MessageMeta,
MessageTimestamp,
} from "./shared";
-import { activityItemsEqual, ActivityGroup } from "./ActivityGroup";
+import { activityItemsEqual } from "./ActivityGroup";
import { GeneratedImages } from "./GeneratedImages";
import { MessageRow } from "./MessageRow";
import { assistantTurnMenuItems } from "./menu-items";
@@ -50,7 +39,12 @@ import {
useChatTextActions,
useTranscriptMenu,
} from "./TranscriptMenu";
-import { useSmoothText } from "../../../hooks/useSmoothText";
+import {
+ getAssistantTurnSummary,
+ getAssistantTurnContent,
+ reuseReferences,
+} from "../../../lib/transcript-summary";
+import { AssistantTurnParts } from "./AssistantTurnParts";
import { TurnProcess } from "./TurnProcess";
import { ActionSlotSide } from "./ActionBarSlots";
import { EntryExtraStack } from "./EntryExtraStack";
@@ -66,16 +60,19 @@ function assistantTurnPropsEqual(
previous: AssistantTurnProps,
next: AssistantTurnProps,
) {
+ if (previous.isActive !== next.isActive || previous.runtimeActivity !== next.runtimeActivity) return false;
+ if (previous.entry === next.entry) return true;
if (
- previous.isActive !== next.isActive ||
- previous.runtimeActivity !== next.runtimeActivity ||
+ previous.entry.id !== next.entry.id ||
previous.entry.anchorId !== next.entry.anchorId ||
previous.entry.parts.length !== next.entry.parts.length
) {
return false;
}
+ if (previous.entry.parts === next.entry.parts) return true;
return previous.entry.parts.every((part, index) => {
const nextPart = next.entry.parts[index];
+ if (part === nextPart) return true;
if (part.kind !== nextPart.kind) return false;
if (part.kind === "message" && nextPart.kind === "message") {
return part.message === nextPart.message;
@@ -84,9 +81,9 @@ function assistantTurnPropsEqual(
return (
part.endedAt === nextPart.endedAt &&
part.items.length === nextPart.items.length &&
- part.items.every((item, itemIndex) =>
+ (part.items === nextPart.items || part.items.every((item, itemIndex) =>
activityItemsEqual(item, nextPart.items[itemIndex]),
- )
+ ))
);
}
return false;
@@ -194,6 +191,7 @@ export const TranscriptHistory = memo(function TranscriptHistory({
) {
return false;
}
+ if (previous.entries === next.entries) return true;
return previous.entries.every((entry, index) =>
transcriptEntryEqual(entry, next.entries[index]),
);
@@ -225,47 +223,6 @@ export const TranscriptTail = memo(function TranscriptTail({
transcriptEntryEqual(previous.entry, next.entry)
);
-/** Message bubble that optionally applies smooth text release. */
-const SmoothMessageBubble = memo(function SmoothMessageBubble({
- message,
- streaming,
-}: {
- message: UiMessage;
- streaming: boolean;
-}) {
- const smoothStreaming = useAppStore(
- (s) => s.settings?.smoothStreaming !== false,
- );
- const prefersReducedMotion =
- typeof window !== "undefined" &&
- window.matchMedia("(prefers-reduced-motion: reduce)").matches;
- const enabled = smoothStreaming && !prefersReducedMotion;
- const displayContent = useSmoothText(
- message.content || "",
- streaming,
- enabled,
- );
- const showCursor = streaming && enabled && (displayContent.length < (message.content || "").length);
-
- return (
- <div
- className={`message-bubble assistant-turn-fragment${
- streaming ? " streaming" : ""
- }${showCursor ? " smooth-cursor" : ""}`}
- data-message-id={message.id}
- >
- {displayContent ? (
- <div className="prose-chat">
- <Markdown source={displayContent} />
- </div>
- ) : null}
- {message.error ? (
- <AssistantErrorMessage message={message} />
- ) : null}
- </div>
- );
-});
-
export const AssistantTurn = memo(function AssistantTurn({
entry,
isActive,
@@ -276,38 +233,20 @@ export const AssistantTurn = memo(function AssistantTurn({
const { copyText, selectText } = useChatTextActions();
const retryAssistantMessage = useAppStore((s) => s.retryAssistantMessage);
const forkAssistantMessage = useAppStore((s) => s.forkAssistantMessage);
- const messages = assistantTurnMessages(entry);
- const content = assistantTurnContent(entry);
- const actionMessage = [...messages]
- .reverse()
- .find((message) => (message.content || "").trim());
- const metaMessage = [...messages]
- .reverse()
- .find(
- (message) =>
- message.modelId ||
- message.usage ||
- message.responseDurationMs ||
- message.responseOutputTokens,
- );
- const latestUsageMessage = [...messages]
- .reverse()
- .find((message) => message.usage);
- const usage = assistantTurnUsage(entry);
- const responseDurationMs = assistantTurnResponseDuration(entry);
- const responseOutputTokens = assistantTurnResponseOutputTokens(entry);
+ const summary = getAssistantTurnSummary(entry);
+ const { actionMessage, metaMessage, latestUsageMessage, usage, responseDurationMs, responseOutputTokens } = summary;
const modelId = metaMessage?.modelId ?? latestUsageMessage?.modelId;
- const hasError = messages.some((message) => Boolean(message.error));
- const complete =
- !isActive && !hasError && Boolean(content) && Boolean(actionMessage);
- // Plugins see a finished reply as the host keys act on it: the id of its
- // answer message and the text Copy copies.
- const slotReply =
- complete && actionMessage
- ? slotMessage("assistant", { ...actionMessage, content })
- : undefined;
- const streaming =
- isActive && messages.some((message) => message.status === "streaming");
+ const complete = !isActive && !summary.hasError && summary.hasContent && Boolean(actionMessage);
+ // A live reply is joined only on menu/copy demand. Finished reply plugins
+ // still receive exactly the text that the completed turn's Copy action uses.
+ const content = useMemo(
+ () => complete ? getAssistantTurnContent(entry) : "",
+ [complete, entry],
+ );
+ const slotReply = useMemo(() => complete && actionMessage
+ ? slotMessage("assistant", { ...actionMessage, content }) : undefined,
+ [complete, actionMessage, content]);
+ const streaming = isActive && summary.streaming;
/*
The turn owns the menu for its whole subtree, the answer rows it renders
included: Regenerate and Branch act on the turn's answer message, so a menu
@@ -318,7 +257,7 @@ export const AssistantTurn = memo(function AssistantTurn({
label: t("chat.messageMenu"),
items: assistantTurnMenuItems({
t,
- answer: content,
+ answer: complete ? content : getAssistantTurnContent(entry),
selectTarget:
[
...event.currentTarget.querySelectorAll<HTMLElement>(
@@ -339,21 +278,22 @@ export const AssistantTurn = memo(function AssistantTurn({
// Collect delegation statuses across ALL activity parts of this turn so that
// a TaskWait in one part can inform the Task cards in a different part.
- const turnAllActivityItems = useMemo(
- () =>
- entry.parts.flatMap((part) =>
- part.kind === "activity" ? part.items : [],
- ),
- [entry.parts],
- );
+ const toolsRef = useRef(summary.tools);
+ const tools = reuseReferences(toolsRef.current, summary.tools);
+ toolsRef.current = tools;
+ const generatedImages = useMemo(() => tools
+ .filter((message) => message.toolName === "GenerateImages")
+ .map((message) => <GeneratedImages key={message.id} message={message} />), [tools]);
+ // Delegation status/timing depends on actual tool messages, never on thinking
+ // or text and never on a Task's attached child transcript identity.
+ const delegationItems = useMemo(() => tools.map((message) => ({ kind: "tool" as const, message })), [tools]);
const rawDelegationStatuses = useMemo(
- () =>
- collectDelegationStatuses(turnAllActivityItems, { turnLive: isActive }),
- [turnAllActivityItems, isActive],
+ () => collectDelegationStatuses(delegationItems, { turnLive: isActive }),
+ [delegationItems, isActive],
);
const rawDelegationTimings = useMemo(
- () => collectDelegationTimings(turnAllActivityItems),
- [turnAllActivityItems],
+ () => collectDelegationTimings(delegationItems),
+ [delegationItems],
);
const statusesRef = useRef(rawDelegationStatuses);
const timingsRef = useRef(rawDelegationTimings);
@@ -374,29 +314,9 @@ export const AssistantTurn = memo(function AssistantTurn({
resolveThinkingDisplayMode(state.settings?.thinkingDisplayMode),
),
);
- const { process, responses } = projectTurnProcess(entry);
+ const { process, responses, lastActivityPart } = summary;
const activePart = isActive ? entry.parts.at(-1) : undefined;
-
- const renderPart = (part: AssistantTurnPart) =>
- part.kind === "activity" ? (
- <ActivityGroup
- embedded
- key={`activity-${part.items[0].message.id}-${part.items[0].kind}${part.items[0].kind === "hostedSearch" ? `-${part.items[0].round.id}` : ""}`}
- items={part.items}
- endedAt={part.endedAt}
- isActive={part === activePart}
- isLast={isLastActivityPart(entry.parts, part)}
- runtimeActivity={part === activePart ? runtimeActivity : undefined}
- turnDelegationStatuses={turnDelegationStatuses}
- turnDelegationTimings={turnDelegationTimings}
- />
- ) : (
- <SmoothMessageBubble
- key={part.message.id}
- message={part.message}
- streaming={isActive && part.message.status === "streaming"}
- />
- );
+ const partContext = { isActive, activePart, lastActivityPart, runtimeActivity, turnDelegationStatuses, turnDelegationTimings };
return (
<div
@@ -411,16 +331,14 @@ export const AssistantTurn = memo(function AssistantTurn({
{groupProcess ? (
<>
<TurnProcess turnId={entry.id} processParts={process} turnParts={entry.parts} isActive={isActive} delegationStatuses={turnDelegationStatuses}>
- {process.map(renderPart)}
+ <AssistantTurnParts parts={process} {...partContext} />
</TurnProcess>
- {responses.map(renderPart)}
+ <AssistantTurnParts parts={responses} {...partContext} />
</>
) : (
- entry.parts.map(renderPart)
+ <AssistantTurnParts parts={entry.parts} {...partContext} />
)}
- {turnAllActivityItems.filter((item) => item.kind === "tool" && item.message.toolName === "GenerateImages").map((item) => (
- <GeneratedImages key={item.message.id} message={item.message} />
- ))}
+ {generatedImages}
{!isActive && metaMessage ? (
<MessageMeta
modelId={modelId}
diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx
new file mode 100644
index 000000000..48587f6eb
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx
@@ -0,0 +1,92 @@
+import { memo } from "react";
+import type { AgentActivity, UiMessage } from "@pi-desktop/shared";
+import type { AssistantTurnPart } from "../../../lib/assistant-turns";
+import type { SubagentOutcome, SubagentTiming } from "../../../lib/subagent-topology";
+import { useAppStore } from "../../../stores/app-store";
+import { Markdown } from "../../../components/Markdown";
+import { useSmoothText } from "../../../hooks/useSmoothText";
+import { ActivityGroup } from "./ActivityGroup";
+import { AssistantErrorMessage } from "./shared";
+import { useRenderBlocks, type RenderBlock } from "./render-blocks";
+
+/** Message bubble that optionally applies smooth text release. */
+const SmoothMessageBubble = memo(function SmoothMessageBubble({ message, streaming }: {
+ message: UiMessage;
+ streaming: boolean;
+}) {
+ const smoothStreaming = useAppStore((s) => s.settings?.smoothStreaming !== false);
+ const prefersReducedMotion = typeof window !== "undefined" &&
+ window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+ const enabled = smoothStreaming && !prefersReducedMotion;
+ const displayContent = useSmoothText(message.content || "", streaming, enabled);
+ const showCursor = streaming && enabled && (displayContent.length < (message.content || "").length);
+ return (
+ <div
+ className={`message-bubble assistant-turn-fragment${streaming ? " streaming" : ""}${showCursor ? " smooth-cursor" : ""}`}
+ data-message-id={message.id}
+ >
+ {displayContent ? <div className="prose-chat"><Markdown source={displayContent} /></div> : null}
+ {message.error ? <AssistantErrorMessage message={message} /> : null}
+ </div>
+ );
+});
+
+function partKey(part: AssistantTurnPart) {
+ if (part.kind === "message") return part.message.id;
+ const first = part.items[0];
+ return `activity-${first.message.id}-${first.kind}${first.kind === "hostedSearch" ? `-${first.round.id}` : ""}`;
+}
+
+type PartContext = {
+ isActive: boolean;
+ activePart?: AssistantTurnPart;
+ lastActivityPart?: AssistantTurnPart;
+ runtimeActivity?: AgentActivity;
+ turnDelegationStatuses: ReadonlyMap<string, SubagentOutcome>;
+ turnDelegationTimings: ReadonlyMap<string, SubagentTiming>;
+};
+
+const TurnPartBlock = memo(function TurnPartBlock({
+ block, isActive, activePart, lastActivityPart, runtimeActivity,
+ turnDelegationStatuses, turnDelegationTimings,
+}: PartContext & { block: RenderBlock<AssistantTurnPart> }) {
+ return <>{block.items.map((part) => part.kind === "activity" ? (
+ <ActivityGroup
+ embedded
+ key={partKey(part)}
+ items={part.items}
+ endedAt={part.endedAt}
+ isActive={part === activePart}
+ isLast={part === lastActivityPart}
+ runtimeActivity={part === activePart ? runtimeActivity : undefined}
+ turnDelegationStatuses={turnDelegationStatuses}
+ turnDelegationTimings={turnDelegationTimings}
+ />
+ ) : (
+ <SmoothMessageBubble
+ key={part.message.id}
+ message={part.message}
+ streaming={isActive && part.message.status === "streaming"}
+ />
+ ))}</>;
+});
+
+export const AssistantTurnParts = memo(function AssistantTurnParts({ parts, ...context }: PartContext & {
+ parts: readonly AssistantTurnPart[];
+}) {
+ const blocks = useRenderBlocks(parts, partKey);
+ return <>{blocks.map((block) => {
+ const activePart = context.activePart && block.items.includes(context.activePart) ? context.activePart : undefined;
+ const lastActivityPart = context.lastActivityPart && block.items.includes(context.lastActivityPart) ? context.lastActivityPart : undefined;
+ return <TurnPartBlock
+ key={block.key}
+ block={block}
+ isActive={context.isActive}
+ activePart={activePart}
+ lastActivityPart={lastActivityPart}
+ runtimeActivity={activePart ? context.runtimeActivity : undefined}
+ turnDelegationStatuses={context.turnDelegationStatuses}
+ turnDelegationTimings={context.turnDelegationTimings}
+ />;
+ })}</>;
+});
diff --git a/apps/desktop/src/features/chat/transcript/ProcessActivityGroup.tsx b/apps/desktop/src/features/chat/transcript/ProcessActivityGroup.tsx
index 36615c302..804faff24 100644
--- a/apps/desktop/src/features/chat/transcript/ProcessActivityGroup.tsx
+++ b/apps/desktop/src/features/chat/transcript/ProcessActivityGroup.tsx
@@ -1,7 +1,7 @@
-import { useId, type ReactNode } from "react";
+import { useId, useMemo, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import type { AssistantActivityItem } from "../../../lib/assistant-turns";
-import { activitySummary } from "../../../lib/activity-summary";
+import { cachedActivitySummary } from "../../../lib/transcript-activity-summary";
import { IconChevronRight, IconCircleAlert, IconSparkles } from "../../../components/icons";
import { DisclosureCollapseRail } from "./shared";
import { DisclosureScope, type useAutomaticDisclosure } from "./disclosure";
@@ -22,7 +22,7 @@ export function ProcessActivityGroup({
const detailsId = useId();
const grouped = items.length > 1;
const open = !grouped || disclosure.open;
- const summary = activitySummary(items);
+ const summary = useMemo(() => cachedActivitySummary(items), [items]);
if (items.length === 0) return null;
return (
<div className={`process-activity-group${grouped ? " grouped" : " singleton"}${open ? " open" : ""}`}>
diff --git a/apps/desktop/src/features/chat/transcript/TurnProcess.tsx b/apps/desktop/src/features/chat/transcript/TurnProcess.tsx
index 7721d7a72..95825e457 100644
--- a/apps/desktop/src/features/chat/transcript/TurnProcess.tsx
+++ b/apps/desktop/src/features/chat/transcript/TurnProcess.tsx
@@ -1,9 +1,9 @@
import type { SubagentOutcome } from "../../../lib/subagent-topology";
-import { useContext, useEffect, useId, useState, type ReactNode } from "react";
+import { useContext, useEffect, useId, useMemo, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import type { AssistantTurnPart } from "../../../lib/assistant-turns";
import { formatToolDuration } from "../../../lib/tool-display";
-import { activitySummary } from "../../../lib/activity-summary";
+import { cachedActivitySummary, cachedVisibleProcessSteps } from "../../../lib/transcript-activity-summary";
import { TranscriptSearchContext } from "../../../lib/transcript-search-context";
import {
isTurnThinking,
@@ -11,7 +11,6 @@ import {
resolveThinkingDisplayMode,
shouldAutoOpenTurnProcess,
turnProcessTiming,
- visibleProcessSteps,
} from "../../../lib/turn-process";
import { useAppStore } from "../../../stores/app-store";
import {
@@ -40,10 +39,13 @@ export function TurnProcess({
const { t } = useTranslation();
const mode = useAppStore((state) => resolveThinkingDisplayMode(state.settings?.thinkingDisplayMode));
const search = useContext(TranscriptSearchContext);
- const revealRequest = search && processContainsMessage(processParts, search.messageId)
- ? search.requestId : undefined;
- const summary = activitySummary(processParts.flatMap((part) => part.kind === "activity" ? part.items : []), delegationStatuses);
- const thinkingNow = isTurnThinking(turnParts, isActive);
+ const revealRequest = useMemo(() => search && processContainsMessage(processParts, search.messageId)
+ ? search.requestId : undefined, [processParts, search]);
+ const summary = useMemo(() => cachedActivitySummary(
+ processParts.flatMap((part) => part.kind === "activity" ? part.items : []), delegationStatuses,
+ ), [processParts, delegationStatuses]);
+ const thinkingNow = useMemo(() => isTurnThinking(turnParts, isActive), [turnParts, isActive]);
+ const visibleSteps = useMemo(() => cachedVisibleProcessSteps(processParts, mode === "compact", isActive), [processParts, mode, isActive]);
const disclosure = useAutomaticDisclosure(
shouldAutoOpenTurnProcess(mode, isActive, summary.issues > 0),
revealRequest,
@@ -51,14 +53,14 @@ export function TurnProcess({
);
const detailsId = useId();
const [now, setNow] = useState(Date.now);
- const { startedAt, endedAt } = turnProcessTiming(turnParts);
+ const { startedAt, endedAt } = useMemo(() => turnProcessTiming(turnParts), [turnParts]);
useEffect(() => {
if (!isActive) return;
setNow(Date.now());
const timer = window.setInterval(() => setNow(Date.now()), 1000);
return () => window.clearInterval(timer);
}, [isActive]);
- if (visibleProcessSteps(processParts, mode, isActive) === 0) return null;
+ if (visibleSteps === 0) return null;
const seconds = startedAt === undefined ? 0 : Math.max(
0, Math.floor(((isActive ? now : (endedAt ?? startedAt)) - startedAt) / 1000),
);
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
index 45ecd37d2..4744995f6 100644
--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
@@ -13,12 +13,8 @@ import type {
UiMessage,
} from "@pi-desktop/shared";
import type { PendingPermission } from "../../../../lib/pending-permissions";
-import {
- buildTranscriptEntries,
- reuseTranscriptEntries,
- transcriptEntryMessages,
- type TranscriptEntry,
-} from "../../../../lib/assistant-turns";
+import { transcriptEntryMessages } from "../../../../lib/assistant-turns";
+import { getTranscriptProjection } from "../../../../lib/transcript-projection";
import {
createTranscriptSettleState,
reduceTranscriptSettle,
@@ -99,8 +95,6 @@ export function useTranscriptScroll({
// Read by `reachTop`, which must stay referentially stable for the scroll
// listener; the projection it describes is only known later in this render.
const historyLengthRef = useRef(0);
- const previousEntriesRef = useRef<TranscriptEntry[]>([]);
- const previousSessionIdRef = useRef(sessionId);
const scrollToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
const el = scrollRef.current;
@@ -446,36 +440,19 @@ export function useTranscriptScroll({
return () => ro.disconnect();
}, [followScrollNow]);
- // Streaming tokens are deferred so the full historical transcript tree does
- // not rebuild at the same priority as the tail. The pane's own first commit is
- // never deferred: its content must be on screen in the commit that reveals it,
- // otherwise the reveal shows one empty frame.
+ // Defer one immutable projection, never messages and compaction boundaries
+ // independently. First paint, reading, and pane reveal use the current source.
const firstCommitRef = useRef(true);
const firstCommit = firstCommitRef.current;
- // A retained pane can receive a newer live snapshot while it is hidden. Do
- // not let useDeferredValue reveal its previous frame first; the reveal itself
- // is a navigation boundary and must paint the snapshot selected for it.
const paneRevealed = paneVisible && !wasPaneVisibleRef.current;
- const deferredMessages = useDeferredValue(messages);
- const deferredCompactions = useDeferredValue(compactions);
- const renderedMessages =
- readingWindow || firstCommit || paneRevealed ? messages : deferredMessages;
- const renderedCompactions =
- firstCommit || paneRevealed ? compactions : deferredCompactions;
- const { entries, visible } = useMemo(() => {
- if (previousSessionIdRef.current !== sessionId) {
- previousSessionIdRef.current = sessionId;
- previousEntriesRef.current = [];
- }
- const built = buildTranscriptEntries(renderedMessages, renderedCompactions);
- const entries = reuseTranscriptEntries(previousEntriesRef.current, built.entries);
- previousEntriesRef.current = entries;
- return { entries, visible: built.visible };
- }, [renderedMessages, renderedCompactions, sessionId]);
- // Memoized so a re-render that changed no message (jump pill, loading row,
- // window growth) hands `TranscriptHistory` the same array, letting its
- // comparator bail on identity instead of walking every mounted row.
- const allHistoryEntries = useMemo(() => entries.slice(0, -1), [entries]);
+ const projection = useMemo(
+ () => getTranscriptProjection(messages, compactions),
+ [messages, compactions],
+ );
+ const deferredProjection = useDeferredValue(projection);
+ const renderedProjection =
+ readingWindow || firstCommit || paneRevealed ? projection : deferredProjection;
+ const { entries, visible, history: allHistoryEntries } = renderedProjection;
const tailEntry = entries.at(-1);
// Published for `reachTop`, which is declared above this projection but only
// runs from a scroll event, long after this render committed.
@@ -567,7 +544,9 @@ export function useTranscriptScroll({
}, [cancelFollowScroll, releaseDisclosureAnchor]);
useTranscriptSearchFocus({
target: searchTarget,
- source: messages.find((message) => message.id === searchTarget?.messageId)?.content ?? "",
+ source: searchTarget
+ ? messages.find((message) => message.id === searchTarget.messageId)?.content ?? ""
+ : "",
visible: paneVisible,
scrollRef,
contentRef,
diff --git a/apps/desktop/src/features/chat/transcript/render-blocks.ts b/apps/desktop/src/features/chat/transcript/render-blocks.ts
new file mode 100644
index 000000000..0fe3f3848
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/render-blocks.ts
@@ -0,0 +1,67 @@
+import { useLayoutEffect, useMemo, useRef } from "react";
+
+export type RenderBlock<T> = { key: string; items: readonly T[] };
+export const TRANSCRIPT_RENDER_BLOCK_SIZE = 64;
+
+/**
+ * Non-DOM reconciliation boundaries. Keep prior block membership rather than
+ * rechunking from index zero: prepended history must not remount every leaf.
+ * Work here is deliberately a shallow O(N) key/reference scan. Only changed
+ * blocks reconstruct React children; no message text or payload is inspected.
+ */
+export function reconcileRenderBlocks<T>(
+ previous: readonly RenderBlock<T>[] | undefined,
+ items: readonly T[],
+ keyOf: (item: T) => string,
+): readonly RenderBlock<T>[] {
+ const membership = new Map<string, string>();
+ const priorBlocks = new Map<string, RenderBlock<T>>();
+ for (const block of previous ?? []) {
+ priorBlocks.set(block.key, block);
+ for (const item of block.items) membership.set(keyOf(item), block.key);
+ }
+ const result: RenderBlock<T>[] = [];
+ const used = new Set<string>();
+ let current: T[] = [];
+ let currentKey = "";
+ let owner: string | undefined;
+ const flush = () => {
+ if (!current.length) return;
+ const prior = priorBlocks.get(currentKey);
+ result.push(prior && prior.items.length === current.length &&
+ prior.items.every((item, index) => item === current[index])
+ ? prior : { key: currentKey, items: current });
+ used.add(currentKey);
+ current = [];
+ };
+ for (const item of items) {
+ const key = keyOf(item);
+ const knownOwner = membership.get(key);
+ if (current.length && ((knownOwner !== undefined && knownOwner !== owner) ||
+ current.length >= TRANSCRIPT_RENDER_BLOCK_SIZE)) flush();
+ if (!current.length) {
+ owner = knownOwner;
+ currentKey = knownOwner ?? key;
+ // A corrected order can split one prior block into disjoint segments.
+ // Even the row-key fallback may equal a key already claimed by an earlier
+ // segment (the old block's first row may now appear later). Check every
+ // candidate, using deterministic encoded suffixes rather than a counter
+ // shared across renders or a remount-prone index-based block key.
+ for (let suffix = 1; used.has(currentKey); suffix += 1) {
+ currentKey = JSON.stringify(["transcript-block", key, suffix]);
+ }
+ }
+ current.push(item);
+ }
+ flush();
+ return previous && previous.length === result.length && previous.every((block, index) => block === result[index])
+ ? previous : result;
+}
+
+export function useRenderBlocks<T>(items: readonly T[], keyOf: (item: T) => string) {
+ const committed = useRef<readonly RenderBlock<T>[] | undefined>(undefined);
+ const blocks = useMemo(() => reconcileRenderBlocks(committed.current, items, keyOf), [items, keyOf]);
+ // Abandoned/deferred renders must not replace the committed membership.
+ useLayoutEffect(() => { committed.current = blocks; }, [blocks]);
+ return blocks;
+}
diff --git a/apps/desktop/src/lib/conversation-minimap.ts b/apps/desktop/src/lib/conversation-minimap.ts
index be417a7bb..644bbcfbe 100644
--- a/apps/desktop/src/lib/conversation-minimap.ts
+++ b/apps/desktop/src/lib/conversation-minimap.ts
@@ -1,4 +1,5 @@
import type { UiMessage } from "@pi-desktop/shared";
+import { messageContentFacts } from "./transcript-summary";
export type ConversationMinimapMarker = {
id: string;
@@ -42,16 +43,20 @@ export function buildConversationMinimapMarkers(
markers.push({
id: message.id,
role: "user",
- preview: (message.content || "")
- .trim()
- .slice(0, CONVERSATION_MINIMAP_PREVIEW_MAX_CHARS),
+ preview: messageContentFacts(message).trimmedContent.slice(
+ 0, CONVERSATION_MINIMAP_PREVIEW_MAX_CHARS,
+ ),
});
assistantMarkerIndex = null;
continue;
}
if (message.role !== "assistant") continue;
- const content = (message.content || "").trim();
+ // Later fragments cannot change a saturated preview or its first anchor.
+ if (assistantMarkerIndex !== null &&
+ markers[assistantMarkerIndex].preview.length >= CONVERSATION_MINIMAP_PREVIEW_MAX_CHARS
+ ) continue;
+ const content = messageContentFacts(message).trimmedContent;
if (!content) continue;
if (assistantMarkerIndex === null) {
markers.push({
diff --git a/apps/desktop/src/lib/latest-turn-context.ts b/apps/desktop/src/lib/latest-turn-context.ts
index add34979e..62d5084fd 100644
--- a/apps/desktop/src/lib/latest-turn-context.ts
+++ b/apps/desktop/src/lib/latest-turn-context.ts
@@ -5,16 +5,10 @@ import type {
ProviderPublic,
UiMessage,
} from "@pi-desktop/shared";
-import {
- assistantTurnResponseDuration,
- assistantTurnResponseOutputIsEstimated,
- assistantTurnResponseOutputTokens,
- assistantTurnTools,
- assistantTurnUsage,
- buildTranscriptEntries,
- type AssistantTurnEntry,
-} from "./assistant-turns";
-import { latestMessageUsage, resolveContextWindow } from "./context-usage";
+import { resolveContextWindow } from "./context-usage";
+import { getSessionMessageSnapshot } from "./session-transcript-updates";
+import { getTranscriptProjection } from "./transcript-projection";
+import { getAssistantTurnSummary } from "./transcript-summary";
export type LatestTurnContextInspector = {
usage: MessageUsage;
@@ -26,54 +20,73 @@ export type LatestTurnContextInspector = {
responseOutputEstimated: boolean;
};
+const inspectors = new WeakMap<object, LatestTurnContextInspector>();
+
+function sameUsage(previous: MessageUsage, next: MessageUsage): boolean {
+ return previous === next || (
+ Object.keys(previous).length === Object.keys(next).length &&
+ Object.keys(next).every((key) => previous[key as keyof MessageUsage] === next[key as keyof MessageUsage])
+ );
+}
+
/**
- * The composer inspector always mirrors the newest assistant turn that
- * reported usage, so a later streaming turn without totals does not steal
- * the previous ring's tools or throughput.
+ * The composer mirrors the newest parent turn with usage, not a later live turn
+ * without totals. It shares the transcript projection instead of rebuilding it.
*/
export function latestTurnContextInspector(
messages: UiMessage[],
providerModels: Record<string, ModelInfo[]>,
providers: ProviderPublic[],
- compactions: readonly ContextCompactionMark[] = [],
+ compactions?: readonly ContextCompactionMark[],
): LatestTurnContextInspector | undefined {
- // Delegate rows carry their own usage; remaining capacity is a parent-session
- // number, so those snapshots must not steal the composer ring.
- const parentMessages = messages.filter((message) => !message.parentToolCallId);
- const latestUsage = latestMessageUsage(parentMessages);
+ let latestUsageMessage: UiMessage | undefined;
+ for (let index = messages.length - 1; index >= 0; index--) {
+ const message = messages[index];
+ if (!message.parentToolCallId && message.usage) {
+ latestUsageMessage = message;
+ break;
+ }
+ }
+ const latestUsage = latestUsageMessage?.usage;
if (!latestUsage) return undefined;
- const turns = buildTranscriptEntries(messages, compactions).entries.filter(
- (entry): entry is AssistantTurnEntry => entry.kind === "assistant-turn",
- );
- const latestTurn =
- [...turns].reverse().find((turn) => assistantTurnUsage(turn)) ??
- turns.at(-1);
- const latestUsageMessage = [...parentMessages]
- .reverse()
- .find((message) => message.usage);
-
- return {
- // Occupancy and provider cache/input/output use this last request.
- // turnUsage remains the visual-turn sum for completed-turn speed.
+ const { entries } = getTranscriptProjection(messages, compactions);
+ let latestTurn: ReturnType<typeof getAssistantTurnSummary> | undefined;
+ for (let index = entries.length - 1; index >= 0; index--) {
+ const entry = entries[index];
+ if (entry.kind !== "assistant-turn") continue;
+ const summary = getAssistantTurnSummary(entry);
+ latestTurn ??= summary;
+ if (summary.usage) {
+ latestTurn = summary;
+ break;
+ }
+ }
+ const result: LatestTurnContextInspector = {
usage: latestUsage,
- turnUsage:
- (latestTurn ? assistantTurnUsage(latestTurn) : undefined) ?? latestUsage,
+ turnUsage: latestTurn?.usage ?? latestUsage,
contextWindow: resolveContextWindow(
latestUsageMessage?.providerId,
latestUsageMessage?.modelId,
providerModels,
providers,
),
- tools: latestTurn ? assistantTurnTools(latestTurn) : [],
- responseDurationMs: latestTurn
- ? assistantTurnResponseDuration(latestTurn)
- : undefined,
- responseOutputTokens: latestTurn
- ? assistantTurnResponseOutputTokens(latestTurn)
- : undefined,
- responseOutputEstimated: latestTurn
- ? assistantTurnResponseOutputIsEstimated(latestTurn)
- : false,
+ tools: latestTurn?.tools ?? [],
+ responseDurationMs: latestTurn?.responseDurationMs,
+ responseOutputTokens: latestTurn?.responseOutputTokens,
+ responseOutputEstimated: latestTurn?.responseOutputEstimated ?? false,
};
+ const owner = getSessionMessageSnapshot(messages).owner;
+ const previous = inspectors.get(owner);
+ if (previous && previous.usage === result.usage &&
+ sameUsage(previous.turnUsage, result.turnUsage) &&
+ previous.contextWindow === result.contextWindow &&
+ previous.responseDurationMs === result.responseDurationMs &&
+ previous.responseOutputTokens === result.responseOutputTokens &&
+ previous.responseOutputEstimated === result.responseOutputEstimated &&
+ previous.tools.length === result.tools.length &&
+ previous.tools.every((tool, index) => tool === result.tools[index])
+ ) return previous;
+ inspectors.set(owner, result);
+ return result;
}
diff --git a/apps/desktop/src/lib/session-transcript-updates.ts b/apps/desktop/src/lib/session-transcript-updates.ts
new file mode 100644
index 000000000..6b81067a8
--- /dev/null
+++ b/apps/desktop/src/lib/session-transcript-updates.ts
@@ -0,0 +1,173 @@
+import type { UiMessage } from "@pi-desktop/shared";
+
+export const SESSION_MESSAGE_BLOCK_SIZE = 64;
+
+export type SessionMessageSnapshot = {
+ readonly owner: object;
+ readonly generation: number;
+ readonly blocks: readonly (readonly UiMessage[])[];
+ /** First physical position for each id; duplicate arrays are not indexed updates. */
+ readonly positions: ReadonlyMap<string, number>;
+ readonly unique: boolean;
+};
+
+type TrackedSessionMessages = {
+ snapshot: SessionMessageSnapshot;
+ // All physical rows are indexed, regardless of role/status. Tool events
+ // historically match toolCallId even when it differs from the row id.
+ toolPositions: ReadonlyMap<string, readonly number[]>;
+};
+
+// Array identity is the ownership boundary. Values contain no predecessor or
+// source array, so abandoned renders do not keep an update history alive.
+const snapshots = new WeakMap<UiMessage[], TrackedSessionMessages>();
+const EMPTY_TOOL_POSITIONS: readonly number[] = Object.freeze([]);
+
+function buildSnapshot(messages: UiMessage[], owner: object, generation: number): TrackedSessionMessages {
+ const positions = new Map<string, number>();
+ const toolPositions = new Map<string, number[]>();
+ let unique = true;
+ for (let index = 0; index < messages.length; index++) {
+ const { id, toolCallId } = messages[index];
+ if (positions.has(id)) unique = false;
+ else positions.set(id, index);
+ if (toolCallId !== undefined) {
+ const indices = toolPositions.get(toolCallId);
+ if (indices) indices.push(index);
+ else toolPositions.set(toolCallId, [index]);
+ }
+ }
+ for (const indices of toolPositions.values()) Object.freeze(indices);
+ const blocks: (readonly UiMessage[])[] = [];
+ for (let index = 0; index < messages.length; index += SESSION_MESSAGE_BLOCK_SIZE) {
+ blocks.push(Object.freeze(messages.slice(index, index + SESSION_MESSAGE_BLOCK_SIZE)));
+ }
+ return {
+ snapshot: Object.freeze({ owner, generation, positions, unique, blocks: Object.freeze(blocks) }),
+ toolPositions,
+ };
+}
+
+function getTrackedMessages(messages: UiMessage[]): TrackedSessionMessages {
+ let tracked = snapshots.get(messages);
+ if (!tracked) {
+ tracked = buildSnapshot(messages, {}, 0);
+ snapshots.set(messages, tracked);
+ }
+ return tracked;
+}
+
+/** Messages and published snapshots must be treated as immutable by callers. */
+export function getSessionMessageSnapshot(messages: UiMessage[]): SessionMessageSnapshot {
+ return getTrackedMessages(messages).snapshot;
+}
+
+/** Includes every matching physical row; callers filter the current tool status. */
+export function getSessionToolMessagePositions(messages: UiMessage[], toolCallId: string): readonly number[] {
+ return getTrackedMessages(messages).toolPositions.get(toolCallId) ?? EMPTY_TOOL_POSITIONS;
+}
+
+function replaceToolPositions(
+ positions: ReadonlyMap<string, readonly number[]>,
+ previous: UiMessage[],
+ next: UiMessage[],
+ indices: readonly number[],
+): ReadonlyMap<string, readonly number[]> {
+ let updated: Map<string, readonly number[]> | undefined;
+ for (const index of new Set(indices)) {
+ const oldCall = previous[index].toolCallId;
+ const newCall = next[index].toolCallId;
+ if (oldCall === newCall) continue;
+ updated ??= new Map(positions);
+ if (oldCall !== undefined) {
+ const remaining = (updated.get(oldCall) ?? []).filter((position) => position !== index);
+ if (remaining.length) updated.set(oldCall, Object.freeze(remaining));
+ else updated.delete(oldCall);
+ }
+ if (newCall !== undefined) {
+ updated.set(newCall, Object.freeze([...(updated.get(newCall) ?? []), index].sort((a, b) => a - b)));
+ }
+ }
+ return updated ?? positions;
+}
+
+/** Register a known structural edit. Unknown arrays otherwise start a new owner. */
+export function registerSessionMessageRewrite(previous: UiMessage[], next: UiMessage[]): UiMessage[] {
+ if (previous === next) return next;
+ const snapshot = getSessionMessageSnapshot(previous);
+ snapshots.set(next, buildSnapshot(next, snapshot.owner, snapshot.generation + 1));
+ return next;
+}
+
+/** Register an array whose only changes are the supplied replacement positions. */
+export function registerSessionMessageReplacements(
+ previous: UiMessage[],
+ next: UiMessage[],
+ indices: readonly number[],
+): UiMessage[] {
+ if (previous === next) return next;
+ const { snapshot, toolPositions } = getTrackedMessages(previous);
+ if (
+ !snapshot.unique || previous.length !== next.length ||
+ indices.some((index) => !next[index] || snapshot.positions.get(next[index].id) !== index)
+ ) return registerSessionMessageRewrite(previous, next);
+
+ const blocks = snapshot.blocks.slice();
+ const changedBlocks = new Set(indices.map((index) => Math.floor(index / SESSION_MESSAGE_BLOCK_SIZE)));
+ for (const blockIndex of changedBlocks) {
+ const start = blockIndex * SESSION_MESSAGE_BLOCK_SIZE;
+ blocks[blockIndex] = Object.freeze(next.slice(start, start + SESSION_MESSAGE_BLOCK_SIZE));
+ }
+ snapshots.set(next, {
+ snapshot: Object.freeze({
+ ...snapshot,
+ generation: snapshot.generation + 1,
+ blocks: Object.freeze(blocks),
+ }),
+ toolPositions: replaceToolPositions(toolPositions, previous, next, indices),
+ });
+ return next;
+}
+
+export function registerSessionMessageReplacement(
+ previous: UiMessage[],
+ next: UiMessage[],
+ index: number,
+): UiMessage[] {
+ return registerSessionMessageReplacements(previous, next, [index]);
+}
+
+/** Register a single append without rereading historical message identities. */
+export function registerSessionMessageAppend(previous: UiMessage[], next: UiMessage[]): UiMessage[] {
+ const { snapshot, toolPositions } = getTrackedMessages(previous);
+ const appended = next[previous.length];
+ if (
+ !snapshot.unique || next.length !== previous.length + 1 ||
+ !appended || snapshot.positions.has(appended.id)
+ ) return registerSessionMessageRewrite(previous, next);
+
+ const positions = new Map(snapshot.positions);
+ positions.set(appended.id, previous.length);
+ const blocks = snapshot.blocks.slice();
+ const blockIndex = Math.floor(previous.length / SESSION_MESSAGE_BLOCK_SIZE);
+ blocks[blockIndex] = Object.freeze(next.slice(blockIndex * SESSION_MESSAGE_BLOCK_SIZE));
+ let nextToolPositions = toolPositions;
+ if (appended.toolCallId !== undefined) {
+ const updated = new Map(toolPositions);
+ updated.set(appended.toolCallId, Object.freeze([
+ ...(toolPositions.get(appended.toolCallId) ?? []), previous.length,
+ ]));
+ nextToolPositions = updated;
+ }
+ snapshots.set(next, {
+ snapshot: Object.freeze({
+ owner: snapshot.owner,
+ generation: snapshot.generation + 1,
+ positions,
+ unique: true,
+ blocks: Object.freeze(blocks),
+ }),
+ toolPositions: nextToolPositions,
+ });
+ return next;
+}
diff --git a/apps/desktop/src/lib/session-transcript.ts b/apps/desktop/src/lib/session-transcript.ts
index 78295bf7f..da0abd6ba 100644
--- a/apps/desktop/src/lib/session-transcript.ts
+++ b/apps/desktop/src/lib/session-transcript.ts
@@ -1,4 +1,10 @@
import type { AgentEvent, MessageAttachment, UiMessage } from "@pi-desktop/shared";
+import {
+ getSessionMessageSnapshot,
+ registerSessionMessageAppend,
+ registerSessionMessageReplacement,
+ registerSessionMessageRewrite,
+} from "./session-transcript-updates";
type OptimisticFileReference = {
path: string;
@@ -64,7 +70,9 @@ export function projectMessageEnd(
message.id === replacesMessageId && message.role === "assistant",
);
if (index >= 0) {
- next = [...messages.slice(0, index), ...messages.slice(index + 1)];
+ next = registerSessionMessageRewrite(messages, [
+ ...messages.slice(0, index), ...messages.slice(index + 1),
+ ]);
}
}
const failed =
@@ -85,6 +93,7 @@ export function projectMessageEnd(
* position, but use the last value, matching host-core's keep-last policy.
*/
export function dedupeSessionMessages(messages: UiMessage[]): UiMessage[] {
+ if (getSessionMessageSnapshot(messages).unique) return messages;
const positions = new Map<string, number>();
let next: UiMessage[] | undefined;
for (const [index, message] of messages.entries()) {
@@ -101,7 +110,7 @@ export function dedupeSessionMessages(messages: UiMessage[]): UiMessage[] {
if (!next) next = messages.slice(0, index);
next[previous] = message;
}
- return next ?? messages;
+ return next ? registerSessionMessageRewrite(messages, next) : messages;
}
/**
@@ -113,12 +122,12 @@ export function upsertLiveSessionMessage(
message: UiMessage,
): UiMessage[] {
const normalized = dedupeSessionMessages(messages);
- const index = normalized.findIndex((candidate) => candidate.id === message.id);
- if (index < 0) return [...normalized, message];
+ const index = getSessionMessageSnapshot(normalized).positions.get(message.id);
+ if (index === undefined) return registerSessionMessageAppend(normalized, [...normalized, message]);
if (normalized[index] === message) return normalized;
const next = normalized.slice();
next[index] = message;
- return next;
+ return registerSessionMessageReplacement(normalized, next, index);
}
/** Replace only the acknowledged submission identity, never an equal-text row. */
@@ -132,7 +141,8 @@ export function reconcilePersistedUserMessage(
!messages.some((row) => row.id === optimisticMessageId && row.role === "user")
) return messages;
return upsertLiveSessionMessage(
- messages.map((row) => row.id === optimisticMessageId ? message : row),
+ registerSessionMessageRewrite(messages,
+ messages.map((row) => row.id === optimisticMessageId ? message : row)),
message,
);
}
@@ -146,9 +156,11 @@ export function removeLiveSessionMessage(
messageId: string,
): UiMessage[] {
const normalized = dedupeSessionMessages(messages);
- const index = normalized.findIndex((message) => message.id === messageId);
- if (index < 0) return normalized;
- return [...normalized.slice(0, index), ...normalized.slice(index + 1)];
+ const index = getSessionMessageSnapshot(normalized).positions.get(messageId);
+ if (index === undefined) return normalized;
+ return registerSessionMessageRewrite(normalized, [
+ ...normalized.slice(0, index), ...normalized.slice(index + 1),
+ ]);
}
/**
diff --git a/apps/desktop/src/lib/transcript-activity-summary.ts b/apps/desktop/src/lib/transcript-activity-summary.ts
new file mode 100644
index 000000000..8aa3775be
--- /dev/null
+++ b/apps/desktop/src/lib/transcript-activity-summary.ts
@@ -0,0 +1,94 @@
+import type { UiMessage } from "@pi-desktop/shared";
+import type { AssistantActivityItem, AssistantTurnPart } from "./assistant-turns";
+import { activityItemHasIssue } from "./activity-summary";
+import { getToolAction } from "./tool-display";
+import { isDelegationActivityItem, subagentOutcome, type SubagentOutcome } from "./subagent-topology";
+import { messageContentFacts } from "./transcript-summary";
+
+const toolFacts = new WeakMap<UiMessage, { action: ReturnType<typeof getToolAction>; issue: boolean }>();
+const outcomes = new WeakMap<UiMessage, {
+ fallback?: SubagentOutcome;
+ byStatuses: WeakMap<ReadonlyMap<string, SubagentOutcome>, SubagentOutcome>;
+}>();
+
+function cachedOutcome(message: UiMessage, statuses?: ReadonlyMap<string, SubagentOutcome>) {
+ let cache = outcomes.get(message);
+ if (!cache) {
+ cache = { byStatuses: new WeakMap() };
+ outcomes.set(message, cache);
+ }
+ const cached = statuses ? cache.byStatuses.get(statuses) : cache.fallback;
+ if (cached) return cached;
+ const outcome = subagentOutcome(message, statuses);
+ if (statuses) cache.byStatuses.set(statuses, outcome);
+ else cache.fallback = outcome;
+ return outcome;
+}
+
+/** Same labels/counts as activitySummary, with payload work keyed by message. */
+export function cachedActivitySummary(items: readonly AssistantActivityItem[], statuses?: ReadonlyMap<string, SubagentOutcome>) {
+ let tools = 0;
+ let thinking = 0;
+ let issues = 0;
+ let allRun = true;
+ let allSearch = true;
+ for (const item of items) {
+ if (item.kind === "thinking") { thinking += 1; continue; }
+ tools += 1;
+ if (item.kind === "hostedSearch") {
+ allRun = false;
+ if (item.round.status === "failed") issues += 1;
+ continue;
+ }
+ let facts = toolFacts.get(item.message);
+ if (!facts) {
+ facts = { action: getToolAction(item.message.toolName), issue: activityItemHasIssue(item) };
+ toolFacts.set(item.message, facts);
+ }
+ allRun &&= facts.action === "run";
+ allSearch &&= facts.action === "search";
+ if (isDelegationActivityItem(item)) {
+ const outcome = cachedOutcome(item.message, statuses);
+ if (outcome === "failed" || outcome === "denied") issues += 1;
+ } else if (facts.issue) issues += 1;
+ }
+ return {
+ label: tools === 0 ? "chat.activityThinking" : allRun ? "chat.activityCommands" : allSearch ? "chat.activitySearches" : "chat.activityTools",
+ count: tools || thinking, tools, thinking, issues,
+ };
+}
+
+/** Precompute the legacy group's fallback formula without a per-second scan. */
+export function activityTimingInputs(items: readonly AssistantActivityItem[]) {
+ const startedAt = Date.parse(items[0]?.message.createdAt || "");
+ let recordedEnd = -Infinity;
+ let missingStartDuration = -Infinity;
+ for (const { message } of items) {
+ const completed = Date.parse(message.toolCompletedAt || "");
+ const created = Date.parse(message.createdAt);
+ const duration = message.toolDurationMs || 0;
+ if (completed) recordedEnd = Math.max(recordedEnd, completed);
+ else if (created) recordedEnd = Math.max(recordedEnd, created + duration);
+ else missingStartDuration = Math.max(missingStartDuration, duration);
+ }
+ return { startedAt, recordedEnd, missingStartDuration };
+}
+export function cachedVisibleActivityItems(items: readonly AssistantActivityItem[], compact: boolean, active: boolean) {
+ return items.filter((item) => item.kind !== "thinking" || !compact ||
+ (active && item.message.status === "streaming" && !messageContentFacts(item.message).hasContent));
+}
+
+export function cachedVisibleProcessSteps(parts: readonly AssistantTurnPart[], compact: boolean, active: boolean) {
+ let count = 0;
+ for (const part of parts) {
+ if (part.kind === "message") {
+ if (messageContentFacts(part.message).hasContent) count += 1;
+ } else {
+ for (const item of part.items) {
+ if (item.kind !== "thinking" || !compact ||
+ (active && item.message.status === "streaming" && !messageContentFacts(item.message).hasContent)) count += 1;
+ }
+ }
+ }
+ return count;
+}
diff --git a/apps/desktop/src/lib/transcript-projection.ts b/apps/desktop/src/lib/transcript-projection.ts
new file mode 100644
index 000000000..093bdb668
--- /dev/null
+++ b/apps/desktop/src/lib/transcript-projection.ts
@@ -0,0 +1,245 @@
+import type { ContextCompactionMark, UiMessage } from "@pi-desktop/shared";
+import {
+ buildTranscriptEntries,
+ messageThinking,
+ reuseTranscriptEntries,
+ type AssistantActivityItem,
+ type AssistantTurnEntry,
+ type AssistantTurnPart,
+ type TranscriptEntry,
+} from "./assistant-turns";
+import {
+ getSessionMessageSnapshot,
+ SESSION_MESSAGE_BLOCK_SIZE,
+} from "./session-transcript-updates";
+import { isDelegationStartTool } from "./tool-display";
+import { messageContentFacts } from "./transcript-summary";
+
+export type TranscriptProjection = {
+ entries: TranscriptEntry[];
+ visible: UiMessage[];
+ history: TranscriptEntry[];
+};
+
+type Location = {
+ entry: number;
+ part?: number;
+ item?: number;
+ delegateItem?: number;
+};
+
+type MessageShape = {
+ visible: boolean;
+ thinking: boolean;
+ content: boolean;
+ answer: boolean;
+};
+
+type ProjectionState = {
+ source: ReturnType<typeof getSessionMessageSnapshot>;
+ messages: UiMessage[];
+ compactions: readonly ContextCompactionMark[];
+ projection: TranscriptProjection;
+ locations: Map<string, Location[]>;
+ visiblePositions: Map<string, number>;
+};
+
+const NO_COMPACTIONS: readonly ContextCompactionMark[] = [];
+const shapes = new WeakMap<UiMessage, MessageShape>();
+const owners = new WeakMap<object, ProjectionState>();
+const snapshots = new WeakMap<UiMessage[], WeakMap<readonly ContextCompactionMark[], TranscriptProjection>>();
+
+function shape(message: UiMessage): MessageShape {
+ const cached = shapes.get(message);
+ if (cached) return cached;
+ const content = messageContentFacts(message).hasContent;
+ const thinking = Boolean(messageThinking(message));
+ const value = {
+ content,
+ thinking,
+ visible: message.role !== "assistant" || content || thinking || Boolean(message.hostedSearch || message.error),
+ answer: message.parentToolCallId
+ ? content || Boolean(message.error)
+ : content || !thinking || Boolean(message.error),
+ };
+ shapes.set(message, value);
+ return value;
+}
+
+function canReplace(previous: UiMessage, next: UiMessage): boolean {
+ if (
+ previous.id !== next.id || previous.role !== next.role ||
+ previous.parentToolCallId !== next.parentToolCallId ||
+ previous.agentName !== next.agentName || previous.createdAt !== next.createdAt ||
+ previous.toolCallId !== next.toolCallId || previous.toolName !== next.toolName ||
+ previous.hostedSearch !== next.hostedSearch
+ ) return false;
+ if (isDelegationStartTool(previous.toolName) && (
+ previous.toolArgs !== next.toolArgs || previous.toolResult !== next.toolResult
+ )) return false;
+ // Tool rows always occupy one activity slot, including their first output.
+ // Parent user/system rows likewise do not split when their text changes.
+ if (previous.role === "tool" || (!previous.parentToolCallId &&
+ (previous.role === "user" || previous.role === "system"))) return true;
+ const before = shape(previous);
+ const after = shape(next);
+ return before.visible === after.visible && before.thinking === after.thinking &&
+ before.content === after.content && before.answer === after.answer;
+}
+
+function indexProjection(projection: TranscriptProjection) {
+ const locations = new Map<string, Location[]>();
+ const add = (message: UiMessage, location: Location) => {
+ const existing = locations.get(message.id);
+ if (existing) existing.push(location);
+ else locations.set(message.id, [location]);
+ };
+ projection.entries.forEach((entry, entryIndex) => {
+ if (entry.kind === "message") add(entry.message, { entry: entryIndex });
+ if (entry.kind !== "assistant-turn") return;
+ entry.parts.forEach((part, partIndex) => {
+ if (part.kind === "message") {
+ add(part.message, { entry: entryIndex, part: partIndex });
+ return;
+ }
+ part.items.forEach((item, itemIndex) => {
+ const location = { entry: entryIndex, part: partIndex, item: itemIndex };
+ add(item.message, location);
+ if (item.kind === "tool") item.delegate?.items.forEach((child, delegateItem) => {
+ add(child.message, { ...location, delegateItem });
+ });
+ });
+ });
+ });
+ const visiblePositions = new Map(projection.visible.map((message, index) => [message.id, index]));
+ return { locations, visiblePositions };
+}
+
+/** Clone only changed paths; previously published render snapshots stay immutable. */
+function replaceMessages(state: ProjectionState, changes: UiMessage[]): TranscriptProjection {
+ const previous = state.projection;
+ const entries = previous.entries.slice();
+ let visible = previous.visible;
+ let historyChanged = false;
+ const turns = new Map<number, AssistantTurnEntry>();
+ const parts = new Map<AssistantTurnPart, AssistantTurnPart>();
+ const items = new Map<AssistantActivityItem, AssistantActivityItem>();
+ for (const message of changes) {
+ const visibleIndex = state.visiblePositions.get(message.id);
+ if (visibleIndex !== undefined) {
+ if (visible === previous.visible) visible = visible.slice();
+ visible[visibleIndex] = message;
+ }
+ for (const location of state.locations.get(message.id) ?? []) {
+ const original = previous.entries[location.entry];
+ historyChanged ||= location.entry < entries.length - 1;
+ if (original.kind === "message") {
+ entries[location.entry] = { ...original, message };
+ continue;
+ }
+ if (original.kind !== "assistant-turn" || location.part === undefined) continue;
+ let turn = turns.get(location.entry);
+ if (!turn) {
+ turn = { ...original, parts: original.parts.slice() };
+ turns.set(location.entry, turn);
+ entries[location.entry] = turn;
+ }
+ const originalPart = original.parts[location.part];
+ if (originalPart.kind === "message") {
+ turn.parts[location.part] = { ...originalPart, message };
+ continue;
+ }
+ if (location.item === undefined) continue;
+ let part = parts.get(originalPart);
+ if (!part) {
+ part = { ...originalPart, items: originalPart.items.slice() };
+ parts.set(originalPart, part);
+ turn.parts[location.part] = part;
+ }
+ if (part.kind !== "activity") continue;
+ const originalItem = originalPart.items[location.item];
+ let item = items.get(originalItem);
+ if (!item) {
+ item = originalItem.kind === "tool" && originalItem.delegate
+ ? { ...originalItem, delegate: { ...originalItem.delegate, items: originalItem.delegate.items.slice() } }
+ : { ...originalItem };
+ items.set(originalItem, item);
+ part.items[location.item] = item;
+ }
+ if (location.delegateItem !== undefined) {
+ if (item.kind === "tool" && item.delegate) {
+ item.delegate.items[location.delegateItem] = {
+ ...item.delegate.items[location.delegateItem], message,
+ };
+ }
+ } else {
+ item.message = message;
+ }
+ }
+ }
+ const unchanged = !turns.size && entries.every((entry, index) => entry === previous.entries[index]);
+ return {
+ entries: unchanged ? previous.entries : entries,
+ visible,
+ history: historyChanged ? entries.slice(0, -1) : previous.history,
+ };
+}
+
+function incremental(state: ProjectionState, messages: UiMessage[], source: ProjectionState["source"]): TranscriptProjection | undefined {
+ if (!source.unique || !state.source.unique || messages.length !== state.messages.length) return undefined;
+ const changes: UiMessage[] = [];
+ for (let blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) {
+ const block = source.blocks[blockIndex];
+ if (block === state.source.blocks[blockIndex]) continue;
+ for (let offset = 0; offset < block.length; offset++) {
+ const next = block[offset];
+ const previous = state.messages[blockIndex * SESSION_MESSAGE_BLOCK_SIZE + offset];
+ if (previous === next) continue;
+ if (!previous || !canReplace(previous, next)) return undefined;
+ changes.push(next);
+ }
+ }
+ return changes.length ? replaceMessages(state, changes) : state.projection;
+}
+
+/**
+ * The exact source snapshot owns reuse. Comparing immutable blocks also handles
+ * skipped/deferred React renders without retaining a chain of prior updates.
+ * Structural changes use the full builder; ordinary deltas never revisit old
+ * content or grouping. Array/block reference copies remain linear shallow work.
+ */
+export function getTranscriptProjection(
+ messages: UiMessage[],
+ compactions: readonly ContextCompactionMark[] = NO_COMPACTIONS,
+): TranscriptProjection {
+ const cached = snapshots.get(messages)?.get(compactions);
+ if (cached) return cached;
+ const source = getSessionMessageSnapshot(messages);
+ const previous = owners.get(source.owner);
+ const matching = previous?.compactions === compactions;
+ let projection = matching ? incremental(previous, messages, source) : undefined;
+ let locations = previous?.locations;
+ let visiblePositions = previous?.visiblePositions;
+ if (!projection) {
+ const built = buildTranscriptEntries(messages, compactions);
+ const entries = reuseTranscriptEntries(matching ? previous.projection.entries : undefined, built.entries);
+ projection = { entries, visible: built.visible, history: entries.slice(0, -1) };
+ ({ locations, visiblePositions } = indexProjection(projection));
+ for (const message of messages) shape(message);
+ }
+ // Old deferred inputs may be queried after newer ones. They can be cached,
+ // but must not move the current owner's cursor backwards.
+ if (!previous || source.generation >= previous.source.generation) {
+ owners.set(source.owner, {
+ source, messages, compactions, projection,
+ locations: locations!, visiblePositions: visiblePositions!,
+ });
+ }
+ let byCompactions = snapshots.get(messages);
+ if (!byCompactions) {
+ byCompactions = new WeakMap();
+ snapshots.set(messages, byCompactions);
+ }
+ byCompactions.set(compactions, projection);
+ return projection;
+}
diff --git a/apps/desktop/src/lib/transcript-reading.ts b/apps/desktop/src/lib/transcript-reading.ts
index fb8a30b7d..1d24a3eef 100644
--- a/apps/desktop/src/lib/transcript-reading.ts
+++ b/apps/desktop/src/lib/transcript-reading.ts
@@ -1,5 +1,11 @@
import type { SessionDetail, UiMessage } from "@pi-desktop/shared";
-import { dedupeSessionMessages, mergeLiveSessionMessages } from "./session-transcript";
+import { dedupeSessionMessages, mergeLiveSessionMessages, upsertLiveSessionMessage } from "./session-transcript";
+import {
+ getSessionMessageSnapshot,
+ registerSessionMessageReplacement,
+ registerSessionMessageReplacements,
+ type SessionMessageSnapshot,
+} from "./session-transcript-updates";
export type TranscriptSearchTarget = {
sessionId: string;
@@ -41,23 +47,91 @@ export function transcriptViewFromSession(
};
}
-/** Live output remains authoritative outside an explicit historical search. */
-export function transcriptViewMessages(live: UiMessage[], view?: TranscriptView): UiMessage[] {
- if (!view) return live;
- const liveById = new Map(live.map((message) => [message.id, message]));
- const messages = view.focus
- ? view.messages
- : mergeLiveSessionMessages(view.messages, live)
- // A reading snapshot can contain an older streaming row. Its status must
- // never outrank the canonical row, including a just-completed reply.
- .map((message) => liveById.get(message.id) ?? message);
- const parent = view.parentMessage;
+type ReadingProjection = {
+ source: SessionMessageSnapshot;
+ messages: UiMessage[];
+};
+
+// One current projection per reading view/live owner, not a linked generation
+// history. Replacing/evicting a view releases its cache. A new live owner or
+// structural edit takes the full merge path; skipped renders compare blocks.
+const readingProjections = new WeakMap<TranscriptView, WeakMap<object, ReadingProjection>>();
+
+function withNavigationParent(messages: UiMessage[], parent?: UiMessage): UiMessage[] {
if (!parent) return messages;
- const index = messages.findIndex((message) => message.id === parent.id);
- if (index < 0) return [parent, ...messages];
+ const snapshot = getSessionMessageSnapshot(messages);
+ const index = snapshot.positions.get(parent.id);
+ if (index === undefined) return [parent, ...messages];
if (messages[index] === parent) return messages;
// A neighboring page may contain an earlier physical copy of the Task.
- return messages.map((message) => (message.id === parent.id ? parent : message));
+ if (!snapshot.unique) return messages.map((message) => message.id === parent.id ? parent : message);
+ const next = messages.slice();
+ next[index] = parent;
+ return registerSessionMessageReplacement(messages, next, index);
+}
+
+function replaceReadingOverlap(
+ cached: ReadingProjection,
+ source: SessionMessageSnapshot,
+ parent?: UiMessage,
+): UiMessage[] | undefined {
+ if (!source.unique || source.positions !== cached.source.positions) return undefined;
+ if (source === cached.source) return cached.messages;
+ const output = getSessionMessageSnapshot(cached.messages);
+ let next: UiMessage[] | undefined;
+ const changed: number[] = [];
+ for (let blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) {
+ const block = source.blocks[blockIndex];
+ const previous = cached.source.blocks[blockIndex];
+ if (block === previous) continue;
+ for (let index = 0; index < block.length; index++) {
+ const message = block[index];
+ if (message === previous[index]) continue;
+ // Timestamp corrections can move live-only rows across the durable
+ // window. Content/status/role updates cannot change that merge ordering.
+ if (message.createdAt !== previous[index].createdAt) return undefined;
+ if (parent && message.id === parent.id) continue;
+ const position = output.positions.get(message.id);
+ if (position === undefined) return undefined;
+ if (cached.messages[position] === message) continue;
+ next ??= cached.messages.slice();
+ next[position] = message;
+ changed.push(position);
+ }
+ }
+ return next ? registerSessionMessageReplacements(cached.messages, next, changed) : cached.messages;
+}
+
+/** Live output remains authoritative outside an explicit historical search. */
+export function transcriptViewMessages(live: UiMessage[], view?: TranscriptView): UiMessage[] {
+ if (!view) return live;
+ // Search deliberately holds its historical snapshot. Do not index or merge
+ // the live transcript when it cannot contribute anything to this view.
+ if (view.focus) return withNavigationParent(view.messages, view.parentMessage);
+
+ const normalized = dedupeSessionMessages(live);
+ const source = getSessionMessageSnapshot(normalized);
+ let projections = readingProjections.get(view);
+ if (!projections) {
+ projections = new WeakMap();
+ readingProjections.set(view, projections);
+ }
+ const cached = projections.get(source.owner);
+ let messages = cached && replaceReadingOverlap(cached, source, view.parentMessage);
+ if (!messages) {
+ messages = withNavigationParent(
+ mergeLiveSessionMessages(view.messages, normalized).map((message) => {
+ // A stale reading snapshot must not outrank the canonical row, even
+ // when a previously streaming row has just completed.
+ const index = source.positions.get(message.id);
+ return index === undefined ? message : normalized[index];
+ }),
+ view.parentMessage,
+ );
+ getSessionMessageSnapshot(messages);
+ }
+ projections.set(source.owner, { source, messages });
+ return messages;
}
export function extendTranscriptView(
@@ -65,13 +139,13 @@ export function extendTranscriptView(
session: SessionDetail,
direction: "before" | "after",
): TranscriptView {
- const messages = dedupeSessionMessages(
+ const merged = dedupeSessionMessages(
direction === "before"
? [...session.messages, ...view.messages]
: [...view.messages, ...session.messages],
);
const focused = view.messages.find((message) => message.id === view.focus?.messageId);
- if (focused) messages[messages.findIndex((message) => message.id === focused.id)] = focused;
+ const messages = focused ? upsertLiveSessionMessage(merged, focused) : merged;
return {
...view,
messages,
diff --git a/apps/desktop/src/lib/transcript-summary.ts b/apps/desktop/src/lib/transcript-summary.ts
new file mode 100644
index 000000000..e984e1d38
--- /dev/null
+++ b/apps/desktop/src/lib/transcript-summary.ts
@@ -0,0 +1,120 @@
+import type { MessageUsage, UiMessage } from "@pi-desktop/shared";
+import type { AssistantActivityItem, AssistantTurnEntry, AssistantTurnPart } from "./assistant-turns";
+
+const contentFacts = new WeakMap<UiMessage, { trimmedContent: string; hasContent: boolean }>();
+
+/** Renderer snapshots are immutable; a same-id replacement is a new cache key. */
+export function messageContentFacts(message: UiMessage) {
+ let facts = contentFacts.get(message);
+ if (!facts) {
+ const trimmedContent = (message.content || "").trim();
+ facts = { trimmedContent, hasContent: Boolean(trimmedContent) };
+ contentFacts.set(message, facts);
+ }
+ return facts;
+}
+
+export type AssistantTurnSummary = {
+ messages: UiMessage[];
+ tools: UiMessage[];
+ activityItems: AssistantActivityItem[];
+ toolItems: Extract<AssistantActivityItem, { kind: "tool" }>[];
+ generatedImages: UiMessage[];
+ actionMessage?: UiMessage;
+ metaMessage?: UiMessage;
+ latestUsageMessage?: UiMessage;
+ usage?: MessageUsage;
+ responseDurationMs?: number;
+ responseOutputTokens?: number;
+ responseOutputEstimated: boolean;
+ hasError: boolean;
+ streaming: boolean;
+ hasContent: boolean;
+ process: AssistantTurnPart[];
+ responses: Extract<AssistantTurnPart, { kind: "message" }>[];
+ lastActivityPart?: AssistantTurnPart;
+};
+
+const summaries = new WeakMap<readonly AssistantTurnPart[], AssistantTurnSummary>();
+
+/**
+ * Share content facts between the transcript and composer without joining the
+ * reply on a stream tick. A changed turn still scans references/metadata, not
+ * old text. Key by the immutable parts snapshot, not a mutable "latest turn",
+ * so deferred and retained panes can safely request older snapshots.
+ */
+export function getAssistantTurnSummary(entry: AssistantTurnEntry): AssistantTurnSummary {
+ const cached = summaries.get(entry.parts);
+ if (cached) return cached;
+ const result: AssistantTurnSummary = {
+ messages: [], tools: [], activityItems: [], toolItems: [], generatedImages: [],
+ responseOutputEstimated: false, hasError: false, streaming: false,
+ hasContent: false, process: [], responses: [],
+ };
+ const last = entry.parts.at(-1);
+ const answer = last?.kind === "message" && messageContentFacts(last.message).hasContent ? last : undefined;
+ for (const part of entry.parts) {
+ if (part.kind === "activity") {
+ result.process.push(part);
+ result.lastActivityPart = part;
+ for (const item of part.items) {
+ result.activityItems.push(item);
+ if (item.kind !== "tool") continue;
+ result.toolItems.push(item);
+ result.tools.push(item.message);
+ if (item.message.toolName === "GenerateImages") result.generatedImages.push(item.message);
+ }
+ continue;
+ }
+ const message = part.message;
+ result.messages.push(message);
+ if (part === answer || message.error) result.responses.push(part);
+ else result.process.push(part);
+ if (messageContentFacts(message).hasContent) {
+ result.actionMessage = message;
+ result.hasContent = true;
+ }
+ if (message.modelId || message.usage || message.responseDurationMs || message.responseOutputTokens) {
+ result.metaMessage = message;
+ }
+ result.hasError ||= Boolean(message.error);
+ result.streaming ||= message.status === "streaming";
+ const duration = message.responseDurationMs;
+ if (typeof duration === "number" && Number.isFinite(duration) && duration > 0) {
+ result.responseDurationMs = (result.responseDurationMs ?? 0) + duration;
+ }
+ const output = message.usage?.outputTokens ?? message.responseOutputTokens;
+ if (typeof output === "number" && Number.isFinite(output) && output > 0) {
+ result.responseOutputTokens = (result.responseOutputTokens ?? 0) + output;
+ }
+ result.responseOutputEstimated ||= (!message.usage || message.usage.outputTokens <= 0) &&
+ typeof message.responseOutputTokens === "number" && message.responseOutputTokens > 0;
+ if (message.usage) {
+ result.latestUsageMessage = message;
+ const usage = result.usage ??= { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
+ usage.inputTokens += message.usage.inputTokens ?? 0;
+ usage.outputTokens += message.usage.outputTokens ?? 0;
+ usage.totalTokens += message.usage.totalTokens ?? 0;
+ for (const key of ["cacheReadTokens", "cacheWriteTokens", "reasoningTokens"] as const) {
+ if (message.usage[key] !== undefined) usage[key] = (usage[key] ?? 0) + (message.usage[key] ?? 0);
+ }
+ }
+ }
+ summaries.set(entry.parts, result);
+ return result;
+}
+
+/** Do not retain duplicated reply text in the session-wide projection cache. */
+export function getAssistantTurnContent(entry: AssistantTurnEntry): string {
+ return getAssistantTurnSummary(entry).messages
+ .map((message) => messageContentFacts(message).trimmedContent)
+ .filter(Boolean)
+ .join("\n\n");
+}
+
+/** Preserve a derived input when only unrelated text/thinking items changed. */
+export function reuseReferences<T>(previous: readonly T[] | undefined, next: T[]): T[] {
+ if (previous === next) return next;
+ return previous && previous.length === next.length && previous.every((item, index) => item === next[index])
+ ? previous as T[] : next;
+}
diff --git a/apps/desktop/src/stores/runtime/session-runtime.ts b/apps/desktop/src/stores/runtime/session-runtime.ts
index fdcf3609f..ab412b731 100644
--- a/apps/desktop/src/stores/runtime/session-runtime.ts
+++ b/apps/desktop/src/stores/runtime/session-runtime.ts
@@ -14,6 +14,7 @@ import {
removeLiveSessionMessage,
upsertLiveSessionMessage,
} from "../../lib/session-transcript";
+import { getSessionMessageSnapshot, getSessionToolMessagePositions } from "../../lib/session-transcript-updates";
import { sessionReadLooksEmpty } from "../../lib/session-transcript-read";
import { sessionIsArchived, type SessionMeta } from "../../lib/sidebar-preferences";
import {
@@ -264,11 +265,12 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntime
next = upsertLiveSessionMessage(current, event.message);
break;
case "message_update": {
- const previous = current.find((message) => message.id === event.message.id);
- next = upsertLiveSessionMessage(current, applyMessageUpdate(previous, event));
+ const normalized = dedupeSessionMessages(current);
+ const index = getSessionMessageSnapshot(normalized).positions.get(event.message.id);
+ const previous = index === undefined ? undefined : normalized[index];
+ next = upsertLiveSessionMessage(normalized, applyMessageUpdate(previous, event));
break;
}
- break;
case "message_end": {
next = projectMessageEnd(current, event);
break;
@@ -292,12 +294,10 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntime
break;
case "tool_update": {
if (event.partialResult === undefined) return current;
- const existing = current.find(
- (message) =>
- message.toolCallId === event.toolCallId &&
- message.toolStatus === "running",
- );
- if (!existing) return current;
+ const index = getSessionToolMessagePositions(current, event.toolCallId)
+ .find((position) => current[position].toolStatus === "running");
+ if (index === undefined) return current;
+ const existing = current[index];
next = upsertLiveSessionMessage(current, {
...existing,
content:
diff --git a/apps/desktop/src/stores/slices/events-slice.ts b/apps/desktop/src/stores/slices/events-slice.ts
index a5f4f24f4..868143415 100644
--- a/apps/desktop/src/stores/slices/events-slice.ts
+++ b/apps/desktop/src/stores/slices/events-slice.ts
@@ -1,5 +1,15 @@
import i18n from "i18next";
-import { projectMessageEnd, reconcilePersistedUserMessage } from "../../lib/session-transcript";
+import {
+ dedupeSessionMessages,
+ projectMessageEnd,
+ reconcilePersistedUserMessage,
+ upsertLiveSessionMessage,
+} from "../../lib/session-transcript";
+import {
+ getSessionMessageSnapshot,
+ getSessionToolMessagePositions,
+ registerSessionMessageReplacements,
+} from "../../lib/session-transcript-updates";
import type {
AgentEventEnvelope,
PlanningStateEvent,
@@ -463,28 +473,21 @@ export function createEventsSlice({
break;
case "message_start":
set((state) =>
- state.messages.some((message) => message.id === event.message.id)
+ getSessionMessageSnapshot(state.messages).positions.has(event.message.id)
? state
- : { messages: [...state.messages, event.message] },
+ : { messages: upsertLiveSessionMessage(state.messages, event.message) },
);
break;
case "message_update":
set((state) => {
- const index = state.messages.findIndex(
- (message) => message.id === event.message.id,
- );
+ const normalized = dedupeSessionMessages(state.messages);
+ const index = getSessionMessageSnapshot(normalized).positions.get(event.message.id);
const nextMessage = applyMessageUpdate(
- index >= 0 ? state.messages[index] : undefined,
+ index === undefined ? undefined : normalized[index],
event,
);
- if (index >= 0 && state.messages[index] === nextMessage) return state;
- const messages =
- index >= 0
- ? state.messages.map((message, messageIndex) =>
- messageIndex === index ? nextMessage : message,
- )
- : [...state.messages, nextMessage];
- return { messages };
+ const messages = upsertLiveSessionMessage(normalized, nextMessage);
+ return messages === state.messages ? state : { messages };
});
break;
case "message_end":
@@ -516,21 +519,19 @@ export function createEventsSlice({
break;
case "tool_update":
if (event.partialResult === undefined) break;
- set((state) => ({
- messages: state.messages.map((message) =>
- message.toolCallId === event.toolCallId &&
- message.toolStatus === "running"
- ? {
- ...message,
- content:
- typeof event.partialResult === "string"
- ? event.partialResult
- : formatToolValue(event.partialResult),
- toolResult: event.partialResult,
- }
- : message,
- ),
- }));
+ set((state) => {
+ const indices = getSessionToolMessagePositions(state.messages, event.toolCallId)
+ .filter((index) => state.messages[index].toolStatus === "running");
+ if (indices.length === 0) return state;
+ const content = typeof event.partialResult === "string"
+ ? event.partialResult
+ : formatToolValue(event.partialResult);
+ const messages = state.messages.slice();
+ for (const index of indices) {
+ messages[index] = { ...messages[index], content, toolResult: event.partialResult };
+ }
+ return { messages: registerSessionMessageReplacements(state.messages, messages, indices) };
+ });
break;
case "tool_end":
set((state) => {
diff --git a/apps/desktop/test/conversation-minimap.test.mjs b/apps/desktop/test/conversation-minimap.test.mjs
index 128952a68..4b35e7ec4 100644
--- a/apps/desktop/test/conversation-minimap.test.mjs
+++ b/apps/desktop/test/conversation-minimap.test.mjs
@@ -1,10 +1,13 @@
import assert from "node:assert/strict";
+import { register } from "node:module";
import test from "node:test";
-import {
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const {
CONVERSATION_MINIMAP_PREVIEW_MAX_CHARS,
buildConversationMinimapMarkers,
shouldRenderConversationMinimap,
-} from "../src/lib/conversation-minimap.ts";
+} = await import("../src/lib/conversation-minimap.ts");
function message(id, role, content) {
return {
diff --git a/apps/desktop/test/interaction-performance.test.mjs b/apps/desktop/test/interaction-performance.test.mjs
index 637c1f79e..c4510b2f7 100644
--- a/apps/desktop/test/interaction-performance.test.mjs
+++ b/apps/desktop/test/interaction-performance.test.mjs
@@ -71,22 +71,19 @@ test("stream rendering avoids duplicate frame state and coalesces following", ()
// commit that reveals it, or the reveal shows one empty frame (ADR 0137).
assert.match(
transcript,
- /const renderedMessages =\s*readingWindow \|\| firstCommit \|\| paneRevealed \? messages : deferredMessages/,
- );
- assert.match(transcript, /const \{ entries, visible \} = useMemo/);
- assert.match(
- transcript,
- /buildTranscriptEntries\(renderedMessages, renderedCompactions\)/,
+ /const renderedProjection =\s*readingWindow \|\| firstCommit \|\| paneRevealed \? projection : deferredProjection/,
);
+ assert.match(transcript, /getTranscriptProjection\(messages, compactions\)/);
+ assert.match(transcript, /useDeferredValue\(projection\)/);
+ assert.doesNotMatch(transcript, /buildTranscriptEntries\(renderedMessages/);
assert.match(transcript, /const TranscriptHistory = memo/);
assert.match(transcript, /const TranscriptTail = memo/);
assert.match(transcript, /function transcriptEntryEqual/);
- // Memoized on `entries`: a re-render that changed no message must hand
- // `TranscriptHistory` the same array so its comparator bails on identity
- // instead of deep-walking every mounted row (D261).
+ // The incremental projection preserves the history array across tail updates;
+ // runtime work-count tests cover its behavior, not only this wiring.
assert.match(
transcript,
- /const allHistoryEntries = useMemo\(\(\) => entries\.slice\(0, -1\), \[entries\]\)/,
+ /history: allHistoryEntries \} = renderedProjection/,
);
assert.match(transcript, /<TranscriptHistory entries=\{historyEntries\}/);
assert.match(transcript, /<TranscriptTail[\s\S]*?entry=\{tailEntry\}/);
@@ -100,7 +97,7 @@ test("expanded live tool output stays local to the changed row", () => {
assert.match(transcript, /const ToolRow = memo\(function ToolRow/);
assert.match(transcript, /function toolRowPropsEqual\(/);
assert.match(transcript, /if \(previous.variant !== "topology"\) return true;/);
- assert.match(transcript, /const autoOpenLatest =\s*!compact && isLast && itemIndex === items.length - 1/);
+ assert.match(transcript, /const autoOpenLatest =\s*!compact && isLast && item === lastItem/);
assert.match(transcript, /if \(variant !== "topology" && open && hasDetails && disclosure\.parentVisible/);
assert.match(transcript, /const blocks = variant !== "topology" && open && hasDetails \? presentation\.current\?\.blocks : null/);
});
diff --git a/apps/desktop/test/session-runtime-updates.test.mjs b/apps/desktop/test/session-runtime-updates.test.mjs
new file mode 100644
index 000000000..ba0770bae
--- /dev/null
+++ b/apps/desktop/test/session-runtime-updates.test.mjs
@@ -0,0 +1,231 @@
+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 { createSessionRuntime } = await import("../src/stores/runtime/session-runtime.ts");
+const { createEventsSlice } = await import("../src/stores/slices/events-slice.ts");
+const { getSessionMessageSnapshot } = await import("../src/lib/session-transcript-updates.ts");
+const { getTranscriptProjection } = await import("../src/lib/transcript-projection.ts");
+
+const message = (id, overrides = {}) => ({
+ id, role: "assistant", content: id, createdAt: "2026-09-30T00:00:00Z", ...overrides,
+});
+const envelope = (sessionId, id, deltaText) => ({
+ sessionId, ts: 1,
+ event: { type: "message_update", stream: "delta", message: message(id, { content: "", status: "streaming" }), deltaText },
+});
+
+function harness(messages, background = []) {
+ let runtime;
+ let writes = 0;
+ let state = {
+ activeSessionId: "active", messages,
+ retainedSessionIds: ["active", "background"],
+ retainedTranscripts: { active: messages, background },
+ runningSessions: { active: true, background: true },
+ sessionHistory: {},
+ };
+ const access = {
+ get: () => state,
+ set: (patch) => {
+ const previous = state;
+ const next = typeof patch === "function" ? patch(state) : patch;
+ if (next === state) return;
+ writes++;
+ state = { ...state, ...next };
+ runtime?.syncTranscriptProjection(state, previous);
+ },
+ };
+ runtime = createSessionRuntime(access);
+ runtime.cacheSessionTranscript("active", messages);
+ runtime.cacheSessionTranscript("background", background);
+ Object.assign(state, createEventsSlice({ ...access, runtime }));
+ return { ...access, runtime, writes: () => writes };
+}
+
+function withFrames(run) {
+ const originalRequest = globalThis.requestAnimationFrame;
+ const originalCancel = globalThis.cancelAnimationFrame;
+ const pending = new Map();
+ let id = 0;
+ globalThis.requestAnimationFrame = (callback) => { pending.set(++id, callback); return id; };
+ globalThis.cancelAnimationFrame = (handle) => pending.delete(handle);
+ try {
+ run(() => {
+ const callbacks = [...pending.values()];
+ pending.clear();
+ callbacks.forEach((callback) => callback(0));
+ });
+ assert.equal(pending.size, 0, "each synthetic frame is drained");
+ } finally {
+ if (originalRequest) globalThis.requestAnimationFrame = originalRequest;
+ else delete globalThis.requestAnimationFrame;
+ if (originalCancel) globalThis.cancelAnimationFrame = originalCancel;
+ else delete globalThis.cancelAnimationFrame;
+ }
+}
+
+test("active frame updates and cache publication do not reread historical ids", () => withFrames((flush) => {
+ let historicalReads = 0;
+ const history = Array.from({ length: 10_000 }, (_, index) => ({
+ ...message(`old-${index}`),
+ get id() { historicalReads++; return `old-${index}`; },
+ }));
+ history.splice(2, 0, message("live", { content: "", status: "streaming" }));
+ const h = harness(history);
+ const initial = getSessionMessageSnapshot(history);
+ historicalReads = 0;
+ for (let index = 0; index < 10; index++) {
+ h.get().handleAgentEvent(envelope("active", "live", "a"));
+ h.get().handleAgentEvent(envelope("active", "live", "b"));
+ flush();
+ }
+ assert.equal(historicalReads, 0);
+ assert.equal(h.get().messages[2].content, "ab".repeat(10));
+ assert.equal(h.get().messages.length, history.length);
+ assert.equal(h.runtime.sessionTranscriptCache.get("active"), h.get().messages);
+ assert.equal(h.get().retainedTranscripts.active, h.get().messages);
+ const latest = getSessionMessageSnapshot(h.get().messages);
+ assert.equal(latest.owner, initial.owner);
+ assert.equal(latest.positions, initial.positions);
+ assert.equal(latest.blocks[1], initial.blocks[1]);
+ assert.equal(history[2].content, "");
+}));
+
+test("background deltas update only their cache and leave active and retained arrays unchanged", () => withFrames((flush) => {
+ let historicalReads = 0;
+ const background = Array.from({ length: 200 }, (_, index) => ({
+ ...message(`background-${index}`),
+ get id() { historicalReads++; return `background-${index}`; },
+ }));
+ background.push(message("live", { content: "", status: "streaming" }));
+ const active = [message("live", { content: "other session" })];
+ const h = harness(active, background);
+ const retained = h.get().retainedTranscripts;
+ historicalReads = 0;
+ h.get().handleAgentEvent(envelope("background", "live", "delta"));
+ flush();
+ assert.equal(historicalReads, 0);
+ assert.equal(h.writes(), 0);
+ assert.equal(h.get().messages, active);
+ assert.equal(h.get().retainedTranscripts, retained);
+ assert.equal(h.get().retainedTranscripts.background, background);
+ assert.equal(background.at(-1).content, "");
+ const cached = h.runtime.sessionTranscriptCache.get("background");
+ assert.equal(cached.at(-1).content, "delta");
+ assert.equal(getSessionMessageSnapshot(cached).owner, getSessionMessageSnapshot(background).owner);
+}));
+
+test("active and background duplicate inputs apply deltas to the last value at the first position", () => withFrames((flush) => {
+ const duplicates = () => [message("live", { content: "old" }), message("middle"), message("live", { content: "latest" })];
+ const h = harness(duplicates(), duplicates());
+ for (const sessionId of ["active", "background"]) h.get().handleAgentEvent(envelope(sessionId, "live", "+delta"));
+ flush();
+ for (const rows of [h.get().messages, h.runtime.sessionTranscriptCache.get("background")]) {
+ assert.deepEqual(rows.map((row) => row.id), ["live", "middle"]);
+ assert.equal(rows[0].content, "latest+delta");
+ assert.equal(getSessionMessageSnapshot(rows).unique, true);
+ }
+}));
+
+test("a delta before message_start appends once and terminal events flush the exact live row", () => withFrames((flush) => {
+ const h = harness([message("historical")]);
+ h.get().handleAgentEvent(envelope("active", "missing", "partial"));
+ flush();
+ const beforeTerminal = h.get().messages;
+ h.get().handleAgentEvent({ sessionId: "active", ts: 2, event: { type: "message_start", message: message("missing", { content: "" }) } });
+ assert.equal(h.get().messages, beforeTerminal, "late start does not reset a partial row");
+ h.get().handleAgentEvent(envelope("active", "missing", "+queued"));
+ h.get().handleAgentEvent({ sessionId: "active", ts: 3, event: { type: "message_end", message: message("missing", { content: "final", status: "complete" }) } });
+ assert.deepEqual(h.get().messages.map((row) => row.id), ["historical", "missing"]);
+ assert.equal(h.get().messages.at(-1).content, "final");
+ assert.equal(beforeTerminal.at(-1).content, "partial");
+}));
+
+const partialTool = (sessionId, toolCallId, partialResult) => ({
+ sessionId, ts: 1, event: { type: "tool_update", toolCallId, partialResult },
+});
+
+test("warm foreground tool partials preserve tracked projection without historical identity or content reads", () => withFrames((flush) => {
+ const reads = { id: 0, toolCallId: 0, content: 0 };
+ const rows = Array.from({ length: 10_000 }, (_, index) => ({
+ ...message(`old-${index}`, { role: index % 2 ? "assistant" : "user" }),
+ get id() { reads.id++; return `old-${index}`; },
+ get toolCallId() { reads.toolCallId++; return undefined; },
+ get content() { reads.content++; return `Historical ${index}`; },
+ }));
+ rows.push(message("noncanonical-tool-row", {
+ role: "tool", toolCallId: "live-call", toolName: "Bash", toolStatus: "running", content: "seed",
+ }));
+ const h = harness(rows);
+ const source = getSessionMessageSnapshot(rows);
+ const projection = getTranscriptProjection(rows);
+ Object.assign(reads, { id: 0, toolCallId: 0, content: 0 });
+ let projected;
+ for (let index = 0; index < 10; index++) {
+ h.get().handleAgentEvent(partialTool("active", "live-call", `partial ${index}`));
+ flush();
+ projected = getTranscriptProjection(h.get().messages);
+ }
+ assert.deepEqual(reads, { id: 0, toolCallId: 0, content: 0 });
+ assert.equal(h.get().messages.at(-1).content, "partial 9");
+ assert.equal(projected.visible.at(-1), h.get().messages.at(-1));
+ assert.equal(projected.history, projection.history);
+ assert.equal(getSessionMessageSnapshot(h.get().messages).owner, source.owner);
+ assert.equal(getSessionMessageSnapshot(h.get().messages).positions, source.positions);
+ assert.equal(getSessionMessageSnapshot(h.get().messages).blocks[0], source.blocks[0]);
+ assert.equal(rows.at(-1).content, "seed");
+}));
+
+test("foreground tool partials replace all running call matches, including duplicate and non-tool rows", () => withFrames((flush) => {
+ const rows = [
+ message("duplicate", { role: "tool", toolCallId: "call", toolStatus: "running", content: "first" }),
+ message("complete", { role: "tool", toolCallId: "call", toolStatus: "success", content: "done" }),
+ message("duplicate", { role: "tool", toolCallId: "call", toolStatus: "running", content: "last" }),
+ message("unusual", { role: "assistant", toolCallId: "call", toolStatus: "running" }),
+ message("other", { role: "tool", toolCallId: "different", toolStatus: "running" }),
+ ];
+ const h = harness(rows);
+ h.get().handleAgentEvent(partialTool("active", "call", { stdout: "partial" }));
+ flush();
+ assert.equal(h.get().messages.length, rows.length, "the foreground path does not dedupe physical rows");
+ for (const index of [0, 2, 3]) {
+ assert.notEqual(h.get().messages[index], rows[index]);
+ assert.deepEqual(h.get().messages[index].toolResult, { stdout: "partial" });
+ assert.match(h.get().messages[index].content, /partial/);
+ }
+ for (const index of [1, 4]) assert.equal(h.get().messages[index], rows[index]);
+ const unchanged = h.get().messages;
+ h.get().handleAgentEvent(partialTool("active", "missing", "ignored"));
+ h.get().handleAgentEvent(partialTool("active", "call", undefined));
+ flush();
+ assert.equal(h.get().messages, unchanged);
+}));
+
+test("background tool partials stay cache-only and update the first running match without historical scans", () => withFrames((flush) => {
+ let reads = 0;
+ const background = Array.from({ length: 200 }, (_, index) => ({
+ ...message(`old-${index}`),
+ get id() { reads++; return `old-${index}`; },
+ get toolCallId() { reads++; return undefined; },
+ get content() { reads++; return "history"; },
+ }));
+ background.push(
+ message("complete", { toolCallId: "call", toolStatus: "success" }),
+ message("first", { toolCallId: "call", toolStatus: "running" }),
+ message("second", { toolCallId: "call", toolStatus: "running" }),
+ );
+ const h = harness([message("active")], background);
+ const retained = h.get().retainedTranscripts;
+ reads = 0;
+ h.get().handleAgentEvent(partialTool("background", "call", "partial"));
+ flush();
+ const updated = h.runtime.sessionTranscriptCache.get("background");
+ assert.equal(reads, 0);
+ assert.equal(updated.at(-2).content, "partial");
+ assert.equal(updated.at(-1), background.at(-1));
+ assert.equal(updated.at(-3), background.at(-3));
+ assert.equal(h.get().retainedTranscripts, retained);
+ assert.equal(h.writes(), 0);
+}));
diff --git a/apps/desktop/test/session-switch-performance.test.mjs b/apps/desktop/test/session-switch-performance.test.mjs
index 99330c6c1..0e309bde3 100644
--- a/apps/desktop/test/session-switch-performance.test.mjs
+++ b/apps/desktop/test/session-switch-performance.test.mjs
@@ -178,7 +178,7 @@ test("reopening a running session never lets durable detail erase its live tail"
// A warm pane must not reveal one deferred frame from before the stream was
// captured; its first visible render uses the selected live snapshot.
assert.match(transcript, /const paneRevealed = paneVisible && !wasPaneVisibleRef\.current/);
- assert.match(transcript, /firstCommit \|\| paneRevealed \? messages : deferredMessages/);
+ assert.match(transcript, /firstCommit \|\| paneRevealed \? projection : deferredProjection/);
});
test("reopening an idle session keeps a completed live tail until the durable page has it (D324)", () => {
diff --git a/apps/desktop/test/session-transcript-updates.test.mjs b/apps/desktop/test/session-transcript-updates.test.mjs
new file mode 100644
index 000000000..536825376
--- /dev/null
+++ b/apps/desktop/test/session-transcript-updates.test.mjs
@@ -0,0 +1,162 @@
+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 {
+ getSessionMessageSnapshot,
+ getSessionToolMessagePositions,
+ SESSION_MESSAGE_BLOCK_SIZE,
+} = await import("../src/lib/session-transcript-updates.ts");
+const {
+ dedupeSessionMessages,
+ projectMessageEnd,
+ reconcilePersistedUserMessage,
+ removeLiveSessionMessage,
+ upsertLiveSessionMessage,
+} = await import("../src/lib/session-transcript.ts");
+
+const message = (id, overrides = {}) => ({
+ id,
+ role: "assistant",
+ content: id,
+ createdAt: "2026-09-30T00:00:00Z",
+ ...overrides,
+});
+const history = (length) => Array.from({ length }, (_, index) => message(`row-${index}`));
+
+test("warm replacements and dedupe do not read historical message ids", () => {
+ let historicalIdReads = 0;
+ const rows = Array.from({ length: 10_000 }, (_, index) => ({
+ ...message(`old-${index}`),
+ get id() { historicalIdReads++; return `old-${index}`; },
+ }));
+ rows.push(message("tail", { status: "streaming" }));
+ const first = getSessionMessageSnapshot(rows);
+ historicalIdReads = 0;
+ let current = rows;
+ for (let index = 0; index < 20; index++) {
+ current = upsertLiveSessionMessage(current, message("tail", { content: `token ${index}` }));
+ assert.equal(dedupeSessionMessages(current), current);
+ }
+ const latest = getSessionMessageSnapshot(current);
+ assert.equal(historicalIdReads, 0);
+ assert.equal(latest.owner, first.owner);
+ assert.equal(latest.generation, first.generation + 20);
+ assert.equal(latest.positions, first.positions);
+ assert.equal(latest.blocks[0], first.blocks[0]);
+ assert.equal(rows.at(-1).content, "tail", "published source array is not mutated");
+});
+
+test("immutable blocks retain every changed region across skipped or branched generations", () => {
+ const rows = history(SESSION_MESSAGE_BLOCK_SIZE * 4);
+ const first = getSessionMessageSnapshot(rows);
+ const changedEarly = upsertLiveSessionMessage(rows, message("row-3", { content: "early" }));
+ const second = getSessionMessageSnapshot(changedEarly);
+ const changedLate = upsertLiveSessionMessage(changedEarly, message("row-130", { content: "late" }));
+ const third = getSessionMessageSnapshot(changedLate);
+ assert.equal(third.owner, first.owner);
+ assert.equal(third.generation, first.generation + 2);
+ assert.notEqual(third.blocks[0], first.blocks[0]);
+ assert.equal(third.blocks[0], second.blocks[0]);
+ assert.equal(third.blocks[1], first.blocks[1]);
+ assert.notEqual(third.blocks[2], first.blocks[2]);
+ assert.equal(third.blocks[3], first.blocks[3]);
+ assert.equal(first.blocks[0][3].content, "row-3");
+ assert.equal(second.blocks[2][2].content, "row-130");
+ assert.equal(getSessionMessageSnapshot(rows), first);
+
+ const abandonedBranch = upsertLiveSessionMessage(rows, message("row-65", { content: "branch" }));
+ const branch = getSessionMessageSnapshot(abandonedBranch);
+ assert.equal(branch.blocks[0], first.blocks[0]);
+ assert.notEqual(branch.blocks[1], first.blocks[1]);
+ assert.equal(branch.blocks[2], first.blocks[2]);
+ assert.equal(third.blocks[1][1].content, "row-65");
+});
+
+test("unknown arrays validate once and receive independent owners", () => {
+ let reads = 0;
+ const rows = [{ ...message("id"), get id() { reads++; return "id"; } }];
+ const snapshot = getSessionMessageSnapshot(rows);
+ assert.equal(getSessionMessageSnapshot(rows), snapshot);
+ assert.equal(dedupeSessionMessages(rows), rows);
+ assert.equal(reads, 1);
+ const copy = rows.slice();
+ assert.notEqual(getSessionMessageSnapshot(copy).owner, snapshot.owner);
+ assert.equal(reads, 2);
+ const reordered = history(3).reverse();
+ assert.equal(getSessionMessageSnapshot(reordered).positions.get("row-2"), 0);
+});
+
+test("duplicates keep first position, last value and become a tracked unique array", () => {
+ const rows = [message("a"), message("b"), message("a", { content: "last a" }), message("c"), message("b", { content: "last b" })];
+ const source = getSessionMessageSnapshot(rows);
+ assert.equal(source.unique, false);
+ assert.equal(source.positions.get("a"), 0);
+ const normalized = dedupeSessionMessages(rows);
+ assert.deepEqual(normalized.map((row) => row.content), ["last a", "last b", "c"]);
+ const next = getSessionMessageSnapshot(normalized);
+ assert.equal(next.unique, true);
+ assert.equal(next.owner, source.owner);
+ assert.equal(next.positions.get("c"), 2);
+ assert.equal(source.positions.get("c"), 3, "normalization never mutates the published index");
+ const updated = upsertLiveSessionMessage(rows, message("b", { content: "updated b" }));
+ assert.deepEqual(updated.map((row) => row.content), ["last a", "updated b", "c"]);
+});
+
+test("append, removal, native rekey and optimistic acknowledgement refresh indexes safely", () => {
+ const rows = history(SESSION_MESSAGE_BLOCK_SIZE);
+ const before = getSessionMessageSnapshot(rows);
+ const appended = upsertLiveSessionMessage(rows, message("provisional", { status: "streaming" }));
+ const after = getSessionMessageSnapshot(appended);
+ assert.equal(after.owner, before.owner);
+ assert.equal(after.blocks[0], before.blocks[0]);
+ assert.notEqual(after.positions, before.positions);
+ assert.equal(before.positions.has("provisional"), false);
+ const terminal = message("durable", { status: "complete" });
+ const rekeyed = projectMessageEnd(appended, { type: "message_end", replacesMessageId: "provisional", message: terminal });
+ assert.equal(rekeyed.at(-1), terminal);
+ const rekeyedSnapshot = getSessionMessageSnapshot(rekeyed);
+ assert.equal(rekeyedSnapshot.owner, before.owner);
+ assert.equal(rekeyedSnapshot.positions.has("provisional"), false);
+ assert.equal(rekeyedSnapshot.positions.get("durable"), SESSION_MESSAGE_BLOCK_SIZE);
+ assert.equal(after.positions.has("provisional"), true);
+ const removed = removeLiveSessionMessage(rekeyed, "row-3");
+ assert.equal(getSessionMessageSnapshot(removed).positions.get("row-4"), 3);
+ assert.equal(rekeyedSnapshot.positions.get("row-4"), 4);
+
+ const optimistic = [message("o", { role: "user" }), message("other"), message("ack", { role: "user" })];
+ const acknowledged = message("ack", { role: "user", content: "acknowledged" });
+ const result = reconcilePersistedUserMessage(optimistic, "o", acknowledged);
+ assert.deepEqual(result.map((row) => row.id), ["ack", "other"]);
+ assert.equal(result[0], acknowledged);
+ assert.equal(getSessionMessageSnapshot(result).unique, true);
+});
+
+test("tool-call positions follow same-id rekeys, role/status changes and structural edits immutably", () => {
+ const rows = [
+ message("first", { role: "tool", toolCallId: "a", toolStatus: "running" }),
+ message("second", { role: "tool", toolCallId: "b", toolStatus: "running" }),
+ message("third", { role: "assistant", toolCallId: "a", toolStatus: "success" }),
+ ];
+ const original = getSessionToolMessagePositions(rows, "a");
+ assert.deepEqual(original, [0, 2]);
+ const rekeyed = upsertLiveSessionMessage(rows, { ...rows[0], toolCallId: "b" });
+ assert.deepEqual(getSessionToolMessagePositions(rekeyed, "a"), [2]);
+ assert.deepEqual(getSessionToolMessagePositions(rekeyed, "b"), [0, 1]);
+ assert.deepEqual(original, [0, 2]);
+ assert.deepEqual(getSessionToolMessagePositions(rows, "b"), [1]);
+ assert.throws(() => original.push(9), TypeError, "callers cannot mutate a published position list");
+
+ const changedRole = upsertLiveSessionMessage(rekeyed, { ...rekeyed[0], role: "user", toolStatus: "success" });
+ assert.deepEqual(getSessionToolMessagePositions(changedRole, "b"), [0, 1], "the event predicate is role independent");
+ const removedCall = upsertLiveSessionMessage(changedRole, { ...changedRole[0], toolCallId: undefined });
+ assert.deepEqual(getSessionToolMessagePositions(removedCall, "b"), [1]);
+ const appended = upsertLiveSessionMessage(removedCall, message("last", { toolCallId: "b" }));
+ assert.deepEqual(getSessionToolMessagePositions(appended, "b"), [1, 3]);
+ assert.deepEqual(getSessionToolMessagePositions(removedCall, "b"), [1]);
+ const shortened = removeLiveSessionMessage(appended, "first");
+ assert.deepEqual(getSessionToolMessagePositions(shortened, "b"), [0, 2]);
+ const unknown = [shortened[2], shortened[0]];
+ assert.deepEqual(getSessionToolMessagePositions(unknown, "b"), [0, 1]);
+});
diff --git a/apps/desktop/test/session-transcript.test.mjs b/apps/desktop/test/session-transcript.test.mjs
index 8edc8322c..2637c3f4c 100644
--- a/apps/desktop/test/session-transcript.test.mjs
+++ b/apps/desktop/test/session-transcript.test.mjs
@@ -1,13 +1,16 @@
import assert from "node:assert/strict";
+import { register } from "node:module";
import test from "node:test";
-import {
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const {
dedupeSessionMessages,
durableCoversLiveSessionMessages,
mergeLiveSessionMessages,
optimisticUserMessage,
removeLiveSessionMessage,
upsertLiveSessionMessage,
-} from "../src/lib/session-transcript.ts";
+} = await import("../src/lib/session-transcript.ts");
const message = (id, overrides = {}) => ({
id,
diff --git a/apps/desktop/test/subagent-transcript.test.mjs b/apps/desktop/test/subagent-transcript.test.mjs
index e7834a67d..64544bff2 100644
--- a/apps/desktop/test/subagent-transcript.test.mjs
+++ b/apps/desktop/test/subagent-transcript.test.mjs
@@ -68,12 +68,14 @@ test("a delegation card reads its outcome from the lifecycle rows", () => {
assert.match(topologySource, /if \(isDelegationActivityItem\(item\)\) continue;/);
assert.match(
transcriptSource,
- /const delegationStatuses = turnDelegationStatuses \?\? collectDelegationStatuses\(items\)/,
+ /const delegationStatuses = useMemo\(\(\) => turnDelegationStatuses \?\? collectDelegationStatuses\(delegationItems\)/,
);
assert.match(
transcriptSource,
- /collectDelegationStatuses\(turnAllActivityItems, \{ turnLive: isActive \}\)/,
+ /collectDelegationStatuses\(delegationItems, \{ turnLive: isActive \}\)/,
);
+ assert.match(transcriptSource, /const tools = reuseReferences\(toolsRef\.current, summary\.tools\)/);
+ assert.match(transcriptSource, /delegationItems = useMemo\(\(\) => tools\.map/);
});
test("a lifecycle row summarizes by agent name, never by delegation id", () => {
@@ -235,7 +237,7 @@ test("every Task row renders as one accessible delegation topology", () => {
);
assert.match(
transcriptSource,
- /<SubagentTopology\s+key="subagent-topology"\s+items=\{delegateItems\}\s+delegationStatuses=\{delegationStatuses\}\s+delegationTimings=\{delegationTimings\}\s+onUserInteraction=\{claimDisclosure\}\s*\/>/,
+ /<SubagentTopology\s+key="subagent-topology"\s+items=\{delegateItems\}\s+delegationStatuses=\{delegationStatuses\}\s+delegationTimings=\{delegationTimings\}\s+onUserInteraction=\{onUserInteraction\}\s*\/>/,
);
assert.match(transcriptSource, /className="subagent-topology" aria-labelledby=/);
assert.match(transcriptSource, /className="subagent-topology-agents"/);
diff --git a/apps/desktop/test/thinking-ui.test.mjs b/apps/desktop/test/thinking-ui.test.mjs
index c90378d3c..7cd56ec5c 100644
--- a/apps/desktop/test/thinking-ui.test.mjs
+++ b/apps/desktop/test/thinking-ui.test.mjs
@@ -252,7 +252,7 @@ test("transcript keeps assistant thinking in a separate disclosure", () => {
assert.match(transcriptSource, /thinking-prose[\s\S]*?Markdown source=\{text\}/);
assert.match(transcriptSource, /CopyButton text=\{content\}/);
assert.match(transcriptSource, /messageThinking as thinkingText/);
- assert.match(transcriptSource, /onlyThinking = items\.every/);
+ assert.match(transcriptSource, /onlyThinking = useMemo\(\(\) => items\.every/);
assert.match(stylesSource, /\.thinking-prose/);
});
@@ -284,11 +284,11 @@ test("detailed mode opens the last tool while compact keeps payloads collapsed",
assert.match(transcriptSource, /useAutomaticDisclosure\(\s*hasSubagentTopology \? live : visibleItems\.length <= 1/);
assert.match(
transcriptSource,
- /<ThinkingRow[\s\S]*?autoOpen=\{live && itemIndex === items.length - 1\}/,
+ /<ThinkingRow[\s\S]*?autoOpen=\{live && item === lastItem\}/,
);
assert.match(
transcriptSource,
- /const autoOpenLatest =\s*!compact && isLast && itemIndex === items.length - 1/,
+ /const autoOpenLatest =\s*!compact && isLast && item === lastItem/,
);
assert.match(transcriptSource, /<ToolRow[\s\S]*?autoOpen=\{autoOpenLatest\}/);
assert.match(transcriptToolRowSource, /const disclosure = useAutomaticDisclosure\(\s*autoOpen && !failed && status !== "denied",\s*revealRequest/);
diff --git a/apps/desktop/test/transcript-projection.test.mjs b/apps/desktop/test/transcript-projection.test.mjs
new file mode 100644
index 000000000..01a3de4ad
--- /dev/null
+++ b/apps/desktop/test/transcript-projection.test.mjs
@@ -0,0 +1,176 @@
+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 { getTranscriptProjection } = await import("../src/lib/transcript-projection.ts");
+const { upsertLiveSessionMessage } = await import("../src/lib/session-transcript.ts");
+const { latestTurnContextInspector } = await import("../src/lib/latest-turn-context.ts");
+const { buildConversationMinimapMarkers } = await import("../src/lib/conversation-minimap.ts");
+
+const usage = { inputTokens: 20, outputTokens: 5, totalTokens: 25 };
+const message = (id, role, content, extra = {}) => ({
+ id, role, content, createdAt: "2026-09-30T00:00:00.000Z", ...extra,
+});
+
+function assertProjection(messages, compactions) {
+ const actual = getTranscriptProjection(messages, compactions);
+ const expected = buildTranscriptEntries(messages, compactions);
+ assert.deepEqual(actual.entries, expected.entries);
+ assert.deepEqual(actual.visible, expected.visible);
+ assert.deepEqual(actual.history, expected.entries.slice(0, -1));
+ return actual;
+}
+
+for (const count of [100, 1_000, 10_784]) {
+ test(`${count} loaded messages: one tail delta does not read historical content`, () => {
+ let reads = 0;
+ let messages = Array.from({ length: count - 1 }, (_, index) => {
+ const row = message(`m-${index}`, index % 2 ? "assistant" : "user", "", index % 2 ? { usage } : {});
+ Object.defineProperty(row, "content", {
+ enumerable: true,
+ get() { reads++; return "Synthetic historical content. ".repeat(36); },
+ });
+ return row;
+ });
+ messages.push(message("tail", "assistant", "Live", { status: "streaming" }));
+ const before = getTranscriptProjection(messages);
+ const inspector = latestTurnContextInspector(messages, {}, []);
+ buildConversationMinimapMarkers(before.visible);
+ messages = upsertLiveSessionMessage(messages, { ...messages.at(-1), content: "Live delta" });
+ reads = 0;
+ const after = getTranscriptProjection(messages);
+ const nextInspector = latestTurnContextInspector(messages, {}, []);
+ buildConversationMinimapMarkers(after.visible);
+ assert.equal(reads, 0, "completed content must stay out of the update path");
+ assert.equal(after.history, before.history);
+ assert.equal(nextInspector, inspector, "unchanged context statistics retain their identity");
+ assertProjection(messages);
+ });
+}
+
+test("the first tool output does not rebuild unrelated completed history", () => {
+ let reads = 0;
+ let messages = Array.from({ length: 1_000 }, (_, index) => {
+ const row = message(`m-${index}`, index % 2 ? "assistant" : "user", "");
+ Object.defineProperty(row, "content", {
+ enumerable: true, get() { reads++; return "Completed content"; },
+ });
+ return row;
+ });
+ messages.push(message("tool", "tool", "", { toolName: "Bash", toolCallId: "tool", toolStatus: "running" }));
+ const before = getTranscriptProjection(messages);
+ messages = upsertLiveSessionMessage(messages, { ...messages.at(-1), content: "First output", toolResult: "First output" });
+ reads = 0;
+ const after = getTranscriptProjection(messages);
+ assert.equal(reads, 0);
+ assert.equal(after.history, before.history);
+ assertProjection(messages);
+});
+
+test("one giant turn preserves completed activity parts and old snapshots", () => {
+ let messages = [message("user", "user", "Work")];
+ for (let index = 0; index < 300; index++) {
+ messages.push(message(`tool-${index}`, "tool", "result", { toolName: "Read", toolCallId: `tool-${index}` }));
+ messages.push(message(`answer-${index}`, "assistant", `Answer ${index}`, { usage }));
+ }
+ messages.push(message("tail", "assistant", "Live", { thinking: "Plan", status: "streaming" }));
+ const before = assertProjection(messages);
+ const oldSource = messages;
+ messages = upsertLiveSessionMessage(messages, { ...messages.at(-1), thinking: "Plan more", content: "Live more" });
+ const after = assertProjection(messages);
+ assert.equal(after.entries[1].parts[0], before.entries[1].parts[0]);
+ assert.equal(before.entries[1].parts.at(-1).message.content, "Live");
+ assert.equal(after.entries[1].parts.at(-1).message.content, "Live more");
+ assert.equal(getTranscriptProjection(oldSource), before);
+});
+
+test("skipped generations and old deferred reads preserve every changed row", () => {
+ let messages = [message("u", "user", "Work"), ...Array.from({ length: 160 }, (_, index) => message(`a-${index}`, "assistant", `Answer ${index}`))];
+ const original = messages;
+ const first = assertProjection(messages);
+ const middle = upsertLiveSessionMessage(messages, { ...messages[3], content: "Changed early" });
+ messages = upsertLiveSessionMessage(middle, { ...middle[130], content: "Changed later" });
+ const newest = assertProjection(messages);
+ assertProjection(middle);
+ assert.equal(getTranscriptProjection(original), first);
+ assert.equal(getTranscriptProjection(messages), newest);
+ messages = upsertLiveSessionMessage(messages, { ...messages.at(-1), content: "Tail" });
+ assertProjection(messages);
+});
+
+test("interleaved delegate text patches every answer/thinking slot, not a guessed tail", () => {
+ let messages = [
+ message("u", "user", "Run delegates"),
+ message("task", "tool", "running", { toolName: "Task", toolCallId: "call", toolArgs: {}, toolResult: {} }),
+ message("child", "assistant", "Child answer", { parentToolCallId: "call", agentName: "worker", thinking: "Child reasoning" }),
+ message("parent", "assistant", "Parent answer"),
+ ];
+ const before = assertProjection(messages);
+ messages = upsertLiveSessionMessage(messages, { ...messages[2], content: "Child answer updated", thinking: "Child reasoning updated" });
+ const after = assertProjection(messages);
+ const items = after.entries[1].parts[0].items[0].delegate.items;
+ assert.equal(items[0].message, messages[2]);
+ assert.equal(items[1].message, messages[2]);
+ assert.equal(after.entries[1].parts[1], before.entries[1].parts[1]);
+ assert.equal(before.entries[1].parts[0].items[0].delegate.items[1].message.content, "Child answer");
+});
+
+test("structural visibility, compaction, resume, rewrite and duplicate inputs match full grouping", () => {
+ let messages = [message("u", "user", "Work"), message("a", "assistant", "", { thinking: "Reason" })];
+ const compactions = [{ id: "compact", throughMessageId: "a", generation: 1, summaryTokens: 10, summarized: true }];
+ assertProjection(messages);
+ for (const change of [
+ { content: "First text" }, { thinking: "" }, { content: " " },
+ { error: { code: "FAILED", message: "Failed" } }, { content: "Recovered", error: undefined },
+ ]) {
+ messages = upsertLiveSessionMessage(messages, { ...messages[1], ...change });
+ assertProjection(messages);
+ assertProjection(messages, compactions);
+ }
+ messages = upsertLiveSessionMessage(messages, message("task-1", "tool", "done", {
+ toolName: "Task", toolCallId: "call-1", toolResult: { details: { delegationId: "delegate" } },
+ }));
+ messages = upsertLiveSessionMessage(messages, message("child", "assistant", "Report", { parentToolCallId: "call-1" }));
+ assertProjection(messages);
+ messages = upsertLiveSessionMessage(messages, message("task-2", "tool", "done", {
+ toolName: "Task", toolCallId: "call-2", toolArgs: { resume: "delegate" },
+ }));
+ assertProjection(messages);
+ messages = upsertLiveSessionMessage(messages, { ...messages.at(-1), toolArgs: {} });
+ assertProjection(messages);
+ assertProjection([message("older", "user", "Older"), ...messages]);
+ assertProjection(messages.slice(2));
+ assertProjection([...messages, { ...messages[1], content: "Duplicate" }]);
+});
+
+test("deterministic replacement sequences match grouping after each update", () => {
+ let messages = [message("u", "user", "Work")];
+ for (let index = 0; index < 80; index++) {
+ messages.push(message(`a-${index}`, "assistant", `Text ${index}`, { thinking: index % 2 ? "Reason" : "", usage }));
+ messages.push(message(`tool-${index}`, "tool", "Result", { toolName: "Read", toolCallId: `tool-${index}` }));
+ }
+ assertProjection(messages);
+ for (let step = 0; step < 100; step++) {
+ const index = 1 + ((step * 37) % (messages.length - 1));
+ messages = upsertLiveSessionMessage(messages, {
+ ...messages[index], content: `Replacement ${step}`,
+ ...(step % 11 === 0 ? { thinking: "New reasoning" } : {}),
+ });
+ assertProjection(messages);
+ }
+});
+
+test("a saturated minimap preview ignores later huge fragments but keeps user boundaries", () => {
+ let reads = 0;
+ const later = message("later", "assistant", "");
+ Object.defineProperty(later, "content", { get() { reads++; return "x".repeat(100_000); } });
+ const markers = buildConversationMinimapMarkers([
+ message("u", "user", "Question"), message("first", "assistant", "a".repeat(280)),
+ later, message("system", "system", "Boundary"), message("after-system", "assistant", "Same marker"),
+ message("u2", "user", "Next"), message("a2", "assistant", "Second answer"),
+ ]);
+ assert.equal(reads, 0);
+ assert.deepEqual(markers.map(({ id }) => id), ["u", "first", "u2", "a2"]);
+});
diff --git a/apps/desktop/test/transcript-reading.test.mjs b/apps/desktop/test/transcript-reading.test.mjs
index 8cee8d1ac..422572c6c 100644
--- a/apps/desktop/test/transcript-reading.test.mjs
+++ b/apps/desktop/test/transcript-reading.test.mjs
@@ -6,7 +6,9 @@ register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
const { createTranscriptReadingRuntime } = await import(
"../src/stores/runtime/transcript-reading-runtime.ts"
);
-const { transcriptViewMessages } = await import("../src/lib/transcript-reading.ts");
+const { transcriptViewMessages, transcriptViewFromSession } = await import("../src/lib/transcript-reading.ts");
+const { getSessionMessageSnapshot } = await import("../src/lib/session-transcript-updates.ts");
+const { mergeLiveSessionMessages, upsertLiveSessionMessage, projectMessageEnd, removeLiveSessionMessage } = await import("../src/lib/session-transcript.ts");
const { buildTranscriptEntries } = await import("../src/lib/assistant-turns.ts");
const { prepareTranscriptAction } = await import("../src/stores/runtime/transcript-action.ts");
@@ -399,3 +401,99 @@ test("paging during an existing stream never freezes its snapshot over newer tok
);
assert.equal(r.visible().at(-1), complete);
});
+
+function fullReadingProjection(live, view) {
+ const current = new Map(live.map((row) => [row.id, row]));
+ return mergeLiveSessionMessages(view.messages, live).map((row) => current.get(row.id) ?? row);
+}
+
+test("ordinary reading replaces only changed overlap without rereading historical ids", () => {
+ let reads = 0;
+ const rows = Array.from({ length: 10_000 }, (_, index) => ({
+ ...message(`old-${index}`),
+ get id() { reads++; return `old-${index}`; },
+ }));
+ const live = [...rows, message("tail", "partial", { role: "assistant", status: "streaming" })];
+ const view = transcriptViewFromSession(page([message("earlier"), ...live]).session);
+ const first = transcriptViewMessages(live, view);
+ assert.equal(transcriptViewMessages(live, view), first);
+ reads = 0;
+ const nextLive = upsertLiveSessionMessage(live, message("tail", "final", { role: "assistant", status: "complete" }));
+ const next = transcriptViewMessages(nextLive, view);
+ assert.equal(reads, 0);
+ assert.equal(next.at(-1), nextLive.at(-1));
+ assert.equal(first.at(-1).content, "partial");
+ const before = getSessionMessageSnapshot(first);
+ const after = getSessionMessageSnapshot(next);
+ assert.equal(before.owner, after.owner);
+ assert.equal(before.positions, after.positions);
+ assert.equal(before.blocks[0], after.blocks[0]);
+ assert.notEqual(before.blocks.at(-1), after.blocks.at(-1));
+});
+
+test("reading overlap includes skipped non-tail updates and remains safe for older renders", () => {
+ const live = Array.from({ length: 200 }, (_, index) => message(`row-${index}`));
+ const view = transcriptViewFromSession(page([message("older"), ...live.slice(0, 5)]).session);
+ const first = transcriptViewMessages(live, view);
+ const early = upsertLiveSessionMessage(live, message("row-2", "changed early"));
+ const late = upsertLiveSessionMessage(early, message("row-150", "changed late"));
+ const latest = transcriptViewMessages(late, view);
+ assert.deepEqual(latest, fullReadingProjection(late, view));
+ assert.equal(latest[3].content, "changed early");
+ assert.equal(latest[151].content, "changed late");
+ assert.equal(first[3].content, "row-2");
+ assert.deepEqual(transcriptViewMessages(early, view), fullReadingProjection(early, view));
+ assert.deepEqual(transcriptViewMessages(late, view), latest);
+});
+
+test("reading cache invalidates structural changes, unrelated sources and changed view owners", () => {
+ const view = transcriptViewFromSession(page([message("older")]).session);
+ const initial = [message("a"), message("provisional", "partial", { role: "assistant" })];
+ const first = transcriptViewMessages(initial, view);
+ const appended = upsertLiveSessionMessage(initial, message("b"));
+ assert.deepEqual(transcriptViewMessages(appended, view), fullReadingProjection(appended, view));
+ const rekeyed = projectMessageEnd(appended, {
+ type: "message_end", replacesMessageId: "provisional",
+ message: message("durable", "final", { role: "assistant", status: "complete" }),
+ });
+ assert.deepEqual(transcriptViewMessages(rekeyed, view), fullReadingProjection(rekeyed, view));
+ const removed = removeLiveSessionMessage(rekeyed, "a");
+ assert.deepEqual(transcriptViewMessages(removed, view), fullReadingProjection(removed, view));
+ const unknown = [message("replacement"), message("replacement", "last duplicate")];
+ assert.deepEqual(transcriptViewMessages(unknown, view), fullReadingProjection(unknown, view));
+ const changedView = { ...view, messages: [message("different history")] };
+ assert.deepEqual(transcriptViewMessages(removed, changedView), fullReadingProjection(removed, changedView));
+ assert.deepEqual(first.map((row) => row.id), ["older", "a", "provisional"]);
+ assert.equal(transcriptViewMessages(removed), removed, "return to latest bypasses the reading cache");
+});
+
+test("timestamp corrections remerge chronological positions instead of patching stale order", () => {
+ const at = (id, day) => message(id, id, { createdAt: `2026-09-${day}T00:00:00Z` });
+ const keep = at("keep", 20);
+ const live = [keep, at("old", 10), at("tail", 30)];
+ const view = transcriptViewFromSession(page([keep]).session);
+ assert.deepEqual(transcriptViewMessages(live, view).map((row) => row.id), ["old", "keep", "tail"]);
+ const corrected = upsertLiveSessionMessage(live, at("old", 25));
+ assert.deepEqual(transcriptViewMessages(corrected, view), fullReadingProjection(corrected, view));
+ assert.deepEqual(transcriptViewMessages(corrected, view).map((row) => row.id), ["keep", "old", "tail"]);
+});
+
+test("focused search never reads unused live identities, including parent context", () => {
+ const live = [{ ...message("unused"), get id() { assert.fail("historical search indexed live rows"); } }];
+ const parent = message("task", "latest parent", { role: "tool" });
+ const view = transcriptViewFromSession(page([message("hit")], { navigationParent: parent }).session, target("hit"));
+ assert.deepEqual(transcriptViewMessages(live, view), [parent, view.messages[0]]);
+ const overlapping = { ...view, messages: [message("task", "old parent"), ...view.messages] };
+ assert.deepEqual(transcriptViewMessages(live, overlapping), [parent, view.messages[0]]);
+});
+
+test("ordinary parent context stays authoritative over tracked live changes", () => {
+ const parent = message("task", "navigation parent", { role: "tool" });
+ const view = transcriptViewFromSession(page([message("hit")], { navigationParent: parent }).session);
+ const live = [message("task", "live parent", { role: "tool" }), message("tail")];
+ const initial = transcriptViewMessages(live, view);
+ const updated = upsertLiveSessionMessage(live, message("task", "new live parent", { role: "tool" }));
+ const next = transcriptViewMessages(updated, view);
+ assert.equal(next, initial);
+ assert.equal(next.find((row) => row.id === "task"), parent);
+});
diff --git a/apps/desktop/test/transcript-summary.test.mjs b/apps/desktop/test/transcript-summary.test.mjs
new file mode 100644
index 000000000..c1dc32d32
--- /dev/null
+++ b/apps/desktop/test/transcript-summary.test.mjs
@@ -0,0 +1,256 @@
+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 {
+ assistantTurnContent, assistantTurnMessages, assistantTurnUsage,
+ assistantTurnResponseDuration, assistantTurnResponseOutputTokens,
+ 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 { 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");
+const { reconcileRenderBlocks, TRANSCRIPT_RENDER_BLOCK_SIZE } = await import("../src/features/chat/transcript/render-blocks.ts");
+
+const message = (id, content, extra = {}) => ({
+ id, role: "assistant", content, createdAt: "2026-09-17T00:00:00.000Z", ...extra,
+});
+const entry = (messages) => ({ kind: "assistant-turn", id: "turn", parts: messages.map((message) => ({ kind: "message", message })) });
+
+test("tail text updates do not read historical assistant content", () => {
+ let reads = 0;
+ const old = Array.from({ length: 1024 }, (_, index) => ({
+ ...message(`old-${index}`, ""),
+ get content() { reads += 1; return `progress ${index}`; },
+ }));
+ const first = entry([...old, message("tail", "a", { status: "streaming" })]);
+ getAssistantTurnSummary(first);
+ reads = 0;
+ const second = { ...first, parts: [...first.parts.slice(0, -1), { kind: "message", message: message("tail", "ab", { status: "streaming" }) }] };
+ assert.equal(getAssistantTurnSummary(second).hasContent, true);
+ assert.equal(reads, 0);
+ assert.equal(getAssistantTurnContent(second), [...old.map((_, index) => `progress ${index}`), "ab"].join("\n\n"));
+ assert.equal(reads, 0, "copy uses cached per-message text");
+});
+
+test("cached turn aggregates and process topology match legacy helpers", () => {
+ const fixtures = [
+ [],
+ [message("blank", " \n ")],
+ [message("partial", " Part ", { status: "aborted" })],
+ [message("a", " A ", { modelId: "model-a", usage: { inputTokens: 4, outputTokens: 3, totalTokens: 7, cacheReadTokens: 0 }, responseDurationMs: 1200 }),
+ message("b", " B ", { responseOutputTokens: 8, responseDurationMs: 400 }),
+ message("c", " C ", { usage: { inputTokens: 8, outputTokens: 0, totalTokens: 8, cacheWriteTokens: 2, reasoningTokens: 6 }, responseOutputTokens: 9, responseDurationMs: -1 })],
+ [message("a", " text ", { responseDurationMs: Infinity, responseOutputTokens: NaN }),
+ message("error", "", { error: { code: "INTERNAL", message: "failed" } })],
+ ];
+ for (const messages of fixtures) {
+ const turn = entry(messages);
+ const summary = getAssistantTurnSummary(turn);
+ assert.equal(getAssistantTurnSummary(turn), summary);
+ assert.equal(getAssistantTurnSummary({ ...turn }), summary);
+ assert.deepEqual(summary.messages, assistantTurnMessages(turn));
+ assert.deepEqual(summary.tools, assistantTurnTools(turn));
+ assert.deepEqual(summary.usage, assistantTurnUsage(turn));
+ assert.equal(summary.responseDurationMs, assistantTurnResponseDuration(turn));
+ assert.equal(summary.responseOutputTokens, assistantTurnResponseOutputTokens(turn));
+ assert.equal(summary.responseOutputEstimated, assistantTurnResponseOutputIsEstimated(turn));
+ assert.equal(summary.actionMessage, [...messages].reverse().find((m) => m.content.trim()));
+ assert.equal(summary.metaMessage, [...messages].reverse().find((m) => m.modelId || m.usage || m.responseDurationMs || m.responseOutputTokens));
+ assert.equal(summary.latestUsageMessage, [...messages].reverse().find((m) => m.usage));
+ assert.equal(summary.hasError, messages.some((m) => Boolean(m.error)));
+ assert.equal(summary.streaming, messages.some((m) => m.status === "streaming"));
+ assert.deepEqual({ process: summary.process, responses: summary.responses }, projectTurnProcess(turn));
+ assert.equal(getAssistantTurnContent(turn), assistantTurnContent(turn));
+ }
+});
+
+test("same-id replacements and deferred older snapshots never share mutable facts", () => {
+ const first = entry([message("same", "before", { status: "streaming" })]);
+ const second = entry([message("same", "after", { status: "complete", responseOutputTokens: 10 })]);
+ assert.equal(messageContentFacts(first.parts[0].message).trimmedContent, "before");
+ assert.equal(getAssistantTurnContent(first), "before");
+ assert.equal(getAssistantTurnContent(second), "after");
+ assert.equal(getAssistantTurnSummary(second).streaming, false);
+ assert.equal(getAssistantTurnSummary(first).streaming, true);
+ assert.equal(getAssistantTurnContent(first), "before");
+});
+
+test("giant group summary/visibility updates never reread historical tool payloads or thinking content", () => {
+ let reads = 0;
+ const old = Array.from({ length: 1024 }, (_, index) => index % 2 ? {
+ kind: "thinking", message: { ...message(`think-${index}`, "", { thinking: "reasoning", status: "streaming" }),
+ get content() { reads += 1; return ""; } },
+ } : {
+ kind: "tool", message: { ...message(`tool-${index}`, "", { role: "tool", toolName: "Bash", toolStatus: "success" }),
+ get content() { reads += 1; return ""; },
+ get toolResult() { reads += 1; return { details: { exitCode: 0 } }; } },
+ });
+ const first = [...old, { kind: "thinking", message: message("tail", "", { thinking: "a", status: "streaming" }) }];
+ cachedActivitySummary(first);
+ cachedVisibleActivityItems(first, true, true);
+ cachedVisibleProcessSteps([{ kind: "activity", items: first }], true, true);
+ reads = 0;
+ const second = [...old, { kind: "thinking", message: message("tail", "", { thinking: "ab", status: "streaming" }) }];
+ assert.equal(cachedActivitySummary(second).tools, 512);
+ assert.equal(cachedVisibleActivityItems(second, true, true).length, 1025);
+ assert.equal(cachedVisibleProcessSteps([{ kind: "activity", items: second }], true, true), 1025);
+ assert.equal(reads, 0);
+});
+
+test("activity summary and compact visibility preserve error, search and thinking semantics", () => {
+ const items = [
+ { kind: "tool", message: message("bash", "", { toolName: "Bash", toolResult: { details: { exitCode: 1 } } }) },
+ { kind: "tool", message: message("denied", "", { toolName: "Read", toolStatus: "denied" }) },
+ { kind: "thinking", message: message("think", "", { thinking: "reason", status: "streaming" }) },
+ { kind: "thinking", message: message("answer", "answer", { thinking: "reason", status: "streaming" }) },
+ { kind: "hostedSearch", message: message("search", ""), round: { id: "r", status: "failed" } },
+ ];
+ for (const subset of [[], items, items.slice(0, 1), items.slice(2, 4), items.slice(4)]) {
+ assert.deepEqual(cachedActivitySummary(subset), activitySummary(subset));
+ for (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 ? "compact" : "detailed", active));
+ }
+ }
+});
+
+test("text and delegate-child changes keep tool inputs stable; cross-part TaskWait status/timing updates still propagate", () => {
+ const task = { kind: "tool", message: message("task", "", { role: "tool", toolName: "Task", toolResult: { details: { delegationId: "d", status: "running", startedAt: 1000 } } }) };
+ const wait = { kind: "tool", message: message("wait", "", { role: "tool", toolName: "TaskWait", toolResult: { details: { delegations: [{ delegationId: "d", status: "running", startedAt: 1000 }] } } }) };
+ const first = { kind: "assistant-turn", id: "turn", parts: [
+ { kind: "activity", items: [task] }, { kind: "message", message: message("progress", "wait") },
+ { kind: "activity", items: [wait] },
+ ] };
+ const tools = getAssistantTurnSummary(first).tools;
+ const textChanged = { ...first, parts: [first.parts[0], { kind: "message", message: message("progress", "waiting") }, first.parts[2]] };
+ assert.equal(reuseReferences(tools, getAssistantTurnSummary(textChanged).tools), tools);
+ const childChanged = { ...first, parts: [{ kind: "activity", items: [{ ...task, delegate: { items: [{ kind: "answer", message: message("child", "answer") }] } }] }, ...first.parts.slice(1)] };
+ assert.equal(reuseReferences(tools, getAssistantTurnSummary(childChanged).tools), tools);
+ const settledWait = { ...wait, message: { ...wait.message, toolResult: { details: { delegations: [{ delegationId: "d", status: "failed", startedAt: 1000, completedAt: 6000 }] } } } };
+ const settled = { ...first, parts: [...first.parts.slice(0, -1), { kind: "activity", items: [settledWait] }] };
+ assert.notEqual(reuseReferences(tools, getAssistantTurnSummary(settled).tools), tools);
+ const inputs = getAssistantTurnSummary(settled).toolItems;
+ const statuses = collectDelegationStatuses(inputs, { turnLive: true });
+ const timings = collectDelegationTimings(inputs);
+ assert.equal(statuses.get("d"), "failed");
+ assert.deepEqual(delegationTimingBounds([task], timings), { startedAt: 1000, completedAt: 6000 });
+ assert.deepEqual(cachedActivitySummary([task], statuses), activitySummary([task], statuses));
+ assert.equal(cachedActivitySummary([task], statuses).issues, 1);
+ assert.equal(collectDelegationStatuses(getAssistantTurnSummary(first).toolItems, { turnLive: false }).get("d"), "aborted");
+});
+
+test("cached activity timing exactly preserves invalid timestamps and fallback durations", () => {
+ const sets = [[], [message("a", "")], [message("bad", "", { createdAt: "invalid", toolDurationMs: 300 })],
+ [message("epoch", "", { createdAt: "1970-01-01T00:00:00Z", toolDurationMs: -300 }), message("a", "", { toolCompletedAt: "2026-09-17T00:00:02Z" })]];
+ for (const messages of sets) {
+ const inputs = activityTimingInputs(messages.map((message) => ({ kind: "tool", message })));
+ for (const startedAt of [1000, Date.parse("2026-09-17T00:00:00Z")]) {
+ const legacy = Math.max(startedAt, ...messages.map((m) => Date.parse(m.toolCompletedAt || "") || (Date.parse(m.createdAt) || startedAt) + (m.toolDurationMs || 0)));
+ assert.equal(Math.max(startedAt, inputs.recordedEnd, startedAt + inputs.missingStartDuration), legacy);
+ }
+ }
+});
+
+
+test("memo boundaries check scalar changes before identity and skip stable child scans", async () => {
+ const { createServer } = await import("vite");
+ const { fileURLToPath } = await import("node:url");
+ const server = await createServer({
+ root: fileURLToPath(new URL("..", import.meta.url)), configFile: false,
+ server: { middlewareMode: true, hmr: false, ws: false },
+ esbuild: { jsx: "automatic" }, appType: "custom",
+ optimizeDeps: { noDiscovery: true, include: [] },
+ });
+ try {
+ const { AssistantTurn, TranscriptHistory, TranscriptTail } = await server.ssrLoadModule("/src/features/chat/transcript/AssistantTurn.tsx");
+ const { ActivityGroup, activityItemsEqual } = await server.ssrLoadModule("/src/features/chat/transcript/ActivityGroup.tsx");
+ const noScan = (items) => new Proxy(items, { get(target, key, receiver) {
+ if (key === "every" || key === "some") throw new Error("stable input was scanned");
+ return Reflect.get(target, key, receiver);
+ } });
+ const stableInputs = noScan([message("stable", "text")]);
+ assert.equal(reuseReferences(stableInputs, stableInputs), stableInputs);
+ const item = { kind: "tool", message: message("tool", "", { toolName: "Read" }) };
+ const part = { kind: "activity", items: noScan([item]) };
+ const turn = { kind: "assistant-turn", id: "turn", anchorId: "anchor", parts: noScan([part]) };
+ const props = { entry: turn, isActive: true };
+ assert.equal(AssistantTurn.compare(props, { ...props }), true);
+ assert.equal(AssistantTurn.compare(props, { ...props, isActive: false }), false);
+ assert.equal(AssistantTurn.compare(props, { ...props, runtimeActivity: { phase: "starting", since: 0 } }), false);
+ assert.equal(AssistantTurn.compare(props, { ...props, entry: { ...turn, anchorId: "new" } }), false);
+ assert.equal(AssistantTurn.compare(props, { ...props, entry: { ...turn } }), true);
+ assert.equal(AssistantTurn.compare({ ...props, entry: { ...turn, parts: [part] } }, { ...props, entry: { ...turn, parts: [part] } }), true);
+ const history = { entries: noScan([turn]), isRunning: true };
+ assert.equal(TranscriptHistory.compare(history, { ...history }), true);
+ assert.equal(TranscriptHistory.compare(history, { ...history, isRunning: false }), false);
+ const tail = { ...props, isRunning: true };
+ assert.equal(TranscriptTail.compare(tail, { ...tail }), true);
+ assert.equal(TranscriptTail.compare(tail, { ...tail, isRunning: false }), false);
+ const group = { items: part.items, isActive: true, isLast: true };
+ assert.equal(ActivityGroup.compare(group, { ...group }), true);
+ assert.equal(ActivityGroup.compare(group, { ...group, isActive: false }), false);
+ assert.equal(ActivityGroup.compare(group, { ...group, isLast: false }), false);
+ assert.equal(ActivityGroup.compare(group, { ...group, endedAt: "now" }), false);
+ const opaque = new Proxy(item, { get() { throw new Error("stable item was inspected"); } });
+ assert.equal(activityItemsEqual(opaque, opaque), true);
+ const taskItems = [{ ...item, message: { ...item.message, toolName: "Task" } }];
+ const taskGroup = { ...group, items: taskItems, turnDelegationStatuses: new Map([["d", "running"]]) };
+ assert.equal(ActivityGroup.compare(taskGroup, { ...taskGroup, turnDelegationStatuses: new Map([["d", "completed"]]) }), false);
+ assert.equal(ActivityGroup.compare(taskGroup, { ...taskGroup, turnDelegationTimings: new Map([["d", { completedAt: 6000 }]]) }), false);
+ } finally {
+ await server.close();
+ }
+});
+
+const keyOf = (item) => item.id;
+test("giant turn/group blocks reconstruct at most one bounded tail block", () => {
+ const items = Array.from({ length: 10784 }, (_, index) => ({ id: `row-${index}` }));
+ const first = reconcileRenderBlocks(undefined, items, keyOf);
+ const replacement = { id: items.at(-1).id };
+ const second = reconcileRenderBlocks(first, [...items.slice(0, -1), replacement], keyOf);
+ assert.equal(second.length, first.length);
+ assert.deepEqual(second.map((b) => b.key), first.map((b) => b.key));
+ const changed = second.filter((block, index) => block !== first[index]);
+ assert.equal(changed.length, 1);
+ assert.ok(changed[0].items.length <= TRANSCRIPT_RENDER_BLOCK_SIZE);
+ assert.equal(reconcileRenderBlocks(second, [...items.slice(0, -1), replacement], keyOf), second);
+});
+
+test("ordering corrections never reuse a render-block key for disjoint segments", () => {
+ const items = Array.from({ length: 128 }, (_, index) => ({ id: `r${index}` }));
+ const first = reconcileRenderBlocks(undefined, items, keyOf);
+ const reordered = [items[1], items[64], items[0], ...items.slice(2, 64), ...items.slice(65)];
+ const second = reconcileRenderBlocks(first, reordered, keyOf);
+ assert.deepEqual(second.flatMap((block) => block.items), reordered);
+ assert.equal(new Set(second.map((block) => block.key)).size, second.length);
+ assert.ok(second.every((block) => block.items.length <= TRANSCRIPT_RENDER_BLOCK_SIZE));
+ assert.equal(reconcileRenderBlocks(second, reordered.slice(), keyOf), second);
+});
+
+test("prepend, same-id replacements, delete and append preserve existing block identities and ordering", () => {
+ const items = Array.from({ length: 192 }, (_, index) => ({ id: `row-${index}` }));
+ const first = reconcileRenderBlocks(undefined, items, keyOf);
+ const prefix = [{ id: "prefix-a" }, { id: "prefix-b" }];
+ const prepended = reconcileRenderBlocks(first, [...prefix, ...items], keyOf);
+ assert.deepEqual(prepended.slice(1), first);
+ first.forEach((block, index) => assert.equal(prepended[index + 1], block));
+ const append = { id: "new-tail" };
+ const appended = reconcileRenderBlocks(prepended, [...prefix, ...items, append], keyOf);
+ prepended.forEach((block, index) => assert.equal(appended[index], block));
+ const changed = [items[0], { id: items[1].id }, ...items.slice(2)];
+ const replaced = reconcileRenderBlocks(first, changed, keyOf);
+ assert.equal(replaced[0].key, first[0].key);
+ assert.equal(replaced[1], first[1]);
+ const removed = reconcileRenderBlocks(first, items.slice(1), keyOf);
+ assert.equal(removed[0].key, first[0].key);
+ assert.equal(removed[1], first[1]);
+ for (const [blocks, expected] of [[prepended, [...prefix, ...items]], [appended, [...prefix, ...items, append]], [replaced, changed], [removed, items.slice(1)]]) {
+ assert.deepEqual(blocks.flatMap((block) => block.items), expected);
+ assert.equal(new Set(blocks.map((block) => block.key)).size, blocks.length);
+ assert.ok(blocks.every((block) => block.items.length <= TRANSCRIPT_RENDER_BLOCK_SIZE));
+ }
+});
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 380d3fe69..b4a2c57c4 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -1639,10 +1639,20 @@ storage but compose into one assistant turn until the next user message.
to the first contentful fragment. Tool-only rows do not create markers or
split an AI response, and a one-page transcript never shows the rail.
- Marker previews are capped at 280 source characters and are display-only
-- Derived visible rows, minimap rows, and activity grouping are memoized by the
- `messages` snapshot. Completed message rows, composed assistant turns, and
- activity groups keep stable render boundaries while only the current stream
- fragment changes.
+- Derived visible rows, minimap rows, and activity grouping share the immutable
+ `messages` projection with the Composer context inspector. After warm-up, an
+ ordinary same-shape delta updates indexed changed rows without rereading
+ unchanged message bodies or rebuilding completed groups. This applies to the
+ normal 100-row page and deliberately loaded full histories, and to foreground
+ and background session caches. Shallow array copies
+ remain permitted; cold loads and structural changes may rebuild the projection.
+- Completed rows and unchanged parts within a large active turn/activity group
+ retain their render boundaries. Deferred presentation consumes one immutable
+ projection snapshot. Older-row and child updates, terminal re-keying, Copy,
+ disclosure state, minimap previews, session switching, and reader-owned scroll
+ positions must remain fresh; performance reuse must not hide these changes.
+ Event-to-DOM latency, long tasks, and heap samples are diagnostics, not a
+ hardware-independent timing guarantee.
---
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 0d4f53a89..f62ab3c99 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -5753,6 +5753,38 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
below measures real geometry against; full provider streaming and shell
responsiveness remain Draft.
+#### E2E-CHAT-long-history-stream-keeps-responsive
+
+- **Preconditions**: Isolated Electron fixture with production React,
+ `ChatTranscript`, Composer, event slice, store subscription, and session cache;
+ synthetic Host reads, clipboard, and DOM input, no credentials or running Desktop.
+- **Steps**: Keep three sessions running with 100, 1,000, and 10,784 canonical
+ loaded rows. Stream warmed deltas into the foreground and both background
+ caches, then switch through real session selection with 100-row revalidation.
+ Correct an older row; inspect its minimap preview. Toggle a disclosure, scroll
+ away from latest, complete/re-key the tail, copy its turn, and switch back.
+ Separately stream a 256-fragment single turn and a 256-tool activity group;
+ update a nested child through the real read-only subagent dock, stream the
+ giant group's final thinking item, and deliver actual `tool_update` partials
+ to a running tool in the middle of that group.
+- **Expected**: Ordinary warmed deltas read zero unchanged bodies; unchanged
+ groups do not rerender. Mounted history stays bounded despite full canonical
+ input. Background updates never replace the foreground, and revalidation never
+ discards its cached live tail. Content, minimap previews, disclosure choice,
+ reader scroll ownership, completed Copy text and terminal identity remain
+ correct. Changed tools/children/thinking still reach their real components.
+- **Specs linked**: `04-ux/08-component-spec.md` §7.6.
+- **Acceptance**: C (chat stream), Quality. **Milestone**: M5 maintenance.
+- **Status**: Automated fixture in `scripts/e2e/transcript-long-history.tsx`,
+ registered in `pnpm test:e2e:transcript`; requires built renderer CSS and the
+ existing Electron environment. Assertions are work counts and DOM state, not
+ timing thresholds. Event-to-settled-DOM latency, supported long-task entries
+ and optional heap samples are diagnostic only. Elapsed-label wall time is
+ controlled; the hidden-window fixture explicitly dispatches DOM `focusin`.
+ Existing deterministic 120 Hz cadence coverage remains unchanged. This is renderer/store integration, not
+ provider/IPC throughput, real-session profiling, or complete shell interaction
+ acceptance; those broader E2E-083 facets remain Draft.
+
#### E2E-CHAT-running-status-survives-output-pauses
- **Preconditions**: Production `ChatTranscript`, real store and React DOM in
@@ -8849,7 +8881,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| A — App startup | E2E-001, E2E-002, E2E-003, E2E-004, E2E-067, E2E-076, E2E-079, E2E-092, E2E-097, E2E-143, E2E-150, E2E-168, E2E-204 |
| A / C / F / Quality — Tray session navigation | E2E-TRAY-bounded-session-navigation |
| B — Model config | E2E-005, E2E-006, E2E-007, E2E-038, E2E-050, E2E-052, E2E-055, E2E-066, E2E-080, E2E-082, E2E-102c, E2E-102d, E2E-102e, E2E-151, E2E-154, E2E-163, E2E-166, E2E-172, E2E-174, E2E-197, E2E-005G, E2E-005J, E2E-199, E2E-201, E2E-202, E2E-203, E2E-205, E2E-206, E2E-209 |
-| C — Conversation & stream | E2E-CHAT-running-status-survives-output-pauses, E2E-008, E2E-008d, E2E-008e, E2E-008a, E2E-009, E2E-010, E2E-011, E2E-011a, E2E-011b, E2E-011d, E2E-011e, E2E-011g, E2E-031, E2E-040, E2E-047, E2E-048, E2E-048A, E2E-049, E2E-052, E2E-053, E2E-054, E2E-055, E2E-059, E2E-059a, E2E-060c, E2E-060d, E2E-061, E2E-061a, E2E-062, E2E-064, E2E-065, E2E-068, E2E-071, E2E-073, E2E-074, E2E-075, E2E-081, E2E-083, E2E-084, E2E-086, E2E-087, E2E-088, E2E-088b, E2E-089, E2E-090, E2E-COMPOSER-narrow-controls, E2E-094, E2E-095, E2E-096, E2E-097, E2E-098, E2E-099, E2E-102, E2E-102a, E2E-102b, E2E-102c, E2E-102d, E2E-102g, E2E-106, E2E-109, E2E-111, E2E-114, E2E-116, E2E-117, E2E-118, E2E-119, E2E-120, E2E-121, E2E-218, E2E-259, E2E-219, E2E-AGENTS-001, E2E-142, E2E-144, E2E-145, E2E-146, E2E-146a, E2E-147, E2E-151, E2E-154, E2E-155, E2E-158, E2E-159, E2E-161, E2E-162, E2E-166, E2E-172, E2E-173, E2E-174, E2E-177, E2E-178, E2E-179, E2E-180, E2E-182, E2E-183, E2E-187, E2E-198, E2E-199, E2E-202, E2E-203, E2E-207, E2E-208, E2E-CHAT-content-width-handles, E2E-250, E2E-102i, E2E-PLUGIN-session-orchestrator-real-workers, E2E-SUBAGENT-settlement-updates-before-parent-poll, E2E-SUBAGENT-resume-a-settled-delegation |
+| C — Conversation & stream | E2E-CHAT-long-history-stream-keeps-responsive, E2E-CHAT-running-status-survives-output-pauses, E2E-008, E2E-008d, E2E-008e, E2E-008a, E2E-009, E2E-010, E2E-011, E2E-011a, E2E-011b, E2E-011d, E2E-011e, E2E-011g, E2E-031, E2E-040, E2E-047, E2E-048, E2E-048A, E2E-049, E2E-052, E2E-053, E2E-054, E2E-055, E2E-059, E2E-059a, E2E-060c, E2E-060d, E2E-061, E2E-061a, E2E-062, E2E-064, E2E-065, E2E-068, E2E-071, E2E-073, E2E-074, E2E-075, E2E-081, E2E-083, E2E-084, E2E-086, E2E-087, E2E-088, E2E-088b, E2E-089, E2E-090, E2E-COMPOSER-narrow-controls, E2E-094, E2E-095, E2E-096, E2E-097, E2E-098, E2E-099, E2E-102, E2E-102a, E2E-102b, E2E-102c, E2E-102d, E2E-102g, E2E-106, E2E-109, E2E-111, E2E-114, E2E-116, E2E-117, E2E-118, E2E-119, E2E-120, E2E-121, E2E-218, E2E-259, E2E-219, E2E-AGENTS-001, E2E-142, E2E-144, E2E-145, E2E-146, E2E-146a, E2E-147, E2E-151, E2E-154, E2E-155, E2E-158, E2E-159, E2E-161, E2E-162, E2E-166, E2E-172, E2E-173, E2E-174, E2E-177, E2E-178, E2E-179, E2E-180, E2E-182, E2E-183, E2E-187, E2E-198, E2E-199, E2E-202, E2E-203, E2E-207, E2E-208, E2E-CHAT-content-width-handles, E2E-250, E2E-102i, E2E-PLUGIN-session-orchestrator-real-workers, E2E-SUBAGENT-settlement-updates-before-parent-poll, E2E-SUBAGENT-resume-a-settled-delegation |
| C — Conversation & stream (composer drafts) | E2E-011c, E2E-011c-1 |
| D — Workspace | E2E-012, E2E-013, E2E-022B, E2E-024I, E2E-047, E2E-049, E2E-057, E2E-058, E2E-060, E2E-068, E2E-075, E2E-078, E2E-153, E2E-158, E2E-182, E2E-187, E2E-252 |
| D — Workspace (project ordering) | E2E-253 |
@@ -8859,7 +8891,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| G — Plugins | E2E-022, E2E-022A, E2E-022B, E2E-022C, E2E-023, E2E-024, E2E-024B, E2E-024C, E2E-024D, E2E-024AA, E2E-024E, E2E-024W, E2E-024F, E2E-024G, E2E-024H, E2E-024I, E2E-024J, E2E-024K, E2E-024L, E2E-024M, E2E-024N, E2E-024O, E2E-024P, E2E-025, E2E-026, E2E-105, E2E-117, E2E-120, E2E-122, E2E-123, E2E-024Q, E2E-148, E2E-152, E2E-153, E2E-PLUGIN-imported-pi-package-skills, E2E-PLUGIN-imported-pi-package-wrapper, E2E-PLUGIN-import-extension-installs-dependencies, E2E-PLUGIN-import-extension-reports-missing-dependency, E2E-PLUGIN-global-shortcut-owns-only-its-own-command, E2E-PLUGIN-permission-gate-for-real-time-capabilities, E2E-PLUGIN-background-audio-and-realtime-connection, E2E-PLUGIN-fs-root-follows-the-calling-session |
| H — Diagnostics | E2E-027, E2E-031, E2E-034, E2E-042, E2E-096, E2E-098, E2E-104, E2E-107, E2E-108, E2E-109, E2E-110, E2E-113, E2E-115, E2E-116, E2E-118, E2E-121, E2E-146, E2E-146a, E2E-155, E2E-159, E2E-176, E2E-194, E2E-195 |
| Security | E2E-028, E2E-029, E2E-030, E2E-024J, E2E-024K, E2E-024M, E2E-049, E2E-068, E2E-086, E2E-102c, E2E-102d, E2E-102e, E2E-105, E2E-106, E2E-107, E2E-108, E2E-109, E2E-110, E2E-112, E2E-113, E2E-115, E2E-116, E2E-117, E2E-119, E2E-121, E2E-122, E2E-123, E2E-142, E2E-148, E2E-151, E2E-153, E2E-158, E2E-187, E2E-196c, E2E-196b, E2E-196, E2E-PLUGIN-fs-root-follows-the-calling-session |
-| Quality | E2E-CHAT-running-status-survives-output-pauses, E2E-032, E2E-033, E2E-039, E2E-043, E2E-044, E2E-045, E2E-046, E2E-047, E2E-048, E2E-048A, E2E-049, E2E-050, E2E-053, E2E-055, E2E-056, E2E-057, E2E-058, E2E-059, E2E-060, E2E-061, E2E-062, E2E-063, E2E-064, E2E-065, E2E-066, E2E-067, E2E-068, E2E-069, E2E-070, E2E-071, E2E-072, E2E-073, E2E-074, E2E-075, E2E-076, E2E-077, E2E-078, E2E-079, E2E-080, E2E-081, E2E-082, E2E-083, E2E-084, E2E-085, E2E-086, E2E-092, E2E-093, E2E-094, E2E-095, E2E-096, E2E-097, E2E-098, E2E-099, E2E-100, E2E-101, E2E-102, E2E-102a, E2E-102b, E2E-102c, E2E-102d, E2E-102e, E2E-103, E2E-AGENTS-001, E2E-021a, E2E-024N, E2E-059a, E2E-060b, E2E-060c, E2E-061a, E2E-073a, E2E-111, E2E-114, E2E-117, E2E-118, E2E-119, E2E-120, E2E-122, E2E-123, E2E-142, E2E-143, E2E-144, E2E-145, E2E-146, E2E-147, E2E-148, E2E-150, E2E-151, E2E-153, E2E-155, E2E-158, E2E-159, E2E-160, E2E-161, E2E-162, E2E-163, E2E-168, E2E-172, E2E-173, E2E-174, E2E-011g, E2E-176, E2E-177, E2E-178, E2E-179, E2E-180, E2E-181, E2E-182, E2E-183, E2E-186, E2E-187, E2E-194, E2E-195, E2E-196a, E2E-196b, E2E-196c, E2E-198, E2E-199, E2E-200, E2E-196, E2E-201, E2E-204, E2E-202, E2E-203, E2E-205, E2E-206, E2E-207, E2E-208, E2E-209, E2E-210, E2E-UPDATE-preference-and-once-only-reminder, E2E-218, E2E-259, E2E-219, E2E-250, E2E-252, E2E-102i, E2E-SUBAGENT-settlement-updates-before-parent-poll, E2E-PLUGIN-imported-pi-package-skills, E2E-PLUGIN-fs-root-follows-the-calling-session, E2E-SUBAGENT-resume-a-settled-delegation |
+| Quality | E2E-CHAT-long-history-stream-keeps-responsive, E2E-CHAT-running-status-survives-output-pauses, E2E-032, E2E-033, E2E-039, E2E-043, E2E-044, E2E-045, E2E-046, E2E-047, E2E-048, E2E-048A, E2E-049, E2E-050, E2E-053, E2E-055, E2E-056, E2E-057, E2E-058, E2E-059, E2E-060, E2E-061, E2E-062, E2E-063, E2E-064, E2E-065, E2E-066, E2E-067, E2E-068, E2E-069, E2E-070, E2E-071, E2E-072, E2E-073, E2E-074, E2E-075, E2E-076, E2E-077, E2E-078, E2E-079, E2E-080, E2E-081, E2E-082, E2E-083, E2E-084, E2E-085, E2E-086, E2E-092, E2E-093, E2E-094, E2E-095, E2E-096, E2E-097, E2E-098, E2E-099, E2E-100, E2E-101, E2E-102, E2E-102a, E2E-102b, E2E-102c, E2E-102d, E2E-102e, E2E-103, E2E-AGENTS-001, E2E-021a, E2E-024N, E2E-059a, E2E-060b, E2E-060c, E2E-061a, E2E-073a, E2E-111, E2E-114, E2E-117, E2E-118, E2E-119, E2E-120, E2E-122, E2E-123, E2E-142, E2E-143, E2E-144, E2E-145, E2E-146, E2E-147, E2E-148, E2E-150, E2E-151, E2E-153, E2E-155, E2E-158, E2E-159, E2E-160, E2E-161, E2E-162, E2E-163, E2E-168, E2E-172, E2E-173, E2E-174, E2E-011g, E2E-176, E2E-177, E2E-178, E2E-179, E2E-180, E2E-181, E2E-182, E2E-183, E2E-186, E2E-187, E2E-194, E2E-195, E2E-196a, E2E-196b, E2E-196c, E2E-198, E2E-199, E2E-200, E2E-196, E2E-201, E2E-204, E2E-202, E2E-203, E2E-205, E2E-206, E2E-207, E2E-208, E2E-209, E2E-210, E2E-UPDATE-preference-and-once-only-reminder, E2E-218, E2E-259, E2E-219, E2E-250, E2E-252, E2E-102i, E2E-SUBAGENT-settlement-updates-before-parent-poll, E2E-PLUGIN-imported-pi-package-skills, E2E-PLUGIN-fs-root-follows-the-calling-session, E2E-SUBAGENT-resume-a-settled-delegation |
| Quality (project ordering) | E2E-253 |
| C — Conversation & stream (IME slash alias) | E2E-255 |
| E — Tools & permissions (Skill residency) | E2E-254 |
@@ -8907,7 +8939,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| M2 | E2E-004, E2E-005, E2E-006, E2E-007, E2E-008, E2E-008d, E2E-008e, E2E-009, E2E-010, E2E-011, E2E-011a, E2E-011b, E2E-011d, E2E-011e, E2E-011g, E2E-020, E2E-021, E2E-021a, E2E-027, E2E-031, E2E-036, E2E-037, E2E-042, E2E-087, E2E-088, E2E-088b, E2E-089, E2E-090, E2E-COMPOSER-narrow-controls, E2E-144, E2E-005J, E2E-201, E2E-202, E2E-207, E2E-206 |
| M3 | E2E-012, E2E-013, E2E-014, E2E-015, E2E-016, E2E-017, E2E-018, E2E-019, E2E-040 |
| M4 | E2E-022, E2E-023, E2E-024, E2E-025, E2E-026, E2E-030, E2E-038 |
-| M5 | E2E-CHAT-running-status-survives-output-pauses, E2E-008a, E2E-032, E2E-033, E2E-034, E2E-039, E2E-043, E2E-044, E2E-045, E2E-046, E2E-047, E2E-048, E2E-048A, E2E-049, E2E-050, E2E-051, E2E-052, E2E-053, E2E-054, E2E-055, E2E-056, E2E-057, E2E-058, E2E-059, E2E-060, E2E-061, E2E-062, E2E-063, E2E-064, E2E-065, E2E-066, E2E-067, E2E-068, E2E-069, E2E-070, E2E-071, E2E-072, E2E-073, E2E-074, E2E-075, E2E-076, E2E-077, E2E-078, E2E-079, E2E-080, E2E-081, E2E-082, E2E-083, E2E-084, E2E-085, E2E-086, E2E-092, E2E-093, E2E-096, E2E-097, E2E-098, E2E-099, E2E-100, E2E-101, E2E-102, E2E-102a, E2E-102b, E2E-102c, E2E-102d, E2E-102e, E2E-AGENTS-001, E2E-059a, E2E-060b, E2E-060c, E2E-061a, E2E-073a, E2E-094, E2E-095, E2E-143, E2E-145, E2E-146, E2E-146a, E2E-147, E2E-177, E2E-178, E2E-180, E2E-181, E2E-182, E2E-183, E2E-186, E2E-187, E2E-194, E2E-195, E2E-204, E2E-208, E2E-CHAT-content-width-handles, E2E-250, E2E-252, E2E-102i |
+| M5 | E2E-CHAT-long-history-stream-keeps-responsive, E2E-CHAT-running-status-survives-output-pauses, E2E-008a, E2E-032, E2E-033, E2E-034, E2E-039, E2E-043, E2E-044, E2E-045, E2E-046, E2E-047, E2E-048, E2E-048A, E2E-049, E2E-050, E2E-051, E2E-052, E2E-053, E2E-054, E2E-055, E2E-056, E2E-057, E2E-058, E2E-059, E2E-060, E2E-061, E2E-062, E2E-063, E2E-064, E2E-065, E2E-066, E2E-067, E2E-068, E2E-069, E2E-070, E2E-071, E2E-072, E2E-073, E2E-074, E2E-075, E2E-076, E2E-077, E2E-078, E2E-079, E2E-080, E2E-081, E2E-082, E2E-083, E2E-084, E2E-085, E2E-086, E2E-092, E2E-093, E2E-096, E2E-097, E2E-098, E2E-099, E2E-100, E2E-101, E2E-102, E2E-102a, E2E-102b, E2E-102c, E2E-102d, E2E-102e, E2E-AGENTS-001, E2E-059a, E2E-060b, E2E-060c, E2E-061a, E2E-073a, E2E-094, E2E-095, E2E-143, E2E-145, E2E-146, E2E-146a, E2E-147, E2E-177, E2E-178, E2E-180, E2E-181, E2E-182, E2E-183, E2E-186, E2E-187, E2E-194, E2E-195, E2E-204, E2E-208, E2E-CHAT-content-width-handles, E2E-250, E2E-252, E2E-102i |
| M5 (project ordering) | E2E-253 |
| M2 (IME slash alias) | E2E-255 |
| M5 (Skill residency) | E2E-254 |
diff --git a/scripts/e2e-transcript-render.mjs b/scripts/e2e-transcript-render.mjs
index b4c2c156a..7f37b8255 100644
--- a/scripts/e2e-transcript-render.mjs
+++ b/scripts/e2e-transcript-render.mjs
@@ -24,7 +24,7 @@ try {
platform: "browser",
format: "iife",
jsx: "automatic",
- define: { "process.env.NODE_ENV": '"production"' },
+ define: { "process.env.NODE_ENV": '"production"', "import.meta.env.DEV": "false" },
// Styles are outside the render-count contract; component and hook code is real.
loader: { ".css": "empty" },
alias: {
@@ -35,6 +35,19 @@ try {
},
nodePaths: [join(root, "apps/desktop/node_modules")],
plugins: [
+ {
+ name: "local-url-assets",
+ setup(build) {
+ // Composer imports the dormant voice worklet via Vite's ?url form.
+ // Preserve a real local asset URL; this fixture never activates voice.
+ build.onResolve({ filter: /\?url$/ }, ({ path, resolveDir }) => ({
+ path: join(resolveDir, path.slice(0, -4)), namespace: "local-url-asset",
+ }));
+ build.onLoad({ filter: /.*/, namespace: "local-url-asset" }, async ({ path }) => ({
+ contents: await readFile(path), loader: "file",
+ }));
+ },
+ },
{
name: "count-activity-group-renders",
setup(build) {
@@ -133,11 +146,12 @@ app.whenReady().then(async () => {
window.webContents.on("console-message", (event) => console.error(event.message));
try {
await window.loadFile(path.join(__dirname, "index.html"));
- const result = await window.webContents.executeJavaScript("globalThis.transcriptRenderProbe().then((render) => globalThis.transcriptRuntimeSlotProbe().then((slot) => globalThis.smoothTextThrottleProbe().then((smoothText) => Object.assign({}, render, { runtimeSlot: slot, smoothText, ok: render.ok && slot.ok && smoothText.ok }))))");
+ await window.webContents.executeJavaScript("window.addEventListener('error', event => console.error(event.error?.stack ?? event.message)); window.addEventListener('unhandledrejection', event => console.error(event.reason?.stack ?? String(event.reason)));");
+ const result = await window.webContents.executeJavaScript("(async () => { const render = await globalThis.transcriptRenderProbe(); const slot = await globalThis.transcriptRuntimeSlotProbe(); const smoothText = await globalThis.smoothTextThrottleProbe(); const longHistory = await globalThis.transcriptLongHistoryProbe(); return { ...render, runtimeSlot: slot, smoothText, longHistory, ok: render.ok && slot.ok && smoothText.ok && longHistory.ok }; })()");
console.log("TRANSCRIPT_RENDER_PROBE " + JSON.stringify(result));
app.quit();
} catch (error) {
- console.error("TRANSCRIPT_RENDER_PROBE " + JSON.stringify({ ok: false, error: String(error) }));
+ console.error("TRANSCRIPT_RENDER_PROBE " + JSON.stringify({ ok: false, error: error?.stack ?? String(error) }));
app.exit(1);
}
});
diff --git a/scripts/e2e/transcript-long-history.tsx b/scripts/e2e/transcript-long-history.tsx
new file mode 100644
index 000000000..9e9ba76f9
--- /dev/null
+++ b/scripts/e2e/transcript-long-history.tsx
@@ -0,0 +1,381 @@
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { en } from "@pi-desktop/i18n";
+import type { AgentEventEnvelope, SessionSummary, UiMessage } from "@pi-desktop/shared";
+import { Composer } from "../../apps/desktop/src/components/Composer";
+import { SubagentTranscriptTab } from "../../apps/desktop/src/components/workpanel/SubagentTranscriptTab";
+import { ChatTranscript } from "../../apps/desktop/src/features/chat/transcript/ChatTranscript";
+import { api } from "../../apps/desktop/src/lib/api";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+
+const createdAt = "2026-09-01T00:00:00.000Z";
+function assert(value: unknown, label: string): asserts value {
+ if (!value) throw new Error(`Long history: ${label}`);
+}
+const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+async function until(predicate: () => boolean, label: string, diagnostic?: () => unknown) {
+ for (let attempt = 0; attempt < 180; attempt++) {
+ if (predicate()) return;
+ await frame();
+ }
+ throw new Error(`Long history did not settle: ${label}${diagnostic ? ` ${JSON.stringify(diagnostic())}` : ""}`);
+}
+
+type FixtureSession = { summary: SessionSummary; messages: UiMessage[]; reads: { count: number }; tail: string };
+const row = (id: string, role: UiMessage["role"], content: string, extra: Partial<UiMessage> = {}): UiMessage => ({
+ id, role, content, createdAt, status: "complete", ...extra,
+});
+const tool = (id: string): UiMessage => row(id, "tool", "Synthetic result", {
+ toolName: "Bash", toolCallId: id, toolStatus: "success",
+ toolArgs: { command: `printf ${id}` }, toolResult: { details: { stdout: "Synthetic result", exitCode: 0 } },
+});
+function session(id: string, messages: UiMessage[]): FixtureSession {
+ const reads = { count: 0 };
+ // Count actual body access, including projection, Composer and mounted rows.
+ // Keep each row immutable: this is observation, not a mocked render/projector.
+ for (const message of messages.filter((message) => message.status !== "streaming")) {
+ const content = message.content;
+ Object.defineProperty(message, "content", { enumerable: true, get() { reads.count++; return content; } });
+ Object.freeze(message);
+ }
+ return { messages, reads, tail: messages.at(-1)!.id, summary: {
+ id, title: `Synthetic ${id}`, mode: "agent", permissionMode: "ask", thinkingLevel: "off",
+ providerId: "fixture", modelId: "fixture", createdAt, updatedAt: createdAt, messageCount: messages.length,
+ } };
+}
+function history(count: number): FixtureSession {
+ const id = `long-history-${count}`;
+ const messages = Array.from({ length: count - 4 }, (_, index) => row(
+ `${id}-${index}`, index % 2 ? "assistant" : "user", `${id} row ${index}. ${"Synthetic history. ".repeat(16)}`,
+ ));
+ messages.push(row(`${id}-user`, "user", `Inspect ${count} loaded rows`), tool(`${id}-tool`),
+ row(`${id}-progress`, "assistant", `${id} unchanged progress`),
+ row(`${id}-tail`, "assistant", `${id} live`, { status: "streaming", usage: { inputTokens: 20, outputTokens: 5, totalTokens: 25 } }));
+ return session(id, messages);
+}
+function giant(group: boolean): FixtureSession {
+ const id = group ? "long-activity-group" : "long-single-turn";
+ const messages = [row(`${id}-user`, "user", id)];
+ for (let index = 0; index < 256; index++) {
+ if (group || index % 8 === 0) messages.push(tool(`${id}-tool-${index}`));
+ if (!group) messages.push(row(`${id}-fragment-${index}`, "assistant", `Fragment ${index}. ${"Synthetic body. ".repeat(96)}`));
+ }
+ if (group) {
+ messages[129] = { ...messages[129], toolStatus: "running", status: "streaming" };
+ messages.push(row(`${id}-thinking`, "assistant", "", { thinking: "Inspecting the final tool", status: "streaming" }));
+ } else {
+ messages[1] = { ...messages[1], toolName: "Task", toolArgs: { agent: "explorer", task: "Synthetic child" },
+ toolResult: { details: { delegationId: `${id}-delegate`, status: "running", startedAt: Date.now() } } };
+ messages.splice(2, 0, row(`${id}-child`, "assistant", "Child initial", {
+ parentToolCallId: messages[1].toolCallId, agentName: "explorer", status: "streaming",
+ }));
+ }
+ messages.push(row(`${id}-tail`, "assistant", `${id} live`, {
+ status: "streaming", usage: { inputTokens: 20, outputTokens: 5, totalTokens: 25 },
+ }));
+ return session(id, messages);
+}
+
+function Surface({ sessions, errors }: { sessions: FixtureSession[]; errors: unknown[] }) {
+ const id = useAppStore((state) => state.activeSessionId);
+ const messages = useAppStore((state) => state.messages);
+ const running = useAppStore((state) => state.isRunning);
+ const tab = useAppStore((state) => state.activeWorkPanelTabId);
+ return <>
+ <nav aria-label="Synthetic session navigation">
+ {sessions.map(({ summary }) => <button key={summary.id} data-session={summary.id}
+ onClick={() => void useAppStore.getState().selectSession(summary.id).catch((error) => errors.push(error))}>
+ {summary.title}
+ </button>)}
+ </nav>
+ <div style={{ position: "relative", display: "flex", flex: 1, minHeight: 0 }}>
+ <ChatTranscript key={id} sessionId={id} messages={messages} isRunning={running} />
+ {id === "long-single-turn" && tab === `subagent:${id}-delegate` ?
+ <aside style={{ width: 300 }}><SubagentTranscriptTab delegationId={`${id}-delegate`} /></aside> : null}
+ </div>
+ <Composer />
+ </>;
+}
+
+/** Credential-free production React/store integration; no direct projection calls. */
+export async function transcriptLongHistoryProbe() {
+ // Store actions use the default i18next instance, not just React's provider.
+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });
+ const initial = useAppStore.getState();
+ const originalDateNow = Date.now;
+ const wallTime = Date.now();
+ const originals = { getSession: api.getSession, listSessions: api.listSessions,
+ pendingPlans: api.pendingPlans, listQueuedPrompts: api.listQueuedPrompts, composerCommands: api.composerCommands,
+ summarizeSessionTitle: api.summarizeSessionTitle };
+ const clipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard");
+ const sessions = [history(100), history(1000), history(10784)];
+ const records = new Map(sessions.map((item) => [item.summary.id, item]));
+ const copied: string[] = [];
+ const reads: { id: string; limit?: number }[] = [];
+ const errors: unknown[] = [];
+ const latencies: number[] = [];
+ const longTasks: number[] = [];
+ const observer = PerformanceObserver.supportedEntryTypes.includes("longtask")
+ ? new PerformanceObserver((list) => longTasks.push(...list.getEntries().map((entry) => entry.duration))) : undefined;
+ observer?.observe({ type: "longtask" });
+ const heap = () => (performance as Performance & { memory?: { usedJSHeapSize: number } }).memory?.usedJSHeapSize ?? null;
+ const heapBefore = heap();
+ const host = document.createElement("div");
+ host.style.cssText = "position:fixed;inset:0;display:flex;flex-direction:column";
+ document.body.append(host);
+ const root = createRoot(host, { onUncaughtError: (error) => errors.push(error) });
+ const element = <T extends HTMLElement = HTMLElement>(selector: string): T => {
+ const result = host.querySelector<T>(selector);
+ assert(result, `missing ${selector}; render errors: ${errors.map(String)}`);
+ return result;
+ };
+ const send = (sessionId: string, event: AgentEventEnvelope["event"]) => {
+ useAppStore.getState().handleAgentEvent({ sessionId, turnId: `turn-${sessionId}`, ts: Date.now(), event });
+ };
+ const delta = (item: FixtureSession, text: string, id = item.tail) => send(item.summary.id, {
+ type: "message_update", stream: "delta", deltaText: text,
+ message: { id, role: "assistant", content: "", createdAt, status: "streaming" },
+ });
+ const settled = async () => {
+ await frame(); await frame();
+ await until(() => !host.querySelector('[data-transcript-settling="true"]'), "transcript veil");
+ assert(errors.length === 0, `render/navigation errors: ${errors.map(String)}`);
+ };
+ const select = async (item: FixtureSession) => {
+ flushSync(() => element<HTMLButtonElement>(`[data-session="${item.summary.id}"]`).click());
+ await until(() => useAppStore.getState().activeSessionId === item.summary.id &&
+ !useAppStore.getState().selectingSessionId, `select ${item.summary.id}`);
+ await settled();
+ assert(useAppStore.getState().messages.length === item.messages.length,
+ `${item.summary.id}: bounded revalidation discarded loaded canonical history`);
+ };
+ const stream = async (item: FixtureSession, text: string) => {
+ const start = performance.now();
+ delta(item, text);
+ await until(() => host.querySelector(`[data-message-id="${item.tail}"]`)?.textContent?.includes(text) === true, text);
+ await settled();
+ latencies.push(performance.now() - start);
+ };
+ const workCounts: { session: string; loaded: number; oldBodyReads: number; unchangedGroupRenders: number; mountedRows: number }[] = [];
+ try {
+ // Keep elapsed-label intervals deterministic without replacing rAF,
+ // performance.now(), event batching, or React scheduling.
+ Date.now = () => wallTime;
+ // Only Host read/queue and clipboard boundaries are fixtures. No bootstrap,
+ // provider invocation, filesystem service, or running Desktop is used.
+ api.getSession = async (id, options) => {
+ const item = records.get(id);
+ assert(item, `unexpected session read ${id}`);
+ reads.push({ id, limit: options?.messageLimit });
+ const messages = options?.messageLimit ? item.messages.slice(-options.messageLimit) : item.messages;
+ return { session: { ...item.summary, messages,
+ messageStart: item.messages.length - messages.length, hasMoreBefore: messages.length < item.messages.length } };
+ };
+ api.listSessions = async () => ({ sessions: [...records.values()].map((item) => item.summary) });
+ api.pendingPlans = async () => ({ plans: [], state: "inactive" });
+ api.listQueuedPrompts = async () => ({ entries: [] });
+ api.composerCommands = async () => ({ commands: [] });
+ api.summarizeSessionTitle = async () => {
+ const error = new Error("Unexpected auto-title provider request in synthetic fixture");
+ errors.push(error);
+ throw error;
+ };
+ Object.defineProperty(navigator, "clipboard", { configurable: true,
+ value: { writeText: async (text: string) => { copied.push(text); } } });
+ useAppStore.setState({
+ sessions: sessions.map((item) => item.summary), providers: [], providerModels: {},
+ retainedTranscripts: {}, retainedSessionIds: [], sessionHistory: {}, sessionCompactions: {},
+ pendingPlans: {}, pendingAsks: {}, pendingPermissions: {}, planningStates: {}, agentStatuses: {},
+ latestTurnResults: {}, queuedPrompts: {}, notifications: [], workspace: undefined,
+ runningSessions: Object.fromEntries(sessions.map((item) => [item.summary.id, true])),
+ isRunning: true, page: "chat", selectingSessionId: undefined,
+ settings: { defaultMode: "agent", theme: "dark", enterToSend: true, onboardingDismissed: true,
+ ...initial.settings, smoothStreaming: false, thinkingDisplayMode: "detailed" },
+ });
+ // Seed canonical loaded snapshots through the real store subscription/cache
+ // writer, rather than bypassing it with a projection builder or custom store.
+ for (const item of sessions) useAppStore.setState({ activeSessionId: item.summary.id, messages: item.messages });
+ flushSync(() => root.render(<I18nextProvider i18n={i18n}><Surface sessions={sessions} errors={errors} /></I18nextProvider>));
+ await settled();
+
+ for (const item of sessions) {
+ await select(item);
+ await stream(item, " warm");
+ item.reads.count = 0;
+ globalThis.__activityGroupRenders = [];
+ for (let index = 0; index < 3; index++) await stream(item, ` delta-${index}`);
+ const sample = { session: item.summary.id, loaded: item.messages.length, oldBodyReads: item.reads.count,
+ unchangedGroupRenders: globalThis.__activityGroupRenders.length,
+ mountedRows: host.querySelectorAll(".message-row").length };
+ workCounts.push(sample);
+ assert(sample.oldBodyReads === 0, `${item.summary.id}: warmed deltas reread ${sample.oldBodyReads} unchanged bodies`);
+ assert(sample.unchangedGroupRenders === 0, `${item.summary.id}: unchanged groups rendered ${sample.unchangedGroupRenders} times`);
+ assert(sample.mountedRows < 150, `${item.summary.id}: mounted unbounded history (${sample.mountedRows})`);
+ const scroller = element(".thread-scroll");
+ await until(() => Math.abs(scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop) < 2, "pinned follow");
+ const editor = element(".composer-input");
+ editor.focus();
+ assert(document.activeElement === editor, "Composer lost keyboard focus during streaming");
+ }
+
+ // Both background caches receive deltas while the foreground stays exact.
+ const foreground = useAppStore.getState().messages;
+ const background = sessions.slice(0, 2);
+ for (const item of background) { item.reads.count = 0; delta(item, " background-fresh"); }
+ await settled();
+ assert(useAppStore.getState().messages === foreground, "background deltas replaced foreground messages");
+ for (const item of background) {
+ assert(item.reads.count === 0, `${item.summary.id}: background delta reread old bodies`);
+ await select(item);
+ assert(element(`[data-message-id="${item.tail}"]`).textContent?.includes("background-fresh"), "switch lost cached background delta");
+ }
+ const largest = sessions[2];
+ await select(largest);
+ // A mounted older row must invalidate its own projection and minimap preview.
+ const older = largest.messages[largest.messages.length - 7];
+ send(largest.summary.id, { type: "message_end", message: { ...older, content: "Older row corrected", status: "complete" } });
+ await until(() => host.textContent?.includes("Older row corrected") === true, "older row correction");
+ await settled();
+ const markers = [...host.querySelectorAll<HTMLButtonElement>(".minimap-marker.assistant")];
+ assert(markers.length > 0, "minimap markers missing");
+ let freshPreview = false;
+ const previews: string[] = [];
+ for (const marker of markers) {
+ // show:false Electron updates activeElement without delivering focusin.
+ // Deliver that DOM event explicitly; the production focus handler and
+ // preview component still consume the real, corrected marker model.
+ flushSync(() => {
+ marker.focus();
+ marker.dispatchEvent(new FocusEvent("focusin", { bubbles: true }));
+ });
+ const preview = host.querySelector(".minimap-popover")?.textContent ?? "<none>";
+ previews.push(preview.slice(0, 64));
+ if (preview.includes("Older row corrected")) {
+ freshPreview = true; flushSync(() => marker.click()); break;
+ }
+ }
+ assert(freshPreview, `minimap kept a stale older-row preview: ${JSON.stringify({ older: older.id, previews })}`);
+ // Actual disclosure toggling hands scroll ownership to the reader.
+ const disclosure = element<HTMLButtonElement>(".tool-activity-header");
+ flushSync(() => disclosure.click());
+ const expanded = disclosure.getAttribute("aria-expanded");
+ await stream(largest, " while-reading");
+ assert(disclosure.getAttribute("aria-expanded") === expanded, "stream reset explicit disclosure state");
+ const scroller = element(".thread-scroll");
+ scroller.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -200 }));
+ scroller.scrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight - 240);
+ scroller.dispatchEvent(new Event("scroll", { bubbles: true }));
+ await settled();
+ const readingTop = scroller.scrollTop;
+ await stream(largest, " reader-stays");
+ assert(Math.abs(scroller.scrollTop - readingTop) < 2, "stream stole the reader's scroll position");
+
+ // Terminal re-key must replace exactly the provisional row, survive cache
+ // reselection and expose fresh copy text through the real turn toolbar.
+ const completed = { ...useAppStore.getState().messages.at(-1)!, id: `${largest.tail}-durable`,
+ content: "Final canonical reply", status: "complete" as const };
+ send(largest.summary.id, { type: "message_end", replacesMessageId: largest.tail, message: completed });
+ send(largest.summary.id, { type: "agent_end", messageIds: [completed.id] });
+ await until(() => host.textContent?.includes("Final canonical reply") === true && !useAppStore.getState().isRunning, "completion");
+ await settled();
+ assert(!useAppStore.getState().messages.some((message) => message.id === largest.tail), "provisional id survived terminal re-key");
+ const final = element(`[data-message-id="${completed.id}"]`);
+ const copy = final.closest(".message-row")?.querySelector<HTMLButtonElement>(`button[aria-label="${i18n.t("chat.copy")}"]`);
+ assert(copy, "completed assistant Copy action missing");
+ flushSync(() => copy.click());
+ await until(() => copied.length > 0, "copy reply");
+ assert(copied.at(-1)?.includes("Final canonical reply") && copied.at(-1)?.includes("unchanged progress"), "copy lost full fresh turn text");
+ // Advance the synthetic durable fixture, as persistence does after completion.
+ largest.messages = useAppStore.getState().messages;
+ await select(sessions[0]); await select(largest);
+ assert(host.textContent?.includes("Final canonical reply"), "switch resurrected a pre-completion reply");
+ assert(!host.querySelector(".transcript-runtime-status"), "finished session returned as running");
+
+ for (const item of [giant(false), giant(true)]) {
+ records.set(item.summary.id, item);
+ flushSync(() => useAppStore.setState((state) => ({
+ sessions: [...state.sessions, item.summary], activeSessionId: item.summary.id, messages: item.messages,
+ isRunning: true, runningSessions: { ...state.runningSessions, [item.summary.id]: true },
+ })));
+ await settled(); await stream(item, " warm");
+ item.reads.count = 0; globalThis.__activityGroupRenders = [];
+ await stream(item, " giant-tail-fresh");
+ const sample = { session: item.summary.id, loaded: item.messages.length, oldBodyReads: item.reads.count,
+ unchangedGroupRenders: globalThis.__activityGroupRenders.length,
+ mountedRows: host.querySelectorAll(".message-row").length };
+ workCounts.push(sample);
+ assert(sample.oldBodyReads === 0, `${item.summary.id}: reread ${sample.oldBodyReads} old bodies`);
+ assert(sample.unchangedGroupRenders === 0, `${item.summary.id}: unchanged groups rerendered`);
+ if (item.summary.id === "long-activity-group") {
+ const groupHeader = element<HTMLButtonElement>(".process-activity-group > .tool-activity-header");
+ if (groupHeader.getAttribute("aria-expanded") !== "true") flushSync(() => groupHeader.click());
+ await settled();
+ const updateThinking = (text: string) => send(item.summary.id, {
+ type: "message_update", stream: "delta", deltaThinking: text,
+ message: { id: `${item.summary.id}-thinking`, role: "assistant", content: "", createdAt, status: "streaming" },
+ });
+ const thinking = element<HTMLButtonElement>(".tool-row.thinking .tool-row-header");
+ if (thinking.getAttribute("aria-expanded") !== "true") flushSync(() => thinking.click());
+ updateThinking(" warm-thinking");
+ await until(() => host.textContent?.includes("warm-thinking") === true, "warm giant thinking");
+ await settled();
+ item.reads.count = 0; globalThis.__activityGroupRenders = [];
+ updateThinking(" giant-thinking-fresh");
+ await until(() => host.textContent?.includes("giant-thinking-fresh") === true, "live giant group item");
+ await settled();
+ assert(item.reads.count === 0, `live giant group reread ${item.reads.count} completed tool bodies`);
+ assert(globalThis.__activityGroupRenders.length === 1, "live giant group must render exactly its changed group");
+ // A real tool_update targets a middle row, not the assistant tail. Warm
+ // its output shape before counting unrelated completed body accesses.
+ const liveToolId = `${item.summary.id}-tool-128`;
+ const liveTool = element<HTMLButtonElement>(`[data-message-id="${liveToolId}"] .tool-row-header`);
+ if (liveTool.getAttribute("aria-expanded") !== "true") flushSync(() => liveTool.click());
+ send(item.summary.id, { type: "tool_update", toolCallId: liveToolId, partialResult: { details: { output: "warm tool output" } } });
+ await until(() => host.querySelector(`[data-message-id="${liveToolId}"]`)?.textContent?.includes("warm tool output") === true,
+ "warm tool_update output", () => ({
+ message: useAppStore.getState().messages.find((message) => message.id === liveToolId),
+ groupExpanded: groupHeader.getAttribute("aria-expanded"),
+ toolExpanded: liveTool.getAttribute("aria-expanded"),
+ toolDom: host.querySelector(`[data-message-id="${liveToolId}"]`)?.outerHTML.slice(-3000),
+ }));
+ await settled();
+ item.reads.count = 0; globalThis.__activityGroupRenders = [];
+ send(item.summary.id, { type: "tool_update", toolCallId: liveToolId, partialResult: { details: { output: "fresh non-tail tool output" } } });
+ await until(() => host.querySelector(`[data-message-id="${liveToolId}"]`)?.textContent?.includes("fresh non-tail tool output") === true,
+ "fresh tool_update output");
+ await settled();
+ assert(item.reads.count === 0, `tool_update reread ${item.reads.count} completed bodies`);
+ assert(globalThis.__activityGroupRenders.length === 1, "tool_update must render exactly its changed group");
+ const changed = item.messages[1];
+ send(item.summary.id, { type: "message_end", message: { ...changed,
+ toolArgs: { command: "printf changed-giant-tool" } } });
+ await until(() => host.textContent?.includes("changed-giant-tool") === true, "giant group changed tool");
+ } else {
+ flushSync(() => element<HTMLButtonElement>(".subagent-topology-node-header").click());
+ await until(() => host.querySelector('[data-testid="subagent-transcript-tab"]') !== null, "child transcript dock");
+ const parent = useAppStore.getState().messages[1];
+ send(item.summary.id, { type: "message_update", stream: "delta", deltaText: " child-fresh",
+ message: { id: `${item.summary.id}-child`, role: "assistant", content: "", createdAt, status: "streaming",
+ parentToolCallId: parent.toolCallId, agentName: "explorer" } });
+ await until(() => host.querySelector('[data-testid="subagent-transcript-tab"]')?.textContent?.includes("child-fresh") === true,
+ "nested child update");
+ assert(useAppStore.getState().messages[1] === parent, "child update replaced its stable parent Task");
+ }
+ }
+ assert(reads.every((read) => read.limit === 100), "ordinary selection requested unbounded Host history");
+ assert(errors.length === 0, `render errors: ${errors.map(String)}`);
+ return { ok: true, workCounts, hostPageSize: 100, simultaneousRunningSessions: 3,
+ diagnostics: { eventToSettledDomMs: latencies, longTasksMs: observer ? longTasks : null,
+ heapBefore, heapAfter: heap() } };
+ } finally {
+ flushSync(() => root.unmount());
+ Date.now = originalDateNow;
+ observer?.disconnect(); host.remove();
+ Object.assign(api, originals);
+ if (clipboard) Object.defineProperty(navigator, "clipboard", clipboard);
+ else Reflect.deleteProperty(navigator, "clipboard");
+ useAppStore.setState(initial, true);
+ }
+}
diff --git a/scripts/e2e/transcript-render.tsx b/scripts/e2e/transcript-render.tsx
index 1036f2018..7728d0ae4 100644
--- a/scripts/e2e/transcript-render.tsx
+++ b/scripts/e2e/transcript-render.tsx
@@ -1,3 +1,4 @@
+import { transcriptLongHistoryProbe as runLongHistoryProbe } from "./transcript-long-history";
import { transcriptEditProbe } from "./transcript-edit";
import { turnProcessProbe } from "./turn-process";
import { transcriptStatusProbe } from "./transcript-status";
@@ -20,8 +21,11 @@ declare global {
var transcriptRenderProbe: () => Promise<unknown>;
var transcriptRuntimeSlotProbe: () => Promise<unknown>;
var smoothTextThrottleProbe: () => Promise<unknown>;
+ var transcriptLongHistoryProbe: typeof runLongHistoryProbe;
}
+globalThis.transcriptLongHistoryProbe = runLongHistoryProbe;
+
function assert(value: unknown, message: string): asserts value {
if (!value) throw new Error(message);
}