Skip to content

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

fix(composer): restore preview focus after the selection

Linuxdazhao047748de868b
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.ts
index bc6055e7c..0481aa35f 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.ts
@@ -93,13 +93,14 @@ export function useComposerImagePreview({
const current = useAppStore.getState();
if (!editor.isConnected || (current.activeSessionId ?? "") !== reference.sessionId ||
(current.workspace?.path ?? null) !== openingWorkspace) return;
- if (focused instanceof HTMLElement && focused.isConnected && (editor.contains(focused) || focused.closest(".composer-chip[data-image]"))) focused.focus();
- else editor.focus();
if (range && editor.contains(range.commonAncestorContainer)) {
const selection = window.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
}
+ // Restoring a selection can focus its editing host; restore the control last.
+ if (focused instanceof HTMLElement && focused.isConnected && (editor.contains(focused) || focused.closest(".composer-chip[data-image]"))) focused.focus();
+ else editor.focus();
},
});
}, [editorRef]);
diff --git a/apps/desktop/test/composer-image-preview-focus.test.mjs b/apps/desktop/test/composer-image-preview-focus.test.mjs
new file mode 100644
index 000000000..429b1010b
--- /dev/null
+++ b/apps/desktop/test/composer-image-preview-focus.test.mjs
@@ -0,0 +1,67 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import vm from "node:vm";
+import test from "node:test";
+import ts from "typescript";
+
+const source = readFileSync(new URL("../src/features/chat/composer/hooks/useComposerImagePreview.ts", import.meta.url), "utf8");
+const tree = ts.createSourceFile("preview.ts", source, ts.ScriptTarget.Latest, true);
+let openCallback;
+function visit(node) {
+ if (ts.isVariableDeclaration(node) && node.name.getText(tree) === "open") openCallback = node.initializer.arguments[0];
+ ts.forEachChild(node, visit);
+}
+visit(tree);
+assert.ok(openCallback);
+const code = ts.transpileModule(`(${openCallback.getText(tree)})`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+}).outputText;
+
+function fixture() {
+ const document = { activeElement: null };
+ class Element {
+ isConnected = true;
+ focus() { document.activeElement = this; }
+ contains(node) { return node === this || (this === editor && node === chip); }
+ closest() { return null; }
+ }
+ const editor = new Element(), chip = new Element();
+ document.activeElement = chip;
+ const range = { commonAncestorContainer: editor };
+ let restoredRange;
+ const selection = {
+ rangeCount: 1, getRangeAt: () => ({ cloneRange: () => range }),
+ removeAllRanges() { restoredRange = undefined; },
+ // Chromium focuses the editing host when a selection is installed inside it.
+ addRange(value) { restoredRange = value; editor.focus(); },
+ };
+ const state = { activeSessionId: "focus-session", workspace: { path: "/synthetic/project" } };
+ let request;
+ const open = vm.runInNewContext(code, {
+ document, window: { getSelection: () => selection }, HTMLElement: Element,
+ editorRef: { current: editor }, useAppStore: { getState: () => state },
+ setRequest(value) { request = value; },
+ });
+ open({ id: "image", sessionId: "focus-session" });
+ return { document, editor, chip, state, request, range, restoredRange: () => restoredRange };
+}
+
+test("closing an image preview restores the selection and original control focus", () => {
+ const run = fixture();
+ run.document.activeElement = null;
+ run.request.restoreFocus();
+ assert.equal(run.restoredRange(), run.range);
+ assert.equal(run.document.activeElement, run.chip, "selection restoration must not steal the final control focus");
+});
+
+for (const changed of ["session", "project"]) {
+ test(`a preview from another ${changed} cannot restore stale focus or selection`, () => {
+ const run = fixture();
+ if (changed === "session") run.state.activeSessionId = "other";
+ else run.state.workspace.path = "/synthetic/other";
+ run.document.activeElement = null;
+ run.request.restoreFocus();
+ assert.equal(run.document.activeElement, null);
+ assert.equal(run.restoredRange(), undefined);
+ });
+}
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index f500c1889..c74157719 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -9754,6 +9754,9 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
delivery are controlled external boundaries; this is not a manual Finder gesture
or a live external provider call. Full paste coverage also verifies restoring
the actual pre-preview focus target, including Chromium's editing-host focus.
+ Restore the saved selection before focusing the original control so selection
+ updates cannot steal its final focus. Stale session/project previews restore
+ neither focus nor selection (`composer-image-preview-focus.test.mjs`).
#### E2E-102h: Composer picker imports files into session scratch
diff --git a/scripts/e2e/composer-paste.tsx b/scripts/e2e/composer-paste.tsx
index 0b1a40de2..addd5db19 100644
--- a/scripts/e2e/composer-paste.tsx
+++ b/scripts/e2e/composer-paste.tsx
@@ -770,9 +770,8 @@ globalThis.composerPasteProbe = async (screenshotOnly = false, fileReferencesOnl
assert(readEditorValue(editor) === beforePreview && submitted === 0,
"preview key altered or sent the draft");
await globalThis.composerPreviewPressKey("Escape");
- await until(() => !dialog(), "native Escape did not dismiss the preview");
- assert(!dialog() && document.activeElement === focusBeforePreview,
- "cancel did not close and restore the original attachment focus");
+ await until(() => !dialog() && document.activeElement === focusBeforePreview,
+ "native Escape did not dismiss the preview and restore the original focus");
}
// The isolated host supplies real images within the allowed scratch directory.
const wide = createFileReference(imageReference.path.replace(/[^/\\]+$/, "wide-fixture.png"), "wide.png", "paste-a", {