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(desktop): add native editing context menu for editable text
Lanbfab44ea2c9b
diff --git a/apps/desktop/electron/main/application-menu.ts b/apps/desktop/electron/main/application-menu.tsindex e23f9ad5e..140cd9c5f 100644--- a/apps/desktop/electron/main/application-menu.ts+++ b/apps/desktop/electron/main/application-menu.ts@@ -1,4 +1,4 @@-import { Menu, type MenuItemConstructorOptions } from "electron";+import { Menu, type BrowserWindow, type MenuItemConstructorOptions } from "electron";import {APP_NAME,KEYBOARD_SHORTCUTS,@@ -246,3 +246,26 @@ export function installApplicationMenu(options: ApplicationMenuOptions) {const template = buildApplicationMenuTemplate(options);Menu.setApplicationMenu(Menu.buildFromTemplate(template));}++export function installEditableContextMenu(window: BrowserWindow) {+ window.webContents.on("context-menu", (_event, params) => {+ if (!params.isEditable) return;+ const flags = params.editFlags;+ Menu.buildFromTemplate([+ { role: "undo", enabled: flags.canUndo },+ { role: "redo", enabled: flags.canRedo },+ { type: "separator" },+ { role: "cut", enabled: flags.canCut },+ { role: "copy", enabled: flags.canCopy },+ { role: "paste", enabled: flags.canPaste },+ { type: "separator" },+ { role: "selectAll", enabled: flags.canSelectAll },+ ]).popup({+ window,+ frame: params.frame ?? undefined,+ x: params.x,+ y: params.y,+ sourceType: params.menuSourceType,+ });+ });+}diff --git a/apps/desktop/electron/main/bootstrap/window.ts b/apps/desktop/electron/main/bootstrap/window.tsindex ed49f3b71..02e39159f 100644--- a/apps/desktop/electron/main/bootstrap/window.ts+++ b/apps/desktop/electron/main/bootstrap/window.ts@@ -38,6 +38,7 @@ import {} from "../work-panel-window";import { readWindowState, writeWindowState } from "../window-preferences";import { suppressLinuxFramelessSystemMenu } from "../frameless-system-menu";+import { installEditableContextMenu } from "../application-menu";import { isWindowFullScreen } from "../window-fullscreen";import { installWindowsNativeSnap } from "../window-native-snap";import {@@ -283,6 +284,7 @@ export async function createWindow({},});const window = windowState.mainWindow;+ installEditableContextMenu(window);installMaximizedWindowGuard(window, process.platform);const setNativeMinimumSize = (width: number, height: number) => {if (window.isMaximized() || isWindowFullScreen(window)) return;diff --git a/apps/desktop/test/editable-context-menu-user-path.test.mjs b/apps/desktop/test/editable-context-menu-user-path.test.mjsnew file mode 100644index 000000000..5e517a7ce--- /dev/null+++ b/apps/desktop/test/editable-context-menu-user-path.test.mjs@@ -0,0 +1,142 @@+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { createRequire } from "node:module";+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 aliases = {+ "@pi-desktop/shared": join(root, "packages/shared/src"),+ "@pi-desktop/i18n": join(root, "packages/i18n/src"),+};++const renderer = `+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import { useRef, useState } from "react";+import { ComposerInput } from "../../apps/desktop/src/features/chat/composer/ComposerInput";+window.probe = { value: "" };+const noop = () => {};+function Fixture() {+ const ref = useRef(null);+ const [value, setValue] = useState("");+ window.probe.value = value;+ return <ComposerInput inputRef={ref} value={value} placeholderText="" placeholderKey="fixture"+ inputBlocked={false} pasting={false} enterToSend={false} runActive={false}+ composerAc={{ open: false, hasItems: false, close: noop }}+ onPaste={noop}+ onInput={(text) => setValue(text)} onAcceptCompletion={noop} onSubmit={noop}+ onInsertNewline={noop} onHistoryNavigate={() => false} onCompositionStart={noop}+ onCompositionEnd={noop} onSettledInput={noop} onFocus={noop} onBlur={noop} />;+}+flushSync(() => createRoot(document.getElementById("root")).render(<Fixture />));+`;++const main = `+import assert from "node:assert/strict";+import { app, BrowserWindow, Menu } from "electron";+import { installEditableContextMenu } from "../../apps/desktop/electron/main/application-menu";+app.setPath("userData", process.argv[2]);+app.whenReady().then(async () => {+const win = new BrowserWindow({ show: true, width: 800, height: 600,+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });+const wc = win.webContents;+let opened;+// Only the popup boundary is replaced. The role each item was built with is asserted+// before the platform performs the edit, so a mis-wired menu cannot pass.+Menu.prototype.popup = function (options) { opened = { menu: this, options }; };+installEditableContextMenu(win);+const read = (expression) => wc.executeJavaScript(expression);+async function openMenu() {+ opened = undefined;+ const point = await read('(() => { const r = document.querySelector(".composer-input").getBoundingClientRect(); return {x: Math.round(r.x + 5), y: Math.round(r.y + 5)}; })()');+ const event = new Promise((resolve) => wc.once("context-menu", (_event, params) => resolve(params)));+ wc.sendInputEvent({ type: "mouseDown", button: "right", clickCount: 1, ...point });+ wc.sendInputEvent({ type: "mouseUp", button: "right", clickCount: 1, ...point });+ return event;+}+function command(role) {+ const item = opened.menu.items.find((candidate) => candidate.role === role);+ assert.equal(item?.enabled, true, role + " must be enabled");+ // The role assert above runs before anything executes, so a menu that wires the wrong+ // role fails here even though the platform performs the edit itself.+ if (process.platform === "darwin") Menu.sendActionToFirstResponder(role === "selectall" ? "selectAll:" : role + ":");+ else item.click({}, win, wc);+}+try {+ Menu.setApplicationMenu(null);+ await win.loadFile(process.argv[3]);+ win.focus();+ await read('document.querySelector(".composer-input").focus()');+ await wc.insertText("alpha beta");+ await read('const range = document.createRange(); const node = document.querySelector(".composer-input").firstChild; range.setStart(node, 0); range.setEnd(node, 5); window.getSelection().removeAllRanges(); window.getSelection().addRange(range)');+ const params = await openMenu();+ assert.ok(opened, "Right-clicking the composer must open an editing menu");+ const roles = opened.menu.items.filter((item) => item.type !== "separator");+ assert.deepEqual(roles.map((item) => item.role), ["undo", "redo", "cut", "copy", "paste", "selectall"]);+ assert.deepEqual(roles.map((item) => item.enabled), [params.editFlags.canUndo, params.editFlags.canRedo,+ params.editFlags.canCut, params.editFlags.canCopy, params.editFlags.canPaste, params.editFlags.canSelectAll]);+ assert.equal(opened.options.window, win);+ assert.equal(opened.options.frame, params.frame);+ assert.equal(await read('window.getSelection().toString()'), "alpha");+ await wc.insertText("gamma");+ assert.equal(await read("window.probe.value"), "gamma beta");+ await openMenu(); command("undo");+ assert.equal(await read("window.probe.value"), "alpha beta");+ await openMenu(); command("redo");+ assert.equal(await read("window.probe.value"), "gamma beta");+ await openMenu(); command("selectall");+ assert.equal(await read('window.getSelection().toString()'), "gamma beta");+ await read('document.querySelector(".composer-input").contentEditable = "false"');+ await openMenu();+ // A read-only control must not open this menu at all; whatever Electron itself does on a+ // real right-click is outside this test's replaced popup boundary.+ assert.equal(opened, undefined, "read-only controls do not open the editing menu");+ console.log("EDITABLE_MENU_PROBE passed");+} catch (error) {+ console.error(error.stack);+ process.exitCode = 1;+} finally {+ win.destroy();+}+app.exit(process.exitCode || 0);+});+`;++test("composer right-click preserves selection and native editing history", {+ skip: process.platform === "linux" && !process.env.DISPLAY ? "Electron requires a display" : false,+ timeout: 30_000,+}, async () => {+ const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR || tmpdir(), "pi-editable-menu-"));+ try {+ await build({ stdin: { contents: renderer, 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: { ...aliases, ...Object.fromEntries(["react", "react-dom", "i18next", "react-i18next"].map((name) => [name, join(root, "apps/desktop/node_modules", name)])) },+ nodePaths: [join(root, "apps/desktop/node_modules")],+ });+ await build({ stdin: { contents: main, resolveDir: join(root, "scripts/e2e") },+ outfile: join(temp, "main.cjs"), bundle: true, platform: "node", format: "cjs", external: ["electron"], alias: aliases });+ await writeFile(join(temp, "index.html"), '<!doctype html><meta charset="utf-8"><style>.composer-input{min-height:100px;white-space:pre-wrap}</style><div id="root"></div><script type="module" src="renderer.js"></script>');+ const env = { ...process.env };+ delete env.ELECTRON_RUN_AS_NODE;+ const child = spawn(resolveElectronBinary(root).electronBinary,+ [join(temp, "main.cjs"), join(temp, "profile"), join(temp, "index.html")],+ { 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"), 15_000);+ try {+ const code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); });+ assert.equal(code, 0, output);+ assert.match(output, /EDITABLE_MENU_PROBE passed/);+ } finally { clearTimeout(timer); }+ } finally { await rm(temp, { recursive: true, force: true }); }+});diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex 184cc1d08..786207fb2 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -1372,6 +1372,13 @@ Running turns and pending approvals continue to gate the controls.- Editable controls (`input`, `textarea`, `select`, and`[contenteditable]`) preserve normal text editing and `Cmd/Ctrl+A/C/V`behavior.+- Editable text controls in the main window expose a native context menu:+ Undo, Redo, Cut, Copy, Paste, and Select All. Availability follows Electron's+ edit flags; native role labels use Electron/OS localization. The menu targets+ the originating window and frame and retains the current text selection.+- Menu Paste uses the existing paste event path, including composer text and+ image/file attachments. Read-only controls and renderer-owned context menus+ retain their existing behavior.- Transcript prose, rendered Markdown, code blocks, and tool input/outputremain text-selectable for inspection and copying.- Interactive controls nested inside selectable content remaindiff --git a/docs/spec/06-delivery/e2e/ui-shell.md b/docs/spec/06-delivery/e2e/ui-shell.mdindex 9c27b19dd..5fd8ed53e 100644--- a/docs/spec/06-delivery/e2e/ui-shell.md+++ b/docs/spec/06-delivery/e2e/ui-shell.md@@ -69,16 +69,24 @@- **Steps**: 1) Drag across sidebar/titlebar chrome and a button label. 2)Drag across user/assistant prose, code, and tool output. 3) Focus thecomposer and a settings/search input, then use `Cmd/Ctrl+A` and replace the- selected text. 4) Copy selected transcript and code text.+ selected text. 4) Copy selected transcript and code text. 5) Right-click the+ composer and a settings/search input; use Copy, Cut, Undo, Redo, Paste, and+ Select All. Paste an image from the menu. 6) Open an existing transcript or+ sidebar context menu and right-click a read-only control.- **Expected**: Chrome does not leave an accidental text selection; messageprose, code, tool input/output, and editable controls remain selectable andcopyable; native editing shortcuts, focus-visible rings, and window drag- behavior remain intact.+ behavior remain intact. Editable controls show the native editing menu with+ actions enabled according to the current editor state; commands preserve+ selection and undo history, and Paste reaches the existing composer paste+ handler. Read-only controls and existing custom menus keep their behavior.- **Specs linked**: `04-ux/07-ui-design-system.md`,`04-ux/09-interaction-patterns.md`- **Acceptance**: Quality (key operations feel polished)- **Milestone**: M5-- **Status**: Unit-covered (`user-select.test.mjs`); scenario Documented+- **Status**: Unit-covered (`user-select.test.mjs`); native composer menu,+ selection, and undo/redo automated (`editable-context-menu-user-path.test.mjs`);+ full shell scenario Documented.## E2E-047b: Sidebar session hover card surfaces rich metadata