Skip to content

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

fix(plugins): preserve JSON setting strings across saves

Linuxdazhaoe9f88e2855b6
diff --git a/apps/desktop/src/components/plugins/PluginSettingsSheet.tsx b/apps/desktop/src/components/plugins/PluginSettingsSheet.tsx
index 9d86e4d78..add10dd9c 100644
--- a/apps/desktop/src/components/plugins/PluginSettingsSheet.tsx
+++ b/apps/desktop/src/components/plugins/PluginSettingsSheet.tsx
@@ -37,6 +37,9 @@ type Props = {
};
function initialValue(setting: PluginSettingDefinition): unknown {
+ if (setting.type === "json") {
+ return serializeJson(setting.value !== undefined ? setting.value : setting.default);
+ }
if (setting.value !== undefined) return setting.value;
if (setting.default !== undefined) return setting.default;
switch (setting.type) {
@@ -44,8 +47,6 @@ function initialValue(setting: PluginSettingDefinition): unknown {
return false;
case "number":
return 0;
- case "json":
- return {};
case "select":
return setting.enum?.[0]?.value ?? "";
default:
@@ -61,18 +62,13 @@ function shortcutLabel(value: unknown, platform: ShortcutPlatform): string {
function serializeJson(value: unknown): string {
try {
- return JSON.stringify(value ?? {}, null, 2);
+ return JSON.stringify(value === undefined ? {} : value, null, 2);
} catch {
return "{}";
}
}
-/**
- * A json setting's draft is the stored value until the user edits its
- * textarea, and the textarea text afterwards. Only text needs parsing:
- * `String({})` is `"[object Object]"`, so parsing an untouched object made
- * every save fail with "invalid JSON" for the first json setting.
- */
+/** JSON drafts start as serialized editor text, including stored strings. */
export function parseJsonSettingDraft(draft: unknown): unknown {
if (typeof draft !== "string") return draft ?? {};
const text = draft.trim();
diff --git a/apps/desktop/test/plugin-settings-json-roundtrip.test.mjs b/apps/desktop/test/plugin-settings-json-roundtrip.test.mjs
new file mode 100644
index 000000000..fd60bedb4
--- /dev/null
+++ b/apps/desktop/test/plugin-settings-json-roundtrip.test.mjs
@@ -0,0 +1,48 @@
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import { stripTypeScriptTypes } from "node:module";
+import test from "node:test";
+
+const sheet = await readFile(new URL("../src/components/plugins/PluginSettingsSheet.tsx", import.meta.url), "utf8");
+const helpers = sheet.slice(sheet.indexOf("function initialValue("), sheet.indexOf("export function PluginSettingsSheet("));
+const assignment = sheet.match(/payload\[setting\.key\] = [^\n]+;/)[0];
+const source = stripTypeScriptTypes(helpers) + `
+export { initialValue, serializeJson };
+export function submit(draft) {
+ const setting = { key: "json" };
+ const payload = { json: draft };
+ ${assignment}
+ return payload.json;
+}
+`;
+const { initialValue, serializeJson, submit } = await import("data:text/javascript," + encodeURIComponent(source));
+
+for (const value of ["hello", "42", "true", "null", "", null, false, 42, ["a"], { mode: "auto" }]) {
+ test(`JSON setting retains ${JSON.stringify(value)} across open/save/reset`, () => {
+ const setting = { key: "json", type: "json", value, default: value };
+ const opened = initialValue(setting);
+ assert.deepEqual(submit(opened), value, "an untouched save must preserve the stored JSON value and type");
+ const displayed = typeof opened === "string" ? opened : serializeJson(opened);
+ assert.equal(displayed, JSON.stringify(value, null, 2), "the textarea must contain valid JSON text");
+ const reset = initialValue({ ...setting, value: undefined });
+ assert.deepEqual(submit(reset), value, "reset must preserve the declared default's type");
+ assert.deepEqual(submit(initialValue({ ...setting, value: submit(JSON.stringify(value)) })), value,
+ "an edited value must survive save, reopen and another untouched save");
+ });
+}
+
+test("JSON settings without a stored value or default start as an empty object", () => {
+ assert.deepEqual(submit(initialValue({ key: "json", type: "json" })), {});
+});
+
+test("editing JSON still rejects malformed text and accepts objects and arrays", () => {
+ assert.throws(() => submit("{broken"), SyntaxError);
+ assert.deepEqual(submit('{"rules": ["a"]}'), { rules: ["a"] });
+ assert.deepEqual(submit('["b"]'), ["b"]);
+});
+
+test("other setting types retain their original initial values", () => {
+ for (const [type, value] of [["string", "hello"], ["number", 42], ["boolean", false]]) {
+ assert.equal(initialValue({ type, value }), value);
+ }
+});
diff --git a/apps/desktop/test/plugin-settings-json-user-path.test.mjs b/apps/desktop/test/plugin-settings-json-user-path.test.mjs
new file mode 100644
index 000000000..0a1788c7a
--- /dev/null
+++ b/apps/desktop/test/plugin-settings-json-user-path.test.mjs
@@ -0,0 +1,145 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { repositoryRoot, resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";
+
+const root = repositoryRoot();
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+const fixture = String.raw`
+import React from "react";
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { initReactI18next } from "react-i18next";
+import { catalogs, flattenCatalog } from "@pi-desktop/i18n";
+import { IPC } from "@pi-desktop/shared";
+import { PluginSettingsSheet } from "../../apps/desktop/src/components/plugins/PluginSettingsSheet";
+
+await i18n.use(initReactI18next).init({ lng: "en", keySeparator: false,
+ resources: { en: { translation: flattenCatalog(catalogs.en) } },
+ interpolation: { escapeValue: false } });
+const writes = [];
+window.piDesktop = { platform: "darwin", on() { return () => {}; },
+ async invoke(channel, payload) {
+ if (channel !== IPC.invoke.pluginSettingsSet) throw new Error("Unexpected IPC: " + channel);
+ writes.push(structuredClone(payload.settings));
+ return { ok: true, data: { settings: [] } };
+ } };
+const view = createRoot(document.getElementById("root"));
+let key = 0;
+let closed = 0;
+const frame = () => new Promise(requestAnimationFrame);
+const settle = async () => { await frame(); await frame(); };
+function check(ok, message) { if (!ok) throw new Error(message); }
+const textarea = () => document.querySelector("textarea");
+async function open(value, fallback = value) {
+ const plugin = { id: "fixture.json", name: "JSON fixture", settings: [
+ { key: "json", title: "JSON", type: "json", value, default: fallback },
+ { key: "enabled", title: "Enabled", type: "boolean", value: false },
+ ] };
+ flushSync(() => view.render(<PluginSettingsSheet key={++key} plugin={plugin}
+ platform="darwin" onSaved={() => {}} onClose={() => { closed++; }} />));
+ await settle();
+}
+async function save(expected) {
+ const count = writes.length;
+ const wasClosed = closed;
+ flushSync(() => document.querySelector(".plugins-modal-actions button:last-child").click());
+ await settle();
+ check(writes.length === count + 1, "save failed: " + document.body.textContent);
+ const actual = writes.at(-1).json;
+ check(JSON.stringify(actual) === JSON.stringify(expected),
+ "JSON value changed: expected " + JSON.stringify(expected) + " got " + JSON.stringify(actual));
+ check(closed === wasClosed + 1, "successful save did not close the sheet");
+ return actual;
+}
+function edit(text) {
+ flushSync(() => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value").set.call(textarea(), text);
+ textarea().dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+window.jsonSettingsProbe = async () => {
+ for (const value of ["42", "hello", "true", "null", "", null, false, 42, ["a"], { mode: "auto" }]) {
+ await open(value);
+ const saved = await save(value);
+ await open(saved);
+ check(textarea().value === JSON.stringify(value, null, 2), "reopened editor lost JSON representation");
+ await save(value);
+ }
+ await open("original", "true");
+ edit(JSON.stringify("edited"));
+ await save("edited");
+ await open("edited", "true");
+ flushSync(() => document.querySelector(".plugins-setting-reset").click());
+ await save("true");
+ await open("safe");
+ edit("{broken");
+ const count = writes.length;
+ flushSync(() => document.querySelector(".plugins-modal-actions button:last-child").click());
+ await settle();
+ check(writes.length === count && document.querySelector('[role="alert"]'), "invalid JSON was not rejected");
+ check(textarea().value === "{broken", "validation erased the draft");
+ flushSync(() => view.unmount());
+ return { passed: true, saves: writes.length };
+};
+`;
+
+test("JSON settings keep their type through the real sheet save/reopen/reset path", {
+ skip: process.platform === "linux" && !process.env.DISPLAY ? "Electron requires a display" : false,
+}, async () => {
+ const temp = await mkdtemp(join(tmpdir(), "pi-plugin-json-ui-"));
+ try {
+ await build({
+ stdin: { contents: fixture, resolveDir: join(root, "scripts/e2e"), loader: "tsx" },
+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "esm", jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"' },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src"),
+ "@pi-desktop/shared": join(root, "packages/shared/src"),
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ i18next: join(root, "apps/desktop/node_modules/i18next"),
+ "react-i18next": join(root, "apps/desktop/node_modules/react-i18next"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ await writeFile(join(temp, "index.html"), '<!doctype html><div id="root"></div><script type="module" src="renderer.js"></script>');
+ await writeFile(join(temp, "main.cjs"), `
+const { app, BrowserWindow } = require("electron");
+const path = require("node:path");
+app.setPath("userData", path.join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({ show: false, webPreferences: {
+ sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ try {
+ await win.loadFile(path.join(__dirname, "index.html"));
+ console.log("JSON_SETTINGS_PROBE " + JSON.stringify(await win.webContents.executeJavaScript("window.jsonSettingsProbe()")));
+ app.exit(0);
+ } catch (error) { console.error(error?.stack ?? error); app.exit(1); }
+});`);
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], {
+ env, stdio: ["ignore", "pipe", "pipe"],
+ });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) {
+ stream.setEncoding("utf8");
+ stream.on("data", (chunk) => { output += chunk; });
+ }
+ const timer = setTimeout(() => child.kill("SIGKILL"), 45_000);
+ let code;
+ try {
+ code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); });
+ } finally { clearTimeout(timer); }
+ assert.equal(code, 0, output.slice(-6000));
+ assert.match(output, /JSON_SETTINGS_PROBE .*"passed":true,"saves":22/);
+ } finally {
+ await rm(temp, { recursive: true, force: true });
+ }
+});
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 1d4aceb69..8c283ef1b 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -10483,17 +10483,25 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
normal field and the shortcut, then save. 3) Reload the plugin list and press
the new shortcut while the app window is focused. 4) Try a reserved app
shortcut and repeat with the plugin scoped away from the current project.
+ 5) For JSON fields, save, reopen and save again with `"hello"`, `"42"`,
+ `"true"`, `"null"`, `""`, a null default, a number, a boolean, an array and an
+ object. Edit a JSON string, reset to a string default, and submit malformed
+ JSON before correcting it.
- **Expected**: Controls are generated from the manifest, values persist in the
plugin-private settings file, and `plugin:settingsChanged` is delivered. The
new shortcut invokes the plugin command only in the focused app window and
matching activation scope. Reserved/conflicting bindings are rejected; no OS
- global shortcut is registered.
+ global shortcut is registered. JSON strings remain quoted in the editor and
+ retain their type after save/reopen/reset. Invalid JSON leaves the draft and
+ sheet open without an IPC settings write.
- **Specs linked**: `07-plugins/02-plugin-manifest-schema.md`,
`07-plugins/03-plugin-api.md`, `07-plugins/11-plugin-storage-isolation.md`,
ADR 0159
- **Acceptance**: F (persistence), G (plugins), Security, Quality
- **Milestone**: M6+
-- **Status**: Source-contract and focused integration coverage; full desktop
+- **Status**: Source-contract and focused integration coverage. JSON
+ save/reopen/edit/reset is covered by `plugin-settings-json-user-path.test.mjs`
+ in an isolated Electron renderer with a settings IPC fixture; full desktop
journey Draft (run only in a capable environment when this surface changes)
#### E2E-OAUTH-anthropic-rate-limit-retry: Bounded token retries preserve the account
diff --git a/docs/spec/07-plugins/02-plugin-manifest-schema.md b/docs/spec/07-plugins/02-plugin-manifest-schema.md
index a781e2466..8d978a70e 100644
--- a/docs/spec/07-plugins/02-plugin-manifest-schema.md
+++ b/docs/spec/07-plugins/02-plugin-manifest-schema.md
@@ -671,7 +671,13 @@ the oldest host you claim. Export `onLoad` / `onUnload` from `main`; there is no
`skills` is the exception — it predates the permission gate, so a manifest
without `agent.prompt.inject` still validates and the runtime simply skips
the skills
-13. Settings keys are unique. `shortcut` settings require `command`, may only
+13. JSON settings accept JSON-serializable values, including strings and null.
+ The generated editor initializes JSON fields as serialized JSON text on
+ open, settings refresh and reset. Saving parses that text once, preserving
+ the supplied value's type across reopen; a string such as `"42"` remains a
+ string. Missing JSON values/defaults use `{}`. Invalid edits retain the
+ draft and prevent submission. Non-JSON setting types retain their controls.
+ Settings keys are unique. `shortcut` settings require `command`, may only
use the `plugin` scope, and are validated as modifier-plus-key or F-key
bindings. Secrets are rejected until secure plugin-secret storage exists.
14. `fs.<mode>` requires the matching `fs.<mode>` permission — a scope nobody can