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: 保留有界读取期间更新的会话缓存
geng yue81e5f136a3de
diff --git a/apps/desktop/src/stores/runtime/session-runtime.ts b/apps/desktop/src/stores/runtime/session-runtime.tsindex 8b0f7121a..92c649f29 100644--- a/apps/desktop/src/stores/runtime/session-runtime.ts+++ b/apps/desktop/src/stores/runtime/session-runtime.ts@@ -165,6 +165,7 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntime) {const active = sessionDetailLoads.get(id);if (active && options?.messageBefore === undefined) return active;+ const previous = sessionTranscriptCache.get(id);const request = api.getSession(id, options).then((detail) => {if (detail.session && options?.messageBefore === undefined) {const state = get();@@ -179,6 +180,8 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntime// would then re-serve that emptiness on every later open, and the// session could not recover without a restart.if (messages.length > 0 || !sessionReadLooksEmpty(detail.session)) {+ if (sessionTranscriptCache.get(id) !== previous &&+ !liveSessionTranscripts.has(id) && !state.runningSessions[id]) return detail;cacheSessionTranscript(id, messages, {messageStart: detail.session.messageStart ?? 0,hasMoreBefore: detail.session.hasMoreBefore === true,diff --git a/apps/desktop/test/session-transcript-empty-read.test.mjs b/apps/desktop/test/session-transcript-empty-read.test.mjsindex aee50ebe7..3675287c0 100644--- a/apps/desktop/test/session-transcript-empty-read.test.mjs+++ b/apps/desktop/test/session-transcript-empty-read.test.mjs@@ -76,7 +76,7 @@ test("the empty read is retried once and then recovered instead of committed", (test("the durable-read cache never stores a suspiciously empty window", () => {assert.match(sessionRuntime,- /if \(messages\.length > 0 \|\| !sessionReadLooksEmpty\(detail\.session\)\) \{\s*cacheSessionTranscript\(/,+ /if \(messages\.length > 0 \|\| !sessionReadLooksEmpty\(detail\.session\)\) \{[\s\S]{0,240}?cacheSessionTranscript\(/,"hover prefetch shares this cache boundary and must not poison it",);});diff --git a/apps/desktop/test/session-window-cache-race.test.mjs b/apps/desktop/test/session-window-cache-race.test.mjsnew file mode 100644index 000000000..94dfe67b2--- /dev/null+++ b/apps/desktop/test/session-window-cache-race.test.mjs@@ -0,0 +1,46 @@+import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const { createSessionRuntime } = await import("../src/stores/runtime/session-runtime.ts");+const { api } = await import("../src/lib/api.ts");++test("a late bounded session read preserves a newer idle edit cache", async t => {+ const old = [{ id: "answer", role: "assistant", content: "before edit" }];+ const edited = [{ ...old[0], content: "after edit" }];+ const state = { activeSessionId: "other", retainedTranscripts: {}, runningSessions: {} };+ const runtime = createSessionRuntime({ get: () => state, set() {} });+ runtime.cacheSessionTranscript("session", old, { messageStart: 10, hasMoreBefore: true });+ let finish;+ t.mock.method(api, "getSession", () => new Promise(resolve => { finish = resolve; }));+ const pending = runtime.loadSessionDetail("session", { messageLimit: 100, contentLimit: 65536 });+ runtime.cacheSessionTranscript("session", edited, { messageStart: 0, hasMoreBefore: false });+ finish({ session: { id: "session", messages: old, messageStart: 10, hasMoreBefore: true } });+ assert.deepEqual((await pending).session.messages, old, "the reader still receives its response");+ assert.equal(runtime.sessionTranscriptCache.get("session"), edited);+ assert.deepEqual(runtime.sessionHistoryCache.get("session"), { messageStart: 0, hasMoreBefore: false });+});++test("an unchanged bounded read still hydrates the transcript and its window", async t => {+ const state = { retainedTranscripts: {}, runningSessions: {} };+ const runtime = createSessionRuntime({ get: () => state, set() {} });+ const messages = [{ id: "answer", role: "assistant", content: "saved answer" }];+ t.mock.method(api, "getSession", async () => ({ session: { id: "session", messages, messageStart: 5, hasMoreBefore: true } }));+ await runtime.loadSessionDetail("session", { messageLimit: 100, contentLimit: 65536 });+ assert.deepEqual(runtime.sessionTranscriptCache.get("session"), messages);+ assert.deepEqual(runtime.sessionHistoryCache.get("session"), { messageStart: 5, hasMoreBefore: true, contentLimited: true });+});++test("live session reads still merge a streamed tail rather than discarding it", async t => {+ const saved = { id: "prompt", role: "user", content: "question" };+ const streamed = { id: "live", role: "assistant", content: "partial", status: "streaming" };+ const state = { retainedTranscripts: {}, runningSessions: { session: true } };+ const runtime = createSessionRuntime({ get: () => state, set() {} });+ let finish;+ t.mock.method(api, "getSession", () => new Promise(resolve => { finish = resolve; }));+ const reading = runtime.loadSessionDetail("session", { messageLimit: 100 });+ runtime.cacheSessionTranscript("session", [saved, streamed]);+ finish({ session: { id: "session", messages: [saved] } });+ await reading;+ assert.deepEqual(runtime.sessionTranscriptCache.get("session"), [saved, streamed]);+});diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 1c42236c6..3b2cd1fae 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1,5 +1,7 @@# 08. Component Spec+A bounded session detail read must not overwrite an idle transcript cache changed while that read was pending. Keep its newer messages and history window together. Running sessions still merge unflushed live rows, and the requesting caller receives its own read response (Refs #2086).+A full transcript read may fill its session cache only when that cache has notchanged during the request. New streaming or edit snapshots retain ownership;the caller still receives the requested history for its own action validation.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex f7347948c..7b3c7ac97 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1,5 +1,9 @@# 04. E2E Test Plan+### E2E-TRANSCRIPT-window-cache-edit-race++Hold a bounded production session read, publish an idle edit cache with a different history window, then return the older window. Navigate/render from cache and observe the edited content. Also cover unchanged hydration and running live-tail merge. `session-window-cache-race.test.mjs` exercises the runtime API; `e2e-session-window-cache-race.mjs` renders the recovered snapshot through production MessageRow in real Electron. The API is controlled and no provider executes.+### E2E-EXTENSION-thinking-request-stateSet high thinking through the production extension bridge, send a prompt anddiff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 01a4366a4..b2efff498 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -1,5 +1,7 @@# 08. 组件规格+有界会话详情读取期间,空闲会话缓存发生修改时,旧读取不能覆盖新消息及其历史窗口。运行中会话继续合并未落盘的实时消息,读取调用方仍得到自己的响应(Refs #2086)。+全量会话读取仅在请求期间缓存未改变时写入该会话缓存。新的流式消息或编辑快照保留所有权;调用方仍得到读取的历史,用于独立动作校验。diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 4f7f956b8..89d5a0426 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -1,5 +1,9 @@# 04. E2E 测试 Plan+### E2E-TRANSCRIPT-window-cache-edit-race++保持生产有界会话读取,发布带新历史窗口的空闲编辑缓存,再返回旧窗口;从缓存恢复并呈现编辑后的正文。同时覆盖未变化时正常填充及运行中实时尾部合并。`session-window-cache-race.test.mjs` 验证 runtime API;`e2e-session-window-cache-race.mjs` 在真实 Electron 中使用生产 MessageRow 呈现恢复快照。仅控制 API,不执行提供商。+### E2E-EXTENSION-thinking-request-state通过生产扩展桥接设置 high,发送提示并捕获提供商流参数。真实 Agent 循环diff --git a/scripts/e2e-session-window-cache-race.mjs b/scripts/e2e-session-window-cache-race.mjsnew file mode 100644index 000000000..c5fa55a1b--- /dev/null+++ b/scripts/e2e-session-window-cache-race.mjs@@ -0,0 +1,66 @@+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { mkdtemp, readFile, cp, writeFile, rm } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { dirname, join } from 'node:path';+import { tmpdir } from 'node:os';+import { fileURLToPath } from 'node:url';+import { resolveElectronBinary } from './e2e/boot.mjs';++const root = join(dirname(fileURLToPath(import.meta.url)), '..');+const require = createRequire(join(root, 'apps/desktop/package.json'));+const { build } = require('esbuild');+const { electronBinary } = resolveElectronBinary(root);+const scratch = await mkdtemp(join(tmpdir(), 'pi-session-window-cache-race-'));+try {+ await build({+ entryPoints: [join(root, 'scripts/e2e/session-window-cache-race.tsx')],+ outfile: join(scratch, 'renderer.js'), bundle: true, platform: 'browser',+ format: 'iife', jsx: 'automatic', loader: { '.css': 'empty' },+ define: { 'process.env.NODE_ENV': '"production"', 'import.meta.env.DEV': 'false' },+ alias: {+ '@pi-desktop/shared': join(root, 'packages/shared/src/index.ts'),+ '@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(builder) {+ builder.onResolve({ filter: /\?url$/ }, ({ path, resolveDir }) => ({ path: join(resolveDir, path.slice(0, -4)), namespace: 'local-url-asset' }));+ builder.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 styles = [...appHtml.matchAll(/href="([^" ]+\.css)"/g)].map(match => match[1]);+ assert(styles.length, 'A compatible host stylesheet is required');+ await cp(join(renderer, 'assets'), join(scratch, 'assets'), { recursive: true });+ await writeFile(join(scratch, '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:"><title>session-window-cache-race</title>${styles.map(path => `<link rel="stylesheet" href="${path}">`).join('')}<body><script src="renderer.js"></script>`);+ await writeFile(join(scratch, 'main.cjs'), `+const { app, BrowserWindow } = require('electron');+const path = require('node:path');+app.setPath('userData', path.join(__dirname, 'profile'));+app.whenReady().then(async () => {+ const window = new BrowserWindow({ show: false, width: 1000, height: 800, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });+ try {+ await window.loadFile(path.join(__dirname, 'index.html'));+ const result = await window.webContents.executeJavaScript('globalThis.maintenanceProbe()');+ console.log('MAINTENANCE_RESULT ' + JSON.stringify(result));+ app.quit();+ } catch (error) { console.error(String(error?.stack ?? error)); app.exit(1); }+});`);+ const env = { ...process.env };+ delete env.ELECTRON_RUN_AS_NODE;+ const child = spawn(electronBinary, [join(scratch, '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'), 45000);+ let code;+ try { code = await new Promise((resolve, reject) => { child.once('error', reject); child.once('close', resolve); }); }+ finally { clearTimeout(timeout); }+ assert.equal(code, 0, output.slice(-5000));+ const line = output.split(/\r?\n/).find(line => line.startsWith('MAINTENANCE_RESULT '));+ assert(line, output.slice(-5000));+ assert.equal(JSON.parse(line.slice('MAINTENANCE_RESULT '.length)).ok, true);+ console.log('PASS session-window-cache-race: real Electron, production renderer/store, controlled external API');+} finally { await rm(scratch, { recursive: true, force: true }); }diff --git a/scripts/e2e/session-window-cache-race.tsx b/scripts/e2e/session-window-cache-race.tsxnew file mode 100644index 000000000..4b067a42e--- /dev/null+++ b/scripts/e2e/session-window-cache-race.tsx@@ -0,0 +1,41 @@+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import { createInstance } from "i18next";+import { I18nextProvider } from "react-i18next";+import { en } from "@pi-desktop/i18n";+import { IPC, type UiMessage } from "@pi-desktop/shared";+import { createSessionRuntime } from "../../apps/desktop/src/stores/runtime/session-runtime";+import { useAppStore } from "../../apps/desktop/src/stores/app-store";+import { MessageRow } from "../../apps/desktop/src/features/chat/transcript/MessageRow";++const i18n = createInstance();+function assert(value: unknown, message: string): asserts value { if (!value) throw new Error(message); }+const settle = () => new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));+function Fixture() { const messages = useAppStore(state => state.messages); return <I18nextProvider i18n={i18n}>{messages.map(message => <MessageRow key={message.id} message={message} isRunning={false} />)}</I18nextProvider>; }+Object.assign(globalThis, { maintenanceProbe: async () => {+ await i18n.init({ lng: "en", resources: { en: { translation: en } }, interpolation: { escapeValue: false } });+ const sessionId = "cache-fixture";+ const original: UiMessage[] = [{ id: "prompt", role: "user", content: "original fixture", createdAt: "2026-01-01T00:00:00Z" }];+ const edited: UiMessage[] = [{ ...original[0]!, content: "edited fixture" }];+ useAppStore.setState({ activeSessionId: "other", runningSessions: {}, retainedTranscripts: {}, messages: [] });+ const runtime = createSessionRuntime({ get: useAppStore.getState, set: useAppStore.setState });+ runtime.cacheSessionTranscript(sessionId, original);+ let finish!: () => void;+ const gate = new Promise<void>(resolve => { finish = resolve; });+ window.piDesktop = { platform: "win32", channels: IPC, on: () => () => {}, invoke: async <T,>(channel: string) => {+ assert(channel === IPC.invoke.sessionGet, `Unexpected API ${channel}`);+ await gate; return { ok: true, data: { session: { id: sessionId, messages: original, messageStart: 8, hasMoreBefore: true } } as T };+ } };+ const reading = runtime.loadSessionDetail(sessionId, { messageLimit: 100, contentLimit: 65536 });+ runtime.cacheSessionTranscript(sessionId, edited, { messageStart: 0, hasMoreBefore: false });+ finish(); await reading;+ const recovered = runtime.sessionTranscriptCache.get(sessionId)!;+ useAppStore.setState({ activeSessionId: sessionId, messages: recovered, sessions: [{ id: sessionId, title: "Fixture", mode: "agent", permissionMode: "ask", createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z" }] });+ const host = document.createElement("div"); document.body.append(host); const root = createRoot(host);+ try {+ flushSync(() => root.render(<Fixture />)); await settle();+ assert(host.textContent?.includes("edited fixture") && !host.textContent?.includes("original fixture"), "returning to the session renders its newer edit");+ assert(runtime.sessionHistoryCache.get(sessionId)?.messageStart === 0, "new cache window remains paired with the new messages");+ return { ok: true, rendered: "edited fixture" };+ } finally { root.unmount(); host.remove(); }+} });