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 yuef3c8fb1c604d
diff --git a/apps/desktop/src/stores/slices/catalog-slice.ts b/apps/desktop/src/stores/slices/catalog-slice.tsindex f6ac4bf6d..af751e2fa 100644--- a/apps/desktop/src/stores/slices/catalog-slice.ts+++ b/apps/desktop/src/stores/slices/catalog-slice.ts@@ -43,6 +43,7 @@ export function createCatalogSlice({| "openNotification"| "acknowledgeSessionOutcome"> {+ let pluginViewRefresh: object | undefined;return {rememberModel: (model) => {const recentModels = rememberModelInList(get().recentModels, model);@@ -193,10 +194,19 @@ export function createCatalogSlice({},refreshPluginViews: async () => {+ const request = {};+ pluginViewRefresh = request;+ const projectPath = get().activeProjectPath;try {- set({ pluginViews: await api.listPluginViews() });+ const pluginViews = await api.listPluginViews();+ if (pluginViewRefresh !== request || get().activeProjectPath !== projectPath) return;+ set({ pluginViews });} catch {- set({ pluginViews: [] });+ if (pluginViewRefresh === request && get().activeProjectPath === projectPath) {+ set({ pluginViews: [] });+ }+ } finally {+ if (pluginViewRefresh === request) pluginViewRefresh = undefined;}},diff --git a/apps/desktop/test/plugin-view-refresh-order.test.mjs b/apps/desktop/test/plugin-view-refresh-order.test.mjsnew file mode 100644index 000000000..5aa5156a8--- /dev/null+++ b/apps/desktop/test/plugin-view-refresh-order.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 { createCatalogSlice } = await import("../src/stores/slices/catalog-slice.ts");+const { createCatalogRuntime } = await import("../src/stores/runtime/catalog-runtime.ts");+const { api } = await import("../src/lib/api.ts");++test("a stale project view response cannot replace the current project's view catalog", async t => {+ let state = { activeProjectPath: "/first", pluginViews: [] };+ const slice = createCatalogSlice({ catalogRuntime: createCatalogRuntime(), get: () => state, set: patch => { state = { ...state, ...patch }; } });+ const releases = [];+ t.mock.method(api, "listPluginViews", () => new Promise(resolve => releases.push(resolve)));+ const first = slice.refreshPluginViews();+ state.activeProjectPath = "/second";+ const second = slice.refreshPluginViews();+ const secondViews = [{ pluginId: "second", id: "view" }];+ releases[1](secondViews); await second;+ releases[0]([{ pluginId: "first", id: "view" }]); await first;+ assert.deepEqual(state.pluginViews, secondViews);+});++test("a project change without a replacement request cannot apply old views", async t => {+ const current = [{ pluginId: "known", id: "view" }];+ let state = { activeProjectPath: "/first", pluginViews: current };+ const slice = createCatalogSlice({ get: () => state, set: patch => { state = { ...state, ...patch }; } });+ let release;+ t.mock.method(api, "listPluginViews", () => new Promise(resolve => { release = resolve; }));+ const reading = slice.refreshPluginViews();+ state.activeProjectPath = "/second";+ release([{ pluginId: "first", id: "view" }]); await reading;+ assert.equal(state.pluginViews, current);+});++test("stale errors cannot clear a successful newer view refresh", async t => {+ let state = { activeProjectPath: "/project", pluginViews: [] };+ const slice = createCatalogSlice({ get: () => state, set: patch => { state = { ...state, ...patch }; } });+ let reject;+ t.mock.method(api, "listPluginViews", () => new Promise((_, fail) => { reject = fail; }));+ const old = slice.refreshPluginViews();+ const current = [{ pluginId: "new", id: "view" }];+ t.mock.method(api, "listPluginViews", async () => current);+ await slice.refreshPluginViews();+ reject(new Error("old failure")); await old;+ assert.deepEqual(state.pluginViews, current);+});diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex bc0a9b98c..e40b1d2cc 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+The renderer commits a project-filtered plugin view refresh only when it is the latest request and its project is still active. Older success or failure responses cannot replace or clear the current project's view catalog. This protects UI response ownership; it does not change service lifetime or desktop.control permissions. (Refs #2377)+Workspace file index Git queries settle at their deadline or output limit,even when inherited child pipes do not close. Composer file search and theFiles index then use the existing bounded filesystem fallback (Refs #1731).diff --git a/docs/spec/06-delivery/e2e/plugins-and-extensions.md b/docs/spec/06-delivery/e2e/plugins-and-extensions.mdindex a64310a6c..b9e64928d 100644--- a/docs/spec/06-delivery/e2e/plugins-and-extensions.md+++ b/docs/spec/06-delivery/e2e/plugins-and-extensions.md@@ -1,5 +1,9 @@# E2E Scenarios: Plugins and Extensions+## E2E-plugin-view-refresh-order++Hold the first project's plugin view request, switch projects and complete the second request, then resolve or reject the first. Verify the production WorkPanel launcher retains only the current project's views. Also switch projects without another request and reject stale writes. Coverage: `plugin-view-refresh-order.test.mjs`, view contracts and `scripts/e2e-plugin-view-refresh-order.mjs` with production WorkPanel/useAppStore in Electron. Host view results are controlled.+> Part of the [E2E test plan](../04-e2e-test-plan.md). Plugins, MCP, trusted extensions, subagents, hooks, skills, and generated UI.> Scenario template, gates, and traceability live in the plan.diff --git a/scripts/e2e-plugin-view-refresh-order.mjs b/scripts/e2e-plugin-view-refresh-order.mjsnew file mode 100644index 000000000..530234854--- /dev/null+++ b/scripts/e2e-plugin-view-refresh-order.mjs@@ -0,0 +1,77 @@+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-plugin-view-refresh-order-'));+try {+ await build({+ entryPoints: [join(root, 'scripts/e2e/plugin-view-refresh-order.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'),+ ...(process.env.PI_DESKTOP_E2E_CJK_ROOT ? {+ 'remark-cjk-friendly/parseOnly': join(process.env.PI_DESKTOP_E2E_CJK_ROOT, 'package/dist/parseOnly.js'),+ 'micromark-extension-cjk-friendly': join(process.env.PI_DESKTOP_E2E_CJK_ROOT, 'micromark-extension-cjk-friendly/package/dist/index.js'),+ 'micromark-extension-cjk-friendly-util': join(process.env.PI_DESKTOP_E2E_CJK_ROOT, 'micromark-extension-cjk-friendly-util/package/dist/index.js'),+ 'devlop': join(process.env.PI_DESKTOP_E2E_CJK_ROOT, 'devlop/package/lib/default.js'),+ 'get-east-asian-width': join(process.env.PI_DESKTOP_E2E_CJK_ROOT, 'get-east-asian-width/package/index.js'),+ 'micromark-util-character': join(process.env.PI_DESKTOP_E2E_CJK_ROOT, 'micromark-util-character/package/index.js'),+ 'micromark-util-chunked': join(process.env.PI_DESKTOP_E2E_CJK_ROOT, 'micromark-util-chunked/package/index.js'),+ 'micromark-util-resolve-all': join(process.env.PI_DESKTOP_E2E_CJK_ROOT, 'micromark-util-resolve-all/package/index.js'),+ 'micromark-util-symbol': join(process.env.PI_DESKTOP_E2E_CJK_ROOT, 'micromark-util-symbol/package/lib/default.js'),+ } : {}),+ 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>plugin-view-refresh-order</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 plugin-view-refresh-order: real Electron, production renderer/store, controlled external API');+} finally { await rm(scratch, { recursive: true, force: true }); }diff --git a/scripts/e2e/plugin-view-refresh-order.tsx b/scripts/e2e/plugin-view-refresh-order.tsxnew file mode 100644index 000000000..9f48fd3bf--- /dev/null+++ b/scripts/e2e/plugin-view-refresh-order.tsx@@ -0,0 +1,34 @@+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 PluginViewMeta } from "@pi-desktop/shared";+import { WorkPanel } from "../../apps/desktop/src/components/workpanel/WorkPanel";+import { useAppStore } from "../../apps/desktop/src/stores/app-store";++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())));+Object.assign(globalThis, { maintenanceProbe: async () => {+ await i18n.init({ lng: "en", resources: { en: { translation: en } }, interpolation: { escapeValue: false } });+ const view = (pluginId: string): PluginViewMeta => ({ pluginId, viewId: "view", ref: `${pluginId}/view`, title: `${pluginId} view`, pluginName: pluginId, order: 0 });+ const releases: Array<(views: PluginViewMeta[]) => void> = [];+ window.piDesktop = { platform: "win32", channels: IPC, on: () => () => {}, invoke: async <T,>(channel: string) => {+ assert(channel === IPC.invoke.pluginViews, `Unexpected API ${channel}`);+ return { ok: true, data: await new Promise<PluginViewMeta[]>(resolve => releases.push(resolve)) as T };+ } };+ useAppStore.setState({ activeSessionId: "fixture", activeProjectPath: "/first", pluginViews: [], workPanelOpen: true, workPanelTabs: [{ id: "new", kind: "new" }], activeWorkPanelTabId: "new", ready: false });+ const first = useAppStore.getState().refreshPluginViews();+ useAppStore.setState({ activeProjectPath: "/second" });+ const second = useAppStore.getState().refreshPluginViews();+ releases[1]!([view("second")]); await second;+ const host = document.createElement("div"); host.style.cssText = "height:700px;width:600px"; document.body.append(host); const root = createRoot(host);+ try {+ flushSync(() => root.render(<I18nextProvider i18n={i18n}><WorkPanel /></I18nextProvider>)); await settle();+ assert(host.querySelector('[data-work-panel-launcher-item="second/view"]'), "current project's view is in production launcher");+ releases[0]!([view("first")]); await first; await settle();+ assert(host.querySelector('[data-work-panel-launcher-item="second/view"]') && !host.querySelector('[data-work-panel-launcher-item="first/view"]'), "older project's views cannot replace current launcher");+ return { ok: true };+ } finally { root.unmount(); host.remove(); }+} });