Skip to content

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

fix(settings): derive capability overrides from the accepted collection

liuzixiange7643cf134d3
diff --git a/apps/desktop/src/components/settings/AgentMcpPage.tsx b/apps/desktop/src/components/settings/AgentMcpPage.tsx
index 3a766f6a5..3d263522f 100644
--- a/apps/desktop/src/components/settings/AgentMcpPage.tsx
+++ b/apps/desktop/src/components/settings/AgentMcpPage.tsx
@@ -80,9 +80,16 @@ type McpCollection = {
global: McpServerRecord[];
project: McpServerRecord[];
statuses: McpServerStatus[];
+ /** Stored per-project overrides on global rows, from the accepted fetch. */
+ globalOverrides: Record<string, CapabilityOverride>;
};
-const EMPTY_MCP_COLLECTION: McpCollection = { global: [], project: [], statuses: [] };
+const EMPTY_MCP_COLLECTION: McpCollection = {
+ global: [],
+ project: [],
+ statuses: [],
+ globalOverrides: {},
+};
export function AgentMcpPage() {
const { t } = useTranslation();
@@ -109,17 +116,22 @@ export function AgentMcpPage() {
statuses: [] as McpServerStatus[],
}),
]);
- setGlobalOverrides(
- deriveProjectOverrides(global.servers ?? [], globalEffective.servers ?? []),
- );
+ // The derived map rides inside the collection: useHostCollection only
+ // accepts the newest request, so a late stale fetch can never repaint the
+ // override badges of the project the reader has since switched to.
return {
global: global.servers ?? [],
project: project.servers ?? [],
statuses: [...(global.statuses ?? []), ...(project.statuses ?? [])],
+ globalOverrides: selectedProjectPath
+ ? Object.fromEntries(
+ deriveProjectOverrides(global.servers ?? [], globalEffective.servers ?? []),
+ )
+ : {},
};
}, [selectedProjectPath]);
const {
- data: { global: globalServers, project: projectServers, statuses },
+ data: { global: globalServers, project: projectServers, statuses, globalOverrides },
setData: setServers,
loading,
refreshing,
@@ -130,9 +142,6 @@ export function AgentMcpPage() {
const setStatuses = (update: (current: McpServerStatus[]) => McpServerStatus[]) =>
setServers((current) => ({ ...current, statuses: update(current.statuses) }));
const [filter, setFilter] = useState<CapabilityFilter>("all");
- const [globalOverrides, setGlobalOverrides] = useState<Map<string, CapabilityOverride>>(
- () => new Map(),
- );
const [importOpen, setImportOpen] = useState(false);
const [search, setSearch] = useState("");
const rowBusy = useRowBusy();
@@ -514,7 +523,7 @@ export function AgentMcpPage() {
} satisfies CapabilityMenuItem,
]
: []),
- ...(level === "global" && selectedProjectPath && globalOverrides.get(server.id)
+ ...(level === "global" && selectedProjectPath && globalOverrides[server.id]
? [
{
key: "reset-override",
@@ -582,9 +591,9 @@ export function AgentMcpPage() {
? t("settings.capabilityFilterGlobal")
: t("settings.capabilityFilterProject")}
</span>
- {level === "global" && selectedProjectPath && globalOverrides.get(server.id) ? (
+ {level === "global" && selectedProjectPath && globalOverrides[server.id] ? (
<span className="agent-capability-badge is-override">
- {globalOverrides.get(server.id) === "off"
+ {globalOverrides[server.id] === "off"
? t("settings.capabilityOverrideOff")
: t("settings.capabilityOverrideOn")}
</span>
diff --git a/apps/desktop/src/components/settings/AgentSkillsPage.tsx b/apps/desktop/src/components/settings/AgentSkillsPage.tsx
index 6c30b2f4a..e17b3849a 100644
--- a/apps/desktop/src/components/settings/AgentSkillsPage.tsx
+++ b/apps/desktop/src/components/settings/AgentSkillsPage.tsx
@@ -67,9 +67,16 @@ type SkillCollection = {
builtins: BuiltinSkillRecord[];
global: UserSkillRecord[];
project: UserSkillRecord[];
+ /** Stored per-project overrides on global rows, from the accepted fetch. */
+ globalOverrides: Record<string, CapabilityOverride>;
};
-const EMPTY_SKILL_COLLECTION: SkillCollection = { builtins: [], global: [], project: [] };
+const EMPTY_SKILL_COLLECTION: SkillCollection = {
+ builtins: [],
+ global: [],
+ project: [],
+ globalOverrides: {},
+};
export function AgentSkillsPage() {
const { t } = useTranslation();
@@ -91,15 +98,20 @@ export function AgentSkillsPage() {
? api.listUserSkills({ level: "global", projectPath: selectedProjectPath })
: Promise.resolve({ skills: [] as UserSkillRecord[] }),
]);
- setGlobalOverrides(deriveProjectOverrides(global.skills ?? [], globalEffective.skills ?? []));
+ // The derived map rides inside the collection: useHostCollection only
+ // accepts the newest request, so a late stale fetch can never repaint the
+ // override badges of the project the reader has since switched to.
return {
builtins: builtins.builtins ?? [],
global: global.skills ?? [],
project: project.skills ?? [],
+ globalOverrides: selectedProjectPath
+ ? Object.fromEntries(deriveProjectOverrides(global.skills ?? [], globalEffective.skills ?? []))
+ : {},
};
}, [selectedProjectPath]);
const {
- data: { builtins: builtinSkills, global: globalSkills, project: projectSkills },
+ data: { builtins: builtinSkills, global: globalSkills, project: projectSkills, globalOverrides },
setData: setSkills,
loading,
refreshing,
@@ -108,9 +120,6 @@ export function AgentSkillsPage() {
showToast(error instanceof Error ? error.message : String(error), { variant: "error" }),
);
const [filter, setFilter] = useState<CapabilityFilter>("all");
- const [globalOverrides, setGlobalOverrides] = useState<Map<string, CapabilityOverride>>(
- () => new Map(),
- );
const [importOpen, setImportOpen] = useState(false);
const [search, setSearch] = useState("");
const rowBusy = useRowBusy();
@@ -471,7 +480,7 @@ export function AgentSkillsPage() {
} satisfies CapabilityMenuItem,
]
: []),
- ...(level === "global" && selectedProjectPath && globalOverrides.get(skill.id)
+ ...(level === "global" && selectedProjectPath && globalOverrides[skill.id]
? [
{
key: "reset-override",
@@ -514,9 +523,9 @@ export function AgentSkillsPage() {
? t("settings.capabilityFilterGlobal")
: t("settings.capabilityFilterProject")}
</span>
- {level === "global" && selectedProjectPath && globalOverrides.get(skill.id) ? (
+ {level === "global" && selectedProjectPath && globalOverrides[skill.id] ? (
<span className="agent-capability-badge is-override">
- {globalOverrides.get(skill.id) === "off"
+ {globalOverrides[skill.id] === "off"
? t("settings.capabilityOverrideOff")
: t("settings.capabilityOverrideOn")}
</span>
diff --git a/apps/desktop/test/capability-override-race.test.mjs b/apps/desktop/test/capability-override-race.test.mjs
new file mode 100644
index 000000000..27460b277
--- /dev/null
+++ b/apps/desktop/test/capability-override-race.test.mjs
@@ -0,0 +1,78 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+// The react alias must be registered so the hook module's "react" import
+// resolves to the minimal runtime; ts-import-hooks then handles the
+// extensionless relative imports.
+register(new URL("./helpers/react-alias-hooks.mjs", import.meta.url));
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+globalThis.window = { piDesktop: undefined };
+const { useHostCollection } = await import("../src/hooks/use-host-collection.ts");
+const stub = await import("./helpers/react-hook-stub.mjs");
+
+const empty = { global: [], project: [], statuses: [], globalOverrides: {} };
+
+const flush = () => new Promise((resolve) => setImmediate(resolve));
+
+test("a late stale project fetch cannot repaint the accepted project's overrides", async () => {
+ // #1964 review round three: the override map used to live in its own state,
+ // written from inside the fetcher before the generation check, so a slow A
+ // fetch landing after the reader had switched to B repainted B's badges with
+ // A's overrides - and reversing the pair hid B's real mismatch entirely.
+ // Overrides now ride inside the collection, so the guard rejects them
+ // wholesale together with the rows they were derived from.
+ const collectionA = {
+ global: [{ id: "s", enabled: true }],
+ project: [],
+ statuses: [],
+ globalOverrides: { s: "off" },
+ };
+ const collectionB = {
+ global: [{ id: "s", enabled: true }],
+ project: [],
+ statuses: [],
+ globalOverrides: {},
+ };
+
+ // One fetcher identity per project, exactly like the page's useCallback.
+ let fetcher = () => new Promise((resolve) => {
+ window.__resolveA = resolve;
+ });
+ let view = stub.__mount(() => useHostCollection(fetcher, empty, () => {}));
+ assert.notEqual(window.__resolveA, undefined, "project A's fetch should be in flight");
+
+ // The reader switches to project B: a new fetcher identity, a new request
+ // generation; the effect cleanup retires everything before it.
+ fetcher = () => Promise.resolve(collectionB);
+ view = stub.__render(() => useHostCollection(fetcher, empty, () => {}));
+ await flush();
+ view = stub.__render(() => useHostCollection(fetcher, empty, () => {}));
+ assert.deepEqual(view.data, collectionB);
+
+ // A lands late. The accepted collection must stay B's, overrides included.
+ window.__resolveA(collectionA);
+ await flush();
+ view = stub.__render(() => useHostCollection(fetcher, empty, () => {}));
+ assert.deepEqual(view.data, collectionB, "the stale collection must be rejected");
+ assert.deepEqual(view.data.globalOverrides, {}, "B shows no overrides after A lands late");
+});
+
+test("the newest generation still wins when it finishes after an older one", async () => {
+ const collectionA = {
+ global: [],
+ project: [],
+ statuses: [],
+ globalOverrides: { s: "on" },
+ };
+ let fetcher = () => Promise.resolve(empty);
+ let view = stub.__mount(() => useHostCollection(fetcher, empty, () => {}));
+ await flush();
+ view = stub.__render(() => useHostCollection(fetcher, empty, () => {}));
+ assert.deepEqual(view.data, empty);
+
+ fetcher = () => Promise.resolve(collectionA);
+ view = stub.__render(() => useHostCollection(fetcher, empty, () => {}));
+ await flush();
+ view = stub.__render(() => useHostCollection(fetcher, empty, () => {}));
+ assert.deepEqual(view.data, collectionA);
+});
diff --git a/apps/desktop/test/helpers/react-alias-hooks.mjs b/apps/desktop/test/helpers/react-alias-hooks.mjs
new file mode 100644
index 000000000..fa3ac0a6e
--- /dev/null
+++ b/apps/desktop/test/helpers/react-alias-hooks.mjs
@@ -0,0 +1,14 @@
+/**
+ * Resolve hook: route "react" imports to the minimal hook runtime so a hook
+ * module can be driven under `node --test` without a renderer.
+ */
+export async function resolve(specifier, context, next) {
+ if (specifier === "react") {
+ return {
+ url: new URL("./react-hook-stub.mjs", import.meta.url).href,
+ format: "module",
+ shortCircuit: true,
+ };
+ }
+ return next(specifier, context);
+}
diff --git a/apps/desktop/test/helpers/react-hook-stub.mjs b/apps/desktop/test/helpers/react-hook-stub.mjs
new file mode 100644
index 000000000..ab3cde25d
--- /dev/null
+++ b/apps/desktop/test/helpers/react-hook-stub.mjs
@@ -0,0 +1,98 @@
+/**
+ * Minimal React hook runtime for driving one hook under test.
+ *
+ * Implements exactly the hooks `use-host-collection.ts` imports, with
+ * production-faithful semantics: state cells survive across renders, a state
+ * write is observable on the next `__render`, `useCallback`/`useEffect`
+ * compare deps with `Object.is`, an effect whose deps changed runs its
+ * cleanup before the new body, and effect bodies run at the end of the render
+ * that scheduled them. Register `react-alias-hooks.mjs` so the module under
+ * test resolves this file as "react".
+ */
+
+let cells = [];
+let cellIndex = 0;
+let pendingEffects = [];
+let renderRequested = false;
+
+/** Reset every cell and start a fresh mount. */
+export function __mount(hookFn) {
+ cells = [];
+ cellIndex = 0;
+ pendingEffects = [];
+ renderRequested = false;
+ return __render(hookFn);
+}
+
+/** Re-run the hook against the surviving cells; runs scheduled effect bodies. */
+export function __render(hookFn) {
+ cellIndex = 0;
+ const result = hookFn();
+ // React commits effect bodies after the render that scheduled them; keep
+ // draining because an effect body can schedule another.
+ while (pendingEffects.length > 0) {
+ const effects = pendingEffects;
+ pendingEffects = [];
+ for (const effect of effects) effect();
+ }
+ return result;
+}
+
+/** Whether a state write happened since the last render. */
+export function __renderRequested() {
+ return renderRequested;
+}
+
+export function useState(initial) {
+ const index = cellIndex++;
+ if (cells[index] === undefined) {
+ cells[index] = { value: typeof initial === "function" ? initial() : initial };
+ }
+ const cell = cells[index];
+ const setState = (action) => {
+ const next = typeof action === "function" ? action(cell.value) : action;
+ if (Object.is(next, cell.value)) return;
+ cell.value = next;
+ renderRequested = true;
+ };
+ return [cell.value, setState];
+}
+
+export function useRef(initial) {
+ const index = cellIndex++;
+ // Unlike useState, a ref stores its initial value as-is - it is often a
+ // callback, never a lazy initializer.
+ if (cells[index] === undefined) {
+ cells[index] = { current: initial };
+ }
+ return cells[index];
+}
+
+export function useCallback(fn, deps) {
+ const index = cellIndex++;
+ const cell = cells[index] ?? (cells[index] = { deps: undefined, fn: undefined });
+ const same =
+ cell.deps !== undefined &&
+ deps?.length === cell.deps.length &&
+ deps.every((dep, i) => Object.is(dep, cell.deps[i]));
+ if (!same) {
+ cell.deps = deps;
+ cell.fn = fn;
+ }
+ return cell.fn;
+}
+
+export function useEffect(fn, deps) {
+ const index = cellIndex++;
+ const cell = cells[index] ?? (cells[index] = { deps: undefined, cleanup: undefined });
+ const same =
+ cell.deps !== undefined &&
+ deps?.length === cell.deps.length &&
+ deps.every((dep, i) => Object.is(dep, cell.deps[i]));
+ if (same) return;
+ cell.deps = deps;
+ if (typeof cell.cleanup === "function") cell.cleanup();
+ pendingEffects.push(() => {
+ cell.cleanup = fn();
+ });
+}