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(subagents): make the shipped builtins switchable from Settings
vastsa404c6590aac0
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 35d3ea34c..41cc3aa4b 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -725,6 +725,7 @@ const {refreshUserMcp,activeUserSkills,activeUserSubagentDocuments,+ disabledBuiltinSubagents,loadUserSkillBody,resolveEffectiveCommandShell,resolveAgentRuntimeLaunch,@@ -1322,6 +1323,7 @@ function registerIpc() {refreshUserMcp,describeError,activeUserSubagentDocuments,+ disabledBuiltinSubagents,pluginViews,pluginSettingsViews,pluginScopes,diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.tsindex 14d4345b0..b5ddbba20 100644--- a/apps/desktop/electron/main/ipc/register.ts+++ b/apps/desktop/electron/main/ipc/register.ts@@ -35,6 +35,7 @@ export type RegisterIpcDependencies = {getNotificationViewingSessionId: () => string | null;setNotificationViewingSessionId: (sessionId: string | null) => void;activeUserSubagentDocuments: (...args: any[]) => Promise<any>;+ disabledBuiltinSubagents: () => Promise<string[]>;[name: string]: any;};@@ -91,6 +92,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {agentExtensions,activeUserSkills,activeUserSubagentDocuments,+ disabledBuiltinSubagents,pluginActiveInProject,getWorkPanelReservationWidth,setWorkPanelReservationWidth,@@ -359,6 +361,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {fetchSkillMarketDocument,optionalWorkspaceRoot,activeUserSubagentDocuments,+ disabledBuiltinSubagents,stripWinLongPrefix,sendToRenderer,logger,diff --git a/apps/desktop/electron/main/ipc/skills-ipc.ts b/apps/desktop/electron/main/ipc/skills-ipc.tsindex a863ea28b..fc60a2409 100644--- a/apps/desktop/electron/main/ipc/skills-ipc.ts+++ b/apps/desktop/electron/main/ipc/skills-ipc.ts@@ -17,6 +17,8 @@ export type SkillsIpcDependencies = {getHost: () => HostProcess | null;optionalWorkspaceRoot: () => Promise<string | null>;activeUserSubagentDocuments: (projectPath: string | undefined) => Promise<UserSubagentDocument[]>;+ /** Handles whose shipped definition the user turned off (builtin activation). */+ disabledBuiltinSubagents: () => Promise<string[]>;stripWinLongPrefix: (path: string) => string;sendToRenderer: (channel: string, payload?: unknown) => void;searchSkillMarket: (query: string, sources: { id: string; name: string; url: string }[]) => Promise<SkillMarketSearchResult>;@@ -30,6 +32,7 @@ export function registerSkillsIpc({getHost,optionalWorkspaceRoot,activeUserSubagentDocuments,+ disabledBuiltinSubagents,stripWinLongPrefix,sendToRenderer,searchSkillMarket,@@ -232,16 +235,33 @@ export function registerSkillsIpc({/*** The effective catalog: what `Task` would actually offer right now, merged- * across builtin, registry and project documents. The renderer needs this to- * show read-only rows and to name the definition that wins each handle.+ * across builtin and registry documents. The renderer needs this to list the+ * shipped defaults and to name the definition that wins each handle.+ *+ * `builtins` carries a switched-off builtin too, with `enabled: false`, so the+ * page can keep its row and let the user turn it back on; `subagents` is the+ * delegation catalog and never lists one.*/handle(IPC.invoke.subagentCatalog, async () => {const projectPath = (await optionalWorkspaceRoot()) ?? undefined;- const { definitions, diagnostics } = await loadSubagentDefinitions(+ const disabled = await disabledBuiltinSubagents();+ const { definitions, builtins, diagnostics } = await loadSubagentDefinitions(projectPath,- { userDocuments: await activeUserSubagentDocuments(projectPath) },+ {+ userDocuments: await activeUserSubagentDocuments(projectPath),+ disabledBuiltins: disabled,+ },);- return { subagents: definitions, diagnostics, projectPath: projectPath ?? null };+ const off = new Set(disabled);+ return {+ subagents: definitions,+ builtins: builtins.map((definition) => ({+ ...definition,+ enabled: !off.has(definition.name),+ })),+ diagnostics,+ projectPath: projectPath ?? null,+ };});handle(IPC.invoke.subagentCreate, async (subagent: Record<string, unknown>) => {@@ -284,6 +304,21 @@ export function registerSkillsIpc({},);+ /**+ * Turn one shipped default off, or back on. The row owns no document:+ * host-core keeps the handle in app-local state, and the exclusion lands on+ * the next catalog load — this prompt's catalog if it has not launched yet.+ */+ handle(+ IPC.invoke.subagentSetBuiltinEnabled,+ async (payload: { id: string; enabled: boolean }) => {+ if (!host) throw new Error("host unavailable");+ const res = await host.call("agents.setBuiltinEnabled", payload);+ sendToRenderer(IPC.event.pluginChanged, { reason: "subagent" });+ return res;+ },+ );+handle(IPC.invoke.subagentSetScope,async (payload: { id: string; scope: ActivationScope }) => {diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.tsindex 636339ebf..d4c43986c 100644--- a/apps/desktop/electron/main/runtime/session-launch.ts+++ b/apps/desktop/electron/main/runtime/session-launch.ts@@ -186,6 +186,31 @@ export function createSessionLaunchRuntime({return documents;}+ /**+ * Handles whose shipped definition the user turned off (D202 activation for+ * builtins, which are constants and so have no document to scan).+ *+ * host-core owns the state. An unavailable host, or a failed read, contributes+ * no exclusions: losing a delegate the user kept is worse than offering one+ * they switched off.+ */+ async function disabledBuiltinSubagents(): Promise<string[]> {+ if (!runtimeState.host?.isAvailable()) return [];+ try {+ const result = await runtimeState.host!.call<{ disabled: string[] }>(+ "agents.disabledBuiltins",+ );+ return result.disabled ?? [];+ } catch (error) {+ if (!isHostUnavailable(error)) {+ logger.app("plugin", "warn", "builtin subagent state failed", {+ data: String(error),+ });+ }+ return [];+ }+ }+/*** Load one of the user's own skill documents by id, or `null` if there is no* such skill — so the caller can fall through to the plugin catalog.@@ -429,6 +454,8 @@ export function createSessionLaunchRuntime({// skills above; a delegate the model can see is one it will try to call.const subagentCatalog = await loadSubagentDefinitions(projectPath, {userDocuments: await activeUserSubagentDocuments(projectPath),+ // A switched-off builtin is dropped from what this prompt may delegate to.+ disabledBuiltins: await disabledBuiltinSubagents(),});const subagentBindings = await resolveSubagentProviders({definitions: subagentCatalog.definitions,@@ -646,6 +673,7 @@ export function createSessionLaunchRuntime({refreshUserMcp,activeUserSkills,activeUserSubagentDocuments,+ disabledBuiltinSubagents,loadUserSkillBody,resolveEffectiveCommandShell,resolveAgentRuntimeLaunch,diff --git a/apps/desktop/src/capture/capture-rig.ts b/apps/desktop/src/capture/capture-rig.tsindex bcb88fc93..9e4b2a926 100644--- a/apps/desktop/src/capture/capture-rig.ts+++ b/apps/desktop/src/capture/capture-rig.ts@@ -895,6 +895,12 @@ export function installCaptureRig(): CaptureRig {source: "builtin",},];++ // The shipped defaults the page lists separately, one of them switched+ // off, so a capture exercises the switch on a built-in row.+ const builtinRows = catalog+ .filter((item) => item.source === "builtin")+ .map((item, index) => ({ ...item, enabled: index !== 0 }));const rowsForQuery = <T extends { level?: string; projectPath?: string }>(rows: readonly T[],query: { level?: string; projectPath?: string } = {},@@ -918,6 +924,7 @@ export function installCaptureRig(): CaptureRig {(api as any).listUserSubagents = async () => ({ subagents });(api as any).subagentCatalog = async () => ({subagents: catalog,+ builtins: builtinRows,diagnostics: [],projectPath: "/Users/pi/work/api",});diff --git a/apps/desktop/src/components/settings/AgentSubagentsPage.tsx b/apps/desktop/src/components/settings/AgentSubagentsPage.tsxindex b8415b54b..721467853 100644--- a/apps/desktop/src/components/settings/AgentSubagentsPage.tsx+++ b/apps/desktop/src/components/settings/AgentSubagentsPage.tsx@@ -27,7 +27,11 @@ import {subagentPresetCopyKey,type SubagentDraft,} from "./SubagentEditorSheet";-import { EMPTY_SUBAGENT_PAGE, fetchSubagentPageData } from "./subagent-settings";+import {+ EMPTY_SUBAGENT_PAGE,+ fetchSubagentPageData,+ type BuiltinSubagentRow,+} from "./subagent-settings";import {IconBot,IconCopy,@@ -109,6 +113,43 @@ export function AgentSubagentsPage() {}};+ /**+ * A builtin has no document to switch, so its handle is stored in app-local+ * state instead — but it is the same switch: flip locally first, call the+ * host, and revert the row only if the host refuses.+ */+ const toggleBuiltin = async (builtin: BuiltinSubagentRow) => {+ const handle = builtin.name;+ if (busyId === `builtin:${handle}`) return;+ const next = !builtin.enabled;+ setBusyId(`builtin:${handle}`);+ setSubagents((current) => ({+ ...current,+ builtins: current.builtins.map((row) =>+ row.name === handle ? { ...row, enabled: next } : row,+ ),+ }));+ try {+ await api.setBuiltinSubagentEnabled(handle, next);+ showToast(+ t(next ? "settings.capabilityEnabled" : "settings.capabilityDisabled", {+ name: builtinDisplayName(handle, t),+ }),+ { variant: "success" },+ );+ } catch (error) {+ setSubagents((current) => ({+ ...current,+ builtins: current.builtins.map((row) =>+ row.name === handle ? { ...row, enabled: builtin.enabled } : row,+ ),+ }));+ showToast(error instanceof Error ? error.message : String(error), { variant: "error" });+ } finally {+ setBusyId(null);+ }+ };+const openEdit = async (subagent: UserSubagentRecord) => {setBusyId(subagent.id);try {@@ -218,15 +259,17 @@ export function AgentSubagentsPage() {const noMatches = searching && visibleOwned.length === 0 && visibleBuiltins.length === 0;const showOwnedGroup = !searching || visibleOwned.length > 0;- const renderBuiltin = (definition: SubagentDefinition) => {+ const renderBuiltin = (definition: BuiltinSubagentRow) => {const handle = definition.name;const name = builtinDisplayName(handle, t);const canCopy = !ownedHandles.has(handle);+ const busy = busyId === `builtin:${handle}`;return (<CapabilityRowkey={`builtin:${handle}`}glyph={<IconBot size={16} />}name={name}+ off={!definition.enabled}command={t("extensions.subagents.handle", { name: handle })}badges={<span className="agent-capability-badge">{t("extensions.subagents.sourceBuiltin")}</span>@@ -242,16 +285,24 @@ export function AgentSubagentsPage() {) : undefined}actions={- canCopy ? (- <TooltipButton- type="button"- className="settings-icon-button"- tooltip={t("extensions.subagents.copy")}- onClick={() => copyBuiltin(definition)}- >- <IconCopy size={15} />- </TooltipButton>- ) : null+ <>+ {canCopy ? (+ <TooltipButton+ type="button"+ className="settings-icon-button"+ tooltip={t("extensions.subagents.copy")}+ onClick={() => copyBuiltin(definition)}+ >+ <IconCopy size={15} />+ </TooltipButton>+ ) : null}+ <CapabilityToggle+ checked={definition.enabled}+ busy={busy}+ label={t("settings.toggleCapability", { name })}+ onChange={() => void toggleBuiltin(definition)}+ />+ </>}/>);diff --git a/apps/desktop/src/components/settings/subagent-settings.ts b/apps/desktop/src/components/settings/subagent-settings.tsindex 973bc2659..649a2d0f5 100644--- a/apps/desktop/src/components/settings/subagent-settings.ts+++ b/apps/desktop/src/components/settings/subagent-settings.ts@@ -5,10 +5,18 @@ import {} from "@pi-desktop/shared";import { api } from "../../lib/api";-/** User-owned documents plus the builtins currently winning in the Task catalog. */+/**+ * One shipped default plus whether this installation still offers it.+ *+ * A switched-off builtin stays in the list on purpose: it has no document to+ * delete, so its row and its switch are the only way back on.+ */+export type BuiltinSubagentRow = SubagentDefinition & { enabled: boolean };++/** User-owned documents plus the shipped defaults, switched off ones included. */export type SubagentPageData = {owned: UserSubagentRecord[];- builtins: SubagentDefinition[];+ builtins: BuiltinSubagentRow[];};export const EMPTY_SUBAGENT_PAGE: SubagentPageData = {@@ -18,8 +26,9 @@ export const EMPTY_SUBAGENT_PAGE: SubagentPageData = {/*** Settings lists two sources: the writable global registry, and the shipped- * defaults that `Task` would actually offer. Catalog load failures must not- * hide the user list, so builtins fall back to the shared preset catalog.+ * defaults `Task` offers. Catalog load failures must not hide the user list, so+ * builtins fall back to the shared preset catalog — reported enabled, because a+ * failed read cannot say which handles the user turned off.*/export async function fetchSubagentPageData(): Promise<SubagentPageData> {const ownedResult = await api.listUserSubagents({ level: "global" });@@ -27,16 +36,26 @@ export async function fetchSubagentPageData(): Promise<SubagentPageData> {const enabledHandles = new Set(owned.filter((row) => row.enabled).map((row) => row.id));try {const catalog = await api.subagentCatalog();+ // Older main processes answer without `builtins`; derive the group from the+ // effective catalog then, which is how this page read it before builtins+ // could be switched off at all.+ const builtins =+ catalog.builtins ??+ (catalog.subagents ?? [])+ .filter((item) => item.source === "builtin")+ .map((item) => ({ ...item, enabled: true }));return {owned,- builtins: (catalog.subagents ?? []).filter(+ builtins: builtins.filter((item) => item.source === "builtin" && !enabledHandles.has(item.name),),};} catch {return {owned,- builtins: fallbackBuiltinDefinitions().filter((item) => !enabledHandles.has(item.name)),+ builtins: fallbackBuiltinDefinitions()+ .map((item) => ({ ...item, enabled: true }))+ .filter((item) => !enabledHandles.has(item.name)),};}}diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex 7168ac056..ddfac9746 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -785,10 +785,15 @@ export const api = {// --- Subagents the user owns ----------------------------------------------listUserSubagents: (query?: Pick<AgentCapabilityQuery, "level">) =>invoke<{ subagents: UserSubagentRecord[] }>(IPC.invoke.subagentList, query),- /** What `Task` would offer right now, merged across all three sources. */+ /**+ * What `Task` would offer right now, merged across the shipped builtins and+ * the registry. `builtins` keeps a switched-off default in the list, flagged+ * `enabled: false`, so Settings can still show that row and its switch.+ */subagentCatalog: () =>invoke<{subagents: SubagentDefinition[];+ builtins: Array<SubagentDefinition & { enabled: boolean }>;diagnostics: string[];projectPath: string | null;}>(IPC.invoke.subagentCatalog),@@ -808,6 +813,15 @@ export const api = {removeUserSubagent: (id: string) => invoke(IPC.invoke.subagentRemove, id),setUserSubagentEnabled: (id: string, enabled: boolean) =>invoke(IPC.invoke.subagentSetEnabled, { id, enabled }),+ /**+ * Turn one shipped default off, or back on. The id is the `Task` handle+ * (`explorer`), never a document id: a builtin has no file to switch.+ */+ setBuiltinSubagentEnabled: (id: string, enabled: boolean) =>+ invoke<{ id: string; enabled: boolean }>(IPC.invoke.subagentSetBuiltinEnabled, {+ id,+ enabled,+ }),setUserSubagentScope: (id: string, scope: ActivationScope) =>invoke(IPC.invoke.subagentSetScope, { id, scope }),/** Registry entries reveal by id; project documents pass their own path. */diff --git a/apps/desktop/test/agent-capability-settings.test.mjs b/apps/desktop/test/agent-capability-settings.test.mjsindex 8921d53a7..98952271a 100644--- a/apps/desktop/test/agent-capability-settings.test.mjs+++ b/apps/desktop/test/agent-capability-settings.test.mjs@@ -327,25 +327,45 @@ test("all capability paths are agents roots, not legacy capability directories",}});-test("Settings lists shipped builtin subagents as read-only rows", () => {+test("Settings lists shipped builtin subagents with a switch of their own", () => {+ const api = read("../src/lib/api.ts");assert.match(subagentSettings, /api\.subagentCatalog/);assert.match(subagentSettings, /item\.source === "builtin"/);assert.match(subagentSettings, /fallbackBuiltinDefinitions/);assert.match(subagentSettings, /owned\.filter\(\(row\) => row\.enabled\)/);+ assert.match(subagentSettings, /catalog\.builtins/);assert.match(subagents, /extensions\.subagents\.sourceBuiltin/);assert.match(subagents, /extensions\.subagents\.copy/);assert.match(subagents, /draftFromDefinition/);assert.match(subagents, /copyBuiltin/);assert.match(subagents, /presetId: definition\.name/);assert.match(subagents, /initialPresetId=\{editor\.presetId\}/);- // Builtins are not files: no enablement switch, reveal, or delete on those rows.+ // A builtin row keeps its badge and Copy as mine, gains the switch, and still+ // has no Reveal or Delete: there is no file behind it.const builtinRow = subagents.slice(subagents.indexOf("const renderBuiltin"),subagents.indexOf("const renderRow"),);assert.notEqual(builtinRow, "", "builtin row renderer should be present");- assert.doesNotMatch(builtinRow, /CapabilityToggle|setUserSubagentEnabled|revealSubagent|removeUserSubagent/);assert.match(builtinRow, /IconCopy/);+ assert.match(builtinRow, /<CapabilityToggle/);+ assert.match(builtinRow, /checked=\{definition\.enabled\}/);+ assert.doesNotMatch(+ builtinRow,+ /setUserSubagentEnabled|revealSubagent|removeUserSubagent/,+ );+ // The switch writes builtin activation, flipping locally first like the rows+ // that own a document do.+ const toggle = subagents.slice(+ subagents.indexOf("const toggleBuiltin = async"),+ subagents.indexOf("const openEdit = async"),+ );+ assert.notEqual(toggle, "", "builtin toggle should be present");+ assert.match(toggle, /api\.setBuiltinSubagentEnabled\(handle, next\)/);+ assert.match(toggle, /enabled: next/);+ assert.doesNotMatch(toggle.slice(0, toggle.indexOf("catch")), /await load\(\)/);+ assert.match(toggle, /catch[\s\S]*?enabled: builtin\.enabled/);+ assert.match(api, /setBuiltinSubagentEnabled: \(id: string, enabled: boolean\) =>/);});test("a capability can be moved between the global and a project level", () => {diff --git a/apps/desktop/test/subagent-wiring.test.mjs b/apps/desktop/test/subagent-wiring.test.mjsindex 721d0a5ea..b575b7fb1 100644--- a/apps/desktop/test/subagent-wiring.test.mjs+++ b/apps/desktop/test/subagent-wiring.test.mjs@@ -114,6 +114,7 @@ test("a dead host transport degrades quietly instead of warning", () => {"refreshUserMcp","activeUserSkills","activeUserSubagentDocuments",+ "disabledBuiltinSubagents",]) {const start = sessionLaunchSource.indexOf(`async function ${fn}(`);assert.notEqual(start, -1, fn);@@ -150,3 +151,18 @@ test("the subagents page recovers when the host comes back", () => {// cleanup rather than a single unsubscribe.assert.match(hostCollectionSource, /offPluginChanged\(\);\n\s+offHostStatus\(\);/);});++test("a switched-off builtin leaves the delegation catalog, not the page", () => {+ // host-core owns the handle; every launch re-reads it, so the switch takes+ // effect on the next prompt and the catalog keeps the row for Settings.+ assert.match(sessionLaunchSource, /"agents\.disabledBuiltins"/);+ assert.match(+ sessionLaunchSource,+ /disabledBuiltins: await disabledBuiltinSubagents\(\),/,+ );+ assert.match(+ sessionLaunchSource,+ /async function disabledBuiltinSubagents\(\): Promise<string\[\]>/,+ );+ assert.match(pageSource, /api\.setBuiltinSubagentEnabled\(handle, next\)/);+});diff --git a/crates/host-core/src/agent_capabilities.rs b/crates/host-core/src/agent_capabilities.rsindex 163564540..ace7f505a 100644--- a/crates/host-core/src/agent_capabilities.rs+++ b/crates/host-core/src/agent_capabilities.rs@@ -145,6 +145,28 @@ impl CapabilityState {self.save()}+ /// Every id of `kind` at `level` whose stored value is an explicit `false`.+ ///+ /// Global records default on, so the state file holds only what a user+ /// turned off. A caller that owns a catalog of records with no document to+ /// scan — the shipped subagent builtins — needs exactly these ids, because+ /// the directory scan that prunes state for deleted files can never see+ /// them. Ids come back sorted so a result never depends on insertion order.+ pub fn disabled_ids(&self, kind: &str, level: CapabilityLevel) -> Vec<String> {+ let mut ids: Vec<String> = self+ .values+ .iter()+ .filter(|(_, enabled)| !**enabled)+ .filter_map(|(raw_key, _)| serde_json::from_str::<StateKey>(raw_key).ok())+ .filter(|key| {+ key.kind == kind && key.level == level.as_str() && key.project_path.is_none()+ })+ .map(|key| key.id)+ .collect();+ ids.sort();+ ids+ }+/// Remove state for records that disappeared from the selected directory./// Other project selections remain untouched because they may still exist.pub fn prune(diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 4e39e2b52..56e20fe14 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -4280,6 +4280,23 @@ async fn handle_request(.map_err(subagent_err)?;Ok(json!({ "subagent": subagent }))}+ "agents.disabledBuiltins" => {+ let st = state.lock().await;+ Ok(json!({ "disabled": st.user_subagents.disabled_builtins() }))+ }+ "agents.setBuiltinEnabled" => {+ let id = require_id(¶ms)?;+ let enabled = params+ .get("enabled")+ .and_then(Value::as_bool)+ .unwrap_or(false);+ let mut st = state.lock().await;+ let id = st+ .user_subagents+ .set_builtin_enabled(&id, enabled)+ .map_err(subagent_err)?;+ Ok(json!({ "id": id, "enabled": enabled }))+ }"market.refresh" => {let force = paramsdiff --git a/crates/host-core/src/user_subagents.rs b/crates/host-core/src/user_subagents.rsindex 298172859..7faeed3a5 100644--- a/crates/host-core/src/user_subagents.rs+++ b/crates/host-core/src/user_subagents.rs@@ -33,6 +33,18 @@ const THINKING_LEVELS: [&str; 8] = ["off", "minimal", "low", "medium", "high", "xhigh", "max", "omit",];const SUBAGENT_KIND: &str = "subagents";+/// Activation state for the subagent builtins, kept in its own file+/// (`<data-dir>/agent-capabilities/subagent-builtins.json`).+///+/// The builtins are constant documents inside agent-runtime, not files in+/// `~/.agents/subagents`, so the directory scan that `list()` performs can+/// never see their handles. That scan also `prune`s state for records it no+/// longer finds, which would delete every builtin entry as an orphan on the+/// first listing. A separate kind keeps the two catalogs apart, and because a+/// `Global` value is only ever stored for an explicit `false`, the state is+/// lazy and sticky: a handle that is off stays off even while it is absent, so+/// a builtin restored in a later release comes back still disabled.+const SUBAGENT_BUILTIN_KIND: &str = "subagent-builtins";#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]#[serde(rename_all = "camelCase")]@@ -82,6 +94,7 @@ pub struct UserSubagentInput {pub struct UserSubagentRegistry {state: CapabilityState,+ builtins: CapabilityState,}fn normalize_name(value: &str) -> String {@@ -256,6 +269,7 @@ impl UserSubagentRegistry {pub fn new(data_dir: &Path) -> Self {Self {state: CapabilityState::new(data_dir, SUBAGENT_KIND),+ builtins: CapabilityState::new(data_dir, SUBAGENT_BUILTIN_KIND),}}@@ -498,6 +512,37 @@ impl UserSubagentRegistry {let _ = scope;self.find(id)}++ /// Handles the user turned off among the shipped subagent builtins.+ ///+ /// Read straight from the state file: the builtins have no document to+ /// scan, and the answer must not depend on which of them the running+ /// build happens to define.+ pub fn disabled_builtins(&self) -> Vec<String> {+ self.builtins+ .disabled_ids(SUBAGENT_BUILTIN_KIND, CapabilityLevel::Global)+ }++ /// Turn one builtin handle on or off, returning the normalized handle.+ ///+ /// The handle is normalized exactly like a document id, so the same+ /// spelling reaches the runtime catalog. Nothing is validated against a+ /// current builtin list on purpose: the state is sticky for handles a+ /// later build may reintroduce.+ pub fn set_builtin_enabled(&mut self, handle: &str, enabled: bool) -> Result<String> {+ let name = normalize_name(handle);+ if name.is_empty() {+ bail!("SUBAGENT_INVALID: a builtin handle is required");+ }+ self.builtins.set_enabled(+ SUBAGENT_BUILTIN_KIND,+ CapabilityLevel::Global,+ &name,+ None,+ enabled,+ )?;+ Ok(name)+ }}#[cfg(test)]@@ -692,4 +737,76 @@ mod tests {assert!(normalize_model(Some("/claude-haiku-4-5")).is_err());assert!(normalize_model(Some("anthropic/")).is_err());}++ #[test]+ fn builtins_are_enabled_until_one_is_turned_off() {+ let dir = tempdir().unwrap();+ let mut registry = UserSubagentRegistry::new(dir.path());+ assert!(registry.disabled_builtins().is_empty());++ let handle = registry.set_builtin_enabled("Fixer", false).unwrap();+ assert_eq!(handle, "fixer");+ assert_eq!(registry.disabled_builtins(), vec!["fixer".to_string()]);++ registry.set_builtin_enabled("fixer", true).unwrap();+ assert!(registry.disabled_builtins().is_empty());+ }++ #[test]+ fn builtin_state_survives_a_registry_rebuild() {+ let dir = tempdir().unwrap();+ let mut registry = UserSubagentRegistry::new(dir.path());+ registry.set_builtin_enabled("fixer", false).unwrap();+ registry+ .set_builtin_enabled("code-reviewer", false)+ .unwrap();++ let reopened = UserSubagentRegistry::new(dir.path());+ // Sorted, so the answer never depends on insertion order.+ assert_eq!(+ reopened.disabled_builtins(),+ vec!["code-reviewer".to_string(), "fixer".to_string()]+ );+ }++ #[test]+ fn a_blank_builtin_handle_is_rejected() {+ let dir = tempdir().unwrap();+ let mut registry = UserSubagentRegistry::new(dir.path());+ let error = registry.set_builtin_enabled(" ", false).unwrap_err();+ assert!(error.to_string().contains("SUBAGENT_INVALID"));+ assert!(registry.disabled_builtins().is_empty());+ }++ #[test]+ fn listing_documents_does_not_prune_builtin_state() {+ // The scan prunes state for ids it did not find. A builtin has no+ // document at all, so the two kinds must never share one state file or+ // the first `list()` would delete every builtin the user turned off.+ use crate::agent_capabilities::test_support;++ let dir = tempdir().unwrap();+ let agents = tempdir().unwrap();+ let mut registry = UserSubagentRegistry::new(dir.path());+ registry.set_builtin_enabled("fixer", false).unwrap();++ test_support::with_global_agents(agents.path(), || {+ registry.list().unwrap();+ });+ assert_eq!(registry.disabled_builtins(), vec!["fixer".to_string()]);++ // And a rebuilt registry still agrees after the listing.+ let mut reopened = UserSubagentRegistry::new(dir.path());+ test_support::with_global_agents(agents.path(), || {+ reopened.list().unwrap();+ });+ assert_eq!(reopened.disabled_builtins(), vec!["fixer".to_string()]);++ // The document kind keeps its own file, so the builtin entry is not+ // mistaken for a user subagent either.+ assert!(dir+ .path()+ .join("agent-capabilities/subagent-builtins.json")+ .exists());+ }}diff --git a/docs/adr/0270-builtin-subagents-can-be-disabled.md b/docs/adr/0270-builtin-subagents-can-be-disabled.mdnew file mode 100644index 000000000..f14fd4f6d--- /dev/null+++ b/docs/adr/0270-builtin-subagents-can-be-disabled.md@@ -0,0 +1,69 @@+# ADR 0270: Builtin Subagents Can Be Switched Off++- Status: Accepted+- Date: 2026-09-17+- Related: D202, ADR 0062, ADR 0063, ADR 0112, ADR 0126++## Context++Settings > Agent > Subagents lists two groups: the five shipped builtins+(`explorer`, `code-reviewer`, `test-runner`, `fixer`, `ui-designer`) and the+user's own `~/.agents/subagents/*.md` documents. Only the user group had an+enablement switch, because only those records are files: the builtins are+constants in `packages/agent-runtime`, and ADR 0063 §2 tied activation to the+document scan that prunes state for deleted files.++That left one delegate the user could not turn off. The only route was to copy a+builtin into `~/.agents/subagents`, disable the copy — and the shipped definition+still reached the catalog, because disabled user documents are filtered out+before the loader merges, so the copy shadowed nothing. Turning off a delegate+the instructions steer toward (a `fixer` that may write files, a `test-runner`+that may run commands) had no supported path at all.++## Decision++1. **Activation for a handle with no document lives in its own app-local file.**+ host-core stores switched-off builtin handles in+ `<data>/agent-capabilities/subagent-builtins.json`, keyed by `Task` handle at+ the global level. It is deliberately not `subagents.json`: the user-document+ scan prunes state for ids it can no longer see, a builtin is never scanned, so+ a shared file would drop every builtin exclusion on the next scan.+2. **Two RPCs own that state.** `agents.disabledBuiltins` reads the switched-off+ handles (sorted), `agents.setBuiltinEnabled(id, enabled)` writes one and+ echoes the normalized handle. A handle no current builtin uses is stored+ inertly rather than refused: host-core does not ship the builtin list, and a+ stale entry costs nothing.+3. **The catalog carries the switch, not the document.** Electron main supplies+ the disabled handles to `loadSubagentDefinitions`, which drops them from+ `definitions` — what `Task` may offer — and returns every builtin that still+ wins its handle in a sibling `builtins` field, switched off ones included, so+ Settings can render that row and its switch. `subagent/catalog` answers with+ both lists.+4. **Switching a builtin off is not deleting it.** A user document of the same+ handle keeps working and keeps shadowing the shipped definition, and turning+ the builtin back on needs no document, because nothing was removed.++## Consequences++- The Built-in group gains the switch the user rows already have, in the same+ place and with the same optimistic flip. Reveal and delete stay absent: there+ is still no file.+- A switched-off builtin stays listed and dimmed, which is the only way back on.+- Session launch and the Settings catalog read the same state, so the page shows+ what `Task` offers — the property E2E-SUBAGENT-settings-lists-builtin-defaults+ asserts.+- A host that is unavailable contributes no exclusions: an unreadable state file+ offers a delegate the user had turned off rather than removing one they kept.+- No Markdown file is written, no project capability layer appears, and+ `~/.agents/subagents` remains the only user-managed subagent source (ADR 0063+ §1, ADR 0112 §1).++## Alternatives++- **A tombstone document in `~/.agents/subagents`.** Switching a builtin off+ would write a file the user never asked for, show up in the Global group, and+ turn a one-click toggle into visible filesystem state.+- **Keeping the state in `agent-capabilities/subagents.json`.** Cheapest to+ write, but the scan-time prune that keeps deleted documents from leaving+ orphaned rows would delete a builtin exclusion at the same moment it was+ written.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 615b6308e..2b83ebdd1 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -294,5 +294,6 @@ Each ADR includes:| transcript-reading-ownership | [Share renderer history and search views](transcript-reading-ownership.md) | Accepted || 0266 | [Plugin fs roots follow the calling session](0266-plugin-fs-root-follows-the-calling-session.md) | Accepted (D093) || 0267 | [Plugin labels follow the app language](0267-plugin-labels-follow-the-app-language.md) | Accepted (amends 0160; ADR 0182) |+| 0270 | [Builtin subagents can be switched off](0270-builtin-subagents-can-be-disabled.md) | Accepted for implementation (amends ADR 0063; ADR 0112) || 0269 | [Move capability documents between the global and project levels](0269-capability-level-transfer.md) | Accepted for implementation (amends ADR 0112) || 0268 | Remove quotes, annotations, and side chats | Accepted (supersedes message-quotes-and-side-chats / response-annotations / floating-annotation-index) |diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex a9d14ed2a..d20f67ca3 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -1501,6 +1501,8 @@ written into the Markdown file.- `agents.read(id)` → `{ subagent, body }`- `agents.remove(id)`- `agents.setEnabled(id, enabled)`+- `agents.disabledBuiltins` → `{ disabled: string[] }`+- `agents.setBuiltinEnabled(id, enabled)` → `{ id, enabled }`The `thinkingLevel` field accepted by `agents.create` and `agents.update` maybe a canonical thinking level, `omit`, or the empty string. The empty string@@ -1518,12 +1520,24 @@ The `tools` array may include the token `inherit` (ADR 0246). `inherit` aloneis a valid grant; host-core must not drop the document. Settings round-tripsthe token as `tools: inherit` or `tools: [inherit, Bash]`.+`agents.disabledBuiltins` and `agents.setBuiltinEnabled` carry activation for the+shipped builtins, which have no document to switch (ADR 0270). Handles are stored+at the global level in `<data>/agent-capabilities/subagent-builtins.json`, a file+of its own: the user-document scan prunes state for ids it cannot see, and a+builtin is never scanned, so a shared file would drop every builtin exclusion on+the next scan. `agents.setBuiltinEnabled` normalizes the id the way a document+name is normalized and rejects an empty one with `SUBAGENT_INVALID`; a handle no+current builtin uses is stored inertly rather than refused, because host-core+does not ship the builtin list.+Electron's `subagent/list` IPC channel exposes the same global-only list toSettings > Agent > Subagents. `subagent/catalog` returns the effective Task-catalog (enabled user documents merged with the five shipped builtins) so the-page can render those defaults as read-only rows. The runtime catalog-combines the same sources; it does not scan `.pi/agents` or any project-capability directory.+catalog — enabled user documents merged with the five shipped builtins, minus the+builtins the user switched off — together with `builtins`: every shipped+definition that still wins its handle, each carrying `enabled`, so the page can+render a switched-off default as a row with its own switch. The runtime catalog+combines the same sources and applies the same exclusions; it does not scan+`.pi/agents` or any project capability directory.## 12d. Capability level and local activationdiff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex d154c6dcb..566096a2b 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -607,8 +607,9 @@ builtins shipped inline in `agent-runtime` (`explorer`, `code-reviewer`,`test-runner`, `fixer`, `ui-designer`) and the global user documents under`~/.agents/subagents/*.md`. There is no project-level subagent directory and`.pi/agents` is not scanned for capabilities. User documents are filtered by-the app-local enabled state before they reach the loader. Electron main loads-the global catalog on every launch and passes `subagents` /+the app-local enabled state before they reach the loader, and the shipped+builtins are filtered by that same app-local state inside it (ADR 0270).+Electron main loads`subagentProviders` in the sidecar params, so editing a definition takes effecton the next prompt. The catalog is capped at `MAX_SUBAGENT_DEFINITIONS` (16);a malformed or unreadable document becomes a launch diagnostic and never failsdiff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.mdindex 6c86b1d4e..4a6056ea3 100644--- a/docs/spec/04-ux/06-settings-ia.md+++ b/docs/spec/04-ux/06-settings-ia.md@@ -343,15 +343,18 @@ system while preserving their different data ownership:picker because it is global-only, keeping only search and its actions.The panel still uses two in-panel groups: **Built-in** (the five shippeddefinitions `explorer`, `code-reviewer`, `test-runner`, `fixer`, and- `ui-designer`, rendered as read-only rows) and **Global**- (`~/.agents/subagents`, user-owned). An enabled user document of the same- name shadows that builtin in the Task catalog, so the Built-in row is omitted- while the user row remains. A disabled user document of the same name leaves- the builtin in the catalog (and on the Built-in list) because Task uses the- shipped definition again. Built-in rows carry a source badge and- **Copy as mine** (opens the create sheet pre-filled from that definition, with- the matching template chip selected); they have no enablement switch, reveal,- or delete because they are not files.+ `ui-designer`) and **Global** (`~/.agents/subagents`, user-owned). An enabled+ user document of the same name shadows that builtin in the Task catalog, so+ the Built-in row is omitted while the user row remains. A disabled user+ document of the same name leaves the builtin in the catalog (and on the+ Built-in list) because Task uses the shipped definition again. Built-in rows+ carry a source badge, **Copy as mine** (opens the create sheet pre-filled from+ that definition, with the matching template chip selected), and the same+ enablement switch a user row has (D202 activation, ADR 0270): turning one off+ writes app-local state rather than a document, the row stays listed and dimmed+ so the switch is still the way back on, and the next catalog load stops+ offering it to `Task`. Reveal and delete remain absent because a builtin is+ not a file.- The level filter narrows which groups the panel renders; it never hides thetoolbar or moves the actions. New capabilities are created at the level thefilter points at — Global under All or Global, Project under Project — and@@ -456,9 +459,9 @@ system while preserving their different data ownership:is a picker over the configured providers' models; the picker groups entriesby provider and every option comes from the configured catalog, so there isno hand-typed pin entry (issue #60). With no providers configured it shows- an empty state whose action opens Models. Builtins stay on the existing- read-only Built-in rows; the picker is for new and user-owned subagents- only.+ an empty state whose action opens Models. A builtin keeps its Built-in row,+ which is switched but never edited; the picker is for new and user-owned+ subagents only.The create/edit sheet stays compact at desktop sizes: form controls arelocal filled wells with restrained padding, the prompt editor is the onlyintentionally tall control, and Advanced remains a compact disclosure. Hoverdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 84a6a9ec9..36d358146 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -6524,8 +6524,8 @@ identify the platform validation still needed.project-level controls. Confirm a Built-in group lists the five shippeddefaults (`explorer`, `code-reviewer`, `test-runner`, `fixer`,`ui-designer`) even when the user directory is empty, each with a- Built-in badge, its tool grant, and no enablement switch, reveal, or- delete. Confirm the Global group header carries the global level label+ Built-in badge, its tool grant, and an enablement switch, but no reveal+ or delete. Confirm the Global group header carries the global level labeland item count, that create/edit/delete/reveal all work from the pagefor user-owned rows, that leaving the output limit empty writes adefinition with no `maxTokens`, and that an empty user@@ -7469,6 +7469,8 @@ identify the platform validation still needed.| Quality (legacy subagent turn limit) | E2E-SUBAGENT-legacy-turn-limit-frontmatter-is-ignored || M6+ (disclosure reading position) | E2E-CHAT-disclosure-toggle-keeps-reading-position || M6+ (capability level move) | E2E-CAPABILITY-move-across-levels |+| E — Tools & permissions (builtin subagent defaults) | E2E-SUBAGENT-settings-lists-builtin-defaults |+| Quality (builtin subagent defaults) | E2E-SUBAGENT-settings-lists-builtin-defaults |The `US-UI-*` visual scenarios (§UI shell visual scenarios) trace to theCodex parity decisions in [decisions-log §D](../08-meta/decisions-log.md)@@ -9190,33 +9192,42 @@ This test plan spec is accepted when:#### E2E-SUBAGENT-settings-lists-builtin-defaults- **Preconditions**: A running app. `~/.agents/subagents` is empty. The five- shipped builtins are present and no user document shadows them.+ shipped builtins are present, none is switched off, and no user document+ shadows them.- **Steps**:1. Open Settings → Agent → Subagents. Confirm a Built-in group lists`explorer`, `code-reviewer`, `test-runner`, `fixer`, and `ui-designer`- with localized names, `Task(<handle>)` copy, tool grants, and a Built-in- badge. Confirm none of those rows has an enablement switch, Reveal, or- Delete.+ with localized names, `Task(<handle>)` copy, tool grants, a Built-in+ badge, **Copy as mine**, and an enablement switch in the on position.+ Confirm none of those rows has Reveal or Delete.2. Confirm the Global group still shows localized `settings.subagentsEmpty`copy and the New subagent action.- 3. Choose **Copy as mine** on explorer. Confirm the create sheet opens+ 3. Switch `fixer` off from its Built-in row. Confirm the row dims with its+ switch off, the toast names it, nothing appears in `~/.agents/subagents`,+ and the row stays listed, because that switch is the way back on.+ 4. Send a prompt with `fixer` switched off. Confirm the Task catalog does not+ offer it while the other four remain, then switch it back on and confirm+ the next prompt offers it again.+ 5. Choose **Copy as mine** on explorer. Confirm the create sheet openspre-filled from that definition (name, description, tools, body) withthe Explorer template chip selected, not Blank. Save. Confirmexplorer now appears only as a user-owned Global row and is omitted fromBuilt-in, and the next prompt's Task catalog uses the user document.- row and is omitted from Built-in, and the next prompt's Task catalog- uses the user document.- 4. Disable the user explorer and reload the page. Confirm the user row is+ 6. Disable the user explorer and reload the page. Confirm the user row isoff and explorer reappears under Built-in (disabled user documents donot reach the loader, so the shipped definition wins again).-- **Expected**: Settings shows the defaults the agent can actually delegate- to. Copying a builtin is how a user retunes it; enablement, reveal, and- delete remain file-backed actions on user-owned rows only.+- **Expected**: Settings shows the defaults the agent can actually delegate to,+ and every one of them can be turned off from its own row. Builtin activation+ is app-local state rather than a document, so a switched-off default keeps its+ row; copying a builtin stays the way to retune one, and reveal and delete+ remain file-backed actions on user-owned rows only.- **Specs linked**: `04-ux/06-settings-ia.md` §2, `03-runtime/01-ipc-protocol.md`- §12c, `03-runtime/02-agent-runtime.md` §5f, ADR 0062, ADR 0063+ §12c, `03-runtime/02-agent-runtime.md` §5f, ADR 0062, ADR 0063, ADR 0270- **Acceptance**: E (tools & permissions), Quality- **Milestone**: M6+- **Status**: Source/unit covered (`apps/desktop/test/agent-capability-settings.test.mjs`,+ `apps/desktop/test/subagent-wiring.test.mjs`,+ `packages/agent-runtime/src/subagent-definitions.test.ts`,`packages/shared/src/subagent-presets.test.ts`); full UI journey Draft(run only in a capable environment when this surface changes)diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 7d157cf71..06521238c 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -5608,3 +5608,24 @@ that was sitting at the bottom — including after the turn had finished.migration change, and no new token. See `04-ux/08-component-spec.md` §2.3 and§5.2, `04-ux/07-ui-design-system.md` §4.3, andE2E-LAYOUT-three-column-width-priority.++## 2026-09-17 — Builtin subagents can be switched off (D434)++- Settings > Agent > Subagents listed the five shipped defaults as read-only+ rows while the user's own documents had an enablement switch, so one delegate+ could not be turned off at all: copying a builtin and disabling the copy left+ the shipped definition in the catalog, because disabled user documents are+ filtered out before the loader merges and so shadowed nothing.+- Every Built-in row now carries the same switch. The handle is stored in+ `<data>/agent-capabilities/subagent-builtins.json`, a file of its own because+ the user-document scan prunes state for ids it can never see, and host-core+ exposes it through `agents.disabledBuiltins` / `agents.setBuiltinEnabled`.+ Electron main hands the disabled handles to `loadSubagentDefinitions`, which+ drops them from the delegation catalog while `subagent/catalog` still returns+ the builtin, flagged `enabled: false`, in its new `builtins` list.+- A switched-off builtin keeps its row, dimmed, so the switch is the way back+ on. A user document of the same handle keeps working and keeps shadowing the+ shipped definition, reveal and delete stay absent because a builtin is not a+ file, and an unavailable host contributes no exclusions. See ADR 0270,+ `04-ux/06-settings-ia.md` §2, `03-runtime/01-ipc-protocol.md` §12c, and+ E2E-SUBAGENT-settings-lists-builtin-defaults.diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.mdindex bb6ceb75d..5d2606cc9 100644--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md@@ -1237,6 +1237,8 @@ ASCII slug:frontmatter `name` 能 slugify 时用它,否则 `SKILL.md` 用技- `agents.read(id)` → `{ subagent, body }`- `agents.remove(id)`- `agents.setEnabled(id, enabled)`+- `agents.disabledBuiltins` → `{ disabled: string[] }`+- `agents.setBuiltinEnabled(id, enabled)` → `{ id, enabled }``agents.create` 和 `agents.update` 接受的 `thinkingLevel` 可以是规范思考档位、`omit` 或空字符串。空字符串清除覆盖;`omit` 持久化为@@ -1247,10 +1249,19 @@ ASCII slug:frontmatter `name` 能 slugify 时用它,否则 `SKILL.md` 用技而不会被存储,因为没有任何解析器能查到它。提供商部分在应用两端都按归一化别名匹配,因此包含空格的显示名是合法的。+`agents.disabledBuiltins` 和 `agents.setBuiltinEnabled` 承载随应用发布的内置子代理的+启用状态,这些内置项没有可切换的文档 (ADR 0270)。句柄存放在全局级别的+`<data>/agent-capabilities/subagent-builtins.json` —— 一个独立文件:用户文档扫描会清理+它永远看不到的 id 的状态,而内置项从不被扫描,因此共用一个文件会让所有内置项的关闭状态+在下一次扫描时丢失。`agents.setBuiltinEnabled` 按文档名同样的规则归一化 id,空值以+`SUBAGENT_INVALID` 拒绝;当前没有任何内置项使用的句柄也会惰性保存而不是拒绝,因为+host-core 不携带内置清单。+Electron 的 `subagent/list` IPC 通道向设置 > 智能体 > 子代理暴露同一份全局列表。`subagent/catalog` 返回当前 `Task` 目录(已启用的用户文档与五个内置定义-合并后的结果),供设置页把默认子智能体渲染为只读行。运行时目录使用同一套来源;-不会扫描 `.pi/agents` 或任何项目能力目录。+合并后,再减去被用户关闭的内置项),并额外返回 `builtins`:每个仍然赢得自己句柄的+内置定义,各自带 `enabled`,供设置页把关闭的默认项渲染成带自己开关的行。运行时+目录使用同一套来源并应用同样的排除;不会扫描 `.pi/agents` 或任何项目能力目录。## 12d. 能力级别与本地启用状态diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex 883846ef2..be40366c8 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -505,7 +505,8 @@ Goal 批准所承诺的内容与 Plan 批准所承诺的内容完全相同:`mo**目录。** 定义是来自两个来源的 Markdown 文档:`agent-runtime` 中内嵌的五个内置函数(`explorer`、`code-reviewer`、`test-runner`、`fixer`、`ui-designer`),以及`~/.agents/subagents/*.md` 下的全局用户文档。没有项目级子代理目录,`.pi/agents`-不会作为能力来源被扫描。用户文档在进入加载器前会根据应用本地启用状态过滤。+不会作为能力来源被扫描。用户文档在进入加载器前会根据应用本地启用状态过滤,+内置定义则由加载器按同一份应用本地状态过滤(ADR 0270)。Electron main 每次启动加载全局目录,并在 sidecar 参数中传递`subagents` / `subagentProviders`,因此编辑定义会在下一次提示时生效。目录上限为 `MAX_SUBAGENT_DEFINITIONS`(16);格式错误或不可读文档只产生启动诊断,diff --git a/docs/zh-CN/spec/04-ux/06-settings-ia.md b/docs/zh-CN/spec/04-ux/06-settings-ia.mdindex 61b122749..adbc1efc1 100644--- a/docs/zh-CN/spec/04-ux/06-settings-ia.md+++ b/docs/zh-CN/spec/04-ux/06-settings-ia.md@@ -157,13 +157,20 @@ Token 用量**不是设置目的地**(D335 / ADR 0173)。已完成回合历- API 键在保存后永远不会显示原始内容- 已登录的厂商行带账户徽标,其编辑对话框用该徽标替换 API 密钥字段 ——这里没有东西可粘贴-- 列表仍分两组:内置五个默认子智能体(只读,可「复制为我的定义」)和- `~/.agents/subagents` 下的用户文档。+- 列表仍分两组:内置五个默认子智能体(`explorer`、`code-reviewer`、`test-runner`、+ `fixer`、`ui-designer`)和 `~/.agents/subagents` 下的用户文档。同名的已启用用户文档+ 会在 `Task` 目录中遮蔽对应的内置定义,内置行随之省略、只保留用户行;同名的已停用用户+ 文档会让该内置重新留在目录(以及内置列表)中,因为 `Task` 又用回随应用发布的定义。+ 内置行带来源角标、「复制为我的定义」(以该定义预填新建表单,并选中对应的模板芯片),+ 以及与用户行相同的启用开关(D202 意义上的应用本地状态,ADR 0270):关掉它写入的是+ 应用本地状态而不是文档,该行仍留在列表中并变暗,所以这个开关就是重新打开的入口;+ 下一次目录加载起不再提供给 `Task`。在文件夹中显示与删除仍然没有,因为内置不是文件。- 子智能体新建/编辑表单使用与 Composer 相同的已配置、可运行模型,控件是可搜索、按提供商分组的锚定菜单(与服务选择器同一套选项菜单控件),并提供“沿用会话模型”选项。原生下拉框无法承载该列表:一次安装可能配置数十个模型,只有锚定浮层能在自身内部滚动并接受过滤。每个选项都来自已配置的提供商目录,表单不接受手填模型 ID;当没有任何提供商提供可运行模型时,改为显示带操作按钮的空态(直接打开模型设置)。+ 内置项保留自己的内置行:可以开关,但永不编辑;模型选择器只用于新建和用户自有子智能体。若已有 pin 不再配置,编辑时仍保留该选项,避免悄悄丢失。通用或重复的厂商标识如果产生歧义,则依次使用唯一的提供商显示名和已存储的提供商 ID,保证不同提供商的选项不会被合并。思考选择器提供沿用会话、不发送以及七个规范档位;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 5eeb5cc0c..2014fa398 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@@ -1567,20 +1567,28 @@ unit/integration 测试;代码 pull request 使用有选择且高价值的 E2E#### E2E-SUBAGENT-settings-lists-builtin-defaults-- **前提条件**:应用已运行。`~/.agents/subagents` 为空。五个内置定义存在,且没有用户文档覆盖它们。+- **前提条件**:应用已运行。`~/.agents/subagents` 为空。五个内置定义存在,没有一个被关闭,且没有用户文档覆盖它们。- **步骤**:1. 打开设置 → 智能体 → 子智能体。确认内置分组列出 `explorer`、`code-reviewer`、- `test-runner`、`fixer`、`ui-designer`,带本地化名称、`Task(<handle>)`、工具授权和「内置」徽标;- 这些行没有启用开关、在文件夹中显示或删除。+ `test-runner`、`fixer`、`ui-designer`,带本地化名称、`Task(<handle>)`、工具授权、「内置」徽标、+ 「复制为我的定义」,以及处于打开位置的启用开关。确认这些行没有在文件夹中显示或删除。2. 确认全局分组仍显示本地化的 `settings.subagentsEmpty` 文案和「新建子智能体」。- 3. 在 explorer 上选择「复制为我的定义」。确认新建表单按该定义预填,且选中的是探索者模板芯片而不是空白开始。保存后确认 explorer 只出现在全局用户行,并从内置分组消失。- 4. 禁用该用户 explorer 并重新加载。确认用户行关闭,explorer 重新出现在内置分组(未启用的用户文档不会进入加载器,因此内置定义重新生效)。-- **预期**:设置页展示主智能体实际可委派的默认子智能体。复制内置项是用户改写它的方式;启用、显示和删除只作用于用户自建文件。+ 3. 在内置行上关掉 `fixer`。确认该行随开关关闭而变暗,toast 指出它的名字,+ `~/.agents/subagents` 中没有出现任何东西,且该行仍留在列表里,因为那个开关就是重新打开的入口。+ 4. 在 `fixer` 关闭的情况下发送一次提示。确认 `Task` 目录不再提供它,而其余四个仍在;然后把它重新打开,+ 确认下一次提示又提供它。+ 5. 在 explorer 上选择「复制为我的定义」。确认新建表单按该定义预填(名称、描述、工具、正文),+ 且选中的是探索者模板芯片而不是空白开始。保存后确认 explorer 只出现在全局用户行,并从内置分组+ 消失,且下一次提示的 `Task` 目录使用该用户文档。+ 6. 禁用该用户 explorer 并重新加载。确认用户行关闭,explorer 重新出现在内置分组(未启用的用户文档不会进入加载器,因此内置定义重新生效)。+- **预期**:设置页展示主智能体实际可委派的默认子智能体,且每一个都能从自己的行上关闭。内置项的启用状态是应用本地状态而不是文档,因此被关闭的默认项保留自己的行;复制内置项仍是改写它的方式;在文件夹中显示与删除仍然只作用于用户自建的行,因为它们以文件为后端。- **链接规格**:`04-ux/06-settings-ia.md` §2、`03-runtime/01-ipc-protocol.md` §12c、- `03-runtime/02-agent-runtime.md` §5f、ADR 0062、ADR 0063+ `03-runtime/02-agent-runtime.md` §5f、ADR 0062、ADR 0063、ADR 0270- **验收**:E(工具与权限)、品质- **里程碑**:M6+-- **状态**:源代码/单元已覆盖;完整 UI 旅程为草稿+- **状态**:源代码/单元已覆盖(`apps/desktop/test/agent-capability-settings.test.mjs`、+ `apps/desktop/test/subagent-wiring.test.mjs`、`packages/agent-runtime/src/subagent-definitions.test.ts`、+ `packages/shared/src/subagent-presets.test.ts`);完整 UI 旅程为草稿#### E2E-200:Linux RPM 保留 Wayland 桌面身份@@ -4520,7 +4528,7 @@ IPC 请求无法关闭。11. 打开子代理,确认它是以 `~/.agents/subagents` 为根的单块全局面板,没有级别筛选、没有项目选择器、也没有项目级控制。确认即使用户目录为空,内置分组仍列出五个默认子智能体(`explorer`、`code-reviewer`、`test-runner`、`fixer`、`ui-designer`),- 带「内置」徽标和工具授权,且没有启用开关、在文件夹中显示或删除。确认全局分组标题+ 带「内置」徽标、工具授权和启用开关,但没有在文件夹中显示或删除。确认全局分组标题带有全局级别标签和数量,新建 / 编辑 / 删除 / 在文件管理器中显示都能对用户自建行在页面内完成,且空的用户目录仍通过`settings.subagentsEmpty` 在全局分组下解析为本地化空态文案,不显示原始翻译键。@@ -4970,6 +4978,8 @@ IPC 请求无法关闭。| 品质(旧版子代理回合上限) | E2E-SUBAGENT-legacy-turn-limit-frontmatter-is-ignored || M6+(展开详情保持阅读位置) | E2E-CHAT-disclosure-toggle-keeps-reading-position || M6+(能力跨级别迁移) | E2E-CAPABILITY-move-across-levels |+| E — 工具与权限(内置子智能体默认项) | E2E-SUBAGENT-settings-lists-builtin-defaults |+| 品质(内置子智能体默认项) | E2E-SUBAGENT-settings-lists-builtin-defaults |`US-UI-*` 视觉场景(§UI shell 视觉场景)追踪到[决策日志 §D](/zh-CN/spec/08-meta/decisions-log) 中的法典平价决策diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex daace494a..92cd58e47 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -4265,3 +4265,9 @@ that amendment are retired by ADR 0268; the upstream work-panel lifecycle stays.- 开关的按下状态去掉填充与抬升阴影,保留被激活的墨色,因此打开状态就是图形切换加 `--ds-text-primary`。`aria-pressed` 仍向辅助技术传达状态,`.app-work-panel-toggle` 继续拥有视口固定定位与 `no-drag` 排除区。- 键盘焦点不变:全局 `:focus-visible` 轮廓与其他 chrome 图标控件一致地生效,因此移除已废弃的 `:focus-visible` 背景淡色不会损失任何焦点提示。- 仅渲染层:几何、间距、内缩、协议、存储、宿主、权限与迁移均无改动,也没有新增 token。见 `04-ux/08-component-spec.md` §2.3 与 §5.2、`04-ux/07-ui-design-system.md` §4.3 与 E2E-LAYOUT-three-column-width-priority。++## 2026-09-17 —— 内置子智能体可以关闭(D434)++- 设置 > 智能体 > 子智能体把五个随应用发布的默认项列为只读行,而用户自建的文档带启用开关,于是有一个委派对象完全无法关闭:复制一个内置项再停用副本,随应用发布的定义仍留在目录里,因为被停用的用户文档在加载器合并前就被过滤掉,也就没有遮蔽任何东西。+- 每个内置行现在都带同一个开关。句柄存放在 `<data>/agent-capabilities/subagent-builtins.json` —— 一个独立文件,因为用户文档扫描会清理它永远看不到的 id 的状态 —— 并由 host-core 通过 `agents.disabledBuiltins` / `agents.setBuiltinEnabled` 暴露。Electron 主进程把被关闭的句柄交给 `loadSubagentDefinitions`,由它把它们从委派目录中剔除,而 `subagent/catalog` 仍会在其新增的 `builtins` 列表中返回该内置项,并标记 `enabled: false`。+- 被关闭的内置项保留自己的行并变暗,因此这个开关就是重新打开的入口。同名的用户文档继续生效并继续遮蔽随应用发布的定义,在文件夹中显示与删除仍然没有,因为内置不是文件;宿主不可用时也不会贡献任何排除项。见 ADR 0270、`04-ux/06-settings-ia.md` §2、`03-runtime/01-ipc-protocol.md` §12c 与 E2E-SUBAGENT-settings-lists-builtin-defaults。diff --git a/packages/agent-runtime/src/subagent-definitions.test.ts b/packages/agent-runtime/src/subagent-definitions.test.tsindex c37d2f075..21883c99b 100644--- a/packages/agent-runtime/src/subagent-definitions.test.ts+++ b/packages/agent-runtime/src/subagent-definitions.test.ts@@ -111,6 +111,36 @@ describe("loadSubagentDefinitions", () => {expect(definitions.map((d) => d.name)).toContain("code-reviewer");});+ it("drops a switched-off builtin from the catalog and keeps it as a builtin row", async () => {+ const { definitions, builtins, diagnostics } = await loadSubagentDefinitions(null, {+ disabledBuiltins: ["fixer"],+ });++ expect(diagnostics).toEqual([]);+ expect(definitions.map((d) => d.name)).not.toContain("fixer");+ expect(definitions.map((d) => d.name)).toContain("explorer");+ // Settings needs the row back: its switch is the only way on again, and a+ // builtin has no document to delete.+ expect(builtins.map((d) => d.name)).toContain("fixer");+ expect(builtins.every((d) => d.source === "builtin")).toBe(true);+ });++ it("lets a user document keep a handle the user switched the builtin off", async () => {+ const { definitions, builtins } = await loadSubagentDefinitions(null, {+ userDocuments: [+ {+ id: "fixer",+ document: "---\nname: fixer\ndescription: Mine.\ntools: [Read]\n---\nMine.\n",+ filePath: "/home/.agents/subagents/fixer.md",+ },+ ],+ disabledBuiltins: ["fixer"],+ });++ expect(definitions.find((d) => d.name === "fixer")?.source).toBe("user");+ expect(builtins.map((d) => d.name)).not.toContain("fixer");+ });+it("reports a malformed document without losing the others", async () => {await writeFile(join(dir, "broken.md"), "---\ntools: [Read]\n---\n\n", "utf8");await writeFile(diff --git a/packages/agent-runtime/src/subagent-definitions.ts b/packages/agent-runtime/src/subagent-definitions.tsindex 82f193037..ba0c9cc4a 100644--- a/packages/agent-runtime/src/subagent-definitions.ts+++ b/packages/agent-runtime/src/subagent-definitions.ts@@ -274,6 +274,12 @@ export type LoadSubagentOptions = {overrideDir?: string;/** Documents already scanned by host-core from `~/.agents/subagents`. */userDocuments?: readonly UserSubagentDocument[];+ /**+ * Handles whose shipped definition the user turned off (D202 activation for+ * builtins, which are constants rather than documents). Their definitions+ * stay out of `definitions` but still reach `builtins`.+ */+ disabledBuiltins?: readonly string[];};function loadUserSubagents(documents: readonly UserSubagentDocument[]): {@@ -298,13 +304,22 @@ function loadUserSubagents(documents: readonly UserSubagentDocument[]): {/*** Definitions offered to a session: the user's global documents and the- * builtins. Load failures degrade to diagnostics: a malformed document must not- * cost the session its other delegates, let alone its turn.+ * builtins, minus the builtins the user turned off. Load failures degrade to+ * diagnostics: a malformed document must not cost the session its other+ * delegates, let alone its turn.+ *+ * `builtins` carries every shipped definition that still wins its handle,+ * whether or not it is switched on, so Settings can render an off builtin as a+ * row with its own switch; `definitions` is what `Task` may actually offer.*/export async function loadSubagentDefinitions(workspaceRoot: string | null | undefined,options: LoadSubagentOptions = {},-): Promise<{ definitions: SubagentDefinition[]; diagnostics: string[] }> {+): Promise<{+ definitions: SubagentDefinition[];+ builtins: SubagentDefinition[];+ diagnostics: string[];+}> {const builtin = builtinSubagents();const dir =options.overrideDir ??@@ -329,7 +344,21 @@ export async function loadSubagentDefinitions(`dropped subagents past the catalog cap: ${merged.dropped.join(", ")}`,);}- return { definitions: merged.definitions, diagnostics };+ // A switched-off builtin is excluded from the delegation catalog and from+ // nothing else: a user document of the same name still shadows it, and a+ // handle the user re-enables needs no document of its own to come back.+ const disabled = new Set(options.disabledBuiltins ?? []);+ const builtins = merged.definitions.filter(+ (definition) => definition.source === "builtin",+ );+ return {+ definitions: merged.definitions.filter(+ (definition) =>+ !(definition.source === "builtin" && disabled.has(definition.name)),+ ),+ builtins,+ diagnostics,+ };}/** The stored-provider fields a pin can be resolved against. */diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 5867ba1bd..85211764e 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -220,6 +220,7 @@ export const IPC = {subagentRemove: "pi-desktop/subagent/remove",subagentSetEnabled: "pi-desktop/subagent/setEnabled",subagentSetScope: "pi-desktop/subagent/setScope",+ subagentSetBuiltinEnabled: "pi-desktop/subagent/setBuiltinEnabled",subagentReveal: "pi-desktop/subagent/reveal",marketRefresh: "pi-desktop/market/refresh",marketSearch: "pi-desktop/market/search",diff --git a/scripts/e2e-subagents.mjs b/scripts/e2e-subagents.mjsindex 4e5143de3..36bd8708b 100644--- a/scripts/e2e-subagents.mjs+++ b/scripts/e2e-subagents.mjs@@ -202,6 +202,31 @@ try {);await call("agents.setEnabled", { id: "log-reader", enabled: true });+ // The shipped builtins have no document, so their switch is app-local state+ // (ADR 0270): it must survive the user-document scan, which is what the+ // registry runs on every list, and the loader must drop the handle from the+ // delegation catalog while still reporting the builtin row.+ const beforeBuiltins = await call("agents.disabledBuiltins");+ const offBuiltin = await call("agents.setBuiltinEnabled", { id: "fixer", enabled: false });+ const disabledNow = await call("agents.disabledBuiltins");+ check(+ "a builtin handle is switched off without writing a document",+ offBuiltin.result?.id === "fixer" &&+ offBuiltin.result?.enabled === false &&+ (beforeBuiltins.result?.disabled ?? []).includes("fixer") === false &&+ (disabledNow.result?.disabled ?? []).includes("fixer") === true &&+ !existsSync(join(agentsDir, "fixer.md")),+ JSON.stringify(disabledNow.result?.disabled),+ );+ const fixed = await call("agents.setBuiltinEnabled", { id: "fixer", enabled: true });+ const restoredBuiltins = await call("agents.disabledBuiltins");+ check(+ "switching it back on clears the stored override",+ fixed.result?.enabled === true &&+ !(restoredBuiltins.result?.disabled ?? []).includes("fixer"),+ JSON.stringify(restoredBuiltins.result?.disabled),+ );+const read = await call("agents.read", { id: "log-reader" });check("read returns the body for the editor",@@ -284,6 +309,20 @@ try {const userDocuments = await readActive(projectA);const merged = await loadSubagentDefinitions(projectA, { userDocuments });const byName = new Map(merged.definitions.map((definition) => [definition.name, definition]));+ // A switched-off builtin leaves the delegation catalog and stays available as+ // a builtin row, which is where Settings keeps its switch (ADR 0270).+ const withDisabledBuiltin = await loadSubagentDefinitions(projectA, {+ userDocuments,+ disabledBuiltins: ["fixer"],+ });+ check(+ "a switched-off builtin leaves the catalog and keeps its builtin row",+ !withDisabledBuiltin.definitions.some((definition) => definition.name === "fixer") &&+ withDisabledBuiltin.builtins.some(+ (definition) => definition.name === "fixer" && definition.source === "builtin",+ ),+ `${withDisabledBuiltin.definitions.length} definitions, ${withDisabledBuiltin.builtins.length} builtins`,+ );const builtinNames = ["explorer", "code-reviewer", "test-runner", "fixer", "ui-designer"];check("the global registry document reaches the loader as a user definition",