Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(plugins): keep session follow alive across renderer reloads and inside scope

liuzixiange455c0aabfc2
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.ts
index a478bb597..f5addefd5 100644
--- a/apps/desktop/electron/main/index.ts
+++ b/apps/desktop/electron/main/index.ts
@@ -304,6 +304,7 @@ let sessionLaunchRuntime: ReturnType<typeof createSessionLaunchRuntime> | null =
const pluginServices = createPluginServices({
dataDir,
logger,
+ pluginActiveInProject,
getMainWindow,
getHost,
sendToRenderer,
diff --git a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts b/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts
index 199ad72f2..7847075d8 100644
--- a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts
+++ b/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts
@@ -49,6 +49,10 @@ export function registerPluginUiIpc({
* after a newer one cannot restore a session the user already left.
*/
let activeSessionSeq = 0;
+ /** The renderer load the high-water mark belongs to. A reload restarts the
+ * renderer's counter from one, so a changed boot id resets the mark and
+ * pushes keep flowing afterwards (#1753). */
+ let activeSessionBootId: string | null = null;
/**
* The session on screen, as the shell sees it.
*
@@ -63,12 +67,21 @@ export function registerPluginUiIpc({
IPC.invoke.pluginSessionActive,
async (
payload:
- | { sessionId?: string | null; projectPath?: string | null; seq?: number | null }
+ | { sessionId?: string | null; projectPath?: string | null; seq?: number | null; bootId?: string | 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 bootId = typeof payload?.bootId === "string" ? payload.bootId : null;
+ if (seq > 0) {
+ if (bootId && bootId !== activeSessionBootId) {
+ activeSessionBootId = bootId;
+ activeSessionSeq = seq;
+ } else if (seq >= activeSessionSeq) {
+ activeSessionSeq = seq;
+ } else {
+ return { ok: true, ignored: true };
+ }
+ }
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.ts
index f98f190a3..fb3e4859a 100644
--- a/apps/desktop/electron/main/plugin-runtime.ts
+++ b/apps/desktop/electron/main/plugin-runtime.ts
@@ -1994,8 +1994,9 @@ export class PluginRuntime {
* receive the same names through `pluginBridge.on`; this is the process
* half (spec 07 §5).
*/
- broadcastEvent(event: string, args: unknown[] = []): void {
+ broadcastEvent(event: string, args: unknown[] = [], filter?: (pluginId: string) => boolean): void {
for (const loaded of this.loaded.values()) {
+ if (filter && !filter(loaded.manifest.id)) continue;
try {
loaded.child?.postMessage({ t: "event", event, args });
} catch (error) {
diff --git a/apps/desktop/electron/main/plugin-view-host.ts b/apps/desktop/electron/main/plugin-view-host.ts
index 9375cd97f..a4976d3d1 100644
--- a/apps/desktop/electron/main/plugin-view-host.ts
+++ b/apps/desktop/electron/main/plugin-view-host.ts
@@ -141,9 +141,10 @@ export class PluginViewHost {
* are broadcast separately by `PluginPanelHost`; both surfaces share the
* preload channel `pi-plugin-panel-event:<event>`.
*/
- broadcast(event: string, payload: unknown): void {
+ broadcast(event: string, payload: unknown, filter?: (pluginId: string) => boolean): void {
const channel = `pi-plugin-panel-event:${event}`;
for (const entry of this.views.values()) {
+ if (filter && !filter(entry.pluginId)) continue;
const wc = entry.view.webContents;
if (wc.isDestroyed()) continue;
try {
diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.ts
index fea3cec9f..5d1ffb6b3 100644
--- a/apps/desktop/electron/main/services/plugin-services.ts
+++ b/apps/desktop/electron/main/services/plugin-services.ts
@@ -85,6 +85,12 @@ export type PluginServicesDependencies = {
* Scope records live in Main, so this is the one lookup that decides.
*/
isPluginActiveInProject: (pluginId: string) => boolean;
+ /**
+ * Scope check against an explicit project path, so the session-event
+ * fan-out can hold the same line `session.getActive` does for sessions
+ * that are not the window's own selection (#1754).
+ */
+ pluginActiveInProject?: (pluginId: string, projectPath: string | null | undefined) => boolean;
};
/**
@@ -114,6 +120,7 @@ export function createPluginServices({
vendorOAuth,
getActiveTurn,
isPluginActiveInProject,
+ pluginActiveInProject,
}: PluginServicesDependencies) {
// A plugin request can lose its race with host shutdown or restart.
const isHostUnavailable = (error: unknown): boolean =>
@@ -575,8 +582,21 @@ export function createPluginServices({
const broadcastSessionEvent = (event: string, payload: unknown): void => {
const sessionId =
(payload as { sessionId?: string } | null | undefined)?.sessionId ?? undefined;
+ // Selection events carry another project's session identity, so the
+ // fan-out holds the scope line the pull side (session.getActive,
+ // ui.revealView) already enforces: a project-scoped plugin does not
+ // receive a session its scope excludes (#1754). Sessions without a
+ // project fall back to the workspace-relative check.
+ const scopeFilter =
+ SESSION_SCOPED_EVENTS.has(event) && pluginActiveInProject
+ ? (pluginId: string) =>
+ pluginActiveInProject(
+ pluginId,
+ (sessionId && sessionProjects.get(sessionId)) ?? null,
+ )
+ : undefined;
try {
- plugins.broadcastEvent(event, [payload]);
+ plugins.broadcastEvent(event, [payload], scopeFilter);
} catch (error) {
logger.app("plugin", "warn", `${event} plugin broadcast failed`, {
sessionId,
@@ -594,7 +614,7 @@ export function createPluginServices({
}
}
try {
- pluginViews.broadcast(event, payload);
+ pluginViews.broadcast(event, payload, scopeFilter);
} catch (error) {
logger.app("plugin", "warn", `${event} view broadcast failed`, {
sessionId,
diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsx
index edc540481..f7058af02 100644
--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx
+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx
@@ -74,6 +74,9 @@ export function useAppShellRuntime() {
const projectPath = useAppStore((s) => s.workspace?.path ?? null);
/** Monotonic counter for the plugin active-session push. */
const activeSessionSeq = useRef(0);
+ /** Identifies this renderer load: a reload restarts the counter, and the
+ * main-side high-water mark must restart with it (#1753). */
+ const sessionPushBootId = useRef(crypto.randomUUID());
/** The project of the session on screen, for the plugin session snapshot. */
const activeSessionProjectPath = useAppStore((s) =>
s.activeSessionId
@@ -476,6 +479,7 @@ export function useAppShellRuntime() {
sessionId: activeSessionId ?? null,
projectPath: activeSessionProjectPath,
seq: activeSessionSeq.current,
+ bootId: sessionPushBootId.current,
})
.catch(() => undefined);
}, [activeSessionId, activeSessionProjectPath]);
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index a23632a11..85810d88a 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -684,6 +684,9 @@ export const api = {
projectPath?: string | null;
/** Renderer-side counter: a slower push must never undo a newer one. */
seq?: number;
+ /** Identifies the renderer load: a reload restarts the counter, and the
+ * main-side high-water mark restarts with it (#1753). */
+ bootId?: string;
}) => invoke<{ ok: boolean }>(IPC.invoke.pluginSessionActive, input),
listSessions: () =>
invoke<{ sessions: SessionSummary[] }>(IPC.invoke.sessionList).then((result) => ({
diff --git a/apps/desktop/test/plugin-session-follow.test.mjs b/apps/desktop/test/plugin-session-follow.test.mjs
index 2160b8caa..a6c5ae338 100644
--- a/apps/desktop/test/plugin-session-follow.test.mjs
+++ b/apps/desktop/test/plugin-session-follow.test.mjs
@@ -322,3 +322,86 @@ test("turn start times stay bounded when a turn ends without a notice", () => {
context.setActiveSession({ sessionId: "session-0", projectPath: null });
assert.equal(context.snapshot().activeTurn, null);
});
+
+test("broadcastEvent's filter keeps an out-of-scope plugin from receiving the session push", async (t) => {
+ const sent = [];
+ const spawnWithSpy = (options) => {
+ const proc = forkPluginProcess(options);
+ const ownerId = currentId;
+ const originalPostMessage = proc.postMessage;
+ proc.postMessage = (message) => {
+ sent.push({ plugin: ownerId, message });
+ originalPostMessage(message);
+ };
+ return proc;
+ };
+ let currentId = "demo.in-scope";
+ const runtime = new PluginRuntime({
+ hostEntry: hostProcessEntry,
+ spawnProcess: spawnWithSpy,
+ isPluginActiveInProject: (pluginId) => pluginId === "demo.in-scope",
+ });
+ t.after(async () => {
+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);
+ });
+
+ await runtime.loadFromPath(
+ writeViewPlugin({
+ id: "demo.in-scope",
+ permissions: ["ui.view"],
+ views: [CHANGES_VIEW],
+ main: "module.exports = { async onLoad() {} };",
+ }),
+ ["ui.view"],
+ );
+ currentId = "demo.out-of-scope";
+ await runtime.loadFromPath(
+ writeViewPlugin({
+ id: "demo.out-of-scope",
+ permissions: ["ui.view"],
+ views: [CHANGES_VIEW],
+ main: "module.exports = { async onLoad() {} };",
+ }),
+ ["ui.view"],
+ );
+
+ const payload = { sessionId: "s-other", projectPath: "/work/other" };
+ runtime.broadcastEvent(
+ "session:activated",
+ [payload],
+ (pluginId) => pluginId === "demo.in-scope",
+ );
+ await new Promise((resolve) => setImmediate(resolve));
+
+ const events = sent.filter((entry) => entry.message?.event === "session:activated");
+ assert.equal(events.length, 1, "exactly the in-scope plugin process received the push");
+ assert.equal(events[0].plugin, "demo.in-scope");
+ assert.deepEqual(events[0].message.args, [payload]);
+});
+
+test("the session-push gate restarts with the renderer's boot id and the payload carries it", async () => {
+ const { readMainSource, readStoreModule } = await import("./helpers/source-contracts.mjs");
+ const ipcSource = await readMainSource("ipc/plugin-ui-ipc.ts");
+
+ // Main (#1753): a changed boot id resets the high-water mark, so pushes
+ // keep flowing after a renderer reload; within one boot the old
+ // out-of-order guard still applies.
+ assert.match(
+ ipcSource,
+ /const\s+bootId\s*=\s*typeof\s+payload\?\.bootId\s*===\s*"string"[\s\S]*?bootId\s*!==\s*activeSessionBootId[\s\S]*?activeSessionSeq\s*=\s*seq;[\s\S]*?return\s+\{\s*ok:\s*true,\s*ignored:\s*true\s*\};/,
+ "the gate must reset the high-water mark on a new renderer boot and keep the out-of-order guard within a boot",
+ );
+
+ // Renderer: the push carries the boot id the gate compares.
+ const runtimeSource = await readStoreModule("../../src/features/app/useAppShellRuntime.tsx");
+ assert.match(
+ runtimeSource,
+ /sessionPushBootId\s*=\s*useRef\(crypto\.randomUUID\(\)\)/,
+ "the renderer must own a per-load boot id",
+ );
+ assert.match(
+ runtimeSource,
+ /bootId:\s*sessionPushBootId\.current/,
+ "the push must carry the boot id",
+ );
+});