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 yue9ab36de45d83
diff --git a/apps/desktop/src/stores/slices/transcript-slice.ts b/apps/desktop/src/stores/slices/transcript-slice.tsindex 9075d343b..8b0aee683 100644--- a/apps/desktop/src/stores/slices/transcript-slice.ts+++ b/apps/desktop/src/stores/slices/transcript-slice.ts@@ -489,6 +489,10 @@ export function createTranscriptSlice({if (target?.source === "pi-native" || isRemoteSession(target)) {await api.abort(sessionId);runtime.submittedComposerDrafts.delete(sessionId);+ set((current) => ({+ runningSessions: { ...current.runningSessions, [sessionId]: false },+ ...(current.activeSessionId === sessionId ? { isRunning: false } : {}),+ }));// Bypass in-flight pre-abort detail reads; request settled source state.const detail = await api.getSession(sessionId);const messages = detail.session?.messages;diff --git a/apps/desktop/test/native-stop-refresh-failure.test.mjs b/apps/desktop/test/native-stop-refresh-failure.test.mjsnew file mode 100644index 000000000..04ff0fcda--- /dev/null+++ b/apps/desktop/test/native-stop-refresh-failure.test.mjs@@ -0,0 +1,31 @@+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 { createTranscriptSlice } = await import("../src/stores/slices/transcript-slice.ts");+const { createSessionRuntime } = await import("../src/stores/runtime/session-runtime.ts");+const { api } = await import("../src/lib/api.ts");++for (const source of ["pi-native", "remote"]) test(`confirmed ${source} Stop remains stopped if detail refresh fails`, async t => {+ const id = source === "remote" ? "remote:fixture" : "native-pi:fixture";+ const messages = [{ id: "answer", role: "assistant", content: "partial", status: "streaming" }];+ let state = { activeSessionId: id, sessions: [{ id, source, capabilities: { canStop: true } }], messages, isRunning: true, runningSessions: { [id]: true }, retainedTranscripts: {} };+ const access = { get: () => state, set: patch => { state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) }; } };+ const runtime = createSessionRuntime(access);+ const slice = createTranscriptSlice({ ...access, runtime });+ t.mock.method(api, "abort", async () => ({ ok: true }));+ t.mock.method(api, "getSession", async () => { throw new Error("detail disconnected"); });+ await assert.rejects(slice.abort(), /detail disconnected/);+ assert.equal(state.isRunning, false);+ assert.equal(state.runningSessions[id], false);+ assert.equal(state.messages, messages, "failed refresh preserves the known transcript");+});++test("a rejected native Stop keeps running and does not attempt a detail read", async t => {+ let state = { activeSessionId: "native-pi:fixture", sessions: [{ id: "native-pi:fixture", source: "pi-native" }], isRunning: true, runningSessions: { "native-pi:fixture": true } };+ const slice = createTranscriptSlice({ get: () => state, set: patch => { state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) }; }, runtime: { submittedComposerDrafts: new Map() } });+ t.mock.method(api, "abort", async () => { throw new Error("abort failed"); });+ t.mock.method(api, "getSession", assert.fail);+ await assert.rejects(slice.abort(), /abort failed/);+ assert.equal(state.isRunning, true);+});diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex bc0a9b98c..c4a0c514e 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 confirmed Native Pi or remote Stop updates its running flag before requesting source details. If that follow-up read fails, the session remains stopped and keeps its known transcript; the refresh error stays visible. A rejected Stop still retains running state. (Refs #1990)+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/conversation.md b/docs/spec/06-delivery/e2e/conversation.mdindex dcca1d3aa..32a8074a7 100644--- a/docs/spec/06-delivery/e2e/conversation.md+++ b/docs/spec/06-delivery/e2e/conversation.md@@ -1,5 +1,9 @@# E2E Scenarios: Conversation and Sessions+## E2E-native-stop-refresh-failure++Click the production Composer Stop button for a Native Pi source. Let abort succeed and reject the follow-up session detail read. Verify the toolbar returns to Send, the session running flag clears, the prior transcript remains, and the read error is shown. The regression also covers remote and rejected Stop. Coverage: `native-stop-refresh-failure.test.mjs` and `scripts/e2e-native-stop-refresh-failure.mjs` with real Electron, production store/toolbar and controlled API results.+> Part of the [E2E test plan](../04-e2e-test-plan.md). Sessions, transcripts, the composer, streaming, queueing, context, and review.> Scenario template, gates, and traceability live in the plan.diff --git a/scripts/e2e-native-stop-refresh-failure.mjs b/scripts/e2e-native-stop-refresh-failure.mjsnew file mode 100644index 000000000..9fd243bfe--- /dev/null+++ b/scripts/e2e-native-stop-refresh-failure.mjs@@ -0,0 +1,71 @@+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-native-stop-refresh-failure-'));+try {+ await build({+ entryPoints: [join(root, 'scripts/e2e/native-stop-refresh-failure.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'),+ } : {}),+ 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>native-stop-refresh-failure</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 native-stop-refresh-failure: real Electron, production renderer/store, controlled external API');+} finally { await rm(scratch, { recursive: true, force: true }); }diff --git a/scripts/e2e/native-stop-refresh-failure.tsx b/scripts/e2e/native-stop-refresh-failure.tsxnew file mode 100644index 000000000..d8e8113cd--- /dev/null+++ b/scripts/e2e/native-stop-refresh-failure.tsx@@ -0,0 +1,39 @@+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import { createInstance } from "i18next";+import { en } from "@pi-desktop/i18n";+import { IPC, type UiMessage } from "@pi-desktop/shared";+import { ComposerToolbar } from "../../apps/desktop/src/features/chat/composer/ComposerToolbar";+import { useComposerModelMenu } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu";+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())));+function Fixture() {+ const running = useAppStore(state => state.isRunning);+ const state = useAppStore.getState();+ const menu = useComposerModelMenu({ mode: "agent", activeSessionId: "native-pi:fixture", provider: undefined, modelId: "", thinkingProvider: undefined, thinkingLevel: "off", controlsBlocked: true, configureActiveSession: state.configureActiveSession });+ return <ComposerToolbar t={i18n.t} mode="agent" planningLive={false} thinkingLevel="off" composerPermissionMode="ask" modeOpen={false} setModeOpen={() => {}} permissionOpen={false} setPermissionOpen={() => {}} controlsBlocked localToolsAllowed={false} attachmentsAllowed={false} pasting={false} pickAndAttach={async () => {}} configureActiveSession={state.configureActiveSession} showToast={state.showToast} modelMenu={menu} modelLabel="Fixture" thinkingLabel="Off" contextUsage={null} value="" modelReady sendBlocked composerTransforms={[]} activeTransformKey={null} undoTransform={null} runComposerTransform={async () => {}} undoComposerTransform={() => {}} runActive={running} hasDraftContent={false} abort={state.abort} submit={async () => {}} />;+}+Object.assign(globalThis, { maintenanceProbe: async () => {+ await i18n.init({ lng: "en", resources: { en: { translation: en } }, interpolation: { escapeValue: false } });+ const errors: string[] = [];+ window.piDesktop = { platform: "win32", channels: IPC, on: () => () => {}, invoke: async <T,>(channel: string) => {+ if (channel === IPC.invoke.agentAbort) return { ok: true, data: { ok: true } as T };+ assert(channel === IPC.invoke.sessionGet, `Unexpected API ${channel}`);+ return { ok: false, error: { code: "NETWORK_ERROR", message: "fixture detail disconnected" } };+ } };+ const rows: UiMessage[] = [{ id: "answer", role: "assistant", content: "known native answer", status: "streaming", createdAt: "2026-01-01T00:00:00Z" }];+ useAppStore.setState({ activeSessionId: "native-pi:fixture", sessions: [{ id: "native-pi:fixture", title: "Fixture", source: "pi-native", mode: "agent", permissionMode: "ask", createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z" }], messages: rows, isRunning: true, runningSessions: { "native-pi:fixture": true }, showToast: message => { errors.push(message); } });+ const host = document.createElement("div"); document.body.append(host); const root = createRoot(host);+ try {+ flushSync(() => root.render(<Fixture />)); await settle();+ const stop = host.querySelector<HTMLButtonElement>(".stop-btn"); assert(stop, "native Stop mounts"); flushSync(() => stop.click()); await settle();+ assert(errors[0] === "fixture detail disconnected", "refresh failure remains visible");+ assert(!useAppStore.getState().isRunning && !useAppStore.getState().runningSessions["native-pi:fixture"], "confirmed Stop is preserved");+ assert(useAppStore.getState().messages[0]?.content === "known native answer", "refresh failure does not clear transcript");+ assert(!host.querySelector(".stop-btn") && host.querySelector(".send-btn"), "toolbar no longer claims the source is running");+ return { ok: true };+ } finally { root.unmount(); host.remove(); }+} });