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(chat): retain stateful Markdown while recycling prose
new-Beginnerdc3c29dee8ab
diff --git a/apps/desktop/src/features/chat/transcript/TranscriptProse.tsx b/apps/desktop/src/features/chat/transcript/TranscriptProse.tsxindex fff1c986f..4b3abc1f8 100644--- a/apps/desktop/src/features/chat/transcript/TranscriptProse.tsx+++ b/apps/desktop/src/features/chat/transcript/TranscriptProse.tsx@@ -1,7 +1,7 @@import { memo, useContext, useLayoutEffect, useRef, useState } from "react";import { Markdown } from "../../../components/Markdown";import { observeTranscriptContent } from "../../../lib/transcript-content-observer";-import { shouldMountTranscriptContent } from "../../../lib/transcript-content-window";+import { hasStatefulTranscriptContent, shouldMountTranscriptContent } from "../../../lib/transcript-content-window";import { ScopeContext } from "./disclosure-scope";/** Keep the existing prose shell and message anchors while releasing its renderer. */@@ -18,7 +18,7 @@ export const TranscriptProse = memo(function TranscriptProse({ source, streaminguseLayoutEffect(() => {const element = elementRef.current;const viewport = element?.closest<HTMLElement>(".thread-scroll");- if (!element || !viewport || streaming || !visible) return;+ if (!element || !viewport || streaming || !visible || hasStatefulTranscriptContent(source)) return;let measuredHeight: number | null = null;let measuredWidth: number | null = null;return observeTranscriptContent(element, () => {diff --git a/apps/desktop/src/lib/transcript-content-window.ts b/apps/desktop/src/lib/transcript-content-window.tsindex 5c793ca25..0284d1a81 100644--- a/apps/desktop/src/lib/transcript-content-window.ts+++ b/apps/desktop/src/lib/transcript-content-window.ts@@ -1,3 +1,9 @@+/** Fences and tables can own lazy layout, plugin state, or portalled previews. */+export function hasStatefulTranscriptContent(source: string): boolean {+ return /`{3,}|~{3,}/.test(source) ||+ /^[ \t]*\|?[ \t]*:?-+:?[ \t]*\|[ \t:|-]*$/m.test(source);+}+/** Geometry is relative to the scroll viewport, not the document. */export interface TranscriptContentGeometry {top: number;diff --git a/apps/desktop/test/transcript-content-window.test.mjs b/apps/desktop/test/transcript-content-window.test.mjsindex 760daad2a..f063e227a 100644--- a/apps/desktop/test/transcript-content-window.test.mjs+++ b/apps/desktop/test/transcript-content-window.test.mjs@@ -2,7 +2,16 @@ import assert from "node:assert/strict";import { register } from "node:module";import test from "node:test";register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));-const { shouldMountTranscriptContent } = await import("../src/lib/transcript-content-window.ts");+const { shouldMountTranscriptContent, hasStatefulTranscriptContent } = await import("../src/lib/transcript-content-window.ts");++test("structured Markdown retains lazy diagrams, plugin fences and table preview state", () => {+ for (const source of [+ "```mermaid\ngraph TD; A-->B\n```", "~~~custom-plugin\ninteractive\n~~~",+ "Name | Value\n--- | ---\nA | B", "| Name | Value |\n| :--- | ---: |\n| A | B |",+ ]) assert.equal(hasStatefulTranscriptContent(source), true, source);+ for (const source of ["A paragraph with **bold** and `inline code`.", "A | B is ordinary prose."])+ assert.equal(hasStatefulTranscriptContent(source), false, source);+});const sample = (changes = {}) => ({top: 10000, bottom: 10200, viewportHeight: 600,diff --git a/docs/adr/0130-bounded-mounted-transcript-window.md b/docs/adr/0130-bounded-mounted-transcript-window.mdindex ba100f24f..a229f1fa3 100644--- a/docs/adr/0130-bounded-mounted-transcript-window.md+++ b/docs/adr/0130-bounded-mounted-transcript-window.md@@ -174,7 +174,8 @@ and the `session.get` window contract are untouched.- **Measured prose window:** `TranscriptProse` preserves the existing prose andmessage shells. At the current width, measured offscreen prose becomes anequal-height placeholder beyond five viewport heights; it remounts within- three. Streaming, focused, selected, and search-target prose stays mounted.+ three. Streaming, focused, selected, search-target, fenced, and table content+ stays mounted so diagrams and portalled previews retain their state.Missing measurements or a changed width require rendering again rather thanguessing a height. Explicitly collapsed disclosure scopes release theirMarkdown without changing stored disclosure choices. One observer and framediff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex fc63e6459..2f3204091 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -1647,8 +1647,10 @@ Project drag/drop follows these patterns:retention buffer and restore it inside a three-screen entry buffer, keepingmeasured-height message/prose shells. Measurements must match the currentwidth; unknown geometry is rendered, not estimated. Streaming, focus,- selection, and search targets protect mounted content. Collapsed disclosure- scopes release their prose without losing explicit disclosure choices.+ selection, and search targets protect mounted content. Fenced blocks and+ tables also stay mounted because they can own diagram/plugin state or a+ portalled table preview. Collapsed disclosure scopes still release their prose+ without losing explicit disclosure choices.This bounds expensive offscreen prose, not retained data, row shells, or thesize of a single intersecting answer; it never initiates a history request.- A real upward scroll gesture starts ahead-loading within a base lead ofdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex cdeb74a51..ab45b380c 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -13754,8 +13754,11 @@ This test plan spec is accepted when:`tests/history-loading-scroll-test-cases.md`.The production `SessionPane` resource journey opens collapsed process groups,traverses both ends and the middle, and checks measured prose recycling plus- restoration of visible content without additional history requests. A separate- variant includes a 1,600-paragraph final answer. `--manual-smoke` drives the+ restoration of visible content without additional history requests.+ `node scripts/e2e-transcript-prose-state.mjs` opens a table preview and Mermaid+ source view, moves their prose offscreen and back, and verifies both states+ survive while ordinary prose still recycles.+ A separate variant includes a 1,600-paragraph final answer. `--manual-smoke` drives themanual toolbar through two 100-message pages and reset, sending 24 nativewheel events in each direction per pending page; directional movement,single-flight requests, and frame-gap p95 <= 100ms are checked. This is adiff --git a/scripts/e2e-transcript-prose-state.mjs b/scripts/e2e-transcript-prose-state.mjsnew file mode 100644index 000000000..733b3f6db--- /dev/null+++ b/scripts/e2e-transcript-prose-state.mjs@@ -0,0 +1,84 @@+#!/usr/bin/env node+/** Real Markdown state must survive transcript content recycling. No providers. */+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { createRequire } from "node:module";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { resolveElectronBinary } from "./e2e/boot.mjs";++const root = fileURLToPath(new URL("..", import.meta.url));+assert(process.env.PI_SCRATCH_DIR, "Set an isolated scratch directory");+const directory = await mkdtemp(join(process.env.PI_SCRATCH_DIR, "prose-state-"));+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");+try {+ await build({ stdin: { resolveDir: root, loader: "tsx", contents: `+import React from 'react';+import {createRoot} from 'react-dom/client';+import {flushSync} from 'react-dom';+import i18n from 'i18next';+import {initReactI18next} from 'react-i18next';+import {TranscriptProse} from './apps/desktop/src/features/chat/transcript/TranscriptProse';+const table='Name | Value\\n--- | ---\\nA | B';+const diagram='\u0060\u0060\u0060mermaid\\ngraph TD; A-->B\\n\u0060\u0060\u0060';+const texts=[table,diagram,'Ordinary **paragraph** with inline code.'];+const frame=()=>new Promise(resolve=>requestAnimationFrame(resolve));+const frames=async()=>{for(let i=0;i<8;i++)await frame()};+const check=(value,message)=>{if(!value)throw Error(message)};+const until=async(test,label)=>{const end=performance.now()+20000;while(!test()){if(performance.now()>end)throw Error(label);await frame()}};+window.proseProbe=async()=>{+ await i18n.use(initReactI18next).init({lng:'en',resources:{en:{translation:{}}}});+ flushSync(()=>createRoot(document.getElementById('root')).render(<>{texts.map((source,index)=><section className='thread-scroll' data-case={index} key={index}><div className='spacer'/><TranscriptProse source={source} streaming={false}/><div style={{height:9000}}/></section>)}</>));+ await until(()=>document.querySelector('.mermaid-action-btn[aria-pressed]'),'Mermaid did not render');+ document.querySelector('.mermaid-action-btn[aria-pressed]').click();+ await frames();+ document.querySelector('.markdown-table button:last-child').click();+ await frames();+ const dialog=document.querySelector('.markdown-table-preview');+ check(dialog,'Table preview must open');+ check(!document.querySelector('[data-case="0"] .prose-chat').contains(document.activeElement),'Preview focus must be portalled outside prose');+ for(const viewport of document.querySelectorAll('.thread-scroll')){viewport.querySelector('.spacer').style.height='8000px';viewport.dispatchEvent(new Event('scroll'))}+ await frames();+ check(dialog.isConnected,'Offscreen recycling closed an open table preview');+ check(document.querySelector('.mermaid-action-btn[aria-pressed="true"]'),'Offscreen recycling reset Mermaid source state');+ check(document.querySelector('[data-case="2"] [data-transcript-content="placeholder"]'),'Ordinary prose must still recycle');+ for(const viewport of document.querySelectorAll('.thread-scroll')){viewport.querySelector('.spacer').style.height='0px';viewport.dispatchEvent(new Event('scroll'))}+ await frames();+ check(dialog.isConnected,'Returning to content lost table preview');+ check(document.querySelector('.mermaid-action-btn[aria-pressed="true"]'),'Returning to content lost Mermaid state');+ check(document.querySelector('[data-case="2"] [data-transcript-content="mounted"]'),'Ordinary prose must remount');+ return {tablePreview:true,mermaidState:true,ordinaryProseRecycled:true};+};+` }, outfile: join(directory, "renderer.js"), bundle: true, platform: "browser", format: "esm", jsx: "automatic",+ define: { "process.env.NODE_ENV": '"production"', "import.meta.env": '{"DEV":false,"MODE":"production"}' },+ loader: { ".css": "empty" }, alias: { 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: "assets", setup(builder) {+ builder.onResolve({ filter: /\?url$/ }, ({ path, resolveDir }) => ({ path: join(resolveDir, path.slice(0, -4)), namespace: "asset" }));+ builder.onLoad({ filter: /.*/, namespace: "asset" }, async ({ path }) => ({ contents: await readFile(path), loader: "file" }));+ } }],+ });+ await writeFile(join(directory, "index.html"), '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'; font-src \'self\' data:; img-src \'self\' data:"><style>.thread-scroll{height:220px;overflow:auto;overflow-anchor:none}.markdown-table-overlay{position:fixed;inset:0}</style><div id="root"></div><script type="module" src="renderer.js"></script>');+ await writeFile(join(directory, "main.cjs"), `+const {app,BrowserWindow}=require('electron');+app.setPath('userData',require('node:path').join(__dirname,'profile'));+app.disableHardwareAcceleration();+const watchdog=setTimeout(()=>{console.error('PROSE_STATE timeout');app.exit(1)},45000);+app.whenReady().then(async()=>{+ const win=new BrowserWindow({show:true,width:1000,height:900,webPreferences:{sandbox:true,contextIsolation:true,backgroundThrottling:false}});+ win.webContents.on('console-message',event=>console.error(event.message));+ try{+ await win.loadFile(require('node:path').join(__dirname,'index.html'));+ const result=await win.webContents.executeJavaScript('globalThis.proseProbe()');+ console.log('PROSE_STATE '+JSON.stringify(result));clearTimeout(watchdog);app.exit(0);+ }catch(error){console.error(String(error));clearTimeout(watchdog);app.exit(1)}+});`);+ const env = { ...process.env }; delete env.ELECTRON_RUN_AS_NODE;+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(directory, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });+ let output = "";+ for (const stream of [child.stdout, child.stderr]) stream.on("data", chunk => { output += chunk; });+ const code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); });+ console.log(output);+ assert.equal(code, 0, "Real Markdown state regression failed");+ assert.match(output, /"ordinaryProseRecycled":true/);+} finally { await rm(directory, { recursive: true, force: true }); }