Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(composer): keep an empty last line's caret without adding a line
Gloow_2011746085fd
diff --git a/apps/desktop/src/features/chat/composer/editor.ts b/apps/desktop/src/features/chat/composer/editor.tsindex fa1b7ee5d..7c56694db 100644--- a/apps/desktop/src/features/chat/composer/editor.ts+++ b/apps/desktop/src/features/chat/composer/editor.ts@@ -100,34 +100,46 @@ function isChipElement(node: Node): boolean {);}-const TAIL_PLACEHOLDER_ATTRIBUTE = "data-composer-tail";--/** The break that keeps an empty last line laid out; the draft never reads it. */-function buildTailPlaceholder(): HTMLBRElement {- const placeholder = document.createElement("br");- placeholder.setAttribute(TAIL_PLACEHOLDER_ATTRIBUTE, "");- placeholder.setAttribute("aria-hidden", "true");- return placeholder;+/**+ * Zero-width space that keeps an empty last line caretable. Chromium gives an+ * empty line a box but no caret box, so a caret left after the final break+ * resolves to the line above (#2433). A trailing `<br>` adds the box but also a+ * second caret position below it, which reads as an extra line. A zero-width+ * space gives the line a real caret and nothing else.+ *+ * Chromium can merge the marker into the neighbouring text node, so every read,+ * index and caret path strips the character instead of looking for a node.+ */+const TAIL_MARKER = "\u200B";++function stripTailMarkers(text: string): string {+ return text.includes(TAIL_MARKER) ? text.replaceAll(TAIL_MARKER, "") : text;}-/** Paint the placeholder for a value whose last line is empty. */-function paintTailPlaceholder(el: HTMLElement, value: string): void {- if (value.endsWith("\n")) el.appendChild(buildTailPlaceholder());+/** Draft-string length of a text node once its markers are stripped. */+function markedTextLength(text: string): number {+ return stripTailMarkers(text).length;}-function isTailPlaceholder(node: Node): boolean {- return (- node.nodeType === Node.ELEMENT_NODE &&- (node as HTMLElement).tagName === "BR" &&- (node as HTMLElement).hasAttribute(TAIL_PLACEHOLDER_ATTRIBUTE)- );+/** Draft offset inside a text node → DOM offset, which sits before a marker. */+function offsetForDraftIndex(text: string, index: number): number {+ if (!text.includes(TAIL_MARKER)) return index;+ let seen = 0;+ for (let offset = 0; offset < text.length; offset += 1) {+ if (seen === index) return offset;+ if (text[offset] !== TAIL_MARKER) seen += 1;+ }+ return text.length;}+/** Paint the marker for a value whose last line is empty. */+function paintTailMarker(el: HTMLElement, value: string): void {+ if (value.endsWith("\n")) el.appendChild(document.createTextNode(TAIL_MARKER));+}/** Rendered length of a node in draft-string characters (chip = 1 char). */function editorNodeLength(node: Node): number {- if (node.nodeType === Node.TEXT_NODE) return (node.nodeValue ?? "").length;+ if (node.nodeType === Node.TEXT_NODE) return markedTextLength(node.nodeValue ?? "");if (isChipElement(node)) return 1;- if (isTailPlaceholder(node)) return 0;if (node.nodeType === Node.ELEMENT_NODE) {const element = node as HTMLElement;if (element.tagName === "BR") return 1;@@ -143,7 +155,7 @@ export function readEditorValue(el: HTMLElement): string {let out = "";const walk = (node: Node, blockStart: boolean): void => {if (node.nodeType === Node.TEXT_NODE) {- out += node.nodeValue ?? "";+ out += stripTailMarkers(node.nodeValue ?? "");return;}if (node.nodeType !== Node.ELEMENT_NODE) return;@@ -153,7 +165,6 @@ export function readEditorValue(el: HTMLElement): string {out += isChipTokenChar(token) ? token : "";return;}- if (isTailPlaceholder(element)) return;if (element.tagName === "BR") {out += "\n";return;@@ -189,9 +200,7 @@ export function editorIndexAt(const walk = (parent: DocumentFragment | HTMLElement): void => {for (const child of Array.from(parent.childNodes)) {if (child.nodeType === Node.TEXT_NODE) {- total += (child.nodeValue ?? "").length;- } else if (isTailPlaceholder(child)) {- // The placeholder break is not part of the draft.+ total += markedTextLength(child.nodeValue ?? "");} else if (isChipElement(child) || (child as HTMLElement).tagName === "BR") {total += 1;} else if (child.nodeType === Node.ELEMENT_NODE) {@@ -234,13 +243,13 @@ function editorCaretPoint(el: HTMLElement, target: number): { node: Node; offsetconst length = editorNodeLength(child);if (child.nodeType === Node.TEXT_NODE) {if (point === null && remaining <= length) {- point = { node: child, offset: remaining };+ // A marker merged into this text node owns the empty line's caret: the+ // caret named by the end index sits right before it, where Chromium+ // has a box.+ point = { node: child, offset: offsetForDraftIndex(child.nodeValue ?? "", remaining) };return true;}remaining -= length;- } else if (isTailPlaceholder(child)) {- // Not a draft position: a caret at the end goes before the placeholder.- continue;} else if (isChipElement(child) || (child as HTMLElement).tagName === "BR") {if (point === null && remaining <= 1) {point = { node: parent, offset: remaining === 0 ? index : index + 1 };@@ -255,8 +264,7 @@ function editorCaretPoint(el: HTMLElement, target: number): { node: Node; offset};descend(el);if (point) return point;- const placeholder = Array.from(el.childNodes).findIndex(isTailPlaceholder);- return { node: el, offset: placeholder === -1 ? el.childNodes.length : placeholder };+ return { node: el, offset: el.childNodes.length };}export function setEditorCaret(el: HTMLElement, index: number): void {@@ -275,22 +283,33 @@ export function setEditorCaret(el: HTMLElement, index: number): void {}/**- * Keep the empty last line laid out. Chromium has no box for a line that holds- * nothing, so a caret left after the final break resolves backwards and the next- * keystroke lands on the line above (#2433). A placeholder break gives that line- * a box; `readEditorValue`, `editorIndexAt` and `editorCaretPoint` all skip it,- * so the draft string and its indices are unchanged.+ * Keep the empty last line laid out *and* caretable. Chromium gives an empty+ * line a box but no caret box, so a caret left after the final break resolves to+ * the line above and the next keystroke lands there (#2433). A trailing break+ * adds a box but also a second caret position below it, which reads as an extra+ * line; a zero-width space gives the line a real caret and nothing else.+ * Every read, index and caret path strips the character, so the draft string and+ * its indices are unchanged.*/-export function syncTailPlaceholder(el: HTMLElement): void {+export function syncTailMarker(el: HTMLElement): void {const value = readEditorValue(el);- const existing = Array.from(el.childNodes).find(isTailPlaceholder) ?? null;- if (!value.endsWith("\n")) {- existing?.remove();- return;+ const last = el.lastChild;+ const lastText = last && last.nodeType === Node.TEXT_NODE ? (last as Text) : null;+ if (value.endsWith("\n")) {+ // Chromium merges typed text into the marker's node, so the marker is kept as+ // a trailing character rather than a node that must stay separate.+ if (lastText) {+ if (!(lastText.nodeValue ?? "").endsWith(TAIL_MARKER)) {+ lastText.nodeValue = `${lastText.nodeValue ?? ""}${TAIL_MARKER}`;+ }+ } else {+ el.appendChild(document.createTextNode(TAIL_MARKER));+ }+ } else if (lastText && (lastText.nodeValue ?? "").includes(TAIL_MARKER)) {+ lastText.nodeValue = stripTailMarkers(lastText.nodeValue ?? "");}- if (!existing) el.appendChild(buildTailPlaceholder());- // A caret after the final break is the position without a box; naming the end- // by draft index puts it on the placeholder side instead.+ // A caret that sits on the empty last line is named by draft index so it lands+ // on the marker instead of after the final break.const selection = window.getSelection();if (!selection || selection.rangeCount === 0 || !selection.isCollapsed) return;if (!el.contains(selection.anchorNode)) return;@@ -498,7 +517,7 @@ export function paintEditorValue(// Chromium needs at least one node for reliable caret placement.el.appendChild(document.createTextNode(""));}- paintTailPlaceholder(el, value);+ paintTailMarker(el, value);}export function clipboardFiles(data: DataTransfer): File[] {diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.tsindex 43edc1264..2fea1932c 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts@@ -42,7 +42,7 @@ import {paintEditorValue,readEditorValue,setEditorCaret,- syncTailPlaceholder,+ syncTailMarker,type ComposerFileReference,} from "../editor";import type { ComposerPrefill } from "../model";@@ -306,11 +306,12 @@ export function useComposerDraft({editorValueRef.current = nextValue;};- // An empty last line has no box of its own, so Chromium types the next- // keystroke one line up; give it a placeholder break after every commit.+ // An empty last line has no caret box of its own, so Chromium resolves a caret+ // left on it to the neighbouring line; give the line a zero-width marker after+ // every commit.useLayoutEffect(() => {const element = ref.current;- if (element) syncTailPlaceholder(element);+ if (element) syncTailMarker(element);}, [value]);useLayoutEffect(() => {diff --git a/apps/desktop/test/composer-tail-line.test.mjs b/apps/desktop/test/composer-tail-line.test.mjsindex b6c6f28e3..db5ae84ea 100644--- a/apps/desktop/test/composer-tail-line.test.mjs+++ b/apps/desktop/test/composer-tail-line.test.mjs@@ -1,7 +1,9 @@/**- * #2433: the empty last line has no box of its own, so Chromium types the next- * keystroke one line up. The editor keeps a placeholder break on that line and- * every read path has to ignore it.+ * #2433 follow-up: Chromium gives an empty line a box but no caret box, so a+ * caret left on the last empty line resolves to the neighbouring line. A+ * trailing `<br>` adds a box but also a second caret position below it, which+ * reads as an extra line. The editor keeps a zero-width space on that line+ * instead, and every read path has to strip the character.*/import assert from "node:assert/strict";import { readFileSync } from "node:fs";@@ -23,53 +25,63 @@ function loadFunction(path, name, globals = {}) {return vm.runInNewContext(`${code}\n${name};`, globals);}-const nodeConstants = { TEXT_NODE: 3, ELEMENT_NODE: 1 };-const isTailPlaceholder = loadFunction("../src/features/chat/composer/editor.ts", "isTailPlaceholder", {- Node: nodeConstants,- TAIL_PLACEHOLDER_ATTRIBUTE: "data-composer-tail",-});-const editorNodeLength = loadFunction("../src/features/chat/composer/editor.ts", "editorNodeLength", {- Node: nodeConstants,- isChipElement: () => false,- isTailPlaceholder: (node) => isTailPlaceholder(node),+const editorPath = "../src/features/chat/composer/editor.ts";+const globals = { TAIL_MARKER: "\u200B" };+const stripTailMarkers = loadFunction(editorPath, "stripTailMarkers", globals);+const markedTextLength = loadFunction(editorPath, "markedTextLength", {+ ...globals,+ stripTailMarkers: (text) => stripTailMarkers(text),});+const offsetForDraftIndex = loadFunction(editorPath, "offsetForDraftIndex", globals);-const placeholder = {- nodeType: 1,- tagName: "BR",- hasAttribute: (name) => name === "data-composer-tail",-};-const realBreak = { nodeType: 1, tagName: "BR", hasAttribute: () => false };-const text = (value) => ({ nodeType: 3, nodeValue: value, childNodes: [] });+test("the zero-width marker never reaches the draft string", () => {+ assert.equal(stripTailMarkers("a\u200B"), "a");+ assert.equal(stripTailMarkers("\u200B"), "");+ assert.equal(stripTailMarkers("a\nb"), "a\nb");+ assert.equal(markedTextLength("a\u200B"), 1);+ assert.equal(markedTextLength("\u200B"), 0);+ assert.equal(markedTextLength("ab"), 2);+});-test("only the marked break is a tail placeholder, and it has no length", () => {- assert.equal(isTailPlaceholder(placeholder), true);- assert.equal(isTailPlaceholder(realBreak), false);- assert.equal(isTailPlaceholder(text("\n")), false);- assert.equal(editorNodeLength(placeholder), 0);- assert.equal(editorNodeLength(realBreak), 1);- assert.equal(editorNodeLength(text("ab")), 2);+test("a caret named by draft index sits before the marker, where the box is", () => {+ // "ab\u200B" with the caret at the end: the DOM offset is the marker's index.+ assert.equal(offsetForDraftIndex("ab\u200B", 2), 2);+ assert.equal(offsetForDraftIndex("ab\u200B", 1), 1);+ assert.equal(offsetForDraftIndex("\u200B", 0), 0);+ assert.equal(offsetForDraftIndex("ab", 2), 2);});-test("the editor model places, reads and paints around the tail placeholder", async () => {+test("the editor model keeps, strips and paints around the tail marker", async () => {const editor = await readComposerModule("editor.ts");const draft = await readComposerModule("hooks/useComposerDraft.ts");const deletion = await readComposerModule("native-deletion.ts");- // Reading and indexing skip it, so the draft string never grows a newline.- assert.match(editor, /if \(isTailPlaceholder\(element\)\) return;/);- assert.match(editor, /} else if \(isTailPlaceholder\(child\)\) \{/);+ // A zero-width space, never a break: a break adds a caret position below the+ // empty line, which is the extra line #2433's first fix introduced.+ assert.match(editor, /const TAIL_MARKER = "\\u200B";/);+ assert.doesNotMatch(editor, /data-composer-tail/);++ // Every read, index and caret path strips the character, because Chromium can+ // merge the marker into the neighbouring text node.+ assert.match(editor, /if \(node\.nodeType === Node\.TEXT_NODE\) return markedTextLength\(node\.nodeValue \?\? ""\);/);+ assert.match(editor, /out \+= stripTailMarkers\(node\.nodeValue \?\? ""\);/);+ assert.match(editor, /total \+= markedTextLength\(child\.nodeValue \?\? ""\);/);+ assert.match(+ editor,+ /point = \{ node: child, offset: offsetForDraftIndex\(child\.nodeValue \?\? "", remaining\) \};/,+ );- // A caret placed by draft index lands before it, never on it.- assert.match(editor, /if \(isTailPlaceholder\(child\)\) \{\n\s+\/\/ Not a draft position/);- assert.match(editor, /const placeholder = Array\.from\(el\.childNodes\)\.findIndex\(isTailPlaceholder\);/);+ // Painting gives an empty last line its caret box, and every commit keeps it.+ assert.match(editor, /function paintTailMarker\(el: HTMLElement, value: string\): void \{/);+ assert.match(editor, /el\.appendChild\(document\.createTextNode\(TAIL_MARKER\)\)/);+ assert.match(draft, /if \(element\) syncTailMarker\(element\);/);- // Painting gives an empty last line its box, and every commit keeps it.- assert.match(editor, /paintTailPlaceholder\(el, value\);/);- assert.match(editor, /if \(value\.endsWith\("\\n"\)\) el\.appendChild\(buildTailPlaceholder\(\)\);/);- assert.match(draft, /useLayoutEffect\(\(\) => \{\n\s+const element = ref\.current;\n\s+if \(element\) syncTailPlaceholder\(element\);/);+ // The marker is a trailing character while the last line is empty and is+ // removed as soon as that line has content.+ assert.match(editor, /lastText\.nodeValue = `\$\{lastText\.nodeValue \?\? ""\}\$\{TAIL_MARKER\}`;/);+ assert.match(editor, /lastText\.nodeValue = stripTailMarkers\(lastText\.nodeValue \?\? ""\);/);// The invariant is restored after the event, never inside it: mutating the// editor while Chromium runs an editing command makes it insert twice.- assert.doesNotMatch(deletion, /syncTailPlaceholder/);+ assert.doesNotMatch(deletion, /syncTailMarker/);});diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 698e767ae..89a1b0239 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -4789,13 +4789,17 @@ as well as its DOM, so submission and draft caching retain the path. Deletedreference history is local to the current draft/workspace and is cleared on send;pasting a private-use character alone must not restore an attachment. The input owns and disposes the native event listeners.-An empty last line keeps its own caret. Chromium has no box for a line that holds-nothing, so a caret left after the final line break types the next keystroke onto-the line above. The editor paints a placeholder break on that line, places an-end-of-draft caret before it when the draft ends in a newline, and restores it-after every commit; the draft string, its indices and the caret's position in it-are unchanged, and the placeholder disappears as soon as the line holds text. A-middle empty line needs none: the break that ends it already gives it a box.+An empty last line keeps its own caret. Chromium gives a line that holds nothing a+box but no caret box, so a caret left after the final line break resolves to the+line above and types the next keystroke there. A trailing break adds the box but+also a second caret position below it, which reads as one line too many; the+editor therefore paints a zero-width space on that line, places an end-of-draft+caret on the character when the draft ends in a newline, and re-syncs it after+every commit. Every read, index and caret path strips the character — Chromium can+merge it into the neighbouring text node — so the draft string, its indices and+the caret's position in it are unchanged, and the marker is removed as soon as+the line holds text. A middle empty line needs none: the break that ends it+already gives it a caret box.### Dialog long-text containmentdiff --git a/docs/spec/06-delivery/e2e/conversation.md b/docs/spec/06-delivery/e2e/conversation.mdindex ef1992558..2e8f3616c 100644--- a/docs/spec/06-delivery/e2e/conversation.md+++ b/docs/spec/06-delivery/e2e/conversation.md@@ -431,11 +431,13 @@ folder/mixed-selection behavior. No system clipboard contents are changed.- **Steps**: 1) Leave Enter-to-send enabled. Type a draft and press Enter.2) Disable Enter-to-send in Settings. 3) Type a second draft and pressCmd/Ctrl+Enter. 4) Press Enter and Shift+Enter in a third draft, then- Shift+Enter at the end and type one character.+ Shift+Enter at the end, then type one character and press ArrowDown once.- **Expected**: Step 1 sends. After the setting is off, Cmd/Ctrl+Enter sends;plain Enter and Shift+Enter insert newlines and do not send. IME composition- and an open autocomplete menu still take precedence over send. The character- typed on the empty last line stays on that line.+ and an open autocomplete menu still take precedence over send. The composer+ grows by exactly one line per newline, the caret stays on the new empty line+ instead of resolving to a neighbouring one, ArrowDown cannot move it below+ that line, and the character typed there stays on it.- **Specs linked**: `04-ux/01-ui-ia.md`, `04-ux/08-component-spec.md` §11.5,`04-ux/09-interaction-patterns.md` §1.2- **Acceptance**: C (composer send)