Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(plugins): offer one line of composer suggestion from a plugin (#1785)
TioitWanga6f4ba121e52
diff --git a/apps/desktop/electron/main/bootstrap/shutdown.ts b/apps/desktop/electron/main/bootstrap/shutdown.tsindex dfd668358..b531b9a95 100644--- a/apps/desktop/electron/main/bootstrap/shutdown.ts+++ b/apps/desktop/electron/main/bootstrap/shutdown.ts@@ -9,6 +9,7 @@ import type { PersistenceOutbox } from "../persistence-outbox";import type { PluginPanelHost } from "../plugin-panel-host";import type { PluginRuntime } from "../plugin-runtime";import type { PluginViewHost } from "../plugin-view-host";+import type { ComposerSuggestionRelay } from "../services/composer-suggestion";import type { AppUpdaterController } from "../updater";import type { UserMcpRuntime } from "../user-mcp";import type { McpControlServer } from "../mcp-control";@@ -45,6 +46,8 @@ export type ShutdownDependencies = {mcpOAuth?: Pick<McpOAuthManager, "disposeAll">;browserHost: Pick<BrowserHost, "dispose">;pluginViews: Pick<PluginViewHost, "dispose">;+ /** Composer suggestions still waiting for an answer at quit (ADR 0332). */+ composerSuggestion?: Pick<ComposerSuggestionRelay, "dispose">;updater: Pick<AppUpdaterController, "dispose" | "isInstallingUpdate">;logger: Pick<Logger, "app">;confirmQuitDialog: () => Promise<boolean>;@@ -70,6 +73,7 @@ export function registerShutdownHandlers({mcpOAuth,browserHost,pluginViews,+ composerSuggestion,updater,logger,confirmQuitDialog,@@ -213,6 +217,7 @@ export function registerShutdownHandlers({userMcp.disposeAll();mcpOAuth?.disposeAll();browserHost.dispose();+ composerSuggestion?.dispose();inflightCheckpointer.dispose();try {diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex d24b89362..7e5520299 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -72,6 +72,7 @@ import { createSessionCoordination } from "./runtime/session-coordination";import { createScheduledRuntime } from "./runtime/scheduled";import { createDesktopServices } from "./services/desktop-services";import { createPluginServices } from "./services/plugin-services";+import type { ComposerSuggestionAnswer } from "./services/composer-suggestion";import { wirePluginThemeRuntimeServices } from "./plugin-theme-services";import { createSessionCollaborationService } from "./services/session-collaboration";import {@@ -638,8 +639,12 @@ const sessionCoordination = createSessionCoordination({* 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),+ onTurnStarted: (sessionId: string, turnId: string) => {+ pluginServices.pluginSession.noteTurnStarted(sessionId, turnId);+ // A new turn owns the composer now, so a suggestion about the previous one+ // stops being shown and stops being showable (ADR 0332).+ pluginServices.composerSuggestion.noteTurnStarted(sessionId, turnId);+ },});const {activeTurnUsages,@@ -884,6 +889,9 @@ function registerIpc() {},/** The shell reports the session on screen; plugin surfaces read it. */setActivePluginSession: (next) => pluginServices.pluginSession.setActiveSession(next),+ /** The shell answers a composer suggestion through the same invoke list. */+ settleComposerSuggestion: (answer: ComposerSuggestionAnswer) =>+ pluginServices.composerSuggestion.settle(answer),getPluginLauncherWindow: () => mainState.pluginLauncherWindow,togglePluginLauncher,safeOpenExternal,@@ -1075,6 +1083,7 @@ registerShutdownHandlers({mcpOAuth,browserHost,pluginViews,+ composerSuggestion: pluginServices.composerSuggestion,updater,logger,confirmQuitDialog,diff --git a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts b/apps/desktop/electron/main/ipc/plugin-ui-ipc.tsindex c0d516a95..675bef859 100644--- a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts+++ b/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts@@ -12,6 +12,11 @@ import type { PluginPanelTheme } from "../../shared/plugin-panel-chrome";import type { IpcRegistrar } from "./types";import { pluginProviderCatalogEntries } from "../plugin-provider-catalog";import { createSessionPushGate } from "../plugin-session-push-gate";+import {+ PLUGIN_COMPOSER_SUGGESTION_REFUSALS,+ type PluginComposerSuggestionRefusal,+} from "@pi-desktop/plugin-sdk";+import type { ComposerSuggestionAnswer } from "../services/composer-suggestion";export type PluginUiIpcDependencies = {registrar: IpcRegistrar;@@ -27,6 +32,12 @@ export type PluginUiIpcDependencies = {setActivePluginSession: (next: { sessionId: string; projectPath: string | null } | null,) => void;+ /**+ * The shell's answer to one composer suggestion (`pi.composer.suggest`): the+ * main process is waiting on it, because only the renderer knows whether the+ * draft could take the line.+ */+ settleComposerSuggestion: (answer: ComposerSuggestionAnswer) => boolean;};/** Register plugin panels, work-panel views, themes and services. */@@ -41,6 +52,7 @@ export function registerPluginUiIpc({getUpdaterLocale,getPluginPanelTheme,setActivePluginSession,+ settleComposerSuggestion,}: PluginUiIpcDependencies): void {const handle = (channel: string, fn: (...args: any[]) => Promise<any>) => {registrar.handle(channel, fn);@@ -86,6 +98,36 @@ export function registerPluginUiIpc({return { ok: true };},);+ /**+ * The shell's answer to one composer suggestion (`pi.composer.suggest`).+ *+ * Nothing is refused here: the offer it answers may already have been+ * replaced, dropped, or timed out, and a late answer to a forgotten offer is+ * simply not applied. `ok` therefore says the message was well formed, not+ * that a suggestion is on screen.+ */+ handle(+ IPC.invoke.pluginComposerSuggestionResult,+ async (+ payload:+ | { requestId?: string | null; shown?: boolean | null; reason?: string | null }+ | null,+ ) => {+ const requestId = typeof payload?.requestId === "string" ? payload.requestId.trim() : "";+ if (!requestId) throw new Error("INVALID_ARGUMENT: requestId is required");+ const reason =+ typeof payload?.reason === "string" &&+ (PLUGIN_COMPOSER_SUGGESTION_REFUSALS as readonly string[]).includes(payload.reason)+ ? (payload.reason as PluginComposerSuggestionRefusal)+ : undefined;+ settleComposerSuggestion({+ requestId,+ shown: payload?.shown === true,+ ...(reason ? { reason } : {}),+ });+ 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.tsindex 5237eb58e..756c03913 100644--- a/apps/desktop/electron/main/ipc/register.ts+++ b/apps/desktop/electron/main/ipc/register.ts@@ -37,6 +37,7 @@ import { registerSpeechIpc } from "./speech-ipc";import { registerVoiceIpc } from "./voice-ipc";import { registerLiveVoiceIpc } from "./live-voice-ipc";import type { LiveCallService } from "../live-voice/call-service";+import type { ComposerSuggestionAnswer } from "../services/composer-suggestion";import type { LiveVoiceWidget } from "../live-voice/widget-window";import type { IpcRegistrar } from "./types";import type { createTraySessions } from "../tray-sessions";@@ -64,6 +65,8 @@ export type RegisterIpcDependencies = {setActivePluginSession: (next: { sessionId: string; projectPath: string | null } | null,) => void;+ /** The shell's answer to a composer suggestion it was offered (ADR 0332). */+ settleComposerSuggestion: (answer: ComposerSuggestionAnswer) => boolean;activeUserSubagentDocuments: (...args: any[]) => Promise<any>;disabledBuiltinSubagents: () => Promise<string[]>;disabledBuiltinSkills: () => Promise<string[]>;@@ -99,6 +102,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {getNotificationViewingSessionId,setNotificationViewingSessionId,setActivePluginSession,+ settleComposerSuggestion,getPluginLauncherWindow,togglePluginLauncher,safeOpenExternal,@@ -505,8 +509,8 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {getUpdaterLocale,getPluginPanelTheme,setActivePluginSession,+ settleComposerSuggestion,});-registerSpeechIpc({ registrar, speech });if (voiceService) {diff --git a/apps/desktop/electron/main/plugin-host-process.mjs b/apps/desktop/electron/main/plugin-host-process.mjsindex 68dd88372..889a75146 100644--- a/apps/desktop/electron/main/plugin-host-process.mjs+++ b/apps/desktop/electron/main/plugin-host-process.mjs@@ -253,6 +253,13 @@ function buildApi() {requestNotificationPermission: () => call("ui.requestNotificationPermission"),showNativeNotification: (input) => call("ui.showNativeNotification", [input]),},+ // One line into the session's composer placeholder (ADR 0332). The shell+ // answers whether it went on screen, so a plugin never has to guess before+ // spending another completion.+ composer: {+ suggest: (input) => call("composer.suggest", [input ?? {}]),+ clearSuggestion: (input) => call("composer.clearSuggestion", [input ?? {}]),+ },project: {create: (input) => call("project.create", [input ?? {}]),},diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.tsindex fb3e4859a..cd2ded1b5 100644--- a/apps/desktop/electron/main/plugin-runtime.ts+++ b/apps/desktop/electron/main/plugin-runtime.ts@@ -71,6 +71,13 @@ import {type PluginServiceContrib,type PluginSettingContrib,type PluginComposerTransformInput,+ type PluginComposerSuggestInput,+ type PluginComposerSuggestResult,+ type PluginComposerClearSuggestionInput,+ PLUGIN_COMPOSER_SUGGESTION_MAX_CHARS,+ PLUGIN_COMPOSER_SUGGESTION_TTL_MS,+ PLUGIN_COMPOSER_SUGGESTION_TTL_MIN_MS,+ PLUGIN_COMPOSER_SUGGESTION_TTL_MAX_MS,type PluginSkillContrib,type PluginThemeVariableContrib,} from "@pi-desktop/plugin-sdk";@@ -127,6 +134,10 @@ import {PROMPT_ENHANCEMENT_PLUGIN_ID,type LegacyPromptEnhancementSettings,} from "./plugin-prompt-enhancement-migration";+import type {+ ComposerSuggestionOffer,+ ComposerSuggestionOutcome,+} from "./services/composer-suggestion";export type RegisteredCommand = {id: string;@@ -514,6 +525,14 @@ export type PluginHostServices = {sessionId: string;location: string | null;}) => Promise<void>;+ /**+ * `pi.composer.suggest`: hand one line to the shell that owns the composer.+ * The runtime already checked the permission and shaped the text; the shell+ * says whether it went on screen, because only it knows the draft.+ */+ suggestComposer?: (offer: ComposerSuggestionOffer) => Promise<ComposerSuggestionOutcome>;+ /** `pi.composer.clearSuggestion`: drop this plugin's own line. */+ clearComposerSuggestion?: (pluginId: string, sessionId?: string) => void;project?: {create: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;};@@ -547,6 +566,8 @@ const HOST_API_ALLOWLIST = new Set(["plugin.setSettings","plugin.getDataPath","ui.revealView",+ "composer.suggest",+ "composer.clearSuggestion","ui.openPanel","ui.closePanel","ui.showToast",@@ -1032,6 +1053,34 @@ function normalizePluginSessionInput(return { ...(input as Record<string, unknown>) };}+/** Longest session or turn id a plugin may name, matching the host's own bound. */+const MAX_SESSION_ID_CHARS = 128;++/**+ * One line of suggestion text, in the form the composer draws: line breaks and+ * runs of whitespace fold to single spaces, and the result is cut at the SDK+ * ceiling. Shaping rather than refusing is deliberate — a plugin that asked for+ * a long or multi-line string still gets a usable suggestion instead of an+ * error it cannot repair from inside a turn.+ */+function composerSuggestionText(value: unknown): string {+ if (typeof value !== "string") return "";+ const line = value.replace(/\s+/g, " ").trim();+ return [...line].slice(0, PLUGIN_COMPOSER_SUGGESTION_MAX_CHARS).join("").trim();+}++/** The requested lifetime, clamped into the range the SDK publishes. */+function composerSuggestionTtl(value: unknown): number {+ if (value === undefined || value === null) return PLUGIN_COMPOSER_SUGGESTION_TTL_MS;+ if (typeof value !== "number" || !Number.isFinite(value)) {+ throw apiError("INVALID_PARAMS", "ttlMs must be a number of milliseconds");+ }+ return Math.min(+ Math.max(Math.round(value), PLUGIN_COMPOSER_SUGGESTION_TTL_MIN_MS),+ PLUGIN_COMPOSER_SUGGESTION_TTL_MAX_MS,+ );+}+/*** Bounds for the read-only usage fact listing. The host RPC re-checks the* same windows, so a caller that skips this main-process side still cannot@@ -4565,6 +4614,84 @@ export class PluginRuntime {ts: Date.now(),});}+ /**+ * `pi.composer.suggest`: one line into the composer of the session the user+ * is looking at (`composer.suggest`, ADR 0332).+ *+ * The plugin names the session and the turn its text answers. Nothing here+ * can fail the plugin for a place that will not show it: the text is shaped+ * rather than refused, and "not shown" comes back as a reason the plugin can+ * log. What does throw is a broken call — no session id, no text left after+ * shaping, a lifetime that is not a number — like every other host API.+ */+ private async suggestComposer(+ loaded: LoadedPlugin,+ input?: PluginComposerSuggestInput,+ ): Promise<PluginComposerSuggestResult> {+ this.assertPermission(loaded, "composer.suggest");+ const raw = input && typeof input === "object" ? input : ({} as PluginComposerSuggestInput);+ const sessionId = typeof raw.sessionId === "string" ? raw.sessionId.trim() : "";+ if (!sessionId || sessionId.length > MAX_SESSION_ID_CHARS) {+ throw apiError("INVALID_PARAMS", "sessionId must be a non-empty string");+ }+ const turnId = typeof raw.turnId === "string" ? raw.turnId.trim() : "";+ if (turnId.length > MAX_SESSION_ID_CHARS) {+ throw apiError("INVALID_PARAMS", "turnId must be at most 128 characters");+ }+ const text = composerSuggestionText(raw.text);+ if (!text) throw apiError("INVALID_PARAMS", "text must contain at least one visible character");+ const ttlMs = composerSuggestionTtl(raw.ttlMs);+ // A plugin scoped to another project is not part of this conversation, so+ // it does not get to write into the composer the user is looking at.+ if (!this.services.isPluginActiveInProject?.(loaded.manifest.id)) {+ return { shown: false, reason: "session-not-visible" };+ }+ if (!this.services.suggestComposer) {+ throw apiError("UNSUPPORTED", "host api not available: composer.suggest");+ }+ const result = await this.services.suggestComposer({+ pluginId: loaded.manifest.id,+ sessionId,+ ...(turnId ? { turnId } : {}),+ text,+ ttlMs,+ });+ this.services.audit?.({+ pluginId: loaded.manifest.id,+ api: "composer.suggest",+ ok: true,+ sessionId,+ shown: result.shown,+ ...(result.shown ? {} : { reason: result.reason }),+ ts: Date.now(),+ });+ return result;+ }++ /**+ * `pi.composer.clearSuggestion`: drop the caller's own line. Nothing is shown+ * when it is already gone, so the answer never depends on what the shell had.+ */+ private clearComposerSuggestion(+ loaded: LoadedPlugin,+ input?: PluginComposerClearSuggestionInput,+ ): { ok: true } {+ this.assertPermission(loaded, "composer.suggest");+ const sessionId = typeof input?.sessionId === "string" ? input.sessionId.trim() : "";+ if (sessionId.length > MAX_SESSION_ID_CHARS) {+ throw apiError("INVALID_PARAMS", "sessionId must be at most 128 characters");+ }+ this.services.clearComposerSuggestion?.(loaded.manifest.id, sessionId || undefined);+ this.services.audit?.({+ pluginId: loaded.manifest.id,+ api: "composer.clearSuggestion",+ ok: true,+ sessionId: sessionId || null,+ ts: Date.now(),+ });+ return { ok: true };+ }+private async readSessionContext(loaded: LoadedPlugin): Promise<PluginLlmContext> {this.assertPermission(loaded, "session.read");@@ -5454,6 +5581,16 @@ export class PluginRuntime {revealView: async (input?: PluginRevealViewInput) =>this.revealWorkPanelView(loaded, input),},+ composer: {+ /**+ * One dismissible line in the placeholder layer of the composer the+ * user is looking at (`composer.suggest`, ADR 0332).+ */+ suggest: async (input?: PluginComposerSuggestInput) =>+ this.suggestComposer(loaded, input),+ clearSuggestion: async (input?: PluginComposerClearSuggestionInput) =>+ this.clearComposerSuggestion(loaded, input),+ },workspace: {get: async () => {// The enriched payload carries the project group behind the visiblediff --git a/apps/desktop/electron/main/services/composer-suggestion.ts b/apps/desktop/electron/main/services/composer-suggestion.tsnew file mode 100644index 000000000..0e92d0c15--- /dev/null+++ b/apps/desktop/electron/main/services/composer-suggestion.ts@@ -0,0 +1,262 @@+/**+ * The main-process half of `pi.composer.suggest` (ADR 0332).+ *+ * A suggestion is produced by a plugin process, long after the turn it answers+ * ended, so by the time it arrives the user may have typed, switched session,+ * or started another turn. Two owners therefore decide together, and this module+ * is the seam between them:+ *+ * - The main process owns the facts it already has — which session is on screen+ * (`pluginSession` snapshot) and which turn that session ran last — so a+ * suggestion naming another session, or a turn that is no longer the newest,+ * is refused here and never crosses to the window.+ * - The renderer owns the composer, so whether the draft is empty and whether a+ * composer takes input at all is its answer, sent back over an invoke. The+ * caller waits for that answer instead of being told a guess.+ *+ * Nothing here writes renderer state: the offer is a message, and the composer+ * decides. The relay also carries the two shell-side invalidations only the main+ * process sees — a new turn starting, and a plugin going away.+ */+import { randomUUID } from "node:crypto";+import type { PluginComposerSuggestionRefusal } from "@pi-desktop/plugin-sdk";+import { IPC } from "@pi-desktop/shared";++/** One suggestion a plugin asked the shell to show. */+export type ComposerSuggestionOffer = {+ pluginId: string;+ sessionId: string;+ turnId?: string;+ text: string;+ ttlMs: number;+};++/** What became of one offer: on screen, or why not. */+export type ComposerSuggestionOutcome =+ | { shown: true }+ | { shown: false; reason: PluginComposerSuggestionRefusal };++/**+ * What main sends the renderer. `offer` asks the shell to show one line; `clear`+ * orders it to drop what it shows — of one plugin, of one session, or of+ * whatever it holds when neither is named.+ */+export type ComposerSuggestionMessage =+ | {+ kind: "offer";+ requestId: string;+ pluginId: string;+ sessionId: string;+ turnId?: string;+ text: string;+ /** Epoch milliseconds; the shell drops the line at this moment. */+ expiresAt: number;+ }+ | { kind: "clear"; pluginId?: string; sessionId?: string };++/** The shell's answer to one `offer`, as it arrives over its own invoke. */+export type ComposerSuggestionAnswer = {+ requestId: string;+ shown: boolean;+ reason?: PluginComposerSuggestionRefusal;+};++export type ComposerSuggestionRelayDependencies = {+ sendToRenderer: (channel: string, payload: unknown) => void;+ /** The session the shell shows, read from the plugin session snapshot. */+ getActiveSession: () => { sessionId: string } | null;+ /** How long the shell has to answer an offer; a slow window is no window. */+ answerTimeoutMs?: number;+ now?: () => number;+ log?: (message: string, data?: Record<string, unknown>) => void;+};++/** Longest wait for the renderer's answer before the offer is given up on. */+const DEFAULT_ANSWER_TIMEOUT_MS = 2_000;+/**+ * Sessions whose last known turn is still remembered. Only the newest turn per+ * session matters and a stale entry is corrected by the next turn start, so the+ * map is capped rather than grown with every session the app ever ran.+ */+const MAX_TRACKED_SESSIONS = 64;++const UNSHOWN: ComposerSuggestionOutcome = { shown: false, reason: "unsupported" };++type PendingOffer = {+ requestId: string;+ pluginId: string;+ sessionId: string;+ settle: (outcome: ComposerSuggestionOutcome) => void;+ timer: ReturnType<typeof setTimeout>;+};++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 ComposerSuggestionRelay = ReturnType<typeof createComposerSuggestionRelay>;++export function createComposerSuggestionRelay({+ sendToRenderer,+ getActiveSession,+ answerTimeoutMs = DEFAULT_ANSWER_TIMEOUT_MS,+ now = Date.now,+ log,+}: ComposerSuggestionRelayDependencies) {+ /** sessionId → the offer waiting for the shell's answer. One per session. */+ const pending = new Map<string, PendingOffer>();+ /** sessionId → the newest turn the main process heard of. */+ const latestTurns = new Map<string, string>();++ const send = (message: ComposerSuggestionMessage): void => {+ try {+ sendToRenderer(IPC.event.pluginComposerSuggestion, message);+ } catch (error) {+ // Delivery is best effort: a window that is gone must not turn a plugin's+ // suggestion call into a failure, and the offer's own timeout already+ // reports the miss.+ log?.("composer suggestion send failed", { kind: message.kind, data: String(error) });+ }+ };++ /** Forget one waiting offer and answer it with `reason`. */+ const drop = (offer: PendingOffer, reason: PluginComposerSuggestionRefusal): void => {+ if (pending.get(offer.sessionId)?.requestId === offer.requestId) {+ pending.delete(offer.sessionId);+ }+ clearTimeout(offer.timer);+ offer.settle({ shown: false, reason });+ };++ /** Exactly one offer can be in flight per session, so the loser learns it lost. */+ const preempt = (sessionId: string, reason: PluginComposerSuggestionRefusal): void => {+ const offer = pending.get(sessionId);+ if (offer) drop(offer, reason);+ };++ const answer = (offer: PendingOffer, result: ComposerSuggestionOutcome): void => {+ if (pending.get(offer.sessionId)?.requestId === offer.requestId) {+ pending.delete(offer.sessionId);+ }+ clearTimeout(offer.timer);+ offer.settle(result);+ };++ return {+ /**+ * Offer one line to the shell and wait for its answer.+ *+ * `turnId` is compared with the newest turn the main process saw for the+ * session: a suggestion about a turn that has since been overtaken names a+ * moment that is over, so it is refused here instead of arriving late in a+ * composer that belongs to the newer turn.+ */+ offer(offer: ComposerSuggestionOffer): Promise<ComposerSuggestionOutcome> {+ const active = getActiveSession();+ if (!active || active.sessionId !== offer.sessionId) {+ return Promise.resolve({ shown: false, reason: "session-not-visible" });+ }+ const newestTurn = latestTurns.get(offer.sessionId);+ if (offer.turnId && newestTurn && newestTurn !== offer.turnId) {+ return Promise.resolve({ shown: false, reason: "stale-turn" });+ }+ // The newer offer takes the session's single slot; the one still waiting+ // for an answer is told so instead of being left to time out.+ preempt(offer.sessionId, "replaced");+ const requestId = randomUUID();+ return new Promise<ComposerSuggestionOutcome>((resolve) => {+ let settled = false;+ const settle = (result: ComposerSuggestionOutcome): void => {+ if (settled) return;+ settled = true;+ resolve(result);+ };+ const timer = setTimeout(() => {+ const current = pending.get(offer.sessionId);+ if (current?.requestId === requestId) drop(current, "unsupported");+ }, answerTimeoutMs);+ // A window that closes mid-answer must not keep the timer alive.+ (timer as { unref?: () => void }).unref?.();+ pending.set(offer.sessionId, {+ requestId,+ pluginId: offer.pluginId,+ sessionId: offer.sessionId,+ settle,+ timer,+ });+ send({+ kind: "offer",+ requestId,+ pluginId: offer.pluginId,+ sessionId: offer.sessionId,+ ...(offer.turnId ? { turnId: offer.turnId } : {}),+ text: offer.text,+ expiresAt: now() + offer.ttlMs,+ });+ });+ },++ /**+ * The shell's word on one offer. Answers arrive asynchronously, so one that+ * lands after its offer was replaced, timed out or dropped is simply+ * ignored.+ */+ settle(reply: ComposerSuggestionAnswer): boolean {+ const offer = [...pending.values()].find((entry) => entry.requestId === reply.requestId);+ if (!offer) return false;+ answer(+ offer,+ reply.shown ? { shown: true } : { shown: false, reason: reply.reason ?? "unsupported" },+ );+ return true;+ },++ /**+ * A host turn opened for this session: the new turn owns the composer now,+ * and a suggestion about an earlier turn is over.+ */+ noteTurnStarted(sessionId: string, turnId: string): void {+ const id = sessionId.trim();+ const turn = turnId.trim();+ if (!id || !turn) return;+ latestTurns.set(id, turn);+ enforceBound(latestTurns, MAX_TRACKED_SESSIONS);+ preempt(id, "stale-turn");+ send({ kind: "clear", sessionId: id });+ },++ /** The plugin stopped (unloaded, disabled, crashed, revoked): its line goes. */+ clearPlugin(pluginId: string): void {+ const id = pluginId.trim();+ if (!id) return;+ for (const offer of [...pending.values()]) {+ if (offer.pluginId === id) drop(offer, "unsupported");+ }+ send({ kind: "clear", pluginId: id });+ },++ /** A plugin dropped its own suggestion; a session narrows it further. */+ clearSuggestion(pluginId: string, sessionId?: string): void {+ const id = pluginId.trim();+ if (!id) return;+ const session = sessionId?.trim() ?? "";+ for (const offer of [...pending.values()]) {+ if (offer.pluginId !== id) continue;+ if (session && offer.sessionId !== session) continue;+ drop(offer, "unsupported");+ }+ send({ kind: "clear", pluginId: id, ...(session ? { sessionId: session } : {}) });+ },++ /** The window is going away: nothing will show these offers. */+ dispose(): void {+ for (const offer of [...pending.values()]) drop(offer, "unsupported");+ pending.clear();+ latestTurns.clear();+ },+ };+}diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.tsindex 9fb135f36..33251db00 100644--- a/apps/desktop/electron/main/services/plugin-services.ts+++ b/apps/desktop/electron/main/services/plugin-services.ts@@ -56,6 +56,7 @@ 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 { createComposerSuggestionRelay } from "./composer-suggestion";import type { Logger } from "../logger";import type { PluginAppearance } from "../../shared/plugin-panel-chrome";@@ -637,6 +638,17 @@ export function createPluginServices({getActiveTurn,announce: broadcastSessionEvent,});+ /**+ * `pi.composer.suggest` (ADR 0332): the main process refuses a suggestion+ * that names another session or an overtaken turn, and the shell answers+ * whether the composer can take it. The composer owns its own state, so this+ * only ever relays — nothing here writes the draft.+ */+ const composerSuggestion = createComposerSuggestionRelay({+ sendToRenderer,+ getActiveSession: () => pluginSession.snapshot(),+ log: (message, data) => logger.app("plugin", "warn", message, { data }),+ });const pluginViews = new PluginViewHost(({ pluginId, url }) => {logger.app("plugin", "warn", "plugin.api", {pluginId,@@ -730,6 +742,15 @@ export function createPluginServices({...(location ? { location } : {}),});},+ /**+ * `pi.composer.suggest`: the runtime already checked the permission and+ * shaped the text, and this only relays the offer to the shell that owns the+ * composer.+ */+ suggestComposer: (offer) => composerSuggestion.offer(offer),+ /** `pi.composer.clearSuggestion`: drop this plugin's own line. */+ clearComposerSuggestion: (pluginId, sessionId) =>+ composerSuggestion.clearSuggestion(pluginId, sessionId),browser: {reveal: (sessionId) => browserHost.reveal(sessionId),navigate: (input, sessionId, tabId) => browserHost.navigate(input, sessionId, tabId),@@ -748,6 +769,8 @@ export function createPluginServices({},onPluginUnload: (pluginId) => {if (pluginId === BROWSER_PLUGIN_ID) browserHost.disposeGuest();+ // A stopped plugin loses its line in the composer with it.+ composerSuggestion.clearPlugin(pluginId);},});const speech = createSpeechService({@@ -768,6 +791,7 @@ export function createPluginServices({pluginViews,browserHost,pluginSession,+ composerSuggestion,speech,};}diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsxindex c9baf395d..05d9fa922 100644--- a/apps/desktop/src/components/Composer.tsx+++ b/apps/desktop/src/components/Composer.tsx@@ -50,6 +50,7 @@ import { useComposerCompletions } from "../features/chat/composer/hooks/useCompoimport { useComposerDraft } from "../features/chat/composer/hooks/useComposerDraft";import { useComposerInputHistory } from "../features/chat/composer/hooks/useComposerInputHistory";import { usePluginComposerBridge } from "../features/chat/composer/hooks/usePluginComposerBridge";+import { useComposerSuggestion } from "../features/chat/composer/hooks/useComposerSuggestion";import { useComposerSubmit } from "../features/chat/composer/hooks/useComposerSubmit";import { useComposerTransforms } from "../features/chat/composer/hooks/useComposerTransforms";import { ComposerInput } from "../features/chat/composer/ComposerInput";@@ -495,6 +496,9 @@ export function Composer({// Plugin draft and attachment actions reach this composer while it takes input.usePluginComposerBridge({ ...draft, inputBlocked, enabled: localToolsAllowed });+ // A plugin may have offered one line for this empty draft; it shows in the+ // placeholder layer and `Tab` takes it (ADR 0332).+ const suggestion = useComposerSuggestion();// Keep the transcript's bottom reserve in sync with the composer's real// height (it grows with multi-line input) so the last message sits just@@ -581,6 +585,7 @@ export function Composer({enterToSend={enterToSend}runActive={runActive}composerAc={completions.ac}+ suggestion={suggestion}onPaste={pasteClipboardFiles}onAcceptCompletion={completions.acceptCompletion}onSubmit={(steering) => void submitFromComposer(steering)}diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsxindex f7058af02..08a94051e 100644--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx@@ -15,6 +15,7 @@ import { useTranslation } from "react-i18next";import { installRendererApi } from "../../capture/renderer-api";import { StartupSplash } from "../../components/StartupSplash";import { api } from "../../lib/api";+import { composerSuggestion } from "../chat/composer/plugins/suggestion-bridge";import { subscribeRemoteInteractions } from "../../lib/remote-interactions";import { playNotificationChime } from "../../lib/notification-sound";import {@@ -700,6 +701,30 @@ export function useAppShellRuntime() {...(event.location ? { location: event.location } : {}),});});+ // A plugin offered one line for the composer (`pi.composer.suggest`). The+ // shell owns the composer, so it decides here and answers the main process,+ // which is waiting on the plugin's call with that answer.+ const offComposerSuggestion = api.onPluginComposerSuggestion((event) => {+ if (event.kind === "clear") {+ composerSuggestion.clear({+ ...(event.pluginId ? { pluginId: event.pluginId } : {}),+ ...(event.sessionId ? { sessionId: event.sessionId } : {}),+ });+ return;+ }+ const outcome = composerSuggestion.offer({+ pluginId: event.pluginId,+ sessionId: event.sessionId,+ ...(event.turnId ? { turnId: event.turnId } : {}),+ text: event.text,+ expiresAt: event.expiresAt,+ });+ void api.pluginComposerSuggestionResult({+ requestId: event.requestId,+ shown: outcome.shown === true,+ ...(outcome.shown ? {} : { reason: outcome.reason }),+ });+ });const offHostStatus = api.onHostStatus((status) => {if (status.archMismatch) setArchMismatch(status.archMismatch);if (status.ok) {@@ -910,6 +935,7 @@ export function useAppShellRuntime() {offPluginViewReveal();offHostStatus();offNotificationChanged();+ offComposerSuggestion();offSessionsChanged();offRemoteInteractions();offNotificationActivated();diff --git a/apps/desktop/src/features/chat/composer/ComposerInput.tsx b/apps/desktop/src/features/chat/composer/ComposerInput.tsxindex 66ca68c02..dcacf7487 100644--- a/apps/desktop/src/features/chat/composer/ComposerInput.tsx+++ b/apps/desktop/src/features/chat/composer/ComposerInput.tsx@@ -11,6 +11,8 @@ import type {import { editorSelectionRange, readEditorValue } from "./editor";import { ComposerImagePreview } from "./ComposerImagePreview";import { ComposerImageHover } from "./ComposerImageHoverPreview";+import { composerSuggestionKeyAction } from "./plugins/suggestion-keys";+import type { ComposerSuggestionView } from "./hooks/useComposerSuggestion";import type { CompletionController } from "./hooks/useComposerCompletions";import type { ComposerImagePreviewController } from "./hooks/useComposerImagePreview";@@ -25,6 +27,12 @@ export type ComposerInputProps = {enterToSend: boolean;runActive: boolean;composerAc: CompletionController;+ /**+ * The plugin suggestion on screen, if any (ADR 0332). It is drawn in the+ * placeholder layer while the draft is empty, and `Tab` / `Esc` act on it only+ * when nothing else claims those keys.+ */+ suggestion?: ComposerSuggestionView | null;onPaste: (event: ClipboardEvent<HTMLDivElement>) => void;onAcceptCompletion: (index: number) => void;onSubmit: (steering?: boolean) => void;@@ -57,6 +65,7 @@ export function ComposerInput({enterToSend,runActive,composerAc,+ suggestion = null,onPaste,onAcceptCompletion,onSubmit,@@ -150,6 +159,19 @@ export function ComposerInput({return;}}+ // A completion list owns `Tab` and the first `Escape`; the plugin+ // suggestion only acts once neither claims the key.+ const suggestionAction = composerSuggestionKeyAction(event, {+ suggestion: suggestion !== null,+ completionItems: composerAc.hasItems,+ completionOpen: composerAc.open,+ });+ if (suggestionAction) {+ event.preventDefault();+ if (suggestionAction === "accept") suggestion?.accept();+ else suggestion?.dismiss();+ return;+ }if ((event.key === "ArrowUp" || event.key === "ArrowDown") &&!event.shiftKey &&@@ -171,13 +193,34 @@ export function ComposerInput({}}}/>+ {/* The plugin suggestion (`pi.composer.suggest`) rides in the+ placeholder layer — never a bubble — and only while the draft is+ empty, which is what makes Tab a plain "write this for me". */}{value.length === 0 ? (- <span- key={placeholderKey}- className="composer-placeholder"- aria-hidden="true"- >- {placeholderText}+ suggestion ? (+ <span+ key={`suggestion-${suggestion.text}`}+ className="composer-placeholder composer-placeholder-suggestion"+ aria-hidden="true"+ >+ <span className="composer-suggestion-text">{suggestion.text}</span>+ <span className="composer-suggestion-hint">{suggestion.hint}</span>+ </span>+ ) : (+ <span+ key={placeholderKey}+ className="composer-placeholder"+ aria-hidden="true"+ >+ {placeholderText}+ </span>+ )+ ) : null}+ {/* The visible line is decoration; the live region is what a screen+ reader announces, once, without stealing focus. */}+ {suggestion ? (+ <span className="sr-only" role="status" aria-live="polite">+ {suggestion.text}</span>) : null}</div>diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerSuggestion.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerSuggestion.tsnew file mode 100644index 000000000..2786277f8--- /dev/null+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerSuggestion.ts@@ -0,0 +1,49 @@+/**+ * The composer's view of the plugin suggestion slot (ADR 0332).+ *+ * The state itself lives in `../plugins/suggestion-bridge.ts`, outside React, so+ * a suggestion that arrives while the composer is unmounted is refused once+ * instead of queued; this only subscribes a mounted composer to it and hands the+ * placeholder layer the line and the key hint it draws.+ */+import { useMemo, useSyncExternalStore } from "react";+import { useTranslation } from "react-i18next";+import { composerSuggestion } from "../plugins/suggestion-bridge";++/** What `ComposerInput` draws and does while a suggestion is on screen. */+export type ComposerSuggestionView = {+ readonly text: string;+ /** `Tab` / `Esc` hint drawn beside the line, in the shell's language. */+ readonly hint: string;+ /** Take it: the draft becomes the text and the caret lands at its end. */+ accept(): boolean;+ dismiss(): void;+};++const subscribe = (listener: () => void) => composerSuggestion.subscribe(listener);+const snapshot = () => composerSuggestion.get();+/**+ * There is no shell state to read while the app is rendered to a string, and+ * React requires this third snapshot for exactly that pass: a suggestion is a+ * live-window fact, so a server render starts with none.+ */+const serverSnapshot = (): null => null;++export function useComposerSuggestion(): ComposerSuggestionView | null {+ const { t } = useTranslation();+ const suggestion = useSyncExternalStore(subscribe, snapshot, serverSnapshot);+ const text = suggestion?.text ?? "";+ const hint = t("chat.suggestionHint");+ return useMemo(+ () =>+ suggestion+ ? {+ text,+ hint,+ accept: () => composerSuggestion.accept(),+ dismiss: () => composerSuggestion.dismiss(),+ }+ : null,+ [suggestion, text, hint],+ );+}diff --git a/apps/desktop/src/features/chat/composer/hooks/usePluginComposerBridge.ts b/apps/desktop/src/features/chat/composer/hooks/usePluginComposerBridge.tsindex 6da1369e9..9d20d3008 100644--- a/apps/desktop/src/features/chat/composer/hooks/usePluginComposerBridge.ts+++ b/apps/desktop/src/features/chat/composer/hooks/usePluginComposerBridge.ts@@ -1,13 +1,16 @@/*** Lends this composer to the plugin draft bridge (`../plugins/draft-bridge.ts`)- * while it is mounted, and tells the bridge after every render that changed- * the draft, so plugin subscribers and the draft's generation follow it.+ * and to the plugin suggestion slot (`../plugins/suggestion-bridge.ts`) while it+ * is mounted, and tells both after every render that changed the draft, so+ * plugin subscribers follow it, the draft's generation advances, and a+ * suggestion about an empty draft ends the moment the draft stops being empty.*/import { useEffect, useRef, type RefObject } from "react";import { api } from "../../../../lib/api";import { editorSelectionRange, readEditorValue } from "../editor";import type { ComposerFileReference } from "../model";import { composerDraftBridge, type ComposerDraftHandle } from "../plugins/draft-bridge";+import { composerSuggestion } from "../plugins/suggestion-bridge";type BridgeSource = {ref: RefObject<HTMLDivElement | null>;@@ -75,14 +78,20 @@ export function usePluginComposerBridge(source: BridgeSource): void {};handleRef.current = handle;const unregister = composerDraftBridge.register(handle);+ // The suggestion slot needs the same handle: it reads the draft to decide+ // whether an offer fits and writes it when the user takes one.+ const unregisterSuggestion = composerSuggestion.register(handle);return () => {handleRef.current = null;+ unregisterSuggestion();unregister();};}, [source.enabled]);const { value, fileReferences, draftKey, referenceSessionId, inputBlocked } = source;useEffect(() => {- if (handleRef.current) composerDraftBridge.publish(handleRef.current);+ if (!handleRef.current) return;+ composerDraftBridge.publish(handleRef.current);+ composerSuggestion.publish(handleRef.current);}, [value, fileReferences, draftKey, referenceSessionId, inputBlocked]);}diff --git a/apps/desktop/src/features/chat/composer/plugins/suggestion-bridge.ts b/apps/desktop/src/features/chat/composer/plugins/suggestion-bridge.tsnew file mode 100644index 000000000..1faedf3a4--- /dev/null+++ b/apps/desktop/src/features/chat/composer/plugins/suggestion-bridge.ts@@ -0,0 +1,219 @@+/**+ * The renderer end of `pi.composer.suggest` (ADR 0332).+ *+ * A plugin process offers one line, the shell decides whether the composer can+ * take it, and the user takes it with Tab, drops it with Esc, or drops it by+ * typing. This module owns that decision and the single suggestion slot; the+ * main process owns the two facts the composer cannot know (which session is on+ * screen, which turn is current) and has already refused a stale offer before it+ * reaches here.+ *+ * The suggestion is never a draft value: it lives beside the draft and shows in+ * the placeholder layer, so nothing a plugin offers can be sent without the user+ * accepting it. Every reason the slot can be emptied is handled here:+ *+ * - the draft stops being empty (typing, pasting, a chip, `composer.insertText`,+ * `composer.replaceDraft`) — the composer publishes each change;+ * - the composer takes input for another session, or stops taking input at all;+ * - the offer's own lifetime runs out;+ * - the main process says so: a new turn started, the plugin stopped, or the+ * plugin asked to clear it.+ *+ * A renderer reload and a window close end the whole module with the page, so+ * there is nothing to hold over.+ */+import type { PluginComposerSuggestionRefusal } from "@pi-desktop/plugin-sdk";+import type { ComposerDraftHandle } from "./draft-bridge";++/** One suggestion the shell may draw in the placeholder layer. */+export type ComposerSuggestion = {+ readonly pluginId: string;+ readonly sessionId: string;+ readonly turnId?: string;+ readonly text: string;+ /** Epoch milliseconds; the line goes away at this moment. */+ readonly expiresAt: number;+};++/** What the main process asks the shell to consider. */+export type ComposerSuggestionOffer = ComposerSuggestion;++/** Whether the offer is on screen now. */+export type ComposerSuggestionOutcome =+ | { shown: true }+ | { shown: false; reason: PluginComposerSuggestionRefusal };++/** Narrowing filter for a host-ordered clear; nothing named means everything. */+export type ComposerSuggestionFilter = {+ readonly pluginId?: string;+ readonly sessionId?: string;+};++type Live = {+ readonly sessionId: string;+ readonly text: string;+ /** References the draft holds, staged attachments included. */+ readonly referenceCount: number;+};++function now(): number {+ return Date.now();+}++export class ComposerSuggestionBridge {+ private readonly handles: ComposerDraftHandle[] = [];+ private readonly listeners = new Set<() => void>();+ private current: ComposerSuggestion | null = null;+ private timer: ReturnType<typeof setTimeout> | null = null;++ /** Lend the bridge a composer; the returned call takes it back. */+ register(handle: ComposerDraftHandle): () => void {+ this.handles.push(handle);+ this.reconcile();+ return () => {+ const index = this.handles.lastIndexOf(handle);+ if (index === -1) return;+ this.handles.splice(index, 1);+ this.reconcile();+ };+ }++ /**+ * The composer's word that its draft changed. The suggestion belongs to an+ * empty draft of one session, so a first character, a staged attachment or a+ * switch of session ends it here — before any render draws it again.+ */+ publish(handle: ComposerDraftHandle): void {+ if (this.handles.at(-1) !== handle) return;+ this.reconcile();+ }++ /** The suggestion on screen, or `null`. Stable between changes. */+ get(): ComposerSuggestion | null {+ return this.current;+ }++ subscribe(listener: () => void): () => void {+ this.listeners.add(listener);+ return () => {+ this.listeners.delete(listener);+ };+ }++ /**+ * Consider one offer. Only the composer taking input can answer, so a window+ * with no composer reports `unsupported` instead of pretending.+ */+ offer(offer: ComposerSuggestionOffer): ComposerSuggestionOutcome {+ const live = this.live();+ if (!live) return { shown: false, reason: "unsupported" };+ if (live.sessionId !== offer.sessionId) return { shown: false, reason: "session-not-visible" };+ if (live.text.length > 0 || live.referenceCount > 0) {+ return { shown: false, reason: "draft-not-empty" };+ }+ // The main process dates the offer when the plugin made it, so an offer+ // that arrives after its own lifetime describes a moment that is over.+ if (offer.expiresAt <= now()) return { shown: false, reason: "stale-turn" };+ this.set({+ pluginId: offer.pluginId,+ sessionId: offer.sessionId,+ ...(offer.turnId ? { turnId: offer.turnId } : {}),+ text: offer.text,+ expiresAt: offer.expiresAt,+ });+ return { shown: true };+ }++ /**+ * Take the suggestion: the draft becomes its text, the caret lands at the end+ * and the input takes focus, which is exactly what typing that sentence would+ * have done. The existing references are kept, so an image staged in the+ * meantime is not lost.+ */+ accept(): boolean {+ const suggestion = this.current;+ const draft = this.handles.at(-1)?.read() ?? null;+ if (+ !suggestion ||+ !draft ||+ draft.text.length > 0 ||+ draft.sessionId !== suggestion.sessionId+ ) {+ this.dismiss();+ return false;+ }+ this.dismiss();+ this.handles+ .at(-1)+ ?.write(suggestion.text, [...draft.references], suggestion.text.length, true);+ return true;+ }++ /** Drop whatever is on screen. */+ dismiss(): void {+ this.set(null);+ }++ /** A host-ordered clear: one plugin, one session, or everything. */+ clear(filter: ComposerSuggestionFilter = {}): void {+ const suggestion = this.current;+ if (!suggestion) return;+ if (filter.pluginId && filter.pluginId !== suggestion.pluginId) return;+ if (filter.sessionId && filter.sessionId !== suggestion.sessionId) return;+ this.dismiss();+ }++ private set(next: ComposerSuggestion | null): void {+ if (this.timer !== null) {+ clearTimeout(this.timer);+ this.timer = null;+ }+ if (this.current === next) return;+ this.current = next;+ if (next) {+ // A lifetime the shell already spent is not a suggestion any more.+ const remaining = next.expiresAt - now();+ this.timer = setTimeout(+ () => {+ if (this.current?.expiresAt === next.expiresAt) this.dismiss();+ },+ Math.max(0, remaining),+ );+ }+ for (const listener of [...this.listeners]) listener();+ }++ /** The composer taking input and its draft, or `null`. */+ private live(): Live | null {+ const handle = this.handles.at(-1);+ const draft = handle?.read() ?? null;+ if (!handle || !draft) return null;+ return {+ sessionId: draft.sessionId,+ text: draft.text,+ referenceCount: draft.references.length,+ };+ }++ /**+ * End the suggestion when the composer can no longer hold it. Called on every+ * draft change and on every registration change, so the slot never outlives+ * the empty draft it was offered for.+ */+ private reconcile(): void {+ const suggestion = this.current;+ if (!suggestion) return;+ const live = this.live();+ if (+ !live ||+ live.sessionId !== suggestion.sessionId ||+ live.text.length > 0 ||+ live.referenceCount > 0+ ) {+ this.dismiss();+ }+ }+}++/** The app window's suggestion slot. */+export const composerSuggestion = new ComposerSuggestionBridge();diff --git a/apps/desktop/src/features/chat/composer/plugins/suggestion-keys.ts b/apps/desktop/src/features/chat/composer/plugins/suggestion-keys.tsnew file mode 100644index 000000000..9111cdb73--- /dev/null+++ b/apps/desktop/src/features/chat/composer/plugins/suggestion-keys.ts@@ -0,0 +1,44 @@+/**+ * Which key, if any, acts on the composer's plugin suggestion (ADR 0332).+ *+ * The composer already has owners for both keys and they keep them: a `@` / `/`+ * completion list takes `Tab` (and `Enter`), and its own `Escape` closes it+ * first. Only when neither claims the key, the draft is empty and a suggestion+ * is on screen does `Tab` take it and `Esc` drop it.+ *+ * Pure, so the ordering is tested without a DOM.+ */+export type ComposerSuggestionKeyAction = "accept" | "dismiss";++export type ComposerSuggestionKeyEvent = {+ readonly key: string;+ readonly shiftKey?: boolean;+ readonly altKey?: boolean;+ readonly metaKey?: boolean;+ readonly ctrlKey?: boolean;+};++export type ComposerSuggestionKeyState = {+ /** A suggestion is on screen. */+ readonly suggestion: boolean;+ /** The completion list has items, so `Tab` belongs to it. */+ readonly completionItems: boolean;+ /** A completion list is open, so the first `Escape` closes it. */+ readonly completionOpen: boolean;+};++export function composerSuggestionKeyAction(+ event: ComposerSuggestionKeyEvent,+ state: ComposerSuggestionKeyState,+): ComposerSuggestionKeyAction | null {+ if (!state.suggestion) return null;+ if (state.completionItems) return null;+ const plain = !event.altKey && !event.metaKey && !event.ctrlKey;+ if (event.key === "Escape") {+ // The list closes on the first Escape; the suggestion is the second one.+ if (state.completionOpen) return null;+ return plain ? "dismiss" : null;+ }+ if (event.key !== "Tab" || !plain) return null;+ return event.shiftKey ? null : "accept";+}diff --git a/apps/desktop/src/features/plugins/model.ts b/apps/desktop/src/features/plugins/model.tsindex d483cde5c..644cc4353 100644--- a/apps/desktop/src/features/plugins/model.ts+++ b/apps/desktop/src/features/plugins/model.ts@@ -73,6 +73,9 @@ export const PERMISSION_RISK: Record<string, RiskTier> = {"session.read.own": "medium","session.update.own": "medium","composer.transform": "medium",+ // Writes user-facing text into a draft the user may send, but only when the+ // draft is empty and only through an explicit Tab; it never reads the draft.+ "composer.suggest": "medium",// Per-turn counters and session titles only, per the usage.read matrix row."usage.read": "medium",// Two capabilities that reach outside PI-Desktop's own window or read itsdiff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex b78fe97fc..982a10cb0 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -1779,6 +1779,79 @@ export const api = {});});},+ /**+ * A plugin offered one line for the composer, or the main process ordered+ * whatever is on screen dropped (`pi.composer.suggest`, ADR 0332).+ *+ * The shell answers every offer over `pluginComposerSuggestionResult`, because+ * only the renderer knows whether the draft can take it. A malformed message+ * is ignored — nothing here decides whether a plugin's suggestion is valid.+ */+ onPluginComposerSuggestion: (+ listener: (+ event:+ | {+ kind: "offer";+ requestId: string;+ pluginId: string;+ sessionId: string;+ turnId?: string;+ text: string;+ expiresAt: number;+ }+ | { kind: "clear"; pluginId?: string; sessionId?: string },+ ) => void,+ ) => {+ if (!window.piDesktop?.on) return () => undefined;+ return window.piDesktop.on(IPC.event.pluginComposerSuggestion, (payload) => {+ const event = payload as {+ kind?: unknown;+ requestId?: unknown;+ pluginId?: unknown;+ sessionId?: unknown;+ turnId?: unknown;+ text?: unknown;+ expiresAt?: unknown;+ };+ if (event?.kind === "clear") {+ listener({+ kind: "clear",+ ...(typeof event.pluginId === "string" && event.pluginId+ ? { pluginId: event.pluginId }+ : {}),+ ...(typeof event.sessionId === "string" && event.sessionId+ ? { sessionId: event.sessionId }+ : {}),+ });+ return;+ }+ if (+ event?.kind !== "offer" ||+ typeof event.requestId !== "string" ||+ typeof event.pluginId !== "string" ||+ typeof event.sessionId !== "string" ||+ typeof event.text !== "string" ||+ typeof event.expiresAt !== "number"+ ) {+ return;+ }+ listener({+ kind: "offer",+ requestId: event.requestId,+ pluginId: event.pluginId,+ sessionId: event.sessionId,+ ...(typeof event.turnId === "string" && event.turnId ? { turnId: event.turnId } : {}),+ text: event.text,+ expiresAt: event.expiresAt,+ });+ });+ },+ /** The shell's answer to one composer suggestion the main process is waiting on. */+ pluginComposerSuggestionResult: (input: {+ requestId: string;+ shown: boolean;+ reason?: string;+ }) => invoke<{ ok: boolean }>(IPC.invoke.pluginComposerSuggestionResult, input),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/src/styles/composer.css b/apps/desktop/src/styles/composer.cssindex a3742d225..569295a3a 100644--- a/apps/desktop/src/styles/composer.css+++ b/apps/desktop/src/styles/composer.css@@ -224,6 +224,39 @@}}+/*+ * A plugin suggestion (`pi.composer.suggest`, ADR 0332) rides in the same+ * placeholder layer, so it can never cover a message. It reads brighter than+ * the shell's own placeholder because it is text a person can take with Tab,+ * not a hint about the box; the hint beside it stays quiet and never wraps.+ * The layer is always one line with an ellipsis, which is why the text, not+ * the hint, is what gets truncated on a narrow composer.+ */+.composer-placeholder-suggestion {+ display: flex;+ align-items: baseline;+ gap: 8px;+ color: var(--ds-text-primary);+ /* The shared fade ends at the placeholder's own weight, not this one's. */+ animation: none;+}++.composer-suggestion-text {+ min-width: 0;+ overflow: hidden;+ /* 62% of primary ink: brighter than the shell placeholder's 42% at 0.72. */+ opacity: 0.62;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.composer-suggestion-hint {+ flex: none;+ color: var(--ds-text-secondary);+ font-size: var(--text-xs);+ white-space: nowrap;+}+.composer-mode-chip-face {display: inline-flex;min-width: 0;diff --git a/apps/desktop/test/composer-suggestion-relay.test.mjs b/apps/desktop/test/composer-suggestion-relay.test.mjsnew file mode 100644index 000000000..820857e60--- /dev/null+++ b/apps/desktop/test/composer-suggestion-relay.test.mjs@@ -0,0 +1,147 @@+import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));++/*+ * The main-process half of `pi.composer.suggest` (ADR 0332): which offers never+ * reach the window, which one may answer, and what happens to a suggestion when+ * the turn or the plugin behind it ends first.+ */+const { createComposerSuggestionRelay } = await import(+ "../electron/main/services/composer-suggestion.ts"+);+const { IPC } = await import("@pi-desktop/shared");++const SESSION = "session-1";++function makeRelay({ activeSession = SESSION, answerTimeoutMs = 50 } = {}) {+ const sent = [];+ const relay = createComposerSuggestionRelay({+ sendToRenderer: (channel, payload) => {+ assert.equal(channel, IPC.event.pluginComposerSuggestion);+ sent.push(payload);+ },+ getActiveSession: () => (activeSession ? { sessionId: activeSession } : null),+ answerTimeoutMs,+ });+ return { relay, sent };+}++function offer(overrides = {}) {+ return {+ pluginId: "demo.suggestion",+ sessionId: SESSION,+ turnId: "turn-1",+ text: "Explain the failing test",+ ttlMs: 60_000,+ ...overrides,+ };+}++test("a suggestion for a session the user left never crosses to the window", async () => {+ const { relay, sent } = makeRelay({ activeSession: "session-2" });+ assert.deepEqual(await relay.offer(offer()), {+ shown: false,+ reason: "session-not-visible",+ });+ assert.equal(sent.length, 0);+});++test("the window's answer is what the plugin is told", async () => {+ const { relay, sent } = makeRelay();+ const pending = relay.offer(offer());++ assert.equal(sent.length, 1);+ assert.equal(sent[0].kind, "offer");+ assert.equal(sent[0].text, "Explain the failing test");+ assert.equal(sent[0].turnId, "turn-1");+ assert.ok(sent[0].expiresAt > Date.now());++ assert.equal(relay.settle({ requestId: sent[0].requestId, shown: true }), true);+ assert.deepEqual(await pending, { shown: true });++ // A second answer to the same request changes nothing.+ assert.equal(relay.settle({ requestId: sent[0].requestId, shown: true }), false);+});++test("a draft that cannot take the line is reported with its own reason", async () => {+ const { relay, sent } = makeRelay();+ const pending = relay.offer(offer());+ relay.settle({ requestId: sent[0].requestId, shown: false, reason: "draft-not-empty" });+ assert.deepEqual(await pending, { shown: false, reason: "draft-not-empty" });+});++test("a silent window costs the caller a miss, never a hang", async () => {+ const { relay } = makeRelay({ answerTimeoutMs: 20 });+ assert.deepEqual(await relay.offer(offer()), { shown: false, reason: "unsupported" });+});++test("one suggestion per session: the newer offer takes the slot", async () => {+ const { relay, sent } = makeRelay();+ const first = relay.offer(offer({ text: "first" }));+ const second = relay.offer(offer({ pluginId: "other.plugin", text: "second" }));++ assert.deepEqual(await first, { shown: false, reason: "replaced" });+ assert.equal(sent.at(-1).text, "second");+ relay.settle({ requestId: sent.at(-1).requestId, shown: true });+ assert.deepEqual(await second, { shown: true });+});++test("a new turn clears the line and refuses a suggestion about the old one", async () => {+ const { relay, sent } = makeRelay();+ const pending = relay.offer(offer());++ relay.noteTurnStarted(SESSION, "turn-2");+ assert.deepEqual(await pending, { shown: false, reason: "stale-turn" });+ assert.deepEqual(sent.at(-1), { kind: "clear", sessionId: SESSION });++ // The turn a plugin answers has been overtaken by the time its text exists.+ assert.deepEqual(await relay.offer(offer({ turnId: "turn-1" })), {+ shown: false,+ reason: "stale-turn",+ });+ // A suggestion for the turn that is running now is still allowed through.+ const current = relay.offer(offer({ turnId: "turn-2" }));+ relay.settle({ requestId: sent.at(-1).requestId, shown: true });+ assert.deepEqual(await current, { shown: true });+});++test("a plugin that stops loses its line, shown or still waiting", async () => {+ const { relay, sent } = makeRelay();+ const pending = relay.offer(offer());++ relay.clearPlugin("demo.suggestion");+ assert.deepEqual(await pending, { shown: false, reason: "unsupported" });+ assert.deepEqual(sent.at(-1), { kind: "clear", pluginId: "demo.suggestion" });++ // Another plugin's waiting offer is untouched by that clear.+ const other = relay.offer(offer({ pluginId: "other.plugin" }));+ const otherOffer = sent.at(-1);+ relay.clearPlugin("demo.suggestion");+ relay.settle({ requestId: otherOffer.requestId, shown: true });+ assert.deepEqual(await other, { shown: true });+});++test("a plugin's own clear names the plugin and, optionally, the session", () => {+ const { relay, sent } = makeRelay();+ relay.clearSuggestion("demo.suggestion", SESSION);+ assert.deepEqual(sent.at(-1), {+ kind: "clear",+ pluginId: "demo.suggestion",+ sessionId: SESSION,+ });+ relay.clearSuggestion("demo.suggestion");+ assert.deepEqual(sent.at(-1), { kind: "clear", pluginId: "demo.suggestion" });+});++test("quitting answers every waiting offer and forgets the turn history", async () => {+ const { relay } = makeRelay();+ const pending = relay.offer(offer());+ relay.dispose();+ assert.deepEqual(await pending, { shown: false, reason: "unsupported" });+++ // Nothing is left to answer for, so a late word from the window is ignored.+ assert.equal(relay.settle({ requestId: "gone", shown: true }), false);+});diff --git a/apps/desktop/test/composer-suggestion-state.test.mjs b/apps/desktop/test/composer-suggestion-state.test.mjsnew file mode 100644index 000000000..15d98a5db--- /dev/null+++ b/apps/desktop/test/composer-suggestion-state.test.mjs@@ -0,0 +1,236 @@+import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));++/*+ * The renderer half of `pi.composer.suggest` (ADR 0332): whether an offer can go+ * on screen, what takes it down, and which key acts on it while the completion+ * list still owns Tab and the first Escape.+ */+const { ComposerSuggestionBridge } = await import(+ "../src/features/chat/composer/plugins/suggestion-bridge.ts"+);+const { composerSuggestionKeyAction } = await import(+ "../src/features/chat/composer/plugins/suggestion-keys.ts"+);++const SESSION = "session-1";+const TURN = "turn-1";++/** A composer that takes input, as `usePluginComposerBridge` lends one. */+function makeHandle({+ sessionId = SESSION,+ text = "",+ references = [],+ caret = null,+} = {}) {+ return {+ state: { sessionId, text, references, caret, focused: false },+ read() {+ return {+ draftKey: this.state.sessionId || "home",+ sessionId: this.state.sessionId,+ text: this.state.text,+ references: this.state.references,+ };+ },+ focused() {+ return this.state.focused;+ },+ selection() {+ const end = this.state.caret ?? this.state.text.length;+ return { start: end, end };+ },+ write(nextText, nextReferences, nextCaret, focus) {+ this.state.text = nextText;+ this.state.references = nextReferences;+ this.state.caret = nextCaret;+ if (focus) this.state.focused = true;+ },+ async stage() {+ throw new Error("staging is not part of this test");+ },+ };+}++function offer(overrides = {}) {+ return {+ pluginId: "demo.suggestion",+ sessionId: SESSION,+ turnId: TURN,+ text: "Explain the failing test",+ expiresAt: Date.now() + 60_000,+ ...overrides,+ };+}++test("an offer shows only in the empty draft of the session it names", () => {+ const bridge = new ComposerSuggestionBridge();+ const handle = makeHandle();++ // No composer takes input: the window says so instead of queueing.+ assert.deepEqual(bridge.offer(offer()), { shown: false, reason: "unsupported" });++ const unregister = bridge.register(handle);+ assert.deepEqual(bridge.offer(offer()), { shown: true });+ assert.equal(bridge.get()?.text, "Explain the failing test");+ assert.deepEqual(bridge.offer(offer({ sessionId: "session-2" })), {+ shown: false,+ reason: "session-not-visible",+ });++ handle.state.text = "half a sentence";+ assert.deepEqual(bridge.offer(offer()), { shown: false, reason: "draft-not-empty" });++ // A staged attachment is a draft too, even with no text at all.+ handle.state.text = "";+ handle.state.references = [{ id: "ref-1" }];+ assert.deepEqual(bridge.offer(offer()), { shown: false, reason: "draft-not-empty" });++ unregister();+ assert.equal(bridge.get(), null);+});++test("an offer that is already over never appears", () => {+ const bridge = new ComposerSuggestionBridge();+ bridge.register(makeHandle());+ assert.deepEqual(bridge.offer(offer({ expiresAt: Date.now() - 1 })), {+ shown: false,+ reason: "stale-turn",+ });+ assert.equal(bridge.get(), null);+});++test("Tab writes the suggestion into the draft, keeps references, and ends it", () => {+ const bridge = new ComposerSuggestionBridge();+ const image = { id: "image-1" };+ const handle = makeHandle({ references: [] });+ bridge.register(handle);+ // The draft is empty when the offer lands; an image staged afterwards keeps+ // the suggestion, because a reference is not text.+ assert.deepEqual(bridge.offer(offer({ text: "Explain the failing test" })), { shown: true });+ handle.state.references = [image];++ assert.equal(bridge.accept(), true);+ assert.equal(handle.state.text, "Explain the failing test");+ assert.equal(handle.state.caret, "Explain the failing test".length);+ assert.equal(handle.state.focused, true);+ assert.deepEqual(handle.state.references, [image]);+ assert.equal(bridge.get(), null);+});++test("taking a suggestion the draft no longer fits is refused, not applied", () => {+ const bridge = new ComposerSuggestionBridge();+ const handle = makeHandle();+ bridge.register(handle);+ bridge.offer(offer());+ // The user typed in the same beat; the draft wins.+ handle.state.text = "mine";++ assert.equal(bridge.accept(), false);+ assert.equal(handle.state.text, "mine");+ assert.equal(bridge.get(), null);+});++test("typing, switching session and losing the composer all end the suggestion", () => {+ const bridge = new ComposerSuggestionBridge();+ const handle = makeHandle();+ bridge.register(handle);++ bridge.offer(offer());+ handle.state.text = "x";+ bridge.publish(handle);+ assert.equal(bridge.get(), null, "a first character ends it");++ handle.state.text = "";+ bridge.offer(offer());+ handle.state.sessionId = "session-2";+ bridge.publish(handle);+ assert.equal(bridge.get(), null, "the draft of another session ends it");++ handle.state.sessionId = SESSION;+ bridge.offer(offer());+ handle.state.text = "restored";+ bridge.publish(handle);+ handle.state.text = "";+ bridge.publish(handle);+ assert.equal(bridge.get(), null, "a suggestion never comes back after a change");++ bridge.offer(offer());+ assert.equal(bridge.get()?.text, "Explain the failing test");+});++test("the host's clear names a plugin, a session, or nothing", () => {+ const bridge = new ComposerSuggestionBridge();+ bridge.register(makeHandle());++ bridge.offer(offer());+ bridge.clear({ pluginId: "other.plugin" });+ assert.notEqual(bridge.get(), null, "another plugin's clear is not mine");++ bridge.clear({ pluginId: "demo.suggestion", sessionId: "session-2" });+ assert.notEqual(bridge.get(), null, "another session's clear is not this one");++ bridge.clear({ pluginId: "demo.suggestion" });+ assert.equal(bridge.get(), null);++ bridge.offer(offer());+ bridge.clear();+ assert.equal(bridge.get(), null, "an unfiltered clear drops everything");+});++test("a newer suggestion takes the slot, and the old one expires on its own clock", async () => {+ const bridge = new ComposerSuggestionBridge();+ bridge.register(makeHandle());++ bridge.offer(offer({ text: "first" }));+ bridge.offer(offer({ pluginId: "other.plugin", text: "second" }));+ assert.equal(bridge.get()?.text, "second");+ assert.equal(bridge.get()?.pluginId, "other.plugin");++ bridge.offer(offer({ text: "short-lived", expiresAt: Date.now() + 20 }));+ assert.equal(bridge.get()?.text, "short-lived");+ await new Promise((resolve) => setTimeout(resolve, 80));+ assert.equal(bridge.get(), null, "a suggestion ends when its lifetime does");+});++test("listeners see every change of the slot", () => {+ const bridge = new ComposerSuggestionBridge();+ bridge.register(makeHandle());+ let changes = 0;+ const off = bridge.subscribe(() => {+ changes += 1;+ });++ bridge.offer(offer());+ bridge.dismiss();+ off();+ bridge.offer(offer());+ assert.equal(changes, 2);+});++test("the completion list keeps Tab, and the first Escape closes it", () => {+ const tab = { key: "Tab" };+ const escape = { key: "Escape" };+ const showing = { suggestion: true, completionItems: false, completionOpen: false };+ const listOpen = { suggestion: true, completionItems: true, completionOpen: true };++ assert.equal(composerSuggestionKeyAction(tab, showing), "accept");+ assert.equal(composerSuggestionKeyAction(escape, showing), "dismiss");+ assert.equal(composerSuggestionKeyAction(tab, listOpen), null, "the list owns Tab");+ assert.equal(+ composerSuggestionKeyAction(escape, { ...listOpen, completionItems: false }),+ null,+ "the first Escape closes the list",+ );+ assert.equal(+ composerSuggestionKeyAction(tab, { ...showing, suggestion: false }),+ null,+ "no suggestion, no key",+ );+ assert.equal(composerSuggestionKeyAction({ key: "Tab", shiftKey: true }, showing), null);+ assert.equal(composerSuggestionKeyAction({ key: "Tab", metaKey: true }, showing), null);+ assert.equal(composerSuggestionKeyAction({ key: "Enter" }, showing), null);+ assert.equal(composerSuggestionKeyAction({ key: "Escape", altKey: true }, showing), null);+});diff --git a/apps/desktop/test/plugin-composer-suggestion.test.mjs b/apps/desktop/test/plugin-composer-suggestion.test.mjsnew file mode 100644index 000000000..ca646b891--- /dev/null+++ b/apps/desktop/test/plugin-composer-suggestion.test.mjs@@ -0,0 +1,220 @@+import assert from "node:assert/strict";+import { fork } from "node:child_process";+import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import test from "node:test";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { register } from "node:module";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+const dataDir = mkdtempSync(join(tmpdir(), "pi-composer-suggestion-data-"));+process.env.PI_DESKTOP_DATA_DIR = dataDir;+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 {+ PLUGIN_COMPOSER_SUGGESTION_MAX_CHARS,+ PLUGIN_COMPOSER_SUGGESTION_TTL_MS,+ PLUGIN_COMPOSER_SUGGESTION_TTL_MAX_MS,+} = await import("@pi-desktop/plugin-sdk");++function forkPluginProcess({ entry }) {+ const child = fork(entry, [], { stdio: ["ignore", "pipe", "pipe", "ipc"] });+ return {+ postMessage: (message) => {+ if (child.connected) child.send(message);+ },+ onMessage: (handler) => child.on("message", handler),+ onExit: (handler) => child.on("exit", (code) => handler(code ?? 0)),+ kill: () => child.kill(),+ };+}++function writePlugin({ id, permissions = [], main }) {+ const dir = mkdtempSync(join(tmpdir(), "pi-composer-suggestion-plugin-"));+ writeFileSync(+ join(dir, "manifest.json"),+ JSON.stringify({ schemaVersion: 1, id, name: id, version: "0.0.1", main: "main.js", permissions }),+ "utf8",+ );+ writeFileSync(join(dir, "main.js"), main, "utf8");+ return dir;+}++function makeRuntime(t, services = {}) {+ const audits = [];+ const toasts = [];+ const runtime = new PluginRuntime({+ hostEntry: hostProcessEntry,+ spawnProcess: forkPluginProcess,+ getLocale: () => "en",+ showToast: (message) => toasts.push(message),+ audit: (entry) => audits.push(entry),+ ...services,+ });+ t.after(async () => {+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);+ });+ return { runtime, audits, toasts };+}++/** Wait for the plugin's own report, which arrives after its `onLoad`. */+async function lastToast(toasts, expected) {+ for (let attempt = 0; attempt < 200; attempt += 1) {+ if (toasts.length > 0 && toasts.at(-1).startsWith(expected)) return toasts.at(-1);+ await new Promise((resolve) => setTimeout(resolve, 20));+ }+ throw new Error(`no ${expected} toast; got ${JSON.stringify(toasts)}`);+}++test("a suggestion crosses from the plugin process with the text the shell draws", async (t) => {+ const offers = [];+ const { runtime, audits, toasts } = makeRuntime(t, {+ isPluginActiveInProject: () => true,+ suggestComposer: async (offer) => {+ offers.push(offer);+ return { shown: true };+ },+ });+ const dir = writePlugin({+ id: "demo.suggestion",+ permissions: ["composer.suggest"],+ main: `module.exports = {+ onLoad: async () => {+ const result = await pi.composer.suggest({+ sessionId: " session-1 ",+ turnId: "turn-1",+ text: " Write\\nthe failing test ",+ ttlMs: 5000,+ });+ await pi.ui.showToast(JSON.stringify(result));+ },+ };`,+ });++ await runtime.loadFromPath(dir);+ assert.equal(await lastToast(toasts, "{"), '{"shown":true}');+ assert.deepEqual(offers, [+ {+ pluginId: "demo.suggestion",+ sessionId: "session-1",+ turnId: "turn-1",+ text: "Write the failing test",+ ttlMs: 5000,+ },+ ]);+ assert.equal(audits.some((entry) => entry.api === "composer.suggest" && entry.ok), true);+});++test("the host bounds the text and the lifetime instead of refusing them", async (t) => {+ const offers = [];+ const { runtime, toasts } = makeRuntime(t, {+ isPluginActiveInProject: () => true,+ suggestComposer: async (offer) => {+ offers.push(offer);+ return { shown: false, reason: "draft-not-empty" };+ },+ });+ const dir = writePlugin({+ id: "demo.suggestion.bounds",+ permissions: ["composer.suggest"],+ main: `module.exports = {+ onLoad: async () => {+ await pi.composer.suggest({ sessionId: "s", text: "x".repeat(500) });+ await pi.composer.suggest({ sessionId: "s", text: "y", ttlMs: 9_000_000 });+ await pi.ui.showToast(JSON.stringify(await pi.composer.suggest({ sessionId: "s", text: "z" })));+ },+ };`,+ });++ await runtime.loadFromPath(dir);+ assert.equal(await lastToast(toasts, "{"), '{"shown":false,"reason":"draft-not-empty"}');+ assert.equal(offers[0].text.length, PLUGIN_COMPOSER_SUGGESTION_MAX_CHARS);+ assert.equal(offers[1].ttlMs, PLUGIN_COMPOSER_SUGGESTION_TTL_MAX_MS);+ assert.equal(offers[2].ttlMs, PLUGIN_COMPOSER_SUGGESTION_TTL_MS);+});++test("a suggestion for a session the shell is not showing is a miss, not a throw", async (t) => {+ const { runtime, toasts } = makeRuntime(t, {+ // The plugin is scoped to another project, so this conversation is not its.+ isPluginActiveInProject: () => false,+ suggestComposer: async () => {+ throw new Error("the shell must not be asked");+ },+ });+ const dir = writePlugin({+ id: "demo.suggestion.scope",+ permissions: ["composer.suggest"],+ main: `module.exports = {+ onLoad: async () => {+ const result = await pi.composer.suggest({ sessionId: "session-1", text: "hi" });+ await pi.ui.showToast(JSON.stringify(result));+ },+ };`,+ });++ await runtime.loadFromPath(dir);+ assert.equal(await lastToast(toasts, "{"), '{"shown":false,"reason":"session-not-visible"}');+});++test("without the grant the call fails, and no suggestion is offered", async (t) => {+ const offers = [];+ const { runtime, toasts } = makeRuntime(t, {+ suggestComposer: async (offer) => {+ offers.push(offer);+ return { shown: true };+ },+ });+ const dir = writePlugin({+ id: "demo.suggestion.denied",+ permissions: ["composer.suggest"],+ main: `module.exports = {+ onLoad: async () => {+ try {+ await pi.composer.suggest({ sessionId: "session-1", text: "hi" });+ await pi.ui.showToast("NO_ERROR");+ } catch (error) {+ await pi.ui.showToast("ERR:" + (error && error.code ? error.code : String(error)));+ }+ },+ };`,+ });++ // Granted nothing: the manifest declares the permission, the user did not.+ await runtime.loadFromPath(dir, []);+ assert.equal(await lastToast(toasts, "ERR:"), "ERR:PERMISSION_DENIED");+ assert.deepEqual(offers, []);+});++test("a plugin's own clear reaches the shell, and a malformed call does not", async (t) => {+ const cleared = [];+ const { runtime, toasts } = makeRuntime(t, {+ suggestComposer: async () => ({ shown: true }),+ clearComposerSuggestion: (pluginId, sessionId) => cleared.push([pluginId, sessionId]),+ });+ const dir = writePlugin({+ id: "demo.suggestion.clear",+ permissions: ["composer.suggest"],+ main: `module.exports = {+ onLoad: async () => {+ await pi.composer.clearSuggestion({ sessionId: "session-1" });+ await pi.composer.clearSuggestion();+ try {+ await pi.composer.suggest({ sessionId: " ", text: "hi" });+ await pi.ui.showToast("NO_ERROR");+ } catch (error) {+ await pi.ui.showToast("ERR:" + (error && error.code ? error.code : String(error)));+ }+ },+ };`,+ });++ await runtime.loadFromPath(dir);+ assert.equal(await lastToast(toasts, "ERR:"), "ERR:INVALID_PARAMS");+ assert.deepEqual(cleared, [+ ["demo.suggestion.clear", "session-1"],+ ["demo.suggestion.clear", undefined],+ ]);+});diff --git a/docs/adr/0332-plugin-composer-suggestion.md b/docs/adr/0332-plugin-composer-suggestion.mdnew file mode 100644index 000000000..676cab0c9--- /dev/null+++ b/docs/adr/0332-plugin-composer-suggestion.md@@ -0,0 +1,124 @@+# ADR 0332: A plugin-owned suggestion in the Composer placeholder++- Status: Accepted+- Date: 2026-10-24+- Deciders: PI-Desktop maintainers+- Related: [ADR 0324](0324-plugin-owned-composer-prompt-enhancement.md) ·+ [ADR 0331](0331-plugin-session-follow-and-work-panel-reveal.md) ·+ [07-plugins/03-plugin-api](../spec/07-plugins/03-plugin-api.md) ·+ [07-plugins/13-plugin-permissions-matrix](../spec/07-plugins/13-plugin-permissions-matrix.md)++## Context++After a turn ends, a plugin often knows something the user would plausibly type+next: a follow-up question, a "continue" instruction, a correction. The only+surfaces a plugin has today are announcements that interrupt (a toast, a+notification, a work-panel view) or a rewrite of text the user already wrote+(`composer.transform`). None of them fits a suggestion: it must be visible where+the user is already looking, carried by no chrome, and trivial to ignore.++The pipeline that produces such a line is the expensive part. A plugin listens+for `session:turnEnded`, reads the session with `pi.session.getLlmContext`, runs+its own `pi.agent.complete` (up to 90 s), and only then has text. So "generate"+and "show" are seconds apart, and in that window the user may have typed,+switched session, started another turn, or uninstalled the plugin. Any contract+that assumes the composer is unchanged when the answer arrives is wrong.++The host already owns every piece needed to make this safe: the renderer owns+the draft and the placeholder layer, `activeTurns` owns turn identity, and+`composer.transform` (ADR 0324) established the permission, audit, and refusal+vocabulary for plugin text that reaches the Composer.++## Decision++1. Add `pi.composer.suggest({ sessionId, turnId?, text, ttlMs? })` and+ `pi.composer.clearSuggestion({ sessionId? })` to the Plugin SDK, gated by the+ new `composer.suggest` permission. `suggest` resolves+ `{ shown: true }` or `{ shown: false, reason }` with+ `session-not-visible` / `draft-not-empty` / `stale-turn` / `replaced` /+ `unsupported`. Only malformed input throws (`INVALID_PARAMS`).+2. Split the decision by ownership instead of centralizing it:+ - Main refuses what it can see without the renderer — a session that is not+ the one on screen, and a `turnId` that a later `onTurnStarted` overtook —+ and relays the rest, then waits for the renderer's answer.+ - The renderer refuses the rest — no composer, a blocked composer, a draft+ with text or an attachment — and answers over a dedicated invoke. The+ plugin receives that answer, so a miss is data it can log rather than an+ exception.+ Main never writes renderer state; it sends a message, exactly like+ `pi.ui.revealView` (ADR 0331).+3. Model the suggestion as a slot beside the draft, not inside it. The text is+ drawn in the existing `.composer-placeholder` layer while `value` is empty, so+ no new overlay can cover a message. `Tab` writes it into the draft (caret at+ the end, focus in the input, staged references kept); `Esc` drops it; a first+ character, a send, a session switch, a new turn, a plugin stop, a reload or a+ window close drops it too. One suggestion exists per session, and a newer+ offer replaces the older one.+4. Keep the existing key owners. A `@` / `/` completion list keeps `Tab`, and an+ open list keeps the first `Esc`; the suggestion acts only when neither claims+ the key. The keys live in a pure decision function so that ordering is+ testable without a DOM.+5. Draw it brighter than the shell's own placeholder (62% primary ink versus+ 72% secondary) with a `Tab` / `Esc` hint beside it, on one line with an+ ellipsis, and announce it once through an `sr-only` polite live region.+ `aria-placeholder` keeps describing the input, because the suggestion is not+ what the field is for.+6. Classify `composer.suggest` as **medium** risk and confirm it at install. It+ cannot read the draft, cannot send, and cannot outlive an empty draft, but it+ can put text in front of a user who may accept it with one key — the same+ trust shape as `composer.transform`.++## Consequences++- A plugin can propose the next message where the user is already looking,+ without a notification, a bubble, or a panel, and it learns immediately+ whether the suggestion was taken up.+- The shell keeps the composer authoritative: a suggestion is decorative state+ that the Composer discards on its own terms and that a plugin cannot promote+ into a draft.+- The answer to `suggest` costs one renderer round trip and a bounded wait+ (`answerTimeoutMs`, 2 s). A window that is gone, hung, or reloading answers+ nothing, and the caller is told `unsupported` instead of being left to hang.+- Suggestion text is capped at 200 characters after line breaks and runs of+ whitespace are folded, so a plugin that asked for a paragraph still gets a+ usable result instead of an error it cannot repair inside a turn.+- The permission list, the manifest schema page, the permissions matrix, the+ plugin API spec, and the nine shipped catalogs all gain one entry; no plugin+ manifest schema version, host-core schema, or persisted format changes.+- Plugins that never declare `composer.suggest` are unaffected: the namespace+ exists, the permission is not granted, and the call fails closed with+ `PERMISSION_DENIED` exactly like every other ungranted host API.++## Alternatives considered++### Let the plugin's own renderer module call `pi.dispatch("composer.setSuggestion")`++Rejected as the primary path. The text is produced by the plugin *process*+after a 90 s completion, and there is no process → renderer-module channel in+the SDK, so a renderer module would have to poll or the process would have to+own a second, invented transport. The process already has an established host+API route, and the reverse direction (a renderer module asking its own process+for an answer) is already `plugin.call`.++### A message, a toast, or an inline transcript row++Rejected: all three interrupt or occupy transcript space for a hint the user+may ignore, and none of them can become the user's own text.++### Store the suggestion as a draft value the user deletes++Rejected: it makes plugin text indistinguishable from typed text, breaks the+"empty draft" invariant other features rely on, and would let a suggestion be+sent without an explicit accept.++### Report `shown` optimistically and clear later++Rejected: the point of the answer is that the plugin can stop spending+completions on a user who is not looking at that session. `draft-not-empty` and+`session-not-visible` are exactly the cases where a guess would be wrong.++### Change `aria-placeholder` while a suggestion is shown++Rejected: the field's purpose does not change with the suggestion, and a+placeholder change is announced differently across screen readers. A polite+live region says the line once without re-describing the input.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex f1701486a..bb90e9f67 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -378,6 +378,7 @@ Each ADR includes:| 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 |+| 0332 | [A plugin-owned suggestion in the Composer placeholder](0332-plugin-composer-suggestion.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/plugin-development.md b/docs/plugin-development.mdindex 208d33eda..54e68ccb7 100644--- a/docs/plugin-development.md+++ b/docs/plugin-development.md@@ -24,6 +24,7 @@ A plugin can contribute one or more of these capabilities:| Service | Resident work supervised by the host | `contributes.services`, `background.service` permission || Message bus | Typed-by-convention events between plugins | `contributes.bus`, bus permissions || Renderer slot | UI drawn inside the app's own window: composer controls, message action bars, blocks below a reply, tool cards, code-block renderers, corner layers | `renderer`, `renderer.extension` permission, `packages/plugin-sdk/src/renderer.ts` |+| Composer suggestion | One dismissible line offered to the input box, taken with Tab | `pi.composer.suggest`, `composer.suggest` permission |Plugin entry code runs in a dedicated Node process. Panels run in sandboxed,context-isolated Electron windows with no Node integration. Calls from eitherdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 5b00986fa..a3ffd74f7 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -18356,3 +18356,29 @@ host-created files. The full app's file-preview viewer is covered separately.- **Milestone:** Maintenance.- **Status:** Automated fixture; record the tested head/base and executionresult in the delivery report.++#### E2E-1175: A plugin suggestion rides in the Composer placeholder and is taken with Tab++- **Preconditions**: A plugin that declares `composer.suggest` is installed,+ enabled, and granted the permission, and it offers one line on+ `session:turnEnded` after its own completion.+- **Steps:** 1) Run an Agent turn in a session and let it complete while that+ session is on screen and its Composer is empty. 2) Observe the placeholder+ layer. 3) Press Tab. 4) Repeat, then press Esc. 5) Repeat, then type one+ character. 6) Repeat, then switch session before the offer arrives.+- **Expected**: The suggestion appears in the placeholder layer of an empty+ draft, brighter than the shell placeholder and on one line with an ellipsis,+ with a `Tab` / `Esc` hint and one polite announcement. Tab writes the exact+ text into the draft with the caret at the end and the input focused, keeping+ any staged attachment; Esc drops it; a first character drops it; a missed+ offer answers `{ shown: false, reason }` and shows nothing. No transcript row,+ toast, or overlay appears, and the plugin's call is audited.+- **Specs linked**: `07-plugins/03-plugin-api.md`,+ `07-plugins/13-plugin-permissions-matrix.md`, ADR 0332.+- **Acceptance**: A (Composer entry path), Security (permission-gated, never+ sent by the plugin).+- **Milestone**: M6++- **Status**: Unit/source-contract-covered by+ `composer-suggestion-state.test.mjs`, `composer-suggestion-relay.test.mjs`,+ and `plugin-composer-suggestion.test.mjs`; the rendered journey remains a+ manual/Electron check when this surface changes.diff --git a/docs/spec/07-plugins/02-plugin-manifest-schema.md b/docs/spec/07-plugins/02-plugin-manifest-schema.mdindex 6d066366c..04927bcf1 100644--- a/docs/spec/07-plugins/02-plugin-manifest-schema.md+++ b/docs/spec/07-plugins/02-plugin-manifest-schema.md@@ -391,6 +391,7 @@ type PluginPermission =| "agent.prompt.inject"| "agent.complete"| "composer.transform"+| "composer.suggest"| "renderer.extension"| "provider.register"| "provider.oauth"diff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.mdindex 5946b678b..041dea630 100644--- a/docs/spec/07-plugins/03-plugin-api.md+++ b/docs/spec/07-plugins/03-plugin-api.md@@ -177,6 +177,70 @@ separately declares the permissions required by that API, such as}```+### Composer suggestions (`composer.suggest`)++A plugin may offer one short line for the Composer of the session the user is+looking at. It is drawn in the placeholder layer while the draft is empty, the+user takes it with `Tab` or drops it with `Esc`, and typing drops it too. It is+never a message, never a bubble, and the plugin cannot send it.++```ts+pi.composer.suggest(input: {+ sessionId: string; // the session from session:turnEnded+ turnId?: string; // the turn the text answers; an overtaken turn is refused+ text: string; // one line; folded and cut at 200 characters+ ttlMs?: number; // default 120000; clamped to 1000..600000+}): Promise<{ shown: true } | {+ shown: false;+ reason:+ | "session-not-visible" // that session is not on screen+ | "draft-not-empty" // the user has text or an attachment in the draft+ | "stale-turn" // the session ran a newer turn+ | "replaced" // a newer suggestion took the slot first+ | "unsupported"; // no window, no composer, or no answer in time+}>++pi.composer.clearSuggestion(input?: { sessionId?: string }): Promise<{ ok: true }>+```++Both calls need `composer.suggest`. A place that will not show the line is not+an error: the call resolves `{ shown: false, reason }` so a plugin can log the+miss and decide whether to spend another completion. Malformed input (an empty+`sessionId`, text with nothing visible in it, a non-numeric `ttlMs`) throws+`INVALID_PARAMS` like every other host API, and a missing grant throws+`PERMISSION_DENIED`.++The host shows a suggestion only when all of the following hold, and checks+them again on every change: the named session is the one on screen, the draft+is empty (no text and no attachment), the named turn is still the session's+newest turn, and a composer is mounted and taking input. One suggestion exists+per session; a newer offer replaces it and answers the superseded caller with+`replaced`. The line is cleared by: any draft change (typing, pasting, an+attachment, `composer.insertText`, `composer.replaceDraft`), a send, a session+switch, a new turn starting, the plugin unloading or being disabled,+`pi.composer.clearSuggestion`, a renderer reload, a window close, and the+suggestion's own lifetime running out. Taking it (`Tab`) puts the text in the+draft with the caret at the end and keeps any attachment already staged.++The call is audited with the plugin id, the session, and whether the line was+shown. A plugin that generates the text with a model also declares that API's+permissions, such as `agent.complete` and `models.list`.++```js+pi.events.on("session:turnEnded", async (event) => {+ if (event.reason !== "completed") return;+ const active = await pi.session.getActive();+ if (active?.sessionId !== event.sessionId) return;+ const text = await writeNextLine(active); // the plugin's own model request+ if (!text) return;+ await pi.composer.suggest({+ sessionId: event.sessionId,+ turnId: event.turnId,+ text,+ });+});+```+### speech (`speech.adapter.register`)```tspi.speech.registerAdapter(adapter: {diff --git a/docs/spec/07-plugins/13-plugin-permissions-matrix.md b/docs/spec/07-plugins/13-plugin-permissions-matrix.mdindex a597b753c..e124de0ab 100644--- a/docs/spec/07-plugins/13-plugin-permissions-matrix.md+++ b/docs/spec/07-plugins/13-plugin-permissions-matrix.md@@ -25,6 +25,7 @@ Provide a permission–capability–risk–default-policy reference table for re| `agent.tool.register` | high | Register an agent tool | Confirm at install | Tool execution is audited separately || `agent.prompt.inject` | high | Inject a system prompt; activates `contributes.skills` | Deny by default / strong confirmation | Easily leads to behavior hijacking || `composer.transform` | medium | `contributes.composerTransforms` and `onComposerTransform` | Confirm at install | Runs only after an explicit Composer action. Receives the draft and optional model key, not session history or separate attachment/file-reference metadata; request and result are capped at 100,000 characters and audited |+| `composer.suggest` | medium | `pi.composer.suggest` / `pi.composer.clearSuggestion` | Confirm at install | Writes one dismissible line into the placeholder layer of the Composer for the session on screen, only while the draft is empty and only for the turn the plugin names. The user takes it with Tab, drops it with Esc, and typing, sending, a session switch, a new turn, the plugin stopping, a reload or a window close all end it. The plugin never sends it and never reads the draft. Text is folded to one line and cut at 200 characters; the lifetime defaults to 120 s and is capped at 10 minutes. Audited; a place that will not show it answers `{ shown: false, reason }` instead of throwing || `agent.extension` | high | Run `contributes.agentExtensions` modules inside the agent process | Explicit confirmation; local imports and development plugins only in v1.1 | Same access as the agent's own tools; the plugin sandbox does not apply (spec 16) || `renderer.extension` | high | `manifest.renderer` is evaluated inside the host renderer to mount UI slots; `rendererActions` and `rendererCallMethods` open the actions and `onRendererCall` methods that module may use | Explicit confirmation; local imports and development plugins only in v1.1, matching `agent.extension` | The module shares the host's own document, so a slot is a contract rather than a sandbox. A component may dispatch only the reviewed vocabulary (`plugin.call`, `composer.insertText`, `composer.readDraft`, `composer.replaceDraft`, `attachments.add` / `list` / `remove`), capped at 16, and `plugin.call` reaches only the calling plugin's own `onRendererCall` methods, capped at 32. Registrations are withdrawn when the plugin unloads; a self-drawn dialog lives in a layer the plugin opened itself || `provider.register` | high | `contributes.providers` become rows in the native provider list, owned by the plugin and refreshed from the manifest on load; unconfigured API-key rows with an endpoint also appear in Add Service, grouped by optional `category` and with optional hover/focus `description` | Explicit confirmation; local imports and development plugins only in v1.1, matching `agent.extension` | The user path refuses edits to the row (`PROVIDER_OWNED_BY_PLUGIN`); Add Service saves the key through the existing Host secret path. Only loaded plugins with this grant contribute entries; the chooser does not expose secrets or run plugin code. An empty API-key model list discovers models after key save. |@@ -162,6 +163,7 @@ so "Modify the files it lists" is followed by the list.| `usage.read` | Read usage statistics | 读取用量统计 || `agent.complete` | Run a one-shot completion with your models | 用你的模型发起一次补全 || `composer.transform` | Transform text in the Composer | 转换输入框中的文本 |+| `composer.suggest` | Offer a suggestion in the Composer | 在输入框中给出建议 || `speech.adapter.register` | Register a speech adapter | 注册语音适配器 || `audio.capture.background` | Use the microphone in the background | 后台使用麦克风 || `audio.playback.background` | Play audio in the background | 后台播放声音 |diff --git a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.mdindex fc36a903c..1c16423f5 100644--- a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md+++ b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md@@ -323,6 +323,7 @@ type PluginPermission =| "agent.prompt.inject"| "agent.complete"| "composer.transform"+| "composer.suggest"| "renderer.extension"| "provider.register"| "net.fetch"diff --git a/docs/zh-CN/spec/07-plugins/03-plugin-api.md b/docs/zh-CN/spec/07-plugins/03-plugin-api.mdindex 8cbf6bc9d..ad5808c5e 100644--- a/docs/zh-CN/spec/07-plugins/03-plugin-api.md+++ b/docs/zh-CN/spec/07-plugins/03-plugin-api.md@@ -149,6 +149,62 @@ type PluginModule = {}```+### 输入框建议(`composer.suggest`)++插件可以为用户当前正在查看的会话输入框提供一条短建议。草稿为空时它显示在占位符层,+用户按 `Tab` 采用、按 `Esc` 忽略,开始输入也会让它消失。它不是消息、不是气泡,+插件也无法替用户发送。++```ts+pi.composer.suggest(input: {+ sessionId: string; // 来自 session:turnEnded 的会话+ turnId?: string; // 这段文本对应的轮次;已被新轮次取代则拒绝+ text: string; // 单行;折行空白并截断到 200 字符+ ttlMs?: number; // 默认 120000;限制在 1000..600000+}): Promise<{ shown: true } | {+ shown: false;+ reason:+ | "session-not-visible" // 该会话不是当前显示的会话+ | "draft-not-empty" // 草稿里已有文本或附件+ | "stale-turn" // 该会话已经跑了更新的轮次+ | "replaced" // 更新的建议先占用了位置+ | "unsupported"; // 没有窗口、没有输入框,或未及时答复+}>++pi.composer.clearSuggestion(input?: { sessionId?: string }): Promise<{ ok: true }>+```++两个调用都需要 `composer.suggest` 权限。无法展示不是错误:调用会返回+`{ shown: false, reason }`,插件可以记录这次落空并决定是否再花一次补全预算。+参数不合法(`sessionId` 为空、文本没有可见内容、`ttlMs` 不是数字)会像其他宿主 API 一样抛+`INVALID_PARAMS`,没有授予权限则抛 `PERMISSION_DENIED`。++宿主只在以下条件全部满足时显示建议,并在每次变化后重新检查:命名的会话正是当前显示的会话、+草稿为空(无文本且无附件)、命名的轮次仍是该会话最新的轮次、有输入框处于可输入状态。+每个会话同时最多一条建议;更新的建议会替换它,并把被替换的调用答复为 `replaced`。+下列任一情况都会清除建议:任何草稿变化(输入、粘贴、附件、`composer.insertText`、+`composer.replaceDraft`)、发送、切换会话、新一轮开始、插件卸载或被禁用、+`pi.composer.clearSuggestion`、页面重载、窗口关闭,以及建议自身的存活时间到期。+采用(`Tab`)会把文本写入草稿、光标置末,并保留已暂存的附件。++调用会记录审计:插件 id、会话,以及是否显示成功。若插件用模型生成文本,还需单独声明该 API+所需的权限,例如 `agent.complete` 与 `models.list`。++```js+pi.events.on("session:turnEnded", async (event) => {+ if (event.reason !== "completed") return;+ const active = await pi.session.getActive();+ if (active?.sessionId !== event.sessionId) return;+ const text = await writeNextLine(active); // 插件自己的模型请求+ if (!text) return;+ await pi.composer.suggest({+ sessionId: event.sessionId,+ turnId: event.turnId,+ text,+ });+});+```+### 语音(`speech.adapter.register`)```tspi.speech.registerAdapter(adapter: {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.mdindex 3aea68dfc..73e7fd57a 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@@ -28,6 +28,7 @@| `agent.tool.register` | 高 | 注册代理工具 | 安装时确认 | 工具执行情况单独审核 || `agent.prompt.inject` | 高 | 注入系统提示符;激活 `contributes.skills` | 默认拒绝/强确认 | 容易导致行为劫持 || `composer.transform` | 中等 | `contributes.composerTransforms` 与 `onComposerTransform` | 安装时确认 | 仅在用户主动执行 Composer 操作后运行。仅接收草稿和可选模型 key,不接收会话历史或单独的附件/文件引用元数据;输入、结果上限均为 100,000 字符并记入审计 |+| `composer.suggest` | 中等 | `pi.composer.suggest` / `pi.composer.clearSuggestion` | 安装时确认 | 仅在草稿为空、且插件声明的轮次仍是当前轮次时,向当前可见会话的输入框占位符层写入一条可忽略的建议。用户按 Tab 采用、Esc 忽略;输入、发送、切换会话、新一轮开始、插件停止、页面重载或窗口关闭都会清除。插件既不能直接发送,也不读取草稿。文本折为单行并截断到 200 字符;存活时间默认 120 秒,上限 10 分钟。记入审计;无法展示时返回 `{ shown: false, reason }` 而不是抛错 || `agent.extension` | 高 | 在 agent 进程内运行 `contributes.agentExtensions` 模块 | 显式确认;v1.1 仅限本地导入和开发插件 | 与 agent 自身工具同等权限;插件沙箱不适用(规格 16) || `renderer.extension` | 高 | 在宿主渲染进程中执行 `manifest.renderer` 以挂载 UI 插槽;`rendererActions` 与 `rendererCallMethods` 决定该模块可以派发的动作与 `onRendererCall` 方法 | 显式确认;v1.1 仅限本地导入和开发插件,与 `agent.extension` 一致 | 模块与 PI-Desktop 同文档运行,因此插槽是契约而不是沙箱。组件只能派发经过审查的动作词表(`plugin.call`、`composer.insertText`、`composer.readDraft`、`composer.replaceDraft`、`attachments.add` / `list` / `remove`),最多 16 个;`plugin.call` 只能触达调用者自己插件的 `onRendererCall` 方法,最多 32 个。插件卸载时注册会被撤销;自绘弹窗位于插件自己打开的层中 || `provider.register` | 高 | `contributes.providers` 成为原生 Provider 列表中的行,归插件所有并在每次加载时按 manifest 刷新 | 显式确认;v1.1 仅限本地导入和开发插件,与 `agent.extension` 一致 | 用户路径拒绝编辑该行(`PROVIDER_OWNED_BY_PLUGIN`);API key 凭据仍存放在 Host secret store 的常规 provider 引用下 |@@ -158,6 +159,7 @@ Agent,在 Plan 中不可见。主机返回 `PLUGIN_DISABLED_IN_PLAN`| `usage.read` | Read usage statistics | 读取用量统计 || `agent.complete` | Run a one-shot completion with your models | 用你的模型发起一次补全 || `composer.transform` | Transform text in the Composer | 转换输入框中的文本 |+| `composer.suggest` | Offer a suggestion in the Composer | 在输入框中给出建议 || `speech.adapter.register` | Register a speech adapter | 注册语音适配器 || `audio.capture.background` | Use the microphone in the background | 后台使用麦克风 || `audio.playback.background` | Play audio in the background | 后台播放声音 |diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 3ee5d487a..a65c32271 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -349,6 +349,7 @@ export const de = {"placeholderHint": "Geben Sie / für Befehle · @ für Dateien ein","placeholderHomeHint": "Geben Sie / für Befehle · @ für Dateien ein","placeholderShortcut": "Umschalt+Eingabetaste für Zeilenumbruch · Verwenden Sie Senden, um zu senden",+ "suggestionHint": "Tab übernehmen · Esc verwerfen","addFiles": "Dateien hinzufügen und mehr","filesAttached": "{{count}} Element(e) zum Entwurf hinzugefügt","filesPasted": "{{count}} eingefügte Datei(en) im Sitzungs-Scratch-Ordner gespeichert",@@ -2386,6 +2387,7 @@ sklm: {"agent.prompt.inject": "Agentenanweisungen anpassen","agent.complete": "One-Shot-Vervollständigung mit Ihren Modellen durchführen","composer.transform": "Text im Composer umwandeln",+ "composer.suggest": "Einen Vorschlag im Composer anbieten","agent.extension": "Code im Agenten ausführen","renderer.extension": "Oberfläche in Chat-Slots zeichnen","provider.register": "Anbieter zur Modellliste hinzufügen",@@ -2428,6 +2430,7 @@ sklm: {"agent.prompt.inject": "Kann Anweisungen ändern, die an den KI-Agenten gesendet werden.","agent.complete": "Kann Ihr Modellkontingent für eine einmalige Fertigstellung ausgeben. Das Plugin erhält niemals Ihre API-Schlüssel.","composer.transform": "Erlaubt diesem Plugin, ausdrücklich im Composer ausgewählten Text umzuwandeln. Es erhält den Entwurf und den Modellschlüssel, aber weder Gesprächsverlauf noch Anhänge.",+ "composer.suggest": "Erlaubt diesem Plugin, bei leerem Entwurf eine verwerfbare Zeile im Platzhalter des Composers anzuzeigen. Sie gelangt nur mit Tab in den Entwurf, kann nie vom Plugin gesendet werden und verschwindet beim Tippen.","renderer.extension": "Lädt das Renderer-Modul dieses Plugins in das App-Fenster, um UI-Slot-Komponenten zu zeichnen (Nachrichten-Aktionsleisten, Antwort-Anhänge, Tool-Karten, Codeblock-Renderer, Eingabebereich). Das Modul läuft im selben Dokument wie PI-Desktop. Aktiviere nur Code, dem du vertraust.","agent.extension": "Führt ExtensionAPI-Module im Agentenprozess mit denselben Rechten wie die Tools des Agenten aus. Aktivieren Sie nur Code, dem Sie vertrauen.","provider.register": "Fügt die Anbieter, die dieses Plugin definiert, zur Anbieterliste in den Einstellungen hinzu. Das Plugin liefert den Endpunkt und die Modelle; Ihr API-Schlüssel bleibt in PI-Desktop.",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex a28e4dc3b..c909a95c2 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -356,6 +356,7 @@ export const en = {placeholderHint: "Type / for commands · @ for files",placeholderHomeHint: "Type / for commands · @ for files",placeholderShortcut: "Shift+Enter for newline · Use Send to submit",+ suggestionHint: "Tab to accept · Esc to ignore",addFiles: "Add files",filesAttached: "Added {{count}} item(s) to the draft",filesPasted: "Saved {{count}} pasted file(s) to the session scratch folder",@@ -2407,6 +2408,7 @@ importConfirm: "Imported extensions run inside the agent process with the same a"agent.prompt.inject": "Adjust agent instructions","agent.complete": "Run a one-shot completion with your models","composer.transform": "Transform text in the Composer",+ "composer.suggest": "Offer a suggestion in the Composer","agent.extension": "Run code inside the agent","renderer.extension": "Draw UI in chat slots","provider.register": "Add providers to the model list",@@ -2458,6 +2460,8 @@ importConfirm: "Imported extensions run inside the agent process with the same a"Can spend your model quota on a one-shot completion. The plugin never receives your API keys.","composer.transform":"Lets this plugin transform text you explicitly select in the Composer. It receives the draft and selected model key, but no conversation history or attachments.",+ "composer.suggest":+ "Lets this plugin show one dismissible line in the Composer's placeholder while the draft is empty. The line enters the draft only when you press Tab, can never be sent by the plugin, and disappears as soon as you type.","agent.extension": "Runs ExtensionAPI modules inside the agent process with the same access as the agent's own tools. Enable only code you trust.","renderer.extension":"Loads this plugin's renderer module into the app window to draw UI slot components (message action bars, entry extras, tool cards, code-block renderers, composer controls). The module runs in the same document as PI-Desktop. Enable only code you trust.",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex dab1dccc4..7d64be7d7 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -349,6 +349,7 @@ export const es = {"placeholderHint": "Escriba / para comandos · @ para archivos","placeholderHomeHint": "Escriba / para comandos · @ para archivos","placeholderShortcut": "Mayús+Entrar para nueva línea · Utilice Enviar para enviar",+ "suggestionHint": "Tab aceptar · Esc descartar","addFiles": "Agregar archivos y más","filesAttached": "Se agregaron {{count}} elementos al borrador","filesPasted": "Se guardaron {{count}} archivos pegados en la carpeta temporal de la sesión",@@ -2386,6 +2387,7 @@ sklm: {"agent.prompt.inject": "Ajustar instrucciones del agente","agent.complete": "Ejecutar una finalización de una sola vez con sus modelos","composer.transform": "Transformar texto en el compositor",+ "composer.suggest": "Ofrecer una sugerencia en el compositor","agent.extension": "Ejecutar código dentro del agente","renderer.extension": "Dibujar interfaz en los slots del chat","provider.register": "Agregar proveedores a la lista de modelos",@@ -2428,6 +2430,7 @@ sklm: {"agent.prompt.inject": "Puede cambiar las instrucciones enviadas al agente de IA.","agent.complete": "Puede gastar su cuota de modelo en una finalización única. El complemento nunca recibe sus claves API.","composer.transform": "Permite que este complemento transforme el texto que selecciones explícitamente en el compositor. Recibe el borrador y la clave del modelo seleccionado, pero no el historial de conversación ni los adjuntos.",+ "composer.suggest": "Permite que este complemento muestre una línea descartable en el marcador del compositor mientras el borrador está vacío. Solo entra en el borrador al pulsar Tab, nunca la envía el complemento y desaparece al escribir.","agent.extension": "Ejecuta módulos ExtensionAPI dentro del proceso del agente con el mismo acceso que sus propias herramientas. Activa solo código en el que confíes.","renderer.extension": "Carga el módulo de renderizado de este complemento en la ventana de la app para dibujar componentes en los slots de la interfaz (barras de acción de mensajes, extras de respuesta, tarjetas de herramientas, renderizadores de bloques de código, controles del compositor). El módulo se ejecuta en el mismo documento que PI-Desktop. Activa solo código de confianza.","provider.register": "Agregue los proveedores que define este complemento a la lista de proveedores de Configuración. El complemento aporta el punto final y los modelos; su clave API permanece en PI-Desktop.",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 701530342..2b6e2056f 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -349,6 +349,7 @@ export const fr = {"placeholderHint": "Tapez / pour les commandes · @ pour les fichiers","placeholderHomeHint": "Tapez / pour les commandes · @ pour les fichiers","placeholderShortcut": "Maj+Entrée pour une nouvelle ligne · Utilisez Envoyer pour soumettre",+ "suggestionHint": "Tab accepter · Échap ignorer","addFiles": "Ajoutez des fichiers et plus encore","filesAttached": "Ajout de {{count}} élément(s) au brouillon","filesPasted": "Enregistrement de {{count}} fichier(s) collé(s) dans le dossier de travail de la session",@@ -2386,6 +2387,7 @@ sklm: {"agent.prompt.inject": "Ajuster les instructions de l'agent","agent.complete": "Exécuter une complétion unique avec vos modèles","composer.transform": "Transformer le texte dans le compositeur",+ "composer.suggest": "Proposer une suggestion dans le compositeur","agent.extension": "Exécuter du code dans l'agent","renderer.extension": "Dessiner l'interface dans les emplacements du chat","provider.register": "Ajouter des fournisseurs à la liste de modèles",@@ -2428,6 +2430,7 @@ sklm: {"agent.prompt.inject": "Peut modifier les instructions envoyées à l'agent IA.","agent.complete": "Peut dépenser votre quota de modèle pour une réalisation unique. Le plugin ne reçoit jamais vos clés API.","composer.transform": "Permet à ce plugin de transformer le texte que vous sélectionnez explicitement dans le compositeur. Il reçoit le brouillon et la clé du modèle sélectionné, mais ni l'historique de la conversation ni les pièces jointes.",+ "composer.suggest": "Permet à ce plugin d'afficher une ligne ignorable dans le texte indicatif du compositeur tant que le brouillon est vide. Elle n'entre dans le brouillon qu'avec Tab, ne peut jamais être envoyée par le plugin et disparaît dès la frappe.","agent.extension": "Exécute des modules ExtensionAPI dans le processus de l'agent avec le même accès que ses propres outils. N'activez que du code auquel vous faites confiance.","renderer.extension": "Charge le module de rendu de ce plugin dans la fenêtre de l'app pour dessiner des composants d'interface (barres d'actions des messages, extras de réponse, cartes d'outils, rendus de blocs de code, contrôles du composeur). Le module s'exécute dans le même document que PI-Desktop. N'activez que du code de confiance.","provider.register": "Ajoute les fournisseurs définis par ce plugin à la liste des fournisseurs des Paramètres. Le plugin fournit le point de terminaison et les modèles ; votre clé API reste dans PI-Desktop.",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex e4e1d2c10..6c9edfcb8 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -358,6 +358,7 @@ export const ko = {placeholderHint: "명령은 / · 파일은 @ 입력",placeholderHomeHint: "명령은 / · 파일은 @ 입력",placeholderShortcut: "줄바꿈은 Shift+Enter · 보내기를 눌러 제출",+ suggestionHint: "Tab 수락 · Esc 무시",addFiles: "파일 추가",filesAttached: "초안에 항목 {{count}}개 추가됨",filesPasted: "붙여넣은 파일 {{count}}개를 세션 임시 폴더에 저장함",@@ -2403,6 +2404,7 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이"agent.prompt.inject": "에이전트 지침 조정","agent.complete": "모델로 일회성 완성 실행","composer.transform": "작성기의 텍스트 변환",+ "composer.suggest": "작성기에 제안 표시","agent.extension": "에이전트 안에서 코드 실행","renderer.extension": "채팅 슬롯에 UI 그리기","provider.register": "모델 목록에 프로바이더 추가",@@ -2452,6 +2454,7 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이"agent.complete":"모델 할당량을 사용해 일회성 완성을 실행할 수 있습니다. 플러그인은 API 키를 받지 않습니다.","composer.transform": "작성기에서 직접 선택한 텍스트를 변환하도록 허용합니다. 플러그인은 초안과 선택된 모델 키만 받으며 대화 기록이나 첨부 파일은 받지 않습니다.",+ "composer.suggest": "초안이 비어 있는 동안 작성기 자리 표시자에 무시할 수 있는 한 줄을 표시하도록 허용합니다. Tab을 눌러야만 초안에 들어가며, 플러그인이 대신 전송할 수 없고 입력을 시작하면 사라집니다.","agent.extension": "ExtensionAPI 모듈을 에이전트 프로세스 안에서 에이전트 자체 도구와 같은 권한으로 실행합니다. 신뢰하는 코드만 켜세요.","renderer.extension": "이 플러그인의 렌더러 모듈을 앱 창에 로드하여 메시지 작업 표시줄, 응답 추가 영역, 도구 카드, 코드 블록 렌더러, 작성기 컨트롤 등 UI 슬롯 구성 요소를 그립니다. 모듈은 PI-Desktop과 같은 문서에서 실행됩니다. 신뢰하는 코드만 활성화하세요.","provider.register":diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 54f3e679b..e02ec85b1 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -348,6 +348,7 @@ export const ptBR = {placeholderHint: "Digite / para comandos · @ para arquivos",placeholderHomeHint: "Digite / para comandos · @ para arquivos",placeholderShortcut: "Shift+Enter para inserir uma quebra de linha · Use Enviar para enviar",+ suggestionHint: "Tab aceitar · Esc descartar",addFiles: "Adicionar arquivos",filesAttached: "{{count}} item(ns) adicionado(s) ao rascunho",filesPasted: "{{count}} arquivo(s) colado(s) salvo(s) na pasta temporária da sessão",@@ -2352,6 +2353,7 @@ export const ptBR = {"agent.prompt.inject": "Alterar as instruções do agente","agent.complete": "Executar uma conclusão avulsa com seus modelos","composer.transform": "Transformar texto no Composer",+ "composer.suggest": "Sugerir algo no Composer","agent.extension": "Executar código dentro do agente","renderer.extension": "Desenhar interface nos slots do chat","provider.register": "Adicionar provedores à lista de modelos",@@ -2394,6 +2396,7 @@ export const ptBR = {"agent.prompt.inject": "Pode alterar as instruções enviadas ao agente de IA.","agent.complete": "Pode consumir sua cota de modelo para uma conclusão avulsa. O plugin nunca recebe suas chaves de API.","composer.transform": "Permite que este plugin transforme o texto selecionado no Composer. Ele recebe o rascunho e a chave do modelo selecionado, mas não o histórico da conversa nem anexos.",+ "composer.suggest": "Permite que este plugin mostre uma linha descartável no texto de exemplo do Composer enquanto o rascunho está vazio. Ela entra no rascunho apenas com Tab, o plugin nunca a envia sozinho e ela desaparece ao digitar.","agent.extension": "Executa módulos da ExtensionAPI dentro do processo do agente, com o mesmo nível de acesso que as ferramentas do próprio agente. Ative somente código em que você confia.","renderer.extension":"Carrega o módulo de renderização deste plugin na janela do aplicativo para desenhar componentes de slot (barras de ações de mensagens, extras de entrada, cartões de ferramentas, renderizadores de blocos de código, controles do compositor). O módulo é executado no mesmo documento do PI-Desktop. Ative somente código em que você confia.",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex b8989edac..8b2d02e32 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -358,6 +358,7 @@ export const tr = {placeholderHint: "Komutlar için / · dosyalar için @ yazın",placeholderHomeHint: "Komutlar için / · dosyalar için @ yazın",placeholderShortcut: "Yeni satır için Shift+Enter · göndermek için Gönder",+ suggestionHint: "Tab kabul · Esc yoksay",addFiles: "Dosya ekle",filesAttached: "Taslağa {{count}} öğe eklendi",filesPasted: "Yapıştırılan {{count}} dosya oturum klasörüne kaydedildi",@@ -2397,6 +2398,7 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç"agent.prompt.inject": "Ajan yönergelerini ayarla","agent.complete": "Modellerinizle tek seferlik tamamlatma çalıştır","composer.transform": "Oluşturucudaki metni dönüştür",+ "composer.suggest": "Oluşturucuda öneri sun","agent.extension": "Ajanın içinde kod çalıştır","renderer.extension": "Sohbet yuvalarında arayüz çiz","provider.register": "Model listesine servis ekle",@@ -2446,6 +2448,7 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç"agent.complete":"Model kotanızı tek seferlik bir tamamlatma için harcayabilir. Eklenti API anahtarlarınızı almaz.","composer.transform": "Eklentinin Oluşturucu'da açıkça seçtiğiniz metni dönüştürmesine izin verir. Eklenti yalnızca taslağı ve seçili model anahtarını alır; konuşma geçmişini veya ekleri almaz.",+ "composer.suggest": "Taslak boşken Oluşturucu yer tutucusunda yok sayılabilir tek bir satır göstermesine izin verir. Satır yalnızca Tab ile taslağa girer, eklenti onu kendi gönderemez ve yazmaya başlayınca kaybolur.","agent.extension": "ExtensionAPI modüllerini ajan sürecinde, ajanın kendi araçlarıyla aynı erişimle çalıştırır. Yalnızca güvendiğiniz kodu etkinleştirin.","renderer.extension": "Bu eklentinin işleyici modülünü uygulama penceresine yükler; mesaj eylem çubukları, yanıt ek alanları, araç kartları, kod bloğu işleyicileri ve besteleyici kontrolleri gibi arayüz yuvası bileşenleri çizer. Modül PI-Desktop ile aynı belgede çalışır. Yalnızca güvendiğiniz kodu etkinleştirin.","provider.register":diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 7c026ae18..cf25670f7 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -351,6 +351,7 @@ export const zhCN = {placeholderHint: "输入 / 使用命令 · @ 引用文件",placeholderHomeHint: "输入 / 使用命令 · @ 引用文件",placeholderShortcut: "Shift+Enter 换行 · 点击发送提交",+ suggestionHint: "Tab 接受 · Esc 忽略",addFiles: "添加文件",filesAttached: "已将 {{count}} 项加入草稿",filesPasted: "已将 {{count}} 个粘贴文件保存到会话临时目录",@@ -2380,6 +2381,7 @@ sklm: {"agent.prompt.inject": "调整智能体指令","agent.complete": "用你的模型发起一次补全","composer.transform": "转换输入框中的文本",+ "composer.suggest": "在输入框中给出建议","agent.extension": "在 agent 内运行代码","renderer.extension": "在聊天插槽绘制界面","provider.register": "将服务添加到模型列表",@@ -2423,6 +2425,7 @@ sklm: {"agent.prompt.inject": "可能修改发送给智能体的指令。","agent.complete": "会消耗你的模型额度发起一次补全。插件拿不到 API 密钥。","composer.transform": "允许插件转换你在输入框中主动选择的文本。插件会收到草稿文本和所选模型标识,不会收到对话历史或附件。",+ "composer.suggest": "允许插件在草稿为空时于输入框占位处显示一条可忽略的建议。只有你按 Tab 它才进入草稿,插件无法直接发送,开始输入即会消失。","agent.extension": "在 agent 进程内运行 ExtensionAPI 模块,拥有与 agent 自身工具相同的权限。只启用你信任的代码。","renderer.extension": "把该插件的渲染模块加载进应用窗口,在消息操作栏、回复追加区、工具卡、代码块、输入区等插槽绘制界面。模块与 PI-Desktop 同文档运行,只启用你信任的代码。","provider.register": "把此插件定义的服务添加到设置的服务列表。接口地址和模型由插件提供,API 密钥则留在 PI-Desktop 中。",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 1ae7643a6..bd3286669 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -351,6 +351,7 @@ export const zhTW = {placeholderHint: "輸入 / 使用命令 · @ 引用檔案",placeholderHomeHint: "輸入 / 使用命令 · @ 引用檔案",placeholderShortcut: "Shift+Enter 換行 · 點擊發送提交",+ suggestionHint: "Tab 接受 · Esc 忽略",addFiles: "新增檔案等內容",filesAttached: "已將 {{count}} 項加入草稿",filesPasted: "已將 {{count}} 個貼上檔案儲存到會話臨時目錄",@@ -2380,6 +2381,7 @@ sklm: {"agent.prompt.inject": "調整智慧體指令","agent.complete": "用你的模型發起一次補全","composer.transform": "轉換輸入框中的文字",+ "composer.suggest": "在輸入框中提供建議","agent.extension": "在 agent 內執行程式碼","renderer.extension": "在聊天插槽繪製介面","provider.register": "將服務新增到模型列表",@@ -2423,6 +2425,7 @@ sklm: {"agent.prompt.inject": "可能修改傳送給智慧體的指令。","agent.complete": "會消耗你的模型額度發起一次補全。外掛拿不到 API 金鑰。","composer.transform": "允許外掛轉換你在輸入框中主動選擇的文字。外掛會收到草稿文字和所選模型識別碼,不會收到對話歷史或附件。",+ "composer.suggest": "允許外掛在草稿為空時於輸入框佔位處顯示一條可忽略的建議。只有你按 Tab 它才進入草稿,外掛無法直接送出,開始輸入即會消失。","agent.extension": "在 agent 程序內執行 ExtensionAPI 模組,擁有與 agent 自身工具相同的權限。只啟用你信任的程式碼。","renderer.extension": "把該外掛的渲染模組載入應用視窗,在訊息操作列、回覆追加區、工具卡、程式碼區塊、輸入區等插槽繪製介面。模組與 PI-Desktop 同文件執行,只啟用你信任的程式碼。","provider.register": "把此外掛定義的服務新增到設定的服務列表。介面地址和模型由外掛提供,API 金鑰則留在 PI-Desktop 中。",diff --git a/packages/plugin-sdk/src/index.test.ts b/packages/plugin-sdk/src/index.test.tsindex fd9e4427d..7953545f1 100644--- a/packages/plugin-sdk/src/index.test.ts+++ b/packages/plugin-sdk/src/index.test.ts@@ -663,6 +663,7 @@ describe("PLUGIN_PERMISSIONS", () => {"agent.prompt.inject","agent.complete","composer.transform",+ "composer.suggest","models.list","project.create","session.read",diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.tsindex 70075658b..566545236 100644--- a/packages/plugin-sdk/src/index.ts+++ b/packages/plugin-sdk/src/index.ts@@ -233,6 +233,76 @@ export type PluginComposerTransformInput = {modelKey?: string;};+/**+ * Longest suggestion text the host keeps, in characters. Longer text is cut;+ * the composer draws it in one line with an ellipsis either way.+ */+export const PLUGIN_COMPOSER_SUGGESTION_MAX_CHARS = 200;+/** Lifetime of one suggestion when `ttlMs` is omitted, in milliseconds. */+export const PLUGIN_COMPOSER_SUGGESTION_TTL_MS = 120_000;+/** Shortest and longest lifetime a caller may ask for, in milliseconds. */+export const PLUGIN_COMPOSER_SUGGESTION_TTL_MIN_MS = 1_000;+export const PLUGIN_COMPOSER_SUGGESTION_TTL_MAX_MS = 600_000;++/**+ * `pi.composer.suggest`: one dismissible line the composer shows in its+ * placeholder layer while the draft is empty (`composer.suggest`).+ *+ * `sessionId` and `turnId` are the ones the plugin learned from+ * `session:turnEnded`. The host shows the text only while that session is+ * still the one on screen, no newer turn has started, and the draft is empty,+ * so an answer that took a model request to produce cannot surface in a place+ * the user already left. `text` is one line: the host folds line breaks and+ * runs of whitespace into single spaces and cuts the result at+ * `PLUGIN_COMPOSER_SUGGESTION_MAX_CHARS`. `ttlMs` defaults to+ * `PLUGIN_COMPOSER_SUGGESTION_TTL_MS` and is clamped into+ * `PLUGIN_COMPOSER_SUGGESTION_TTL_MIN_MS`..`PLUGIN_COMPOSER_SUGGESTION_TTL_MAX_MS`.+ */+export type PluginComposerSuggestInput = {+ readonly sessionId: string;+ /** The turn the suggestion belongs to; a older turn that already ran is stale. */+ readonly turnId?: string;+ readonly text: string;+ readonly ttlMs?: number;+};++/**+ * Why a suggestion is not on screen.+ * - `session-not-visible`: that session is not the one the user is looking at.+ * - `draft-not-empty`: the composer already holds text or an attachment.+ * - `stale-turn`: the session has run a newer turn since `turnId`, so the+ * suggestion would arrive about a moment that is already over.+ * - `replaced`: a newer suggestion took the slot before this one was answered.+ * - `unsupported`: nothing could take it — no window, no composer mounted, or+ * the shell did not answer in time.+ */+export const PLUGIN_COMPOSER_SUGGESTION_REFUSALS = [+ "session-not-visible",+ "draft-not-empty",+ "stale-turn",+ "replaced",+ "unsupported",+] as const;++export type PluginComposerSuggestionRefusal =+ (typeof PLUGIN_COMPOSER_SUGGESTION_REFUSALS)[number];++/**+ * `pi.composer.suggest` answer. A place that will not show the text is not an+ * error: `shown: false` and a `reason` let a plugin log the miss and decide+ * whether to spend another completion. Only malformed input throws —+ * `INVALID_PARAMS`, like every other host API.+ */+export type PluginComposerSuggestResult =+ | { readonly shown: true }+ | { readonly shown: false; readonly reason: PluginComposerSuggestionRefusal };++/**+ * `pi.composer.clearSuggestion`: drop this plugin's suggestion. `sessionId`+ * defaults to the session the user is looking at.+ */+export type PluginComposerClearSuggestionInput = { readonly sessionId?: string };+export type PluginSessionMessage =| { role: "user"; content: string; createdAt: string }| {@@ -1188,6 +1258,24 @@ export type PluginHostApi = {registerAdapter: (adapter: PluginSpeechAdapter) => Promise<void>;unregisterAdapter: (protocol: string) => Promise<void>;};+ /**+ * The session's input box (`composer.suggest`). A plugin gets one+ * dismissible line into the placeholder layer of a session whose draft is+ * empty; the user takes it with Tab, drops it with Esc, and typing anything+ * drops it too. Never a message, never a bubble, never a send.+ */+ composer: {+ /**+ * Offer one line for the composer of `sessionId`. Resolves+ * `{ shown: false, reason }` instead of throwing when nothing will show+ * it, so the answer is safe to log. The whole suggestion is cleared by+ * the shell on: typing, pasting, an attachment, a send, a session switch,+ * a new turn, this plugin unloading, a renderer reload, or a window close.+ */+ suggest: (input: PluginComposerSuggestInput) => Promise<PluginComposerSuggestResult>;+ /** Drop this plugin's suggestion; nothing is shown when it is already gone. */+ clearSuggestion: (input?: PluginComposerClearSuggestionInput) => Promise<{ ok: true }>;+ };ui: {openPanel: (opts?: { title?: string }) => Promise<void>;closePanel: () => Promise<void>;@@ -1484,6 +1572,10 @@ export const PLUGIN_PERMISSIONS = ["agent.prompt.inject","agent.complete","composer.transform",+ // One dismissible line in the composer's placeholder layer. A grant here can+ // put text into a draft the user may send, so it sits with the draft writer+ // (`composer.transform`) rather than with the display-only grants.+ "composer.suggest","agent.extension",// Renderer slots (`docs/plugin-plan/ui/`): the entry module loads into the// host renderer's own document, so the surface it can touch is thediff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 763584524..ecc0524c7 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -343,6 +343,12 @@ export const IPC = {* `session:activated` snapshot is assembled from both (spec 07-plugins/03).*/pluginSessionActive: "pi-desktop/plugin/session/active",+ /**+ * The shell's answer to one composer suggestion (`pi.composer.suggest`):+ * whether it went on screen and, if not, why. The main process is waiting+ * on this invoke, so a suggestion's caller learns what happened to it.+ */+ pluginComposerSuggestionResult: "pi-desktop/plugin/composer/suggestionResult",mcpList: "pi-desktop/mcp/list",mcpUpsert: "pi-desktop/mcp/upsert",mcpRemove: "pi-desktop/mcp/remove",@@ -465,6 +471,13 @@ export const IPC = {* which session's panel takes the view.*/pluginViewReveal: "pi-desktop/plugin/view/event/reveal",+ /**+ * One composer suggestion (`pi.composer.suggest`): an offer to show a+ * plugin's line in the placeholder layer, or the shell's order to drop what+ * it shows. The shell owns the composer, so it decides and answers over+ * `pluginComposerSuggestionResult`.+ */+ pluginComposerSuggestion: "pi-desktop/plugin/composer/event/suggestion",windowMaximized: "pi-desktop/window/event/maximized",windowFullScreen: "pi-desktop/window/event/fullscreen",windowWorkPanelResize: "pi-desktop/window/event/workPanelResize",