Skip to content

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

feat(plugins): follow the selected session and reveal work-panel views

vastsa192f716fabde
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.ts
index 78189811d..0d794fa8a 100644
--- a/apps/desktop/electron/main/index.ts
+++ b/apps/desktop/electron/main/index.ts
@@ -332,6 +332,12 @@ const pluginServices = createPluginServices({
) => Promise<any>
)(...args);
},
+ /**
+ * The live turn of one session, read through the one map that owns turn
+ * identity. Bound lazily because `activeTurns` is declared below, next to the
+ * coordination instance that reads it too.
+ */
+ getActiveTurn: (sessionId) => activeTurns.get(sessionId) ?? null,
vendorOAuth,
});
const {
@@ -623,6 +629,13 @@ const sessionCoordination = createSessionCoordination({
activeTurns,
getMainWindow,
getViewingSessionId: () => mainState.notificationViewingSessionId,
+ /**
+ * Plugin surfaces follow turn starts from here, so a selected session that
+ * begins running is reported with the durable turn id instead of being
+ * inferred from the previous turn's end.
+ */
+ onTurnStarted: (sessionId: string, turnId: string) =>
+ pluginServices.pluginSession.noteTurnStarted(sessionId, turnId),
});
const {
activeTurnUsages,
@@ -865,6 +878,8 @@ function registerIpc() {
setNotificationViewingSessionId: (sessionId: string | null) => {
mainState.notificationViewingSessionId = sessionId;
},
+ /** The shell reports the session on screen; plugin surfaces read it. */
+ setActivePluginSession: (next) => pluginServices.pluginSession.setActiveSession(next),
getPluginLauncherWindow: () => mainState.pluginLauncherWindow,
togglePluginLauncher,
safeOpenExternal,
diff --git a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts b/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts
index 39abaea4f..0817e1870 100644
--- a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts
+++ b/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts
@@ -22,6 +22,10 @@ export type PluginUiIpcDependencies = {
currentWorkspacePath: () => string | null;
getUpdaterLocale: () => string;
getPluginPanelTheme: () => PluginPanelTheme;
+ /** The shell's selected session, reported on to the plugin surfaces. */
+ setActivePluginSession: (
+ next: { sessionId: string; projectPath: string | null } | null,
+ ) => void;
};
/** Register plugin panels, work-panel views, themes and services. */
@@ -35,10 +39,35 @@ export function registerPluginUiIpc({
currentWorkspacePath,
getUpdaterLocale,
getPluginPanelTheme,
+ setActivePluginSession,
}: PluginUiIpcDependencies): void {
const handle = (channel: string, fn: (...args: any[]) => Promise<any>) => {
registrar.handle(channel, fn);
};
+ /**
+ * 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).
+ */
+ handle(
+ IPC.invoke.pluginSessionActive,
+ async (payload: { sessionId?: string | null; projectPath?: string | null } | null) => {
+ const sessionId = typeof payload?.sessionId === "string" ? payload.sessionId.trim() : "";
+ if (!sessionId) {
+ setActivePluginSession(null);
+ return { ok: true };
+ }
+ if (sessionId.length > 128) {
+ throw new Error("INVALID_ARGUMENT: sessionId must be at most 128 characters");
+ }
+ const projectPath =
+ typeof payload?.projectPath === "string" ? payload.projectPath.trim() : "";
+ setActivePluginSession({ sessionId, projectPath: projectPath || null });
+ return { ok: true };
+ },
+ );
handle(IPC.invoke.pluginOpenPanel, async (id: string) => {
const loaded = plugins.getLoaded(id);
if (!loaded) throw new Error("plugin not loaded");
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index bd718f67c..464618685 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -60,6 +60,10 @@ export type RegisterIpcDependencies = {
getBackendRouter?: () => BackendRouter | null;
getNotificationViewingSessionId: () => string | null;
setNotificationViewingSessionId: (sessionId: string | null) => void;
+ /** The session on screen, as the shell reported it (plugin `session:activated`). */
+ setActivePluginSession: (
+ next: { sessionId: string; projectPath: string | null } | null,
+ ) => void;
activeUserSubagentDocuments: (...args: any[]) => Promise<any>;
disabledBuiltinSubagents: () => Promise<string[]>;
disabledBuiltinSkills: () => Promise<string[]>;
@@ -94,6 +98,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
getBackendRouter,
getNotificationViewingSessionId,
setNotificationViewingSessionId,
+ setActivePluginSession,
getPluginLauncherWindow,
togglePluginLauncher,
safeOpenExternal,
@@ -487,7 +492,6 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
currentWorkspacePath,
});
-
registerPluginUiIpc({
registrar,
plugins,
@@ -498,6 +502,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
currentWorkspacePath,
getUpdaterLocale,
getPluginPanelTheme,
+ setActivePluginSession,
});
registerSpeechIpc({ registrar, speech });
diff --git a/apps/desktop/electron/main/plugin-host-process.mjs b/apps/desktop/electron/main/plugin-host-process.mjs
index 93b0b2d80..68dd88372 100644
--- a/apps/desktop/electron/main/plugin-host-process.mjs
+++ b/apps/desktop/electron/main/plugin-host-process.mjs
@@ -244,6 +244,10 @@ function buildApi() {
openPanel: (options) => call("ui.openPanel", [options]),
closePanel: () => call("ui.closePanel"),
showToast: (message, level) => call("ui.showToast", [message, level]),
+ // The work panel is the shell's own surface: the plugin names one of its
+ // declared views and the subject, and the main process refuses a session
+ // that stopped being the one the user is looking at.
+ revealView: (input) => call("ui.revealView", [input ?? {}]),
notify: (input) => call("ui.notify", [input]),
getNotificationPermission: () => call("ui.getNotificationPermission"),
requestNotificationPermission: () => call("ui.requestNotificationPermission"),
@@ -316,6 +320,9 @@ function buildApi() {
list: () => call("models.list"),
},
session: {
+ // The selected session, as the shell shows it. A snapshot is a value: a
+ // plugin compares `sessionId` rather than assuming the session still holds.
+ getActive: () => call("session.getActive"),
getLlmContext: () => call("session.getLlmContext"),
getAutoTitleContext: (input) => call("session.getAutoTitleContext", [input ?? {}]),
setAutoTitle: (input) => call("session.setAutoTitle", [input ?? {}]),
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.ts
index e262e0638..89c269304 100644
--- a/apps/desktop/electron/main/plugin-runtime.ts
+++ b/apps/desktop/electron/main/plugin-runtime.ts
@@ -50,6 +50,7 @@ import {
validateManifest,
validateMcpServer,
type ClipboardHistoryEntry,
+ type PluginActiveSession,
type PluginCompleteInput,
type PluginCompleteResult,
type PluginFsMode,
@@ -66,6 +67,7 @@ import {
type PluginProviderOAuthPrompt,
type PluginProviderOAuthRequest,
type PluginProviderContrib,
+ type PluginRevealViewInput,
type PluginServiceContrib,
type PluginSettingContrib,
type PluginComposerTransformInput,
@@ -491,6 +493,21 @@ export type PluginHostServices = {
rename: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;
delete: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;
};
+ /**
+ * The session the user is looking at, as the shell shows it. Read from the
+ * host's own selection and turn maps, so a plugin never infers it.
+ */
+ getActiveSession?: () => PluginActiveSession | null;
+ /**
+ * 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.
+ */
+ revealView?: (request: {
+ pluginId: string;
+ viewId: string;
+ sessionId: string;
+ location: string | null;
+ }) => Promise<void>;
project?: {
create: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;
};
@@ -523,6 +540,7 @@ const HOST_API_ALLOWLIST = new Set([
"plugin.getSettings",
"plugin.setSettings",
"plugin.getDataPath",
+ "ui.revealView",
"ui.openPanel",
"ui.closePanel",
"ui.showToast",
@@ -582,6 +600,7 @@ const HOST_API_ALLOWLIST = new Set([
"audio.closeOutput",
"browser.cdp",
"models.list",
+ "session.getActive",
"session.getLlmContext",
"session.getAutoTitleContext",
"session.setAutoTitle",
@@ -756,6 +775,12 @@ const MAX_GLOB_MATCHES = 500;
const MAX_LIST_ENTRIES = 1000;
/** Maximum bytes one plugin range call may cross the broker with. */
const MAX_FS_READ_RANGE_BYTES = 8 * 1024 * 1024;
+/**
+ * Longest subject `ui.revealView` carries into a view. It travels in a query
+ * parameter and an IPC frame, so it is bounded like every other free-form
+ * string a plugin hands the host.
+ */
+const MAX_VIEW_LOCATION_CHARS = 8 * 1024;
/** Directories `pi.fs.glob` never walks into; they are noise and are denied anyway. */
const GLOB_SKIP_DIRS = new Set([".git", "node_modules", ".venv", "__pycache__"]);
/** Entries in one plugin's write ledger; oldest are dropped past this. */
@@ -2393,6 +2418,13 @@ export class PluginRuntime {
case "ui.closePanel":
await api.ui.closePanel();
return { ok: true };
+ case "ui.revealView":
+ await api.ui.revealView(payload as PluginRevealViewInput);
+ return { ok: true };
+ case "session.getActive":
+ // A docked view follows the user's selection the same way a plugin
+ // process does, and reads the same snapshot.
+ return this.readActiveSession(loaded);
case "fs.readText":
return api.fs.readText(String(payload?.path ?? ""));
case "fs.stat":
@@ -2988,6 +3020,12 @@ export class PluginRuntime {
case "session.getLlmContext": {
return this.readSessionContext(loaded);
}
+ case "session.getActive": {
+ // The selected session, not a session the plugin names: the host
+ // reports what the user is looking at and refuses to address anything
+ // else (spec 07-plugins/03 §session).
+ return this.readActiveSession(loaded);
+ }
case "session.getAutoTitleContext": {
this.assertPermission(loaded, "session.autoTitle");
const input = normalizePluginSessionInput(args[0] ?? {}, "other");
@@ -4424,6 +4462,95 @@ export class PluginRuntime {
return current.count > MAX_COMPLETES_PER_WINDOW;
}
+ /**
+ * `session.getActive`: the selected session as the shell shows it.
+ *
+ * Ungated like `workspace.get`, because it reports facts the user already
+ * sees — the session on screen and its project path — and never a session the
+ * plugin names. Turn identity comes from the host's live turn map, so a plugin
+ * does not have to infer a running task from the previous turn's end event.
+ */
+ private async readActiveSession(loaded: LoadedPlugin): Promise<PluginActiveSession | null> {
+ if (!this.services.getActiveSession) {
+ throw apiError("UNSUPPORTED", "host api not available: session.getActive");
+ }
+ const snapshot = this.services.getActiveSession();
+ this.services.audit?.({
+ pluginId: loaded.manifest.id,
+ api: "session.getActive",
+ ok: true,
+ ts: Date.now(),
+ });
+ return snapshot;
+ }
+
+ /**
+ * `ui.revealView`: open one of the plugin's own views in a session's work
+ * panel.
+ *
+ * The plugin names a view and a subject; the host decides where the view
+ * appears. Every refusal here replaces a guess: `ui.view` must be held, a
+ * `viewId` must resolve to exactly one declared view, a subject must stay
+ * bounded, and a named session must still be the one the user is looking at.
+ * A work-panel tab belongs to a session, so a stale request would open a
+ * panel nobody is watching — refusing it is the whole point of the call.
+ */
+ private async revealWorkPanelView(
+ loaded: LoadedPlugin,
+ input?: PluginRevealViewInput,
+ ): Promise<void> {
+ this.assertPermission(loaded, "ui.view");
+ const views = loaded.manifest.contributes?.views ?? [];
+ if (views.length === 0) {
+ throw apiError("NOT_FOUND", "plugin does not declare a work panel view");
+ }
+ const requested = typeof input?.viewId === "string" ? input.viewId.trim() : "";
+ const view = requested
+ ? views.find((candidate) => candidate?.id === requested)
+ : views.length === 1
+ ? views[0]
+ : undefined;
+ if (!view) {
+ throw apiError(
+ requested ? "NOT_FOUND" : "INVALID_ARGUMENT",
+ requested
+ ? `plugin has no view: ${requested}`
+ : "viewId is required when the plugin declares more than one view",
+ );
+ }
+ const location = typeof input?.location === "string" ? input.location.trim() : "";
+ if (location.length > MAX_VIEW_LOCATION_CHARS) {
+ throw apiError(
+ "INVALID_ARGUMENT",
+ `location must be at most ${MAX_VIEW_LOCATION_CHARS} characters`,
+ );
+ }
+ const named = typeof input?.sessionId === "string" ? input.sessionId.trim() : "";
+ const active = this.services.getActiveSession?.() ?? null;
+ const sessionId = named || active?.sessionId || "";
+ if (!sessionId) {
+ throw apiError("INVALID_ARGUMENT", "no session is active");
+ }
+ if (named && active?.sessionId !== named) {
+ throw apiError("INVALID_ARGUMENT", "the session is no longer the active one");
+ }
+ if (!this.services.revealView) {
+ throw apiError("UNSUPPORTED", "host api not available: ui.revealView");
+ }
+ await this.services.revealView({
+ pluginId: loaded.manifest.id,
+ viewId: view.id,
+ sessionId,
+ location: location || null,
+ });
+ this.services.audit?.({
+ pluginId: loaded.manifest.id,
+ api: "ui.revealView",
+ ok: true,
+ ts: Date.now(),
+ });
+ }
+
private async readSessionContext(loaded: LoadedPlugin): Promise<PluginLlmContext> {
this.assertPermission(loaded, "session.read");
const inFlight = this.inFlightTool(loaded.manifest.id);
@@ -5308,6 +5435,9 @@ export class PluginRuntime {
this.assertPermission(loaded, "notify");
return this.services.showNativeNotification(input);
},
+ /** Show one of this plugin's own views in a session's work panel. */
+ revealView: async (input?: PluginRevealViewInput) =>
+ this.revealWorkPanelView(loaded, input),
},
workspace: {
get: async () => {
diff --git a/apps/desktop/electron/main/runtime/session-coordination.ts b/apps/desktop/electron/main/runtime/session-coordination.ts
index a0fa85bbe..e140ea943 100644
--- a/apps/desktop/electron/main/runtime/session-coordination.ts
+++ b/apps/desktop/electron/main/runtime/session-coordination.ts
@@ -31,6 +31,13 @@ export type SessionCoordinationDependencies = {
activeTurns: Map<string, string>;
getMainWindow: () => BrowserWindow | null;
getViewingSessionId: () => string | null;
+ /**
+ * Told the moment a turn opens, with the identity the host just made durable.
+ * Nothing else observes a turn start, so this is where a plugin surface learns
+ * that the selected session began running (spec 07-plugins/03 §session).
+ * Optional: coordination stays usable without any observer.
+ */
+ onTurnStarted?: (sessionId: string, turnId: string) => void;
};
/**
@@ -44,6 +51,7 @@ export function createSessionCoordination({
activeTurns,
getMainWindow,
getViewingSessionId,
+ onTurnStarted,
}: SessionCoordinationDependencies) {
const sessionOperationTails = new Map<string, Promise<void>>();
const turnSettlements = new Map<string, Set<() => void>>();
@@ -78,6 +86,12 @@ export function createSessionCoordination({
const turns = startedTurnsBySession.get(id) ?? new Set<string>();
turns.add(turn);
startedTurnsBySession.set(id, turns);
+ try {
+ onTurnStarted?.(id, turn);
+ } catch {
+ // An observer must never fail the turn it was told about. Each plugin
+ // surface owns its delivery errors and logs them where it delivers.
+ }
}
function beginTranscriptRewrite(sessionId: string): TranscriptRewriteLease {
diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.ts
index 5ce606a5d..e410b71c4 100644
--- a/apps/desktop/electron/main/services/plugin-services.ts
+++ b/apps/desktop/electron/main/services/plugin-services.ts
@@ -54,6 +54,7 @@ import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";
import type { ClipboardHistory } from "../clipboard-history";
import type { TurnEndedPayload } from "../runtime/session-coordination";
import type { HostProcess } from "../host-process";
+import { createPluginSessionContext } from "./plugin-session-context";
import type { Logger } from "../logger";
import type { PluginAppearance } from "../../shared/plugin-panel-chrome";
@@ -77,6 +78,8 @@ export type PluginServicesDependencies = {
getWorkspacePath: () => string | null;
resolveAgentRuntimeLaunch: (...args: any[]) => Promise<any>;
vendorOAuth: VendorOAuth;
+ /** The live turn of one session, read from the host's own turn map. */
+ getActiveTurn: (sessionId: string) => string | null;
};
export function createPluginServices({
@@ -97,6 +100,7 @@ export function createPluginServices({
getWorkspacePath,
resolveAgentRuntimeLaunch,
vendorOAuth,
+ getActiveTurn,
}: PluginServicesDependencies) {
// A plugin request can lose its race with host shutdown or restart.
const isHostUnavailable = (error: unknown): boolean =>
@@ -579,7 +583,49 @@ export function createPluginServices({
data: String(error),
});
}
+ // 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.
+ pluginSession.noteTurnEnded(payload.sessionId, payload.turnId);
};
+ /**
+ * 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.
+ */
+ 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 }),
+ });
const pluginViews = new PluginViewHost(({ pluginId, url }) => {
logger.app("plugin", "warn", "plugin.api", {
pluginId,
@@ -654,6 +700,20 @@ export function createPluginServices({
getWorkspacePathForSession: (sessionId) => sessionProjects.get(sessionId) ?? null,
agentExtensionsChanged: () =>
sendToRenderer(IPC.event.pluginChanged, { reason: "agentExtensions" }),
+ /** `pi.session.getActive`: the selected session as the shell shows it. */
+ getActiveSession: () => pluginSession.snapshot(),
+ /**
+ * `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.
+ */
+ revealView: async ({ pluginId, viewId, sessionId, location }) => {
+ sendToRenderer(IPC.event.pluginViewReveal, {
+ pluginId,
+ viewId,
+ sessionId,
+ ...(location ? { location } : {}),
+ });
+ },
browser: {
reveal: (sessionId) => browserHost.reveal(sessionId),
navigate: (input, sessionId, tabId) => browserHost.navigate(input, sessionId, tabId),
@@ -691,6 +751,7 @@ export function createPluginServices({
pluginPanels,
pluginViews,
browserHost,
+ pluginSession,
speech,
};
}
diff --git a/apps/desktop/electron/main/services/plugin-session-context.ts b/apps/desktop/electron/main/services/plugin-session-context.ts
new file mode 100644
index 000000000..d6eb09b52
--- /dev/null
+++ b/apps/desktop/electron/main/services/plugin-session-context.ts
@@ -0,0 +1,113 @@
+import type { PluginActiveSession } from "@pi-desktop/plugin-sdk";
+
+/**
+ * What the user is looking at, in the shape a plugin can subscribe to
+ * (spec 07-plugins/03 §session).
+ *
+ * Two owners feed one snapshot. The renderer owns the selection, because the
+ * shell is what decides which session is on screen, so it pushes the id and the
+ * project path. The main process owns turn identity, because `activeTurns` is
+ * the only place a durable turn id exists; this module remembers *when* that
+ * turn started and never invents an identity of its own.
+ *
+ * The snapshot is a value. A session can switch or go idle between two reads, so
+ * every consumer compares `sessionId` instead of holding a reference, and a
+ * navigation naming a stale session is refused rather than applied.
+ */
+export type PluginActiveSessionSelection = {
+ sessionId: string;
+ projectPath: string | null;
+};
+
+export type PluginSessionContextDependencies = {
+ /** The live turn this session is running, straight from `activeTurns`. */
+ getActiveTurn: (sessionId: string) => string | null;
+ /** Fan-out to the three plugin surfaces: processes, panels, docked views. */
+ announce: (event: "session:activated", payload: PluginActiveSession | null) => void;
+ now?: () => number;
+ log?: (message: string, data?: Record<string, unknown>) => void;
+};
+
+export type PluginSessionContext = ReturnType<typeof createPluginSessionContext>;
+
+export function createPluginSessionContext({
+ getActiveTurn,
+ announce,
+ now = Date.now,
+ log,
+}: PluginSessionContextDependencies) {
+ let selection: PluginActiveSessionSelection | null = null;
+ /**
+ * sessionId → the turn whose start this module saw. Only a start that was
+ * observed can be dated, so an entry here is what lets the snapshot report
+ * `startedAt`; the turn id it names is still validated against `activeTurns`
+ * on every read, which is why a turn that ended without notice ages out
+ * instead of pinning a stale "running" state.
+ */
+ const turnStarts = new Map<string, { turnId: string; startedAt: number }>();
+ /** The last payload delivered, so identical snapshots stay silent. */
+ let announced: string | null = null;
+
+ const snapshot = (): PluginActiveSession | null => {
+ if (!selection) return null;
+ const turnId = getActiveTurn(selection.sessionId);
+ const started = turnStarts.get(selection.sessionId);
+ return {
+ sessionId: selection.sessionId,
+ projectPath: selection.projectPath,
+ activeTurn:
+ turnId && started?.turnId === turnId
+ ? { turnId, startedAt: started.startedAt }
+ : null,
+ };
+ };
+
+ const publish = (): void => {
+ const next = snapshot();
+ const key = JSON.stringify(next);
+ if (key === announced) return;
+ announced = key;
+ try {
+ announce("session:activated", next);
+ } catch (error) {
+ // Delivery is best-effort by contract: a surface that is gone must not
+ // break the others, and the whole fan-out is the caller's responsibility,
+ // so this only records that the snapshot reached nobody.
+ log?.("session activated announce failed", {
+ sessionId: next?.sessionId ?? null,
+ data: String(error),
+ });
+ }
+ };
+
+ return {
+ /** The current snapshot, for `pi.session.getActive` and stale checks. */
+ snapshot,
+ /**
+ * The renderer reported a different selection, or none. Keeping the start
+ * times of turns it already reported is deliberate: switching away and back
+ * must not reset the running turn's duration.
+ */
+ setActiveSession(next: PluginActiveSessionSelection | null): void {
+ const sessionId = String(next?.sessionId ?? "").trim();
+ const projectPath = String(next?.projectPath ?? "").trim() || null;
+ selection = sessionId ? { sessionId, projectPath } : null;
+ publish();
+ },
+ /** A host turn opened for this session: date it so the snapshot can report it. */
+ 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() });
+ if (selection?.sessionId === id) publish();
+ },
+ /** That turn reached a terminal state, so the session is idle again. */
+ noteTurnEnded(sessionId: string, turnId: string): void {
+ const id = String(sessionId ?? "").trim();
+ const turn = String(turnId ?? "").trim();
+ if (turnStarts.get(id)?.turnId === turn) turnStarts.delete(id);
+ if (selection?.sessionId === id) publish();
+ },
+ };
+}
diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsx
index 2685b1d78..7f2f67737 100644
--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx
+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx
@@ -29,7 +29,11 @@ import {
workPanelRequestedWidth,
workPanelWidthForSidebarReopen,
} from "../../lib/work-panel-resize";
-import { browserPluginTab, browserPluginTabForReveal } from "../../lib/work-panel-tabs";
+import {
+ browserPluginTab,
+ browserPluginTabForReveal,
+ pluginWorkPanelTab,
+} from "../../lib/work-panel-tabs";
import { useAppStore } from "../../stores/app-store";
import { useSidebarTransition } from "./useSidebarTransition";
import { useStartupWatchdog } from "./useStartupWatchdog";
@@ -68,6 +72,12 @@ export function useAppShellRuntime() {
const refreshPluginThemes = useAppStore((s) => s.refreshPluginThemes);
const plugins = useAppStore((s) => s.plugins);
const projectPath = useAppStore((s) => s.workspace?.path ?? null);
+ /** The project of the session on screen, for the plugin session snapshot. */
+ const activeSessionProjectPath = useAppStore((s) =>
+ s.activeSessionId
+ ? (s.sessions.find((session) => session.id === s.activeSessionId)?.projectPath ?? null)
+ : null,
+ );
const workPanelVisible = workPanelOpen;
const [searchOpen, setSearchOpen] = useState(false);
@@ -448,6 +458,20 @@ export function useAppShellRuntime() {
.catch(() => undefined);
}, [activeSessionId, page]);
+ /**
+ * 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.
+ */
+ useEffect(() => {
+ void api
+ .setPluginActiveSession({
+ sessionId: activeSessionId ?? null,
+ projectPath: activeSessionProjectPath,
+ })
+ .catch(() => undefined);
+ }, [activeSessionId, activeSessionProjectPath]);
+
useEffect(() => {
const acknowledgeFocusedSession = () => {
if (!ready || page !== "chat" || !activeSessionId) return;
@@ -655,6 +679,15 @@ export function useAppShellRuntime() {
state.openWorkPanelTabForSession(state.activeSessionId, browserPluginTab(path));
}
});
+ // A plugin asked to show one of its own views in the work panel
+ // (`pi.ui.revealView`). The main process already refused a stale session,
+ // so this only has to open — and focus — the tab that session owns.
+ const offPluginViewReveal = api.onPluginViewReveal((event) => {
+ useAppStore.getState().openWorkPanelTabForSession(event.sessionId, {
+ ...pluginWorkPanelTab(event.pluginId, event.viewId),
+ ...(event.location ? { location: event.location } : {}),
+ });
+ });
const offHostStatus = api.onHostStatus((status) => {
if (status.archMismatch) setArchMismatch(status.archMismatch);
if (status.ok) {
@@ -862,6 +895,7 @@ export function useAppShellRuntime() {
offBrowserPreview();
offBrowserOpenFile();
offBrowserState();
+ offPluginViewReveal();
offHostStatus();
offNotificationChanged();
offSessionsChanged();
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 7e08a3270..6adce36b8 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -670,6 +670,13 @@ export const api = {
invoke<{ ok: boolean }>(IPC.invoke.notificationSetViewingSession, {
sessionId,
}),
+ /**
+ * Report the session on screen to the main process. Plugin
+ * `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),
listSessions: () =>
invoke<{ sessions: SessionSummary[] }>(IPC.invoke.sessionList).then((result) => ({
...result,
@@ -1711,6 +1718,42 @@ export const api = {
}),
);
},
+ /**
+ * A plugin asked to show one of its own views in a session's work panel
+ * (`pi.ui.revealView`). The shell owns tabs, so it opens the tab for the
+ * session the main process already validated as the active one.
+ */
+ onPluginViewReveal: (
+ listener: (event: {
+ pluginId: string;
+ viewId: string;
+ sessionId: string;
+ location?: string;
+ }) => void,
+ ) => {
+ if (!window.piDesktop?.on) return () => undefined;
+ return window.piDesktop.on(IPC.event.pluginViewReveal, (payload) => {
+ const event = payload as {
+ pluginId?: unknown;
+ viewId?: unknown;
+ sessionId?: unknown;
+ location?: unknown;
+ };
+ if (
+ typeof event?.pluginId !== "string" ||
+ typeof event?.viewId !== "string" ||
+ typeof event?.sessionId !== "string"
+ ) {
+ return;
+ }
+ listener({
+ pluginId: event.pluginId,
+ viewId: event.viewId,
+ sessionId: event.sessionId,
+ ...(typeof event.location === "string" && event.location ? { location: event.location } : {}),
+ });
+ });
+ },
onBrowserOpenFile: (listener: (event: { path: string }) => void) => {
if (!window.piDesktop?.on) return () => undefined;
return window.piDesktop.on(IPC.event.browserOpenFile, (payload) => {
diff --git a/apps/desktop/test/main-wiring-contract.test.mjs b/apps/desktop/test/main-wiring-contract.test.mjs
index fafc93fcf..89faf3967 100644
--- a/apps/desktop/test/main-wiring-contract.test.mjs
+++ b/apps/desktop/test/main-wiring-contract.test.mjs
@@ -215,3 +215,37 @@ test("a finished turn is announced to every plugin surface", () => {
"every plugin surface must isolate its own delivery",
);
});
+
+test("the selected session is announced to every plugin surface", () => {
+ const services = read("services/plugin-services.ts");
+ const context = read("services/plugin-session-context.ts");
+ // The snapshot is announced from the one module that owns it, and reaches the
+ // same three surfaces as a finished turn.
+ assert.match(context, /announce\("session:activated", next\)/);
+ assert.match(services, /plugins\.broadcastEvent\(event, \[payload\]\)/);
+ assert.match(services, /pluginPanels\.broadcast\(event, payload\)/);
+ assert.match(services, /pluginViews\.broadcast\(event, payload\)/);
+ // Turn identity and start time come from the host, never from the renderer.
+ assert.match(
+ services,
+ /const pluginSession = createPluginSessionContext\(\{\n getActiveTurn,/,
+ );
+ assert.match(services, /pluginSession\.noteTurnEnded\(payload\.sessionId, payload\.turnId\)/);
+ const root = read("index.ts");
+ assert.match(root, /onTurnStarted: \(sessionId: string, turnId: string\)/);
+ assert.match(root, /pluginServices\.pluginSession\.noteTurnStarted\(sessionId, turnId\)/);
+});
+
+test("the shell publishes its selection and opens a revealed view", () => {
+ const shell = readFileSync(
+ join(here, "..", "src", "features", "app", "useAppShellRuntime.tsx"),
+ "utf8",
+ );
+ assert.match(shell, /api\s*\.setPluginActiveSession\(/);
+ const reveal = braceBody(
+ shell,
+ shell.indexOf("{", shell.indexOf("api.onPluginViewReveal(")),
+ );
+ assert.match(reveal, /openWorkPanelTabForSession\(event\.sessionId/);
+ assert.match(reveal, /pluginWorkPanelTab\(event\.pluginId, event\.viewId\)/);
+});
diff --git a/apps/desktop/test/plugin-session-follow.test.mjs b/apps/desktop/test/plugin-session-follow.test.mjs
new file mode 100644
index 000000000..6cd32d6f3
--- /dev/null
+++ b/apps/desktop/test/plugin-session-follow.test.mjs
@@ -0,0 +1,256 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { fork } from "node:child_process";
+import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";
+import { register } from "node:module";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const desktopRoot = join(here, "..");
+const hostProcessEntry = join(desktopRoot, "electron/main/plugin-host-process.mjs");
+
+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));
+const { PluginRuntime } = await import("../electron/main/plugin-runtime.ts");
+const { createPluginSessionContext } = await import(
+ "../electron/main/services/plugin-session-context.ts"
+);
+
+function forkPluginProcess({ entry }) {
+ const child = fork(entry, [], { stdio: ["ignore", "pipe", "pipe", "ipc"] });
+ return {
+ postMessage: (message) => child.connected && child.send(message),
+ onMessage: (handler) => child.on("message", handler),
+ onExit: (handler) => child.on("exit", (code) => handler(code ?? 0)),
+ kill: () => child.kill(),
+ };
+}
+
+/** A plugin that contributes views, so `ui.revealView` has something to name. */
+function writeViewPlugin({ id, permissions, views, main }) {
+ const dir = mkdtempSync(join(tmpdir(), "pi-session-follow-"));
+ writeFileSync(
+ join(dir, "manifest.json"),
+ JSON.stringify({
+ schemaVersion: 1,
+ id,
+ name: id,
+ version: "0.0.1",
+ main: "main.js",
+ permissions,
+ contributes: { views },
+ }),
+ "utf8",
+ );
+ writeFileSync(join(dir, "main.js"), main, "utf8");
+ for (const view of views) {
+ const entry = join(dir, view.entry);
+ mkdirSync(dirname(entry), { recursive: true });
+ writeFileSync(entry, "<!doctype html><html><body></body></html>", "utf8");
+ }
+ return dir;
+}
+
+async function runCommand(runtime, id) {
+ const command = runtime.getCommands().find((entry) => entry.id === id);
+ assert.ok(command, `command not registered: ${id}`);
+ await command.run();
+}
+
+const CHANGES_VIEW = { id: "changes", title: "Changes", entry: "views/changes.html" };
+
+test("session snapshot reports the selection and the running turn", () => {
+ const announced = [];
+ const liveTurns = new Map();
+ const context = createPluginSessionContext({
+ getActiveTurn: (sessionId) => liveTurns.get(sessionId) ?? null,
+ announce: (event, payload) => announced.push([event, payload]),
+ now: () => 1_000,
+ });
+
+ assert.equal(context.snapshot(), null);
+
+ context.setActiveSession({ sessionId: "s1", projectPath: "/work/pi" });
+ assert.deepEqual(context.snapshot(), {
+ sessionId: "s1",
+ projectPath: "/work/pi",
+ activeTurn: null,
+ });
+
+ // A turn opening in another session is not the selected session's business.
+ liveTurns.set("s2", "turn-2");
+ context.noteTurnStarted("s2", "turn-2");
+ liveTurns.set("s1", "turn-1");
+ context.noteTurnStarted("s1", "turn-1");
+
+ assert.deepEqual(context.snapshot(), {
+ sessionId: "s1",
+ projectPath: "/work/pi",
+ activeTurn: { turnId: "turn-1", startedAt: 1_000 },
+ });
+ // Selection, then the selected session's turn start.
+ assert.equal(announced.length, 2);
+ assert.equal(announced[0][0], "session:activated");
+ assert.equal(announced[1][1].activeTurn.turnId, "turn-1");
+});
+
+test("session snapshot goes idle on turn end and drops a turn the host forgot", () => {
+ const announced = [];
+ const liveTurns = new Map();
+ const context = createPluginSessionContext({
+ getActiveTurn: (sessionId) => liveTurns.get(sessionId) ?? null,
+ announce: (event, payload) => announced.push([event, payload]),
+ });
+ context.setActiveSession({ sessionId: "s1", projectPath: null });
+ liveTurns.set("s1", "turn-1");
+ context.noteTurnStarted("s1", "turn-1");
+ assert.equal(context.snapshot().activeTurn.turnId, "turn-1");
+
+ // A recorded start is only reported while the host still owns that turn: a
+ // turn that ended without a notice must not pin a stale "running" state.
+ liveTurns.delete("s1");
+ assert.equal(context.snapshot().activeTurn, null);
+
+ liveTurns.set("s1", "turn-1");
+ context.noteTurnEnded("s1", "turn-1");
+ liveTurns.delete("s1");
+ assert.equal(context.snapshot().activeTurn, null);
+ assert.equal(announced.at(-1)[0], "session:activated");
+ assert.equal(announced.at(-1)[1].activeTurn, null);
+});
+
+test("an unchanged snapshot is announced once", () => {
+ const announced = [];
+ const context = createPluginSessionContext({
+ getActiveTurn: () => null,
+ announce: (event, payload) => announced.push([event, payload]),
+ });
+ context.setActiveSession({ sessionId: "s1", projectPath: "/work/pi" });
+ context.setActiveSession({ sessionId: "s1", projectPath: "/work/pi" });
+ context.setActiveSession({ sessionId: "s1", projectPath: "/work/pi" });
+ assert.equal(announced.length, 1);
+
+ // A blank path is "no project", which is a real change, not a repeat.
+ context.setActiveSession({ sessionId: "s1", projectPath: " " });
+ assert.equal(announced.length, 2);
+ assert.equal(announced[1][1].projectPath, null);
+ context.setActiveSession(null);
+ assert.equal(announced.length, 3);
+ assert.equal(announced[2][1], null);
+});
+
+test("plugin session follow reads the snapshot and refuses a stale reveal", async (t) => {
+ const revealed = [];
+ const runtime = new PluginRuntime({
+ hostEntry: hostProcessEntry,
+ spawnProcess: forkPluginProcess,
+ getActiveSession: () => ({
+ sessionId: "s1",
+ projectPath: "/work/pi",
+ activeTurn: { turnId: "turn-1", startedAt: 1_000 },
+ }),
+ 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.follow",
+ permissions: ["ui.view"],
+ views: [CHANGES_VIEW],
+ main: `
+ module.exports = {
+ async onLoad() {
+ await pi.commands.register({
+ id: "exercise",
+ title: "Exercise",
+ run: async () => {
+ const active = await pi.session.getActive();
+ await pi.ui.showToast("active:" + active.sessionId + ":" + active.activeTurn.turnId);
+ // No view id: the plugin contributes exactly one view.
+ await pi.ui.revealView({ location: "src/App.tsx" });
+ try { await pi.ui.revealView({ viewId: "changes", sessionId: "s0" }); }
+ catch (error) { await pi.ui.showToast("stale:" + error.code); }
+ try { await pi.ui.revealView({ viewId: "missing" }); }
+ catch (error) { await pi.ui.showToast("view:" + error.code); }
+ }
+ });
+ }
+ };
+ `,
+ });
+ await runtime.loadFromPath(dir, ["ui.view"]);
+ await runCommand(runtime, "exercise");
+
+ assert.deepEqual(runtime.drainToasts(), [
+ "active:s1:turn-1",
+ "stale:INVALID_ARGUMENT",
+ "view:NOT_FOUND",
+ ]);
+ assert.deepEqual(revealed, [
+ {
+ pluginId: "demo.follow",
+ viewId: "changes",
+ sessionId: "s1",
+ location: "src/App.tsx",
+ },
+ ]);
+});
+
+test("revealing a work-panel view requires the view permission", async (t) => {
+ const revealed = [];
+ const runtime = new PluginRuntime({
+ hostEntry: hostProcessEntry,
+ spawnProcess: forkPluginProcess,
+ getActiveSession: () => ({ sessionId: "s1", projectPath: null, activeTurn: null }),
+ 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.no-view-grant",
+ permissions: [],
+ views: [CHANGES_VIEW],
+ main: `
+ module.exports = {
+ async onLoad() {
+ await pi.commands.register({
+ id: "exercise",
+ title: "Exercise",
+ run: async () => {
+ try { await pi.ui.revealView(); }
+ catch (error) { await pi.ui.showToast(error.code); }
+ }
+ });
+ }
+ };
+ `,
+ });
+ await runtime.loadFromPath(dir, []);
+ await runCommand(runtime, "exercise");
+ assert.deepEqual(runtime.drainToasts(), ["PERMISSION_DENIED"]);
+ assert.deepEqual(revealed, []);
+});
+
+test("a docked view reads the same snapshot through the panel bridge", async (t) => {
+ const runtime = new PluginRuntime({
+ hostEntry: hostProcessEntry,
+ spawnProcess: forkPluginProcess,
+ getActiveSession: () => ({ sessionId: "s7", projectPath: "/work/pi", activeTurn: null }),
+ });
+ t.after(async () => {
+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);
+ });
+ const dir = writeViewPlugin({
+ id: "demo.view-bridge",
+ permissions: ["ui.view"],
+ views: [CHANGES_VIEW],
+ main: "module.exports = { async onLoad() {} };",
+ });
+ await runtime.loadFromPath(dir, ["ui.view"]);
+ const snapshot = await runtime.invokePanelBridge("demo.view-bridge", "session.getActive");
+ assert.deepEqual(snapshot, { sessionId: "s7", projectPath: "/work/pi", activeTurn: null });
+});
diff --git a/docs/adr/0331-plugin-session-follow-and-work-panel-reveal.md b/docs/adr/0331-plugin-session-follow-and-work-panel-reveal.md
new file mode 100644
index 000000000..b5659773a
--- /dev/null
+++ b/docs/adr/0331-plugin-session-follow-and-work-panel-reveal.md
@@ -0,0 +1,86 @@
+# ADR 0331: Plugin session follow and host-owned work-panel reveal
+
+- Status: Accepted
+- Date: 2026-10-18
+- Deciders: PI-Desktop maintainers
+- Related: [ADR 0104](0104-plugin-work-panel-views.md) ·
+ [ADR 0263](0263-project-groups-and-folder-roots.md) ·
+ [ADR 0330](0330-open-html-files-in-work-panel-browser-from-plugins.md) ·
+ [07-plugins/03-plugin-api](../spec/07-plugins/03-plugin-api.md)
+
+## Context
+
+Plugins that follow the conversation — a diff view, a running-task overlay, a
+side panel that reacts to the selected session — need three facts the public API
+did not expose: which session the user is looking at, which host turn that
+session is running, and how to show the plugin's own view beside that session.
+
+The only way to obtain them was to import the host's internal modules from a
+plugin renderer entry, which the packaging check refuses as dynamic module
+loading (`renderer/index.mjs:466: dynamic or remote code execution`). The
+plugin then cannot be published at all, and the workaround a plugin author
+reaches for next is host-store access, which is exactly the boundary the
+plugin SDK exists to keep.
+
+The host already had every piece internally: the renderer owns the selection,
+the main process owns `activeTurns`, and the work panel owns one tab set per
+session. `session:activated` was already documented as a planned event.
+
+## Decision
+
+1. Add the additive `pi.session.getActive(): Promise<PluginActiveSession | null>`
+ with `{ sessionId, projectPath, activeTurn: { turnId, startedAt } | null }`,
+ and deliver the same payload on the `session:activated` event whenever that
+ snapshot changes. It takes no session id and needs no new permission: it
+ reports what the shell already shows, exactly as `workspace.get` reports the
+ open folder.
+2. Assemble the snapshot from two owners rather than one. The renderer pushes
+ its selection and the session's project path over a dedicated IPC invoke; the
+ main process dates the turn start from the same `recordTurnStart` seam that
+ already records durable turn identity, and validates every reported turn id
+ against `activeTurns` before publishing it. A turn that ended without notice
+ therefore ages out instead of pinning a stale "running" state.
+3. Add the additive `pi.ui.revealView({ viewId?, location?, sessionId? })`
+ requiring `ui.view`. It resolves the plugin's own `contributes.views`,
+ caps the location, and compares `sessionId` with the active session before
+ Electron Main asks the renderer to open that session's tab. Reuse the
+ existing `piViewOpen` / `view:open` location transport, so a live view is
+ never reloaded.
+4. Expose both on the panel bridge as `session.getActive` and `ui.revealView`,
+ so a docked view reads the same snapshot and reveals itself.
+5. No host-core protocol, persisted data, manifest schema, or permission list
+ changes. Older hosts reject the new calls with `UNSUPPORTED`, which is what a
+ plugin already has to handle.
+
+## Consequences
+
+- A plugin can follow the selected session, name its running turn, and open its
+ own view beside that session without touching host internals, which makes
+ such plugins publishable again.
+- The selection stays shell-owned: a plugin cannot address a session the user
+ is not looking at, and a reveal naming a session the user left is refused
+ instead of opening a tab nobody sees.
+- The snapshot is a value, not a subscription handle. A plugin compares
+ `sessionId` instead of assuming the session still holds, and a missed event
+ is repaired by one `getActive()` call.
+- Session selection now crosses one more IPC hop on every switch. The push is
+ idempotent and deduplicated before any plugin is told, so an unchanged
+ snapshot costs one invoke and no event.
+
+## Alternatives considered
+
+### Expose the renderer store to `renderer.extension` plugins
+
+Rejected: it makes host internals a contract, has no permission boundary, and
+would freeze every store refactor.
+
+### Let the plugin read `pi.session.list` and infer the selection
+
+Rejected: it exposes sessions the user is not looking at, and `session.list` is
+scoped to plugin-owned sessions; inference from `session:turnEnded` and draft
+changes is what produced the wrong-turn overlay this ADR removes.
+
+### A separate `session:turnStarted` event
+
+Rejected: the snapshot already carries the turn, so a second event would give
+plugins two ways to learn one fact and two chances to disagree.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index c65981843..728f4e585 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -376,6 +376,7 @@ Each ADR includes:
| 0328 | [Open arbitrary local files in the embedded Browser](0328-browser-arbitrary-local-files.md) | Accepted (D657; amends ADR 0170; issue #1627) |
| 0329 | [Isolate parallel sessions of one project in git worktrees](0329-session-worktree-isolation.md) | Accepted (Windows E2E pending) |
| 0330 | [Open scoped HTML files in the work-panel Browser from plugins](0330-open-html-files-in-work-panel-browser-from-plugins.md) | Accepted |
+| 0331 | [Plugin session follow and host-owned work-panel reveal](0331-plugin-session-follow-and-work-panel-reveal.md) | Accepted |
| plugin-fetch-redirect-policy | [Host-enforced plugin fetch redirect policy](plugin-fetch-redirect-policy.md) | Accepted (implementation candidate for #1475) |
| local-agent-remote-workspace-tools | [Local Agent and model requests for remote workspaces](local-agent-remote-workspace-tools.md) | Accepted for implementation |
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index e6d4c5364..7bb2cf76c 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -18177,3 +18177,41 @@ host-created files. The full app's file-preview viewer is covered separately.
the theme-token and reduced-motion guarantees; the interactive sidebar
scenario remains a manual validation scenario run in a capable
environment.
+
+### E2E-267: A plugin follows the selected session and opens its own view
+
+- **Preconditions**: A development plugin that declares one
+ `contributes.views` entry and holds `ui.view`, and whose command calls
+ `pi.session.getActive()`, subscribes to `pi.events.on("session:activated")`,
+ and then calls `pi.ui.revealView({ location: "src/App.tsx" })`. Two sessions
+ exist in different projects; one of them is running a turn.
+- **Steps**:
+ 1. Select the idle session and run the plugin's command.
+ 2. Switch to the other project's session and start a turn; re-check the
+ payload the plugin reported.
+ 3. While that turn runs, run the plugin's command and inspect the work panel.
+ 4. Switch to the first session, then run the plugin's command again from a
+ stale reference to the previous session id.
+ 5. Disable the plugin and re-open the same work-panel tab.
+- **Expected**: `pi.session.getActive()` answers with the session on screen, its
+ project path, and `activeTurn: null` while it is idle. `session:activated`
+ arrives once per real change — a selection switch, a project change, and the
+ turn starting or finishing — and the running session reports the durable
+ `turnId` with its start time rather than an inferred one. `pi.ui.revealView`
+ opens the plugin's view as a work-panel tab of the active session and focuses
+ it, and the view receives `src/App.tsx` through `piViewOpen`/`view:open`
+ without being reloaded when it is already open. A call naming a session the
+ user left fails with `INVALID_ARGUMENT` and opens nothing. Revealing without
+ `ui.view` fails with `PERMISSION_DENIED`. With the plugin disabled the tab
+ reports the missing view instead of showing stale content.
+- **Specs linked**: `07-plugins/03-plugin-api.md` §ui, §session follow, §5
+ events, §6 panel bridge; ADR 0331.
+- **Acceptance**: A plugin can follow the selected session and show its own view
+ beside it without importing host internals, and a stale session can never be
+ revealed onto a panel the user is no longer looking at.
+- **Status**: Draft. Unit coverage in
+ `apps/desktop/test/plugin-session-follow.test.mjs` (snapshot assembly,
+ announcement deduplication, stale-turn and stale-session refusal,
+ `ui.view` gating, panel-bridge channel) and the wiring contract in
+ `apps/desktop/test/main-wiring-contract.test.mjs`; the interactive Electron
+ scenario remains a manual validation run.
diff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.md
index 65422a591..417c30777 100644
--- a/docs/spec/07-plugins/03-plugin-api.md
+++ b/docs/spec/07-plugins/03-plugin-api.md
@@ -220,6 +220,33 @@ the banner without changing the durable task notification inbox. Clicking a
delivered plugin notification restores and focuses the main window, but never
activates a session or creates a durable task notification.
+`pi.ui.revealView` shows one of the plugin's own `contributes.views` in the work
+panel of a session, which is the supported replacement for reaching into the
+host's own navigation:
+
+```ts
+pi.ui.revealView(input?: {
+ viewId?: string // one of contributes.views; omittable when there is one
+ location?: string // the same opaque subject a view already receives
+ sessionId?: string // the session whose panel shows it; defaults to the active one
+}): Promise<void>
+```
+
+Requires `ui.view`, like the view itself. The host resolves the view and refuses
+a `viewId` that does not name exactly one declared view (`NOT_FOUND` when the
+plugin declares none or the name is unknown, `INVALID_ARGUMENT` when the plugin
+declares several and the call names none). `location` is capped at 8 KiB.
+`sessionId` is compared with the session the user is looking at: a session that
+is no longer the active one rejects with `INVALID_ARGUMENT` instead of opening a
+tab nobody is watching, and a call made with no active session rejects the same
+way. The tab belongs to the shell — the plugin names the view and the subject,
+the shell opens and focuses it — so the `location` still travels through
+`piViewOpen` / `view:open` and a live view is never reloaded.
+
+`pi.ui.openPanel()` opens a separate window, `pi.browser.reveal()` activates the
+Browser, and `pi.fs.openDefault` / `pi.fs.reveal` hand a file to the operating
+system; none of them is this.
+
### project (requires `project.create`)
```ts
@@ -515,6 +542,37 @@ session (D333 / D336). Calling this outside a tool execution fails with
plugin's own tool is stripped from the tail. A compaction summary replaces
pre-checkpoint history. Combined content is capped at 200k characters.
+### session follow (no extra permission)
+
+The selected session is what the user is looking at, and the host already shows
+it; following it needs no permission, the same way `workspace.get` reports the
+open folder.
+
+```ts
+pi.session.getActive(): Promise<PluginActiveSession | null>
+
+type PluginActiveSession = {
+ sessionId: string
+ projectPath: string | null // working directory of the session's project
+ activeTurn: { turnId: string; startedAt: number } | null
+}
+```
+
+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
+Settings page, or no chat session selected. `activeTurn` names the durable host
+turn that session is running, and is `null` while the session is idle, so a
+plugin does not have to infer a running task from the previous turn's end event
+or from draft changes. `startedAt` is the host clock in epoch ms at the moment
+that turn opened.
+
+A snapshot is a value, not a handle: the session can switch or finish between
+two calls, so a plugin compares `sessionId` and treats a mismatch as "this
+answer belongs to a session the user left". The `session:activated` event below
+delivers the same payload whenever the snapshot changes, which is what makes
+polling unnecessary. `session.getLlmContext` is a different capability: it is
+scoped to the plugin's own in-flight tool call and cannot address the selected
+session.
### session auto-title (requires `session.autoTitle`)
This capability is separate from `session.read`: it never exposes a transcript
@@ -1226,10 +1284,17 @@ Delivered today:
yet — 0.14.8 does not include it — so a plugin that depends on it must require
the release that actually ships it rather than assume 0.14.7 or 0.14.8.
+- `session:activated` — payload is the `PluginActiveSession` object or `null`,
+ sent whenever that snapshot changes: the user selected another session (or
+ left the chat), the selected session's project changed, or its running turn
+ started or stopped. Delivery is fire-and-forget like every other event; the
+ snapshot in the payload is the answer, so a missed delivery is repaired by one
+ `pi.session.getActive()` call. Needs no permission, and the selected session's
+ turn id is the same identity `session:turnEnded` reports.
+
A throwing handler is logged and does not affect other listeners or the plugin.
-Planned events:
-- `session:activated`
+Planned events: none.
## 6. Panel bridge API
@@ -1248,7 +1313,7 @@ works in either placement. The only differences are chrome and the view
and its `--pi-plugin-titlebar-height` is `0px` rather than `46px`.
Detached panel pages using the current chrome contract declare
-`<meta name="pi-plugin-chrome" content="v2">` and use the published variable
+| `ui.revealView` | `ui.view` |
for normal-flow top spacing. The host preserves that page-owned spacing. A
page without the marker remains supported through the legacy additive offset.
@@ -1305,6 +1370,8 @@ The host-owned preload forwards only fixed channels to the plugin runtime:
| `clipboard.writeText` | `clipboard.write` |
| `shell.openExternal` | `shell.openExternal` |
| `net.fetch` | `net.fetch` |
+| `session.getActive` | None |
+| `ui.revealView` | `ui.view` |
`plugin.setSettings`, `fs.remove`, and arbitrary Electron IPC are not exposed. A
channel the host does not implement itself is forwarded to the plugin's
@@ -1331,6 +1398,8 @@ Delivered today:
URL; this event delivers a later one.
- `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.
## 7. Call auditing
@@ -1354,6 +1423,8 @@ Any of the following calls must be logged for audit:
- service start / stop / restart
- models.list (returned row count)
- session.getLlmContext (session id, message count, truncated flag — never transcript text)
+- session.getActive (the selected session's presence, never its transcript)
+- ui.revealView (view id, session id, whether a location was carried)
- agent.complete (model key, sizes, usage — never prompt or completion text)
- provider.oauth (plugin id, declared provider id, operation, result/error code — never credential contents)
@@ -1384,6 +1455,7 @@ The desktop plugin runtime now implements the MVP host API surface used by local
- `agent.registerTool` / `unregisterTool` / `agent.complete`
- `speech.registerAdapter` / `unregisterAdapter` (`speech.adapter.register`)
- `models.list`, `session.getLlmContext`
+- `session.getActive` and the `session:activated` event (`ui.revealView` needs `ui.view`)
- `onProviderOAuth` and `pi.providers.oauth.prompt` / `notify` (`provider.oauth`)
- `clipboard.*`, `shell.openExternal`, `net.fetch`
- `browser.*` (guest CDP; `browser.cdp`)
diff --git a/docs/spec/07-plugins/13-plugin-permissions-matrix.md b/docs/spec/07-plugins/13-plugin-permissions-matrix.md
index 3c35e5747..c9521728c 100644
--- a/docs/spec/07-plugins/13-plugin-permissions-matrix.md
+++ b/docs/spec/07-plugins/13-plugin-permissions-matrix.md
@@ -99,6 +99,9 @@ plugin, so it carries three bounds the other modes do not:
- `ui.panel` is required to load a panel entry
- `ui.view` is required to contribute work panel views; it is independent of
`ui.panel`, so a plugin may ship docked views without a detached window
+- `ui.view` also covers `pi.ui.revealView`, which shows one of the plugin's own
+ views in a session's work panel; following the selected session
+ (`pi.session.getActive`, `session:activated`) needs no permission
- `agent.tool.register` is required to contribute agentTools
- When `fs.write` is present, it is recommended to also declare `fs.read`
- `manifest.fs.<mode>` requires the matching `fs.<mode>` permission; a scope
diff --git a/docs/zh-CN/spec/07-plugins/03-plugin-api.md b/docs/zh-CN/spec/07-plugins/03-plugin-api.md
index 5cbba3618..4e3b59ec8 100644
--- a/docs/zh-CN/spec/07-plugins/03-plugin-api.md
+++ b/docs/zh-CN/spec/07-plugins/03-plugin-api.md
@@ -206,6 +206,28 @@ pi.project.create(input: { path: string }): Promise<{
`project.create`;省略 `projectId` 的导入会保持未绑定,`projectPath` 只是历史来源
元数据,本身不会创建项目。
+`pi.ui.revealView` 在某个会话的工作面板中显示插件自己的 `contributes.views`,
+这是替代插件直接读写宿主导航的受支持接口:
+
+```ts
+pi.ui.revealView(input?: {
+ viewId?: string // contributes.views 之一;只声明一个视图时可省略
+ location?: string // 视图已经收到的那个不透明主体
+ sessionId?: string // 用哪个会话的面板显示;默认当前选中会话
+}): Promise<void>
+```
+
+和视图本身一样需要 `ui.view`。宿主解析视图并拒绝不能唯一对应一个已声明视图的
+`viewId`(没有声明任何视图、或名字未知为 `NOT_FOUND`;声明多个却未指名时为
+`INVALID_ARGUMENT`);`location` 上限 8 KiB。`sessionId` 会与用户当前正在看的
+会话比较:已不是当前会话时以 `INVALID_ARGUMENT` 拒绝,而不是打开一个没人看的
+标签页;没有选中会话时同样拒绝。标签页属于外壳——插件给出视图与主体,由外壳
+打开并聚焦——因此 `location` 仍沿 `piViewOpen` / `view:open` 传递,已加载的视图
+不会被重载。
+
+`pi.ui.openPanel()` 打开独立窗口,`pi.browser.reveal()` 激活 Browser,
+`pi.fs.openDefault` / `pi.fs.reveal` 把文件交给操作系统;三者都不是它。
+
### 工作区/fs
```ts
pi.workspace.get(): Promise<{
@@ -395,6 +417,33 @@ pi.session.getLlmContext(): Promise<PluginLlmContext>
正在飞行的工具调用会从尾部剥掉。compaction 摘要替换检查点之前的历史。
合计内容上限 200k 字符。
+### 会话跟随(不需要额外权限)
+
+选中会话就是用户正在看的东西,宿主本来就在显示它;跟随它不需要权限,
+与 `workspace.get` 报告当前打开的文件夹同理。
+
+```ts
+pi.session.getActive(): Promise<PluginActiveSession | null>
+
+type PluginActiveSession = {
+ sessionId: string
+ projectPath: string | null // 该会话所属项目的工作目录
+ activeTurn: { turnId: string; startedAt: number } | null
+}
+```
+
+它不接受 session id:宿主报告选中项,而不允许插件去寻址用户没在看的会话。
+`null` 表示首页、设置页,或没有选中任何聊天会话。`activeTurn` 是该会话正在跑的
+那个持久宿主回合,空闲时为 `null`,因此插件不必从上一回合的结束事件或草稿变化
+去推断「正在运行的任务」;`startedAt` 是宿主时钟(epoch 毫秒),取自该回合开始的
+时刻。
+
+快照是值而不是句柄:两次调用之间会话可能已经切换或结束,因此插件应比较
+`sessionId`,把不一致当作「这个答案属于用户已经离开的会话」。下面的
+`session:activated` 事件在快照变化时投递同一载荷,这才是无需轮询的原因。
+`session.getLlmContext` 是另一项能力:它限定在插件自己进行中的工具调用上,
+无法寻址选中会话。
+
### 会话自动标题(需要 `session.autoTitle`)
此能力与 `session.read` 分开:它不会开放任意转录窗口或消息查询,仅用于在回合完成后生成标题。
@@ -966,10 +1015,15 @@ pi.events.off(event, handler)
也不会报错。目前尚无任何已发布宿主会发出该事件(0.14.8 也尚未包含),因此依赖它
的插件必须按真正包含该事件的发布版本要求,而不能假定 0.14.7 或 0.14.8。
+- `session:activated` —— 载荷是 `PluginActiveSession` 对象或 `null`,在该快照变化时
+ 发送:用户切到另一个会话(或离开聊天)、选中会话的项目变化、或它的运行回合开始
+ / 结束。投递与其它事件一样是即发即忘;载荷里的快照就是答案,漏掉一次只需调用
+ 一次 `pi.session.getActive()` 补齐。不需要权限,且其中回合 id 与
+ `session:turnEnded` 报告的身份一致。
+
抛出的处理程序会被记录下来,并且不会影响其他侦听器或插件。
-计划活动:
-- `session:activated`
+计划活动:无。
## 6. 面板桥 API
@@ -1010,6 +1064,8 @@ window.pluginBridge.on(event, handler)
| `clipboard.writeText` | `clipboard.write` |
| `shell.openExternal` | `shell.openExternal` |
| `net.fetch` | `net.fetch` |
+| `session.getActive` | 无 |
+| `ui.revealView` | `ui.view` |
`plugin.setSettings`、`fs.remove` 和任意 Electron IPC 未暴露。主机自己
没有实现的通道会被转发到插件的 `onPanelInvoke(channel, payload)`,
@@ -1032,6 +1088,8 @@ window.pluginBridge.on(event, handler)
已经从入口 URL 拿到它;这个事件投递的是之后的 location。
- `session:turnEnded` —— 与 §5 的插件进程事件同一载荷,在宿主回合到达终止状态
时发送。
+- `session:activated` —— 与 §5 的插件进程事件同一载荷,在选中会话、它的项目或它的
+ 运行回合发生变化时发送。
## 7. 通话审计
@@ -1054,6 +1112,8 @@ window.pluginBridge.on(event, handler)
- 服务启动/停止/重新启动
- models.list(返回行数)
- session.getLlmContext(会话 id、消息数、truncated 标志 —— 不含转录文本)
+- session.getActive(只记录选中会话的存在,不含转录)
+- ui.revealView(视图 id、会话 id、是否携带 location)
- agent.complete(模型 key、体积、usage —— 不含提示或补全文本)
- provider.oauth(插件 id、声明的 provider id、操作、结果/错误码——绝不记录凭据内容)
@@ -1085,6 +1145,7 @@ window.pluginBridge.on(event, handler)
- `speech.registerAdapter` / `unregisterAdapter`(`speech.adapter.register`)
- `models.list`、`session.getLlmContext`
+- `session.getActive` 与 `session:activated` 事件(`ui.revealView` 需要 `ui.view`)
- `onProviderOAuth` 和 `pi.providers.oauth.prompt` / `notify`(`provider.oauth`)
- `clipboard.*`、`shell.openExternal`、`net.fetch`
- `browser.*`(访客页 CDP;`browser.cdp`)
diff --git a/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md b/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md
index e59af06d5..3aea68dfc 100644
--- a/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md
+++ b/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md
@@ -97,6 +97,8 @@ manifest 里的字段负责回答「能做到多远」。两个字段都由主
- 加载面板条目需要 `ui.panel`
- 贡献工作面板视图需要 `ui.view`;它与 `ui.panel` 相互独立,
因此插件可以只提供停靠视图而没有独立窗口
+- `ui.view` 也覆盖 `pi.ui.revealView`:在某个会话的工作面板里显示插件自己的视图;
+ 跟随选中会话(`pi.session.getActive`、`session:activated`)不需要权限
- 需要`agent.tool.register`来贡献agent工具
- 当 `fs.write` 存在时,建议同时声明 `fs.read`
- `manifest.fs.<mode>` 需要对应的 `fs.<mode>` 权限;没人能用的范围会导致校验失败,
diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts
index da955f6c3..70075658b 100644
--- a/packages/plugin-sdk/src/index.ts
+++ b/packages/plugin-sdk/src/index.ts
@@ -862,6 +862,49 @@ export type PluginLlmContext = {
truncated: boolean;
};
+/**
+ * The host turn one session is running right now (spec 07-plugins/03 §session).
+ *
+ * `turnId` is the durable identity the host opened for that turn, so a plugin
+ * can scope its own work by turn instead of guessing from the previous turn's
+ * end event or from draft changes. `startedAt` is the host's clock in epoch ms.
+ */
+export type PluginActiveTurn = {
+ readonly turnId: string;
+ readonly startedAt: number;
+};
+
+/**
+ * The session the user is looking at, as the host shows it.
+ *
+ * `projectPath` is the working directory of the session's project (`null` for a
+ * session without one). `activeTurn` is `null` while the session is idle. The
+ * snapshot is a value, not a handle: the session can change or stop between two
+ * calls, so a plugin must compare `sessionId` instead of assuming it held.
+ */
+export type PluginActiveSession = {
+ readonly sessionId: string;
+ readonly projectPath: string | null;
+ readonly activeTurn: PluginActiveTurn | null;
+};
+
+/** What `pi.ui.revealView` accepts: which of the plugin's views, showing what. */
+export type PluginRevealViewInput = {
+ /**
+ * One of the plugin's own `contributes.views`. Omitting it names the view only
+ * when the plugin contributes exactly one.
+ */
+ readonly viewId?: string;
+ /** Opaque subject for the view, the same value `piViewOpen` carries. */
+ readonly location?: string;
+ /**
+ * The session whose work panel should show the view. Omitting it means the
+ * session the user is looking at right now; naming a session that is no
+ * longer active is refused instead of opening a view on a stale panel.
+ */
+ readonly sessionId?: string;
+};
+
export type PluginCompleteInput = {
modelKey: string;
thinkingLevel?: string;
@@ -1155,6 +1198,17 @@ export type PluginHostApi = {
showNativeNotification: (
input: PluginNativeNotificationInput,
) => Promise<PluginNativeNotificationResult>;
+ /**
+ * Show one of this plugin's own `contributes.views` in the work panel of a
+ * session (`ui.view`). The view travels through the same `location` channel
+ * the tool launcher and chat file references use, and a live view receives
+ * it as a `view:open` push instead of a reload.
+ *
+ * Rejects with `INVALID_ARGUMENT` when no session is active, when the named
+ * `sessionId` is no longer the one the user is looking at, or when `viewId`
+ * does not name exactly one of the plugin's views.
+ */
+ revealView: (input?: PluginRevealViewInput) => Promise<void>;
};
project: {
create: (input: { path: string }) => Promise<PluginProjectRecord>;
@@ -1260,6 +1314,15 @@ export type PluginHostApi = {
};
session: {
getLlmContext: () => Promise<PluginLlmContext>;
+ /**
+ * The session the user is looking at, or `null` at home and while no chat
+ * session is selected. This is the snapshot the `session:activated` event
+ * carries, so a plugin that subscribes does not need to poll.
+ *
+ * It takes no session id: the host reports the selection instead of letting
+ * a plugin address a session the user is not looking at.
+ */
+ getActive: () => Promise<PluginActiveSession | null>;
getAutoTitleContext: (input: { sessionId: string }) => Promise<PluginAutoTitleContext | null>;
setAutoTitle: (input: {
sessionId: string;
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index 746db1c21..9fbe4f3f4 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -337,6 +337,12 @@ export const IPC = {
pluginViewClose: "pi-desktop/plugin/view/close",
pluginViewSetBounds: "pi-desktop/plugin/view/setBounds",
pluginViewSetVisible: "pi-desktop/plugin/view/setVisible",
+ /**
+ * The session the user is looking at, pushed by the renderer. The shell owns
+ * the selection; the main process owns turn identity, so the plugin
+ * `session:activated` snapshot is assembled from both (spec 07-plugins/03).
+ */
+ pluginSessionActive: "pi-desktop/plugin/session/active",
mcpList: "pi-desktop/mcp/list",
mcpUpsert: "pi-desktop/mcp/upsert",
mcpRemove: "pi-desktop/mcp/remove",
@@ -452,6 +458,12 @@ export const IPC = {
browserState: "pi-desktop/browser/event/state",
browserPreview: "pi-desktop/browser/event/preview",
browserOpenFile: "pi-desktop/browser/event/openFile",
+ /**
+ * A plugin asked the shell to show one of its own work-panel views
+ * (`pi.ui.revealView`). The shell owns tabs, so it — not the plugin — decides
+ * which session's panel takes the view.
+ */
+ pluginViewReveal: "pi-desktop/plugin/view/event/reveal",
windowMaximized: "pi-desktop/window/event/maximized",
windowFullScreen: "pi-desktop/window/event/fullscreen",
windowWorkPanelResize: "pi-desktop/window/event/workPanelResize",