Skip to content

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

fix(renderer): page large tool output

vastsabfb17c17168a
diff --git a/apps/desktop/electron/main/bootstrap/shutdown.ts b/apps/desktop/electron/main/bootstrap/shutdown.ts
index 855e15edc..09838771c 100644
--- a/apps/desktop/electron/main/bootstrap/shutdown.ts
+++ b/apps/desktop/electron/main/bootstrap/shutdown.ts
@@ -123,6 +123,9 @@ export function registerShutdownHandlers({
}
state.quitting = true;
+ // Persist the confirmed shutdown before any awaited cleanup so a forced
+ // process termination still leaves an observable lifecycle boundary.
+ logger.app("lifecycle", "info", "app shutdown");
disposePowerSaveBlockers();
state.tray?.destroy();
state.tray = null;
@@ -164,7 +167,6 @@ export function registerShutdownHandlers({
pluginPanels.closeAll(),
pluginViews.dispose(),
]);
- logger.app("lifecycle", "info", "app shutdown");
await pluginSurfacesShutdown;
const hostShutdown = getHost()?.dispose();
const mcpShutdown = getMcpControl()?.stop();
diff --git a/apps/desktop/src/components/LargeTextPreview.tsx b/apps/desktop/src/components/LargeTextPreview.tsx
new file mode 100644
index 000000000..928db5bfa
--- /dev/null
+++ b/apps/desktop/src/components/LargeTextPreview.tsx
@@ -0,0 +1,74 @@
+import { useState, type ReactNode } from "react";
+import { useTranslation } from "react-i18next";
+import { renderedTextPage } from "../lib/render-content-limits";
+import { Button } from "./ui";
+
+export function LargeTextPreview({
+ text,
+ preClassName,
+ renderPage,
+ followLatest = false,
+}: {
+ text: string;
+ preClassName?: string;
+ renderPage?: (page: string) => ReactNode;
+ /** Keep a live output on its newest page until the reader navigates away. */
+ followLatest?: boolean;
+}) {
+ const { t } = useTranslation();
+ const [selectedPage, setSelectedPage] = useState<number | null>(() =>
+ followLatest ? null : 0,
+ );
+ const page = renderedTextPage(
+ text,
+ selectedPage ?? 0,
+ selectedPage === null,
+ );
+ const content = renderPage ? renderPage(page.text) : page.text;
+ const pre = <pre className={preClassName}>{content}</pre>;
+
+ if (page.count === 1) return pre;
+
+ const movePrevious = () => {
+ setSelectedPage(Math.max(0, page.index - 1));
+ };
+ const moveNext = () => {
+ if (page.index + 1 < page.count) {
+ const nextPage = page.index + 1;
+ setSelectedPage(followLatest && nextPage === page.count - 1 ? null : nextPage);
+ } else {
+ setSelectedPage(null);
+ }
+ };
+
+ return (
+ <div className="large-text-preview" data-page-index={page.index} data-page-count={page.count}>
+ <div className="large-text-preview-controls" role="group" aria-label={t("chat.largeTextPageControls")}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-label={t("chat.largeTextPreviousPage")}
+ disabled={page.index === 0}
+ onClick={movePrevious}
+ >
+ {t("chat.largeTextPreviousPage")}
+ </Button>
+ <span className="large-text-preview-status" role="status" aria-live="polite">
+ {t("chat.largeTextPage", { current: page.index + 1, total: page.count })}
+ </span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-label={t("chat.largeTextNextPage")}
+ disabled={page.index === page.count - 1}
+ onClick={moveNext}
+ >
+ {t("chat.largeTextNextPage")}
+ </Button>
+ </div>
+ {pre}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/components/ToolDetails.tsx b/apps/desktop/src/components/ToolDetails.tsx
index 605ae9561..7bc851997 100644
--- a/apps/desktop/src/components/ToolDetails.tsx
+++ b/apps/desktop/src/components/ToolDetails.tsx
@@ -1,5 +1,6 @@
import { useTranslation } from "react-i18next";
import { HighlightedCode, useCopy } from "./Markdown";
+import { LargeTextPreview } from "./LargeTextPreview";
import { IconCheck, IconCircleAlert, IconCopy, IconInfo } from "./icons";
import { TooltipButton, cx } from "./ui";
import { toWorkspaceRel } from "../lib/chat-links";
@@ -157,17 +158,18 @@ function MatchList({ block }: { block: Extract<ToolBlock, { kind: "matches" }> }
);
}
-function BlockBody({ block }: { block: ToolBlock }) {
+function BlockBody({ block, streaming }: { block: ToolBlock; streaming: boolean }) {
switch (block.kind) {
case "code":
return (
- <pre className={cx("tool-row-content", block.tone === "error" && "is-error")}>
- {block.highlight ? (
- <HighlightedCode code={block.text} lang={block.lang} />
- ) : (
- block.text
- )}
- </pre>
+ <LargeTextPreview
+ text={block.text}
+ followLatest={streaming}
+ preClassName={cx("tool-row-content", block.tone === "error" && "is-error")}
+ renderPage={(page) =>
+ block.highlight ? <HighlightedCode code={page} lang={block.lang} /> : page
+ }
+ />
);
case "diff":
return (
@@ -229,9 +231,11 @@ function BlockBody({ block }: { block: ToolBlock }) {
export function ToolDetailBlocks({
blocks,
plain = false,
+ streaming = false,
}: {
blocks: ToolBlock[];
plain?: boolean;
+ streaming?: boolean;
}) {
const { t } = useTranslation();
return (
@@ -251,7 +255,7 @@ export function ToolDetailBlocks({
) : (
<BlockHead label={label} copy={blockCopyText(block)} />
)}
- <BlockBody block={block} />
+ <BlockBody block={block} streaming={streaming} />
</section>
);
})}
diff --git a/apps/desktop/src/features/chat/transcript/ToolRow.tsx b/apps/desktop/src/features/chat/transcript/ToolRow.tsx
index f2fd8d17c..a0305e460 100644
--- a/apps/desktop/src/features/chat/transcript/ToolRow.tsx
+++ b/apps/desktop/src/features/chat/transcript/ToolRow.tsx
@@ -585,7 +585,7 @@ function HostToolRow({
label={t("chat.collapseToolOutput")}
onCollapse={collapseRow}
/>
- <ToolDetailBlocks blocks={blocks} plain={runHead} />
+ <ToolDetailBlocks blocks={blocks} plain={runHead} streaming={status === "running"} />
</div>
) : null}
{!imagesInTurn && <GeneratedImages message={message} />}
diff --git a/apps/desktop/src/lib/render-content-limits.ts b/apps/desktop/src/lib/render-content-limits.ts
index 8debca4dd..290d234cd 100644
--- a/apps/desktop/src/lib/render-content-limits.ts
+++ b/apps/desktop/src/lib/render-content-limits.ts
@@ -5,6 +5,50 @@ 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 const MAX_RENDERED_TEXT_PAGE_CODE_UNITS = 32 * 1024;
+
+export type RenderedTextPage = {
+ text: string;
+ index: number;
+ count: number;
+};
+
+/** Return one bounded, UTF-16-safe page from a potentially large output. */
+export function renderedTextPage(
+ source: string,
+ requestedIndex: number,
+ followLatest = false,
+): RenderedTextPage {
+ const count = Math.max(1, Math.ceil(source.length / MAX_RENDERED_TEXT_PAGE_CODE_UNITS));
+ const index = followLatest
+ ? count - 1
+ : Math.max(
+ 0,
+ Math.min(count - 1, Number.isNaN(requestedIndex) ? 0 : Math.floor(requestedIndex)),
+ );
+ const pageStart = index * MAX_RENDERED_TEXT_PAGE_CODE_UNITS;
+ const pageEnd = Math.min(source.length, pageStart + MAX_RENDERED_TEXT_PAGE_CODE_UNITS);
+ const startsWithLowSurrogate =
+ pageStart > 0 &&
+ pageStart < source.length &&
+ isLowSurrogate(source.charCodeAt(pageStart)) &&
+ isHighSurrogate(source.charCodeAt(pageStart - 1));
+ const endsWithHighSurrogate =
+ pageEnd < source.length &&
+ isLowSurrogate(source.charCodeAt(pageEnd)) &&
+ isHighSurrogate(source.charCodeAt(pageEnd - 1));
+ const start = pageStart + Number(startsWithLowSurrogate);
+ const end = pageEnd + Number(endsWithHighSurrogate);
+ return { text: source.slice(start, end), index, count };
+}
+
+function isHighSurrogate(value: number): boolean {
+ return value >= 0xd800 && value <= 0xdbff;
+}
+
+function isLowSurrogate(value: number): boolean {
+ return value >= 0xdc00 && value <= 0xdfff;
+}
export type HighlightLimitInspection = {
within: boolean;
diff --git a/apps/desktop/src/styles/messages.css b/apps/desktop/src/styles/messages.css
index be6c3d3cf..ba18005e8 100644
--- a/apps/desktop/src/styles/messages.css
+++ b/apps/desktop/src/styles/messages.css
@@ -2934,6 +2934,20 @@
word-break: break-word;
}
+.large-text-preview-controls {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 6px;
+ margin-bottom: 4px;
+}
+
+.large-text-preview-status {
+ color: var(--ds-text-muted);
+ font-size: var(--text-xs);
+ font-variant-numeric: tabular-nums;
+}
+
.tool-row-content.is-error {
background: color-mix(in oklab, var(--ds-error) 7%, transparent);
color: color-mix(in oklab, var(--ds-error) 72%, var(--ds-text-primary));
diff --git a/apps/desktop/test/render-content-limits.test.mjs b/apps/desktop/test/render-content-limits.test.mjs
index 8b707b246..2cfa3c2cf 100644
--- a/apps/desktop/test/render-content-limits.test.mjs
+++ b/apps/desktop/test/render-content-limits.test.mjs
@@ -6,6 +6,8 @@ import {
MAX_HIGHLIGHT_CODE_UNITS,
MAX_HIGHLIGHT_LINES,
MAX_HIGHLIGHT_LINE_CODE_UNITS,
+ MAX_RENDERED_TEXT_PAGE_CODE_UNITS,
+ renderedTextPage,
} from "../src/lib/render-content-limits.ts";
test("highlight boundaries are checked in UTF-16 units before splitting", () => {
@@ -23,3 +25,32 @@ test("highlight boundaries are checked in UTF-16 units before splitting", () =>
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);
});
+
+test("large text pages stay bounded and reconstruct the complete source", () => {
+ const source = `start\n${"x".repeat(MAX_RENDERED_TEXT_PAGE_CODE_UNITS * 4)}\nend`;
+ const first = renderedTextPage(source, 0);
+ const latest = renderedTextPage(source, 0, true);
+ assert.equal(first.index, 0);
+ assert.equal(first.count, 5);
+ assert.ok(first.text.length <= MAX_RENDERED_TEXT_PAGE_CODE_UNITS);
+ assert.equal(latest.index, latest.count - 1);
+ assert.ok(latest.text.endsWith("\nend"));
+ assert.equal(renderedTextPage(source, Number.NaN).index, 0);
+ assert.equal(
+ Array.from({ length: first.count }, (_, index) => renderedTextPage(source, index).text).join(""),
+ source,
+ );
+ assert.equal(renderedTextPage(source, Number.POSITIVE_INFINITY).index, first.count - 1);
+});
+
+test("large text page boundaries never split a surrogate pair", () => {
+ const prefix = "x".repeat(MAX_RENDERED_TEXT_PAGE_CODE_UNITS - 1);
+ const source = `${prefix}😀${"y".repeat(MAX_RENDERED_TEXT_PAGE_CODE_UNITS)}`;
+ const pages = Array.from(
+ { length: Math.ceil(source.length / MAX_RENDERED_TEXT_PAGE_CODE_UNITS) },
+ (_, index) => renderedTextPage(source, index).text,
+ );
+ assert.equal(pages.join(""), source);
+ assert.ok(pages.every((page) => !/^[\uDC00-\uDFFF]/.test(page)));
+ assert.ok(pages.every((page) => !/[\uD800-\uDBFF]$/.test(page)));
+});
diff --git a/apps/desktop/test/rpc-lifecycle-contract.test.mjs b/apps/desktop/test/rpc-lifecycle-contract.test.mjs
index 9703b8fdc..a087b65e6 100644
--- a/apps/desktop/test/rpc-lifecycle-contract.test.mjs
+++ b/apps/desktop/test/rpc-lifecycle-contract.test.mjs
@@ -213,6 +213,11 @@ test("app quit waits for one idempotent teardown before allowing the follow-up q
assert.match(shutdownSource, /if \(state\.shutdownComplete\) return/);
assert.match(shutdownSource, /event\.preventDefault\(\)/);
assert.match(shutdownSource, /if \(state\.shutdownPromise\) return/);
+ assert.ok(
+ shutdownSource.indexOf('logger.app("lifecycle", "info", "app shutdown")') <
+ shutdownSource.indexOf("await liveCallService?.endForLifecycle"),
+ "the confirmed shutdown boundary must be logged before awaited cleanup",
+ );
assert.ok(
shutdownSource.indexOf("event.preventDefault()") <
shutdownSource.indexOf("if (state.shutdownPromise) return"),
diff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.md
index f89357085..ac1346bf1 100644
--- a/docs/spec/03-runtime/07-process-model.md
+++ b/docs/spec/03-runtime/07-process-model.md
@@ -216,6 +216,10 @@ renderer-facing status):
## 5. Shutdown order
+After a confirmed quit, Electron Main synchronously records `app shutdown`
+before the first awaited teardown step. A force-terminated process therefore
+retains the lifecycle boundary whenever the local log write succeeds.
+
1. Reject new prompts
2. Flush the in-flight reply checkpoints, then abort active turns through the
sidecar and wait, bounded (2 s total), for their aborted final rows to
diff --git a/docs/spec/03-runtime/09-logging-and-observability.md b/docs/spec/03-runtime/09-logging-and-observability.md
index cd2eecbac..19dafbeda 100644
--- a/docs/spec/03-runtime/09-logging-and-observability.md
+++ b/docs/spec/03-runtime/09-logging-and-observability.md
@@ -138,6 +138,8 @@ record.
### Always
- app boot and shutdown;
+- the confirmed shutdown record is synchronously appended before any awaited
+ teardown; cancelling the quit does not write it;
- host/agent spawn, handshake, and unexpected exit;
- session create/delete;
- prompt accepted/aborted;
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 1518021fd..320760b0c 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -2024,7 +2024,12 @@ Renderer: `apps/desktop/src/components/Markdown.tsx` + `apps/desktop/src/lib/shi
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.
+ or a 2,000-code-unit line; tool output uses the same guard. Tool text blocks
+ longer than 32 Ki code units show one UTF-16-safe page at a time, with a
+ possible extra code unit where needed to keep a surrogate pair together, and
+ localized previous/next controls. A live output follows its latest page until
+ the reader navigates away. The tool block's Copy action still copies the full
+ result.
- **Plugins**: `remark-gfm` (tables, task lists, strikethrough, autolinks),
`remark-math` + `rehype-katex` (inline `$…$` or `\(…\)`, display `$$…$$`
or `\[…\]`). Raw HTML is
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 80b4d01bd..02424e643 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -6345,24 +6345,29 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
fails by 40.125px of content height and 40px of row movement when the reserved
lane is removed (issue #323).
-#### E2E-263: Native interaction stays live during large transcript streaming
+#### E2E-263: Native interaction stays live during large transcript and tool-output rendering
- **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.
+ `Markdown` and `ToolDetailBlocks` renderers 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**: Mount a 680 Ki-code-unit tool result, then 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, move between tool-output pages, 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.
+ stream, and the finished content retains the exact received source. The large
+ tool result exposes page controls, renders one page at a time (at most 32 Ki
+ code units plus one code unit where a surrogate pair crosses the boundary),
+ and retains its final page marker.
+- **Specs linked**: `04-ux/08-component-spec.md` §8.7, §9.6.
- **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
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 7ca6403e9..1658e5e12 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -231,6 +231,10 @@ export const de = {
"chat": {
"tableActions": "Tabellenaktionen",
"markdownPlainTextFallback": "Große Antworten werden zur besseren Reaktionsfähigkeit als Klartext angezeigt.",
+ "largeTextPageControls": "Seiten der großen Ausgabe",
+ "largeTextPage": "Abschnitt {{current}} von {{total}}",
+ "largeTextPreviousPage": "Vorheriger Abschnitt",
+ "largeTextNextPage": "Nächster Abschnitt",
"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.ts
index e4b6a1584..2f6c3b2e5 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -238,6 +238,10 @@ export const en = {
chat: {
tableActions: "Table actions",
markdownPlainTextFallback: "Large response shown as plain text to keep the conversation responsive.",
+ largeTextPageControls: "Large output pages",
+ largeTextPage: "Part {{current}} of {{total}}",
+ largeTextPreviousPage: "Previous part",
+ largeTextNextPage: "Next part",
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.ts
index 118a3d565..27d75ad00 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -231,6 +231,10 @@ export const es = {
"chat": {
"tableActions": "Acciones de tabla",
"markdownPlainTextFallback": "La respuesta extensa se muestra como texto sin formato para mantener la fluidez.",
+ "largeTextPageControls": "Páginas de la salida extensa",
+ "largeTextPage": "Parte {{current}} de {{total}}",
+ "largeTextPreviousPage": "Parte anterior",
+ "largeTextNextPage": "Parte siguiente",
"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.ts
index 231bc2c6c..17b751258 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -231,6 +231,10 @@ 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é.",
+ "largeTextPageControls": "Pages de la sortie volumineuse",
+ "largeTextPage": "Partie {{current}} sur {{total}}",
+ "largeTextPreviousPage": "Partie précédente",
+ "largeTextNextPage": "Partie suivante",
"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.ts
index 8ab395069..fabfd3d35 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -240,6 +240,10 @@ export const ko = {
chat: {
tableActions: "표 작업",
markdownPlainTextFallback: "긴 응답은 화면의 반응성을 유지하기 위해 일반 텍스트로 표시됩니다.",
+ largeTextPageControls: "대용량 출력 페이지",
+ largeTextPage: "{{total}}개 중 {{current}}번째 부분",
+ largeTextPreviousPage: "이전 부분",
+ largeTextNextPage: "다음 부분",
copyTableMarkdown: "표를 Markdown으로 복사",
exportTableCsv: "표를 CSV로 다운로드",
tablePreview: "표 확대",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 4610a8b34..84ecc9fd4 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -230,6 +230,10 @@ export const ptBR = {
chat: {
tableActions: "Ações da tabela",
markdownPlainTextFallback: "Respostas extensas são exibidas como texto simples para manter a interface responsiva.",
+ largeTextPageControls: "Páginas da saída extensa",
+ largeTextPage: "Parte {{current}} de {{total}}",
+ largeTextPreviousPage: "Parte anterior",
+ largeTextNextPage: "Próxima parte",
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.ts
index d6eaae50c..2b17c0857 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -240,6 +240,10 @@ 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.",
+ largeTextPageControls: "Büyük çıktı sayfaları",
+ largeTextPage: "{{total}} bölümden {{current}}. bölüm",
+ largeTextPreviousPage: "Önceki bölüm",
+ largeTextNextPage: "Sonraki bölüm",
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.ts
index a78bd2ef9..9277b5025 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -233,6 +233,10 @@ export const zhCN = {
chat: {
tableActions: "表格操作",
markdownPlainTextFallback: "内容较长,为保持界面响应速度,现以纯文本显示。",
+ largeTextPageControls: "大段输出分页",
+ largeTextPage: "第 {{current}} / {{total}} 部分",
+ largeTextPreviousPage: "上一部分",
+ largeTextNextPage: "下一部分",
copyTableMarkdown: "复制表格为 Markdown",
exportTableCsv: "下载表格为 CSV",
tablePreview: "放大表格",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index e89e8a776..16d7cf54f 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -233,6 +233,10 @@ export const zhTW = {
chat: {
tableActions: "表格操作",
markdownPlainTextFallback: "內容較長,為維持介面回應速度,現以純文字顯示。",
+ largeTextPageControls: "大型輸出分頁",
+ largeTextPage: "第 {{current}} / {{total}} 部分",
+ largeTextPreviousPage: "上一部分",
+ largeTextNextPage: "下一部分",
copyTableMarkdown: "複製表格為 Markdown",
exportTableCsv: "下載表格為 CSV",
tablePreview: "放大表格",
diff --git a/scripts/e2e-renderer-responsiveness.mjs b/scripts/e2e-renderer-responsiveness.mjs
index 2680d3b1a..3a4815bbd 100644
--- a/scripts/e2e-renderer-responsiveness.mjs
+++ b/scripts/e2e-renderer-responsiveness.mjs
@@ -55,10 +55,10 @@ try {
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"),
+ 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>`,
+ .join("")}<style>body{margin:0;padding:16px}header{display:flex;gap:8px}#large-tool-result,#streaming-tool-result{max-height:200px;overflow:auto}#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 = `
@@ -85,7 +85,8 @@ async function until(predicate, label, ms = 4000) {
if (await evaluate("(() => " + predicate + ")()")) return;
await wait(15);
}
- throw new Error("timed out waiting for " + label);
+ const details = await evaluate("({ body: document.body.innerText.slice(0, 500), tool: document.querySelector('#large-tool-result')?.innerHTML.slice(0, 1200) })");
+ throw new Error("timed out waiting for " + label + ": " + JSON.stringify(details));
}
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 }; })()");
@@ -93,6 +94,12 @@ async function nativeClick(id) {
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 nativeClickByLabel(label, containerId) {
+ const rect = await evaluate("(() => { const root = " + JSON.stringify(containerId) + " ? document.getElementById(" + JSON.stringify(containerId) + ") : document; const e = [...root.querySelectorAll('button[aria-label]')].find(button => button.getAttribute('aria-label') === " + JSON.stringify(label) + "); if (!e) throw new Error('missing button: ' + " + JSON.stringify(label) + "); const r = e.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");
@@ -118,6 +125,8 @@ app.whenReady().then(async () => {
windowRef.show();
windowRef.focus();
await until("document.getElementById('native-action') !== null", "fixture mount");
+ await until("document.querySelector('#large-tool-result .large-text-preview[data-page-count]') !== null", "large tool output page");
+ await until("document.querySelector('#streaming-tool-result .large-text-preview[data-page-count]') !== null", "streaming tool output page");
await evaluate("window.startRendererStream()");
let expected = "";
@@ -152,6 +161,14 @@ app.whenReady().then(async () => {
const timings = [];
timings.push(await nativeAction("button click", () => nativeClick("native-action"), "window.readRendererProbe().nativeClicks === 1"));
+ const streamingToolPageCount = await evaluate("Number(document.querySelector('#streaming-tool-result .large-text-preview')?.dataset.pageCount ?? 0)");
+ timings.push(await nativeAction("previous live tool output page", () => nativeClickByLabel("Previous part", "streaming-tool-result"), "document.querySelector('#streaming-tool-result .large-text-preview')?.dataset.pageIndex === " + JSON.stringify(String(streamingToolPageCount - 2))));
+ timings.push(await nativeAction("return live tool output to newest page", () => nativeClickByLabel("Next part", "streaming-tool-result"), "document.querySelector('#streaming-tool-result .large-text-preview')?.dataset.pageIndex === " + JSON.stringify(String(streamingToolPageCount - 1))));
+ const liveDelta = String.fromCharCode(10) + ("tool-stream-line" + String.fromCharCode(10)).repeat(2048) + "streaming-tool-final-marker";
+ await evaluate("window.appendStreamingToolOutput(" + JSON.stringify(liveDelta) + ")");
+ await until("Number(document.querySelector('#streaming-tool-result .large-text-preview')?.dataset.pageIndex) === Number(document.querySelector('#streaming-tool-result .large-text-preview')?.dataset.pageCount) - 1 && document.querySelector('#streaming-tool-result .large-text-preview pre')?.textContent?.includes('streaming-tool-final-marker') === true", "newest streaming tool output page");
+ timings.push(await nativeAction("next tool output page", () => nativeClickByLabel("Next part"), "document.querySelector('#large-tool-result .large-text-preview')?.dataset.pageIndex === '1'"));
+ timings.push(await nativeAction("previous tool output page", () => nativeClickByLabel("Previous part"), "document.querySelector('#large-tool-result .large-text-preview')?.dataset.pageIndex === '0'"));
timings.push(await nativeAction("text input", async () => {
await nativeClick("native-input");
for (const event of [
@@ -164,6 +181,16 @@ app.whenReady().then(async () => {
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"));
+ const toolPageCount = await evaluate("Number(document.querySelector('#large-tool-result .large-text-preview')?.dataset.pageCount ?? 0)");
+ for (let page = 2; page <= toolPageCount; page += 1) {
+ await nativeClickByLabel("Next part");
+ await until(
+ "document.querySelector('#large-tool-result .large-text-preview')?.dataset.pageIndex === " + JSON.stringify(String(page - 1)),
+ "tool output page " + page,
+ );
+ }
+ const toolOutputTailMarker = await evaluate("document.querySelector('#large-tool-result .large-text-preview pre')?.textContent?.includes('tool-result-final-marker') === true");
+ if (!toolOutputTailMarker) throw new Error("last tool-output page lost its final marker");
timings.push(await nativeAction("transcript scroll", async () => {
await nativeClick("scroll-area");
windowRef.webContents.sendInputEvent({ type: "keyDown", keyCode: "PageDown" });
@@ -184,15 +211,16 @@ app.whenReady().then(async () => {
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 finalSnapshot = await evaluate("({ ...window.readRendererProbe(), finalMarker: document.getElementById('message').textContent.includes('final-sequence-180'), largeToolOutputPaged: window.verifyLargeToolOutput(), streamingToolTracksLatest: Number(document.querySelector('#streaming-tool-result .large-text-preview')?.dataset.pageIndex) === Number(document.querySelector('#streaming-tool-result .large-text-preview')?.dataset.pageCount) - 1 })");
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,
+ ok: sourceMatches && finalSnapshot.sequence === 180 && !finalSnapshot.streaming && finalSnapshot.finalMarker && finalSnapshot.largeToolOutputPaged && finalSnapshot.streamingToolTracksLatest && toolOutputTailMarker && scrollTop > 0 && p95Ms <= 100,
sourceMatches,
sequence: finalSnapshot.sequence,
finalSourceLength: finalSnapshot.receivedSource.length,
finalMarker: finalSnapshot.finalMarker,
+ toolOutputTailMarker,
scrollTop,
timings,
p95Ms,
diff --git a/scripts/e2e/renderer-responsiveness.tsx b/scripts/e2e/renderer-responsiveness.tsx
index ad008e6a9..d2d51b4d0 100644
--- a/scripts/e2e/renderer-responsiveness.tsx
+++ b/scripts/e2e/renderer-responsiveness.tsx
@@ -4,6 +4,10 @@ import { createInstance } from "i18next";
import { I18nextProvider } from "react-i18next";
import { en } from "@pi-desktop/i18n";
import { Markdown } from "../../apps/desktop/src/components/Markdown";
+import { ToolDetailBlocks } from "../../apps/desktop/src/components/ToolDetails";
+import { MAX_RENDERED_TEXT_PAGE_CODE_UNITS } from "../../apps/desktop/src/lib/render-content-limits";
+
+const LARGE_TOOL_RESULT = `${"tool-output-line\n".repeat(40_960)}tool-result-final-marker`;
type Probe = {
activeSession: "session-a" | "session-b";
@@ -26,14 +30,17 @@ const probe: Probe = {
};
let pushNext: ((sequence: number, delta: string) => void) | undefined;
let setStreamingState: ((streaming: boolean) => void) | undefined;
+let appendToolOutput: ((text: string) => void) | undefined;
declare global {
interface Window {
- finishRendererStream: () => void;
+ finishRendererStream: () => void;
+ appendStreamingToolOutput: (text: string) => void;
pushRendererDelta: (sequence: number, delta: string) => void;
readRendererProbe: () => Probe;
startRendererStream: () => void;
verifyRendererSource: (expected: string) => boolean;
+ verifyLargeToolOutput: () => boolean;
}
}
@@ -41,6 +48,7 @@ function Fixture() {
const [activeSession, setActiveSession] = useState<Probe["activeSession"]>("session-a");
const [sources, setSources] = useState({ "session-a": "", "session-b": "" });
const [streaming, setStreaming] = useState(false);
+ const [streamingToolOutput, setStreamingToolOutput] = useState(LARGE_TOOL_RESULT);
const [collapsed, setCollapsed] = useState(false);
const [inputValue, setInputValue] = useState("");
pushNext = (sequence, delta) => {
@@ -53,6 +61,7 @@ function Fixture() {
probe.streaming = value;
setStreaming(value);
};
+ appendToolOutput = (text) => setStreamingToolOutput((current) => current + text);
const toggleSession = () => {
const next = activeSession === "session-a" ? "session-b" : "session-a";
@@ -86,6 +95,29 @@ function Fixture() {
<p id="load-state" data-streaming={streaming} data-sequence={probe.sequence}>
{streaming ? "Streaming" : "Complete"} {probe.sequence}
</p>
+ <section id="large-tool-result" aria-label="Large tool result">
+ <ToolDetailBlocks
+ blocks={[{
+ kind: "code",
+ role: "stdout",
+ text: LARGE_TOOL_RESULT,
+ lang: "",
+ highlight: false,
+ }]}
+ />
+ </section>
+ <section id="streaming-tool-result" aria-label="Streaming tool result">
+ <ToolDetailBlocks
+ blocks={[{
+ kind: "code",
+ role: "stdout",
+ text: streamingToolOutput,
+ lang: "",
+ highlight: false,
+ }]}
+ streaming
+ />
+ </section>
<section id="scroll-area" aria-label="Transcript" tabIndex={0}>
<div id="message" data-source-length={sources[activeSession].length}>
{!collapsed && sources[activeSession] ? (
@@ -107,9 +139,17 @@ void i18n.init({ lng: "en", resources: { en: { translation: en } } }).then(() =>
window.startRendererStream = () => setStreamingState?.(true);
window.finishRendererStream = () => setStreamingState?.(false);
+ window.appendStreamingToolOutput = (text) => appendToolOutput?.(text);
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);
+ window.verifyLargeToolOutput = () => {
+ const root = document.querySelector("#large-tool-result .large-text-preview");
+ const page = root?.querySelector("pre");
+ return root?.getAttribute("data-page-count") === String(Math.ceil(LARGE_TOOL_RESULT.length / MAX_RENDERED_TEXT_PAGE_CODE_UNITS)) &&
+ root?.querySelectorAll("pre").length === 1 &&
+ Boolean(page) && page!.textContent!.length <= MAX_RENDERED_TEXT_PAGE_CODE_UNITS + 1;
+ };
});