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(session-titles): delegate titles to plugins
vastsac58923fab4e4
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.tsindex 9d2d28a79..cbe6ab2f3 100644--- a/apps/desktop/electron/main/ipc/agent-ipc.ts+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts@@ -1,7 +1,7 @@import { expandMcpInvocation } from "../composer-mcp";-import { IPC, ErrorCodes, compactionRecordId, findSkillMentions, isGlobalPermissionMode, isRpcTimeoutError, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PendingInteractiveRequests, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type PromptEnhancementRequest, type SessionSummarizeTitleRequest, type VoiceOrigin, canonicalThinkingLevel, type ThinkingLevel } from "@pi-desktop/shared";+import { IPC, ErrorCodes, compactionRecordId, findSkillMentions, isGlobalPermissionMode, isRpcTimeoutError, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PendingInteractiveRequests, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type PromptEnhancementRequest, type VoiceOrigin, canonicalThinkingLevel, type ThinkingLevel } from "@pi-desktop/shared";import type { FinishTurn } from "../runtime/plans";-import { expandSlashInvocation, enhancePromptDraft, summarizeSessionTitle, visionFromModelConfig, type ComposerTemplate, type RuntimeProviderConfig } from "@pi-desktop/agent-runtime";+import { expandSlashInvocation, enhancePromptDraft, visionFromModelConfig, type ComposerTemplate, type RuntimeProviderConfig } from "@pi-desktop/agent-runtime";import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";import { appendPromptFallbackPaths, durableUserMessageId, preparePromptAttachments, type PreparedPromptAttachment } from "../prompt-attachments";import { resolveSessionReferences } from "../session-references";@@ -219,54 +219,6 @@ export function registerAgentIpc({return { enhancedDraft };});- handle(IPC.invoke.sessionSummarizeTitle, async (req: SessionSummarizeTitleRequest) => {- if (!host) throw new Error("backend unavailable");- const sessionId = typeof req?.sessionId === "string" ? req.sessionId.trim() : "";- const userPrompt = typeof req?.userPrompt === "string" ? req.userPrompt.trim() : "";- if (!sessionId || !userPrompt) {- throw Object.assign(new Error("sessionId and userPrompt required"), {- errorCode: ErrorCodes.INVALID_ARGUMENT,- });- }- const session = (await host.call<{ session?: any }>("session.get", { id: sessionId })).session;- if (!session) {- throw Object.assign(new Error("Session not found"), {- errorCode: ErrorCodes.NOT_FOUND,- });- }- const settings = await host.call<any>("settings.get");- const launch = await resolveAgentRuntimeLaunch(- `title-summary:${sessionId}`,- session,- settings,- {- mode: "agent",- providerId: typeof req.providerId === "string" ? req.providerId.trim() : undefined,- modelId: typeof req.modelId === "string" ? req.modelId.trim() : undefined,- thinkingLevel: "off",- },- );- const runtimeProvider = {- ...launch.sidecarParams.provider,- ...(launch.sidecarParams.provider.authKind === OAUTH_AUTH_KIND- ? { resolveAuth: () => vendorOAuth.resolveAuth(launch.providerId) }- : {}),- } as RuntimeProviderConfig;-- const title = await summarizeSessionTitle(- runtimeProvider,- userPrompt,- req.assistantReply,- "off",- { sessionId },- );- logger.app("session", "info", "session title summarized", {- sessionId,- data: { title, providerId: launch.providerId, modelId: launch.modelId },- });- return { title };- });-handle(IPC.invoke.agentSteer, async (req: AgentSteerRequest) => {if (!host || !sidecar) throw new Error("backend unavailable");if (diff --git a/apps/desktop/electron/main/mcp-control.ts b/apps/desktop/electron/main/mcp-control.tsindex 1befeba83..5d9e6eb9a 100644--- a/apps/desktop/electron/main/mcp-control.ts+++ b/apps/desktop/electron/main/mcp-control.ts@@ -140,7 +140,6 @@ const SESSION_MUTATION_IDS = new Set(["session/rename","session/configure","session/moveProject",- "session/summarizeTitle","session/replaceMessages","session/saveRevision","session/activateRevision",@@ -219,7 +218,6 @@ const CONTROL_OPERATION_SPECS: OperationSpec[] = [spec("sessionGetScratchPath", "session/getScratchPath", "Return a session scratch path.", "read", ["input"]),spec("sessionImportScan", "session/importScan", "Scan supported external session sources.", "read", []),spec("modelConfigImportScan", "modelConfig/importScan", "Scan supported model configuration sources.", "read", []),- spec("sessionSummarizeTitle", "session/summarizeTitle", "Generate a session title.", "write", ["request"]),spec("settingsGet", "settings/get", "Read application settings.", "read", []),spec("networkProxyTest", "network/testProxy", "Test a network proxy configuration.", "read", ["settings"]),spec("commandShellList", "commandShell/list", "List supported command shells.", "read", []),diff --git a/apps/desktop/electron/main/plugin-host-process.mjs b/apps/desktop/electron/main/plugin-host-process.mjsindex 9919b2dcd..d9366b047 100644--- a/apps/desktop/electron/main/plugin-host-process.mjs+++ b/apps/desktop/electron/main/plugin-host-process.mjs@@ -316,6 +316,8 @@ function buildApi() {},session: {getLlmContext: () => call("session.getLlmContext"),+ getAutoTitleContext: (input) => call("session.getAutoTitleContext", [input ?? {}]),+ setAutoTitle: (input) => call("session.setAutoTitle", [input ?? {}]),list: (input) => call("session.list", [input ?? {}]),get: (input) => call("session.get", [input ?? {}]),listMessages: (input) => call("session.listMessages", [input ?? {}]),diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.tsindex 5891e468c..6a1c1c593 100644--- a/apps/desktop/electron/main/plugin-runtime.ts+++ b/apps/desktop/electron/main/plugin-runtime.ts@@ -472,6 +472,8 @@ export type PluginHostServices = {list: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;get: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;listMessages: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;+ getAutoTitleContext: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;+ setAutoTitle: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;import: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;importBatch: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;rename: (pluginId: string, input: Record<string, unknown>) => Promise<unknown>;@@ -566,6 +568,8 @@ const HOST_API_ALLOWLIST = new Set(["browser.cdp","models.list","session.getLlmContext",+ "session.getAutoTitleContext",+ "session.setAutoTitle","session.list","session.get","session.listMessages",@@ -2831,6 +2835,59 @@ export class PluginRuntime {case "session.getLlmContext": {return this.readSessionContext(loaded);}+ case "session.getAutoTitleContext": {+ this.assertPermission(loaded, "session.autoTitle");+ const input = normalizePluginSessionInput(args[0] ?? {}, "other");+ const sessionId = typeof input.sessionId === "string" ? input.sessionId.trim() : "";+ if (!sessionId || sessionId.length > 128) {+ throw apiError("INVALID_PARAMS", "sessionId must be a non-empty string");+ }+ if (!this.services.session?.getAutoTitleContext) {+ throw apiError("UNSUPPORTED", "host api not available: session.getAutoTitleContext");+ }+ const context = await this.services.session.getAutoTitleContext(+ loaded.manifest.id,+ { sessionId },+ );+ this.services.audit?.({+ pluginId,+ api,+ ok: true,+ sessionId,+ ts: Date.now(),+ });+ return context;+ }+ case "session.setAutoTitle": {+ this.assertPermission(loaded, "session.autoTitle");+ const input = normalizePluginSessionInput(args[0] ?? {}, "other");+ const sessionId = typeof input.sessionId === "string" ? input.sessionId.trim() : "";+ const expectedTitle = typeof input.expectedTitle === "string" ? input.expectedTitle : "";+ const title = typeof input.title === "string" ? input.title : "";+ if (!sessionId || sessionId.length > 128 || !expectedTitle || !title) {+ throw apiError("INVALID_PARAMS", "sessionId, expectedTitle and title are required");+ }+ if ([...expectedTitle].length > 80 || [...title].length > 80) {+ throw apiError("LIMIT_EXCEEDED", "session title exceeds 80 characters");+ }+ if (!this.services.session?.setAutoTitle) {+ throw apiError("UNSUPPORTED", "host api not available: session.setAutoTitle");+ }+ const result = await this.services.session.setAutoTitle(loaded.manifest.id, {+ sessionId,+ expectedTitle,+ title,+ }) as { updated?: unknown };+ this.services.audit?.({+ pluginId,+ api,+ ok: true,+ sessionId,+ updated: result?.updated === true,+ ts: Date.now(),+ });+ return result;+ }case "session.import": {this.assertPermission(loaded, "session.import");const input = normalizePluginSessionInput(args[0] ?? {}, "import");diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.tsindex 25246a95b..39e36bc75 100644--- a/apps/desktop/electron/main/services/plugin-services.ts+++ b/apps/desktop/electron/main/services/plugin-services.ts@@ -138,6 +138,8 @@ export function createPluginServices({Number((result as { imported?: unknown })?.imported ?? 0) > 0) ||(method === "plugin.session.rename" &&(result as { updated?: unknown })?.updated === true) ||+ (method === "plugin.session.setAutoTitle" &&+ (result as { updated?: unknown })?.updated === true) ||(method === "plugin.session.delete" &&(result as { deleted?: unknown })?.deleted === true);if (changed) {@@ -344,6 +346,10 @@ export function createPluginServices({get: (pluginId, input) => callPluginSessionHost("plugin.session.get", pluginId, input),listMessages: (pluginId, input) =>callPluginSessionHost("plugin.session.listMessages", pluginId, input),+ getAutoTitleContext: (pluginId, input) =>+ callPluginSessionHost("plugin.session.autoTitleContext", pluginId, input),+ setAutoTitle: (pluginId, input) =>+ callPluginSessionHost("plugin.session.setAutoTitle", pluginId, input),import: (pluginId, input) => callPluginSessionHost("plugin.session.import", pluginId, input),importBatch: (pluginId, input) =>callPluginSessionHost("plugin.session.importBatch", pluginId, input),diff --git a/apps/desktop/electron/main/tray-sessions.ts b/apps/desktop/electron/main/tray-sessions.tsindex 7304b6544..1b5e8943f 100644--- a/apps/desktop/electron/main/tray-sessions.ts+++ b/apps/desktop/electron/main/tray-sessions.ts@@ -18,7 +18,6 @@ const REFRESH_AFTER_INVOKE = new Set<string>([IPC.invoke.sessionRename,IPC.invoke.sessionDelete,IPC.invoke.sessionMoveProject,- IPC.invoke.sessionSummarizeTitle,IPC.invoke.sessionImportRun,IPC.invoke.notificationMarkRead,IPC.invoke.notificationMarkAllRead,diff --git a/apps/desktop/src/features/plugins/model.ts b/apps/desktop/src/features/plugins/model.tsindex 1ffc6c92a..3bc7ec8a5 100644--- a/apps/desktop/src/features/plugins/model.ts+++ b/apps/desktop/src/features/plugins/model.ts@@ -53,6 +53,7 @@ export const PERMISSION_RISK: Record<string, RiskTier> = {"provider.oauth": "high","desktop.control": "high","session.read": "high",+ "session.autoTitle": "high","browser.cdp": "high",// Reading is a tier below writing because what makes a read dangerous is// where the data can go, and outbound requests are declared separately.diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex 26da9d526..715f3a181 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -18,8 +18,6 @@ import type {SpeechSynthesizeRequest,SpeechSynthesizeResult,SpeechTranscribeRequest,- SessionSummarizeTitleRequest,- SessionSummarizeTitleResponse,AgentStopResponse,AgentQueueChangedEvent,AgentQueuePushRequest,@@ -630,8 +628,6 @@ export const api = {sessionId,projectPath,}).then((result) => ({ ...result, session: normalizeSession(result.session) })),- summarizeSessionTitle: (req: SessionSummarizeTitleRequest) =>- invoke<SessionSummarizeTitleResponse>(IPC.invoke.sessionSummarizeTitle, req),configureSession: (id: string,config: Pick<SessionSummary, "mode" | "providerId" | "modelId"> &diff --git a/apps/desktop/src/lib/session-title-utils.ts b/apps/desktop/src/lib/session-title-utils.tsnew file mode 100644index 000000000..0cad126df--- /dev/null+++ b/apps/desktop/src/lib/session-title-utils.ts@@ -0,0 +1,16 @@+import i18n from "i18next";++const LEGACY_DEFAULT_TITLES = new Set(["new task", "new chat", "新建任务", "新对话"]);+export function untitledTaskTitle(): string {+ return i18n.t("chat.untitledTask");+}++export function isDefaultSessionTitle(title?: string | null): boolean {+ const trimmed = (title || "").trim().toLowerCase();+ return (+ !trimmed ||+ LEGACY_DEFAULT_TITLES.has(trimmed) ||+ trimmed === untitledTaskTitle().toLowerCase() ||+ trimmed === i18n.t("nav.newChat").toLowerCase()+ );+}diff --git a/apps/desktop/src/stores/app-store.ts b/apps/desktop/src/stores/app-store.tsindex 5588be5d2..e29e77143 100644--- a/apps/desktop/src/stores/app-store.ts+++ b/apps/desktop/src/stores/app-store.ts@@ -64,11 +64,9 @@ import {type InteractionRuntime,} from "./runtime/interaction-runtime";import {- createSessionTitleRuntime,isDefaultSessionTitle,- promptFallbackSessionTitle,untitledTaskTitle,-} from "./runtime/session-title-runtime";+} from "../lib/session-title-utils";import { createInteractivePromptNotifier } from "./runtime/notification-runtime";import { createTranscriptReadingRuntime } from "./runtime/transcript-reading-runtime";export type {@@ -79,7 +77,7 @@ export type {ToastOptions,ToastVariant,} from "./app-state";-export { isDefaultSessionTitle } from "./runtime/session-title-runtime";+export { isDefaultSessionTitle } from "../lib/session-title-utils";export type { WorkPanelTab } from "../lib/work-panel-tabs";@@ -126,13 +124,6 @@ const runtimeStoreAccess: StoreAccess = {const sessionRuntime: SessionRuntime = createSessionRuntime(runtimeStoreAccess);const catalogRuntime: CatalogRuntime = createCatalogRuntime();const interactionRuntime: InteractionRuntime = createInteractionRuntime();-const titleRuntime = createSessionTitleRuntime({- ...runtimeStoreAccess,- sessionRuntime,- initialSessionMeta: initialSidebarPreferences.sessionMeta,-});-const manuallyRenamedSessionIds = titleRuntime.manualSessionTitles;-const { triggerAutoTitleSummarization } = titleRuntime;const notifyInteractivePrompt = createInteractivePromptNotifier(runtimeStoreAccess.get,);@@ -188,9 +179,6 @@ export const useAppStore = create<AppState>((set, get) => {runtime: sessionRuntime,promptAttachmentsFromDraft,withoutRecordKey,- promptFallbackSessionTitle,- untitledTaskTitle,- isDefaultSessionTitle,viewingSessionIdForPrompt,messageErrorFromUnknown,assistantErrorMessage,@@ -210,7 +198,6 @@ export const useAppStore = create<AppState>((set, get) => {get,set,runtime: sessionRuntime,- manualSessionTitles: manuallyRenamedSessionIds,withoutRecordKey,withProjectDisplayName,promoteProjectPath,@@ -236,7 +223,6 @@ export const useAppStore = create<AppState>((set, get) => {sessionModeForPlanningState,openPlanArtifact,notifyInteractivePrompt,- triggerAutoTitleSummarization,flushPendingSessionConfiguration,assistantErrorMessage,withCompactionMark,diff --git a/apps/desktop/src/stores/runtime/session-title-runtime.ts b/apps/desktop/src/stores/runtime/session-title-runtime.tsdeleted file mode 100644index 6c2bd34b9..000000000--- a/apps/desktop/src/stores/runtime/session-title-runtime.ts+++ /dev/null@@ -1,102 +0,0 @@-import i18n from "i18next";-import type { AppState } from "../app-state";-import type { SessionRuntime } from "./session-runtime";-import type { StoreAccess } from "../slices/types";-import { api } from "../../lib/api";--const LEGACY_DEFAULT_TITLES = new Set(["new task", "new chat", "新建任务", "新对话"]);-const SESSION_TITLE_FALLBACK_LENGTH = 48;--export function untitledTaskTitle(): string {- return i18n.t("chat.untitledTask");-}--export function promptFallbackSessionTitle(- userPrompt: string,- emptyTitle: string,-): string {- return (- userPrompt.trim().replace(/\s+/g, " ").slice(0, SESSION_TITLE_FALLBACK_LENGTH) ||- emptyTitle- );-}--export function isDefaultSessionTitle(title?: string | null): boolean {- const trimmed = (title || "").trim().toLowerCase();- return (- !trimmed ||- LEGACY_DEFAULT_TITLES.has(trimmed) ||- trimmed === untitledTaskTitle().toLowerCase() ||- trimmed === i18n.t("nav.newChat").toLowerCase()- );-}--export type SessionTitleRuntime = {- manualSessionTitles: Set<string>;- triggerAutoTitleSummarization: (sessionId: string) => Promise<void>;-};--export function createSessionTitleRuntime({- get,- sessionRuntime,- initialSessionMeta,-}: StoreAccess & {- sessionRuntime: SessionRuntime;- initialSessionMeta: AppState["sessionMeta"];-}): SessionTitleRuntime {- const manualSessionTitles = new Set<string>();- const summarizedSessionIds = new Set<string>();- for (const [sessionId, meta] of Object.entries(initialSessionMeta)) {- if (meta.manualTitle) manualSessionTitles.add(sessionId);- }-- async function triggerAutoTitleSummarization(sessionId: string): Promise<void> {- if (!sessionId) return;- if (manualSessionTitles.has(sessionId)) return;- if (summarizedSessionIds.has(sessionId)) return;-- const state = get();- const session = state.sessions.find((item) => item.id === sessionId);- if (!session) return;- const messages =- sessionId === state.activeSessionId- ? state.messages- : sessionRuntime.sessionTranscriptCache.get(sessionId) ?? [];- const firstUser = messages.find((message) => message.role === "user");- if (!firstUser?.content) return;- if (- state.sessionMeta[sessionId]?.manualTitle ||- (!isDefaultSessionTitle(session.title) &&- session.title.trim() !== promptFallbackSessionTitle(firstUser.content, ""))- ) {- return;- }- const firstAssistant = messages.find(- (message) =>- message.role === "assistant" &&- typeof message.content === "string" &&- message.content.trim(),- );-- summarizedSessionIds.add(sessionId);- try {- const result = await api.summarizeSessionTitle({- sessionId,- userPrompt: firstUser.content,- assistantReply:- typeof firstAssistant?.content === "string"- ? firstAssistant.content- : undefined,- });- const nextTitle = result?.title?.trim();- if (nextTitle && !manualSessionTitles.has(sessionId)) {- await api.renameSession(sessionId, nextTitle);- await get().refreshSessions();- }- } catch {- // Non-fatal: keep the current truncated prompt title as fallback.- }- }-- return { manualSessionTitles, triggerAutoTitleSummarization };-}diff --git a/apps/desktop/src/stores/slices/events-slice.ts b/apps/desktop/src/stores/slices/events-slice.tsindex e72bbfad5..fe4ef21dd 100644--- a/apps/desktop/src/stores/slices/events-slice.ts+++ b/apps/desktop/src/stores/slices/events-slice.ts@@ -60,7 +60,6 @@ export type EventsSliceDependencies = StoreAccess & {kind: "ask" | "permission" | "plan",payload?: { question?: string; toolName?: string },) => void;- triggerAutoTitleSummarization: (sessionId: string) => Promise<void>;flushPendingSessionConfiguration: (sessionId: string) => Promise<void>;assistantErrorMessage: (error: {code: string;@@ -104,7 +103,6 @@ export function createEventsSlice({sessionModeForPlanningState,openPlanArtifact,notifyInteractivePrompt,- triggerAutoTitleSummarization,flushPendingSessionConfiguration,assistantErrorMessage,withCompactionMark,@@ -498,7 +496,6 @@ export function createEventsSlice({});} else if (event.type === "agent_end") {void get().refreshSessions();- void triggerAutoTitleSummarization(envelope.sessionId);} else if (event.type === "planning_state") {void get().refreshSessions();}@@ -540,7 +537,6 @@ export function createEventsSlice({case "agent_end":set({ isRunning: false });void get().refreshSessions();- void triggerAutoTitleSummarization(envelope.sessionId);break;case "turn_end":break;diff --git a/apps/desktop/src/stores/slices/project-slice.ts b/apps/desktop/src/stores/slices/project-slice.tsindex 9206675e3..ab556ae79 100644--- a/apps/desktop/src/stores/slices/project-slice.ts+++ b/apps/desktop/src/stores/slices/project-slice.ts@@ -38,7 +38,6 @@ import type { StoreAccess } from "./types";export type ProjectSliceDependencies = StoreAccess & {runtime: SessionRuntime;- manualSessionTitles: Set<string>;withoutRecordKey: <T>(record: Record<string, T>, key: string) => Record<string, T>;withProjectDisplayName: (workspace: ProjectWorkspace,@@ -144,15 +143,13 @@ function clearLocalSessionState(get,set,runtime,- manualSessionTitles,withoutRecordKey,}: Pick<ProjectSliceDependencies,- "get" | "set" | "runtime" | "manualSessionTitles" | "withoutRecordKey"+ "get" | "set" | "runtime" | "withoutRecordKey">,id: string,): void {- manualSessionTitles.delete(id);runtime.pendingSessionConfigurations.delete(id);runtime.sessionTranscriptCache.delete(id);runtime.sessionHistoryCache.delete(id);@@ -219,7 +216,6 @@ export function createProjectSlice({get,set,runtime,- manualSessionTitles,withoutRecordKey,withProjectDisplayName,promoteProjectPath,@@ -446,7 +442,7 @@ export function createProjectSlice({await api.removeProject(path);for (const id of removedSessionIds) {clearLocalSessionState(- { get, set, runtime, manualSessionTitles, withoutRecordKey },+ { get, set, runtime, withoutRecordKey },id,);}@@ -534,14 +530,9 @@ export function createProjectSlice({if (!id) return;const nextTitle = title.trim();if (!nextTitle) throw new Error(i18n.t("errors.sessionTitleEmpty"));- manualSessionTitles.add(id);const result = await api.renameSession(id, nextTitle);if (!result.ok) throw new Error(i18n.t("errors.sessionNotFound"));set((state) => ({- sessionMeta: {- ...state.sessionMeta,- [id]: { ...(state.sessionMeta[id] || {}), manualTitle: true },- },sessions: state.sessions.map((session) =>session.id === id ? { ...session, title: nextTitle } : session,),@@ -577,10 +568,7 @@ export function createProjectSlice({await api.deleteSession(id);void api.pluginViewClose("pi.browser", "browser", { sessionId: id }).catch((error) => get().showToast(String(error), { variant: "error" }));- clearLocalSessionState(- { get, set, runtime, manualSessionTitles, withoutRecordKey },- id,- );+ clearLocalSessionState({ get, set, runtime, withoutRecordKey }, id);persistCurrentSidebar(get);await get().refreshSessions();},diff --git a/apps/desktop/src/stores/slices/queue-slice.ts b/apps/desktop/src/stores/slices/queue-slice.tsindex 585172078..e75de35b5 100644--- a/apps/desktop/src/stores/slices/queue-slice.ts+++ b/apps/desktop/src/stores/slices/queue-slice.ts@@ -38,9 +38,6 @@ export type QueueSliceDependencies = StoreAccess & {runtime: SessionRuntime;promptAttachmentsFromDraft: PromptAttachmentConverter;withoutRecordKey: <T>(record: Record<string, T>, key: string) => Record<string, T>;- promptFallbackSessionTitle: (content: string, emptyTitle: string) => string;- untitledTaskTitle: () => string;- isDefaultSessionTitle: (title?: string | null) => boolean;viewingSessionIdForPrompt: (state: Pick<AppState, "page" | "activeSessionId">,sessionId: string,@@ -56,9 +53,6 @@ export function createQueueSlice({runtime,promptAttachmentsFromDraft,withoutRecordKey,- promptFallbackSessionTitle,- untitledTaskTitle,- isDefaultSessionTitle,viewingSessionIdForPrompt,messageErrorFromUnknown,assistantErrorMessage,@@ -439,20 +433,8 @@ export function createQueueSlice({submission.draft.fileReferences,);runtime.insertOptimisticUserMessage(startedIn, optimisticMessage);+ const current = get().sessions.find((session) => session.id === sessionId);try {- const current = get().sessions.find((session) => session.id === sessionId);- if (isDefaultSessionTitle(current?.title)) {- const nextTitle = promptFallbackSessionTitle(- content,- untitledTaskTitle(),- );- api- .renameSession(sessionId, nextTitle)- .then(() => get().refreshSessions())- .catch(() => {- // Non-fatal title fallback.- });- }if (get().pendingPlans[sessionId]?.status === "pending") {runtime.submittedComposerDrafts.delete(startedIn);runtime.retractOptimisticUserMessage(startedIn, optimisticMessage);diff --git a/apps/desktop/test/plugin-runtime-risk.test.mjs b/apps/desktop/test/plugin-runtime-risk.test.mjsindex 7ffd94208..4bb7d127a 100644--- a/apps/desktop/test/plugin-runtime-risk.test.mjs+++ b/apps/desktop/test/plugin-runtime-risk.test.mjs@@ -44,6 +44,7 @@ test("plugin runtime exposes gated high-risk host APIs", () => {"agent.complete","desktop.control","session.read",+ "session.autoTitle","models.list","shell.openExternal","clipboard.read",@@ -110,6 +111,8 @@ test("the plugins page shows the file scope behind a file permission", () => {assert.equal(typeof catalog.plugins.permissionHelp["fs.delete"], "string");assert.equal(typeof catalog.plugins.permissions["agent.complete"], "string");assert.equal(typeof catalog.plugins.permissionHelp["session.read"], "string");+ assert.equal(typeof catalog.plugins.permissions["session.autoTitle"], "string");+ assert.equal(typeof catalog.plugins.permissionHelp["session.autoTitle"], "string");assert.equal(typeof catalog.plugins.permissions["models.list"], "string");assert.equal(typeof catalog.plugins.permissions["ui.microphone"], "string");assert.equal(typeof catalog.plugins.permissionHelp["ui.microphone"], "string");diff --git a/apps/desktop/test/plugin-session-api.test.mjs b/apps/desktop/test/plugin-session-api.test.mjsindex 554c6df08..c08257bf1 100644--- a/apps/desktop/test/plugin-session-api.test.mjs+++ b/apps/desktop/test/plugin-session-api.test.mjs@@ -312,6 +312,121 @@ test("plugin session read, update, and delete permissions are independent", asyn]);});+test("plugin auto-title APIs require the narrow permission and forward only bounded inputs", async (t) => {+ const calls = [];+ const runtime = new PluginRuntime({+ hostEntry: hostProcessEntry,+ spawnProcess: forkPluginProcess,+ session: {+ getAutoTitleContext: async (pluginId, input) => {+ calls.push(["context", pluginId, input]);+ return {+ sessionId: input.sessionId,+ expectedTitle: "New task",+ userPrompt: "Summarize this work",+ assistantReply: "Updated the session title flow",+ };+ },+ setAutoTitle: async (pluginId, input) => {+ calls.push(["set", pluginId, input]);+ return { updated: true };+ },+ },+ });+ t.after(async () => {+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);+ });+ const dir = writePlugin({+ id: "demo.auto-title",+ permissions: ["session.autoTitle"],+ main: `+ module.exports = {+ async onLoad() {+ await pi.commands.register({+ id: "title",+ title: "Title",+ run: async () => {+ const context = await pi.session.getAutoTitleContext({ sessionId: "s1" });+ await pi.ui.showToast("prompt:" + context.userPrompt);+ const result = await pi.session.setAutoTitle({+ sessionId: "s1", expectedTitle: context.expectedTitle, title: "Concise title"+ });+ await pi.ui.showToast("updated:" + result.updated);+ try {+ await pi.session.setAutoTitle({+ sessionId: "s1", expectedTitle: "New task", title: "界".repeat(81)+ });+ } catch (error) { await pi.ui.showToast("long:" + error.code); }+ }+ });+ }+ };+ `,+ });+ await runtime.loadFromPath(dir, ["session.autoTitle"]);+ await runCommand(runtime, "title");+ assert.deepEqual(calls, [+ ["context", "demo.auto-title", { sessionId: "s1" }],+ ["set", "demo.auto-title", {+ sessionId: "s1",+ expectedTitle: "New task",+ title: "Concise title",+ }],+ ]);+ assert.deepEqual(runtime.drainToasts(), [+ "prompt:Summarize this work",+ "updated:true",+ "long:LIMIT_EXCEEDED",+ ]);+});++test("plugin auto-title APIs are refused without session.autoTitle", async (t) => {+ const calls = [];+ const runtime = new PluginRuntime({+ hostEntry: hostProcessEntry,+ spawnProcess: forkPluginProcess,+ session: {+ getAutoTitleContext: async () => calls.push("context"),+ setAutoTitle: async () => calls.push("set"),+ },+ });+ t.after(async () => {+ for (const loaded of runtime.listLoaded()) await runtime.unload(loaded.manifest.id);+ });+ const dir = writePlugin({+ id: "demo.auto-title-denied",+ permissions: [],+ main: `+ module.exports = {+ async onLoad() {+ await pi.commands.register({+ id: "denied",+ title: "Denied",+ run: async () => {+ for (const [name, call] of [+ ["context", () => pi.session.getAutoTitleContext({ sessionId: "s1" })],+ ["set", () => pi.session.setAutoTitle({+ sessionId: "s1", expectedTitle: "New task", title: "Title"+ })],+ ]) {+ try { await call(); }+ catch (error) { await pi.ui.showToast(name + ":" + error.code); }+ }+ }+ });+ }+ };+ `,+ });+ await runtime.loadFromPath(dir, []);+ await runCommand(runtime, "denied");+ assert.deepEqual(calls, []);+ assert.deepEqual(runtime.drainToasts(), [+ "context:PERMISSION_DENIED",+ "set:PERMISSION_DENIED",+ ]);+});+test("plugin usage listTurns requires usage.read and forwards the plugin id", async (t) => {const calls = [];const runtime = new PluginRuntime({diff --git a/apps/desktop/test/queue-pending-actions.test.mjs b/apps/desktop/test/queue-pending-actions.test.mjsindex 5eec111cb..14c6faa87 100644--- a/apps/desktop/test/queue-pending-actions.test.mjs+++ b/apps/desktop/test/queue-pending-actions.test.mjs@@ -6,6 +6,68 @@ import { renderToStaticMarkup } from "react-dom/server";import { createServer } from "vite";import { IPC } from "@pi-desktop/shared";+test("sending the first prompt keeps the default session title for the title plugin", async (t) => {+ const server = await createServer({+ root: fileURLToPath(new URL("..", import.meta.url)),+ configFile: false,+ server: { middlewareMode: true, hmr: false, ws: false },+ appType: "custom",+ optimizeDeps: { noDiscovery: true, include: [] },+ });+ const previousWindow = globalThis.window;+ try {+ const { createQueueSlice } = await server.ssrLoadModule("/src/stores/slices/queue-slice.ts");+ const invoked = [];+ globalThis.window = { piDesktop: { invoke: async (channel, payload) => {+ invoked.push([channel, payload]);+ if (channel !== IPC.invoke.agentPrompt) throw new Error(`Unexpected IPC: ${channel}`);+ return { ok: true, data: { turnId: "turn-1" } };+ } } };+ let state = {+ activeSessionId: "session-a",+ sessions: [{ id: "session-a", title: "New task", source: "desktop" }],+ messages: [],+ pendingPlans: {},+ runningSessions: {},+ latestTurnResults: {},+ sessionOutcomes: {},+ showToast: assert.fail,+ rememberModel() {},+ };+ const runtime = {+ submittedComposerDrafts: new Map(),+ sessionTranscriptCache: new Map(),+ insertOptimisticUserMessage() {},+ retractOptimisticUserMessage() {},+ };+ const slice = createQueueSlice({+ get: () => state,+ set: (update) => {+ const next = typeof update === "function" ? update(state) : update;+ state = { ...state, ...next };+ },+ runtime,+ promptAttachmentsFromDraft: () => [],+ withoutRecordKey: (record, key) => {+ const next = { ...record };+ delete next[key];+ return next;+ },+ viewingSessionIdForPrompt: () => "session-a",+ messageErrorFromUnknown: (error) => ({ code: "FAILED", message: String(error) }),+ assistantErrorMessage: () => ({ role: "assistant", content: "failed" }),+ materializeDraftSession: async () => null,+ });++ assert.equal(await slice.sendPrompt("Summarize the first turn", undefined, "session-a"), true);+ assert.equal(state.sessions[0].title, "New task");+ assert.deepEqual(invoked.map(([channel]) => channel), [IPC.invoke.agentPrompt]);+ } finally {+ globalThis.window = previousWindow;+ await server.close();+ }+});+test("pending queue actions stay locked until admission succeeds", async (t) => {const server = await createServer({root: fileURLToPath(new URL("..", import.meta.url)),diff --git a/apps/desktop/test/session-auto-title.test.mjs b/apps/desktop/test/session-auto-title.test.mjsdeleted file mode 100644index 7f0a59833..000000000--- a/apps/desktop/test/session-auto-title.test.mjs+++ /dev/null@@ -1,41 +0,0 @@-import { readAppSource, readStoreSource, readMainSource } from "./helpers/source-contracts.mjs";-import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";-import test from "node:test";--const read = (path) => readFile(new URL(path, import.meta.url), "utf8");-const [store, sidebarPreferences, api, app, main, protocol, runtime] = await Promise.all([- readStoreSource(),- read("../src/lib/sidebar-preferences.ts"),- read("../src/lib/api.ts"),- readAppSource(),- readMainSource(),- read("../../../packages/shared/src/protocol.ts"),- read("../../../packages/agent-runtime/src/session-title-summarize.ts"),-]);--test("session title summarization is wired through the full desktop path", () => {- assert.match(protocol, /sessionSummarizeTitle: "pi-desktop\/session\/summarizeTitle"/);- assert.match(api, /summarizeSessionTitle: \(req: SessionSummarizeTitleRequest\)/);- assert.match(api, /IPC\.invoke\.sessionSummarizeTitle/);- assert.match(main, /handle\(IPC\.invoke\.sessionSummarizeTitle/);- assert.match(main, /resolveAgentRuntimeLaunch\(/);- assert.match(main, /summarizeSessionTitle\(/);- assert.match(main, /thinkingLevel: "off"/);- assert.match(runtime, /completeOneShot\(/);-});--test("automatic title generation runs after the first turn and respects restart-safe custom titles", () => {- assert.match(store, /event\.type === "agent_end"[\s\S]*triggerAutoTitleSummarization/);- assert.match(store, /manualTitle/);- assert.match(store, /!isDefaultSessionTitle\(session\.title\)/);- assert.match(store, /promptFallbackSessionTitle\(firstUser\.content, ""\)/);- assert.match(store, /initialSidebarPreferences\.sessionMeta/);- assert.match(store, /manualTitle: true/);- assert.match(sidebarPreferences, /manualTitle\?: boolean/);- assert.match(sidebarPreferences, /raw\.manualTitle/);- assert.match(store, /kind: "interactive"/);- assert.match(app, /kind: "task"/);- assert.match(main, /kind\?: "task" \| "interactive"/);- assert.match(main, /shouldShowNativeNotification\(/);-});diff --git a/apps/desktop/test/session-rename.test.mjs b/apps/desktop/test/session-rename.test.mjsindex 749069598..60e0d650a 100644--- a/apps/desktop/test/session-rename.test.mjs+++ b/apps/desktop/test/session-rename.test.mjs@@ -67,7 +67,7 @@ test("host title validation is bounded and does not change activity ordering", (assert.match(hostSource, /MAX_SESSION_TITLE_CHARS: usize = 80/);assert.match(hostSource, /let title = title\.trim\(\)/);assert.match(hostSource, /title\.chars\(\)\.count\(\) > MAX_SESSION_TITLE_CHARS/);- assert.match(hostSource, /UPDATE sessions SET title = \?1 WHERE id = \?2/);+ assert.match(hostSource, /UPDATE sessions SET title = \?1, title_source = \?2 WHERE id = \?3/);assert.doesNotMatch(hostSource, /UPDATE sessions SET title = \?1, updated_at = \?2 WHERE id = \?3/);assert.match(hostSource, /rename_session_normalizes_title_without_touching_activity/);});diff --git a/apps/desktop/test/todo-events.test.mjs b/apps/desktop/test/todo-events.test.mjsindex ccb925a89..f58bd9321 100644--- a/apps/desktop/test/todo-events.test.mjs+++ b/apps/desktop/test/todo-events.test.mjs@@ -37,7 +37,6 @@ function makeSlice() {sessionModeForPlanningState: () => "agent",openPlanArtifact() {},notifyInteractivePrompt() {},- triggerAutoTitleSummarization: async () => {},flushPendingSessionConfiguration: async () => {},assistantErrorMessage: () => ({ role: "assistant", content: "" }),withCompactionMark: (marks, mark) => [...(marks ?? []), mark],diff --git a/crates/host-core/src/db.rs b/crates/host-core/src/db.rsindex 3b133f677..fc8c18a12 100644--- a/crates/host-core/src/db.rs+++ b/crates/host-core/src/db.rs@@ -7,7 +7,7 @@ pub(crate) use serde_json::Value;pub(crate) use std::path::{Path, PathBuf};/// Current SQLite schema version.-pub const SCHEMA_VERSION: i64 = 22;+pub const SCHEMA_VERSION: i64 = 23;/// Absolute approval deadline for a newly submitted Plan or Goal proposal.pub const PLAN_APPROVAL_TIMEOUT_MS: i64 = 30 * 60 * 1000;diff --git a/crates/host-core/src/db/migrations.rs b/crates/host-core/src/db/migrations.rsindex 95a004fa2..86a93ffd7 100644--- a/crates/host-core/src/db/migrations.rs+++ b/crates/host-core/src/db/migrations.rs@@ -984,3 +984,43 @@ pub(crate) fn migrate_v21_to_v22(conn: &Connection, path: &Path) -> Result<()> {})?;Ok(())}++pub(crate) fn migrate_v22_to_v23_tx(tx: &rusqlite::Transaction<'_>) -> Result<()> {+ let has_title_source: bool = tx.query_row(+ "SELECT EXISTS(SELECT 1 FROM pragma_table_info('sessions') WHERE name = 'title_source')",+ [],+ |row| row.get(0),+ )?;+ if !has_title_source {+ tx.execute_batch(+ "ALTER TABLE sessions ADD COLUMN title_source TEXT NOT NULL DEFAULT 'legacy'+ CHECK (title_source IN ('legacy', 'default', 'manual', 'generated'));",+ )?;+ // Older releases stored default and manually-entered titles in the+ // same column. Preserve the distinction where it is observable: only+ // known placeholders remain eligible for the standalone title plugin;+ // every other pre-existing title is treated as manual.+ tx.execute(+ "UPDATE sessions SET title_source = CASE+ WHEN title IN ('', 'New task', 'New chat', '新建任务', '新对话') THEN 'default'+ ELSE 'manual'+ END",+ [],+ )?;+ }+ tx.pragma_update(None, "user_version", 23i64)?;+ Ok(())+}++pub(crate) fn migrate_v22_to_v23(conn: &Connection, path: &Path) -> Result<()> {+ let backup = create_migration_backup(conn, path, 22)?;+ let tx = conn.unchecked_transaction()?;+ migrate_v22_to_v23_tx(&tx)?;+ tx.commit().with_context(|| {+ format!(+ "commit schema v22 to v23 migration; backup {} remains",+ backup.display()+ )+ })?;+ Ok(())+}diff --git a/crates/host-core/src/db/repositories.rs b/crates/host-core/src/db/repositories.rsindex 5ad6ba12c..b44ea8249 100644--- a/crates/host-core/src/db/repositories.rs+++ b/crates/host-core/src/db/repositories.rs@@ -197,6 +197,9 @@ impl Database {21 => {crate::db::migrations::migrate_v21_to_v22(&conn, path)?;}+ 22 => {+ crate::db::migrations::migrate_v22_to_v23(&conn, path)?;+ }legacy @ 1..=6 => {let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");drop(conn);@@ -239,6 +242,10 @@ impl Database {}if migrated_version == 21 {crate::db::migrations::migrate_v21_to_v22(&conn, path)?;+ migrated_version = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;+ }+ if migrated_version == 22 {+ crate::db::migrations::migrate_v22_to_v23(&conn, path)?;}let db = Self { conn, data_dir };db.boot_maintenance()?;diff --git a/crates/host-core/src/db/schema.rs b/crates/host-core/src/db/schema.rsindex f096a2fca..dc2b2a4af 100644--- a/crates/host-core/src/db/schema.rs+++ b/crates/host-core/src/db/schema.rs@@ -89,6 +89,8 @@ CREATE TABLE sessions (provider_id TEXT,model_id TEXT,mode TEXT NOT NULL DEFAULT 'agent',+ title_source TEXT NOT NULL DEFAULT 'legacy'+ CHECK (title_source IN ('legacy', 'default', 'manual', 'generated')),thinking_level TEXT NOT NULL DEFAULT 'off'CHECK (thinking_level IN ('off', 'minimal', 'low', 'medium','high', 'xhigh', 'max', 'omit')),diff --git a/crates/host-core/src/db/tests.rs b/crates/host-core/src/db/tests.rsindex ae8ffd8f3..ce6e508df 100644--- a/crates/host-core/src/db/tests.rs+++ b/crates/host-core/src/db/tests.rs@@ -122,6 +122,54 @@ fn v18_database_migrates_session_thinking_omit() {assert!(sql.contains("'omit'"), "{sql}");}+#[test]+fn v22_database_migrates_session_title_sources_without_losing_titles() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ let (default_id, manual_id) = {+ let db = Database::open(&path).unwrap();+ let default_session =+ crate::sessions::create_session(&db, None, None, None, None, None).unwrap();+ let manual_session = crate::sessions::create_session(+ &db,+ Some("A title chosen by the user".into()),+ None,+ None,+ None,+ None,+ )+ .unwrap();+ db.conn()+ .execute_batch("ALTER TABLE sessions DROP COLUMN title_source;")+ .unwrap();+ db.conn().pragma_update(None, "user_version", 22).unwrap();+ (default_session.id, manual_session.id)+ };++ let db = Database::open(&path).unwrap();+ assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);+ assert!(migration_backup_path(&path, 22).exists());+ let sources: (String, String) = db+ .conn()+ .query_row(+ "SELECT+ (SELECT title_source FROM sessions WHERE id = ?1),+ (SELECT title_source FROM sessions WHERE id = ?2)",+ params![default_id, manual_id],+ |row| Ok((row.get(0)?, row.get(1)?)),+ )+ .unwrap();+ assert_eq!(sources, ("default".into(), "manual".into()));+ assert_eq!(+ crate::sessions::get_session(&db, &manual_id)+ .unwrap()+ .unwrap()+ .summary+ .title,+ "A title chosen by the user"+ );+}+/// v21 owns the session checklist. A real v20 database has neither the/// `sessions` stamps nor the `session_todo` table, so the upgrade must add/// both, keep the v20 rows, leave a readable pre-migration backup, and staydiff --git a/crates/host-core/src/plugin_sessions.rs b/crates/host-core/src/plugin_sessions.rsindex bbc982407..ad98fce43 100644--- a/crates/host-core/src/plugin_sessions.rs+++ b/crates/host-core/src/plugin_sessions.rs@@ -1122,6 +1122,62 @@ pub fn rename(db: &Database, plugin_id: &str, params_value: &Value) -> Result<VaOk(json!({ "updated": true }))}+/// Narrow title-context access for plugins that hold `session.autoTitle`.+/// The Electron broker performs the permission check; this method still+/// returns only the first user prompt and first assistant reply, and only for+/// sessions whose title remains eligible for automatic replacement.+pub fn auto_title_context(db: &Database, plugin_id: &str, params_value: &Value) -> Result<Value> {+ validate_payload(params_value)?;+ if plugin_id.trim().is_empty() {+ return Err(invalid("pluginId is required"));+ }+ let session_id = required_text(+ params_value+ .get("sessionId")+ .and_then(Value::as_str)+ .unwrap_or_default(),+ "sessionId",+ 128,+ )?;+ Ok(sessions::auto_title_context(db, &session_id)?+ .map(|context| json!(context))+ .unwrap_or(Value::Null))+}++/// Compare-and-set the title of an untouched default/fallback session.+pub fn set_auto_title(db: &Database, plugin_id: &str, params_value: &Value) -> Result<Value> {+ validate_payload(params_value)?;+ if plugin_id.trim().is_empty() {+ return Err(invalid("pluginId is required"));+ }+ let session_id = required_text(+ params_value+ .get("sessionId")+ .and_then(Value::as_str)+ .unwrap_or_default(),+ "sessionId",+ 128,+ )?;+ let expected_title = required_text(+ params_value+ .get("expectedTitle")+ .and_then(Value::as_str)+ .unwrap_or_default(),+ "expectedTitle",+ MAX_TITLE_CHARS,+ )?;+ let title = required_text(+ params_value+ .get("title")+ .and_then(Value::as_str)+ .unwrap_or_default(),+ "title",+ MAX_TITLE_CHARS,+ )?;+ let updated = sessions::set_automatic_session_title(db, &session_id, &expected_title, &title)?;+ Ok(json!({ "updated": updated }))+}+pub fn delete(db: &Database, plugin_id: &str, params_value: &Value) -> Result<Value> {validate_payload(params_value)?;let session_id = required_text(@@ -1197,6 +1253,24 @@ mod tests {})}+ fn append_text_message(+ db: &Database,+ session_id: &str,+ id: &str,+ role: &str,+ content: &str,+ second: u8,+ ) {+ let message: UiMessage = serde_json::from_value(json!({+ "id": id,+ "role": role,+ "content": content,+ "createdAt": format!("2026-01-01T00:00:{second:02}Z")+ }))+ .unwrap();+ sessions::append_message(db, session_id, &message, None).unwrap();+ }+#[test]fn import_is_host_owned_idempotent_and_keeps_history_unbound() {let (_dir, db) = db();@@ -1403,6 +1477,61 @@ mod tests {assert_ne!(reimported["sessionId"], id);}+ #[test]+ fn auto_title_plugin_api_exposes_only_first_turn_and_uses_compare_and_set() {+ let (_dir, db) = db();+ let session = sessions::create_session_with_options(+ &db,+ sessions::SessionCreateOptions {+ provider_id: Some("provider".into()),+ model_id: Some("model".into()),+ ..Default::default()+ },+ )+ .unwrap();+ append_text_message(&db, &session.id, "u1", "user", "first prompt", 1);+ append_text_message(&db, &session.id, "a1", "assistant", "first reply", 2);+ append_text_message(&db, &session.id, "u2", "user", "later prompt", 3);+ append_text_message(&db, &session.id, "a2", "assistant", "later reply", 4);++ let context =+ auto_title_context(&db, "plugin.title", &json!({ "sessionId": session.id })).unwrap();+ assert_eq!(context["userPrompt"], "first prompt");+ assert_eq!(context["assistantReply"], "first reply");+ assert_eq!(context["modelKey"], "provider/model");+ assert!(context.get("messages").is_none());++ let update = json!({+ "sessionId": session.id,+ "expectedTitle": "New task",+ "title": "Plugin generated"+ });+ assert_eq!(+ set_auto_title(&db, "plugin.title", &update).unwrap()["updated"],+ true+ );+ assert_eq!(+ set_auto_title(&db, "plugin.title", &update).unwrap()["updated"],+ false+ );+ assert_eq!(+ auto_title_context(&db, "plugin.title", &json!({ "sessionId": session.id })).unwrap(),+ Value::Null+ );+ }++ #[test]+ fn auto_title_plugin_api_does_not_return_manually_named_sessions() {+ let (_dir, db) = db();+ let session = sessions::create_session(&db, None, None, None, None, None).unwrap();+ append_text_message(&db, &session.id, "u1", "user", "first prompt", 1);+ sessions::rename_session(&db, &session.id, "Picked by user").unwrap();+ assert_eq!(+ auto_title_context(&db, "plugin.title", &json!({ "sessionId": session.id })).unwrap(),+ Value::Null+ );+ }+#[test]fn tool_import_scrubs_reserved_fields_and_rejects_invalid_timestamps() {let (_dir, db) = db();diff --git a/crates/host-core/src/plugins/providers/tests.rs b/crates/host-core/src/plugins/providers/tests.rsindex ff306aef2..f028989c2 100644--- a/crates/host-core/src/plugins/providers/tests.rs+++ b/crates/host-core/src/plugins/providers/tests.rs@@ -101,7 +101,7 @@ fn a_new_database_carries_the_owner_column_at_the_current_schema_version() {// v19 session omit, v21 the session Todo checklist, and v22 the// session-list index. A fresh database is stamped with the newest version,// so the column set is the current one.- assert_eq!(SCHEMA_VERSION, 22);+ assert_eq!(SCHEMA_VERSION, 23);let version: i64 = db.conn().query_row("PRAGMA user_version", [], |row| row.get(0))diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex cbdd5036e..09dbcc30f 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -2933,6 +2933,24 @@ async fn handle_request(plugin_sessions::list_messages(&st.db, plugin_id, ¶ms).map_err(plugin_session_rpc_err)}+ "plugin.session.autoTitleContext" => {+ let plugin_id = params+ .get("pluginId")+ .and_then(Value::as_str)+ .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))?;+ let st = state.lock().await;+ plugin_sessions::auto_title_context(&st.db, plugin_id, ¶ms)+ .map_err(plugin_session_rpc_err)+ }+ "plugin.session.setAutoTitle" => {+ let plugin_id = params+ .get("pluginId")+ .and_then(Value::as_str)+ .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))?;+ let st = state.lock().await;+ plugin_sessions::set_auto_title(&st.db, plugin_id, ¶ms)+ .map_err(plugin_session_rpc_err)+ }"plugin.session.rename" => {let plugin_id = params.get("pluginId")diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex 8669afe64..6dd1fa1f5 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -20,6 +20,21 @@ pub const MODES: [&str; 3] = ["plan", "goal", "agent"];/// Maximum number of Unicode scalar values accepted for a user-defined title.pub const MAX_SESSION_TITLE_CHARS: usize = 80;+const TITLE_SOURCE_DEFAULT: &str = "default";+const TITLE_SOURCE_MANUAL: &str = "manual";+const TITLE_SOURCE_GENERATED: &str = "generated";++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct AutoTitleContext {+ pub session_id: String,+ pub expected_title: String,+ pub user_prompt: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub assistant_reply: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub model_key: Option<String>,+}/// Compatibility normalization for v7 callers and imported records. The/// persisted operating profile is now always `plan`, `goal` or `agent`.@@ -1275,50 +1290,13 @@ pub(crate) fn summary_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Sess// ---- sessions ----------------------------------------------------------------fn first_user_title(db: &Database, session_id: &str) -> Result<Option<String>> {- let mut stmt = db.conn().prepare_cached(- "SELECT text FROM messages- WHERE session_id = ?1 AND role = 'user' AND text IS NOT NULL- ORDER BY seq ASC LIMIT 1",- )?;- let content: Option<String> = stmt- .query_row(params![session_id], |row| row.get(0))- .optional()?;- Ok(content.and_then(|c| {- let t = c.trim().replace('\n', " ");- let t = t.split_whitespace().collect::<Vec<_>>().join(" ");- if t.is_empty() {- None- } else {- let mut out = t.chars().take(48).collect::<String>();- if t.chars().count() > 48 {- out.push('…');- }- Some(out)- }- }))-}-pub fn list_sessions(db: &Database) -> Result<Vec<SessionSummary>> {let sql = format!("{SUMMARY_SELECT} ORDER BY s.updated_at DESC");let mut stmt = db.conn().prepare_cached(&sql)?;let rows = stmt.query_map([], summary_from_row)?;let mut out = Vec::new();for row in rows {- let mut session = row?;- if is_default_title(&session.title) {- if let Some(title) = first_user_title(db, &session.id)? {- // Persist so Recents stays stable across restarts. Each write is- // its own commit, which looks like an obvious batching win —- // batching them into one transaction measured 0.114 ms -> 0.022 ms- // for forty sessions, and was left out anyway: a- // session stops having a default title the first time this runs,- // so the extra commits happen once per session, not per read.- let _ = rename_session(db, &session.id, &title);- session.title = title;- }- }- out.push(session);+ out.push(row?);}Ok(out)}@@ -1394,6 +1372,11 @@ pub fn create_session_with_options(let now = now_ms();let id = Uuid::new_v4().to_string();let title = title.unwrap_or_else(|| "New task".into());+ let title_source = if is_default_title(&title) {+ TITLE_SOURCE_DEFAULT+ } else {+ TITLE_SOURCE_MANUAL+ };let mode = normalize_mode(mode.as_deref());let thinking_level = thinking_level.unwrap_or_else(default_thinking_level);validate_thinking_level(&thinking_level)?;@@ -1414,8 +1397,8 @@ pub fn create_session_with_options(.prepare_cached("INSERT INTO sessions (id, title, project_id, provider_id, model_id, mode, thinking_level,- permission_mode, created_at, updated_at- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)",+ permission_mode, title_source, created_at, updated_at+ ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10)",)?.execute(params![id,@@ -1426,6 +1409,7 @@ pub fn create_session_with_options(mode,thinking_level,permission_mode,+ title_source,now])?;Ok(SessionSummary {@@ -1941,8 +1925,98 @@ pub fn rename_session(db: &Database, id: &str, title: &str) -> Result<bool> {let title = normalize_session_title(title)?;let n = db.conn()- .prepare_cached("UPDATE sessions SET title = ?1 WHERE id = ?2")?- .execute(params![title, id])?;+ .prepare_cached("UPDATE sessions SET title = ?1, title_source = ?2 WHERE id = ?3")?+ .execute(params![title, TITLE_SOURCE_MANUAL, id])?;+ Ok(n > 0)+}++/// Return only the first-turn text needed to name an untouched session.+/// The dedicated plugin API must not become a transcript-reading shortcut.+pub fn auto_title_context(db: &Database, id: &str) -> Result<Option<AutoTitleContext>> {+ let row: Option<(String, String, Option<String>, Option<String>)> = db+ .conn()+ .query_row(+ "SELECT title, title_source, provider_id, model_id+ FROM sessions WHERE id = ?1 AND deleted_at IS NULL",+ params![id],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),+ )+ .optional()?;+ let Some((title, title_source, provider_id, model_id)) = row else {+ return Ok(None);+ };+ if title_source != TITLE_SOURCE_DEFAULT {+ return Ok(None);+ }++ let first_user: Option<(i64, Option<String>, String)> = db+ .conn()+ .query_row(+ "SELECT seq, turn_id, text FROM messages+ WHERE session_id = ?1 AND role = 'user' AND text IS NOT NULL+ ORDER BY seq ASC LIMIT 1",+ params![id],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),+ )+ .optional()?;+ let Some((user_seq, turn_id, user_prompt)) = first_user else {+ return Ok(None);+ };+ if user_prompt.trim().is_empty() {+ return Ok(None);+ }+ let assistant_reply: Option<String> = db+ .conn()+ .query_row(+ "SELECT text FROM messages+ WHERE session_id = ?1 AND role = 'assistant' AND text IS NOT NULL AND seq > ?2+ AND (?3 IS NULL OR turn_id = ?3)+ ORDER BY seq ASC LIMIT 1",+ params![id, user_seq, turn_id],+ |row| row.get(0),+ )+ .optional()?;+ let user_prompt = truncate_title_context(&user_prompt, 1_000);+ let assistant_reply = assistant_reply+ .map(|reply| truncate_title_context(&reply, 500))+ .filter(|reply| !reply.trim().is_empty());+ Ok(Some(AutoTitleContext {+ session_id: id.to_string(),+ expected_title: title,+ user_prompt,+ assistant_reply,+ model_key: provider_id+ .zip(model_id)+ .map(|(provider, model)| format!("{provider}/{model}")),+ }))+}++fn truncate_title_context(value: &str, limit: usize) -> String {+ value.chars().take(limit).collect()+}++/// Apply a plugin-generated title only if the exact default title read by the+/// plugin is still current and no manual or generated title has won the race.+pub fn set_automatic_session_title(+ db: &Database,+ id: &str,+ expected_title: &str,+ title: &str,+) -> Result<bool> {+ let title = normalize_session_title(title)?;+ let n = db+ .conn()+ .prepare_cached(+ "UPDATE sessions SET title = ?1, title_source = ?2+ WHERE id = ?3 AND title = ?4 AND title_source = ?5 AND deleted_at IS NULL",+ )?+ .execute(params![+ title,+ TITLE_SOURCE_GENERATED,+ id,+ expected_title,+ TITLE_SOURCE_DEFAULT+ ])?;Ok(n > 0)}@@ -4622,6 +4696,65 @@ mod tests {assert!(!rename_session(&db, "missing", "Valid").unwrap());}+ #[test]+ fn auto_title_context_is_limited_to_the_first_turn_and_bounded() {+ let db = test_db();+ let session = create_session_with_options(+ &db,+ SessionCreateOptions {+ provider_id: Some("provider".into()),+ model_id: Some("model".into()),+ ..Default::default()+ },+ )+ .unwrap();+ let first_prompt = "p".repeat(1_100);+ append_message(+ &db,+ &session.id,+ &user_msg("user-1", &first_prompt, "2026-01-01T00:00:01Z"),+ None,+ )+ .unwrap();+ let mut first_reply = user_msg("assistant-1", &"r".repeat(600), "2026-01-01T00:00:02Z");+ first_reply.role = "assistant".into();+ append_message(&db, &session.id, &first_reply, None).unwrap();+ append_message(+ &db,+ &session.id,+ &user_msg("user-2", "later prompt", "2026-01-01T00:00:03Z"),+ None,+ )+ .unwrap();+ let mut later_reply = user_msg("assistant-2", "later reply", "2026-01-01T00:00:04Z");+ later_reply.role = "assistant".into();+ append_message(&db, &session.id, &later_reply, None).unwrap();++ let context = auto_title_context(&db, &session.id).unwrap().unwrap();+ assert_eq!(context.session_id, session.id);+ assert_eq!(context.expected_title, "New task");+ assert_eq!(context.user_prompt, "p".repeat(1_000));+ assert_eq!(context.assistant_reply, Some("r".repeat(500)));+ assert_eq!(context.model_key.as_deref(), Some("provider/model"));+ }++ #[test]+ fn automatic_title_compare_and_set_respects_manual_and_stale_titles() {+ let db = test_db();+ let session = create_session(&db, None, None, None, None, None).unwrap();+ assert!(set_automatic_session_title(&db, &session.id, "New task", "Generated").unwrap());+ assert!(auto_title_context(&db, &session.id).unwrap().is_none());+ assert!(!set_automatic_session_title(&db, &session.id, "New task", "Stale").unwrap());++ let manual = create_session(&db, None, None, None, None, None).unwrap();+ assert!(rename_session(&db, &manual.id, "Picked by user").unwrap());+ assert!(!set_automatic_session_title(&db, &manual.id, "New task", "Generated").unwrap());+ assert_eq!(+ get_session(&db, &manual.id).unwrap().unwrap().summary.title,+ "Picked by user"+ );+ }+#[test]fn create_session_returns_canonical_project_path() {let dir = tempfile::tempdir().unwrap();diff --git a/crates/host-core/src/turn_queue.rs b/crates/host-core/src/turn_queue.rsindex b34cb9e77..9addb58bd 100644--- a/crates/host-core/src/turn_queue.rs+++ b/crates/host-core/src/turn_queue.rs@@ -532,7 +532,7 @@ mod tests {assert_eq!(entries[0].content, "existing");assert!(entries[0].user_message_id.is_none());assert!(entries[0].voice_origin.is_none());- assert_eq!(crate::db::SCHEMA_VERSION, 22);+ assert_eq!(crate::db::SCHEMA_VERSION, 23);}#[test]diff --git a/docs/adr/0143-user-renamable-session-titles.md b/docs/adr/0143-user-renamable-session-titles.mdindex c0608c201..e5e83a578 100644--- a/docs/adr/0143-user-renamable-session-titles.md+++ b/docs/adr/0143-user-renamable-session-titles.md@@ -19,11 +19,11 @@ the Project archive task row. It trims input, accepts 1–80 Unicode code pointsand keeps the Save action unavailable for an empty value. The host validates thesame rules so direct IPC callers cannot persist invalid titles.-Renaming updates only `sessions.title`. It does not modify the transcript,-message count, project binding, empty-session predicate, or `updated_at` activity-timestamp. A non-default title continues to opt out of first-prompt automatic-title generation. Existing `session.rename` IPC and host RPC channels are used;-no schema or protocol version change is required.+Renaming updates `sessions.title` and marks its host-owned `title_source` as+`manual`. It does not modify the transcript, message count, project binding,+empty-session predicate, or `updated_at` activity timestamp. Plugin-generated+titles use a compare-and-set against the default title, so a manual rename wins+a race without renderer-local title state.Historical notification title snapshots remain unchanged. Newly renderedsurfaces read the current session summary, so the renamed title is shown in thediff --git a/docs/adr/0186-session-auto-title-summary.md b/docs/adr/0186-session-auto-title-summary.mdindex 5cb800321..dedd106bb 100644--- a/docs/adr/0186-session-auto-title-summary.md+++ b/docs/adr/0186-session-auto-title-summary.md@@ -1,6 +1,6 @@# ADR 0186: Summarize First-Turn Session Titles with a Main-Owned One-Shot-- Status: Accepted+- Status: Superseded by ADR 0323- Date: 2026-09-08## Context@@ -10,7 +10,7 @@ prompt is noisy and can obscure the task's topic. The title summary must use thesame provider/model as the session without moving model execution into therenderer or changing host-owned session storage.-## Decision+## Decision (historical)Keep the normalized first-prompt fallback synchronous from the renderer's pointof view. After the initial turn emits `agent_end`, the renderer calls the@@ -27,7 +27,7 @@ the deterministic first-prompt fallback. This protects manual titles madebefore the marker existed and prevents a completed summary from being replacedon a later renderer restart. No host RPC or storage schema version changes.-## Consequences+## Consequences (historical)- New sessions get immediate, readable fallback labels and a concise backgroundsummary when the configured provider succeeds.diff --git a/docs/adr/0323-plugin-owned-session-titles.md b/docs/adr/0323-plugin-owned-session-titles.mdnew file mode 100644index 000000000..7ad0a966b--- /dev/null+++ b/docs/adr/0323-plugin-owned-session-titles.md@@ -0,0 +1,57 @@+# ADR 0323: Make Session Title Generation a Standalone Plugin++- Status: Accepted+- Date: 2026-10-08+- Supersedes: ADR 0186++## Context++The core currently derives a prompt fallback in the renderer and runs a+main-owned one-shot completion after a turn. That couples title policy to the+agent lifecycle and gives users no prompt or model controls. Automatic title+generation is optional behavior and belongs in an independently installable+plugin.++The plugin still needs a safe way to name a normal Desktop session. Existing+plugin session reads are limited to sessions imported by that plugin, while the+general transcript API is intentionally too broad for this task.++## Decision++- Remove core prompt-derived fallback titles and the built-in title one-shot.+ New sessions keep their localized default title until the user renames them+ or an installed plugin updates them.+- Provide `session.autoTitle`, a dedicated high-risk permission for a narrow+ first-turn context and a compare-and-set title update. Context contains only+ the first user message and first assistant reply, each bounded, and is+ available only while the title source is `default`.+- Store `title_source` in host-core schema v23. Manual renames set `manual`;+ plugin updates set `generated`; default placeholders remain `default`. The+ title update compares the exact expected title and source so manual changes+ win races and survive renderer restarts.+- Ship title generation as the standalone `pi-desktop-session-title-plugin`+ repository. The plugin listens for completed turns and uses the existing+ `agent.complete` and `models.list` APIs. Its settings panel exposes an+ editable prompt template, model selection, and thinking level.++## Consequences++- Without the plugin, a new session keeps the default title. Installing and+ granting the plugin is required for generated titles.+- The plugin can customize title policy without adding a second title engine+ inside Electron or the renderer.+- The new permission allows the plugin to see bounded excerpts from any+ active default-titled Desktop session. It does not expose attachments, tools,+ later messages, or a general transcript-read method.+- Schema v23 classifies existing default placeholders as `default` and other+ existing titles as `manual`, preserving user-chosen titles during migration.++## Alternatives considered++- Keep the first-prompt fallback in the core: rejected because it would still+ automatically mutate titles when the optional plugin is absent.+- Give the plugin `session.read` or `session.read.own`: rejected because those+ permissions either expose a general transcript projection or only imported+ sessions and do not match the required boundary.+- Run a second title flow in Electron main: rejected because title policy and+ user-configured prompts/models belong to the plugin after this change.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 93805909d..10d8484dc 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -215,7 +215,7 @@ Each ADR includes:| 0183 | P0 international shell locales | Accepted (amends 0160 / 0182) || 0184 | Dock the context usage inspector in the composer toolbar | Accepted (amends 0047 / 0103) || 0185 | Korean shell locale | Accepted (amends 0160 / 0183) |-| 0186 | Summarize First-Turn Session Titles with a Main-Owned One-Shot | Accepted |+| 0186 | Summarize First-Turn Session Titles with a Main-Owned One-Shot | Superseded by 0323 || 0187 | Focus-Aware Native Task Notifications | Accepted (amends 0107 / D117) || 0188 | Preserve distinct credentials during model configuration import | Accepted (amends 0179 / D342) || 0189 | Parent fatal error aborts leftover delegates | Accepted (amends 0166 / D328) |@@ -364,3 +364,4 @@ Each ADR includes:| 0320 | [Host-owned OAuth lifecycle for plugin providers](0320-plugin-oauth-provider-callbacks.md) | Accepted for implementation (D647; amends ADR 0259) || 0321 | [Pin an acceptable address for mixed direct DNS answers](0321-skill-market-direct-dns-pinning.md) | Accepted (D648; amends ADR 0272) || 0322 | [Plugin providers appear in Add Service](0322-plugin-providers-in-add-service.md) | Accepted for implementation (D650; amends ADR 0259) |+| 0323 | [Make Session Title Generation a Standalone Plugin](0323-plugin-owned-session-titles.md) | Accepted (D651; supersedes ADR 0186) |diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex a1f97b469..493433976 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -53,7 +53,6 @@ Examples:- `pi-desktop/agent/event/message`- `pi-desktop/agent/askTool/resolve`- `pi-desktop/session/list`-- `pi-desktop/session/summarizeTitle`- `pi-desktop/project/open`- `pi-desktop/project/pickFolders`- `pi-desktop/project/clone`@@ -1066,13 +1065,8 @@ Minimal interface:- `session/rename({ id, title }) -> { ok: boolean }` trims the title andaccepts 1–80 Unicode code points. Blank or overlong titles are rejected as`INVALID_PARAMS`; a successful rename changes only session metadata and does- not alter transcript content, message count, or activity timestamps.-- `session/summarizeTitle({ sessionId, userPrompt, assistantReply? }) ->- { title }` validates the session and prompt in Electron main, resolves that- session's provider/model, and runs one `thinkingLevel: "off"` one-shot- completion. It never writes the title itself; the renderer applies the- result through `session/rename` only while the session still has a default or- first-prompt fallback title. A one-shot failure leaves that fallback intact.+ not alter transcript content, message count, or activity timestamps. It marks+ the title source as manual so an installed title plugin cannot replace it.- `session/getScratchPath({ sessionId }) -> { path }` returns the sessionscratch directory `<data_dir>/scratch/<sessionId>/` without creating it.- `session/openScratchPath({ sessionId }) -> { ok, path }` resolves that samediff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex ffc51e6fd..ea758c932 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -90,22 +90,20 @@ from pi's steering queue so it cannot execute independently on a later turn.An ordinary follow-up stays in the separate Host-owned FIFO until durable turnfinalization. A steering failure must not terminate the active run.-### 4.1 Session title summarization--The renderer applies a short first-prompt fallback immediately so sending a-prompt never waits on title generation. After the first turn emits `agent_end`,-Electron main resolves the session's effective provider/model and invokes the-runtime's `summarizeSessionTitle` one-shot path with thinking disabled. The-runtime supplies the initial user prompt and an optional assistant reply,-returns only sanitized title text, and treats an empty/failing completion as a-non-fatal result. The renderer persists a successful title through the existing-`session.rename` path.--The renderer also persists a `manualTitle` marker in its local session metadata.-Automatic summarization is skipped for that marker and for any persisted title-that is neither a recognized default nor the deterministic first-prompt-fallback, which protects manual and already-summarized titles after restart.-No host RPC or storage schema change is required.+### 4.1 Session title generation++The core keeps new sessions at their localized default title. It does not+derive a title from the first prompt or run a title completion. An optional+standalone plugin may subscribe to `session:turnEnded`; with the dedicated+`session.autoTitle` permission it can read only the first user prompt and first+assistant reply for a session whose title is still default, then use+`agent.complete` with its configured prompt, model, and thinking level.++The plugin writes through a host compare-and-set that succeeds only while the+exact default title is still current. Manual renames and another generated+title therefore win concurrent updates. Host-core owns the title source in+schema v23; this state survives renderer restart and does not expose a general+transcript-read API.## 5. Prompt flowdiff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 113bce6ef..e5ea5f958 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -1,4 +1,4 @@-# 04. Data Storage (Schema v17)+# 04. Data Storage (Schema v23)## 0. Ownership decision@@ -519,6 +519,8 @@ CREATE TABLE sessions (provider_id TEXT, -- loose ref, see belowmodel_id TEXT,mode TEXT NOT NULL DEFAULT 'agent', -- plan | agent+ title_source TEXT NOT NULL DEFAULT 'legacy' -- legacy | default | manual | generated+ CHECK (title_source IN ('legacy', 'default', 'manual', 'generated')),thinking_level TEXT NOT NULL DEFAULT 'off'CHECK (thinking_level IN ('off', 'minimal', 'low', 'medium','high', 'xhigh', 'max', 'omit')),@@ -531,7 +533,7 @@ CREATE TABLE sessions (created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL);-CREATE INDEX idx_sessions_updated ON sessions(updated_at DESC);+CREATE INDEX idx_sessions_updated_id ON sessions(updated_at DESC, id DESC);CREATE INDEX idx_sessions_project ON sessions(project_id) WHERE project_id IS NOT NULL;CREATE INDEX idx_sessions_deleted ON sessions(deleted_at) WHERE deleted_at IS NOT NULL;```@@ -574,6 +576,12 @@ CREATE INDEX idx_session_import_origins_pluginrename does not update `updated_at`, so changing a label cannot reorderrecent activity; transcript rows, message count, and session state remainunchanged.+- `title_source` records `legacy`, `default`, `manual`, or `generated`. Schema+ v23 classifies pre-existing known placeholder titles as `default` and all+ other titles as `manual`; new session creation and manual rename write the+ corresponding source. The standalone title plugin can read first-turn text+ only for `default` sessions and can write only with an exact-title+ compare-and-set, so a manual rename wins a race.- Import binds every non-empty normalized `projectPath` to `project_id`;path-less imports remain `NULL`. Re-importing a deterministic session idcreates neither another session nor another project row.@@ -1451,7 +1459,7 @@ truncating at a guessed position.- JSON columns are read blind on hot paths (shipped to the renderer as-is);anything filtered or summed is a promoted column by rule.-## 7. Versioning, v7 reset, and v8-to-v15 migration+## 7. Versioning, v7 reset, and v8-to-v23 migration- `PRAGMA user_version` stays the schema authority; future structural changesadd ordered Rust migration fns again, each in one transaction, with a@@ -1462,7 +1470,7 @@ truncating at a guessed position.Sessions, providers, and settings from the old file are not carried over;the archive remains for manual recovery. All pre-v7 migration code(v1 `settings.sqlite` import, v2→v6 chain) is deleted.-- Fresh installs run the full v15 DDL directly.+- Fresh installs run the full v23 DDL directly.- **Schema v7 first reaches v8, then uses the guarded path.** The v7→v8migration is followed by the same guarded v8→v15 migration; schema-v9 andschema-v10 databases take the same guarded path and receive an exact readable@@ -1523,6 +1531,9 @@ truncating at a guessed position.- **Schema v22 is additive.** It replaces `idx_sessions_updated` with`idx_sessions_updated_id(updated_at DESC, id DESC)` for session-list ordering.It changes no rows or persisted fields; a v21 backup precedes the migration.+- **Schema v23 is additive.** It adds `sessions.title_source` and classifies+ existing placeholder titles as `default`; every other existing title is+ preserved and classified as `manual`. The migration keeps a v22 backup.- **Schema v14 is additive.** It adds nullable `sessions.deleted_at`, thepartial deletion index, and `session_import_origins`. Existing sessions stayactive and have no origin rows. The migration runs in the same guardeddiff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.mdindex 589b8490f..6de3c0409 100644--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@ -171,12 +171,14 @@ Rules:advertises `"a2a"`. A v10 host or client is rejected before the UI becomesinteractive, so a mixed pair cannot call a missing domain.-Protocol v11 is paired with host-core storage schema v16. Schema v12 had added+Protocol v11 is paired with host-core storage schema v23. Schema v12 had addedthe A2A tables (`a2a_tasks`, `a2a_messages`, `a2a_artifacts`,`a2a_push_configs`) via `migrate_v11_to_v12`; `migrate_v12_to_v13` drops thosetables, and v14 adds the plugin-session ownership sidecar and soft-deletecolumn. Schema v15 adds the Host-owned turn queue, and schema v16 adds the-session collaboration ledger and its turn-queue binding. A fresh database+session collaboration ledger and its turn-queue binding. Schema v23 adds+`sessions.title_source` to preserve default, manual, and plugin-generated title+ownership. A fresh databasecreates neither A2A tables nor unowned plugin-session rows. The schema version is aninternal persistence invariant, not an additional JSON-RPC field; thecheckpoint architecture remains host-owned.@@ -331,8 +333,9 @@ to later refresh and inference; the vendor picker does not collect them.- `session.rename({ id, title })` trims and validates the title at the hostboundary. It accepts 1–80 Unicode code points and returns `{ ok: boolean }`;blank or overlong titles are `INVALID_PARAMS`. A successful rename changes- only session metadata and does not update `updated_at`, transcript content,- message count, or historical notification title snapshots.+ title metadata and marks the title source `manual`; it does not update+ `updated_at`, transcript content, message count, or historical notification+ title snapshots.- `session.configure` — atomically persists `mode`, `providerId`, `modelId`,and optional `thinkingLevel` (`off|minimal|low|medium|high|xhigh|max|omit`)for the next pi turn; omitting/null@@ -447,6 +450,11 @@ Electron main after plugin permission and manifest-source checks:- `plugin.session.importBatch` — bounded `skip` or all-or-nothing `fail` batch- `plugin.session.list` / `plugin.session.get` / `plugin.session.listMessages` —read only the calling plugin's active imported sessions+- `plugin.session.autoTitleContext` — under Electron's `session.autoTitle`+ permission, return only the first user prompt (≤1,000 characters) and first+ assistant reply (≤500 characters) for an active `default`-titled session+- `plugin.session.setAutoTitle` — validate a title and update only when the+ expected title and `default` source still match; returns `{ updated }`- `plugin.session.rename` — rename an owned active imported session- `plugin.session.delete` — `trash` hides and retains the transcript; `purge`removes it and permits re-importdiff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex a902b4da2..ba5f24e32 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -442,9 +442,9 @@ visually distinct from list content.| Archived row | Hidden by default; visible in the explicit archived view || No retained project | Compact Open project entry; standalone Sessions rows remain available || Empty group | Muted one-line empty state; group create action remains available |-| Default session title | New task/New chat (localized where applicable) until the first prompt |-| First prompt title | A normalized 48-character prompt fallback appears immediately; after the first turn, a successful background summary replaces it |-| Manual session title | User-defined title remains stable across refresh and renderer restart; automatic summary never overwrites it |+| Default session title | New task/New chat (localized where applicable) until the user or an installed title plugin sets one |+| Plugin-generated session title | A title plugin may replace the default after the first completed turn when its permission is granted |+| Manual session title | User-defined title remains stable across refresh and renderer restart; plugin updates use a host compare-and-set and never overwrite it || Footer idle | Transparent 58px band; build and action controls remain visually quiet || Footer hover/focus | Only the targeted control receives the semantic hover/focus treatment || Profile menu open | Profile trigger is active; 280px menu opens 8px above the footer |diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 5f6240bd1..20f2ce1c8 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -2831,25 +2831,33 @@ identify the platform validation still needed.- **Preconditions**: A project-scoped session and a path-less session exist;at least one session has transcript history and one still has the default- title.+ title. The standalone Session Titles plugin is enabled with+ `session.autoTitle`, `agent.complete`, and `models.list`, a deterministic test+ model, a custom prompt template, and thinking set to off.- **Steps**: 1) Open a Sidebar session overflow menu or right-click a sessionrow and choose Rename. 2) Enter a title with surrounding whitespace andsave. 3) Verify the title in the Sidebar, topbar, Project archive, andSearch. 4) Restart the app and verify the title again. 5) Try an empty and- an over-80-Unicode-code-point title. 6) Send the first prompt in the- default-title session.+ an over-80-Unicode-code-point title. 6) Open **Session Titles: Configure**,+ set the prompt to return a fixed test title, choose the deterministic test+ model, and save. 7) Send the first prompt in the default-title session. 8)+ Confirm the title stays at its localized default while the turn runs, then+ wait for `session:turnEnded` and the plugin completion. 9) Manually rename+ that session and complete another turn.- **Expected**: The saved title is trimmed, displayed across every currentsession-summary surface, and persists after restart. The session stays inthe same project or Temporary group, its transcript/message count andrecent-activity ordering do not change, and historical notification title- snapshots are unchanged. Empty and overlong values are rejected. A custom- title is not replaced by first-prompt auto-title; a still-default session- continues to receive its automatic title. After its first turn, the default- session first shows the prompt fallback and then adopts the concise- background LLM summary when the provider returns one.+ snapshots are unchanged. Empty and overlong values are rejected. Sending a+ prompt does not change the core title. The enabled plugin replaces a+ still-default title with the deterministic test title after the completed+ turn; after a manual rename, a later plugin completion cannot replace it. A+ session without the plugin remains at its localized default title.- **Specs linked**: `03-runtime/01-ipc-protocol.md`,`03-runtime/04-data-storage.md`, `03-runtime/06-host-rpc-protocol.md`,- `04-ux/01-ui-ia.md`, `04-ux/08-component-spec.md`, ADR 0143+ `03-runtime/02-agent-runtime.md`, `07-plugins/03-plugin-api.md`,+ `07-plugins/13-plugin-permissions-matrix.md`, `04-ux/01-ui-ia.md`,+ `04-ux/08-component-spec.md`, ADR 0143, ADR 0323- **Acceptance**: F (session metadata persistence), Quality (localized taskmanagement)- **Milestone**: M2@@ -9744,24 +9752,26 @@ This test plan spec is accepted when:- Composer omits the 本地 workspace label and shows Agent/Plan/Goal plus theactive model ID; both locales expose the Plan and Goal approval copy.-### US-UI-06 Session auto-title+### US-UI-06 Session title plugin- Create a new task and send a first prompt such as "同步代码".-- Expect its project or temporary session row to show the normalized prompt- fallback immediately, then adopt a concise LLM summary after the first turn.-- Restart before/after the summary and confirm the current title is retained;- rename a task from its session menu and send a first prompt if it was still- using a default title. Expect the custom label to remain unchanged while the- default-title task receives the normal first-prompt title.+- The core keeps the localized default title while the prompt is sent and after+ completion. When the Session Titles plugin is enabled and authorized, it may+ generate a title after the first completed turn using its configured prompt,+ model, and thinking level. Without the plugin, the title remains the default.+- Rename the session manually and complete another turn. The plugin must not+ replace the user-defined title.### US-UI-08 Shortcut-only destination history- Navigate Settings → Project archive → a project session → Plugins.- Expect no back/forward buttons in the expanded sidebar or main titlebar.- Press `Cmd/Ctrl+[` and `Cmd/Ctrl+]`; expect them to traverse that history.-### US-UI-09 Grouped session title backfill-- Open an older session that previously showed "New task"/"New chat" but has a first user message.-- Expect its scoped sidebar row to display a truncated first-user-message title- after session list load.+### US-UI-09 Default session title persistence+- Open an older session that showed "New task"/"New chat" and has a first user+ message.+- Without the title plugin, its scoped sidebar row keeps the default title;+ with the plugin, the title changes only after the first turn completes and the+ plugin is authorized.### US-UI-11 Empty draft reuse- Click New task twice.diff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.mdindex 96cbe2862..f23b3376c 100644--- a/docs/spec/07-plugins/03-plugin-api.md+++ b/docs/spec/07-plugins/03-plugin-api.md@@ -455,6 +455,40 @@ session (D333 / D336). Calling this outside a tool execution fails withplugin's own tool is stripped from the tail. A compaction summary replacespre-checkpoint history. Combined content is capped at 200k characters.+### session auto-title (requires `session.autoTitle`)++This capability is separate from `session.read`: it never exposes a transcript+window or arbitrary message lookup. It exists for plugins that generate a title+after a completed turn.++```ts+type PluginAutoTitleContext = {+ sessionId: string+ expectedTitle: string+ userPrompt: string // first user message, at most 1,000 characters+ assistantReply?: string // first assistant reply, at most 500 characters+ modelKey?: string // providerId/modelId from the session configuration+}++pi.session.getAutoTitleContext(input: {+ sessionId: string+}): Promise<PluginAutoTitleContext | null>++pi.session.setAutoTitle(input: {+ sessionId: string+ expectedTitle: string+ title: string+}): Promise<{ updated: boolean }>+```++Context is returned only for an active session whose title source is still+`default`. The host does not return attachments, tool calls, later turns, or+the rest of the transcript. Title updates accept 1–80 Unicode code points and+use the exact `expectedTitle` as a compare-and-set; a manual rename or another+update makes the result `{ updated: false }`. Both methods require+`session.autoTitle`, which is high risk because the first-turn text can be sent+to a model by a plugin holding `agent.complete`.+### plugin-owned sessions (P0/P1; requires the matching permission)Plugins may import and manage only sessions whose origin belongs to that samediff --git a/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md b/docs/spec/07-plugins/12-plugin-ipc-and-host-services.mdindex 35c849f3a..8618062c3 100644--- a/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md+++ b/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md@@ -227,6 +227,19 @@ toast plus `pluginChanged` to the renderer.3. Start/stop triggers contribution registration/deregistration4. The market IPC runs end-to-end under a mock provider (later milestone)+The title plugin uses two narrow plugin session RPC methods after the Electron+broker enforces `session.autoTitle`:++- `plugin.session.autoTitleContext` returns only the first user message and+ first assistant reply, each character-bounded, and only while `title_source`+ is `default`.+- `plugin.session.setAutoTitle` validates the title and updates it only when+ both the expected title and `default` source still match. A successful update+ triggers the ordinary host-owned `sessionsChanged` event.++These methods are additive to host RPC protocol v11. They do not grant access to+`plugin.session.listMessages` or the general session transcript.+## Appendix: agent-tool dispatch protocol (implemented M5)Plugin agent tools execute in the desktop runner (Electron main), while thediff --git a/docs/spec/07-plugins/13-plugin-permissions-matrix.md b/docs/spec/07-plugins/13-plugin-permissions-matrix.mdindex 260e6201e..4e5e54f07 100644--- a/docs/spec/07-plugins/13-plugin-permissions-matrix.md+++ b/docs/spec/07-plugins/13-plugin-permissions-matrix.md@@ -45,6 +45,7 @@ Provide a permission–capability–risk–default-policy reference table for re| `models.list` | medium | `pi.models.list` | Confirm at install | Ready provider/model rows only; no secrets || `project.create` | high | `pi.project.create` and explicit `projectId` on session import | Confirm at install | Creates or reuses a durable project row without activating the workspace; imported sessions remain unbound unless the id is supplied || `session.read` | high | `pi.session.getLlmContext` | Confirm at install | In-flight tool session only; compaction-aware projection (D019 / D336) |+| `session.autoTitle` | high | `pi.session.getAutoTitleContext`, `pi.session.setAutoTitle` | Confirm at install | First user prompt (≤1,000 chars) and first assistant reply (≤500 chars) only, for default-titled sessions; title writes are compare-and-set. It does not grant transcript reads || `session.import` | high | `pi.session.import`, `pi.session.importBatch` | Confirm at install | Imports only into the calling plugin's declared session sources; bounded and rate-limited || `session.read.own` | medium | `pi.session.list`, `pi.session.get`, `pi.session.listMessages` | Confirm at install | Reads only sessions imported by the calling plugin; no cross-plugin access || `session.update.own` | medium | `pi.session.rename` | Confirm at install | Renames only the calling plugin's active imported sessions |diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 7cc38c90a..309b81dfc 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -44,6 +44,7 @@ This log freezes previously open questions into concrete decisions.| D648 | Skill Market pins an acceptable address for mixed direct DNS answers | **Amend ADR 0272: on a direct route, when DNS includes both rejected and acceptable answers, Skill Market selects and pins one acceptable address instead of letting Chromium choose among them. Third-party content prefers a public answer; the benchmark fake-IP is eligible only under the existing opt-in. ULA-only and other non-public-only answers remain blocked. Proxied and unreadable routes keep the existing policy. See ADR 0321 and E2E-SKILL-MARKET-NET-BOUNDARY.** | Dual-stack and transparent-proxy DNS can include an unused synthetic ULA answer beside an address the request can safely use; pinning prevents the rejected address from being dialed while avoiding the false refusal. || D649 | Cloud backup stays closed to users | **Amend D642 / D643: the Settings `sync` destination carries `developmentOnly: true` again, so a packaged build omits its rail row, page, and settings-search hits and falls back to General, while development builds keep it. Developer mode stays irrelevant to the destination and it still carries no Experimental badge. Sync behavior, protocol, host schema, and persisted data are unchanged; dropping the flag reopens it for packaged builds. See `04-ux/06-settings-ia.md` and E2E-CONFIG-SYNC-webdav-portable-configuration.** | The encrypted WebDAV backup is not ready to be offered to packaged-build users yet, so it stays implemented but out of the way until it opens. || D650 | Plugin providers appear in Add Service | **Amend ADR 0259: optional `category` groups manifest-owned provider rows; optional localized `description` supplies one-sentence hover/focus copy. Loaded plugins with `provider.register` contribute unconfigured API-key providers with endpoints. Tiles display provider names only; the Host saves keys through the existing provider secret path. There is no per-plugin provider-count cap. An empty model list is allowed only for an API-key provider with a base URL; after explicit key save, Host discovery populates its cached model choices. Configured rows remain in the provider list and leave the chooser. OAuth / no-auth rows are omitted; no new permission, runtime plugin API, provider row, or credential migration is added. See ADR 0322, `07-plugins/02-plugin-manifest-schema.md`, and E2E-PLUGIN-provider-catalog-add-service.** | Users could not discover manifest-owned community providers in the normal Add Service flow, and each plugin needed to group its own sites without owning credential UI. |+| D651 | Make session title generation a standalone plugin | **Supersede ADR 0186: remove core prompt-derived fallback and built-in title completion; new sessions keep their localized default title until a user or plugin changes it. Add the high-risk `session.autoTitle` capability for bounded first-turn context and compare-and-set title updates, backed by schema v23 `sessions.title_source`; manual rename marks `manual`, plugin output marks `generated`. The standalone plugin configures its prompt template, model, and thinking level through its panel and uses `session:turnEnded`, `models.list`, and `agent.complete`. See ADR 0323, E2E-021a, and the plugin API/permission specs.** | Title generation is optional product policy with model and prompt settings, and the host needs a narrow durable boundary that makes manual titles win races. |## B. Secondary implementation defaults@@ -385,7 +386,7 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.| D605 | Brazilian Portuguese (pt-BR) shell locale | **Amend D314 / ADR 0160 / ADR 0183 / ADR 0185: ship a complete `pt-BR` shell catalog with native name Português (Brasil) and English name Portuguese (Brazil). `pt-BR`, `pt_BR`, and regional `pt-*` resolve to the Brazilian Portuguese catalog; persisted `AppSettings.language` accepts `pt-BR`; Electron packages `pt-BR` and `pt_BR` Chromium locales; and a matching Brazilian Portuguese changelog keeps release notes in the active locale. No host protocol, storage schema, or IPC version change. See ADR 0306.** | Brazilian Portuguese users need a distinct complete shell and release-note language matching the existing searchable locale registry and packaging conventions. || D350 | Focus-aware native task notifications | **Amend D117 / ADR 0107: `notification/showNative` carries `kind` as `task` or `interactive`. Omitted or unknown values default to `task`. Task banners are suppressed whenever the main window is visible and focused, including a focused background session. Interactive prompts are suppressed only for the exact visible focused session. Interactive prompts never create a durable task inbox row. Plugin notifications stay on their permission-gated path. No host protocol or storage schema change. See ADR 0187 and E2E-065 / E2E-065a.** | Task completions and interactive asks share one native channel but need different focus rules. The field is `kind`; a colliding `source` name is not part of the contract. || D358 | Show provider retry causes in the active-turn status | **Amend ADR 0175: `AgentActivity.retrying` may carry bounded, already-redacted error details. The compact retry row stays at rest; hover or keyboard focus reveals the localized summary, stable code/status, and provider message. Intermediate retries never become transcript error rows. See ADR 0196 and US-UI-60d.** | Users need the current retry cause without duplicating the final assistant error. |-| D359 | Summarize first-turn session titles with a main-owned one-shot | **Keep the first-prompt fallback synchronous. After `agent_end`, the renderer calls allowlisted `session/summarizeTitle`. Electron resolves the session model and runs a thinking-disabled one-shot; a valid result persists through `session.rename`. Automatic replacement refuses a persisted `manualTitle` and any title that is neither a default nor the first-prompt fallback. No host schema change. See ADR 0186 and E2E-021a.** | A truncated first prompt is a poor sidebar label, but title generation must not block the turn or expose credentials to the renderer. |+| D359 | Summarize first-turn session titles with a main-owned one-shot *(superseded by D651)* | **Historical: the core once applied a first-prompt fallback, then ran `session/summarizeTitle` from Electron after `agent_end`. D651 removes both automatic title paths and moves optional generation to a standalone plugin.** | A truncated first prompt was a poor sidebar label, but title generation must not block the turn or expose credentials to the renderer. || D361 | Inline image transport uses a 10 MB app-side bound | **Amend ADR 0101 / D197: `MAX_INLINE_IMAGE_BYTES` is 10,000,000. Vision-capable models receive images at or below that decimal 10 MB bound as transient base64; larger images and non-vision models keep the `@path` fallback. Electron main and the sidecar share the constant so replay cannot take a different path. No protocol or schema change.** | MiniMax's OpenAI-compatible endpoint accepts one image up to 10 MB; a higher app bound produced provider rejections after the composer had already inlined the bytes. || D316 | Searchable theme picker | **Amend ADR 0160: Settings → General theme is a searchable picker row (same anchored-menu pattern as Language), not three preview cards. System / Light / Dark stay pinned at the top; plugin themes follow after a divider. `AppSettings.theme` and plugin-theme fallback are unchanged. See ADR 0161 and E2E-091.** | Plugin themes wrap a three-column card grid, and Language already solved the growing-list control. || D121 | Branded macOS development host | **`pnpm dev` on macOS launches electron-vite through a fingerprinted, ad-hoc-signed PI-Desktop copy of the installed Electron host bundle under `.cache/electron-dev/`. The generated bundle changes only development host metadata, executable name, bundle identifier, and the ICNS resource; it never mutates `node_modules`. Windows/Linux keep the stock development executable, while packaged lanes remain electron-builder-owned.** | AppKit ignores runtime app-name/menu overrides for the top-level application identity and takes the native menu name and About icon from the host bundle; a branded development host is required for parity with packaged PI-Desktop. |@@ -4136,17 +4137,14 @@ D193, and D194.mapping, settings/pluginChanged apply path, and the darwin live-windowvibrancy guard. See `04-ux/08-component-spec.md` §1.7 and US-UI-74 / E2E-076.-## 2026-09-08 — Session title summaries and focus-aware native task notifications (D359/D350)+## 2026-09-08 — Session title summaries and focus-aware native task notifications (historical title decision superseded by D651; D350 remains active)-- The initial prompt remains visible immediately as a normalized 48-character+- At the time, the initial prompt appeared immediately as a normalized 48-characterfallback. After the first turn, Electron resolves the session's effectiveprovider/model and runs the main-owned `session/summarizeTitle` one-shot withthinking disabled; the renderer persists a successful result through- `session.rename`.-- Renderer-local session metadata persists `manualTitle`. Automatic title- generation skips that marker and any persisted title that is neither a known- default nor the first-prompt fallback, so manual and already-summarized titles- survive renderer restart without a host schema change.+ `session.rename`. D651 / ADR 0323 removed this behavior and made title+ generation an optional standalone plugin.- Native task completion and interactive prompt alerts share an Electron IPCentry but have explicit `kind` values. Task banners are suppressed wheneverthe main window is visible and focused, including focused background sessions;@@ -7549,3 +7547,16 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.row leaves the chooser. OAuth and no-auth declarations do not appear.- See E2E-PLUGIN-provider-catalog-add-service and`07-plugins/02-plugin-manifest-schema.md` §5.4.+## 2026-10-08 — Make session title generation a standalone plugin (D651)++- The core no longer derives a title from the first prompt or runs a title+ completion. New sessions remain at their localized default until the user or+ an installed plugin changes the title.+- The `session.autoTitle` permission exposes only bounded first-turn text for a+ default-titled session and a host compare-and-set title update. Schema v23+ tracks default, manual, and generated title ownership.+- The standalone plugin exposes its prompt template, model, and thinking level+ in a settings panel. It uses `session:turnEnded`, `models.list`, and+ `agent.complete`; manual rename wins any concurrent update.+- Covered by the host title-source and plugin API tests and E2E-021a. See+ ADR 0323 and the plugin API and permission specifications.diff --git a/docs/zh-CN/adr/index.md b/docs/zh-CN/adr/index.mdindex b9ebb811e..29b6e034d 100644--- a/docs/zh-CN/adr/index.md+++ b/docs/zh-CN/adr/index.md@@ -42,7 +42,7 @@ ADR 记录那些不应被静默改变的架构选择。中文入口与英文索| [ADR 0183:P0 国际化应用程序壳语言](/adr/0183-p0-international-shell-locales) | 提供德语、西班牙语和法语完整外壳目录及发版日志 || [ADR 0184:输入框工具栏中的上下文用量检查器](/adr/0184-composer-context-usage-inspector) | 把剩余容量检查器移到模型选择器左侧,答案下方只保留模型徽章 || [ADR 0185:韩语应用程序壳](/adr/0185-korean-shell-locale) | 提供完整韩语外壳、系统语言解析和韩语发版日志目录 |-| [ADR 0186:用宿主一次性补全总结首轮会话标题](/adr/0186-session-auto-title-summary) | 首轮提示先显示回退标题,结束后由主进程按会话模型生成摘要 |+| [ADR 0186:用宿主一次性补全总结首轮会话标题](/adr/0186-session-auto-title-summary) | 已由 ADR 0323 取代:标题生成由可配置的独立插件拥有 || [ADR 0187:按焦点区分任务和交互式本机通知](/adr/0187-focus-aware-native-task-notifications) | 任务横幅仅在窗口失焦时出现;交互询问可通知聚焦的其他会话。字段名为 `kind` || [ADR 0188:模型配置导入保留不同凭据](/adr/0188-preserve-distinct-import-credentials) | 同一端点的不同 API 密钥作为独立提供商导入,相同凭据仍保持幂等跳过 || [ADR 0189:父级终态错误中止残留委托](/adr/0189-parent-fatal-error-aborts-leftover-delegates) | 父级空闲仍不中止委托;429 等终态错误会中止残留子智能体,让“继续”不再 AGENT_BUSY |@@ -50,6 +50,7 @@ ADR 记录那些不应被静默改变的架构选择。中文入口与英文索| [ADR 0191:明确标注两个 macOS 发布架构](/adr/0191-label-both-macos-release-architectures) | macOS DMG/ZIP 统一使用 `-arm64` / `-x64` 后缀,更新源 URL 与校验和保持一致 || [ADR 0192:为已配置模型设置别名并允许复制模型 id](/adr/0192-model-alias) | 别名只用于展示;配置页模型 id 可选择复制,请求仍使用真实 id || [ADR 0193:上下文检查器按最后一次请求计算占用](/adr/0193-last-request-context-occupancy) | 占用、本轮合计和缓存读写取最新一条助手消息,不再把工具循环里的每次请求加总 |+| [ADR 0323:会话标题由独立插件拥有](/adr/0323-plugin-owned-session-titles) | 核心保留默认标题;独立插件可配置提示词、模型与思考级别,并通过主机 CAS 更新标题 || [ADR 0194:可选的子智能体思考覆盖](/adr/0194-subagent-thinking-parameter-omission) | 子智能体可继承、显式关闭或不发送思考参数 || [ADR 0195:视口固定的工作面板开关](/adr/0195-viewport-fixed-work-panel-toggle) | 非设置页右上角提供与 Cmd/Ctrl+J 等价的指针开关 || [ADR 0196:在进行中重试行显示 provider 原因](/adr/0196-retry-cause-in-active-turn-status) | 悬停或聚焦重试状态行时显示错误摘要、错误码和安全的 provider 消息 |@@ -252,7 +253,7 @@ ADR 记录那些不应被静默改变的架构选择。中文入口与英文索| 0183 | [P0 国际化应用程序壳语言](/adr/0183-p0-international-shell-locales) | 已接受(修订 ADR 0160 / ADR 0182) || 0184 | [输入框工具栏中的上下文用量检查器](/adr/0184-composer-context-usage-inspector) | 已接受(修订 ADR 0047 / ADR 0103) || 0185 | [韩语应用程序壳](/adr/0185-korean-shell-locale) | 已接受(修订 ADR 0160 / ADR 0183) |-| 0186 | [用宿主一次性补全总结首轮会话标题](/adr/0186-session-auto-title-summary) | 已接受 |+| 0186 | [用宿主一次性补全总结首轮会话标题](/adr/0186-session-auto-title-summary) | 已被 ADR 0323 取代 || 0187 | [按焦点区分任务和交互式本机通知](/adr/0187-focus-aware-native-task-notifications) | 已接受(修订 ADR 0107 / D117) || 0188 | [模型配置导入保留不同凭据](/adr/0188-preserve-distinct-import-credentials) | 已接受(修订 ADR 0179 / D342) || 0189 | [父级终态错误中止残留委托](/adr/0189-parent-fatal-error-aborts-leftover-delegates) | 已接受(修订 ADR 0166 / D328) |@@ -260,6 +261,7 @@ ADR 记录那些不应被静默改变的架构选择。中文入口与英文索| 0191 | [明确标注两个 macOS 发布架构](/adr/0191-label-both-macos-release-architectures) | 已接受(修订 ADR 0145 / D353) || 0192 | [为已配置模型设置别名并允许复制模型 id](/adr/0192-model-alias) | 已接受(修订 D266) || 0193 | [上下文检查器按最后一次请求计算占用](/adr/0193-last-request-context-occupancy) | 已接受(修订 ADR 0047 / ADR 0103 / ADR 0184) |+| 0323 | [会话标题由独立插件拥有](/adr/0323-plugin-owned-session-titles) | 已接受 || 0194 | [可选的子智能体思考覆盖](/adr/0194-subagent-thinking-parameter-omission) | 已接受待实现 || 0195 | [视口固定的工作面板开关](/adr/0195-viewport-fixed-work-panel-toggle) | 已接受(修订 ADR 0068 / ADR 0085) || 0196 | [在进行中重试行显示 provider 原因](/adr/0196-retry-cause-in-active-turn-status) | 已接受(修订 ADR 0175) |diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.mdindex d8586829f..061587e88 100644--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md@@ -21,7 +21,7 @@| `app` | 应用程序信息、健康检查 || `agent` | 对话、中止、状态和交互式 Asktool 解决方案 || `plan` | Plan 提案列出、决议和变更事件 |-| `session` | 会话 CRUD/历史记录 |+| `session` | 会话 CRUD/历史记录/标题元数据 || `session collaboration` | 侧边栏投影使用的有界只读协作状态;变更仍通过已审查的插件网关完成 || `settings` | 配置 read/write || `secrets` | 秘密 write/delete/exists(绝不将明文返回到 UI 日志) |@@ -871,6 +871,10 @@ ID、或会话无法解析出默认目标时,得到 `supportsReasoning: false`- `session/importScan`- `session/importRun(candidates) -> { imported, skipped, failed }`+`session/rename({ id, title })` 会裁剪标题并接受 1–80 个 Unicode 码点;空标题或+超长标题返回 `INVALID_PARAMS`。成功重命名只更新会话元数据、不改活动时间,并将标题来源+标为 `manual`,因此标题插件不能覆盖它。+导入候选者携带 `projectPath: string | null` 与`messageCount: number | null`。扫描对每个源文件全量读取的上限为导入器的采样阈值;超过阈值的文件只做采样(头部 + 尾部),使多吉字节归档的扫描diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex 850e3c1d2..a745fe6c2 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -82,6 +82,17 @@ pi 消费排队输入时保留渲染器提供的消息 id;即使补充输入普通 follow-up 仍留在独立的 Host FIFO 中,直到当前持久回合最终落定。补充指令失败不得终止当前运行。+### 4.1 会话标题生成++核心会让新会话保持本地化默认标题,不会从第一条提示派生标题,也不会运行标题补全。+可选的独立插件可以订阅 `session:turnEnded`;获得专用的 `session.autoTitle` 权限后,+它只能读取标题仍为默认值的会话中的首条用户提示和首条助手回复,再使用配置的提示词、+模型及思考级别调用 `agent.complete`。++插件通过主机比较并设置更新标题,只有在当前标题仍与读取时完全一致且来源仍为 `default`+时才会成功。因此并发手动重命名或另一项标题更新会胜出。host-core 在架构 v23 中拥有+标题来源状态;该状态可跨渲染器重启保留,也不会开放通用转录读取 API。+## 5. 提示流程1. 加载持久会话,会话缺失则拒绝diff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.mdindex 109808c45..b139f8f92 100644--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md@@ -1,4 +1,4 @@-# 04. 数据存储(架构 v17)+# 04. 数据存储(架构 v23)> **翻译说明:** 本页是与 [英文源规格](/spec/03-runtime/04-data-storage) 一一对应的机器辅助翻译。代码、协议字段和标识符保持原文;如翻译与英文源事实有歧义,以英文版本为准。@@ -355,6 +355,8 @@ CREATE TABLE sessions (provider_id TEXT, -- loose ref, see belowmodel_id TEXT,mode TEXT NOT NULL DEFAULT 'agent', -- plan | agent+ title_source TEXT NOT NULL DEFAULT 'legacy' -- legacy | default | manual | generated+ CHECK (title_source IN ('legacy', 'default', 'manual', 'generated')),thinking_level TEXT NOT NULL DEFAULT 'off'CHECK (thinking_level IN ('off', 'minimal', 'low', 'medium','high', 'xhigh', 'max', 'omit')),@@ -367,11 +369,16 @@ CREATE TABLE sessions (created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL);-CREATE INDEX idx_sessions_updated ON sessions(updated_at DESC);+CREATE INDEX idx_sessions_updated_id ON sessions(updated_at DESC, id DESC);CREATE INDEX idx_sessions_project ON sessions(project_id) WHERE project_id IS NOT NULL;CREATE INDEX idx_sessions_deleted ON sessions(deleted_at) WHERE deleted_at IS NOT NULL;```+`title_source` 记录 `legacy`、`default`、`manual` 或 `generated`。架构 v23 会将已有的+已知占位标题归类为 `default`,其余标题归类为 `manual`,不改写标题。新建会话和手动重命名+会写入相应来源。独立标题插件只能读取 `default` 会话的首轮文本,并且只能用精确标题+比较并设置,因此并发手动重命名会胜出。+插件导入增加一个由主机拥有的来源 sidecar。它与核心会话身份分离,每次插件读写都必须匹配创建该行的 `plugin_id`:@@ -1146,7 +1153,7 @@ outbox 排空。渲染器侧的停止绝不重写已有已开始回复的转录- JSON 列在热路径上盲读(按原样发送到渲染器);任何过滤或求和的内容都是按规则提升的列。-## 7. 版本控制、v7 重置和 v8 到 v16 迁移+## 7. 版本控制、v7 重置和 v8 到 v23 迁移- `PRAGMA user_version` 保留模式权限;未来的结构性变化再次添加有序的 Rust 迁移 fns,每个都在一个事务中,并带有一个@@ -1157,7 +1164,7 @@ outbox 排空。渲染器侧的停止绝不重写已有已开始回复的转录旧文件中的会话、提供程序和设置不会保留;存档仍保留以供手动恢复。所有 v7 之前的迁移代码(v1 `settings.sqlite` 导入,v2→v6 链)被删除。-- 全新安装直接运行完整的 v16 DDL。+- 全新安装直接运行完整的 v23 DDL。- **架构 v15 是增量的。** 它增加 `turn_queue` 表及其两个索引(D386 / ADR 0213),使 Host拥有的回合队列在重启后存活;不改动任何已有行,迁移前保留 `pi.sqlite.v14.bak`。- **架构 v16 是增量的。** 它增加会话协作 link 和投递表、生命周期索引,以及可为空的@@ -1166,6 +1173,8 @@ outbox 排空。渲染器侧的停止绝不重写已有已开始回复的转录- **架构 v17 是增量的。** 它增加可为空的 `providers.owner_plugin_id` 归属列及其部分索引(ADR 0259),从而把插件在 `contributes.providers` 中声明的 provider 行与用户创建的行区分开—— 所有 v17 之前的行保持 NULL 归属。该步骤之前保留 `pi.sqlite.v16.bak` 副本。+- **架构 v23 是增量的。** 它增加 `sessions.title_source`,并将现有占位标题归类为+ `default`;其余现有标题保持原样并归类为 `manual`。迁移前保留 v22 备份。v15→v16 会话协作步骤现在写入 `16`(它自己的版本)而不是最新的架构常量,因此 v15 文件可以在一次启动中走完两个步骤。- **架构 v7 首先到达 v8,然后使用受保护的路径。** v7→v8diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.mdindex 1e0d5d4ad..5e45ce811 100644--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md@@ -154,8 +154,9 @@ type HandshakeResult = {9. 版本 11 撤回 A2A 协议栈(ADR 0165 / D326)。`a2a.*` 方法和通知已移除,握手不再声明 `a2a`;v10 主机或客户端必须在 UI 交互前拒绝。-协议 v11 与 host-core 存储架构 v14 配对。v14 增加插件会话来源 sidecar-和软删除字段;架构版本是内部持久性不变量,而不是额外的 JSON-RPC 字段,+协议 v11 与 host-core 存储架构 v23 配对。v14 增加插件会话来源 sidecar+和软删除字段;v23 增加 `sessions.title_source`,持久记录默认、手动和插件生成标题的归属。+架构版本是内部持久性不变量,而不是额外的 JSON-RPC 字段,检查点架构仍然由主机拥有。## 4. 方法目录(MVP)@@ -242,7 +243,8 @@ type ToolBudgetHealth = {- `session.get`- `session.delete`- `session.getScratchPath` — 会话的 scratch 目录(D114),按需创建-- `session.rename`+- `session.rename` — 在主机边界裁剪并校验标题,接受 1–80 个 Unicode 码点;成功后将标题来源+ 标记为 `manual`,但不更新 `updated_at`、转录内容、消息数或历史通知标题快照。- `session.configure` — 以原子方式持久保存 `mode`、`providerId`、`modelId`,以及可选的 `thinkingLevel` 用于下一个 pi 回合; omitting/null`thinkingLevel` 保留当前值;返回无效模式或级别@@ -324,6 +326,9 @@ ids 和非负 `tokensBefore`;它不会插入 message/search 行- `plugin.session.importBatch` — 有界的 `skip` 或全有或全无 `fail` 批量导入- `plugin.session.list` / `plugin.session.get` / `plugin.session.listMessages` —只读取调用插件自己导入且仍处于活动状态的会话+- `plugin.session.autoTitleContext` — 通过 Electron 的 `session.autoTitle` 权限校验后,+ 仅返回活动且标题来源为 `default` 的会话首条用户提示(≤1,000 字符)和首条助手回复(≤500 字符)+- `plugin.session.setAutoTitle` — 仅在预期标题和 `default` 来源仍匹配时更新标题;返回 `{ updated }`- `plugin.session.rename` — 重命名自己拥有的活动导入会话- `plugin.session.delete` — `trash` 隐藏并保留转录本;`purge` 删除并允许重新导入- `plugin.usage.listTurns` — 未删除会话的已完成 turn 事实页(标识符与 tokendiff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 48639dd42..a7c6dc972 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -361,9 +361,9 @@ Collapsed (48px):| 存档行 | 默认隐藏;在显式存档视图中可见 || 无保留项目 | 紧凑的开放式项目入口;独立会话行仍然可用 || 空组 | 静音单线空状态;组创建操作仍然可用 |-| 默认会话标题 | 首条提示前显示 New task/New chat(适时本地化) |-| 首条提示标题 | 立即显示规范化的 48 字符提示回退标题;首轮完成后,成功的后台摘要会替换它 |-| 手动会话标题 | 用户定义的标题在刷新和渲染器重启后保持稳定;自动摘要不会覆盖它 |+| 默认会话标题 | 保留本地化的 New task/New chat,直到用户或已安装的标题插件设置标题 |+| 插件生成的会话标题 | 获得权限的标题插件可在首轮完成后替换默认标题 |+| 手动会话标题 | 用户标题在刷新和渲染器重启后保持稳定;插件使用主机比较并设置,不会覆盖手动标题 || 页脚闲置 | 透明58px带;构建和动作控制在视觉上保持安静 || 页脚 hover/focus | 仅目标控件接受语义 hover/focus 处理 || 个人资料菜单打开 | 配置文件触发器已激活; 280px 菜单在页脚上方 8px 处打开 |diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 6308e2a23..63dd17d4e 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -5795,20 +5795,22 @@ eleven-tool-round desktop paths are verified by- Composer 省略本地工作区标签并显示 Agent/Plan/Goal 以及活动模型 ID;这两个区域设置都会公开 Plan 和 Goal 批准副本。-### US-UI-06 会话自动标题+### US-UI-06 会话标题插件- 创建一个新任务并发送第一个提示,例如“同步代码”。-- 期望其项目或临时会话行标题成为截断形式- 该提示而不是保留“新任务”。+- 提示发送期间及完成后,核心都保留本地化默认标题。启用并授权+ Session Titles 插件后,完成首轮可由插件按配置的提示词、模型和思考级别+ 生成标题;没有插件时标题继续保持默认值。+- 手动重命名后再完成一轮,插件不得覆盖用户设置的标题。### US-UI-08 仅快捷方式目的地历史记录- 导航设置 → 项目存档 → 项目会话 → 插件。- 扩展侧边栏或主标题栏中不会有 back/forward 按钮。- 按 `Cmd/Ctrl+[` 和 `Cmd/Ctrl+]`;期望他们能够穿越那段历史。-### US-UI-09 分组会话标题回填-- 打开先前显示“新任务”/“新聊天”但有第一条用户消息的旧会话。-- 期望其范围侧边栏行显示截断的第一用户消息标题- 会话列表加载后。+### US-UI-09 默认会话标题持久化+- 打开先前显示“新任务”/“新聊天”且有第一条用户消息的旧会话。+- 未启用标题插件时,范围侧边栏行仍显示原默认标题;启用插件时,只有+ 首轮完成且插件获准后才更新标题。### US-UI-11 空草稿重用- 单击“新任务”两次。diff --git a/docs/zh-CN/spec/07-plugins/03-plugin-api.md b/docs/zh-CN/spec/07-plugins/03-plugin-api.mdindex a92091994..d34e9d3fd 100644--- a/docs/zh-CN/spec/07-plugins/03-plugin-api.md+++ b/docs/zh-CN/spec/07-plugins/03-plugin-api.md@@ -353,6 +353,35 @@ pi.session.getLlmContext(): Promise<PluginLlmContext>正在飞行的工具调用会从尾部剥掉。compaction 摘要替换检查点之前的历史。合计内容上限 200k 字符。+### 会话自动标题(需要 `session.autoTitle`)++此能力与 `session.read` 分开:它不会开放任意转录窗口或消息查询,仅用于在回合完成后生成标题。++```ts+type PluginAutoTitleContext = {+ sessionId: string+ expectedTitle: string+ userPrompt: string // 第一条用户消息,最多 1,000 个字符+ assistantReply?: string // 第一条助手回复,最多 500 个字符+ modelKey?: string // 来自会话配置的 providerId/modelId+}++pi.session.getAutoTitleContext(input: {+ sessionId: string+}): Promise<PluginAutoTitleContext | null>++pi.session.setAutoTitle(input: {+ sessionId: string+ expectedTitle: string+ title: string+}): Promise<{ updated: boolean }>+```++只有活动会话且标题来源仍为 `default` 时才返回上下文。宿主不会返回附件、工具调用、后续回合+或其他转录内容。标题长度为 1–80 个 Unicode 码点,并通过精确的 `expectedTitle` 比较并设置;+手动重命名或另一项更新发生后返回 `{ updated: false }`。两个方法都需要高风险权限+`session.autoTitle`,因为持有 `agent.complete` 的插件可能将首轮文本发送给模型。+### 插件拥有的会话(P0/P1;需要对应权限)插件只能导入和管理归属于自身的会话。来源必须在diff --git a/docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.md b/docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.mdindex d5b18d225..142483336 100644--- a/docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.md+++ b/docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.md@@ -115,6 +115,10 @@ PluginManager## 6. RuntimeBroker 调用链+`plugin.session.autoTitleContext` 和 `plugin.session.setAutoTitle` 属于+`session.autoTitle` 权限管控的白名单能力。前者只读取默认标题会话的有界首轮文本;后者+在 Rust host-core 内通过精确标题 CAS 更新。它们不复用插件拥有会话的转录读取 API。+插件 API 调用:```textdiff --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 83b9ac2ae..c16b3a004 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@@ -48,6 +48,7 @@| `models.list` | 中等 | `pi.models.list` | 安装时确认 | 仅已就绪的 provider/model 行;不含密钥 || `project.create` | 高 | `pi.project.create` 及会话导入中的显式 `projectId` | 安装时确认 | 创建或复用持久项目记录但不激活工作区;只有显式传入 id 的导入会绑定项目 || `session.read` | 高 | `pi.session.getLlmContext` | 安装时确认 | 仅限进行中的工具会话;带 compaction 的投影(D019 / D336) |+| `session.autoTitle` | 高 | `pi.session.getAutoTitleContext`、`pi.session.setAutoTitle` | 安装时确认 | 仅限默认标题会话的首条用户提示(≤1,000 字符)和首条助手回复(≤500 字符);标题通过比较并设置写入;不授予转录读取 || `session.import` | 高 | `pi.session.import`、`pi.session.importBatch` | 安装时确认 | 只能导入插件声明来源;有大小和频率限制 || `session.read.own` | 中等 | `pi.session.list`、`pi.session.get`、`pi.session.listMessages` | 安装时确认 | 只能读取本插件导入的会话;不能跨插件访问 || `session.update.own` | 中等 | `pi.session.rename` | 安装时确认 | 只能重命名本插件拥有的活动导入会话 |diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex f21f40392..3ce56f26a 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -42,10 +42,11 @@| D642 | 云同步是对所有用户开放的实验性目的地 *(由 D643 修订)* | **移除设置中 `sync` 目的地的开发者模式与打包构建门控:其导轨行、页面和设置搜索命中在任何构建中对所有用户存在,已保存的 `sync` 标签页也不再回落到常规。远程主机保留这两道门控和它自己的徽章。该目的地继续在导轨行与页面标题上保留实验性徽章;同步行为、协议、Host schema 与持久化数据均不变。见 `04-ux/06-settings-ia.md` 与 E2E-CONFIG-SYNC-webdav-portable-configuration。** | 加密 WebDAV 备份是应用唯一的多设备配置路径,而开发者模式门控让需要它的用户无法发现该功能。 || D643 | 云同步不再带实验性徽章 *(由 D649 修订)* | **修订 D642:设置中的 `sync` 目的地不再有 `experimentalBadgeKey`,各内置语言包中的 `settings.configSync.experimental` 键也已删除。云同步在任何构建中对所有用户保持可用。远程主机保留自己的徽章和两道门控。同步行为、协议、Host schema 与持久化数据均不变。见 `04-ux/06-settings-ia.md` 与 E2E-CONFIG-SYNC-webdav-portable-configuration。** | 云同步是应用已发布的多设备路径,实验性标签已不再描述它,只会让该目的地看起来尚未完成。 || D644 | 便携指令文件没有体积上限 | **移除 Host 对便携指令文件施加的 32 KiB 单文件上限。全局与项目指令内容只受其他域同样拥有的便携实体负载上限约束,并在上传修订与校验远端修订时检查。UTF-8 校验、symlink 拒绝、作用域选择、映射与审批规则均不变。见 `03-runtime/22-config-sync.md` §2。** | 一个 33 KiB 的项目 `AGENTS.md` 会让整次采集以 `CONFIG_SYNC_LIMIT_EXCEEDED: instruction file is too large` 失败,而设置页只能把它显示为泛化的备份体积错误。 |+| D450 | 签名的 macOS GitHub Release | **修订 D078 / ADR 0022:GitHub tag 发布使用身份 `Developer ID Application: XingYu Liu (DUV63RKYTW)` / 团队 `DUV63RKYTW`,通过 Actions 密钥(`CSC_LINK`、`CSC_KEY_PASSWORD`、`APPLE_ID`、`APPLE_APP_SPECIFIC_PASSWORD`、`APPLE_TEAM_ID`)对 macOS DMG/ZIP 做 Developer ID 签名、`notarytool` 公证、装订和 Gatekeeper 校验;缺少密钥则失败。无证书的本地未签名打包仍可用。`workflow_dispatch` 仅可把 `sign_macos: false` 用于未签名调试产物。打包的 macOS 走应用内 `electron-updater`(ZIP + 合并后的 `latest-mac.yml`);Linux deb/rpm 与 Windows 便携版 ZIP 仍为通知并打开发布页。禁止 afterPack/afterSign adhoc 签名(ADR 0278)。** | 正式 DMG 应无需 Gatekeeper 警告即可打开,已签名 macOS 安装可下载并重启到新 tag。见 ADR 0289、E2E-196c、E2E-067A。 || D648 | 混合直接 DNS 结果时固定使用可接受地址 | **修订 ADR 0272:在直连路由上,当 DNS 同时包含被拒绝与可接受的结果时,技能市场会选择并固定到一个可接受地址,而不会让 Chromium 在这些地址中自行选择。第三方内容优先使用公网地址;仅在现有策略允许时使用 `benchmark` 假 IP。仅返回 ULA 或其他非公网地址时仍会拦截。代理与无法读取的路由保持现有策略。见 ADR 0321 与 E2E-SKILL-MARKET-NET-BOUNDARY。** | 双栈与透明代理 DNS 可能在可安全使用的地址旁返回未使用的合成 ULA 地址;固定已通过校验的地址可避免连接到被拒绝结果并消除误拦截。 || D649 | 云备份暂不对外开放 | **修订 D642 / D643:设置中的 `sync` 目的地重新带上 `developmentOnly: true`,因此打包构建会省略其导轨行、页面和设置搜索命中并回落到常规,开发构建则保留该目的地。开发者模式与它无关,它仍不带实验性徽章。同步行为、协议、Host schema 与持久化数据均不变;移除该标记即可对打包构建重新开放。见 `04-ux/06-settings-ia.md` 与 E2E-CONFIG-SYNC-webdav-portable-configuration。** | 加密 WebDAV 备份尚未准备好提供给打包构建用户,因此先保持已实现但不出现在界面上,直到正式开放。 || D650 | 插件提供商出现在添加服务中 | **修订 ADR 0259:`contributes.providers[].category` 是可选分类;`description` 可提供一句简介。已加载且拥有现有 `provider.register` 权限的插件,可向 Host 渲染的添加服务选择器贡献带端点、尚未配置的 API Key 提供商。卡片只显示站名,悬停或键盘聚焦显示一句简介;分类可自定义。每个插件不设服务数量上限。空模型列表仅适用于带端点的 API Key 提供商,用户保存密钥后由 Host 发现并缓存模型。密钥仍通过现有提供商密钥路径保存,已配置的行从选择器隐藏。不提供 OAuth / 无认证行;不新增权限、运行时 API、提供商行或凭据迁移。见 ADR 0322、`07-plugins/02-plugin-manifest-schema.md` 与 E2E-PLUGIN-provider-catalog-add-service。** | 用户无法在常规添加服务流程中发现由清单声明的社区提供商;每个插件也需要自己分组站点,却不应拥有密钥界面。 |-| D450 | 签名的 macOS GitHub Release | **修订 D078 / ADR 0022:GitHub tag 发布使用身份 `Developer ID Application: XingYu Liu (DUV63RKYTW)` / 团队 `DUV63RKYTW`,通过 Actions 密钥(`CSC_LINK`、`CSC_KEY_PASSWORD`、`APPLE_ID`、`APPLE_APP_SPECIFIC_PASSWORD`、`APPLE_TEAM_ID`)对 macOS DMG/ZIP 做 Developer ID 签名、`notarytool` 公证、装订和 Gatekeeper 校验;缺少密钥则失败。无证书的本地未签名打包仍可用。`workflow_dispatch` 仅可把 `sign_macos: false` 用于未签名调试产物。打包的 macOS 走应用内 `electron-updater`(ZIP + 合并后的 `latest-mac.yml`);Linux deb/rpm 与 Windows 便携版 ZIP 仍为通知并打开发布页。禁止 afterPack/afterSign adhoc 签名(ADR 0278)。** | 正式 DMG 应无需 Gatekeeper 警告即可打开,已签名 macOS 安装可下载并重启到新 tag。见 ADR 0289、E2E-196c、E2E-067A。 |+| D651 | 会话标题生成改为独立插件 | **取代 ADR 0186:移除核心的提示词回退标题和内置标题补全;新会话在用户或插件修改前保留本地化默认标题。新增高风险 `session.autoTitle` 能力,用于读取有界首轮上下文并通过比较并设置写入标题,数据由架构 v23 的 `sessions.title_source` 支撑。独立插件可在面板配置提示词模板、模型和思考级别,并使用 `session:turnEnded`、`models.list` 和 `agent.complete`。见 ADR 0323、E2E-021a 及插件 API/权限规格。** | 标题生成是可选产品策略,且支持模型与提示词配置;宿主需要狭窄、持久的边界来保证手动标题在竞态中胜出。 |## B. 辅助实现默认值@@ -385,7 +386,7 @@| D605 | 巴西葡萄牙语应用程序壳 | **修订 D314 / ADR 0160 / ADR 0183 / ADR 0185:提供完整 `pt-BR` 外壳目录,本地名 Português (Brasil),英文名 Portuguese (Brazil)。`pt-BR`、`pt_BR` 和 `pt-*` 解析到巴西葡萄牙语目录;持久化 `AppSettings.language` 接受 `pt-BR`;Electron 打包 `pt-BR` 与 `pt_BR` Chromium locale,并有匹配的巴西葡萄牙语发版日志。不改主机协议或存储 schema。见 ADR 0306。** | 巴西葡萄牙语用户需要独立完整外壳和发版说明语言。 || D350 | 按焦点区分本机通知投递 | **修订 D117 / ADR 0107:渲染器在 `notification/showNative` 终端结果调用中标记 `kind: "task"`,在 asktool、工具权限和 Plan 审批调用中标记 `kind: "interactive"`。缺失或未知值默认为 `task`。任务本机投递仍然仅在未聚焦时进行,包括聚焦的背景会话;交互投递仅在确切的询问会话已在聚焦窗口中可见时抑制,因此聚焦其他会话时可以收到横幅。交互询问从不创建持久任务收件箱行,插件本机通知仍使用独立的权限门控 API。不改变主机协议或存储架构版本。** | PR #84 扩展共享 handler 的门控时,使聚焦的背景终端完成也显示了本机横幅,同时实现了聚焦背景交互询问通知的目标。显式 `kind` 在同一个 Electron 边界隔离这两种用户可见策略。 || D358 | 在进行中重试行显示 provider 原因 | **修订 ADR 0175:`AgentActivity.retrying` 可携带有界、已脱敏的错误详情。紧凑重试行在静止时保持原样;悬停或键盘聚焦揭示本地化摘要、稳定码/状态和 provider 消息。中间重试不会变成转录错误行。见 ADR 0196 与 US-UI-60d。** | 用户需要当前重试原因,又不能复制最终助手错误。 |-| D359 | 用宿主一次性补全总结首轮会话标题 | **首轮提示回退保持同步。`agent_end` 后渲染器调用白名单 `session/summarizeTitle`。Electron 解析会话模型并跑关闭思考的一次性补全;有效结果经 `session.rename` 持久化。自动替换拒绝已持久的 `manualTitle`。见 ADR 0186 与 E2E-021a。** | 截断的首轮提示当侧栏标签很差,但标题生成不能挡住回合或把凭据暴露给渲染器。 |+| D359 | 用宿主一次性补全总结首轮会话标题(已被 D651 取代) | **历史决策:核心曾先应用首条提示回退标题,再在 `agent_end` 后调用 `session/summarizeTitle`。D651 移除了这两条自动标题路径,并把可选生成移到独立插件。** | 截断的首轮提示当侧栏标签很差,但标题生成不能挡住回合或把凭据暴露给渲染器。 || D361 | 内联图片传输使用 10 MB 应用侧上限 | **修订 ADR 0101 / D197:`MAX_INLINE_IMAGE_BYTES` 为 10,000,000。具备视觉能力的模型把不超过该十进制 10 MB 上限的图片作为瞬时 base64 接收;更大的图片和非视觉模型保留 `@path` 回退。Electron main 和 sidecar 共用该常量。不改协议或 schema。** | MiniMax 的 OpenAI 兼容端点单张图上限是 10 MB;更高的应用上限会在 Composer 已经内联字节后被提供商拒绝。 || D316 | 可搜索主题选择器 | **修订 ADR 0160:设置 → 常规的主题是可搜索选择行(与语言相同的锚定菜单),不再是三张预览卡。系统 / 浅色 / 深色钉在顶部;插件主题在分隔线之后。`AppSettings.theme` 与插件主题回退不变。见 ADR 0161 与 E2E-091。** | 插件主题会撑破三列卡片网格,而语言选择器已经解决了可增长列表的控件问题。 || D121 | 品牌macOS开发主机 | **macOS 上的 `pnpm dev` 通过 `.cache/electron-dev/` 下已安装的 Electron 主机包的指纹、临时签名的 PI-Desktop 副本启动 electro-vite。生成的捆绑包仅更改开发主机元数据、可执行文件名称、捆绑包标识符和 ICNS 资源;它永远不会改变 `node_modules`。 Windows/Linux 保持库存开发可执行,而打包通道仍归电子制造商所有。** | AppKit 会忽略顶级应用程序身份的运行时 app-name/menu 覆盖,并从主机包中获取本机菜单名称和“关于”图标;需要品牌开发主机才能与打包的 PI-Desktop 保持一致。 |@@ -3500,12 +3501,18 @@ D193 和 D194。pluginChanged 路径,以及 darwin 存活窗口守卫。见`04-ux/08-component-spec.md` §1.7 与 US-UI-74 / E2E-076。-## 2026-09-08 —— 会话标题摘要与按焦点区分的原生任务通知(D349/D350)+## 2026-09-08 —— 会话标题摘要与按焦点区分的原生任务通知(历史标题决策已被 D651 取代;D350 仍有效)-- 首条提示会立即显示规范化的 48 字符回退标题。首轮完成后,Electron 根据会话的有效提供商/模型运行关闭推理的 `session/summarizeTitle` 单次请求;渲染器通过 `session.rename` 持久化成功结果。-- 渲染器本地会话元数据持久化 `manualTitle`。自动标题会跳过该标记,也会跳过既不是已知默认标题、也不是首条提示回退标题的持久化标题,因此手动标题和已有摘要在重启后不会被覆盖。+- 当时的标题决策是:首条提示立即显示规范化回退标题,首轮完成后由 Electron 运行 `session/summarizeTitle` 并由渲染器保存结果。D651 / ADR 0323 已移除此行为,标题现由可选的独立插件拥有。- 原生任务完成通知和交互式提示共用 Electron IPC 入口,但使用明确的 `kind`。主窗口可见且聚焦时(包括聚焦在后台会话时)抑制任务横幅;交互式提示仍只抑制当前可见会话,因此聚焦的后台请求仍会提醒。持久任务插入仍遵循 D117,插件通知保持独立。-- 见 ADR 0186 / ADR 0187、`03-runtime/01-ipc-protocol.md`、`03-runtime/02-agent-runtime.md`、`04-ux/08-component-spec.md` 与 E2E-021a / E2E-065。+- 见 ADR 0186(标题决策已被 ADR 0323 取代)/ ADR 0187、`03-runtime/01-ipc-protocol.md`、`03-runtime/02-agent-runtime.md`、`04-ux/08-component-spec.md` 与 E2E-021a / E2E-065。++## 2026-10-08 —— 会话标题生成改为独立插件(D651)++- 核心不再根据首条提示生成标题,也不再运行标题补全。新会话会保留本地化默认标题,直到用户或插件修改。+- 获得 `session.autoTitle` 权限的插件只能读取默认标题会话的有界首轮提示与回复,并且只能通过主机 CAS 更新标题。架构 v23 持久记录 `default`、`manual`、`generated` 来源;手动重命名会让插件竞态写入失败。+- 独立 Session Titles 插件从 `session:turnEnded` 触发,可配置提示词模板、模型和思考级别;模型调用使用 `agent.complete`。+- 见 ADR 0323、`03-runtime/02-agent-runtime.md`、`03-runtime/04-data-storage.md`、`07-plugins/03-plugin-api.md`、`07-plugins/13-plugin-permissions-matrix.md` 和 E2E-021a。## 2026-09-08 —— 父级终态错误中止残留委托(D352)diff --git a/packages/agent-runtime/src/index.ts b/packages/agent-runtime/src/index.tsindex 792a88a03..8157deb97 100644--- a/packages/agent-runtime/src/index.ts+++ b/packages/agent-runtime/src/index.ts@@ -18,7 +18,6 @@ export * from "./subagent.js";export { classifySidecarCrash, sidecarCrashErrorCode } from "./sidecar-crash.js";export type { SidecarCrash, SidecarCrashKind } from "./sidecar-crash.js";export * from "./subagent-definitions.js";-export * from "./session-title-summarize.js";export * from "./stream-coalescer.js";export * from "./extensions/index.js";export { startAuthenticatedProxyRelay } from "./authenticated-proxy-relay.js";diff --git a/packages/agent-runtime/src/session-title-summarize.test.ts b/packages/agent-runtime/src/session-title-summarize.test.tsdeleted file mode 100644index 71a75a927..000000000--- a/packages/agent-runtime/src/session-title-summarize.test.ts+++ /dev/null@@ -1,55 +0,0 @@-import { describe, expect, it } from "vitest";-import {- cleanSummarizedTitle,- sessionTitleSummarizeContext,- summarizeSessionTitle,-} from "./session-title-summarize.js";-import type { RuntimeProviderConfig } from "./provider-binding.js";--const provider: RuntimeProviderConfig = {- id: "test-provider",- name: "Test Provider",- baseUrl: "http://localhost:8000",- apiKey: "test-key",- modelId: "test-model",- supportsReasoning: false,- supportedThinkingLevels: [],-};--describe("cleanSummarizedTitle", () => {- it("strips outer quotes, backticks, and markdown brackets", () => {- expect(cleanSummarizedTitle('"Debug WebSocket reconnection"')).toBe("Debug WebSocket reconnection");- expect(cleanSummarizedTitle('“重构用户认证模块”')).toBe("重构用户认证模块");- expect(cleanSummarizedTitle('`Fix typo in README`')).toBe("Fix typo in README");- expect(cleanSummarizedTitle('「优化数据库查询」')).toBe("优化数据库查询");- });-- it("removes redundant Title prefix and trailing punctuation", () => {- expect(cleanSummarizedTitle("Title: Improve search indexing.")).toBe("Improve search indexing");- expect(cleanSummarizedTitle("标题:修复登录失败问题!")).toBe("修复登录失败问题");- expect(cleanSummarizedTitle("Session Title: Add export CSV feature")).toBe("Add export CSV feature");- });-- it("collapses internal whitespace and limits length", () => {- expect(cleanSummarizedTitle(" Refactor theme switching ")).toBe("Refactor theme switching");- const long = "A".repeat(100);- expect(cleanSummarizedTitle(long).length).toBe(80);- });-});--describe("sessionTitleSummarizeContext", () => {- it("formats user prompt and optional reply into context", () => {- const ctx = sessionTitleSummarizeContext("How to configure Nginx reverse proxy?");- expect(ctx.messages[0]?.content).toContain("User Prompt:\nHow to configure Nginx reverse proxy?");- expect(ctx.systemPrompt).toContain("short, concise, descriptive session title");- });-- it("includes assistant response summary when provided", () => {- const ctx = sessionTitleSummarizeContext(- "Deploy Docker container",- "Created docker-compose.yml and started the services.",- );- expect(ctx.messages[0]?.content).toContain("User Prompt:\nDeploy Docker container");- expect(ctx.messages[0]?.content).toContain("Assistant Response Summary:\nCreated docker-compose.yml");- });-});diff --git a/packages/agent-runtime/src/session-title-summarize.ts b/packages/agent-runtime/src/session-title-summarize.tsdeleted file mode 100644index 0b99923ca..000000000--- a/packages/agent-runtime/src/session-title-summarize.ts+++ /dev/null@@ -1,91 +0,0 @@-import type {- Api,- AssistantMessageEventStream,- Context,- Model,- SimpleStreamOptions,-} from "@earendil-works/pi-ai";-import type { ThinkingLevel } from "@pi-desktop/shared";-import { completeOneShot } from "./one-shot-complete.js";-import type { RuntimeProviderConfig } from "./provider-binding.js";--export const SESSION_TITLE_SUMMARIZE_SYSTEM_PROMPT =- "You generate a short, concise, descriptive session title summarizing the conversation based on the user's initial prompt and context.\n" +- "Rules:\n" +- "1. Output ONLY the title text. Do NOT wrap in quotes, brackets, or backticks.\n" +- "2. Do not include markdown formatting, trailing punctuation, or emojis.\n" +- "3. Keep it under 25 characters (or 4-7 words).\n" +- "4. Use the primary language of the user's prompt (e.g. Chinese for Chinese requests, English for English requests).\n" +- "5. Focus on the key topic or action (e.g. \"Debug WebSocket reconnect\", \"重构用户认证模块\").";--export type SessionTitleSummarizeStream = (- model: Model<Api>,- context: Context,- options?: SimpleStreamOptions,-) => AssistantMessageEventStream;--export type SessionTitleSummarizeOptions = {- signal?: AbortSignal;- stream?: SessionTitleSummarizeStream;- sessionId?: string;-};--export function sessionTitleSummarizeContext(- userPrompt: string,- assistantReply?: string,-): Context {- const cleanPrompt = userPrompt.trim().slice(0, 1000);- const cleanReply = assistantReply ? assistantReply.trim().slice(0, 500) : "";- const content = cleanReply- ? `User Prompt:\n${cleanPrompt}\n\nAssistant Response Summary:\n${cleanReply}`- : `User Prompt:\n${cleanPrompt}`;-- return {- systemPrompt: SESSION_TITLE_SUMMARIZE_SYSTEM_PROMPT,- messages: [- {- role: "user",- content,- timestamp: Date.now(),- },- ],- };-}--export function cleanSummarizedTitle(raw: string): string {- let text = raw.trim();- // Remove markdown quotes, code blocks, bold markers- text = text.replace(/^[`"'\u201c\u201d\u300c\u300d]+|[`"'\u201c\u201d\u300c\u300d]+$/g, "").trim();- // Remove possible "Title: " prefix- text = text.replace(/^(Title|Session Title|会话标题|标题)\s*[::]\s*/i, "").trim();- // Collapse whitespace- text = text.replace(/\s+/g, " ");- // Remove trailing period or punctuation- text = text.replace(/[.。!!??]+$/, "").trim();- return text.slice(0, 80);-}--/**- * Run a one-shot completion to generate a smart summary title for a session.- */-export async function summarizeSessionTitle(- provider: RuntimeProviderConfig,- userPrompt: string,- assistantReply?: string,- thinkingLevel: ThinkingLevel = "off",- options: SessionTitleSummarizeOptions = {},-): Promise<string> {- const result = await completeOneShot(- provider,- sessionTitleSummarizeContext(userPrompt, assistantReply),- thinkingLevel,- {- signal: options.signal,- stream: options.stream,- sessionId: options.sessionId,- emptyErrorCode: "TITLE_SUMMARIZATION_EMPTY",- emptyErrorMessage: "The model returned an empty session title.",- },- );- return cleanSummarizedTitle(result.text);-}diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 8ba926af4..979b1f140 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -2242,7 +2242,8 @@ sklm: {"bus.publish": "Nachrichten an andere Plugins senden","bus.subscribe": "Nachrichten von anderen Plugins empfangen","browser.cdp": "Den Arbeitspanel-Browser steuern",- "usage.read": "Nutzungsstatistiken lesen"+ "usage.read": "Nutzungsstatistiken lesen",+ "session.autoTitle": "Kontext des ersten Durchlaufs lesen und automatische Titel ändern"},"permissionHelp": {"ui.panel": "Lässt das Plugin sein eigenes Panel innerhalb der App anzeigen.",@@ -2284,6 +2285,8 @@ sklm: {"browser.cdp": "Kann im Arbeitsbereichsbrowser navigieren, die Seite lesen, JavaScript ausführen und auf der Zulassungsliste stehende Chrome DevTools-Befehle senden. Cookies und Speichermethoden sind blockiert.","usage.read":"Listet Nutzungsdaten abgeschlossener Runden auf (Token-Zähler pro Runde, seitenweise). Nachrichteninhalte sind nicht enthalten.",+ "session.autoTitle":+ "Kann nur die erste Eingabe und Antwort geeigneter Sitzungen lesen und den Titel ändern, sofern er nicht manuell geändert wurde. Das vollständige Transkript bleibt unzugänglich.",}},"extensions": {diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex b0e69c7b6..754085311 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -2267,6 +2267,7 @@ importConfirm: "Imported extensions run inside the agent process with the same a"bus.subscribe": "Receive messages from other plugins","browser.cdp": "Control the work-panel browser","usage.read": "Read usage statistics",+ "session.autoTitle": "Read first-turn title context and update automatic titles",},permissionHelp: {"ui.panel": "Lets the plugin show its own panel inside the app.",@@ -2323,6 +2324,8 @@ importConfirm: "Imported extensions run inside the agent process with the same a"Can navigate the work-panel browser, read the page, run JavaScript, and send allowlisted Chrome DevTools commands. Cookie and storage methods are blocked.","usage.read":"Lists completed-turn usage facts (paginated token counters and session titles). No message content is included.",+ "session.autoTitle":+ "Can read only the first prompt and reply for eligible sessions, then replace an automatic title if it has not been manually changed. It cannot read the full transcript.",},},/**diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex c83168bc4..88a83e12a 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -2242,7 +2242,8 @@ sklm: {"bus.publish": "Enviar mensajes a otros complementos","bus.subscribe": "Recibir mensajes de otros complementos","browser.cdp": "Controlar el navegador del panel de trabajo",- "usage.read": "Leer estadísticas de uso"+ "usage.read": "Leer estadísticas de uso",+ "session.autoTitle": "Leer el contexto del primer turno y actualizar títulos automáticos"},"permissionHelp": {"ui.panel": "Permite que el complemento muestre su propio panel dentro de la aplicación.",@@ -2284,6 +2285,8 @@ sklm: {"browser.cdp": "Puede navegar por el navegador del panel de trabajo, leer la página, ejecutar JavaScript y enviar comandos de Chrome DevTools incluidos en la lista permitida. Las cookies y los métodos de almacenamiento están bloqueados.","usage.read":"Enumera los datos de uso de los turnos completados (contadores de tokens por turno, paginados). No incluye el contenido de los mensajes.",+ "session.autoTitle":+ "Solo puede leer el primer mensaje y la primera respuesta de las sesiones aptas y actualizar el título si nadie lo cambió manualmente. No puede leer la transcripción completa.",}},"extensions": {diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 9df718159..fd36acd9a 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -2242,7 +2242,8 @@ sklm: {"bus.publish": "Envoyer des messages à d'autres plugins","bus.subscribe": "Recevoir des messages d'autres plugins","browser.cdp": "Contrôler le navigateur du panneau de travail",- "usage.read": "Lire les statistiques d'utilisation"+ "usage.read": "Lire les statistiques d'utilisation",+ "session.autoTitle": "Lire le contexte du premier tour et modifier les titres automatiques"},"permissionHelp": {"ui.panel": "Permet au plugin d'afficher son propre panneau dans l'application.",@@ -2284,6 +2285,8 @@ sklm: {"browser.cdp": "Peut naviguer dans le navigateur du panneau de travail, lire la page, exécuter JavaScript et envoyer des commandes Chrome DevTools sur liste autorisée. Les cookies et les méthodes de stockage sont bloqués.","usage.read":"Liste les données d'utilisation des tours terminés (compteurs de tokens par tour, paginés). Aucun contenu de message n'est inclus.",+ "session.autoTitle":+ "Peut lire uniquement le premier message et la première réponse des sessions admissibles, puis modifier le titre s'il n'a pas été changé manuellement. Ne peut pas lire la transcription complète.",}},"extensions": {diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 3f280fa68..423e379d7 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -2259,6 +2259,7 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이"bus.subscribe": "다른 플러그인의 메시지 받기","browser.cdp": "작업 패널 브라우저 제어","usage.read": "사용량 통계 읽기",+ "session.autoTitle": "첫 턴 제목 맥락 읽기 및 자동 제목 업데이트",},permissionHelp: {"ui.panel": "플러그인이 앱 안에 자체 패널을 표시할 수 있습니다.",@@ -2313,6 +2314,8 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이"작업 패널 브라우저를 탐색하고 페이지를 읽으며 JavaScript를 실행하고 허용 목록에 있는 Chrome DevTools 명령을 보낼 수 있습니다. 쿠키 및 저장소 메서드는 차단됩니다.","usage.read":"완료된 턴의 사용량 팩트를 페이지별로 나열합니다(턴당 토큰 카운터). 메시지 내용은 포함되지 않습니다.",+ "session.autoTitle":+ "대상 세션의 첫 요청과 첫 답변만 읽고, 사용자가 직접 바꾸지 않은 경우에만 자동 제목을 업데이트할 수 있습니다. 전체 대화 기록은 읽을 수 없습니다.",},},/**diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 68574537d..97d1d0e3c 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -2193,7 +2193,8 @@ export const ptBR = {"bus.publish": "Enviar mensagens a outros plugins","bus.subscribe": "Receber mensagens de outros plugins","browser.cdp": "Controlar o navegador do painel de trabalho",- "usage.read": "Ler estatísticas de uso"+ "usage.read": "Ler estatísticas de uso",+ "session.autoTitle": "Ler o contexto do primeiro turno e atualizar títulos automáticos"},permissionHelp: {"ui.panel": "Permite que o plugin exiba seu próprio painel no aplicativo.",@@ -2235,6 +2236,7 @@ export const ptBR = {"bus.subscribe": "Pode receber mensagens nos tópicos que declarou.","browser.cdp": "Pode navegar pelo navegador do painel de trabalho, ler páginas, executar JavaScript e enviar comandos permitidos do Chrome DevTools. Métodos de cookies e armazenamento são bloqueados.","usage.read": "Lista dados de uso de rodadas concluídas (contagens paginadas de tokens e títulos de sessões). Nenhum conteúdo das mensagens é incluído.",+ "session.autoTitle": "Pode ler apenas a primeira solicitação e resposta de sessões elegíveis e atualizar o título se ele não tiver sido alterado manualmente. Não pode ler a transcrição completa.",}},extensions: {diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 70754ea18..a5c6d3de4 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -2249,6 +2249,7 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç"bus.subscribe": "Diğer eklentilerden ileti al","browser.cdp": "Çalışma paneli tarayıcısını kontrol et","usage.read": "Kullanım istatistiklerini oku",+ "session.autoTitle": "İlk tur başlık bağlamını oku ve otomatik başlıkları güncelle",},permissionHelp: {"ui.panel": "Eklentinin uygulama içinde kendi panelini göstermesini sağlar.",@@ -2303,6 +2304,8 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç"Çalışma paneli tarayıcısında gezebilir, sayfayı okuyabilir, JavaScript çalıştırabilir ve izin listesindeki Chrome DevTools komutlarını gönderebilir. Çerez ve depolama yöntemleri engellenir.","usage.read":"Tamamlanan turların kullanım verilerini sayfalı olarak listeler (tur başına token sayaçları). Mesaj içeriği dahil değildir.",+ "session.autoTitle":+ "Yalnızca uygun oturumların ilk istemini ve ilk yanıtını okuyabilir; başlık elle değiştirilmemişse otomatik başlığı günceller. Tam dökümü okuyamaz.",},},/**diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 1f31272da..f884bbd93 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -2228,6 +2228,7 @@ sklm: {"bus.subscribe": "接收其他插件的消息","browser.cdp": "控制工作面板浏览器","usage.read": "读取用量统计",+ "session.autoTitle": "读取首轮标题上下文并更新自动标题",},permissionHelp: {"ui.panel": "允许插件在应用内显示独立面板。",@@ -2272,6 +2273,8 @@ sklm: {"可导航工作面板浏览器、读取页面、运行 JavaScript,并发送白名单内的 Chrome DevTools 命令。Cookie 与存储相关方法会被拒绝。","usage.read":"分页列出已完成回合的用量事实(每回合 token 计数与会话标题)。不包含任何消息内容。",+ "session.autoTitle":+ "只能读取符合条件会话的首条提示和首条回复,并仅在标题未被手动修改时更新;不能读取完整会话记录。",},},extensions: {diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 0411b6a75..41b097b8f 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -2228,6 +2228,7 @@ sklm: {"bus.subscribe": "接收其他外掛的訊息","browser.cdp": "控制工作面板瀏覽器","usage.read": "讀取用量統計",+ "session.autoTitle": "讀取首輪標題內容並更新自動標題",},permissionHelp: {"ui.panel": "允許外掛在應用內顯示獨立面板。",@@ -2271,6 +2272,8 @@ sklm: {"可導航工作面板瀏覽器、讀取頁面、執行 JavaScript,併發送白名單內的 Chrome DevTools 命令。Cookie 與儲存相關方法會被拒絕。","usage.read":"分頁列出已完成回合的用量事實(每回合的 token 計數)。不包含任何訊息內容。",+ "session.autoTitle":+ "僅能讀取符合條件工作階段的首則提示和首則回覆,並只在標題未被手動修改時更新;無法讀取完整對話記錄。",},},extensions: {diff --git a/packages/plugin-devkit/src/check.test.ts b/packages/plugin-devkit/src/check.test.tsindex 022aac707..33303ac64 100644--- a/packages/plugin-devkit/src/check.test.ts+++ b/packages/plugin-devkit/src/check.test.ts@@ -141,6 +141,7 @@ describe("check", () => {"agent.tool.register","browser.cdp","audio.capture.background",+ "session.autoTitle",]) {expect(HIGH_RISK_PERMISSIONS).toContain(permission);}@@ -162,11 +163,12 @@ describe("check", () => {const dir = join(await tempDir(), "high-risk-grants");await scaffold({ dir, template: "panel-basic" });await editManifest(dir, (m) => {- m.permissions = [...(m.permissions ?? []), "desktop.control", "session.read"];+ m.permissions = [...(m.permissions ?? []), "desktop.control", "session.read", "session.autoTitle"];});const highRisk = (await check(dir)).warnings.find((w) => w.code === "permission.high-risk");expect(highRisk?.message).toContain("desktop.control");expect(highRisk?.message).toContain("session.read");+ expect(highRisk?.message).toContain("session.autoTitle");});it("warns when background capability permissions are declared but never called", async () => {diff --git a/packages/plugin-devkit/src/check.ts b/packages/plugin-devkit/src/check.tsindex 6eee3691b..3ce105155 100644--- a/packages/plugin-devkit/src/check.ts+++ b/packages/plugin-devkit/src/check.ts@@ -42,6 +42,7 @@ export const HIGH_RISK_PERMISSIONS = ["desktop.control","project.create","session.read",+ "session.autoTitle","session.import","session.delete.own","mcp.server.local",diff --git a/packages/plugin-sdk/src/index.test.ts b/packages/plugin-sdk/src/index.test.tsindex c45e5ed29..6104b4d02 100644--- a/packages/plugin-sdk/src/index.test.ts+++ b/packages/plugin-sdk/src/index.test.ts@@ -638,6 +638,7 @@ describe("PLUGIN_PERMISSIONS", () => {"models.list","project.create","session.read",+ "session.autoTitle","usage.read","fs.read","fs.write",diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.tsindex 231529bfa..9e2c21a69 100644--- a/packages/plugin-sdk/src/index.ts+++ b/packages/plugin-sdk/src/index.ts@@ -303,6 +303,15 @@ export type PluginSessionGetResult = {updatedAt: string;};+/** Bounded first-turn data for an eligible default-titled session, never a full transcript. */+export type PluginAutoTitleContext = {+ sessionId: string;+ expectedTitle: string;+ userPrompt: string;+ assistantReply?: string;+ modelKey?: string;+};+/*** One completed turn as a flat fact row (`usage.read`). The host serves raw* counters — per-turn tokens and identifiers only; no message body ever@@ -1216,6 +1225,12 @@ export type PluginHostApi = {};session: {getLlmContext: () => Promise<PluginLlmContext>;+ getAutoTitleContext: (input: { sessionId: string }) => Promise<PluginAutoTitleContext | null>;+ setAutoTitle: (input: {+ sessionId: string;+ expectedTitle: string;+ title: string;+ }) => Promise<{ updated: boolean }>;list: (input?: {limit?: number;cursor?: string;@@ -1383,6 +1398,7 @@ export const PLUGIN_PERMISSIONS = ["session.read.own","session.update.own","session.delete.own",+ "session.autoTitle",// Read-only usage facts (pi.usage.listTurns):// completed-turn counters and session titles, never message bodies."usage.read",diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 60fda0e7a..f88a33bf6 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -137,7 +137,6 @@ export const IPC = {sessionOpen: "pi-desktop/session/open",sessionDelete: "pi-desktop/session/delete",sessionRename: "pi-desktop/session/rename",- sessionSummarizeTitle: "pi-desktop/session/summarizeTitle",sessionConfigure: "pi-desktop/session/configure",sessionImportScan: "pi-desktop/session/importScan",sessionImportRun: "pi-desktop/session/importRun",diff --git a/packages/shared/src/types/agent.ts b/packages/shared/src/types/agent.tsindex 1bc2ce424..1a4581939 100644--- a/packages/shared/src/types/agent.ts+++ b/packages/shared/src/types/agent.ts@@ -101,19 +101,6 @@ export type PromptEnhancementResponse = {enhancedDraft: string;};-export type SessionSummarizeTitleRequest = {- sessionId: string;- userPrompt: string;- assistantReply?: string;- providerId?: string;- modelId?: string;- thinkingLevel?: ThinkingLevel;-};--export type SessionSummarizeTitleResponse = {- title: string;-};-export type AgentExecuteApprovedPlanRequest = {sessionId: string;turnId: string;diff --git a/scripts/e2e/composer-paste.tsx b/scripts/e2e/composer-paste.tsxindex bf6e678a3..cecde6cd6 100644--- a/scripts/e2e/composer-paste.tsx+++ b/scripts/e2e/composer-paste.tsx@@ -1149,9 +1149,6 @@ globalThis.composerHistoryProbe = async (phase) => {delete next[key];return next;},- promptFallbackSessionTitle: () => "",- untitledTaskTitle: () => "",- isDefaultSessionTitle: () => false,viewingSessionIdForPrompt: () => null,messageErrorFromUnknown: () => { throw new Error("unexpected prompt failure"); },assistantErrorMessage: () => { throw new Error("unexpected prompt failure"); },diff --git a/scripts/e2e/transcript-long-history.tsx b/scripts/e2e/transcript-long-history.tsxindex 84ff5d516..06264c133 100644--- a/scripts/e2e/transcript-long-history.tsx+++ b/scripts/e2e/transcript-long-history.tsx@@ -107,8 +107,7 @@ export async function transcriptLongHistoryProbe() {const originalDateNow = Date.now;const wallTime = Date.now();const originals = { getSession: api.getSession, listSessions: api.listSessions,- pendingPlans: api.pendingPlans, listQueuedPrompts: api.listQueuedPrompts, composerCommands: api.composerCommands,- summarizeSessionTitle: api.summarizeSessionTitle };+ pendingPlans: api.pendingPlans, listQueuedPrompts: api.listQueuedPrompts, composerCommands: api.composerCommands };const clipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard");const sessions = [history(100), history(1000), history(10784)];const records = new Map(sessions.map((item) => [item.summary.id, item]));@@ -177,11 +176,6 @@ export async function transcriptLongHistoryProbe() {api.pendingPlans = async () => ({ plans: [], state: "inactive" });api.listQueuedPrompts = async () => ({ entries: [] });api.composerCommands = async () => ({ commands: [] });- api.summarizeSessionTitle = async () => {- const error = new Error("Unexpected auto-title provider request in synthetic fixture");- errors.push(error);- throw error;- };Object.defineProperty(navigator, "clipboard", { configurable: true,value: { writeText: async (text: string) => { copied.push(text); } } });useAppStore.setState({diff --git a/scripts/e2e/transcript-minimap-jump.tsx b/scripts/e2e/transcript-minimap-jump.tsxindex c02e5f20d..2a0bff3e1 100644--- a/scripts/e2e/transcript-minimap-jump.tsx+++ b/scripts/e2e/transcript-minimap-jump.tsx@@ -92,7 +92,6 @@ export async function transcriptMinimapJumpProbe() {pendingPlans: api.pendingPlans,listQueuedPrompts: api.listQueuedPrompts,composerCommands: api.composerCommands,- summarizeSessionTitle: api.summarizeSessionTitle,};const messages = transcriptMessages();const errors: unknown[] = [];@@ -124,9 +123,6 @@ export async function transcriptMinimapJumpProbe() {api.pendingPlans = async () => ({ plans: [], state: "inactive" });api.listQueuedPrompts = async () => ({ entries: [] });api.composerCommands = async () => ({ commands: [] });- api.summarizeSessionTitle = async () => {- throw new Error("unexpected auto-title provider request in fixture");- };useAppStore.setState({sessions: [sessionSummary()],providers: [],diff --git a/scripts/e2e/transcript-render.tsx b/scripts/e2e/transcript-render.tsxindex da4f29a75..272c69739 100644--- a/scripts/e2e/transcript-render.tsx+++ b/scripts/e2e/transcript-render.tsx@@ -188,7 +188,6 @@ globalThis.resetContextOverflowRecoveryProbe = async () => {sessionModeForPlanningState: () => "agent",openPlanArtifact: () => undefined,notifyInteractivePrompt: () => undefined,- triggerAutoTitleSummarization: async () => undefined,flushPendingSessionConfiguration: async () => undefined,assistantErrorMessage: (error) =>assistantErrorMessage({