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(plugins): keep session follow inside scope and ordered under switches
vastsa3bf9abd43bf6
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 0d794fa8a..a478bb597 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -338,6 +338,8 @@ const pluginServices = createPluginServices({* coordination instance that reads it too.*/getActiveTurn: (sessionId) => activeTurns.get(sessionId) ?? null,+ /** The same scope lookup every plugin view IPC consults. */+ isPluginActiveInProject: (pluginId) => pluginActiveInProject(pluginId, currentWorkspacePath()),vendorOAuth,});const {diff --git a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts b/apps/desktop/electron/main/ipc/plugin-ui-ipc.tsindex 0817e1870..199ad72f2 100644--- a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts+++ b/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts@@ -44,16 +44,31 @@ export function registerPluginUiIpc({const handle = (channel: string, fn: (...args: any[]) => Promise<any>) => {registrar.handle(channel, fn);};+ /**+ * The newest selection the shell reported, so a slower invoke that lands+ * after a newer one cannot restore a session the user already left.+ */+ let activeSessionSeq = 0;/*** The session on screen, as the shell sees it.** The renderer owns the selection and the project path; the main process owns* turn identity, so this only records the half it does not already know and* the snapshot is assembled from both (spec 07-plugins/03 §session).+ *+ * `seq` is the renderer's own counter: two switches can be in flight at once,+ * and the one that was produced first must never win.*/handle(IPC.invoke.pluginSessionActive,- async (payload: { sessionId?: string | null; projectPath?: string | null } | null) => {+ async (+ payload:+ | { sessionId?: string | null; projectPath?: string | null; seq?: number | null }+ | null,+ ) => {+ const seq = typeof payload?.seq === "number" ? payload.seq : 0;+ if (seq > 0 && seq < activeSessionSeq) return { ok: true, ignored: true };+ if (seq > 0) activeSessionSeq = seq;const sessionId = typeof payload?.sessionId === "string" ? payload.sessionId.trim() : "";if (!sessionId) {setActivePluginSession(null);diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.tsindex 89c269304..f98f190a3 100644--- a/apps/desktop/electron/main/plugin-runtime.ts+++ b/apps/desktop/electron/main/plugin-runtime.ts@@ -498,9 +498,15 @@ export type PluginHostServices = {* host's own selection and turn maps, so a plugin never infers it.*/getActiveSession?: () => PluginActiveSession | null;+ /**+ * Whether a plugin's contributions still apply to the shell's current+ * project. The same scope check every view IPC applies, so a project-scoped+ * plugin cannot read or reveal a session it is inactive in.+ */+ isPluginActiveInProject?: (pluginId: string) => boolean;/*** Ask the shell to show one of this plugin's views in a session's work panel.- * The runtime has already resolved the view and rejected a stale session.+ * The runtime has already resolved the view, the scope and a stale session.*/revealView?: (request: {pluginId: string;@@ -4474,6 +4480,11 @@ export class PluginRuntime {if (!this.services.getActiveSession) {throw apiError("UNSUPPORTED", "host api not available: session.getActive");}+ // A project-scoped plugin is not part of another project's conversation, so+ // it does not get to read which session that project has open.+ if (!this.services.isPluginActiveInProject?.(loaded.manifest.id)) {+ throw apiError("PERMISSION_DENIED", "plugin is not active in this project");+ }const snapshot = this.services.getActiveSession();this.services.audit?.({pluginId: loaded.manifest.id,@@ -4504,6 +4515,9 @@ export class PluginRuntime {if (views.length === 0) {throw apiError("NOT_FOUND", "plugin does not declare a work panel view");}+ if (!this.services.isPluginActiveInProject?.(loaded.manifest.id)) {+ throw apiError("PERMISSION_DENIED", "plugin is not active in this project");+ }const requested = typeof input?.viewId === "string" ? input.viewId.trim() : "";const view = requested? views.find((candidate) => candidate?.id === requested)diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.tsindex e410b71c4..fea3cec9f 100644--- a/apps/desktop/electron/main/services/plugin-services.ts+++ b/apps/desktop/electron/main/services/plugin-services.ts@@ -80,8 +80,20 @@ export type PluginServicesDependencies = {vendorOAuth: VendorOAuth;/** The live turn of one session, read from the host's own turn map. */getActiveTurn: (sessionId: string) => string | null;+ /**+ * Whether a plugin's contributions apply to the project the window shows.+ * Scope records live in Main, so this is the one lookup that decides.+ */+ isPluginActiveInProject: (pluginId: string) => boolean;};+/**+ * Session events whose payload describes the user's current selection. A+ * detached `ui.panel` window is application-scoped — it does not belong to a+ * session — so it never receives them; plugin processes and docked views do.+ */+const SESSION_SCOPED_EVENTS = new Set(["session:activated"]);+export function createPluginServices({dataDir,logger,@@ -101,6 +113,7 @@ export function createPluginServices({resolveAgentRuntimeLaunch,vendorOAuth,getActiveTurn,+ isPluginActiveInProject,}: PluginServicesDependencies) {// A plugin request can lose its race with host shutdown or restart.const isHostUnavailable = (error: unknown): boolean =>@@ -550,39 +563,47 @@ export function createPluginServices({pluginViews.broadcast("browser:state", state);};/**- * Tell the plugin surfaces that a host turn reached a terminal state. The- * three surfaces are independent: a failure to reach one of them must not- * suppress the other two, and inside each one an unreachable recipient is- * skipped by the host that owns the fan-out.+ * One fan-out for every session-lifecycle event, so a rule added here cannot+ * apply to `session:turnEnded` and be forgotten for `session:activated`.*- * Delivery is best-effort by contract — no acknowledgement, no replay, and no- * guarantee for a plugin that is loading, crashed or unloaded right now.+ * The selected session and its project path are reported to the plugin+ * processes and to the docked views that follow the user's selection; a+ * detached `ui.panel` window is application-scoped and never receives them.+ * Each surface owns its failure: one unreachable plugin process, panel or view+ * must not suppress the other two.*/- const announceTurnEnded = (payload: TurnEndedPayload): void => {+ const broadcastSessionEvent = (event: string, payload: unknown): void => {+ const sessionId =+ (payload as { sessionId?: string } | null | undefined)?.sessionId ?? undefined;try {- plugins.broadcastEvent("session:turnEnded", [payload]);+ plugins.broadcastEvent(event, [payload]);} catch (error) {- logger.app("plugin", "warn", "turnEnded plugin broadcast failed", {- sessionId: payload.sessionId,+ logger.app("plugin", "warn", `${event} plugin broadcast failed`, {+ sessionId,data: String(error),});}- try {- pluginPanels.broadcast("session:turnEnded", payload);- } catch (error) {- logger.app("plugin", "warn", "turnEnded panel broadcast failed", {- sessionId: payload.sessionId,- data: String(error),- });+ if (!SESSION_SCOPED_EVENTS.has(event)) {+ try {+ pluginPanels.broadcast(event, payload);+ } catch (error) {+ logger.app("plugin", "warn", `${event} panel broadcast failed`, {+ sessionId,+ data: String(error),+ });+ }}try {- pluginViews.broadcast("session:turnEnded", payload);+ pluginViews.broadcast(event, payload);} catch (error) {- logger.app("plugin", "warn", "turnEnded view broadcast failed", {- sessionId: payload.sessionId,+ logger.app("plugin", "warn", `${event} view broadcast failed`, {+ sessionId,data: String(error),});}+ };+ const announceTurnEnded = (payload: TurnEndedPayload): void => {+ broadcastSessionEvent("session:turnEnded", payload);// The snapshot also carries the running turn, so a surface that subscribes// to `session:activated` learns the selected session went idle from the// same event stream it learns a switch from.@@ -591,40 +612,13 @@ export function createPluginServices({/*** The selected session and its running turn, as the plugin surfaces see it.*- * Created after the two window hosts above because its fan-out — like- * `announceTurnEnded` — reaches all three surfaces, and after nothing else:- * `announceTurnEnded` below notifies it, and that only ever runs once this- * factory has returned.+ * Created after the two window hosts above because its fan-out reaches them,+ * and after nothing else: `announceTurnEnded` above notifies it, and that only+ * ever runs once this factory has returned.*/const pluginSession = createPluginSessionContext({getActiveTurn,- announce: (event, payload) => {- try {- plugins.broadcastEvent(event, [payload]);- } catch (error) {- logger.app("plugin", "warn", "sessionContext plugin broadcast failed", {- sessionId: payload?.sessionId ?? undefined,- data: String(error),- });- }- try {- pluginPanels.broadcast(event, payload);- } catch (error) {- logger.app("plugin", "warn", "sessionContext panel broadcast failed", {- sessionId: payload?.sessionId ?? undefined,- data: String(error),- });- }- try {- pluginViews.broadcast(event, payload);- } catch (error) {- logger.app("plugin", "warn", "sessionContext view broadcast failed", {- sessionId: payload?.sessionId ?? undefined,- data: String(error),- });- }- },- log: (message, data) => logger.app("plugin", "warn", message, { data }),+ announce: broadcastSessionEvent,});const pluginViews = new PluginViewHost(({ pluginId, url }) => {logger.app("plugin", "warn", "plugin.api", {@@ -702,6 +696,11 @@ export function createPluginServices({sendToRenderer(IPC.event.pluginChanged, { reason: "agentExtensions" }),/** `pi.session.getActive`: the selected session as the shell shows it. */getActiveSession: () => pluginSession.snapshot(),+ /**+ * The same project-scope check the view IPCs apply, so following a session+ * and revealing a view stay inside the project the plugin was activated in.+ */+ isPluginActiveInProject: (pluginId) => isPluginActiveInProject(pluginId),/*** `pi.ui.revealView`: the runtime validated the view and the session; the* shell owns work-panel tabs, so it is the surface that opens the tab.diff --git a/apps/desktop/electron/main/services/plugin-session-context.ts b/apps/desktop/electron/main/services/plugin-session-context.tsindex d6eb09b52..49929d9e0 100644--- a/apps/desktop/electron/main/services/plugin-session-context.ts+++ b/apps/desktop/electron/main/services/plugin-session-context.ts@@ -28,6 +28,23 @@ export type PluginSessionContextDependencies = {log?: (message: string, data?: Record<string, unknown>) => void;};+/**+ * Sessions whose turn start this module still remembers. Start times exist only+ * to date the selected session's turn, and a turn that ends without a notice+ * never removes its entry, so the map is capped instead of growing with every+ * session that ever ran. Oldest insertions go first.+ */+const MAX_TRACKED_SESSIONS = 64;++/** Drop the oldest insertions until `map` holds at most `limit` entries. */+function enforceBound<K, V>(map: Map<K, V>, limit: number): void {+ while (map.size > limit) {+ const oldest = map.keys().next();+ if (oldest.done) return;+ map.delete(oldest.value);+ }+}+export type PluginSessionContext = ReturnType<typeof createPluginSessionContext>;export function createPluginSessionContext({@@ -94,12 +111,19 @@ export function createPluginSessionContext({selection = sessionId ? { sessionId, projectPath } : null;publish();},- /** A host turn opened for this session: date it so the snapshot can report it. */+ /**+ * A host turn opened for this session: date it so the snapshot can report+ * it whenever the user switches to that session.+ */noteTurnStarted(sessionId: string, turnId: string): void {const id = String(sessionId ?? "").trim();const turn = String(turnId ?? "").trim();if (!id || !turn) return;turnStarts.set(id, { turnId: turn, startedAt: now() });+ // Only the selected session can change the snapshot, so no other session+ // needs an announcement — but every session needs a bounded map, because+ // a turn that ends without a notice never reports its end.+ enforceBound(turnStarts, MAX_TRACKED_SESSIONS);if (selection?.sessionId === id) publish();},/** That turn reached a terminal state, so the session is idle again. */diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsxindex 7f2f67737..edc540481 100644--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx@@ -72,6 +72,8 @@ export function useAppShellRuntime() {const refreshPluginThemes = useAppStore((s) => s.refreshPluginThemes);const plugins = useAppStore((s) => s.plugins);const projectPath = useAppStore((s) => s.workspace?.path ?? null);+ /** Monotonic counter for the plugin active-session push. */+ const activeSessionSeq = useRef(0);/** The project of the session on screen, for the plugin session snapshot. */const activeSessionProjectPath = useAppStore((s) =>s.activeSessionId@@ -462,12 +464,18 @@ export function useAppShellRuntime() {* The selected session is shell state, so the shell publishes it. Plugin* `pi.session.getActive()` and `session:activated` read this instead of any* plugin guessing from the transcript.+ *+ * Each push carries a counter because two switches can be in flight at once:+ * a slower invoke must never land after a newer one and restore a session the+ * user already left.*/useEffect(() => {+ activeSessionSeq.current += 1;void api.setPluginActiveSession({sessionId: activeSessionId ?? null,projectPath: activeSessionProjectPath,+ seq: activeSessionSeq.current,}).catch(() => undefined);}, [activeSessionId, activeSessionProjectPath]);diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex 6adce36b8..f0b17ff01 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -675,8 +675,12 @@ export const api = {* `pi.session.getActive()` and the `session:activated` event answer from it,* so the shell — not a plugin — is what decides which session is active.*/- setPluginActiveSession: (input: { sessionId: string | null; projectPath?: string | null }) =>- invoke<{ ok: boolean }>(IPC.invoke.pluginSessionActive, input),+ setPluginActiveSession: (input: {+ sessionId: string | null;+ projectPath?: string | null;+ /** Renderer-side counter: a slower push must never undo a newer one. */+ seq?: number;+ }) => invoke<{ ok: boolean }>(IPC.invoke.pluginSessionActive, input),listSessions: () =>invoke<{ sessions: SessionSummary[] }>(IPC.invoke.sessionList).then((result) => ({...result,diff --git a/apps/desktop/test/main-wiring-contract.test.mjs b/apps/desktop/test/main-wiring-contract.test.mjsindex 89faf3967..f29da9c74 100644--- a/apps/desktop/test/main-wiring-contract.test.mjs+++ b/apps/desktop/test/main-wiring-contract.test.mjs@@ -200,20 +200,26 @@ test("browser state reaches every plugin surface", () => {test("a finished turn is announced to every plugin surface", () => {const services = read("services/plugin-services.ts");- const announce = braceBody(+ const fanOut = braceBody(services,- services.indexOf("{", services.indexOf("const announceTurnEnded")),+ services.indexOf("{", services.indexOf("const broadcastSessionEvent")),);- assert.match(announce, /plugins\.broadcastEvent\("session:turnEnded", \[payload\]\)/);- assert.match(announce, /pluginPanels\.broadcast\("session:turnEnded", payload\)/);- assert.match(announce, /pluginViews\.broadcast\("session:turnEnded", payload\)/);+ assert.match(fanOut, /plugins\.broadcastEvent\(event, \[payload\]\)/);+ assert.match(fanOut, /pluginPanels\.broadcast\(event, payload\)/);+ assert.match(fanOut, /pluginViews\.broadcast\(event, payload\)/);// Each surface owns its failure: one unreachable plugin process, panel or// view must not suppress the other two.assert.equal(- (announce.match(/\} catch \(/g) ?? []).length,+ (fanOut.match(/\} catch \(/g) ?? []).length,3,"every plugin surface must isolate its own delivery",);+ // The turn-end event still takes that fan-out; it only adds the snapshot.+ const announce = braceBody(+ services,+ services.indexOf("{", services.indexOf("const announceTurnEnded")),+ );+ assert.match(announce, /broadcastSessionEvent\("session:turnEnded", payload\)/);});test("the selected session is announced to every plugin surface", () => {diff --git a/apps/desktop/test/plugin-session-follow.test.mjs b/apps/desktop/test/plugin-session-follow.test.mjsindex 6cd32d6f3..2160b8caa 100644--- a/apps/desktop/test/plugin-session-follow.test.mjs+++ b/apps/desktop/test/plugin-session-follow.test.mjs@@ -150,6 +150,7 @@ test("plugin session follow reads the snapshot and refuses a stale reveal", asynprojectPath: "/work/pi",activeTurn: { turnId: "turn-1", startedAt: 1_000 },}),+ isPluginActiveInProject: () => true,revealView: async (request) => revealed.push(request),});t.after(async () => {@@ -205,6 +206,7 @@ test("revealing a work-panel view requires the view permission", async (t) => {hostEntry: hostProcessEntry,spawnProcess: forkPluginProcess,getActiveSession: () => ({ sessionId: "s1", projectPath: null, activeTurn: null }),+ isPluginActiveInProject: () => true,revealView: async (request) => revealed.push(request),});t.after(async () => {@@ -240,6 +242,7 @@ test("a docked view reads the same snapshot through the panel bridge", async (t)hostEntry: hostProcessEntry,spawnProcess: forkPluginProcess,getActiveSession: () => ({ sessionId: "s7", projectPath: "/work/pi", activeTurn: null }),+ isPluginActiveInProject: () => true,});t.after(async () => {for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);@@ -254,3 +257,68 @@ test("a docked view reads the same snapshot through the panel bridge", async (t)const snapshot = await runtime.invokePanelBridge("demo.view-bridge", "session.getActive");assert.deepEqual(snapshot, { sessionId: "s7", projectPath: "/work/pi", activeTurn: null });});++test("a project-scoped plugin cannot follow or reveal outside its project", async (t) => {+ const revealed = [];+ const runtime = new PluginRuntime({+ hostEntry: hostProcessEntry,+ spawnProcess: forkPluginProcess,+ getActiveSession: () => ({ sessionId: "s9", projectPath: "/work/other", activeTurn: null }),+ isPluginActiveInProject: () => false,+ revealView: async (request) => revealed.push(request),+ });+ t.after(async () => {+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);+ });+ const dir = writeViewPlugin({+ id: "demo.out-of-scope",+ permissions: ["ui.view"],+ views: [CHANGES_VIEW],+ main: `+ module.exports = {+ async onLoad() {+ await pi.commands.register({+ id: "exercise",+ title: "Exercise",+ run: async () => {+ try { await pi.session.getActive(); }+ catch (error) { await pi.ui.showToast("active:" + error.code); }+ try { await pi.ui.revealView(); }+ catch (error) { await pi.ui.showToast("reveal:" + error.code); }+ }+ });+ }+ };+ `,+ });+ await runtime.loadFromPath(dir, ["ui.view"]);+ await runCommand(runtime, "exercise");+ assert.deepEqual(runtime.drainToasts(), [+ "active:PERMISSION_DENIED",+ "reveal:PERMISSION_DENIED",+ ]);+ assert.deepEqual(revealed, []);+});++test("turn start times stay bounded when a turn ends without a notice", () => {+ const announced = [];+ const liveTurns = new Map();+ const context = createPluginSessionContext({+ getActiveTurn: (sessionId) => liveTurns.get(sessionId) ?? null,+ announce: (event, payload) => announced.push([event, payload]),+ });+ // Far more sessions than the cap: the map must not grow with the app's life.+ for (let index = 0; index < 500; index += 1) {+ context.noteTurnStarted(`session-${index}`, `turn-${index}`);+ }+ for (const sessionId of ["session-0", "session-100", "session-499"]) {+ liveTurns.set(sessionId, sessionId.replace("session", "turn"));+ }+ context.setActiveSession({ sessionId: "session-499", projectPath: null });+ assert.equal(context.snapshot().activeTurn.turnId, "turn-499");+ assert.equal(typeof context.snapshot().activeTurn.startedAt, "number");+ // The oldest insertions were dropped, so switching back reports no turn start+ // rather than a start time that no longer exists.+ context.setActiveSession({ sessionId: "session-0", projectPath: null });+ assert.equal(context.snapshot().activeTurn, null);+});diff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.mdindex 417c30777..c22c18977 100644--- a/docs/spec/07-plugins/03-plugin-api.md+++ b/docs/spec/07-plugins/03-plugin-api.md@@ -559,7 +559,10 @@ type PluginActiveSession = {```It takes no session id: the host reports the selection instead of letting a-plugin address a session the user is not looking at. `null` means home, the+plugin address a session the user is not looking at. A plugin whose activation+scope does not match the project on screen gets `PERMISSION_DENIED`, the same+answer `pi.ui.revealView` and the view IPC give, so a project-scoped plugin never+learns which session another project has open. `null` means home, theSettings page, or no chat session selected. `activeTurn` names the durable hostturn that session is running, and is `null` while the session is idle, so aplugin does not have to infer a running task from the previous turn's end event@@ -1399,7 +1402,9 @@ Delivered today:- `session:turnEnded` — the same payload as the plugin-process event in §5,sent when a host turn reaches a terminal state.- `session:activated` — the same payload as the plugin-process event in §5, sent- whenever the selected session, its project, or its running turn changes.+ to docked views whenever the selected session, its project, or its running+ turn changes. A detached `ui.panel` window is application-scoped and does not+ belong to a session, so it is the one surface that never receives this event.## 7. Call auditingdiff --git a/docs/zh-CN/spec/07-plugins/03-plugin-api.md b/docs/zh-CN/spec/07-plugins/03-plugin-api.mdindex 4e3b59ec8..8cbf6bc9d 100644--- a/docs/zh-CN/spec/07-plugins/03-plugin-api.md+++ b/docs/zh-CN/spec/07-plugins/03-plugin-api.md@@ -432,7 +432,9 @@ type PluginActiveSession = {}```-它不接受 session id:宿主报告选中项,而不允许插件去寻址用户没在看的会话。+它不接受 session id:宿主报告选中项,而不允许插件去寻址用户没在看的会话。若插件的+激活范围与当前项目不匹配,调用以 `PERMISSION_DENIED` 拒绝——与 `pi.ui.revealView`+和视图 IPC 的答案一致,因此按项目激活的插件不会得知另一个项目打开了哪个会话。`null` 表示首页、设置页,或没有选中任何聊天会话。`activeTurn` 是该会话正在跑的那个持久宿主回合,空闲时为 `null`,因此插件不必从上一回合的结束事件或草稿变化去推断「正在运行的任务」;`startedAt` 是宿主时钟(epoch 毫秒),取自该回合开始的@@ -1089,7 +1091,8 @@ window.pluginBridge.on(event, handler)- `session:turnEnded` —— 与 §5 的插件进程事件同一载荷,在宿主回合到达终止状态时发送。- `session:activated` —— 与 §5 的插件进程事件同一载荷,在选中会话、它的项目或它的- 运行回合发生变化时发送。+ 运行回合发生变化时发给停靠视图。独立 `ui.panel` 窗口属于应用级、不属于某个会话,+ 因此它是唯一不会收到该事件的表面。## 7. 通话审计