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 the empty last line without a phantom character
Gloow_fa7a21d866fb
diff --git a/apps/desktop/src/features/chat/composer/ComposerInput.tsx b/apps/desktop/src/features/chat/composer/ComposerInput.tsxindex 1e69a3512..4c2d1ec76 100644--- a/apps/desktop/src/features/chat/composer/ComposerInput.tsx+++ b/apps/desktop/src/features/chat/composer/ComposerInput.tsx@@ -1,4 +1,4 @@-import { useLayoutEffect } from "react";+import { useLayoutEffect, useRef } from "react";import { installComposerDeletionGuard } from "./native-deletion";import type {ClipboardEvent,@@ -86,9 +86,16 @@ export function ComposerInput({onFocus,onBlur,}: ComposerInputProps) {+ // The guard installs native listeners once; the break callback stays current+ // through a ref so a re-render does not reset its redo bookkeeping.+ const insertNewlineRef = useRef(onInsertNewline);+ insertNewlineRef.current = onInsertNewline;useLayoutEffect(() => {const editor = inputRef.current;- return editor ? installComposerDeletionGuard(editor) : undefined;+ if (!editor) return;+ // Enter is owned here, not by React: the native beforeinput handler replaces+ // Chromium's break-plus-placeholder insertion with one newline.+ return installComposerDeletionGuard(editor, () => insertNewlineRef.current());}, [inputRef]);const navigation = suggestion?.navigation;return (@@ -126,16 +133,6 @@ export function ComposerInput({autoCapitalize="off"translate="no"onPaste={onPaste}- onBeforeInput={(event) => {- const native = event.nativeEvent as InputEvent;- if (- native.inputType === "insertParagraph" ||- native.inputType === "insertLineBreak"- ) {- event.preventDefault();- onInsertNewline();- }- }}onInput={(event) => {const element = event.currentTarget;const source = readEditorValue(element);diff --git a/apps/desktop/src/features/chat/composer/editor.ts b/apps/desktop/src/features/chat/composer/editor.tsindex 7c56694db..6635236ad 100644--- a/apps/desktop/src/features/chat/composer/editor.ts+++ b/apps/desktop/src/features/chat/composer/editor.ts@@ -101,44 +101,39 @@ function isChipElement(node: Node): boolean {}/**- * 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.+ * Placeholder break that keeps an empty last line laid out and caretable.+ * Chromium drops the last break of a block — a trailing "\n" and a trailing+ * `<br>` both end the line above and add none of their own — so a draft that ends+ * with a newline paints one extra break after it. That break belongs to the+ * layout, not to the draft: every read, index and caret path counts it as zero+ * characters. Because it holds no text it cannot be selected, copied or typed,+ * and it never merges into a neighbouring text node.*/-const TAIL_MARKER = "\u200B";+const TAIL_PLACEHOLDER = "data-composer-tail";-function stripTailMarkers(text: string): string {- return text.includes(TAIL_MARKER) ? text.replaceAll(TAIL_MARKER, "") : text;+function isTailPlaceholder(node: Node): boolean {+ return (+ node.nodeType === Node.ELEMENT_NODE &&+ (node as HTMLElement).tagName === "BR" &&+ (node as HTMLElement).hasAttribute(TAIL_PLACEHOLDER)+ );}-/** Draft-string length of a text node once its markers are stripped. */-function markedTextLength(text: string): number {- return stripTailMarkers(text).length;+function createTailPlaceholder(): HTMLBRElement {+ const br = document.createElement("br");+ br.setAttribute(TAIL_PLACEHOLDER, "");+ return br;}-/** 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 line box an empty last line needs, without adding a character. */+function paintTailPlaceholder(el: HTMLElement, value: string): void {+ if (value.endsWith("\n")) el.appendChild(createTailPlaceholder());}-/** 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 markedTextLength(node.nodeValue ?? "");+ if (isTailPlaceholder(node)) return 0;+ if (node.nodeType === Node.TEXT_NODE) return (node.nodeValue ?? "").length;if (isChipElement(node)) return 1;if (node.nodeType === Node.ELEMENT_NODE) {const element = node as HTMLElement;@@ -155,11 +150,12 @@ export function readEditorValue(el: HTMLElement): string {let out = "";const walk = (node: Node, blockStart: boolean): void => {if (node.nodeType === Node.TEXT_NODE) {- out += stripTailMarkers(node.nodeValue ?? "");+ out += node.nodeValue ?? "";return;}if (node.nodeType !== Node.ELEMENT_NODE) return;const element = node as HTMLElement;+ if (isTailPlaceholder(element)) return;if (isChipElement(element)) {const token = element.dataset.token ?? "";out += isChipTokenChar(token) ? token : "";@@ -199,8 +195,9 @@ export function editorIndexAt(let total = 0;const walk = (parent: DocumentFragment | HTMLElement): void => {for (const child of Array.from(parent.childNodes)) {+ if (isTailPlaceholder(child)) continue;if (child.nodeType === Node.TEXT_NODE) {- total += markedTextLength(child.nodeValue ?? "");+ total += (child.nodeValue ?? "").length;} else if (isChipElement(child) || (child as HTMLElement).tagName === "BR") {total += 1;} else if (child.nodeType === Node.ELEMENT_NODE) {@@ -240,13 +237,19 @@ function editorCaretPoint(el: HTMLElement, target: number): { node: Node; offsetconst children = Array.from(parent.childNodes);for (let index = 0; index < children.length; index += 1) {const child = children[index];+ if (isTailPlaceholder(child)) {+ // The draft ends before the placeholder, so the end-of-draft caret sits+ // at the start of the empty line that placeholder lays out.+ if (point === null && remaining <= 0) {+ point = { node: parent, offset: index };+ return true;+ }+ continue;+ }const length = editorNodeLength(child);if (child.nodeType === Node.TEXT_NODE) {if (point === null && remaining <= length) {- // 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) };+ point = { node: child, offset: remaining };return true;}remaining -= length;@@ -283,37 +286,26 @@ export function setEditorCaret(el: HTMLElement, index: number): void {}/**- * 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.+ * Keep the empty last line laid out and caretable. Chromium drops the last break+ * of a block, so a draft that ends with a newline paints one extra break after it+ * and counts that break as zero characters everywhere; that keeps the line count,+ * the draft string and its indices unchanged, without a character that could be+ * selected or copied. Text typed into the empty line lands before the placeholder,+ * and a line with content drops it on the next commit.*/-export function syncTailMarker(el: HTMLElement): void {- const value = readEditorValue(el);- 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 ?? "");+export function syncTailPlaceholder(el: HTMLElement): void {+ const placeholders = Array.from(+ el.querySelectorAll<HTMLBRElement>(`br[${TAIL_PLACEHOLDER}]`),+ );+ if (readEditorValue(el).endsWith("\n")) {+ const placeholder = placeholders[0] ?? createTailPlaceholder();+ // A native edit can leave text after the placeholder while the line is still+ // empty; the placeholder stays the last node so the line keeps its box.+ if (el.lastChild !== placeholder) el.appendChild(placeholder);+ for (const extra of placeholders.slice(1)) extra.remove();+ return;}- // 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;- if (editorSelectionRange(el).start === value.length) setEditorCaret(el, value.length);+ for (const placeholder of placeholders) placeholder.remove();}/** One glyph per file family on attachment chips, as inline SVG strings. */@@ -517,7 +509,7 @@ export function paintEditorValue(// Chromium needs at least one node for reliable caret placement.el.appendChild(document.createTextNode(""));}- paintTailMarker(el, value);+ paintTailPlaceholder(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 2fea1932c..38f0c3160 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,- syncTailMarker,+ syncTailPlaceholder,type ComposerFileReference,} from "../editor";import type { ComposerPrefill } from "../model";@@ -306,12 +306,12 @@ export function useComposerDraft({editorValueRef.current = nextValue;};- // 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.+ // An empty last line needs a break of its own: Chromium drops the draft's last+ // break, so the line would collapse onto the line above. The placeholder holds+ // no text, and every read and caret path counts it as zero characters.useLayoutEffect(() => {const element = ref.current;- if (element) syncTailMarker(element);+ if (element) syncTailPlaceholder(element);}, [value]);useLayoutEffect(() => {@@ -407,7 +407,7 @@ export function useComposerDraft({updateCursor(start);};- /** Enter inserts a bare newline text node so the draft round-trips. */+ /** Enter inserts exactly one newline; Chromium would add a second one. */const insertNewlineInEditor = () => {const element = ref.current;if (!element) return;@@ -416,9 +416,11 @@ export function useComposerDraft({const range = selection.getRangeAt(0);if (!element.contains(range.startContainer) || !element.contains(range.endContainer)) return;const { start } = editorSelectionRange(element);+ // Chromium's own `insertLineBreak` also adds a placeholder newline after the+ // caret, which reaches the draft as one empty line too many (#2555), so the+ // break is inserted here as the single newline the draft model stores.range.deleteContents();- const node = document.createTextNode("\n");- range.insertNode(node);+ range.insertNode(document.createTextNode("\n"));setEditorCaret(element, start + 1);commitEditorDom();};diff --git a/apps/desktop/src/features/chat/composer/native-deletion.ts b/apps/desktop/src/features/chat/composer/native-deletion.tsindex 373d87f38..f30fd7534 100644--- a/apps/desktop/src/features/chat/composer/native-deletion.ts+++ b/apps/desktop/src/features/chat/composer/native-deletion.ts@@ -2,15 +2,32 @@ import { editorIndexAt, editorSelectionRange, readEditorValue, setEditorCaret }type DeletionSnapshot = { expected: string; breaks: Set<HTMLBRElement> };-/** Preserve native deletion/undo; remove only a proven extra Chromium placeholder. */-export function installComposerDeletionGuard(editor: HTMLElement): () => void {+/**+ * Preserve native deletion/undo; remove only a proven extra Chromium placeholder.+ * With `onInsertLineBreak` the editor also owns line breaks: Chromium inserts the+ * break *and* a placeholder newline after the caret, so one Enter would reach the+ * draft as one empty line too many.+ */+export function installComposerDeletionGuard(+ editor: HTMLElement,+ onInsertLineBreak?: () => void,+): () => void {// Chromium reuses its original BR node on redo. Remember only nodes proven// spurious, never a string pattern that could also be an intentional newline.const placeholders = new WeakSet<HTMLBRElement>();let snapshot: DeletionSnapshot | null = null;const beforeInput = (event: InputEvent) => {snapshot = null;- if (event.isComposing || !event.inputType.startsWith("delete")) return;+ if (event.isComposing) return;+ if (+ onInsertLineBreak &&+ (event.inputType === "insertLineBreak" || event.inputType === "insertParagraph")+ ) {+ event.preventDefault();+ onInsertLineBreak();+ return;+ }+ if (!event.inputType.startsWith("delete")) return;const range = event.getTargetRanges()[0];if (!range || !editor.contains(range.startContainer) || !editor.contains(range.endContainer)) return;const before = readEditorValue(editor);diff --git a/apps/desktop/test/composer-native-deletion.test.mjs b/apps/desktop/test/composer-native-deletion.test.mjsindex 9b0b8bed3..ba6b9ba1c 100644--- a/apps/desktop/test/composer-native-deletion.test.mjs+++ b/apps/desktop/test/composer-native-deletion.test.mjs@@ -8,7 +8,7 @@ const [inputSource, deletionSource] = await Promise.all([]);test("composer input owns the native deletion guard", () => {- assert.match(inputSource, /installComposerDeletionGuard\(editor\)/);+ assert.match(inputSource, /installComposerDeletionGuard\(editor, \(\) => insertNewlineRef\.current\(\)\)/);assert.match(inputSource, /useLayoutEffect\(\(\) => \{/);assert.match(deletionSource, /event\.inputType\.startsWith\("delete"\)/);assert.match(deletionSource, /event\.getTargetRanges\(\)/);@@ -17,3 +17,12 @@ test("composer input owns the native deletion guard", () => {assert.match(deletionSource, /placeholders\.has\(br\)/);assert.doesNotMatch(deletionSource, /trim\(\)/);});++test("one Enter is one newline, owned by the editor", () => {+ // Chromium inserts the break plus a placeholder newline after the caret, so a+ // draft would gain an empty line the user did not ask for (#2555).+ assert.match(deletionSource, /event\.inputType === "insertLineBreak" \|\| event\.inputType === "insertParagraph"/);+ assert.match(deletionSource, /event\.preventDefault\(\);\n\s+onInsertLineBreak\(\);/);+ // React never dispatches the synthetic beforeinput event, so the guard owns it.+ assert.doesNotMatch(inputSource, /onBeforeInput/);+});diff --git a/apps/desktop/test/composer-tail-line.test.mjs b/apps/desktop/test/composer-tail-line.test.mjsindex db5ae84ea..ba3cb6e30 100644--- a/apps/desktop/test/composer-tail-line.test.mjs+++ b/apps/desktop/test/composer-tail-line.test.mjs@@ -1,87 +1,56 @@/**- * #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.+ * #2433 / #2555: the composer's empty last line.+ *+ * Chromium drops the last break of a block, so a draft that ends with a newline+ * paints no line of its own and a caret left there resolves to the line above.+ * The editor paints one placeholder break after it instead: a node with no text,+ * counted as zero characters by every read, index and caret path, so nothing can+ * be selected, copied or typed and the draft string never changes.*/import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import test from "node:test";-import ts from "typescript";-import vm from "node:vm";import { readComposerModule } from "./helpers/source-contracts.mjs";+import test from "node:test";-function loadFunction(path, name, globals = {}) {- const source = readFileSync(new URL(path, import.meta.url), "utf8");- const tree = ts.createSourceFile("module.ts", source, ts.ScriptTarget.Latest, true);- const node = tree.statements.find(- (statement) => ts.isFunctionDeclaration(statement) && statement.name?.text === name,- );- assert.ok(node, name);- const code = ts.transpileModule(node.getText(tree).replace(/^export\s+/, ""), {- compilerOptions: { target: ts.ScriptTarget.ES2022 },- }).outputText;- return vm.runInNewContext(`${code}\n${name};`, globals);-}--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);--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("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);+const [editor, draft, deletion] = await Promise.all([+ readComposerModule("editor.ts"),+ readComposerModule("hooks/useComposerDraft.ts"),+ readComposerModule("native-deletion.ts"),+]);++test("the empty last line is a placeholder break, not a character", () => {+ assert.match(editor, /const TAIL_PLACEHOLDER = "data-composer-tail";/);+ assert.match(editor, /function createTailPlaceholder\(\): HTMLBRElement \{/);+ assert.match(editor, /el\.appendChild\(createTailPlaceholder\(\)\);/);+ // The zero-width space this replaced was a real character: it could be+ // selected, copied, and some fonts render it as a space (#2555).+ assert.doesNotMatch(editor, /\\u200B/);+ assert.doesNotMatch(editor, /stripTailMarkers|markedTextLength|offsetForDraftIndex/);});-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");-- // 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 \?\? ""\);/);+test("every read, index and caret path counts the placeholder as nothing", () => {+ assert.match(editor, /if \(node\.nodeType === Node\.TEXT_NODE\) return \(node\.nodeValue \?\? ""\)\.length;/);+ assert.match(editor, /if \(isTailPlaceholder\(element\)\) return;/);+ assert.match(editor, /if \(isTailPlaceholder\(child\)\) continue;/);+ // The end-of-draft caret sits at the start of the empty line, before the break.assert.match(editor,- /point = \{ node: child, offset: offsetForDraftIndex\(child\.nodeValue \?\? "", remaining\) \};/,+ /if \(isTailPlaceholder\(child\)\) \{[\s\S]*?point = \{ node: parent, offset: index \};/,);+});- // 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\);/);-- // 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 \?\? ""\);/);+test("the placeholder is re-synced after every commit and never rewritten into text", () => {+ assert.match(editor, /export function syncTailPlaceholder\(el: HTMLElement\): void \{/);+ assert.match(editor, /if \(el\.lastChild !== placeholder\) el\.appendChild\(placeholder\);/);+ assert.match(editor, /for \(const placeholder of placeholders\) placeholder\.remove\(\);/);+ assert.match(draft, /if \(element\) syncTailPlaceholder\(element\);/);+ // Mutating a text node's value is what moved the caret off the tail (#2555).+ assert.doesNotMatch(editor, /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, /syncTailMarker/);+test("Chromium does not get to add a second newline for one Enter", () => {+ // A break command owns the draft: Chromium inserts the break plus a placeholder+ // newline after the caret, which reached the draft as one empty line too many.+ assert.match(deletion, /onInsertLineBreak/);+ assert.match(deletion, /event\.inputType === "insertLineBreak"/);+ assert.doesNotMatch(deletion, /syncTailPlaceholder/);});diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 1422e22a8..337c06cc3 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -4812,17 +4812,20 @@ 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 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.+An empty last line keeps its own caret. Chromium drops the last break of a block:+a draft that ends in a newline paints no line of its own, and a caret left there+resolves to the line above and types the next keystroke there. The editor paints a+placeholder break — `<br data-composer-tail>` — after that newline, and every read,+index and caret path counts it as zero characters. The placeholder carries no+text, so it cannot be selected, copied or typed, never merges into a neighbouring+text node, and the draft string and its indices are unchanged; the end-of-draft+caret sits before the placeholder, on the empty line, and the placeholder is+removed as soon as the line holds text. The editor also owns the break itself:+Chromium inserts the break plus a placeholder newline after the caret, which+reached the draft as one empty line too many, so a native `insertLineBreak` or+`insertParagraph` is prevented and the editor inserts a single newline. A middle+empty line keeps its existing behavior; the placeholder only covers the line that+ends the draft.### Dialog long-text containmentdiff --git a/package.json b/package.jsonindex f805121f2..0c75472cf 100644--- a/package.json+++ b/package.json@@ -42,6 +42,7 @@"test:e2e:composer-occlusion": "node scripts/e2e-theme-surfaces.mjs --dock-mask-only","test:e2e:composer-autocomplete": "node scripts/e2e-composer-autocomplete.mjs","test:e2e:composer-ime-slash": "node scripts/e2e-composer-ime-stack.mjs",+ "test:e2e:composer-tail-line": "node scripts/e2e-composer-tail-line.mjs","test:e2e:model-discovery-state": "node scripts/e2e-model-discovery-state.mjs","test:e2e:composer-model-selection": "node scripts/e2e-composer-model-selection.mjs","test:e2e:composer-paste": "node scripts/e2e-composer-paste.mjs",diff --git a/scripts/e2e-composer-tail-line.mjs b/scripts/e2e-composer-tail-line.mjsnew file mode 100644index 000000000..9d8a0bb4b--- /dev/null+++ b/scripts/e2e-composer-tail-line.mjs@@ -0,0 +1,221 @@+#!/usr/bin/env node+/**+ * Real-Chromium regression for the composer's empty last line (#2433, #2555).+ *+ * Mounts the production `useComposerDraft` + `useComposerCompletions` ++ * `ComposerInput` wiring and drives it with CDP keyboard input, the way a user+ * types: three lines, a break inside line 1, then typing and deleting at the+ * draft end. Every step asserts the draft, the painted line count, the caret's+ * draft index and that the editable holds no invisible character.+ */+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createRequire } from "node:module";+import { mkdtemp, readFile, rm, 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 { electronBinary } = resolveElectronBinary(root);+const temp = await mkdtemp(join(tmpdir(), "pi-composer-tail-"));+try {+ await build({+ entryPoints: [join(root, "scripts/e2e/composer-tail-line.tsx")],+ outfile: join(temp, "renderer.js"),+ bundle: true,+ platform: "browser",+ format: "iife",+ jsx: "automatic",+ loader: { ".woff": "file", ".woff2": "file", ".ttf": "file", ".png": "dataurl" },+ define: {+ "import.meta.env.DEV": "false",+ "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")],+ });+ await writeFile(+ join(temp, "tokens.css"),+ (await readFile(join(root, "apps/desktop/src/styles/tokens.css"), "utf8")).replace(+ /@theme(?: inline)?/g,+ ":root",+ ),+ );+ await writeFile(+ join(temp, "composer.css"),+ await readFile(join(root, "apps/desktop/src/styles/composer.css")),+ );+ await writeFile(+ join(temp, "index.html"),+ `<!doctype html><meta charset="utf-8"><link rel="stylesheet" href="tokens.css"><link rel="stylesheet" href="composer.css"><body style="margin:0;background:#111;color:#eee"><div id="root" style="width:640px"></div><script src="renderer.js"></script>`,+ );+ await writeFile(+ join(temp, "main.cjs"),+ `+const { app, BrowserWindow } = require("electron");+const path = require("node:path");+app.setPath("userData", path.join(__dirname, "profile"));+const SHIFT = 8;+const VK = { Enter: 13, Backspace: 8 };+app.whenReady().then(async () => {+ const window = new BrowserWindow({+ show: false, width: 760, height: 520,+ webPreferences: { offscreen: true, backgroundThrottling: false, sandbox: true, contextIsolation: true, nodeIntegration: false },+ });+ window.webContents.on("console-message", (event) => console.error("RENDERER " + event.message));+ try {+ await window.loadFile(path.join(__dirname, "index.html"));+ await window.webContents.debugger.attach("1.3");+ const js = (expression) => window.webContents.executeJavaScript(expression);+ const input = (method, params) => window.webContents.debugger.sendCommand("Input." + method, params);+ const frames = () => js("new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))");+ const state = async () => {+ await frames();+ return js("globalThis.composerTailState()");+ };+ const failures = [];+ const expect = (condition, message, snapshot) => {+ if (condition) return;+ failures.push(message + " " + JSON.stringify(snapshot));+ };+ const press = async (key, modifiers = 0) => {+ const text = key === "Enter" ? "\\r" : undefined;+ await input("dispatchKeyEvent", {+ type: text ? "keyDown" : "rawKeyDown",+ key, code: key, modifiers,+ windowsVirtualKeyCode: VK[key] ?? 0,+ nativeVirtualKeyCode: VK[key] ?? 0,+ ...(text ? { text, unmodifiedText: text } : {}),+ });+ await input("dispatchKeyEvent", {+ type: "keyUp", key, code: key, modifiers,+ windowsVirtualKeyCode: VK[key] ?? 0,+ nativeVirtualKeyCode: VK[key] ?? 0,+ });+ await frames();+ };+ const type = async (text) => {+ await input("insertText", { text });+ await frames();+ };+ const clickLine = async (line) => js("globalThis.composerTailClickLine(" + line + ")");++ await js("globalThis.composerTailReset('')");+ await js("document.querySelector('.composer-input').focus()");+ await type("1test");+ await press("Enter", SHIFT);+ await type("2test");+ await press("Enter", SHIFT);+ await type("3test");+ const typed = await state();+ expect(typed.value === "1test\\n2test\\n3test", "one Enter must add exactly one line", typed);+ expect(typed.lineTops.length === 3, "three lines must paint three line boxes", typed);+ expect(typed.invisibleChars.length === 0, "the editable must hold no invisible character", typed);+ expect(typed.caret === typed.value.length, "the caret must stay at the draft end", typed);++ await js("globalThis.composerTailCaret(5)");+ await press("Enter", SHIFT);+ const brokenInLine1 = await state();+ expect(+ brokenInLine1.value === "1test\\n\\n2test\\n3test",+ "a break inside line 1 must add exactly one line",+ brokenInLine1,+ );+ expect(brokenInLine1.lineTops.length === 4, "four lines must paint four line boxes", brokenInLine1);+ expect(brokenInLine1.invisibleChars.length === 0, "a break must not leave a character behind", brokenInLine1);+ expect(brokenInLine1.caret === 6, "the caret must sit on the new empty line", brokenInLine1);++ const clicks = [];+ for (const line of [1, 2, 3, 4]) {+ const clicked = await clickLine(line);+ clicks.push(clicked.clickLine);+ }+ expect(+ JSON.stringify(clicks) === JSON.stringify([5, 6, 12, 18]),+ "each painted line must map to its own draft offset",+ { clicks },+ );+ const beyondLast = await clickLine(5);+ expect(beyondLast.clickLine !== null && beyondLast.clickLine === 18, "there is no line below the last one", beyondLast);++ await js("globalThis.composerTailCaret(" + JSON.stringify("1test\\n\\n2test\\n3test".length) + ")");+ await type("x");+ const typedAtEnd = await state();+ expect(typedAtEnd.value === "1test\\n\\n2test\\n3testx", "typing at the end must append there", typedAtEnd);+ expect(typedAtEnd.caret === typedAtEnd.value.length, "typing at the end must keep the caret at the end", typedAtEnd);++ await press("Backspace");+ const deletedAtEnd = await state();+ expect(deletedAtEnd.value === "1test\\n\\n2test\\n3test", "Backspace at the end must drop the last character", deletedAtEnd);+ expect(deletedAtEnd.caret === deletedAtEnd.value.length, "Backspace must keep the caret at the end", deletedAtEnd);++ await press("Enter", SHIFT);+ const tailBreak = await state();+ expect(tailBreak.value === "1test\\n\\n2test\\n3test\\n", "a trailing break must add one line", tailBreak);+ expect(tailBreak.invisibleChars.length === 0, "an empty last line must hold no character", tailBreak);+ await type("z");+ const typedOnEmptyLine = await state();+ expect(typedOnEmptyLine.value === "1test\\n\\n2test\\n3test\\nz", "the keystroke must land on the empty line", typedOnEmptyLine);+ expect(typedOnEmptyLine.lineTops.length === 5, "the empty last line must keep its box", typedOnEmptyLine);++ if (failures.length > 0) {+ console.error("COMPOSER_TAIL_LINE " + JSON.stringify({ ok: false, failures }));+ app.exit(1);+ return;+ }+ console.log("COMPOSER_TAIL_LINE " + JSON.stringify({ ok: true, clicks, last: typedOnEmptyLine }));+ app.exit(0);+ } catch (error) {+ console.error("COMPOSER_TAIL_LINE " + JSON.stringify({ ok: false, error: String(error), stack: error && error.stack }));+ app.exit(1);+ }+});+`,+ );+ 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;+ });+ }+ const timeout = setTimeout(() => child.kill("SIGKILL"), 120_000);+ let code;+ try {+ code = await new Promise((resolve, reject) => {+ child.once("error", reject);+ child.once("close", resolve);+ });+ } finally {+ clearTimeout(timeout);+ }+ const line = output+ .split(/\r?\n/)+ .find((entry) => entry.startsWith("COMPOSER_TAIL_LINE "));+ if (!line) {+ console.error(output.slice(-6000));+ assert.fail(`renderer returned no tail-line result (exit=${code})`);+ }+ const result = JSON.parse(line.slice("COMPOSER_TAIL_LINE ".length));+ if (!result.ok) {+ console.error("COMPOSER_TAIL_LINE " + JSON.stringify(result, null, 2));+ assert.fail(`composer tail-line regression: ${result.failures?.join(" | ") ?? result.error}`);+ }+ console.log("COMPOSER_TAIL_LINE " + JSON.stringify(result));+ assert.equal(code, 0, output.slice(-4000));+} finally {+ await rm(temp, { recursive: true, force: true });+}diff --git a/scripts/e2e/composer-tail-line.tsx b/scripts/e2e/composer-tail-line.tsxnew file mode 100644index 000000000..032d1c928--- /dev/null+++ b/scripts/e2e/composer-tail-line.tsx@@ -0,0 +1,171 @@+/**+ * Fixture for the composer's empty last line (#2433, #2555).+ *+ * Mounts the production `useComposerDraft` + `useComposerCompletions` ++ * `ComposerInput` wiring so the real hook layouts run, and exposes the draft, the+ * painted line boxes and the caret's draft index for a CDP-driven key sequence.+ */+import { createRoot } from "react-dom/client";+import { createInstance, type TFunction } from "i18next";+import { I18nextProvider } from "react-i18next";+import { useComposerDraft } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerDraft";+import { useComposerCompletions } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerCompletions";+import { ComposerInput } from "../../apps/desktop/src/features/chat/composer/ComposerInput";+import { editorSelectionRange } from "../../apps/desktop/src/features/chat/composer/editor";++type Snapshot = {+ value: string;+ dom: string;+ caret: number;+ /** Distinct painted line tops of a range over the whole editor. */+ lineTops: number[];+ /** Invisible code points present in the editable. */+ invisibleChars: string[];+};++declare global {+ var composerTailState: () => Promise<Snapshot>;+ var composerTailReset: (text: string) => Promise<void>;+ var composerTailCaret: (index: number) => Promise<void>;+ var composerTailClickLine: (line: number) => Promise<Snapshot & { clickLine: number | null }>;+}++const noop = () => {};+const t = ((key: string) => key) as unknown as TFunction;+const i18n = createInstance();+let draftValue = "";+let draftCaret: (index: number) => void = noop;++function Fixture() {+ const draft = useComposerDraft({+ variant: "docked",+ activeSessionId: "s1",+ workspacePath: "/ws",+ sessions: [{ id: "s1" }],+ composerPrefill: null,+ clearComposerPrefill: noop,+ t,+ invalidateComposerTransforms: noop,+ inputBlocked: false,+ });+ const completions = useComposerCompletions({+ value: draft.value,+ cursor: draft.cursor,+ composing: draft.composing,+ enabled: true,+ referenceSessionId: "s1",+ fileReferencesRef: draft.fileReferencesRef,+ applyEditorDraft: draft.applyEditorDraft,+ handleInput: draft.handleInput,+ invalidateComposerTransforms: noop,+ });+ draftValue = draft.value;+ draftCaret = (index: number) => draft.applyEditorDraft(draft.value, [], index);+ globalThis.composerTailReset = async (text: string) => {+ draft.setComposing(false);+ draft.applyEditorDraft(text, [], text.length);+ await frames(2);+ };+ return (+ <I18nextProvider i18n={i18n}>+ <ComposerInput+ inputRef={draft.ref}+ value={draft.value}+ placeholderText=""+ placeholderKey="tail"+ inputBlocked={false}+ pasting={false}+ enterToSend={false}+ runActive={false}+ composerAc={completions.ac}+ onPaste={noop}+ onAcceptCompletion={completions.acceptCompletion}+ onSubmit={noop}+ onInsertNewline={() => draft.insertNewlineInEditor()}+ onHistoryNavigate={() => false}+ onInput={(source, caret, composing) => completions.handleInput(source, caret, composing)}+ onCompositionStart={() => draft.setComposing(true)}+ onCompositionEnd={() => draft.setComposing(false)}+ onSettledInput={() => draft.setComposing(false)}+ onFocus={noop}+ onBlur={noop}+ />+ </I18nextProvider>+ );+}++function frames(count: number): Promise<void> {+ return new Promise((resolve) => {+ let left = count;+ const step = () => (left <= 0 ? resolve() : ((left -= 1), requestAnimationFrame(step)));+ requestAnimationFrame(step);+ });+}++const INVISIBLE = new Set([0x200b, 0xfeff, 0x00a0]);++function editor(): HTMLElement {+ const element = document.querySelector<HTMLElement>(".composer-input");+ if (!element) throw new Error("composer input missing");+ return element;+}++function describe(value: string): Snapshot {+ const element = editor();+ const range = document.createRange();+ range.selectNodeContents(element);+ const lineTops = Array.from(+ new Set(Array.from(range.getClientRects()).map((rect) => Math.round(rect.top))),+ ).sort((a, b) => a - b);+ const invisibleChars: string[] = [];+ for (const char of element.textContent ?? "") {+ const code = char.codePointAt(0) ?? 0;+ if (INVISIBLE.has(code)) invisibleChars.push(`U+${code.toString(16)}`);+ }+ return {+ value,+ dom: element.innerHTML,+ caret: editorSelectionRange(element).start,+ lineTops,+ invisibleChars,+ };+}++globalThis.composerTailState = async () => {+ await frames(2);+ return describe(draftValue);+};++globalThis.composerTailCaret = async (index: number) => {+ draftCaret(index);+ await frames(2);+};++globalThis.composerTailClickLine = async (line: number) => {+ const element = editor();+ const rect = element.getBoundingClientRect();+ const lineHeight = Number.parseFloat(getComputedStyle(element).lineHeight) || 1;+ element.focus();+ await frames(1);+ const range = document.caretRangeFromPoint(+ Math.round(rect.left + 40),+ Math.round(rect.top + lineHeight * (line - 0.5)),+ );+ let clickLine: number | null = null;+ if (range) {+ const selection = window.getSelection();+ selection?.removeAllRanges();+ selection?.addRange(range);+ clickLine = editorSelectionRange(element).start;+ }+ await frames(1);+ return { ...describe(draftValue), clickLine };+};++createRoot(document.getElementById("root") as HTMLElement).render(+ <div className="composer-input-wrap">+ <div className="composer-input-stage">+ <Fixture />+ </div>+ </div>,+);