Skip to content

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

fix(projects): preserve editor drafts during background updates

yuxinocf0ff49cb4c5
diff --git a/apps/desktop/src/components/ProjectEditDialog.tsx b/apps/desktop/src/components/ProjectEditDialog.tsx
index 7687bb340..58a57288b 100644
--- a/apps/desktop/src/components/ProjectEditDialog.tsx
+++ b/apps/desktop/src/components/ProjectEditDialog.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useEffectEvent, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import type { ProjectGroupRecord, ProjectGroupRoot } from "@pi-desktop/shared";
@@ -66,6 +66,7 @@ export function ProjectEditDialog({
const dialogRef = useRef<HTMLDivElement | null>(null);
const busyRef = useRef(false);
const folderPickerInFlightRef = useRef(false);
+ const reportLoadError = useEffectEvent((error: unknown) => onError(error));
useEffect(() => {
let cancelled = false;
@@ -97,13 +98,13 @@ export function ProjectEditDialog({
.catch((error) => {
if (!cancelled) {
setLoading(false);
- onError(error);
+ reportLoadError(error);
}
});
return () => {
cancelled = true;
};
- }, [onError, project.groupId, project.path, t]);
+ }, [project.groupId, project.path, t]);
useEffect(() => {
const previouslyFocused = document.activeElement as HTMLElement | null;
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 12ecac6ad..2111fc9da 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -526,7 +526,8 @@ visually distinct from list content.
accent-tinted focus ring, not an outline stroke. Edit project reuses the same
surface, loads the host-owned group, allows the name and non-primary folders
to be adjusted, keeps Primary first and non-removable, and rejects removal of
- a folder that still owns chats. The source selector offers This computer and
+ a folder that still owns chats. Background session or run-status updates
+ must preserve unsaved name and folder edits in the open editor. The source selector offers This computer and
Git repository as equal filled tiles without strokes (D297); the active source
uses a deeper tile, not a selected border. A repository URL reuses the clone
rules of ADR 0247 and its checkout becomes the primary root of the same group.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 0aa54929f..31ec3e2d4 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -3079,6 +3079,11 @@ identify the platform validation still needed.
again with the native folder picker. 3) Confirm the Primary row cannot be
removed. 4) Save and inspect the sidebar row, Project archive roots, and
active workspace. 5) Restart the app and inspect the group again.
+- **Background-update regression**: Open Edit project from Settings, change the
+ name and remove the additional folder, then complete a background task before
+ saving. Both draft edits must remain visible and save together. The isolated
+ rendered test is `node scripts/e2e-project-edit.mjs`; it uses real page/store
+ wiring with a controlled host IPC boundary and does not prove disk persistence.
- **Expected**: Both project menus offer Edit project. The editor keeps focus
contained, trims the name, limits it to 80 Unicode characters, preserves the
Primary folder as the first row, and updates the root count without removing
diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.md
index bf720f1be..ada2bc33e 100644
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@ -516,6 +516,8 @@ expanded/collapsed 侧边栏仍为 20px/18px 且启动画面为 64 像素。
侧边栏与本机交通信号灯位于同一 46 像素行中。全屏保留
品牌在回收原生镀铬填充物时隐藏起来。
+- 项目编辑器打开期间,后台会话或运行状态更新必须保留尚未保存的名称和文件夹修改。
+
### 3.8 MVP 约束
- 全局搜索从会话顶栏、键盘快捷键和应用菜单打开;
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.md
index 35e0ca654..262df5108 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
@@ -1791,6 +1791,10 @@ hover/focus 不带移位标签,项目标题 hover/focus 路径显示
- **步骤**:1) 打开侧边栏项目溢出菜单并选择“编辑项目”。2) 修改名称,移除
附加文件夹,再通过原生文件夹选择器将其添加回来。3) 确认 Primary 行不能移除。
4) 保存并检查侧边栏、项目存档中的根目录和当前工作区。5) 重启应用并再次检查项目组。
+- **后台更新回归**:从设置打开编辑项目,修改名称并移除附加文件夹,然后在保存前
+ 完成一个后台任务。两项草稿修改必须保留,并一起保存。隔离渲染测试为
+ `node scripts/e2e-project-edit.mjs`;使用真实页面和 store,仅控制 host IPC 边界,
+ 不代表已验证磁盘持久化。
- **预期**:两个项目菜单都提供编辑项目;编辑器保持焦点、去除首尾空格并限制为
80 个 Unicode 字符,Primary 文件夹始终是第一行,根目录数量更新且不会误删其他行。
保存后仍是一个逻辑项目组,调整后的根目录会持久化;名称在重启后保留,规范化
diff --git a/package.json b/package.json
index 4bb784178..b99035c71 100644
--- a/package.json
+++ b/package.json
@@ -33,6 +33,7 @@
"test:e2e:transcript-disclosure": "node scripts/e2e-transcript-disclosure-anchor.mjs",
"test:e2e:images": "node scripts/e2e-image-generation.mjs && node scripts/e2e-image-generation-ui.mjs && node scripts/e2e-image-chat.mjs",
"test:e2e:provider-order": "node scripts/e2e-provider-order.mjs",
+ "test:e2e:project-edit": "node scripts/e2e-project-edit.mjs",
"test:e2e:provider-api-style": "node scripts/e2e-provider-api-style.mjs",
"test:e2e:oauth-retry": "node --test apps/desktop/test/anthropic-oauth-retry.test.mjs",
"test:e2e:boot": "node scripts/e2e-electron-boot.mjs",
diff --git a/scripts/e2e-project-edit.mjs b/scripts/e2e-project-edit.mjs
new file mode 100644
index 000000000..64f66d443
--- /dev/null
+++ b/scripts/e2e-project-edit.mjs
@@ -0,0 +1,83 @@
+#!/usr/bin/env node
+/** Real ProjectsPage/editor integration; only the host IPC boundary is a fixture. */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const require = createRequire(join(root, "packages/agent-runtime/package.json"));
+const { build } = require("esbuild");
+const interactive = process.argv.includes("--interactive");
+const temp = await mkdtemp(join(tmpdir(), "pi-project-edit-"));
+await build({
+ entryPoints: [join(root, "scripts/e2e/project-edit.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/index.ts"),
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom") },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+});
+const styles = ["tokens", "base", "ui-kit", "overlays", "settings", "projects", "project-create-dialog"];
+await writeFile(join(temp, "styles.css"), (await Promise.all(styles.map(name =>
+ readFile(join(root, `apps/desktop/src/styles/${name}.css`), "utf8"))))
+ .join("\n").replace(/@theme(?: inline)?/g, ":root") + `
+ body { margin: 0; background: #f7f7f7; }
+ .fixture-page { padding: 120px 60px 30px; height: 100vh; overflow: auto; }
+ .fixture-controls { position: fixed; z-index: 2147483647; inset: 0 0 auto;
+ display: flex; align-items: center; gap: 18px; padding: 14px 24px;
+ background: #171717; color: white; font: 13px system-ui; }
+ .fixture-controls button { background: white; color: #171717; padding: 8px 12px; border-radius: 6px; }
+ .fixture-controls small { margin-left: auto; color: #ccc; }
+`);
+await writeFile(join(temp, "index.html"), `<!doctype html><html lang="en"><meta charset="utf-8">
+<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:">
+<link rel="stylesheet" href="styles.css"><body><div id="root"></div><script type="module" src="renderer.js"></script></body></html>`);
+await writeFile(join(temp, "preload.cjs"), `const {contextBridge,ipcRenderer}=require('electron');
+contextBridge.exposeInMainWorld('piDesktop',{invoke:(channel,...args)=>ipcRenderer.invoke(channel,...args)});`);
+await writeFile(join(temp, "main.cjs"), `
+const {app,BrowserWindow,ipcMain}=require('electron');
+const path=require('node:path');
+app.setPath('userData',path.join(__dirname,'profile'));
+let group={id:'website',name:'Website',primaryPath:'/fixture/website',lastOpenedAt:1,pinned:false,
+ roots:[{path:'/fixture/website',name:'website',position:0},{path:'/fixture/assets',name:'assets',position:1}]};
+ipcMain.handle('pi-desktop/project-group/list',()=>({ok:true,data:{groups:[group]}}));
+ipcMain.handle('pi-desktop/project-group/update',(_event,input)=>{
+ group={...group,name:input.name,roots:input.folders.map((p,i)=>({path:p,name:path.basename(p),position:i}))};
+ return {ok:true,data:{group}};
+});
+app.whenReady().then(async()=>{
+ const win=new BrowserWindow({title:'Project editor regression',width:1280,height:900,show:${interactive},
+ webPreferences:{preload:path.join(__dirname,'preload.cjs'),contextIsolation:true,sandbox:true,nodeIntegration:false,backgroundThrottling:false}});
+ win.webContents.on('console-message',event=>console.error(event.message));
+ await win.loadFile(path.join(__dirname,'index.html'));
+ ${interactive ? "console.log('PROJECT_EDIT_INTERACTIVE '+__dirname);" : `try {
+ const result=await win.webContents.executeJavaScript('projectEditProbe()');
+ console.log('PROJECT_EDIT_PROBE '+JSON.stringify(result));
+ app.exit(result.ok?0:1);
+ } catch(error){console.error(error);app.exit(1);}`}
+});
+app.on('window-all-closed',()=>app.quit());
+`);
+const electronBinary = process.env.PI_DESKTOP_ELECTRON_BIN ?? resolveElectronBinary(root).electronBinary;
+const env = { ...process.env };
+delete env.ELECTRON_RUN_AS_NODE;
+const child = spawn(electronBinary, [join(temp, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });
+let output = "";
+for (const stream of [child.stdout, child.stderr]) stream.on("data", data => {
+ output += data;
+ if (interactive) process.stdout.write(data);
+});
+const timeout = interactive ? null : setTimeout(() => child.kill("SIGTERM"), 30000);
+const code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); });
+if (timeout) clearTimeout(timeout);
+if (!interactive) {
+ const line = output.split(/\r?\n/).find(line => line.startsWith("PROJECT_EDIT_PROBE "));
+ console.log(line ?? output.slice(-3000));
+ assert.equal(code, 0, output.slice(-3000));
+}
diff --git a/scripts/e2e/project-edit.tsx b/scripts/e2e/project-edit.tsx
new file mode 100644
index 000000000..ffac5f0f7
--- /dev/null
+++ b/scripts/e2e/project-edit.tsx
@@ -0,0 +1,100 @@
+import { createRoot } from "react-dom/client";
+import { createInstance } from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { en } from "@pi-desktop/i18n";
+import { api } from "../../apps/desktop/src/lib/api";
+import { ProjectsPage } from "../../apps/desktop/src/pages/ProjectsPage";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+
+declare global {
+ var projectEditProbe: () => Promise<unknown>;
+}
+
+const i18n = createInstance();
+await i18n.init({ lng: "en", resources: { en: { translation: en } }, initImmediate: false });
+useAppStore.setState({
+ sessions: [],
+ workspace: null,
+ openProjectPaths: ["/fixture/website"],
+ projectMeta: {},
+ runningSessions: { background: true },
+});
+
+function completeTask() {
+ useAppStore.setState({ runningSessions: { background: false } });
+ document.getElementById("background-status")!.textContent = "Background task completed";
+}
+
+createRoot(document.getElementById("root")!).render(
+ <I18nextProvider i18n={i18n}>
+ <aside className="fixture-controls">
+ <strong>Project editor regression test</strong>
+ <span id="background-status">Background task running</span>
+ <button id="complete-background" onClick={completeTask}>Complete background task</button>
+ <small>Real Settings → Projects UI · controlled background event</small>
+ </aside>
+ <main className="fixture-page"><ProjectsPage /></main>
+ </I18nextProvider>,
+);
+
+async function until<T>(read: () => T | null | false, label: string): Promise<T> {
+ const deadline = performance.now() + 5000;
+ while (performance.now() < deadline) {
+ const value = read();
+ if (value) return value;
+ await new Promise(requestAnimationFrame);
+ }
+ throw new Error(`Timed out: ${label}`);
+}
+
+function button(label: string) {
+ return [...document.querySelectorAll<HTMLButtonElement>("button")].find(
+ (node) => node.textContent?.trim() === label || node.getAttribute("aria-label") === label,
+ ) ?? null;
+}
+
+async function click(label: string) {
+ (await until(() => button(label), label)).click();
+}
+
+function inputName(value: string) {
+ const input = document.querySelector<HTMLInputElement>("#project-edit-name")!;
+ input.focus();
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ return input;
+}
+
+async function openEditor() {
+ (await until(() => document.querySelector<HTMLButtonElement>(".projects-row"), "project row")).click();
+ await click("Open actions for Website");
+ (await until(() => document.querySelector<HTMLButtonElement>('[data-action="edit-project"]'), "edit action")).click();
+ await until(() => {
+ const input = document.querySelector<HTMLInputElement>("#project-edit-name");
+ return input && !input.disabled && input.value === "Website" ? input : null;
+ }, "loaded editor");
+}
+
+globalThis.projectEditProbe = async () => {
+ await openEditor();
+ inputName("Website redesign");
+ await click("Remove folder: assets");
+ await until(() => !document.querySelector('[aria-label="Remove folder: assets"]'), "removed extra folder");
+ completeTask();
+ // Let the update traverse the real ProjectsPage and any resulting IPC loads.
+ await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
+ const input = document.querySelector<HTMLInputElement>("#project-edit-name")!;
+ const preserved = input.value === "Website redesign";
+ const foldersPreserved = !document.querySelector('[aria-label="Remove folder: assets"]');
+ if (!preserved || !foldersPreserved) {
+ return { ok: false, name: input.value, preserved, foldersPreserved };
+ }
+ await click("Save changes");
+ await until(() => !document.querySelector("#project-edit-name"), "saved editor closed");
+ await until(() => document.body.textContent?.includes("Website redesign"), "updated project visible");
+ const { groups } = await api.listProjectGroups();
+ const saved = groups[0]?.name === "Website redesign" &&
+ groups[0]?.primaryPath === "/fixture/website" &&
+ groups[0]?.roots.length === 1 && groups[0]?.roots[0]?.path === "/fixture/website";
+ return { ok: saved, preserved, foldersPreserved, saved };
+};