Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(renderer): bound transcript rendering work
vastsa9b546658cf52
diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsxindex 7d913439e..77bb7591e 100644--- a/apps/desktop/src/components/Markdown.tsx+++ b/apps/desktop/src/components/Markdown.tsx@@ -3,6 +3,7 @@ import {Fragment,isValidElement,memo,+ Profiler,useCallback,useContext,useEffect,@@ -25,6 +26,14 @@ import {emptyMarkdownBlockCache,markdownRemarkPlugins,} from "../lib/markdown-blocks";+import {+ MAX_STREAMING_MARKDOWN_TAIL_CODE_UNITS,+ MAX_SYNC_MARKDOWN_CODE_UNITS,+} from "../lib/render-content-limits";+import {+ beginRenderDiagnostic,+ recordRenderDiagnostic,+} from "../lib/render-diagnostics";import { useTranslation } from "react-i18next";import type { ThemedToken } from "shiki";import "katex/dist/katex.min.css";@@ -860,12 +869,16 @@ const rehypePlugins = [rehypeRaw, [rehypeSanitize, sanitizeSchema], rehypeKatex]* Splitting and its streaming reuse live in `markdown-blocks`, which owns the* rules a slice has to satisfy before it can be parsed on its own.*/-function useBlocks(source: string): string[] {+function useBlocks(source: string, maxTailCodeUnits: number): string[] {const cacheRef = useRef(emptyMarkdownBlockCache);return useMemo(() => {- cacheRef.current = advanceMarkdownBlocks(cacheRef.current, source);+ cacheRef.current = advanceMarkdownBlocks(+ cacheRef.current,+ source,+ maxTailCodeUnits,+ );return cacheRef.current.blocks;- }, [source]);+ }, [source, maxTailCodeUnits]);}const Block = memo(function MarkdownBlock({@@ -907,15 +920,29 @@ const Block = memo(function MarkdownBlock({[sourceOffset],);return (- <MarkdownBlockContext.Provider value={context}>- <ReactMarkdown- remarkPlugins={remarkPlugins}- rehypePlugins={positionedRehypePlugins}- components={markdownComponents}- >- {raw}- </ReactMarkdown>- </MarkdownBlockContext.Provider>+ <Profiler+ id="transcript-markdown-block"+ onRender={(_id, phase, actualDuration, baseDuration, startTime, commitTime) => {+ recordRenderDiagnostic("markdown-react-render", {+ sourceLength: raw.length,+ durationMs: actualDuration,+ baseDurationMs: baseDuration,+ startTime,+ commitTime,+ renderPhase: phase,+ });+ }}+ >+ <MarkdownBlockContext.Provider value={context}>+ <ReactMarkdown+ remarkPlugins={remarkPlugins}+ rehypePlugins={positionedRehypePlugins}+ components={markdownComponents}+ >+ {raw}+ </ReactMarkdown>+ </MarkdownBlockContext.Provider>+ </Profiler>);});@@ -923,9 +950,12 @@ export const Markdown = memo(function Markdown({source,renderDiagrams = true,baseDir,+ streaming = false,}: {source: string;renderDiagrams?: boolean;+ /** True only while an assistant message is still receiving text. */+ streaming?: boolean;/** Workspace-relative directory of the source file, for `./` / `../` links. */baseDir?: string;}) {@@ -947,22 +977,64 @@ export const Markdown = memo(function Markdown({(event, target) => openFileMenu(event, { items: fileMenuItems(target) }),[fileMenuItems, openFileMenu],);+ const { t } = useTranslation();+ const fullSourceTooLarge = source.length > MAX_SYNC_MARKDOWN_CODE_UNITS;+ const markdownTailLimit = streaming+ ? MAX_STREAMING_MARKDOWN_TAIL_CODE_UNITS+ : MAX_SYNC_MARKDOWN_CODE_UNITS;// Keep normalization length-preserving so source anchors and the bracket// display plugin still address the original text. Block splitting uses the// same math grammar as rendering, including unclosed streaming math blocks.const normalizedSource = useMemo(- () => normalizeLatexMathDelimiters(source),- [source],+ () => {+ const finishDiagnostic = beginRenderDiagnostic("markdown-normalize", {+ sourceLength: source.length,+ });+ if (fullSourceTooLarge) {+ finishDiagnostic({ reason: "source-limit" });+ return "";+ }+ const normalized = normalizeLatexMathDelimiters(source);+ finishDiagnostic();+ return normalized;+ },+ [fullSourceTooLarge, source],+ );+ const blocks = useBlocks(+ fullSourceTooLarge ? "" : normalizedSource,+ markdownTailLimit,);- const blocks = useBlocks(normalizedSource);let sourceOffset = 0;return (<MarkdownFileMenuContext.Provider value={openMarkdownFileMenu}><MarkdownBaseDirContext.Provider value={baseDir ?? ""}>- {blocks.map((raw, i) => {+ {fullSourceTooLarge ? (+ <div+ className="markdown-plain-fallback"+ data-source-start={0}+ data-source-end={source.length}+ >+ <div role="status">{t("chat.markdownPlainTextFallback")}</div>+ <pre>{source}</pre>+ </div>+ ) : blocks.map((raw, i) => {const start = sourceOffset;sourceOffset = start + raw.length;const originalRaw = source.slice(start, start + raw.length);+ const tailTooLarge = streaming && raw.length > markdownTailLimit;+ if (tailTooLarge) {+ return (+ <div+ className="markdown-plain-fallback"+ key={i}+ data-source-start={start}+ data-source-end={start + raw.length}+ >+ <div role="status">{t("chat.markdownPlainTextFallback")}</div>+ <pre>{originalRaw}</pre>+ </div>+ );+ }return (<Blockkey={i}diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsxindex a070d88e0..5af84c09c 100644--- a/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx+++ b/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx@@ -25,7 +25,7 @@ const SmoothMessageBubble = memo(function SmoothMessageBubble({ message, streamiclassName={`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}+ {displayContent ? <div className="prose-chat"><Markdown source={displayContent} streaming={streaming} /></div> : null}{message.error ? <AssistantErrorMessage message={message} /> : null}</div>);diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsxindex cd0e3e012..00889e2c7 100644--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx@@ -8,9 +8,8 @@ import {type ReactNode,} from "react";import { useTranslation } from "react-i18next";-import type { MessageAttachment, UiMessage } from "@pi-desktop/shared";+import type { UiMessage } from "@pi-desktop/shared";import { useOpenChatFileRef } from "../../../hooks/use-preview-target";-import { splitChatText } from "../../../lib/chat-links";import { useAppStore } from "../../../stores/app-store";import { Markdown } from "../../../components/Markdown";import {@@ -35,6 +34,7 @@ import {useChatTextActions,useTranscriptMenu,} from "./TranscriptMenu";+import { getExtraMessageAttachments } from "./extra-attachments";function SkillInvocationText({ message }: { message: UiMessage }) {const command = message.command ?? "";@@ -109,18 +109,10 @@ export const MessageRow = memo(function MessageRow({const activeRevision = message.activeRevision ?? revisionCount;const showRevisionPager = editableUserMessage && revisionCount > 1;const extraAttachments = useMemo(() => {- const attachments = message.attachments;- if (!attachments?.length) return [];- const inline = new Set(- splitChatText(String(message.content || ""), workspaceRoot)- .filter((segment): segment is { kind: "target"; text: string; label: string; target: { kind: "file"; path: string } } => segment.kind === "target" && segment.target.kind === "file")- .map((segment) => segment.target.path),- );- // A conversation reference is already its chip in the body link, so it- // needs no second block; only a file the body does not show inline does.- return attachments.filter(- (attachment): attachment is MessageAttachment & { kind: "file" | "image" } =>- attachment.kind !== "session" && !inline.has(attachment.ref),+ return getExtraMessageAttachments(+ String(message.content || ""),+ message.attachments,+ workspaceRoot,);}, [message.attachments, message.content, workspaceRoot]);// An attachment the body does not already name inline continues the bodydiff --git a/apps/desktop/src/features/chat/transcript/extra-attachments.ts b/apps/desktop/src/features/chat/transcript/extra-attachments.tsnew file mode 100644index 000000000..438948679--- /dev/null+++ b/apps/desktop/src/features/chat/transcript/extra-attachments.ts@@ -0,0 +1,22 @@+import type { MessageAttachment } from "@pi-desktop/shared";+import { splitChatText } from "../../../lib/chat-links.ts";++/** Attachments already represented by a verified inline file link stay inline. */+export function getExtraMessageAttachments(+ content: string,+ attachments: readonly MessageAttachment[] | undefined,+ workspaceRoot?: string | null,+): (MessageAttachment & { kind: "file" | "image" })[] {+ if (!attachments?.length) return [];+ const inline = new Set(+ splitChatText(content, workspaceRoot)+ .map((segment) => segment.kind === "target" && segment.target.kind === "file"+ ? segment.target.path+ : null)+ .filter((path): path is string => path !== null),+ );+ return attachments.filter(+ (attachment): attachment is MessageAttachment & { kind: "file" | "image" } =>+ attachment.kind !== "session" && !inline.has(attachment.ref),+ );+}diff --git a/apps/desktop/src/hooks/useSmoothText.ts b/apps/desktop/src/hooks/useSmoothText.tsindex bb0444fd6..b8f783db6 100644--- a/apps/desktop/src/hooks/useSmoothText.ts+++ b/apps/desktop/src/hooks/useSmoothText.ts@@ -1,4 +1,5 @@import { useEffect, useRef, useState } from "react";+import { MAX_SMOOTH_TEXT_CODE_UNITS } from "../lib/render-content-limits";/*** Progressively reveals `source` text at an adaptive rate.@@ -15,6 +16,10 @@ export function useSmoothText(streaming: boolean,enabled: boolean,): string {+ const shouldSmooth =+ enabled &&+ streaming &&+ source.length <= MAX_SMOOTH_TEXT_CODE_UNITS;const [revealed, setRevealed] = useState(source.length);const revealedRef = useRef(source.length);const rafRef = useRef<number | null>(null);@@ -23,7 +28,7 @@ export function useSmoothText(// When not enabled or not streaming, always show full textuseEffect(() => {- if (!enabled || !streaming) {+ if (!shouldSmooth) {revealedRef.current = source.length;lastFrameRef.current = 0;fractionalAdvanceRef.current = 0;@@ -33,11 +38,11 @@ export function useSmoothText(rafRef.current = null;}}- }, [enabled, streaming, source.length]);+ }, [shouldSmooth, source.length]);// Core release loopuseEffect(() => {- if (!enabled || !streaming) return;+ if (!shouldSmooth) return;const tick = (now: number) => {const backlog = source.length - revealedRef.current;@@ -94,7 +99,7 @@ export function useSmoothText(rafRef.current = null;}};- }, [enabled, streaming, source]);+ }, [shouldSmooth, source]);// Flush on unmountuseEffect(() => {@@ -106,7 +111,7 @@ export function useSmoothText(};}, []);- if (!enabled || !streaming) return source;+ if (!shouldSmooth) return source;// Avoid slicing in the middle of a UTF-16 surrogate pair.let end = revealed;if (end < source.length && end > 0) {diff --git a/apps/desktop/src/lib/chat-link-scanner.ts b/apps/desktop/src/lib/chat-link-scanner.tsnew file mode 100644index 000000000..7bca4529e--- /dev/null+++ b/apps/desktop/src/lib/chat-link-scanner.ts@@ -0,0 +1,622 @@+import { beginRenderDiagnostic } from "./render-diagnostics.ts";++/**+ * Bounded candidate scanning for transcript links.+ *+ * File recognition still uses the chat-links grammar, but only against one+ * complete candidate of at most 512 UTF-16 code units. The outer cursor moves+ * monotonically and never retries a failed suffix of an overlong candidate.+ */++export const CHAT_LINK_SCAN_LIMITS = Object.freeze({+ maxScanWorkCodeUnits: 128 * 1024,+ maxFileCandidates: 512,+ maxLinks: 256,+ maxFileCandidateCodeUnits: 512,+ maxUrlCandidateCodeUnits: 16 * 1024,+});++export const KNOWN_BARE_CHAT_FILES = new Set([+ "Makefile",+ "Dockerfile",+ "LICENSE",+ "README",+ "CHANGELOG",+]);++export type ChatLinkScanBudget = {+ workCodeUnits: number;+ fileCandidates: number;+ links: number;+};++export type ChatLinkScanStats = {+ scannedCodeUnits: number;+ candidateWindowCodeUnits: number;+ fileCandidateCount: number;+ linkCount: number;+ workCodeUnits: number;+};++export type ScannedChatLink<T> = {+ start: number;+ end: number;+ raw: string;+ target: T;+};++export type ChatLinkCandidateDisposition = "accept" | "retry" | "skip" | "exhausted";+export type ChatLinkCandidateDispositionResolver = (+ raw: string,+ source: string,+ start: number,+ budget: ChatLinkScanBudget,+ stats: ChatLinkScanStats,+) => ChatLinkCandidateDisposition;++const PATH_WORD_RE = /^[\p{L}\p{N}_@+./\\-]$/u;+const TERMINAL_FILE_RE = /\.[A-Za-z0-9]{1,8}(?:[+@-][\p{L}\p{N}_@+-]*)?(?::\d+(?::\d+)?)?$/u;+const PROSE_BOUNDARIES = new Set([+ "a", "an", "and", "against", "because", "but", "change", "check",+ "copy", "create", "created", "delete", "edit", "find", "fix", "for",+ "generated", "i", "is", "move", "now", "open", "or", "please", "read",+ "remove", "review", "saved", "see", "show", "then", "this", "update",+ "use", "view", "with", "write", "和", "与", "再看", "然后", "接着",+]);++function createStats(): ChatLinkScanStats {+ return {+ scannedCodeUnits: 0,+ candidateWindowCodeUnits: 0,+ fileCandidateCount: 0,+ linkCount: 0,+ workCodeUnits: 0,+ };+}++export function createChatLinkScanBudget(): ChatLinkScanBudget {+ return { workCodeUnits: 0, fileCandidates: 0, links: 0 };+}++function spend(+ budget: ChatLinkScanBudget,+ stats: ChatLinkScanStats,+ codeUnits: number,+ category: "scan" | "window",+): boolean {+ if (+ codeUnits < 0 ||+ budget.workCodeUnits + codeUnits >+ CHAT_LINK_SCAN_LIMITS.maxScanWorkCodeUnits+ ) {+ return false;+ }+ budget.workCodeUnits += codeUnits;+ stats.workCodeUnits += codeUnits;+ if (category === "scan") stats.scannedCodeUnits += codeUnits;+ else stats.candidateWindowCodeUnits += codeUnits;+ return true;+}++/** Charge bounded candidate-context inspection to this conversion's budget. */+export function spendChatLinkScanWork(+ budget: ChatLinkScanBudget,+ stats: ChatLinkScanStats,+ codeUnits: number,+): boolean {+ return spend(budget, stats, codeUnits, "scan");+}++function codePointWidth(text: string, index: number): number {+ const value = text.codePointAt(index);+ return value !== undefined && value > 0xffff ? 2 : 1;+}++function pathWordAt(text: string, index: number): boolean {+ return PATH_WORD_RE.test(String.fromCodePoint(text.codePointAt(index) ?? 0));+}++function isWhitespace(code: number): boolean {+ return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;+}++function isHardBoundary(code: number): boolean {+ return (+ code === 0x0a || code === 0x0d || code === 0x2c || code === 0x21 ||+ code === 0x3b || code === 0x3f || code === 0x3c || code === 0x3e ||+ code === 0x22 || code === 0x27 || code === 0x28 || code === 0x29 ||+ code === 0x5b || code === 0x5d || code === 0x7b || code === 0x7d ||+ code === 0xff0c || code === 0xff01 || code === 0xff1b || code === 0xff1f ||+ code === 0xff1a || code === 0x3002+ );+}++function startsHttpUrl(text: string, index: number): boolean {+ const first = text.charCodeAt(index) | 0x20;+ if (first !== 0x68) return false;+ const second = text.charCodeAt(index + 1) | 0x20;+ const third = text.charCodeAt(index + 2) | 0x20;+ const fourth = text.charCodeAt(index + 3) | 0x20;+ if (second !== 0x74 || third !== 0x74 || fourth !== 0x70) return false;+ let offset = 4;+ if ((text.charCodeAt(index + offset) | 0x20) === 0x73) offset += 1;+ return text.slice(index + offset, index + offset + 3) === "://";+}++function urlBreak(code: number): boolean {+ return (+ isWhitespace(code) || code === 0x3c || code === 0x3e || code === 0x22 ||+ code === 0x27 || code === 0x5b || code === 0x5d || code === 0x7b ||+ code === 0x7d+ );+}++function trimUrlPunctuation(url: string): string {+ let end = url.length;+ while (end > 0) {+ const code = url.charCodeAt(end - 1);+ if (+ code === 0x2e || code === 0x2c || code === 0x21 || code === 0x3f ||+ code === 0x3b || code === 0x3a || code === 0xff0c || code === 0x3002 ||+ code === 0xff01 || code === 0xff1f || code === 0xff1b || code === 0xff1a+ ) {+ end -= 1;+ } else {+ break;+ }+ }+ return url.slice(0, end);+}++function scanUrlEnd(+ text: string,+ start: number,+ budget: ChatLinkScanBudget,+ stats: ChatLinkScanStats,+): { end: number; overflow: boolean; exhausted: boolean } {+ let depth = 0;+ let index = start;+ let length = 0;+ while (index < text.length) {+ const code = text.charCodeAt(index);+ if (urlBreak(code)) break;+ if (length >= CHAT_LINK_SCAN_LIMITS.maxUrlCandidateCodeUnits) {+ return { end: index, overflow: true, exhausted: false };+ }+ if (!spend(budget, stats, 1, "scan")) {+ return { end: index, overflow: true, exhausted: true };+ }+ if (code === 0x28) depth += 1;+ else if (code === 0x29) {+ if (depth === 0) break;+ depth -= 1;+ }+ index += 1;+ length += 1;+ }+ return { end: index, overflow: false, exhausted: false };+}++function hasPathMarker(+ text: string,+ start: number,+ budget: ChatLinkScanBudget,+ stats: ChatLinkScanStats,+): { found: boolean; end: number; exhausted: boolean } {+ for (let index = start; index < text.length;) {+ const code = text.charCodeAt(index);+ if (isWhitespace(code) || isHardBoundary(code)) {+ return { found: false, end: index, exhausted: false };+ }+ if (code === 0x2e || code === 0x2f || code === 0x5c || code === 0x40) {+ return { found: true, end: index, exhausted: false };+ }+ const width = codePointWidth(text, index);+ if (!spend(budget, stats, width, "scan")) {+ return { found: false, end: index, exhausted: true };+ }+ index += width;+ }+ return { found: false, end: text.length, exhausted: false };+}++function isTerminalFileToken(token: string): boolean {+ return TERMINAL_FILE_RE.test(token) || KNOWN_BARE_CHAT_FILES.has(token);+}++function candidateWindowEnd(+ text: string,+ start: number,+ budget: ChatLinkScanBudget,+ stats: ChatLinkScanStats,+): { end: number; exhausted: boolean; truncated: boolean } {+ let limit = Math.min(+ text.length,+ start + CHAT_LINK_SCAN_LIMITS.maxFileCandidateCodeUnits,+ );+ if (+ limit < text.length &&+ text.charCodeAt(limit - 1) >= 0xd800 && text.charCodeAt(limit - 1) <= 0xdbff &&+ text.charCodeAt(limit) >= 0xdc00 && text.charCodeAt(limit) <= 0xdfff+ ) limit -= 1;+ let index = start;+ let tokenStart = start;+ while (index < limit) {+ const code = text.charCodeAt(index);+ if (isHardBoundary(code)) {+ return { end: index, exhausted: false, truncated: false };+ }+ if (isWhitespace(code)) {+ const token = text.slice(tokenStart, index);+ if (isTerminalFileToken(token)) {+ return { end: index, exhausted: false, truncated: false };+ }+ while (index < limit && isWhitespace(text.charCodeAt(index))) {+ if (!spend(budget, stats, 1, "window")) {+ return { end: index, exhausted: true, truncated: false };+ }+ index += 1;+ }+ tokenStart = index;+ continue;+ }+ const width = codePointWidth(text, index);+ if (!spend(budget, stats, width, "window")) {+ return { end: index, exhausted: true, truncated: false };+ }+ index += width;+ }+ return {+ end: limit,+ exhausted: false,+ truncated: limit < text.length && !isHardBoundary(text.charCodeAt(limit)),+ };+}++function overlongCandidateEnd(+ text: string,+ candidateStart: number,+ index: number,+ budget: ChatLinkScanBudget,+ stats: ChatLinkScanStats,+): { end: number; exhausted: boolean } {+ const absoluteCandidate =+ text[candidateStart] === "/" ||+ text.startsWith("\\\\", candidateStart) ||+ /^[A-Za-z]:[\\/]/.test(text.slice(candidateStart, candidateStart + 3));+ let tokenStart = index;+ while (index < text.length) {+ const code = text.charCodeAt(index);+ if (isHardBoundary(code)) return { end: index, exhausted: false };+ if (isWhitespace(code)) {+ const token = text.slice(tokenStart, index);+ if (isTerminalFileToken(token)) {+ return { end: index, exhausted: false };+ }+ // A following prose connector closes an incomplete long candidate. This+ // lets a later independent path be considered without linking a suffix.+ let next = index;+ while (next < text.length && isWhitespace(text.charCodeAt(next))) {+ if (!spend(budget, stats, 1, "scan")) {+ return { end: index, exhausted: true };+ }+ next += 1;+ }+ const nextStart = next;+ while (+ next < text.length &&+ !isWhitespace(text.charCodeAt(next)) &&+ !isHardBoundary(text.charCodeAt(next))+ ) {+ const nextWidth = codePointWidth(text, next);+ if (!spend(budget, stats, nextWidth, "scan")) {+ return { end: index, exhausted: true };+ }+ next += nextWidth;+ }+ const nextToken = text.slice(nextStart, next);+ if (+ isTerminalFileToken(nextToken) &&+ !(absoluteCandidate && /[\\/]/u.test(nextToken)) &&+ !(!absoluteCandidate && text.slice(candidateStart, index).includes("/") && /[\\/]/u.test(nextToken))+ ) {+ return { end: index, exhausted: false };+ }+ if (PROSE_BOUNDARIES.has(nextToken.toLowerCase())) {+ return { end: index, exhausted: false };+ }+ while (index < text.length && isWhitespace(text.charCodeAt(index))) {+ if (!spend(budget, stats, 1, "scan")) {+ return { end: index, exhausted: true };+ }+ index += 1;+ }+ tokenStart = index;+ continue;+ }+ const width = codePointWidth(text, index);+ if (!spend(budget, stats, width, "scan")) {+ return { end: index, exhausted: true };+ }+ index += width;+ }+ return { end: index, exhausted: false };+}++function isCandidateBoundary(text: string, index: number): boolean {+ if (index === 0) return true;+ const previous = index - codePointWidth(text, index - 1);+ return !pathWordAt(text, previous) && text[previous] !== "/" && text[previous] !== "\\";+}++function sessionLinkEnd(text: string, start: number): number {+ const prefix = "pi-desktop://session/";+ if (!text.startsWith(prefix, start)) return start;+ let end = start + prefix.length;+ const idStart = end;+ while (end < text.length && end - idStart < 65) {+ const code = text.charCodeAt(end);+ if (+ !((code >= 0x41 && code <= 0x5a) || (code >= 0x61 && code <= 0x7a) ||+ (code >= 0x30 && code <= 0x39) || code === 0x5f || code === 0x2d)+ ) break;+ end += 1;+ }+ return end;+}++function scanAtReference<T>(+ text: string,+ start: number,+ budget: ChatLinkScanBudget,+ stats: ChatLinkScanStats,+ resolve: (raw: string) => T | null,+): { end: number; candidate?: ScannedChatLink<T>; exhausted: boolean } {+ const withinCandidateLimit =+ budget.fileCandidates < CHAT_LINK_SCAN_LIMITS.maxFileCandidates;+ if (withinCandidateLimit) {+ budget.fileCandidates += 1;+ stats.fileCandidateCount += 1;+ }+ let end = start;+ const quoted = text[start + 1] === '"';+ if (quoted) {+ end = start + 2;+ while (+ end < text.length &&+ text.charCodeAt(end) !== 0x0a &&+ text.charCodeAt(end) !== 0x0d &&+ text.charCodeAt(end) !== 0x22+ ) {+ const width = codePointWidth(text, end);+ if (!spend(budget, stats, width, "scan")) {+ return { end, exhausted: true };+ }+ end += width;+ }+ if (end < text.length && text.charCodeAt(end) === 0x22) end += 1;+ } else {+ while (end < text.length && !isWhitespace(text.charCodeAt(end))) {+ const width = codePointWidth(text, end);+ if (!spend(budget, stats, width, "scan")) {+ return { end, exhausted: true };+ }+ end += width;+ }+ }+ if (end - start > CHAT_LINK_SCAN_LIMITS.maxFileCandidateCodeUnits) {+ return { end, exhausted: false };+ }+ if (!withinCandidateLimit) return { end, exhausted: false };+ const raw = text.slice(start, end);+ if (!spend(budget, stats, raw.length, "window")) {+ return { end, exhausted: true };+ }+ const target = resolve(raw);+ if (!target) return { end, exhausted: false };+ budget.links += 1;+ stats.linkCount += 1;+ return {+ end,+ candidate: { start, end, raw, target },+ exhausted: false,+ };+}++/** Scan once and resolve references without allowing a candidate to exceed its budget. */+export function scanChatLinkCandidates<T>(+ text: string,+ budget: ChatLinkScanBudget,+ resolve: (raw: string) => T | null,+ disposition: ChatLinkCandidateDispositionResolver,+): { candidates: ScannedChatLink<T>[]; stats: ChatLinkScanStats } {+ const finishDiagnostic = beginRenderDiagnostic("chat-link-scan", {+ sourceLength: text.length,+ });+ const candidates: ScannedChatLink<T>[] = [];+ const stats = createStats();+ let index = 0;+ while (+ index < text.length &&+ budget.workCodeUnits < CHAT_LINK_SCAN_LIMITS.maxScanWorkCodeUnits &&+ budget.links < CHAT_LINK_SCAN_LIMITS.maxLinks+ ) {+ const start = index;+ if (startsHttpUrl(text, index)) {+ const scanned = scanUrlEnd(text, start, budget, stats);+ if (scanned.exhausted) break;+ if (scanned.overflow) {+ index = scanned.end;+ while (index < text.length && !urlBreak(text.charCodeAt(index))) {+ const width = codePointWidth(text, index);+ if (!spend(budget, stats, width, "scan")) break;+ index += width;+ }+ if (budget.workCodeUnits >= CHAT_LINK_SCAN_LIMITS.maxScanWorkCodeUnits) break;+ continue;+ }+ const raw = trimUrlPunctuation(text.slice(start, scanned.end));+ const target = raw ? resolve(raw) : null;+ if (target) {+ candidates.push({ start, end: start + raw.length, raw, target });+ budget.links += 1;+ stats.linkCount += 1;+ index = start + raw.length;+ } else {+ index = Math.max(scanned.end, start + 1);+ }+ continue;+ }++ const sessionEnd = sessionLinkEnd(text, index);+ if (sessionEnd > index) {+ const length = sessionEnd - index;+ if (!spend(budget, stats, length, "scan")) break;+ const raw = text.slice(index, sessionEnd);+ const target = resolve(raw);+ if (target) {+ candidates.push({ start, end: sessionEnd, raw, target });+ budget.links += 1;+ stats.linkCount += 1;+ }+ index = sessionEnd;+ continue;+ }++ const currentCode = text.charCodeAt(index);+ const tildePathStart = currentCode === 0x7e &&+ (text[index + 1] === "/" || text[index + 1] === "\\");+ if (+ (currentCode === 0x2f || currentCode === 0x5c) &&+ text[index - 1] === "~"+ ) {+ if (!spend(budget, stats, 1, "scan")) break;+ index += 1;+ continue;+ }+ const explicitAt = currentCode === 0x40;+ if (explicitAt) {+ const scanned = scanAtReference(text, index, budget, stats, resolve);+ if (scanned.exhausted) break;+ if (scanned.candidate) candidates.push(scanned.candidate);+ index = Math.max(scanned.end, index + 1);+ continue;+ }+ if (+ (tildePathStart || (isCandidateBoundary(text, index) && pathWordAt(text, index))) &&+ budget.fileCandidates < CHAT_LINK_SCAN_LIMITS.maxFileCandidates+ ) {+ const marker = tildePathStart+ ? { found: true, end: index, exhausted: false }+ : hasPathMarker(text, index, budget, stats);+ if (marker.exhausted) break;+ if (!marker.found && marker.end > index) {+ index = marker.end;+ continue;+ }+ if (marker.found) {+ budget.fileCandidates += 1;+ stats.fileCandidateCount += 1;+ const window = candidateWindowEnd(text, index, budget, stats);+ if (window.exhausted) break;+ const candidateText = text.slice(index, window.end);+ if (!spend(budget, stats, candidateText.length, "window")) break;++ FILE_SCAN_RE.lastIndex = 0;+ const match = FILE_SCAN_RE.exec(candidateText);+ if (match?.[0]) {+ const raw = match[0];+ const end = index + raw.length;+ const continuesBeyondWindow =+ window.truncated && end >= window.end &&+ pathWordAt(text, window.end);+ if (continuesBeyondWindow) {+ const overlong = overlongCandidateEnd(+ text,+ start,+ window.end,+ budget,+ stats,+ );+ if (overlong.exhausted) break;+ index = Math.max(overlong.end, window.end);+ continue;+ }+ const decision = disposition(raw, text, start, budget, stats);+ if (decision === "exhausted") break;+ if (decision === "retry") {+ const space = raw.indexOf(" ");+ index = space >= 0 ? start + space + 1 : end;+ continue;+ }+ if (decision === "skip") {+ index = end;+ continue;+ }+ const target = resolve(raw);+ if (target) {+ candidates.push({ start, end, raw, target });+ budget.links += 1;+ stats.linkCount += 1;+ index = end;+ } else {+ index = end;+ }+ continue;+ }++ if (window.truncated) {+ const overlong = overlongCandidateEnd(+ text,+ start,+ window.end,+ budget,+ stats,+ );+ if (overlong.exhausted) break;+ index = Math.max(overlong.end, window.end);+ continue;+ }+ if (tildePathStart) {+ index = Math.max(window.end, index + 1);+ continue;+ }+ }+ }++ const width = codePointWidth(text, index);+ if (!spend(budget, stats, width, "scan")) break;+ index += width;+ }+ finishDiagnostic({+ workCodeUnits: stats.workCodeUnits,+ linkCount: stats.linkCount,+ reason: budget.links >= CHAT_LINK_SCAN_LIMITS.maxLinks+ ? "link-limit"+ : budget.workCodeUnits >= CHAT_LINK_SCAN_LIMITS.maxScanWorkCodeUnits+ ? "scan-budget"+ : undefined,+ });+ return { candidates, stats };+}++const PATH_WORD = String.raw`[\p{L}\p{N}_@+.-]+`;+const PATH_SEGMENT = String.raw`[\p{L}\p{N}_@+. -]+`;+const PATH_CONTINUATION = String.raw`[\p{L}\p{N}_@+.-]*[\\/]`;+const FILE_END = String.raw`\.[A-Za-z0-9]{1,8}(?:[+@-][\p{L}\p{N}_@+-]*)?(?::\d+(?::\d+)?)?(?![A-Za-z0-9_@+-]|\.[A-Za-z0-9]|${PATH_CONTINUATION})`;+const BARE_FILE_END = String.raw`(?:${[...KNOWN_BARE_CHAT_FILES].join("|")})(?![\p{L}\p{N}_@+.-]|${PATH_CONTINUATION})`;+const FILE_NAME = String.raw`(?:${PATH_SEGMENT}?${FILE_END}|${BARE_FILE_END})`;+const UNC_PREFIX = String.raw`(?:\\\\[^\\/\s]+[\\/]|\/\/[^/\s]+\/)`;+const SPACED_START = String.raw`(?<![\p{L}\p{N}_@+.-])[A-Za-z][\p{L}\p{N}_+-]*(?: [\p{L}\p{N}_+-]+)+`;+const FILE_SCAN_SOURCE = [+ String.raw`@"[^"\n]+"`,+ String.raw`@[^\s]+`,+ String.raw`(?:[A-Za-z]:[\\/]|${UNC_PREFIX}|\/)(?:${PATH_SEGMENT}[\\/])*?${FILE_NAME}`,+ String.raw`${SPACED_START}[\\/](?:${PATH_SEGMENT}[\\/])*?${FILE_NAME}`,+ String.raw`${SPACED_START}(?:\.[A-Za-z0-9_-]+)*${FILE_END}`,+ String.raw`(?:${PATH_WORD}[\\/])+(?:${PATH_SEGMENT}[\\/])*?${FILE_NAME}`,+ String.raw`(?:~[\\/])?\/?\.{1,2}[\\/](?:${PATH_WORD}\/)*${PATH_WORD}(?::\d+(?::\d+)?)?`,+ String.raw`(?:~[\\/])?\/?(?:${PATH_WORD}\/)+${PATH_WORD}(?::\d+(?::\d+)?)?`,+ String.raw`[\p{L}\p{N}_@+-][\p{L}\p{N}_@+.-]*${FILE_END}`,+].join("|");+const FILE_SCAN_RE = new RegExp(FILE_SCAN_SOURCE, "uy");diff --git a/apps/desktop/src/lib/chat-links.ts b/apps/desktop/src/lib/chat-links.tsindex 8922fe8ce..40991b27f 100644--- a/apps/desktop/src/lib/chat-links.ts+++ b/apps/desktop/src/lib/chat-links.ts@@ -18,6 +18,16 @@*/import { formatSessionLink, parseSessionLinkToken } from "@pi-desktop/shared";+import {+ CHAT_LINK_SCAN_LIMITS,+ createChatLinkScanBudget,+ KNOWN_BARE_CHAT_FILES,+ scanChatLinkCandidates,+ spendChatLinkScanWork,+ type ChatLinkScanBudget,+ type ChatLinkScanStats,+} from "./chat-link-scanner.ts";+import { beginRenderDiagnostic } from "./render-diagnostics.ts";const KNOWN_EXTS = new Set(["ts", "tsx", "js", "jsx", "mjs", "cjs", "json", "css", "scss", "less",@@ -28,14 +38,6 @@ const KNOWN_EXTS = new Set(["csv", "tsv", "log",]);-const KNOWN_BARE_NAMES = new Set([- "Makefile",- "Dockerfile",- "LICENSE",- "README",- "CHANGELOG",-]);-const FILE_TOKEN_RE =/^(?:(?:[A-Za-z]:[\\/]|~[\\/]|\\\\|\/\/|[\\/])|(?:\.{1,2}[\\/])?)[\p{L}\p{N}_@+. -]+(?:[\\/][\p{L}\p{N}_@+. -]+)*(?::\d+(?::\d+)?)?$/u;@@ -82,10 +84,10 @@ function isLikelyFilePath(path: string): boolean {const baseExt = ext.replace(/[+@-][\p{L}\p{N}_@+-]*$/u, "");if (normalized.includes("/")) {if (baseExt && baseExt.length <= 8) return true;- if (KNOWN_BARE_NAMES.has(base)) return true;+ if (KNOWN_BARE_CHAT_FILES.has(base)) return true;return false;}- if (KNOWN_BARE_NAMES.has(base)) return true;+ if (KNOWN_BARE_CHAT_FILES.has(base)) return true;return KNOWN_EXTS.has(baseExt);}@@ -273,19 +275,6 @@ export type ChatTextSegment =target: ChatPreviewTarget;};-// Unicode-aware scan (#235). Keep absolute candidates whole, and do not stop-// at an inner extension such as the `.v1` in `report.v1.md`. CJK prose after-// the extension remains outside the link (Unicode `\b` cannot express that).-const PATH_WORD = String.raw`[\p{L}\p{N}_@+.-]+`;-const PATH_SEGMENT = String.raw`[\p{L}\p{N}_@+. -]+`;-// Only adjacent characters can extend a dotted directory. Whitespace after an-// extension is ambiguous with prose; quote such paths with @"...".-const PATH_CONTINUATION = String.raw`[\p{L}\p{N}_@+.-]*[\\/]`;-const FILE_END = String.raw`\.[A-Za-z0-9]{1,8}(?:[+@-][\p{L}\p{N}_@+-]*)?(?::\d+(?::\d+)?)?(?![A-Za-z0-9_@+-]|\.[A-Za-z0-9]|${PATH_CONTINUATION})`;-const BARE_FILE_END = String.raw`(?:${[...KNOWN_BARE_NAMES].join("|")})(?![\p{L}\p{N}_@+.-]|${PATH_CONTINUATION})`;-const FILE_NAME = String.raw`(?:${PATH_SEGMENT}?${FILE_END}|${BARE_FILE_END})`;-const UNC_PREFIX = String.raw`(?:\\\\[^\\/\s]+[\\/]|\/\/[^/\s]+\/)`;-const SPACED_START = String.raw`(?<![\p{L}\p{N}_@+.-])[A-Za-z][\p{L}\p{N}_+-]*(?: [\p{L}\p{N}_+-]+)+`;// Unmarked first-segment spaces cannot be distinguished from prose. Retry// after common introducers so ordinary bare file links still work.const PROSE_INTRODUCERS = new Set([@@ -293,88 +282,89 @@ const PROSE_INTRODUCERS = new Set(["see", "open", "read", "view", "check", "show", "find", "edit","update", "fix", "inspect", "compare", "review", "use", "add", "remove","write", "create", "created", "delete", "rename", "move", "copy",- "change", "saved", "generated",+ "change", "saved", "generated", "和", "与", "再看", "然后", "接着",+ "打开", "请看", "先看", "查看", "读取", "编辑",]);-const SCAN_RE = new RegExp([- String.raw`@"[^"\n]+"`,- String.raw`@[^\s]+`,- String.raw`https?:\/\/(?=[^\s<>"'()[\]{}])`,- String.raw`pi-desktop:\/\/session\/[A-Za-z0-9_-]{1,64}`,- String.raw`(?:[A-Za-z]:[\\/]|${UNC_PREFIX}|\/)(?:${PATH_SEGMENT}[\\/])*?${FILE_NAME}`,- String.raw`${SPACED_START}[\\/](?:${PATH_SEGMENT}[\\/])*?${FILE_NAME}`,- String.raw`${SPACED_START}(?:\.[A-Za-z0-9_-]+)*${FILE_END}`,- String.raw`(?:${PATH_WORD}[\\/])+(?:${PATH_SEGMENT}[\\/])*?${FILE_NAME}`,- String.raw`(?:~\/)?\/?\.{1,2}\/(?:${PATH_WORD}\/)*${PATH_WORD}(?::\d+(?::\d+)?)?`,- String.raw`(?:~\/)?\/?(?:${PATH_WORD}\/)+${PATH_WORD}(?::\d+(?::\d+)?)?`,- String.raw`[\p{L}\p{N}_@+-][\p{L}\p{N}_@+.-]*${FILE_END}`,-].join("|"), "gu");--function spacedRefDisposition(raw: string): "accept" | "retry" | "skip" {+function spacedRefDisposition(+ raw: string,+ source: string,+ start: number,+ budget: ChatLinkScanBudget,+ stats: ChatLinkScanStats,+): "accept" | "retry" | "skip" | "exhausted" {if (isAbsoluteFilePath(raw) || raw.startsWith("@") || isHttpUrl(raw)) return "accept";const firstSegment = raw.split(/[\\/]/, 1)[0];- if (!firstSegment.includes(" ")) return "accept";- const firstWord = firstSegment.slice(0, firstSegment.indexOf(" ")).toLowerCase();- return PROSE_INTRODUCERS.has(firstWord) ? "retry" : "skip";-}--/** Scan once, keeping URL parentheses but stopping at a closing prose wrapper. */-function scanUrl(text: string, start: number): string {- let depth = 0;- let end = start;- for (; end < text.length; end += 1) {- const character = text[end];- if (/[\s<>"'[\]{}]/u.test(character)) break;- if (character === "(") depth += 1;- else if (character === ")") {- if (depth === 0) break;- depth -= 1;+ if (!firstSegment.includes(" ")) {+ if (start > 0 && /[ \t]/u.test(source[start - 1])) {+ if (!spendChatLinkScanWork(budget, stats, 1)) return "exhausted";+ let previousStart = start - 1;+ let inspected = 0;+ const separator = /[\s(),!?;:,。!?;:()[\]{}<>"']/u;+ while (previousStart > 0 && inspected < CHAT_LINK_SCAN_LIMITS.maxFileCandidateCodeUnits) {+ if (!spendChatLinkScanWork(budget, stats, 1)) return "exhausted";+ inspected += 1;+ if (separator.test(source[previousStart - 1])) {+ break;+ }+ previousStart -= 1;+ }+ const previousWord = source.slice(previousStart, start - 1).toLowerCase();+ const previousLooksLikeFile = /[./\\]/u.test(previousWord) ||+ /\.[A-Za-z0-9]{1,8}(?:[+@-][\p{L}\p{N}_@+-]*)?$/u.test(previousWord) ||+ /\p{Script=Han}/u.test(previousWord);+ if (+ previousWord &&+ inspected < CHAT_LINK_SCAN_LIMITS.maxFileCandidateCodeUnits &&+ !previousLooksLikeFile &&+ !PROSE_INTRODUCERS.has(previousWord)+ ) return "skip";}+ return "accept";}- // Sentence punctuation belongs to the surrounding prose, regardless of- // whether the URL itself ends with a parenthesized path segment.- return text.slice(start, end).replace(/[.,!?;:,。!?;:]+$/u, "");+ const firstWord = firstSegment.slice(0, firstSegment.indexOf(" ")).toLowerCase();+ return PROSE_INTRODUCERS.has(firstWord) ? "retry" : "skip";}-/**- * Split plain chat text (user messages) into literal runs and previewable- * references. Unresolvable candidates stay literal text. File targets carry a- * leaf-name `label` so the transcript can render composer-like chips (D320).- */-export function splitChatText(+function splitChatTextWithBudget(text: string,root?: string | null,baseDir?: string | null,+ budget: ChatLinkScanBudget = createChatLinkScanBudget(),): ChatTextSegment[] {const segments: ChatTextSegment[] = [];let last = 0;- const scanner = new RegExp(SCAN_RE);- for (let match = scanner.exec(text); match; match = scanner.exec(text)) {- const start = match.index;- const raw = /^https?:\/\//i.test(match[0])- ? scanUrl(text, start)- : match[0];- scanner.lastIndex = start + raw.length;- if ((text[start - 1] === "~" && /^[\\/]/u.test(raw)) ||- ["~/", "~\\"].includes(text.slice(start - 2, start))) continue;- const disposition = spacedRefDisposition(raw);- if (disposition === "skip") continue;- if (disposition === "retry") {- scanner.lastIndex = start + raw.indexOf(" ") + 1;- continue;- }- const target = resolvePreviewTarget(raw, root, baseDir);- if (!target) continue;+ const { candidates } = scanChatLinkCandidates(+ text,+ budget,+ (raw) => resolvePreviewTarget(raw, root, baseDir),+ spacedRefDisposition,+ );+ for (const { start, end, raw, target } of candidates) {+ if (start < last) continue;if (start > last) segments.push({ kind: "text", text: text.slice(last, start) });const label =target.kind === "file" ? leafName(target.path) : raw;segments.push({ kind: "target", text: raw, label, target });- last = start + raw.length;+ last = end;}if (segments.length === 0) return [{ kind: "text", text }];if (last < text.length) segments.push({ kind: "text", text: text.slice(last) });return segments;}+/**+ * Split plain chat text (user messages) into literal runs and previewable+ * references. Unresolvable candidates stay literal text. File targets carry a+ * leaf-name `label` so the transcript can render composer-like chips (D320).+ */+export function splitChatText(+ text: string,+ root?: string | null,+ baseDir?: string | null,+): ChatTextSegment[] {+ return splitChatTextWithBudget(text, root, baseDir);+}+/** Minimal mdast node the markdown rewriter understands. */export type MdastNode = {type: string;@@ -401,10 +391,29 @@ export function linkifyMdastTree(root?: string | null,baseDir?: string | null,): void {+ const budget = createChatLinkScanBudget();+ const finishDiagnostic = beginRenderDiagnostic("markdown-linkify-tree");+ let inputNodeCount = 0;+ let sourceLength = 0;walk(tree, false);+ finishDiagnostic({+ inputNodeCount,+ sourceLength,+ linkCount: budget.links,+ workCodeUnits: budget.workCodeUnits,+ reason: budget.workCodeUnits >= CHAT_LINK_SCAN_LIMITS.maxScanWorkCodeUnits+ ? "scan-budget"+ : budget.links >= CHAT_LINK_SCAN_LIMITS.maxLinks+ ? "link-limit"+ : undefined,+ });function walk(node: MdastNode | null | undefined, skip: boolean) {if (!node || typeof node.type !== "string") return;+ inputNodeCount += 1;+ if ((node.type === "text" || node.type === "inlineCode") && typeof node.value === "string") {+ sourceLength += node.value.length;+ }const nextSkip = skip || SKIP_MDAST.has(node.type);if (!node.children) return;const next: MdastNode[] = [];@@ -417,12 +426,23 @@ export function linkifyMdastTree(// token must still look path-like the way the text scanner demands —// absolute or drive-letter anchored — so ordinary prose code runs// never turn into chips.- const value = child.value.trim();- const spacedPathLike = /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("/") || value.startsWith("~/");- const target =- spacedPathLike || !value.includes(" ")+ let target: ChatPreviewTarget | null = null;+ const withinBudget =+ child.value.length <= CHAT_LINK_SCAN_LIMITS.maxFileCandidateCodeUnits &&+ budget.fileCandidates < CHAT_LINK_SCAN_LIMITS.maxFileCandidates &&+ budget.links < CHAT_LINK_SCAN_LIMITS.maxLinks &&+ budget.workCodeUnits + child.value.length * 2 <=+ CHAT_LINK_SCAN_LIMITS.maxScanWorkCodeUnits;+ if (withinBudget) {+ budget.fileCandidates += 1;+ budget.workCodeUnits += child.value.length * 2;+ const value = child.value.trim();+ const spacedPathLike = /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("/") || value.startsWith("~/");+ target = spacedPathLike || !value.includes(" ")? resolvePreviewTarget(value, root, baseDir): null;+ if (target) budget.links += 1;+ }if (target) {const url =target.kind === "url"@@ -441,7 +461,7 @@ export function linkifyMdastTree(}}if (!nextSkip && child.type === "text" && typeof child.value === "string") {- const segments = splitChatText(child.value, root, baseDir);+ const segments = splitChatTextWithBudget(child.value, root, baseDir, budget);if (segments.length === 1 && segments[0].kind === "text") {next.push(child);continue;diff --git a/apps/desktop/src/lib/markdown-blocks.ts b/apps/desktop/src/lib/markdown-blocks.tsindex a46668839..59493c7cd 100644--- a/apps/desktop/src/lib/markdown-blocks.ts+++ b/apps/desktop/src/lib/markdown-blocks.ts@@ -2,6 +2,7 @@ import { unified } from "unified";import remarkParse from "remark-parse";import remarkGfm from "remark-gfm";import remarkMath from "remark-math";+import { beginRenderDiagnostic } from "./render-diagnostics.ts";// Share the grammar with ReactMarkdown. A different block lexer can split a// valid math node at a list, quote, heading, or blank line inside its TeX.@@ -165,13 +166,18 @@ export const emptyMarkdownBlockCache: MarkdownBlockCache = {export function advanceMarkdownBlocks(cache: MarkdownBlockCache,source: string,+ maxTailCodeUnits = Number.POSITIVE_INFINITY,): MarkdownBlockCache {+ const finishDiagnostic = beginRenderDiagnostic("markdown-split", {+ sourceLength: source.length,+ });const appended =cache.blocks.length > 0 &&source.length >= cache.consumed.length &&source.startsWith(cache.consumed);// Latched one-way; see above for why a stale latch costs speed, not output.if (appended && cache.singleUnit) {+ finishDiagnostic({ reason: "document-scoped-definition" });return { consumed: source, blocks: [source], singleUnit: true };}let stable: string[] = [];@@ -182,6 +188,17 @@ export function advanceMarkdownBlocks(cache.consumed.length - cache.blocks[cache.blocks.length - 1].length;tail = source.slice(lastStart);}+ // A growing unclosed block can otherwise be parsed from its first byte on+ // every streaming frame. Keep the stable prefix and render this tail raw+ // until it either closes or streaming ends.+ if (tail.length > maxTailCodeUnits) {+ finishDiagnostic({ sourceLength: tail.length, reason: "tail-limit" });+ return {+ consumed: source,+ blocks: [...stable, tail],+ singleUnit: false,+ };+ }// An unclosed math fence owns its entire body, including blank lines, so no// interior list or quote is mistaken for a completed streaming boundary.const split = tail@@ -189,5 +206,9 @@ export function advanceMarkdownBlocks(: { blocks: [], hasDocumentScopedDefinition: false };const singleUnit = split.hasDocumentScopedDefinition;const blocks = singleUnit ? [source] : [...stable, ...split.blocks];+ finishDiagnostic({+ sourceLength: tail.length,+ reason: singleUnit ? "document-scoped-definition" : undefined,+ });return { consumed: source, blocks, singleUnit };}diff --git a/apps/desktop/src/lib/render-content-limits.ts b/apps/desktop/src/lib/render-content-limits.tsnew file mode 100644index 000000000..8debca4dd--- /dev/null+++ b/apps/desktop/src/lib/render-content-limits.ts@@ -0,0 +1,54 @@+/** Bounds for work performed synchronously while rendering transcript content. */+export const MAX_SYNC_MARKDOWN_CODE_UNITS = 128 * 1024;+export const MAX_STREAMING_MARKDOWN_TAIL_CODE_UNITS = 32 * 1024;+export const MAX_SMOOTH_TEXT_CODE_UNITS = 32 * 1024;+export const MAX_HIGHLIGHT_CODE_UNITS = 100_000;+export const MAX_HIGHLIGHT_LINES = 800;+export const MAX_HIGHLIGHT_LINE_CODE_UNITS = 2_000;++export type HighlightLimitInspection = {+ within: boolean;+ lineCount: number;+ longestLine: number;+ reason?: "code-length" | "line-count" | "line-length";+};++/** Cheap raw-source guard; call before splitting, parsing, or normalizing code. */+export function inspectHighlightLimits(source: string): HighlightLimitInspection {+ if (source.length > MAX_HIGHLIGHT_CODE_UNITS) {+ return { within: false, lineCount: 0, longestLine: 0, reason: "code-length" };+ }++ let lineCount = 1;+ let lineLength = 0;+ let longestLine = 0;+ for (let index = 0; index < source.length; index += 1) {+ if (source.charCodeAt(index) === 0x0a) {+ longestLine = Math.max(longestLine, lineLength);+ lineCount += 1;+ if (lineCount > MAX_HIGHLIGHT_LINES) {+ return { within: false, lineCount, longestLine, reason: "line-count" };+ }+ lineLength = 0;+ } else {+ lineLength += 1;+ if (lineLength > MAX_HIGHLIGHT_LINE_CODE_UNITS) {+ return {+ within: false,+ lineCount,+ longestLine: Math.max(longestLine, lineLength),+ reason: "line-length",+ };+ }+ }+ }+ return {+ within: true,+ lineCount,+ longestLine: Math.max(longestLine, lineLength),+ };+}++export function isWithinHighlightLimits(source: string): boolean {+ return inspectHighlightLimits(source).within;+}diff --git a/apps/desktop/src/lib/render-diagnostics.ts b/apps/desktop/src/lib/render-diagnostics.tsnew file mode 100644index 000000000..2c93699c5--- /dev/null+++ b/apps/desktop/src/lib/render-diagnostics.ts@@ -0,0 +1,104 @@+export type RenderDiagnosticStage =+ | "chat-link-scan"+ | "markdown-linkify-tree"+ | "markdown-normalize"+ | "markdown-split"+ | "markdown-react-render"+ | "code-highlight";++export type RenderDiagnosticFields = {+ sourceLength?: number;+ longestLine?: number;+ inputNodeCount?: number;+ workCodeUnits?: number;+ linkCount?: number;+ durationMs?: number;+ baseDurationMs?: number;+ startTime?: number;+ commitTime?: number;+ reason?: string;+ renderPhase?: string;+};++export type RenderDiagnosticSample = RenderDiagnosticFields & {+ key: string;+ stage: RenderDiagnosticStage;+ phase: "start" | "end" | "complete";+ at: number;+};++const MAX_SAMPLES = 128;+const samples: RenderDiagnosticSample[] = [];+let sequence = 0;++function enabled(): boolean {+ return typeof import.meta.env !== "undefined" &&+ (import.meta.env.DEV || import.meta.env.MODE === "test");+}++function append(sample: RenderDiagnosticSample): void {+ samples.push(sample);+ if (samples.length > MAX_SAMPLES) samples.splice(0, samples.length - MAX_SAMPLES);+}++export function readRenderDiagnosticSamples(): RenderDiagnosticSample[] {+ return samples.map((sample) => ({ ...sample }));+}++export function clearRenderDiagnosticSamples(): void {+ samples.length = 0;+}++/** Start a bounded, content-free record for the current synchronous phase. */+export function beginRenderDiagnostic(+ stage: RenderDiagnosticStage,+ fields: RenderDiagnosticFields = {},+): (result?: RenderDiagnosticFields) => void {+ if (!enabled()) return () => undefined;+ const key = `render-${++sequence}`;+ const startedAt = performance.now();+ append({ key, stage, phase: "start", at: startedAt, ...fields });+ return (result = {}) => {+ const at = performance.now();+ append({+ key,+ stage,+ phase: "end",+ at,+ durationMs: at - startedAt,+ ...fields,+ ...result,+ });+ };+}++/** Add a completed render measurement supplied by React Profiler. */+export function recordRenderDiagnostic(+ stage: RenderDiagnosticStage,+ fields: RenderDiagnosticFields = {},+): void {+ if (!enabled()) return;+ append({+ key: `render-${++sequence}`,+ stage,+ phase: "complete",+ at: performance.now(),+ ...fields,+ });+}++declare global {+ interface Window {+ __piDesktopRenderDiagnostics?: {+ clear: typeof clearRenderDiagnosticSamples;+ read: typeof readRenderDiagnosticSamples;+ };+ }+}++if (enabled() && typeof window !== "undefined") {+ window.__piDesktopRenderDiagnostics = {+ clear: clearRenderDiagnosticSamples,+ read: readRenderDiagnosticSamples,+ };+}diff --git a/apps/desktop/src/lib/shiki.ts b/apps/desktop/src/lib/shiki.tsindex c3a1d999b..822f22524 100644--- a/apps/desktop/src/lib/shiki.ts+++ b/apps/desktop/src/lib/shiki.ts@@ -6,6 +6,8 @@ import type {} from "shiki/core";import { createHighlighterCore } from "shiki/core";import { createJavaScriptRegexEngine } from "shiki/engine/javascript";+import { inspectHighlightLimits } from "./render-content-limits.ts";+import { beginRenderDiagnostic } from "./render-diagnostics.ts";/** Singleton Shiki highlighter for chat code blocks.@@ -241,7 +243,18 @@ export function tokenizeIncremental(lang: string,theme: string,): LineCache | null {- if (!highlighter || !readyLangs.has(lang)) return null;+ const finishDiagnostic = beginRenderDiagnostic("code-highlight", {+ sourceLength: code.length,+ });+ if (!highlighter || !readyLangs.has(lang)) {+ finishDiagnostic({ reason: "language-unavailable" });+ return null;+ }+ const limits = inspectHighlightLimits(code);+ if (!limits.within) {+ finishDiagnostic({ longestLine: limits.longestLine, inputNodeCount: limits.lineCount, reason: limits.reason });+ return null;+ }const lines = code.split("\n");const cache =@@ -254,6 +267,11 @@ export function tokenizeIncremental(while (start < reusable && cache!.lines[start] === lines[start]) start += 1;if (cache && start === lines.length && cache.lines.length === lines.length) {+ finishDiagnostic({+ longestLine: limits.longestLine,+ inputNodeCount: lines.length,+ reason: "cache-hit",+ });return cache;}@@ -274,5 +292,6 @@ export function tokenizeIncremental(outStates.push(highlighter.getLastGrammarState(rows));}+ finishDiagnostic({ longestLine: limits.longestLine, inputNodeCount: lines.length });return { lang, theme, lines: outLines, tokens: outTokens, states: outStates };}diff --git a/apps/desktop/src/lib/tool-presentation.ts b/apps/desktop/src/lib/tool-presentation.tsindex 789c21795..b1e0bb7e6 100644--- a/apps/desktop/src/lib/tool-presentation.ts+++ b/apps/desktop/src/lib/tool-presentation.ts@@ -6,6 +6,7 @@ import {type ToolAction,} from "./tool-display";import { reviewChangeFromMessage } from "./workspace-review";+import { isWithinHighlightLimits } from "./render-content-limits";/** Structured presentation of one tool call (D192).@@ -22,8 +23,6 @@ import { reviewChangeFromMessage } from "./workspace-review";*//** Beyond this, syntax highlighting costs more than it is worth on expand. */-const MAX_HIGHLIGHT_BYTES = 100_000;-const MAX_HIGHLIGHT_LINES = 800;/** Rendered list caps; the remainder is reported, never silently dropped. */const MAX_LIST_ITEMS = 200;const DIFF_CONTEXT_LINES = 2;@@ -224,14 +223,6 @@ function rosterRows(return rows.length > 0 ? { kind: "fields", role: "details", rows } : null;}-function countLines(text: string): number {- let lines = 1;- for (let i = 0; i < text.length; i += 1) {- if (text.charCodeAt(i) === 10) lines += 1;- }- return lines;-}-/** Extension-derived Shiki tag; `resolveLang` normalizes it at render time. */export function langForPath(path: string | null): string {if (!path) return "";@@ -257,8 +248,7 @@ function codeBlock(lang,highlight:lang !== "" &&- text.length <= MAX_HIGHLIGHT_BYTES &&- countLines(text) <= MAX_HIGHLIGHT_LINES,+ isWithinHighlightLimits(text),...(extra?.tone ? { tone: extra.tone } : {}),...(extra?.label ? { label: extra.label } : {}),};diff --git a/apps/desktop/src/styles/prose.css b/apps/desktop/src/styles/prose.cssindex 51ec3095c..313021093 100644--- a/apps/desktop/src/styles/prose.css+++ b/apps/desktop/src/styles/prose.css@@ -22,6 +22,25 @@letter-spacing: var(--tracking-normal);}+.markdown-plain-fallback {+ min-width: 0;+ max-width: 100%;+}++.markdown-plain-fallback > [role="status"] {+ color: var(--ds-text-secondary);+ font-size: var(--text-sm);+ margin-bottom: 0.5rem;+}++.markdown-plain-fallback pre {+ max-width: 100%;+ overflow: auto;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ word-break: break-word;+}+.prose-chat > :first-child {margin-top: 0 !important;}diff --git a/apps/desktop/test/chat-file-reveal-menu.test.mjs b/apps/desktop/test/chat-file-reveal-menu.test.mjsindex 00deae6e6..f036b5ffa 100644--- a/apps/desktop/test/chat-file-reveal-menu.test.mjs+++ b/apps/desktop/test/chat-file-reveal-menu.test.mjs@@ -110,6 +110,10 @@ const previewTarget = loadModule("../src/hooks/use-preview-target.ts", {},"../lib/chat-links": loadModule("../src/lib/chat-links.ts", {"@pi-desktop/shared": await import("@pi-desktop/shared"),+ "./chat-link-scanner.ts": loadModule("../src/lib/chat-link-scanner.ts", {+ "./render-diagnostics.ts": { beginRenderDiagnostic: () => () => {} },+ }),+ "./render-diagnostics.ts": { beginRenderDiagnostic: () => () => {} },}),"../lib/open-http-url": { openHttpUrl: (...args) => calls.urls.push(args) },"../lib/work-panel-tabs": loadModule("../src/lib/work-panel-tabs.ts", {}),diff --git a/apps/desktop/test/chat-link-scanner-bounds.test.mjs b/apps/desktop/test/chat-link-scanner-bounds.test.mjsnew file mode 100644index 000000000..50a5b955f--- /dev/null+++ b/apps/desktop/test/chat-link-scanner-bounds.test.mjs@@ -0,0 +1,71 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ createChatLinkScanBudget,+ scanChatLinkCandidates,+} from "../src/lib/chat-link-scanner.ts";+import { linkifyMdastTree, splitChatText } from "../src/lib/chat-links.ts";++const ROOT = "/Users/dev/project";+const targets = (segments) => segments.filter((segment) => segment.kind === "target");++test("file candidates stop at 512 UTF-16 units without linking a suffix", () => {+ const max = `${"a".repeat(509)}.ts`;+ const over = `${"b".repeat(510)}.ts`;+ assert.equal(max.length, 512);+ assert.equal(over.length, 513);++ const accepted = splitChatText(`${max} ${over} safe.ts`, ROOT);+ assert.deepEqual(targets(accepted).map((segment) => segment.text), [max, "safe.ts"]);+ assert.equal(accepted.map((segment) => segment.text).join(""), `${max} ${over} safe.ts`);+});++test("long URLs remain eligible under the independent URL limit", () => {+ const url = `https://example.com/${"x".repeat(700)}.md`;+ const source = `See ${url} now`;+ const linked = targets(splitChatText(source, ROOT));+ assert.equal(linked.length, 1);+ assert.equal(linked[0].text, url);+});++test("the file candidate and link caps are independent and reconstruct source", () => {+ const source = Array.from({ length: 600 }, (_, index) => `file${index}.ts`).join(" ");+ const budget = createChatLinkScanBudget();+ const scan = scanChatLinkCandidates(source, budget, () => null, () => "accept");+ assert.equal(scan.stats.fileCandidateCount, 512);+ assert.equal(scan.stats.linkCount, 0);++ const linked = splitChatText(Array.from({ length: 400 }, (_, i) => `f${i}.ts`).join(" "), ROOT);+ assert.equal(targets(linked).length, 256);+ assert.equal(linked.map((segment) => segment.text).join(""), Array.from({ length: 400 }, (_, i) => `f${i}.ts`).join(" "));+});++test("Markdown text nodes in one tree share scan work while later trees get fresh budgets", () => {+ const source = "x".repeat(131_000);+ const firstTree = {+ type: "root",+ children: [{+ type: "paragraph",+ children: [+ { type: "text", value: source },+ { type: "text", value: " safe.ts" },+ ],+ }],+ };+ linkifyMdastTree(firstTree, ROOT);+ assert.equal(firstTree.children[0].children[1].type, "text");++ const nextTree = {+ type: "root",+ children: [{ type: "paragraph", children: [{ type: "text", value: "safe.ts" }] }],+ };+ linkifyMdastTree(nextTree, ROOT);+ assert.equal(nextTree.children[0].children[0].type, "link");+});++test("CRLF and Unicode source survive bounded linkification unchanged", () => {+ const source = "查看 报告.pdf\r\n😀 and docs/规范/架构.md";+ const linked = splitChatText(source, ROOT);+ assert.deepEqual(targets(linked).map((segment) => segment.text), ["报告.pdf", "docs/规范/架构.md"]);+ assert.equal(linked.map((segment) => segment.text).join(""), source);+});diff --git a/apps/desktop/test/chat-links-performance-worker.mjs b/apps/desktop/test/chat-links-performance-worker.mjsnew file mode 100644index 000000000..90358f367--- /dev/null+++ b/apps/desktop/test/chat-links-performance-worker.mjs@@ -0,0 +1,41 @@+import { parentPort } from "node:worker_threads";+import { createChatLinkScanBudget, scanChatLinkCandidates } from "../src/lib/chat-link-scanner.ts";+import { splitChatText } from "../src/lib/chat-links.ts";++function run(source) {+ const startedAt = performance.now();+ const budget = createChatLinkScanBudget();+ const { candidates, stats } = scanChatLinkCandidates(+ source,+ budget,+ () => null,+ () => "accept",+ );+ const segments = splitChatText(source);+ return {+ elapsedMs: performance.now() - startedAt,+ candidateCount: candidates.length,+ workCodeUnits: stats.workCodeUnits,+ reconstructed: segments.map((segment) => segment.text).join("") === source,+ };+}++parentPort.postMessage({ type: "ready" });+parentPort.on("message", ({ sizes }) => {+ const samples = sizes.map((size) => {+ const source = "a".repeat(size);+ const cold = run(source);+ const durations = Array.from({ length: 20 }, () => run(source).elapsedMs).sort((a, b) => a - b);+ return {+ size,+ coldMs: cold.elapsedMs,+ medianMs: (durations[9] + durations[10]) / 2,+ p95Ms: durations[18],+ candidateCount: cold.candidateCount,+ workCodeUnits: cold.workCodeUnits,+ reconstructed: cold.reconstructed,+ };+ });+ parentPort.postMessage({ type: "result", samples });+ parentPort.close();+});diff --git a/apps/desktop/test/chat-links-performance.test.mjs b/apps/desktop/test/chat-links-performance.test.mjsnew file mode 100644index 000000000..76d54e8b9--- /dev/null+++ b/apps/desktop/test/chat-links-performance.test.mjs@@ -0,0 +1,58 @@+import assert from "node:assert/strict";+import test from "node:test";+import { Worker } from "node:worker_threads";+import { CHAT_LINK_SCAN_LIMITS } from "../src/lib/chat-link-scanner.ts";++function nextWorkerMessage(worker, timeoutMs) {+ return new Promise((resolve, reject) => {+ const deadline = setTimeout(() => {+ void worker.terminate();+ reject(new Error(`scanner worker exceeded ${timeoutMs}ms`));+ }, timeoutMs);+ worker.once("message", (value) => {+ clearTimeout(deadline);+ resolve(value);+ });+ worker.once("error", (error) => {+ clearTimeout(deadline);+ reject(error);+ });+ worker.once("exit", (code) => {+ if (code !== 0) {+ clearTimeout(deadline);+ reject(new Error(`scanner worker exited with code ${code}`));+ }+ });+ });+}++test("production scanner stays bounded on oversized plain text in an isolated worker", { timeout: 15_000 }, async () => {+ const sizes = [5_000, 10_000, 30_000, 60_000, 100_000, 1_000_000];+ const spawnedAt = performance.now();+ const worker = new Worker(new URL("./chat-links-performance-worker.mjs", import.meta.url));+ const ready = await nextWorkerMessage(worker, 10_000);+ assert.equal(ready.type, "ready");+ const workerWarmStartMs = performance.now() - spawnedAt;++ const startedAt = performance.now();+ worker.postMessage({ sizes });+ const { samples } = await nextWorkerMessage(worker, 10_000);+ const totalMs = performance.now() - startedAt;++ assert.equal(samples.length, sizes.length);+ for (const sample of samples) {+ assert.equal(sample.reconstructed, true, `source reconstruction at ${sample.size}`);+ assert.equal(sample.candidateCount, 0);+ assert.ok(+ sample.workCodeUnits <= CHAT_LINK_SCAN_LIMITS.maxScanWorkCodeUnits,+ `scan work at ${sample.size}: ${sample.workCodeUnits}`,+ );+ assert.ok(+ sample.workCodeUnits <= sample.size * 2,+ `pre-budget scan work grew beyond the linear ceiling at ${sample.size}`,+ );+ }+ assert.ok(samples.find((sample) => sample.size === 30_000).p95Ms <= 10);+ assert.ok(samples.find((sample) => sample.size === 100_000).p95Ms <= 25);+ console.info("SCANNER_BENCHMARK", JSON.stringify({ workerWarmStartMs, totalMs, samples }));+});diff --git a/apps/desktop/test/chat-links.test.mjs b/apps/desktop/test/chat-links.test.mjsindex 5c9989974..805574cdd 100644--- a/apps/desktop/test/chat-links.test.mjs+++ b/apps/desktop/test/chat-links.test.mjs@@ -725,11 +725,15 @@ test("sentence punctuation after URLs stays outside the link", () => {);});-test("adjacent parenthesis-wrapped URLs all remain independently linkable", () => {+test("URL link creation is capped per conversion without changing source text", () => {const source = "(https://example.com)".repeat(1000);const segments = splitChatText(source, ROOT);- assert.equal(segments.filter(s => s.kind === "target").length, 1000);+ assert.equal(segments.filter(s => s.kind === "target").length, 256);assert.equal(segments.map(s => s.text).join(""), source);+ assert.equal(+ splitChatText("(https://example.com)", ROOT).filter((s) => s.kind === "target").length,+ 1,+ );});test("parseFileRefPosition keeps :line[:col] that parseFileRef strips", () => {diff --git a/apps/desktop/test/extra-attachments.test.mjs b/apps/desktop/test/extra-attachments.test.mjsnew file mode 100644index 000000000..33238e698--- /dev/null+++ b/apps/desktop/test/extra-attachments.test.mjs@@ -0,0 +1,24 @@+import assert from "node:assert/strict";+import test from "node:test";+import { getExtraMessageAttachments } from "../src/features/chat/transcript/extra-attachments.ts";++const attachments = [+ { kind: "file", name: "file.ts", ref: "docs/file.ts" },+ { kind: "image", name: "image.png", ref: "assets/image.png" },+ { kind: "session", name: "Session", ref: "session-1" },+];++test("long user text still deduplicates a later inline file against attachments", () => {+ const content = `${"a".repeat(80_000)} docs/file.ts`;+ assert.deepEqual(getExtraMessageAttachments(content, attachments, "/workspace"), [+ attachments[1],+ ]);+});++test("budgeted scanning preserves unresolved attachments instead of dropping them", () => {+ const content = `${"a".repeat(140_000)} docs/file.ts`;+ assert.deepEqual(+ getExtraMessageAttachments(content, attachments, "/workspace"),+ [attachments[0], attachments[1]],+ );+});diff --git a/apps/desktop/test/markdown-blocks.test.mjs b/apps/desktop/test/markdown-blocks.test.mjsindex 59ebfe0bc..4710900b1 100644--- a/apps/desktop/test/markdown-blocks.test.mjs+++ b/apps/desktop/test/markdown-blocks.test.mjs@@ -113,6 +113,16 @@ test("streaming an appended source splits it exactly like one full parse", () =>}});+test("oversized streaming tails remain raw while settled prefix blocks are reused", () => {+ const first = advanceMarkdownBlocks(emptyMarkdownBlockCache, "Heading\n\nFirst.", 16);+ const growing = `${first.consumed}\n\nSecond paragraph.`;+ const bounded = advanceMarkdownBlocks(first, growing, 16);+ assert.deepEqual(bounded.blocks, ["Heading\n\n", "First.\n\nSecond paragraph."]);++ const finished = advanceMarkdownBlocks(bounded, growing, Number.POSITIVE_INFINITY);+ assert.deepEqual(finished.blocks, parseMarkdownBlocks(growing).blocks);+});+test("a source that stops extending the cached one is re-decided from scratch", () => {const withDefinition = stream("See [spec].\n\n[spec]: https://example.com\n");assert.equal(withDefinition.singleUnit, true);diff --git a/apps/desktop/test/markdown-math-rendering.test.mjs b/apps/desktop/test/markdown-math-rendering.test.mjsindex f102c0d4b..aa5a6e17e 100644--- a/apps/desktop/test/markdown-math-rendering.test.mjs+++ b/apps/desktop/test/markdown-math-rendering.test.mjs@@ -36,12 +36,12 @@ test("TeX math and wrapped HTTP links render through the production Markdown piplng: "en",resources: { en: { translation: catalogs.en } },});- const render = (source) =>+ const render = (source, streaming = false) =>renderToStaticMarkup(createElement(I18nextProvider,{ i18n },- createElement(Markdown, { source }),+ createElement(Markdown, { source, streaming }),),);const display = (html) => html.includes("katex-display");@@ -93,6 +93,19 @@ test("TeX math and wrapped HTTP links render through the production Markdown pipassert.doesNotMatch(render("\\\\(escaped\\\\)"), /katex/);assert.doesNotMatch(render("text \\(unmatched"), /katex/);+ const largeMarkdown = "raw-source-".repeat(12_000);+ const largeMarkdownHtml = render(largeMarkdown);+ assert.match(largeMarkdownHtml, /role="status"/);+ assert.match(largeMarkdownHtml, /data-source-start="0"/);+ assert.match(largeMarkdownHtml, /data-source-end="132000"/);+ assert.match(largeMarkdownHtml, /<pre>raw-source-/);+ assert.doesNotMatch(largeMarkdownHtml, /<p>raw-source-/);++ const streamingMarkdownHtml = render(`# Settled\n\n${"large-tail-".repeat(3_000)}`, true);+ assert.match(streamingMarkdownHtml, /role="status"/);+ assert.match(streamingMarkdownHtml, /<pre># Settled/);+ assert.match(streamingMarkdownHtml, /large-tail-/);+// Issue #541: display math whose body puts `=`, `-`, `+` or `*` on their// own lines used to be shredded by marked's block lexer (setext headings /// list markers), which left `\[` and `\]` in different blocks so thediff --git a/apps/desktop/test/markdown-prose-style.test.mjs b/apps/desktop/test/markdown-prose-style.test.mjsindex 226e40fff..6d963da9c 100644--- a/apps/desktop/test/markdown-prose-style.test.mjs+++ b/apps/desktop/test/markdown-prose-style.test.mjs@@ -51,7 +51,9 @@ test("chat prose keeps a refined hierarchy and quieter chrome", () => {});test("markdown renderer still streams by memoized blocks", () => {- assert.match(markdownSource, /function useBlocks\(source: string\)/);+ assert.match(markdownSource, /function useBlocks\(source: string, maxTailCodeUnits: number\)/);+ assert.match(markdownSource, /advanceMarkdownBlocks\(/);+ assert.match(markdownSource, /MAX_STREAMING_MARKDOWN_TAIL_CODE_UNITS/);assert.match(markdownSource, /const markdownComponents: Components =/);assert.match(markdownSource, /className="code-block"/);assert.match(markdownSource, /className="table-wrap"/);diff --git a/apps/desktop/test/render-content-limits.test.mjs b/apps/desktop/test/render-content-limits.test.mjsnew file mode 100644index 000000000..8b707b246--- /dev/null+++ b/apps/desktop/test/render-content-limits.test.mjs@@ -0,0 +1,25 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ inspectHighlightLimits,+ isWithinHighlightLimits,+ MAX_HIGHLIGHT_CODE_UNITS,+ MAX_HIGHLIGHT_LINES,+ MAX_HIGHLIGHT_LINE_CODE_UNITS,+} from "../src/lib/render-content-limits.ts";++test("highlight boundaries are checked in UTF-16 units before splitting", () => {+ const maximumSource = ("x".repeat(999) + "\n").repeat(100);+ assert.equal(maximumSource.length, MAX_HIGHLIGHT_CODE_UNITS);+ assert.equal(isWithinHighlightLimits(maximumSource), true);+ assert.deepEqual(inspectHighlightLimits("x".repeat(MAX_HIGHLIGHT_CODE_UNITS + 1)), {+ within: false,+ lineCount: 0,+ longestLine: 0,+ reason: "code-length",+ });+ assert.equal(isWithinHighlightLimits("x".repeat(MAX_HIGHLIGHT_LINE_CODE_UNITS)), true);+ assert.equal(isWithinHighlightLimits("x".repeat(MAX_HIGHLIGHT_LINE_CODE_UNITS + 1)), false);+ assert.equal(isWithinHighlightLimits(Array.from({ length: MAX_HIGHLIGHT_LINES }, () => "x").join("\n")), true);+ assert.equal(isWithinHighlightLimits(Array.from({ length: MAX_HIGHLIGHT_LINES + 1 }, () => "x").join("\n")), false);+});diff --git a/apps/desktop/test/render-diagnostics.test.mjs b/apps/desktop/test/render-diagnostics.test.mjsnew file mode 100644index 000000000..aab18ffde--- /dev/null+++ b/apps/desktop/test/render-diagnostics.test.mjs@@ -0,0 +1,33 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createServer } from "vite";+import { fileURLToPath } from "node:url";++test("development diagnostics retain bounded content-free phase samples", async () => {+ const server = await createServer({+ root: fileURLToPath(new URL("..", import.meta.url)),+ configFile: false,+ mode: "test",+ server: { middlewareMode: true, hmr: false, ws: false },+ appType: "custom",+ optimizeDeps: { noDiscovery: true, include: [] },+ });+ try {+ const diagnostics = await server.ssrLoadModule("/src/lib/render-diagnostics.ts");+ diagnostics.clearRenderDiagnosticSamples();+ for (let index = 0; index < 100; index += 1) {+ const finish = diagnostics.beginRenderDiagnostic("chat-link-scan", {+ sourceLength: 50_000,+ inputNodeCount: 4,+ });+ finish({ workCodeUnits: 100_000, reason: index === 99 ? "scan-budget" : undefined });+ }+ const samples = diagnostics.readRenderDiagnosticSamples();+ assert.equal(samples.length, 128);+ assert.equal(samples.at(-1).reason, "scan-budget");+ assert.ok(samples.every((sample) => sample.stage === "chat-link-scan"));+ assert.doesNotMatch(JSON.stringify(samples), /secret|workspace|payload/);+ } finally {+ await server.close();+ }+});diff --git a/apps/desktop/test/session-message-presentation.test.mjs b/apps/desktop/test/session-message-presentation.test.mjsindex 621dd3f89..cc1e32dc5 100644--- a/apps/desktop/test/session-message-presentation.test.mjs+++ b/apps/desktop/test/session-message-presentation.test.mjs@@ -62,7 +62,10 @@ function loadComponent(name, extras = {}) {}const origin = loadComponent("SessionMessageOrigin");-const { MessageRow } = loadComponent("MessageRow", { "./SessionMessageOrigin": origin });+const { MessageRow } = loadComponent("MessageRow", {+ "./SessionMessageOrigin": origin,+ "./extra-attachments": { getExtraMessageAttachments: () => [] },+});const userMessage = {id: "incoming-row",role: "user",diff --git a/apps/desktop/test/session-reference-ui.test.mjs b/apps/desktop/test/session-reference-ui.test.mjsindex 6f8fc9a9c..7e2db8989 100644--- a/apps/desktop/test/session-reference-ui.test.mjs+++ b/apps/desktop/test/session-reference-ui.test.mjs@@ -16,6 +16,7 @@ import ts from "typescript";import { catalogs } from "@pi-desktop/i18n";import { formatSessionLink, isRenderableAttachment } from "@pi-desktop/shared";import { splitChatText } from "../src/lib/chat-links.ts";+import { getExtraMessageAttachments } from "../src/features/chat/transcript/extra-attachments.ts";const here = dirname(fileURLToPath(import.meta.url));register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));@@ -119,6 +120,7 @@ const { MessageRow } = load(new URL("../src/features/chat/transcript/MessageRow."./menu-items": { userMessageMenuItems: () => [] },"./ActionBarSlots": { ActionSlotSide: () => null },"./SessionMessageOrigin": { SessionMessageOrigin: () => null },+ "./extra-attachments": { getExtraMessageAttachments },"./TranscriptMenu": {useTranscriptMenu: () => () => {},useChatTextActions: () => ({ copyText: () => {}, selectText: () => {} }),diff --git a/apps/desktop/test/shiki.test.mjs b/apps/desktop/test/shiki.test.mjsindex f8c53d2d8..21b4c2105 100644--- a/apps/desktop/test/shiki.test.mjs+++ b/apps/desktop/test/shiki.test.mjs@@ -155,6 +155,26 @@ test(),extended,);+ assert.equal(+ tokenizeIncremental(+ null,+ "x".repeat(100_001),+ lang,+ themeForMode("dark"),+ ),+ null,+ "oversized code should use the plain-text render path before token splitting",+ );+ assert.equal(+ tokenizeIncremental(+ null,+ "x".repeat(2_001),+ lang,+ themeForMode("dark"),+ ),+ null,+ "an oversized single line should not reach Shiki",+ );}}},diff --git a/apps/desktop/test/tool-presentation.test.mjs b/apps/desktop/test/tool-presentation.test.mjsindex dd2cd5133..9039c7aba 100644--- a/apps/desktop/test/tool-presentation.test.mjs+++ b/apps/desktop/test/tool-presentation.test.mjs@@ -68,6 +68,22 @@ test("Read renders file content as code with a path-derived language", () => {assert.equal(content.text, "export const App = () => null;\n");});+test("Read keeps oversized or exceptionally long-line content as plain text", () => {+ for (const content of ["x".repeat(100_001), "x".repeat(2_001)]) {+ const blocks = buildToolPresentation(+ {+ toolName: "Read",+ toolArgs: { path: "src/App.tsx" },+ toolResult: envelope({ path: "src/App.tsx", content, truncated: false }),+ },+ { hideSummaryArg: true },+ );+ assert.equal(blocks[0].kind, "code");+ assert.equal(blocks[0].text, content);+ assert.equal(blocks[0].highlight, false);+ }+});+test("Write shows the written content and a size chip", () => {const message = {toolName: "Write",diff --git a/apps/desktop/test/tool-row-file-refs.test.mjs b/apps/desktop/test/tool-row-file-refs.test.mjsindex fe3cd0ea3..6a1b0c19d 100644--- a/apps/desktop/test/tool-row-file-refs.test.mjs+++ b/apps/desktop/test/tool-row-file-refs.test.mjs@@ -75,6 +75,10 @@ const { useOpenPreviewTarget } = loadModule("../src/hooks/use-preview-target.ts"},"../lib/chat-links": loadModule("../src/lib/chat-links.ts", {"@pi-desktop/shared": await import("@pi-desktop/shared"),+ "./chat-link-scanner.ts": loadModule("../src/lib/chat-link-scanner.ts", {+ "./render-diagnostics.ts": { beginRenderDiagnostic: () => () => {} },+ }),+ "./render-diagnostics.ts": { beginRenderDiagnostic: () => () => {} },}),"../lib/open-http-url": { openHttpUrl: (...args) => calls.urls.push(args) },"../lib/work-panel-tabs": workPanelTabs,diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex b08b00fe4..a83fc2708 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -2005,6 +2005,19 @@ Renderer: `apps/desktop/src/components/Markdown.tsx` + `apps/desktop/src/lib/shiacross the whole message, and footnotes also number, reuse and back-linkacross it, so the message renders as one parse context and gives up per-blockmemoization for as long as it streams.+- **Bounded large content**: transcript linkification uses one shared per-tree+ budget of 128 Ki UTF-16 code units, at most 512 file candidates and 256+ generated links; one file candidate is at most 512 code units, while URLs+ have their separate 16 Ki candidate limit. Exceeded ranges remain verbatim+ text, and each new conversion starts with a fresh budget. Markdown skips+ synchronous full-source formatting above 128 Ki code units. During streaming,+ an oversized unparsed tail stays verbatim while any trusted stable prefix+ remains formatted; a message above the full-source bound stays verbatim after+ streaming ends. The visible localized notice explains the display downgrade.+ Searchable/copyable source and source offsets continue to use the complete+ message. Smooth text release stops above 32 Ki code units. Shiki returns to+ plain text before splitting when code exceeds 100,000 code units, 800 lines,+ or a 2,000-code-unit line; tool output uses the same guard.- **Plugins**: `remark-gfm` (tables, task lists, strikethrough, autolinks),`remark-math` + `rehype-katex` (inline `$…$` or `\(…\)`, display `$$…$$`or `\[…\]`). Raw HTML isdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 80f722739..e7161ece6 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -6288,6 +6288,30 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.fails by 40.125px of content height and 40px of row movement when the reservedlane is removed (issue #323).+#### E2E-263: Native interaction stays live during large transcript streaming++- **Preconditions**: Isolated visible Electron window with the production+ `Markdown` renderer and built app stylesheet. A separate local Node fixture+ emits ordered synthetic deltas; no provider, real Host, production session,+ or user data is used.+- **Steps**: Stream a 90 Ki-code-unit unbroken message plus a final marker from+ the child process. Once the rendered message exceeds the streaming-tail+ threshold, use Electron `webContents.sendInputEvent` to click, type into the+ draft, switch to another session and back, collapse and expand the transcript,+ and scroll while deltas continue. Finish the stream and compare every received+ source code unit, sequence number, final marker, and rendered source length.+- **Expected**: Every native action is acknowledged while streaming remains+ active, each completes within 250 ms, and the action P95 is at most 100 ms on+ the recorded environment. The independent producer advances all 180 sequence+ numbers in order; switching sessions does not move or lose the background+ stream, and the finished content retains the exact received source.+- **Specs linked**: `04-ux/08-component-spec.md` §8.7.+- **Status**: Automated by `pnpm test:e2e:renderer-responsiveness`. The parent+ Electron process drives native input under an external 25-second deadline;+ the renderer cannot self-report its own timeout. The fixture is deterministic+ and offline, not an incident replay or a claim about production-session root+ cause.+#### E2E-STREAM-long-turn-keeps-realtime- **Preconditions**: Provider configured; an Agent session can run a longdiff --git a/package.json b/package.jsonindex fa2fb700c..af174af1d 100644--- a/package.json+++ b/package.json@@ -37,6 +37,7 @@"test:e2e:composer-model-selection": "node scripts/e2e-composer-model-selection.mjs","test:e2e:composer-paste": "node scripts/e2e-composer-paste.mjs","test:e2e:transcript": "node scripts/e2e-transcript-render.mjs",+ "test:e2e:renderer-responsiveness": "node scripts/e2e-renderer-responsiveness.mjs","test:e2e:transcript-minimap-jump": "node scripts/e2e-transcript-minimap-jump.mjs","test:e2e:copy-tex": "node scripts/e2e-copy-tex.mjs","test:e2e:transcript-disclosure": "node scripts/e2e-transcript-disclosure-anchor.mjs",diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex bc8f0813b..e81a8344e 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -230,6 +230,7 @@ export const de = {},"chat": {"tableActions": "Tabellenaktionen",+ "markdownPlainTextFallback": "Große Antworten werden zur besseren Reaktionsfähigkeit als Klartext angezeigt.","copyTableMarkdown": "Tabelle als Markdown kopieren","exportTableCsv": "Tabelle als CSV herunterladen","tablePreview": "Tabelle vergrößern",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 776740761..b36374fee 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -237,6 +237,7 @@ export const en = {},chat: {tableActions: "Table actions",+ markdownPlainTextFallback: "Large response shown as plain text to keep the conversation responsive.",copyTableMarkdown: "Copy table as Markdown",exportTableCsv: "Download table as CSV",tablePreview: "Expand table",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex a935cc71b..66fa3c999 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -230,6 +230,7 @@ export const es = {},"chat": {"tableActions": "Acciones de tabla",+ "markdownPlainTextFallback": "La respuesta extensa se muestra como texto sin formato para mantener la fluidez.","copyTableMarkdown": "Copiar tabla como Markdown","exportTableCsv": "Descargar tabla como CSV","tablePreview": "Ampliar tabla",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 07be0301b..e218a265a 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -230,6 +230,7 @@ export const fr = {},"chat": {"tableActions": "Actions du tableau",+ "markdownPlainTextFallback": "La réponse volumineuse est affichée en texte brut pour préserver la réactivité.","copyTableMarkdown": "Copier le tableau en Markdown","exportTableCsv": "Télécharger le tableau en CSV","tablePreview": "Agrandir le tableau",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 422a65b85..5674b9ba3 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -239,6 +239,7 @@ export const ko = {},chat: {tableActions: "표 작업",+ markdownPlainTextFallback: "긴 응답은 화면의 반응성을 유지하기 위해 일반 텍스트로 표시됩니다.",copyTableMarkdown: "표를 Markdown으로 복사",exportTableCsv: "표를 CSV로 다운로드",tablePreview: "표 확대",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 87bed5ad7..479d407a6 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -229,6 +229,7 @@ export const ptBR = {},chat: {tableActions: "Ações da tabela",+ markdownPlainTextFallback: "Respostas extensas são exibidas como texto simples para manter a interface responsiva.",copyTableMarkdown: "Copiar tabela como Markdown",exportTableCsv: "Baixar tabela como CSV",tablePreview: "Expandir tabela",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex b6782b682..c10e71371 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -239,6 +239,7 @@ export const tr = {},chat: {tableActions: "Tablo işlemleri",+ markdownPlainTextFallback: "Büyük yanıtlar arayüzün duyarlı kalması için düz metin olarak gösterilir.",copyTableMarkdown: "Tabloyu Markdown olarak kopyala",exportTableCsv: "Tabloyu CSV olarak indir",tablePreview: "Tabloyu büyüt",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 0ad6e4230..c1249d6c8 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -232,6 +232,7 @@ export const zhCN = {},chat: {tableActions: "表格操作",+ markdownPlainTextFallback: "内容较长,为保持界面响应速度,现以纯文本显示。",copyTableMarkdown: "复制表格为 Markdown",exportTableCsv: "下载表格为 CSV",tablePreview: "放大表格",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex d98259532..5c6a78750 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -232,6 +232,7 @@ export const zhTW = {},chat: {tableActions: "表格操作",+ markdownPlainTextFallback: "內容較長,為維持介面回應速度,現以純文字顯示。",copyTableMarkdown: "複製表格為 Markdown",exportTableCsv: "下載表格為 CSV",tablePreview: "放大表格",diff --git a/scripts/README.md b/scripts/README.mdindex dd837b60f..7eb7d45d0 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -59,6 +59,7 @@ The scenarios are specified in| `e2e-provider-recovery.mjs` | `node scripts/e2e-provider-recovery.mjs` | Isolated desktop with a localhost fault-injection provider: socket failures, interrupted streams, Responses recovery, exhausted retries, Continue, and recovery across eleven real Read calls. Requires a built desktop/runtime and host binary (`PI_DESKTOP_HOST_BIN` when outside the checkout); retains screenshots and JSON under `.artifacts/issue-699/` || `e2e-settings-scroll.mjs` | `pnpm test:e2e:settings-scroll` | Production Settings component navigation, search anchoring, focus-on-mount, and scroll behavior || `e2e-transcript-render.mjs` | `pnpm test:e2e:transcript` | Production transcript render boundaries, runtime status geometry, and deterministic smooth-text cadence |+| `e2e-renderer-responsiveness.mjs` | `pnpm test:e2e:renderer-responsiveness` | Native Electron click, typing, session switching, disclosure, and scroll while an isolated child process streams large transcript deltas || `e2e-config-sync-multidevice.mjs` | `pnpm test:e2e:config-sync` | Two isolated host-core devices against an ephemeral local WebDAV fixture; covers encrypted sync, new-device approval, cross-device edits, conditional requests, and ciphertext-only remote storage || `e2e-supervision.mjs` | `pnpm test:e2e:supervision` | Process supervision and restart behavior || `e2e-subagents.mjs` | `pnpm test:e2e:subagents` | Subagent registry over RPC, then through the real loader (D202) |diff --git a/scripts/e2e-copy-tex.mjs b/scripts/e2e-copy-tex.mjsindex fb421fa1c..2e55e39e7 100644--- a/scripts/e2e-copy-tex.mjs+++ b/scripts/e2e-copy-tex.mjs@@ -31,7 +31,10 @@ try {platform: "browser",format: "iife",jsx: "automatic",- define: { "process.env.NODE_ENV": '"production"' },+ define: {+ "process.env.NODE_ENV": '"production"',+ "import.meta.env": '{"DEV":false,"MODE":"production"}',+ },/*The reduction hands its clone to the platform's text serializer, so thecascade *is* the reading and this fixture has to carry the real one.diff --git a/scripts/e2e-renderer-responsiveness.mjs b/scripts/e2e-renderer-responsiveness.mjsnew file mode 100644index 000000000..2680d3b1a--- /dev/null+++ b/scripts/e2e-renderer-responsiveness.mjs@@ -0,0 +1,232 @@+#!/usr/bin/env node+/** Native Electron interaction while an isolated renderer receives large deltas. */+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createRequire } from "node:module";+import { cp, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { resolveElectronBinary } from "./e2e/boot.mjs";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const require = createRequire(join(root, "packages/agent-runtime/package.json"));+const { build } = require("esbuild");+const { electronBinary } = resolveElectronBinary(root);+const temp = await mkdtemp(join(tmpdir(), "pi-renderer-responsiveness-"));++try {+ await build({+ entryPoints: [join(root, "scripts/e2e/renderer-responsiveness.tsx")],+ outfile: join(temp, "renderer.js"),+ bundle: true,+ platform: "browser",+ format: "iife",+ jsx: "automatic",+ define: {+ "process.env.NODE_ENV": '"production"',+ "import.meta.env": '{"DEV":false,"MODE":"production"}',+ },+ loader: { ".css": "empty" },+ alias: {+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),+ react: join(root, "apps/desktop/node_modules/react"),+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),+ },+ nodePaths: [join(root, "apps/desktop/node_modules")],+ plugins: [{+ name: "local-url-assets",+ setup(build) {+ 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",+ }));+ },+ }],+ });++ const renderer = join(root, "apps/desktop/out/renderer");+ const appHtml = await readFile(join(renderer, "index.html"), "utf8");+ const css = [...appHtml.matchAll(/href="([^" ]+\.css)"/g)].map((match) => match[1]);+ assert(css.length, "Build the app with pnpm build:js before running this check");+ await cp(join(renderer, "assets"), join(temp, "assets"), { recursive: true });+ await writeFile(+ join(temp, "index.html"),+ `<!doctype html><meta charset="utf-8"><title>Renderer responsiveness</title>${css+ .map((path) => `<link rel="stylesheet" href="${path}">`)+ .join("")}<style>body{margin:0;padding:16px}header{display:flex;gap:8px}#scroll-area{height:360px;overflow:auto;border:1px solid #777;margin-top:12px}#message{min-height:600px}.markdown-plain-fallback pre{white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}</style><div id="root"></div><script src="renderer.js"></script>`,+ );++ const mainSource = `+const { app, BrowserWindow } = require("electron");+const { spawn } = require("node:child_process");+const readline = require("node:readline");+const path = require("node:path");+app.setPath("userData", path.join(__dirname, "profile"));+let windowRef;+let producer;+const timeout = setTimeout(() => fail(new Error("external interaction deadline exceeded")), 25000);+function fail(error) {+ console.error("RENDERER_RESPONSIVENESS " + JSON.stringify({ ok: false, error: error?.stack ?? String(error) }));+ try { producer?.kill(); } catch {}+ app.exit(1);+}+const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));+async function evaluate(source) {+ return windowRef.webContents.executeJavaScript(source, true);+}+async function until(predicate, label, ms = 4000) {+ const end = Date.now() + ms;+ while (Date.now() < end) {+ if (await evaluate("(() => " + predicate + ")()")) return;+ await wait(15);+ }+ throw new Error("timed out waiting for " + label);+}+async function nativeClick(id) {+ const rect = await evaluate("(() => { const r = document.getElementById(" + JSON.stringify(id) + ").getBoundingClientRect(); return { x:r.left+r.width/2, y:r.top+r.height/2 }; })()");+ windowRef.webContents.sendInputEvent({ type: "mouseMove", x: Math.round(rect.x), y: Math.round(rect.y) });+ windowRef.webContents.sendInputEvent({ type: "mouseDown", x: Math.round(rect.x), y: Math.round(rect.y), button: "left", clickCount: 1 });+ windowRef.webContents.sendInputEvent({ type: "mouseUp", x: Math.round(rect.x), y: Math.round(rect.y), button: "left", clickCount: 1 });+}+async function nativeAction(label, action, predicate) {+ const before = await evaluate("window.readRendererProbe()");+ if (!before.streaming || before.receivedSource.length < 32768) throw new Error(label + " did not start under large streaming load");+ const started = performance.now();+ await action();+ await until(predicate, label + " acknowledgement", 1500);+ const durationMs = performance.now() - started;+ if (durationMs > 250) throw new Error(label + " took " + durationMs.toFixed(1) + "ms");+ await until("window.readRendererProbe().sequence > " + before.sequence, label + " concurrent data progress", 1500);+ return { action: label, durationMs, streamingAtSend: before.streaming, sourceLengthAtSend: before.receivedSource.length };+}+app.whenReady().then(async () => {+ windowRef = new BrowserWindow({+ show: true,+ width: 1200,+ height: 900,+ resizable: false,+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false },+ });+ windowRef.on("closed", () => { windowRef = undefined; });+ windowRef.webContents.on("console-message", (event) => console.error(event.message));+ await windowRef.loadFile(path.join(__dirname, "index.html"));+ windowRef.show();+ windowRef.focus();+ await until("document.getElementById('native-action') !== null", "fixture mount");+ await evaluate("window.startRendererStream()");++ let expected = "";+ let lastSequence = 0;+ const pending = [];+ let delivery = Promise.resolve();+ let producerError;+ producer = spawn(${JSON.stringify(process.execPath)}, [${JSON.stringify(join(root, "scripts/e2e/renderer-load-producer.mjs"))}], { stdio: ["ignore", "pipe", "pipe"] });+ const lines = readline.createInterface({ input: producer.stdout });+ lines.on("line", (line) => {+ try {+ const item = JSON.parse(line);+ if (item.sequence !== lastSequence + 1) throw new Error("producer sequence gap");+ lastSequence = item.sequence;+ expected += item.delta;+ pending.push(item);+ } catch (error) { producerError = error; }+ });+ producer.stderr.on("data", (chunk) => { producerError = new Error(String(chunk)); });+ const flush = () => {+ if (!pending.length) return delivery;+ const batch = pending.splice(0);+ delivery = delivery.then(async () => {+ for (const item of batch) {+ await evaluate("window.pushRendererDelta(" + item.sequence + "," + JSON.stringify(item.delta) + ")");+ }+ });+ return delivery;+ };+ const flushTimer = setInterval(() => { void flush().catch((error) => { producerError = error; }); }, 35);+ await until("window.readRendererProbe().receivedSource.length >= 36864", "large renderer load", 6000);++ const timings = [];+ timings.push(await nativeAction("button click", () => nativeClick("native-action"), "window.readRendererProbe().nativeClicks === 1"));+ timings.push(await nativeAction("text input", async () => {+ await nativeClick("native-input");+ for (const event of [+ { type: "keyDown", keyCode: "X" },+ { type: "char", keyCode: "x" },+ { type: "keyUp", keyCode: "X" },+ ]) windowRef.webContents.sendInputEvent(event);+ }, "window.readRendererProbe().inputValue === 'x'"));+ timings.push(await nativeAction("session switch", () => nativeClick("switch-session"), "window.readRendererProbe().activeSession === 'session-b'"));+ timings.push(await nativeAction("return to streaming session", () => nativeClick("switch-session"), "window.readRendererProbe().activeSession === 'session-a'"));+ timings.push(await nativeAction("collapse transcript", () => nativeClick("toggle-collapse"), "window.readRendererProbe().collapsed === true"));+ timings.push(await nativeAction("expand transcript", () => nativeClick("toggle-collapse"), "window.readRendererProbe().collapsed === false"));+ timings.push(await nativeAction("transcript scroll", async () => {+ await nativeClick("scroll-area");+ windowRef.webContents.sendInputEvent({ type: "keyDown", keyCode: "PageDown" });+ windowRef.webContents.sendInputEvent({ type: "keyUp", keyCode: "PageDown" });+ }, "document.getElementById('scroll-area').scrollTop > 0"));+ const scrollTop = await evaluate("document.getElementById('scroll-area').scrollTop");++ const producerCode = await new Promise((resolve, reject) => {+ producer.once("error", reject);+ producer.once("close", resolve);+ });+ clearInterval(flushTimer);+ if (producerError) throw producerError;+ await flush();+ await delivery;+ if (producerCode !== 0 || lastSequence !== 180) throw new Error("independent producer did not finish all ordered deltas");+ await evaluate("window.finishRendererStream()");+ await wait(100);+ await evaluate("new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))");+ const sourceMatches = await evaluate("window.verifyRendererSource(" + JSON.stringify(expected) + ")");+ const finalSnapshot = await evaluate("({ ...window.readRendererProbe(), finalMarker: document.getElementById('message').textContent.includes('final-sequence-180') })");+ const sorted = timings.map((item) => item.durationMs).sort((a, b) => a - b);+ const p95Ms = sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * 0.95) - 1)];+ const result = {+ ok: sourceMatches && finalSnapshot.sequence === 180 && !finalSnapshot.streaming && finalSnapshot.finalMarker && scrollTop > 0 && p95Ms <= 100,+ sourceMatches,+ sequence: finalSnapshot.sequence,+ finalSourceLength: finalSnapshot.receivedSource.length,+ finalMarker: finalSnapshot.finalMarker,+ scrollTop,+ timings,+ p95Ms,+ producerCode,+ environment: { electron: process.versions.electron, chromium: process.versions.chrome, node: process.versions.node, platform: process.platform },+ };+ clearTimeout(timeout);+ console.log("RENDERER_RESPONSIVENESS " + JSON.stringify(result));+ app.quit();+}).catch(fail);+`;+ await writeFile(join(temp, "main.cjs"), mainSource);++ const env = { ...process.env };+ delete env.ELECTRON_RUN_AS_NODE;+ const child = spawn(electronBinary, [join(temp, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });+ let output = "";+ for (const stream of [child.stdout, child.stderr]) stream.on("data", (data) => { output += data; });+ const timeout = setTimeout(() => child.kill("SIGKILL"), 35_000);+ let code;+ try {+ code = await new Promise((resolve, reject) => {+ child.once("error", reject);+ child.once("close", resolve);+ });+ } finally {+ clearTimeout(timeout);+ }+ const line = output.split(/\r?\n/).find((entry) => entry.startsWith("RENDERER_RESPONSIVENESS "));+ assert(line, `Electron returned no responsiveness result (exit=${code}): ${output.slice(-4000)}`);+ const result = JSON.parse(line.slice("RENDERER_RESPONSIVENESS ".length));+ console.log("RENDERER_RESPONSIVENESS " + JSON.stringify(result));+ assert.equal(code, 0, output.slice(-6000));+ assert.equal(result.ok, true, JSON.stringify(result));+} finally {+ await rm(temp, { recursive: true, force: true });+}diff --git a/scripts/e2e-transcript-disclosure-anchor.mjs b/scripts/e2e-transcript-disclosure-anchor.mjsindex b2b1838d6..816bf6d6f 100644--- a/scripts/e2e-transcript-disclosure-anchor.mjs+++ b/scripts/e2e-transcript-disclosure-anchor.mjs@@ -35,7 +35,10 @@ try {platform: "browser",format: "iife",jsx: "automatic",- define: { "process.env.NODE_ENV": '"production"' },+ define: {+ "process.env.NODE_ENV": '"production"',+ "import.meta.env": '{"DEV":false,"MODE":"production"}',+ },// The fixture measures its own geometry, so no app stylesheet is needed.loader: { ".css": "empty" },alias: {diff --git a/scripts/e2e-transcript-render.mjs b/scripts/e2e-transcript-render.mjsindex 21e48ad58..cb417f9a2 100644--- a/scripts/e2e-transcript-render.mjs+++ b/scripts/e2e-transcript-render.mjs@@ -24,7 +24,10 @@ try {platform: "browser",format: "iife",jsx: "automatic",- define: { "process.env.NODE_ENV": '"production"', "import.meta.env.DEV": "false" },+ define: {+ "process.env.NODE_ENV": '"production"',+ "import.meta.env": '{"DEV":false,"MODE":"production"}',+ },// Styles are outside the render-count contract; component and hook code is real.loader: { ".css": "empty" },alias: {diff --git a/scripts/e2e/renderer-load-producer.mjs b/scripts/e2e/renderer-load-producer.mjsnew file mode 100644index 000000000..94a1a0c31--- /dev/null+++ b/scripts/e2e/renderer-load-producer.mjs@@ -0,0 +1,11 @@+const chunkCount = 180;+const chunkSize = 512;+let sequence = 0;+const timer = setInterval(() => {+ sequence += 1;+ const delta = sequence === chunkCount+ ? `${"a".repeat(chunkSize)}\n\n# final-sequence-${sequence}`+ : "a".repeat(chunkSize);+ process.stdout.write(`${JSON.stringify({ sequence, delta })}\n`);+ if (sequence === chunkCount) clearInterval(timer);+}, 25);diff --git a/scripts/e2e/renderer-responsiveness.tsx b/scripts/e2e/renderer-responsiveness.tsxnew file mode 100644index 000000000..ad008e6a9--- /dev/null+++ b/scripts/e2e/renderer-responsiveness.tsx@@ -0,0 +1,115 @@+import { createRoot } from "react-dom/client";+import { useState } from "react";+import { createInstance } from "i18next";+import { I18nextProvider } from "react-i18next";+import { en } from "@pi-desktop/i18n";+import { Markdown } from "../../apps/desktop/src/components/Markdown";++type Probe = {+ activeSession: "session-a" | "session-b";+ collapsed: boolean;+ inputValue: string;+ nativeClicks: number;+ receivedSource: string;+ sequence: number;+ streaming: boolean;+};++const probe: Probe = {+ activeSession: "session-a",+ collapsed: false,+ inputValue: "",+ nativeClicks: 0,+ receivedSource: "",+ sequence: 0,+ streaming: false,+};+let pushNext: ((sequence: number, delta: string) => void) | undefined;+let setStreamingState: ((streaming: boolean) => void) | undefined;++declare global {+ interface Window {+ finishRendererStream: () => void;+ pushRendererDelta: (sequence: number, delta: string) => void;+ readRendererProbe: () => Probe;+ startRendererStream: () => void;+ verifyRendererSource: (expected: string) => boolean;+ }+}++function Fixture() {+ const [activeSession, setActiveSession] = useState<Probe["activeSession"]>("session-a");+ const [sources, setSources] = useState({ "session-a": "", "session-b": "" });+ const [streaming, setStreaming] = useState(false);+ const [collapsed, setCollapsed] = useState(false);+ const [inputValue, setInputValue] = useState("");+ pushNext = (sequence, delta) => {+ if (sequence !== probe.sequence + 1) throw new Error(`out-of-order fixture delta ${sequence}`);+ probe.sequence = sequence;+ probe.receivedSource += delta;+ setSources((current) => ({ ...current, "session-a": current["session-a"] + delta }));+ };+ setStreamingState = (value) => {+ probe.streaming = value;+ setStreaming(value);+ };++ const toggleSession = () => {+ const next = activeSession === "session-a" ? "session-b" : "session-a";+ probe.activeSession = next;+ setActiveSession(next);+ };+ const toggleCollapsed = () => {+ const next = !collapsed;+ probe.collapsed = next;+ setCollapsed(next);+ };++ return (+ <main>+ <header>+ <button id="native-action" onClick={() => { probe.nativeClicks += 1; }}>Native action</button>+ <input+ id="native-input"+ aria-label="Draft"+ value={inputValue}+ onChange={(event) => {+ probe.inputValue = event.target.value;+ setInputValue(event.target.value);+ }}+ />+ <button id="switch-session" onClick={toggleSession}>Switch session</button>+ <button id="toggle-collapse" aria-expanded={!collapsed} onClick={toggleCollapsed}>+ {collapsed ? "Expand" : "Collapse"}+ </button>+ </header>+ <p id="load-state" data-streaming={streaming} data-sequence={probe.sequence}>+ {streaming ? "Streaming" : "Complete"} {probe.sequence}+ </p>+ <section id="scroll-area" aria-label="Transcript" tabIndex={0}>+ <div id="message" data-source-length={sources[activeSession].length}>+ {!collapsed && sources[activeSession] ? (+ <div className="prose-chat">+ <Markdown source={sources[activeSession]} streaming={streaming && activeSession === "session-a"} />+ </div>+ ) : null}+ </div>+ </section>+ </main>+ );+}++const i18n = createInstance();+void i18n.init({ lng: "en", resources: { en: { translation: en } } }).then(() => {+ createRoot(document.getElementById("root")!).render(+ <I18nextProvider i18n={i18n}><Fixture /></I18nextProvider>,+ );++ window.startRendererStream = () => setStreamingState?.(true);+ window.finishRendererStream = () => setStreamingState?.(false);+ window.pushRendererDelta = (sequence, delta) => pushNext?.(sequence, delta);+ window.readRendererProbe = () => ({ ...probe });+ window.verifyRendererSource = (expected) =>+ probe.receivedSource === expected &&+ document.querySelector("#message")?.getAttribute("data-source-length") === String(expected.length);+});diff --git a/scripts/e2e/transcript-render.tsx b/scripts/e2e/transcript-render.tsxindex fef9127ee..da4f29a75 100644--- a/scripts/e2e/transcript-render.tsx+++ b/scripts/e2e/transcript-render.tsx@@ -19,6 +19,7 @@ import { createSessionRuntime } from "../../apps/desktop/src/stores/runtime/sessimport { createEventsSlice } from "../../apps/desktop/src/stores/slices/events-slice";import type { StoreSet } from "../../apps/desktop/src/stores/slices/types";import { useSmoothText } from "../../apps/desktop/src/hooks/useSmoothText";+import { MAX_SMOOTH_TEXT_CODE_UNITS } from "../../apps/desktop/src/lib/render-content-limits";import { useAppStore } from "../../apps/desktop/src/stores/app-store";declare global {@@ -860,10 +861,18 @@ globalThis.smoothTextThrottleProbe = async () => {);flushFrame(start + 361 * frameInterval);assert(callbacks.size === 0, "smooth text kept scheduling frames after catching up");++ const largeSource = "large-stream-".repeat(Math.ceil((MAX_SMOOTH_TEXT_CODE_UNITS + 1) / 13));+ flushSync(() => updateSource(largeSource));+ await yieldToEffects();+ assert(host.textContent === largeSource, "large streaming text was not shown in full immediately");+ assert(callbacks.size === 0, "large streaming text still scheduled per-frame reveal work");return {ok: true,commits: commits.length,minimumGapMs,+ largeSourceLength: largeSource.length,+ largeSourceShownImmediately: host.textContent === largeSource,idleFramesAfterCatchUp: callbacks.size,};} finally {