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 yuecd1208a12f50
diff --git a/apps/desktop/src/stores/slices/transcript-slice.ts b/apps/desktop/src/stores/slices/transcript-slice.tsindex 9075d343b..b3aaf03e4 100644--- a/apps/desktop/src/stores/slices/transcript-slice.ts+++ b/apps/desktop/src/stores/slices/transcript-slice.ts@@ -578,6 +578,13 @@ export function createTranscriptSlice({const fullMessages = await runtime.loadFullSessionMessages(sessionId);if (!fullMessages || get().activeSessionId !== sessionId) {submittedDraft?.resolveAbort?.(false);+ if (runtime.submittedComposerDrafts.get(sessionId) === submittedDraft) {+ runtime.submittedComposerDrafts.delete(sessionId);+ }+ set((current) => ({+ runningSessions: { ...current.runningSessions, [sessionId]: false },+ isRunning: current.activeSessionId === sessionId ? false : current.isRunning,+ }));return;}const merged = mergeLiveSessionMessages(fullMessages, get().messages);@@ -680,7 +687,7 @@ export function createTranscriptSlice({current.activeSessionId === sessionId? stoppedRows(current.messages): current.messages,- isRunning: false,+ isRunning: current.activeSessionId === sessionId ? false : current.isRunning,runningSessions: { ...current.runningSessions, [sessionId]: false },}));void flushPendingSessionConfiguration(sessionId);diff --git a/apps/desktop/test/stop-navigation-running-state.test.mjs b/apps/desktop/test/stop-navigation-running-state.test.mjsnew file mode 100644index 000000000..c173cf204--- /dev/null+++ b/apps/desktop/test/stop-navigation-running-state.test.mjs@@ -0,0 +1,51 @@+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");++test("a Stop hydration finishing after navigation does not stop the visible session", async t => {+ const user = { id: "prompt", role: "user", content: "pending" };+ let state = { activeSessionId: "first", sessions: [{ id: "first" }, { id: "second" }], messages: [user], isRunning: true, runningSessions: { first: true, second: true }, pendingPermissions: {}, retainedTranscripts: {}, sessionHistory: {} };+ const access = { get: () => state, set: patch => { state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) }; } };+ const runtime = createSessionRuntime(access);+ const draft = { messageCountBeforeSend: 0, draft: { text: "pending", fileReferences: [] } };+ runtime.submittedComposerDrafts.set("first", draft);+ const slice = createTranscriptSlice({ ...access, runtime, flushPendingSessionConfiguration: async () => {} });+ t.mock.method(api, "abort", async () => ({}));+ let release;+ t.mock.method(api, "getSession", () => new Promise(resolve => { release = resolve; }));+ const stopping = slice.abort();+ while (!release) await new Promise(resolve => setImmediate(resolve));+ const secondRows = [{ id: "second-answer", role: "assistant", content: "live", status: "streaming" }];+ state = { ...state, activeSessionId: "second", messages: secondRows };+ release({ session: { messages: [user, { id: "first-answer", role: "assistant", content: "finished" }] } });+ await stopping;+ assert.equal(state.runningSessions.first, false);+ assert.equal(state.runningSessions.second, true);+ assert.equal(state.isRunning, true);+ assert.equal(state.messages, secondRows);+ assert.equal(runtime.submittedComposerDrafts.has("first"), false);+});++test("a synchronous navigation at hydration commit preserves the new session's running flag", async t => {+ const user = { id: "prompt", role: "user", content: "pending" };+ let state = { activeSessionId: "first", sessions: [{ id: "first" }], messages: [user], isRunning: true, runningSessions: { first: true, second: true }, pendingPermissions: {}, retainedTranscripts: {}, sessionHistory: {} };+ const other = [{ id: "second-answer", role: "assistant", content: "stream", status: "streaming" }];+ const access = { get: () => state, set: patch => {+ const update = typeof patch === "function" ? patch(state) : patch;+ state = { ...state, ...update };+ if (update.sessionHistory) state = { ...state, activeSessionId: "second", messages: other, isRunning: true };+ } };+ const runtime = createSessionRuntime(access);+ const actions = createTranscriptSlice({ ...access, runtime, flushPendingSessionConfiguration: async () => {} });+ t.mock.method(api, "abort", async () => ({}));+ t.mock.method(api, "getSession", async () => ({ session: { messages: [user, { id: "answer", role: "assistant", content: "finished" }] } }));+ await actions.abort();+ assert.equal(state.activeSessionId, "second");+ assert.equal(state.isRunning, true);+ assert.equal(state.messages, other);+ assert.equal(state.runningSessions.first, false);+});diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex bc0a9b98c..404c20a93 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+Composer Stop completion owns only the session that requested it. Switching to another running session while Stop hydrates history must retain that session's Stop button, transcript and running flag. The original session clears its flag and releases the matching submitted draft. (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..c318b9c89 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-stop-navigation-running-state++Hold the history read after a successful local Stop, switch to another running session, then resolve the older session's history. Verify only the stopped session is settled, the new transcript remains and its toolbar still offers Stop. Also navigate synchronously during the hydration commit to exercise the final state writer. Coverage: `stop-navigation-running-state.test.mjs`, related smart-stop/terminal regressions, and `scripts/e2e-stop-navigation-running-state.mjs` using the production store and ComposerToolbar in Electron.+> 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-stop-navigation-running-state.mjs b/scripts/e2e-stop-navigation-running-state.mjsnew file mode 100644index 000000000..0f893ef0f--- /dev/null+++ b/scripts/e2e-stop-navigation-running-state.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-stop-navigation-running-state-'));+try {+ await build({+ entryPoints: [join(root, 'scripts/e2e/stop-navigation-running-state.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>stop-navigation-running-state</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 stop-navigation-running-state: real Electron, production renderer/store, controlled external API');+} finally { await rm(scratch, { recursive: true, force: true }); }diff --git a/scripts/e2e/stop-navigation-running-state.tsx b/scripts/e2e/stop-navigation-running-state.tsxnew file mode 100644index 000000000..d72af5bb0--- /dev/null+++ b/scripts/e2e/stop-navigation-running-state.tsx@@ -0,0 +1,47 @@+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: state.activeSessionId, 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 user: UiMessage = { id: "prompt", role: "user", content: "pending", createdAt: "2026-01-01T00:00:00Z" };+ let release!: () => void;+ let started!: () => void;+ const wait = new Promise<void>(resolve => { release = resolve; });+ const entered = new Promise<void>(resolve => { started = resolve; });+ window.piDesktop = { platform: "win32", channels: IPC, on: () => () => {}, invoke: async <T,>(channel: string) => {+ if (channel === IPC.invoke.agentAbort) return { ok: true, data: {} as T };+ assert(channel === IPC.invoke.sessionGet, `Unexpected API ${channel}`);+ started(); await wait;+ return { ok: true, data: { session: { messages: [user, { id: "first-answer", role: "assistant", content: "finished", createdAt: "2026-01-01T00:00:00Z" }] } } as T };+ } };+ const session = (id: string) => ({ id, title: id, mode: "agent" as const, permissionMode: "ask" as const, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z" });+ useAppStore.setState({ activeSessionId: "first", sessions: [session("first"), session("second")], messages: [user], isRunning: true, runningSessions: { first: true, second: true }, pendingPermissions: {}, showToast: message => { throw new Error(message); } });+ const host = document.createElement("div"); document.body.append(host); const root = createRoot(host);+ try {+ flushSync(() => root.render(<Fixture />)); await settle();+ const stopping = useAppStore.getState().abort(); await entered;+ const secondRows: UiMessage[] = [{ id: "second-answer", role: "assistant", content: "other live task", status: "streaming", createdAt: "2026-01-01T00:00:00Z" }];+ useAppStore.setState({ activeSessionId: "second", messages: secondRows }); await settle();+ assert(host.querySelector(".stop-btn"), "other active session still has Stop before old read finishes");+ release(); await stopping; await settle();+ assert(useAppStore.getState().runningSessions.first === false && useAppStore.getState().runningSessions.second === true, "Stop settles only its own session");+ assert(useAppStore.getState().isRunning && host.querySelector(".stop-btn"), "late Stop cannot hide current session's Stop");+ assert(useAppStore.getState().messages[0]?.id === "second-answer", "new transcript stays selected");+ return { ok: true };+ } finally { root.unmount(); host.remove(); }+} });