Skip to content

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

fix(composer): notify the renderer after a subagent style write

Tioit-Wang2857aee1336e
diff --git a/apps/desktop/electron/main/ipc/settings-ipc.ts b/apps/desktop/electron/main/ipc/settings-ipc.ts
index 19b5b10c3..fcd1b6b88 100644
--- a/apps/desktop/electron/main/ipc/settings-ipc.ts
+++ b/apps/desktop/electron/main/ipc/settings-ipc.ts
@@ -80,13 +80,15 @@ export function registerSettingsIpc({
? { ...currentSettings, ...(validatedSettings as Partial<AppSettings>) }
: currentSettings;
const releaseSettingsWrite = liveCallService?.beginSettingsWrite(prospectiveSettings);
- let result: AppSettings;
+ let result: { ok: true };
try {
- result = await host.call<AppSettings>("settings.set", validatedSettings);
- if (isSubagentStyle(result.subagentStyle) && result.subagentStyle !== currentSettings.subagentStyle) {
- sendToRenderer(IPC.event.settingsChanged, { subagentStyle: result.subagentStyle });
+ result = await host.call<{ ok: true }>("settings.set", validatedSettings);
+ // settings.set acknowledges the write; it does not return the stored settings.
+ const style = validatedSettings?.subagentStyle;
+ if (isSubagentStyle(style)) {
+ sendToRenderer(IPC.event.settingsChanged, { subagentStyle: style });
}
- await liveCallService?.settingsWritten(result);
+ await liveCallService?.settingsWritten(prospectiveSettings);
} finally {
releaseSettingsWrite?.();
}
diff --git a/docs/public/screenshots/subagent-presence/bar-light-collapsed.png b/docs/public/screenshots/subagent-presence/bar-light-collapsed.png
new file mode 100644
index 000000000..b50caa5dc
Binary files /dev/null and b/docs/public/screenshots/subagent-presence/bar-light-collapsed.png differ
diff --git a/docs/public/screenshots/subagent-presence/card-dark-reduced-motion.png b/docs/public/screenshots/subagent-presence/card-dark-reduced-motion.png
new file mode 100644
index 000000000..53935664a
Binary files /dev/null and b/docs/public/screenshots/subagent-presence/card-dark-reduced-motion.png differ
diff --git a/docs/public/screenshots/subagent-presence/transcript-light.png b/docs/public/screenshots/subagent-presence/transcript-light.png
new file mode 100644
index 000000000..500747524
Binary files /dev/null and b/docs/public/screenshots/subagent-presence/transcript-light.png differ
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index d99e0981e..ee861bf23 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -151,6 +151,10 @@ workspace packages here. If the primary installation is stale, pass the path of
another checkout of this repository with matching installed dependencies and
keep it until the consuming worktree is removed. If none matches, use an
isolated install. Never install, prune, or rebuild through shared links.
+The helper copies mutable `.bin` shims locally. Before `pnpm run` or `pnpm exec`,
+set `pnpm_config_verify_deps_before_run=false` in the command environment to
+prevent pnpm from automatically installing into the linked layout (PowerShell:
+`$env:pnpm_config_verify_deps_before_run='false'`).
Use the root `package.json` as the source of truth for executable commands.
The minimum selection is:
diff --git a/docs/spec/06-delivery/e2e/conversation.md b/docs/spec/06-delivery/e2e/conversation.md
index 667135b4c..15deb5146 100644
--- a/docs/spec/06-delivery/e2e/conversation.md
+++ b/docs/spec/06-delivery/e2e/conversation.md
@@ -11,6 +11,10 @@ Escape. Stop a worker while another runs: its settled status remains visible;
after the last worker settles the entire row disappears. Switch sessions and
restart to verify isolation and the saved presentation preference.
+Production Electron captures (local streaming fixture): [Transcript only](/screenshots/subagent-presence/transcript-light.png), [Light, task dock collapsed](/screenshots/subagent-presence/bar-light-collapsed.png), [Dark, reduced motion](/screenshots/subagent-presence/card-dark-reduced-motion.png).
+Set `PI_SUBAGENT_SCREENSHOT_DIR` when running `node scripts/e2e-subagent-stop.mjs`
+to capture the same states.
+
## E2E-stop-navigation-running-state
Hold the history read after a successful local Stop, switch to another running session, then resolve the older session's history. Verify only the stopped session is settled, the new transcript remains and its toolbar still offers Stop. Also navigate synchronously during the hydration commit to exercise the final state writer. Coverage: `stop-navigation-running-state.test.mjs`, related smart-stop/terminal regressions, and `scripts/e2e-stop-navigation-running-state.mjs` using the production store and ComposerToolbar in Electron.
diff --git a/scripts/e2e-subagent-stop.mjs b/scripts/e2e-subagent-stop.mjs
index aba9cd5d3..74cbce62f 100644
--- a/scripts/e2e-subagent-stop.mjs
+++ b/scripts/e2e-subagent-stop.mjs
@@ -11,7 +11,7 @@ import { resolveHostBinary } from "./e2e/host.mjs";
const root = repositoryRoot();
const show = process.argv.includes("--show");
-const scratch = await mkdtemp(join(tmpdir(), "pi-subagent-stop-"));
+const scratch = await mkdtemp(join(process.env.PI_SCRATCH_DIR || tmpdir(), "pi-subagent-stop-"));
const workspace = join(scratch, "workspace");
await mkdir(workspace);
await mkdir(join(scratch, "home"));
@@ -49,7 +49,13 @@ const server = createServer(async (req, res) => {
res.write(": coordinator still working\n\n");
return;
}
- const calls = body.tools?.some(tool => tool.function?.name === "Task")
+ const offered = name => body.tools?.some(tool => tool.function?.name === name);
+ const needTodo = !tools.some(message => message.tool_call_id === "fixture_todo");
+ const calls = needTodo
+ ? offered("TodoWrite")
+ ? [{ id: "fixture_todo", name: "TodoWrite", arguments: { todos: [{ content: "Inspect fixture workers", status: "in_progress" }] } }]
+ : [{ id: "discover_todo", name: "ToolSearch", arguments: { query: "TodoWrite" } }]
+ : body.tools?.some(tool => tool.function?.name === "Task")
? ["A", "B"].map(label => ({ id: `task_${label}`, name: "Task", arguments: { agent: "explorer", task: `Fixture worker ${label}`, description: `Worker ${label}` } }))
: [{ id: "discover", name: "ToolSearch", arguments: { query: "Task" } }];
delta({ role: "assistant", tool_calls: calls.map((call, index) => ({ index, id: call.id, type: "function", function: { name: call.name, arguments: JSON.stringify(call.arguments) } })) });
@@ -122,17 +128,27 @@ async function connect(port, type) {
} };
}
const ports = [await freePort(), await freePort()];
-const env = { ...process.env, HOME: join(scratch, "home"), PI_DESKTOP_DATA_DIR: join(scratch, "data"), PI_DESKTOP_HOST_BIN: resolveHostBinary(), PI_DESKTOP_PLAN_UI_PROBE: "1", PI_DESKTOP_TEST_API_KEY: "local-fixture", PI_DESKTOP_TEST_BASE_URL: `http://127.0.0.1:${server.address().port}/v1`, PI_DESKTOP_TEST_MODEL: "deepseek-flash", ELECTRON_RENDERER_URL: "", PI_DESKTOP_START_MAXIMIZED: "0" };
+const home = join(scratch, "home");
+// Do not pass a running Desktop's plugin paths, model credentials or control endpoints to the fixture.
+const systemEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) =>
+ /^(PATH|PATHEXT|SystemRoot|WINDIR|ComSpec|SystemDrive|TEMP|TMP|TMPDIR|LANG|LC_.*|DISPLAY|WAYLAND_DISPLAY|XAUTHORITY|XDG_RUNTIME_DIR|DBUS_SESSION_BUS_ADDRESS)$/i.test(key)));
+const env = { ...systemEnv, HOME: home, USERPROFILE: home, XDG_CONFIG_HOME: join(home, ".config"),
+ PI_CODING_AGENT_DIR: join(home, ".pi", "agent"), PI_DESKTOP_AGENTS_DIR: join(home, ".agents"), PI_DESKTOP_DATA_DIR: join(scratch, "data"), PI_DESKTOP_HOST_BIN: resolveHostBinary(), PI_DESKTOP_PLAN_UI_PROBE: "1", PI_DESKTOP_TEST_API_KEY: "local-fixture", PI_DESKTOP_TEST_BASE_URL: `http://127.0.0.1:${server.address().port}/v1`, PI_DESKTOP_TEST_MODEL: "deepseek-flash", ELECTRON_RENDERER_URL: "", PI_DESKTOP_START_MAXIMIZED: "0" };
if (process.platform === "win32") {
env.USERPROFILE = env.HOME;
env.APPDATA = join(scratch, "roaming");
env.LOCALAPPDATA = join(scratch, "local");
}
delete env.ELECTRON_RUN_AS_NODE;
-const child = spawn(resolveElectronBinary(root).electronBinary, [`--remote-debugging-port=${ports[0]}`, `--inspect=${ports[1]}`, `--user-data-dir=${join(scratch, "profile")}`, "."], { cwd: join(root, "apps/desktop"), env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32" });
+const launch = () => spawn(resolveElectronBinary(root).electronBinary, [`--remote-debugging-port=${ports[0]}`, `--inspect=${ports[1]}`, `--user-data-dir=${join(scratch, "profile")}`, "."], { cwd: join(root, "apps/desktop"), env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32" });
let output = "";
-child.stdout.on("data", chunk => { output += chunk; });
-child.stderr.on("data", chunk => { output += chunk; });
+function start() {
+ const child = launch();
+ child.stdout.on("data", chunk => { output += chunk; });
+ child.stderr.on("data", chunk => { output += chunk; });
+ return child;
+}
+let child = start();
let main, page;
try {
main = await connect(ports[1], "node");
@@ -148,7 +164,12 @@ try {
const setup = await main.evaluate(`globalThis.__PI_DESKTOP_PLAN_UI_PROBE({operation:'liveSetup',workspace:${JSON.stringify(workspace)}})`);
assert.equal(setup.ok, true, JSON.stringify(setup));
const invoke = (key, ...input) => page.evaluate(`piDesktop.invoke(piDesktop.channels.invoke[${JSON.stringify(key)}],...${JSON.stringify(input)})`);
- assert.equal((await invoke("settingsSet", { transcriptDisplayMode: "flat" })).ok, true);
+ const mcp = await invoke("mcpList", { projectPath: workspace });
+ assert.ok(mcp.ok && mcp.data.servers.length === 0, "fixture must not load user MCP servers");
+ const agents = await invoke("subagentList");
+ assert.ok(agents.ok && agents.data.subagents.length === 0, "fixture must not load user agent definitions");
+ await page.evaluate("window.__PI_DESKTOP__.skipStartupOverlays()");
+ assert.equal((await invoke("settingsSet", { transcriptDisplayMode: "command-first" })).ok, true);
assert.equal((await invoke("providersUpdate", { id: setup.providerId, models: [{ id: setup.modelId, contextWindow: 128000, maxTokens: 8192, thinkingLevels: ["off", "medium"], defaultThinkingLevel: "medium" }] })).ok, true);
assert.equal((await invoke("sessionConfigure", setup.sessionId, { mode: "agent", providerId: setup.providerId, modelId: setup.modelId, thinkingLevel: "medium" })).ok, true);
await invoke("sessionRename", setup.sessionId, "Subagent stop controls · local fixture");
@@ -162,6 +183,16 @@ try {
const bar = '.composer-shell > .subagent-bar:first-child';
const barVisible = () => page.evaluate(`!!document.querySelector(${JSON.stringify(bar)})`);
assert.equal(await barVisible(), false, "transcript-only is the default");
+ const capture = async name => {
+ const dir = process.env.PI_SUBAGENT_SCREENSHOT_DIR;
+ if (!dir) return;
+ await mkdir(dir, { recursive: true });
+ const clip = await page.evaluate(`{ const r = document.querySelector('.composer-dock').getBoundingClientRect(); const y = Math.max(0, r.top - 320); ({ x: r.left, y, width: r.width, height: Math.min(innerHeight, r.bottom) - y, scale: 1 }); }`);
+ const shot = await page.call("Page.captureScreenshot", { format: "png", clip });
+ await writeFile(join(dir, `${name}.png`), Buffer.from(shot.data, "base64"));
+ };
+ await page.evaluate(`window.__PI_DESKTOP__.setThemeAttr('light')`);
+ await capture("transcript-light");
const settings = await invoke("settingsGet");
assert.equal(settings.ok, true);
const setStyle = async subagentStyle => {
@@ -176,9 +207,32 @@ try {
await until(async () => !await barVisible(), "switching back removes the entire bar");
await setStyle("bar");
await until(barVisible, "restored presence bar");
+ const other = await invoke("sessionCreate", { title: "Idle fixture", mode: "agent", projectPath: workspace });
+ assert.equal(other.ok, true);
+ const select = id => page.evaluate(`window.__PI_DESKTOP__.selectSession(${JSON.stringify(id)})`);
+ await select(other.data.session.id);
+ await until(async () => !await barVisible(), "idle session does not inherit the active delegates");
+ await select(setup.sessionId);
+ await until(barVisible, "returning to the running session restores its delegates");
+ const dock = '.composer-dock .dock-header-main';
+ await until(() => page.evaluate(`!!document.querySelector('${dock}')`), "fixture task dock");
+ for (const expanded of [true, false]) {
+ await page.evaluate(`{ const b = document.querySelector('${dock}'); if (b.getAttribute('aria-expanded') !== '${expanded}') b.click(); }`);
+ await until(() => page.evaluate(`document.querySelector('${dock}').getAttribute('aria-expanded') === '${expanded}' && document.querySelector('${bar}').getBoundingClientRect().height > 0`), "presence independent of dock disclosure");
+ }
+ const motion = reduce => page.call("Emulation.setEmulatedMedia", { features: [{ name: "prefers-reduced-motion", value: reduce ? "reduce" : "no-preference" }] });
+ const ring = () => page.evaluate(`getComputedStyle(document.querySelector('.presence-avatar[data-status="running"]'), '::before').animationName`);
+ await motion(false);
+ assert.equal(await ring(), "presence-spin");
+ await capture("bar-light-collapsed");
+ await motion(true);
+ assert.equal(await ring(), "none");
+ await page.evaluate(`window.__PI_DESKTOP__.setThemeAttr('dark')`);
await page.evaluate(`document.querySelector('.presence-avatar').focus()`);
await until(() => page.evaluate(`!!document.querySelector('.presence-card footer button')`), "focus opens delegate card");
assert.equal(await page.evaluate(`document.querySelector('.presence-card').closest('.composer-shell') === null`), true);
+ assert.equal(await page.evaluate(`getComputedStyle(document.querySelector('.presence-live')).animationName`), "none");
+ await capture("card-dark-reduced-motion");
await page.evaluate(`document.querySelector('.presence-card footer button').click()`);
await until(() => page.evaluate(`!!document.querySelector('.subagent-transcript-composer-controls .stop-btn')`), "detail stop control");
await until(() => page.evaluate(`document.body.innerText.includes('Partial output from worker A')`), "worker A partial output rendered");
@@ -253,11 +307,20 @@ try {
console.log(`DEMO ${JSON.stringify({ scratch, ports, pid: child.pid })}`);
main.ws.close();
await new Promise(resolve => child.once("exit", resolve));
+ } else {
+ main.ws.close(); page.ws.close();
+ await terminateChildTree(child);
+ child = start();
+ page = await connect(ports[0], "page");
+ await until(() => page.evaluate("!!window.__PI_DESKTOP__"), "restarted renderer");
+ assert.equal((await invoke("settingsGet")).data.subagentStyle, "bar", "style survives Desktop restart");
+ assert.equal(await barVisible(), false, "saved style does not add an empty row");
+ console.log("PASS session isolation, restart persistence, themes, dock disclosure and reduced motion");
}
} finally {
main?.ws.close(); page?.ws.close();
await terminateChildTree(child);
server.closeAllConnections();
await new Promise(resolve => server.close(resolve));
- if (!show) await rm(scratch, { recursive: true, force: true });
+ if (!show) await rm(scratch, { recursive: true, force: true, maxRetries: 8, retryDelay: 200 });
}
diff --git a/scripts/reuse-worktree-deps.mjs b/scripts/reuse-worktree-deps.mjs
index f0f3e397e..22caa5f71 100644
--- a/scripts/reuse-worktree-deps.mjs
+++ b/scripts/reuse-worktree-deps.mjs
@@ -1,6 +1,6 @@
-// Run from a fresh request worktree. Links only; never install against this layout.
+// Run from a fresh request worktree. Never install against this shared layout.
import { execFileSync } from "node:child_process";
-import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, symlinkSync } from "node:fs";
+import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, symlinkSync } from "node:fs";
import { dirname, join } from "node:path";
const git = (...args) => execFileSync("git", args, { encoding: "utf8" }).trim();
@@ -27,6 +27,7 @@ if (projectLock(installedLock) !== projectLock(join(root, "pnpm-lock.yaml"))) th
const packages = inputs.filter(path => /^(?:(?:apps|packages)\/[^/]+|docs)\/package\.json$/.test(path));
const workspace = new Map(packages.map(file => [JSON.parse(readFileSync(join(root, file), "utf8")).name, join(root, dirname(file))]));
const links = [];
+const binDirs = [];
const directories = [];
for (const folder of [".", ...packages.map(dirname)]) {
const source = join(main, folder, "node_modules");
@@ -45,6 +46,9 @@ for (const folder of [".", ...packages.map(dirname)]) {
if (!target) throw new Error(`Unknown workspace package @pi-desktop/${name}`);
links.push([target, join(to, name)]);
}
+ } else if (entry.name === ".bin") {
+ // pnpm can regenerate shims even during `exec`; never share writable bins.
+ binDirs.push([from, to]);
} else if (entry.isDirectory() || entry.isSymbolicLink()) {
links.push([realpathSync(from), to]);
}
@@ -52,5 +56,7 @@ for (const folder of [".", ...packages.map(dirname)]) {
}
for (const dir of directories) mkdirSync(dir);
for (const [target, path] of links) symlinkSync(target, path, process.platform === "win32" ? "junction" : "dir");
+for (const [from, to] of binDirs) cpSync(realpathSync(from), to, { recursive: true, verbatimSymlinks: true });
console.log(`Linked ${links.length} dependency directories. Workspace packages resolve inside ${root}.`);
console.log("Build workspace packages here. Do not install, prune, or rebuild shared dependencies through these links.");
+console.log("For pnpm run/exec, set pnpm_config_verify_deps_before_run=false to disable automatic installs.");
diff --git a/scripts/reuse-worktree-deps.test.mjs b/scripts/reuse-worktree-deps.test.mjs
index c867055cb..052b75a30 100644
--- a/scripts/reuse-worktree-deps.test.mjs
+++ b/scripts/reuse-worktree-deps.test.mjs
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
-import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -22,7 +22,8 @@ test("reuse refuses incompatible or existing installs and resolves internal pack
git("add", "packages/shared/package.json", "pnpm-lock.yaml");
git("-c", "user.name=Test", "-c", "[email protected]", "-c", "commit.gpgsign=false", "commit", "-m", "Fixture");
git("worktree", "add", "--detach", wt, "HEAD");
- for (const path of [".pnpm/react", "@pi-desktop"]) mkdirSync(join(main, "node_modules", path), { recursive: true });
+ for (const path of [".pnpm/react", "@pi-desktop", ".bin"]) mkdirSync(join(main, "node_modules", path), { recursive: true });
+ writeFileSync(join(main, "node_modules/.bin/tool"), "original shim");
writeFileSync(join(main, "node_modules/.pnpm/lock.yaml"), "lock");
const kind = process.platform === "win32" ? "junction" : "dir";
symlinkSync(join(main, "packages/shared"), join(main, "node_modules/@pi-desktop/shared"), kind);
@@ -38,5 +39,9 @@ test("reuse refuses incompatible or existing installs and resolves internal pack
assert.equal(result.status, 0, result.stderr);
assert.equal(realpathSync.native(join(wt, "node_modules/react")), realpathSync.native(join(main, "node_modules/react")));
assert.equal(realpathSync.native(join(wt, "node_modules/@pi-desktop/shared")), realpathSync.native(join(wt, "packages/shared")));
+ const localShim = join(wt, "node_modules/.bin/tool");
+ assert.equal(readFileSync(localShim, "utf8"), "original shim");
+ writeFileSync(localShim, "regenerated shim");
+ assert.equal(readFileSync(join(main, "node_modules/.bin/tool"), "utf8"), "original shim");
assert.match(run(wt).stderr, /Refusing to overwrite/);
});