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(chat): classify Unicode letters and isolate message paragraphs
koeriaa0dc3a3bc36b
diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsxindex ccce2584c..047faf6f6 100644--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx@@ -159,22 +159,48 @@ export const MessageRow = memo(function MessageRow({part: (typeof userContentParts)[number],index: number,keyPrefix: string,- ) =>- part.kind === "text" ? (- <LinkifiedText- key={`${keyPrefix}-${index}`}- text={part.text}- attachments={message.attachments}- sourceOffset={part.start}- />- ) : (- <MessageAttachmentImage- key={`${keyPrefix}-${index}`}- attachment={part.attachment}- onOpenFile={openFileRef}- inline- />+ ) => part.kind === "text" ? (+ <LinkifiedText+ key={`${keyPrefix}-${index}`}+ text={part.text}+ attachments={message.attachments}+ sourceOffset={part.start}+ />+ ) : (+ <MessageAttachmentImage+ key={`${keyPrefix}-${index}`}+ attachment={part.attachment}+ onOpenFile={openFileRef}+ inline+ />+ );+ // Group the existing inline runs inside actual paragraph boxes. This gives+ // each paragraph its own base direction and alignment without moving chips+ // out of their paragraph or losing LinkifiedText's source offsets.+ const userParagraphs: ReactNode[] = [];+ let paragraphStart = 0;+ for (const paragraph of directories.text.match(/[^\n]*(?:\n+|$)/g) ?? []) {+ if (!paragraph) continue;+ const start = paragraphStart;+ const end = start + paragraph.length;+ paragraphStart = end;+ userParagraphs.push(+ <span key={start} dir={directionAttr(paragraph)} style={{ display: "block", textAlign: "start" }}>+ {userContentParts.map((part, index) => {+ if (part.end <= start || part.start >= end) return null;+ if (part.kind === "attachment") return renderContentPart(part, index, `paragraph-${start}`);+ const sliceStart = Math.max(start, part.start);+ const sliceEnd = Math.min(end, part.end);+ return renderContentPart({+ ...part,+ start: sliceStart,+ end: sliceEnd,+ text: part.text.slice(sliceStart - part.start, sliceEnd - part.start),+ }, index, `paragraph-${start}`);+ })}+ </span>,);+ }// An attachment the body does not already name inline continues the body// text instead of taking a line of its own above it.const attachmentChips = extraAttachments.length ? (@@ -369,9 +395,7 @@ export const MessageRow = memo(function MessageRow({.map((part, index) => renderContentPart(part, index, "inline"))}</>) : (- userContentParts.map((part, index) =>- renderContentPart(part, index, "content"),- )+ userParagraphs)}{attachmentChips}</div>diff --git a/apps/desktop/src/lib/text-direction.ts b/apps/desktop/src/lib/text-direction.tsindex d44ccd225..a1aa5653c 100644--- a/apps/desktop/src/lib/text-direction.ts+++ b/apps/desktop/src/lib/text-direction.ts@@ -10,15 +10,26 @@* neutral ("auto") so the renderer's first-strong fallback still applies.*/-const RTL_STRONG =- /[\u0590-\u05FF\u0600-\u065F\u066A-\u066F\u06FA-\u06FF\u0700-\u074F\u0750-\u077F\u07C0-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF]/g;-const LTR_STRONG = /[A-Za-z\u00C0-\u02AF\u0370-\u03FF\u0400-\u052F]/g;+// Unicode 17.0 UnicodeData.txt fields General_Category and Bidi_Class:+// https://www.unicode.org/Public/17.0.0/ucd/UnicodeData.txt+// All Letter characters in the RTL blocks below have Bidi_Class R/AL.+// The 26 neutral modifier letters are Letter but not strong L, R or AL.+// Keep the Letter guard: digits, punctuation and marks inside RTL blocks must+// not vote. Unknown letters follow the JS engine's Unicode property version.+const LETTER = /\p{Letter}/u;+const NEUTRAL_LETTER = /[\u02b9\u02ba\u02c6-\u02cf\u02ec\u0374\u2e2f\ua67f\ua717-\ua71f\ua788]/u;+const RTL_LETTER = /[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufefc\u{10800}-\u{10fff}\u{1e800}-\u{1edff}\u{1ee00}-\u{1eeff}]/u;export type TextDirection = "ltr" | "rtl" | "auto";export function countStrongCharacters(text: string): { ltr: number; rtl: number } {- const rtl = (text.match(RTL_STRONG) ?? []).length;- const ltr = (text.match(LTR_STRONG) ?? []).length;+ let ltr = 0;+ let rtl = 0;+ for (const character of text) {+ if (!LETTER.test(character) || NEUTRAL_LETTER.test(character)) continue;+ if (RTL_LETTER.test(character)) rtl++;+ else ltr++;+ }return { ltr, rtl };}diff --git a/apps/desktop/test/text-direction.test.mjs b/apps/desktop/test/text-direction.test.mjsindex 3bec97e1d..c4c00c1c4 100644--- a/apps/desktop/test/text-direction.test.mjs+++ b/apps/desktop/test/text-direction.test.mjs@@ -1,77 +1,44 @@import { register } from "node:module";import assert from "node:assert/strict";import test from "node:test";-import { readFile } from "node:fs/promises";register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));const { detectTextDirection, directionAttr, countStrongCharacters } = await import("../src/lib/text-direction.ts");-const PERSIAN_FIRST = "این یک تست است با کلمه React و next.js در وسط جمله.";-const ENGLISH_FIRST = "rtl یه متن بنویس فارسی قاطی میشه یا نه رندوم ببینم";-const ENGLISH_OPEN_PERSIAN_BODY = "hello این جمله فارسی است و باید راستبهچپ باشد";--test("counts strong LTR and RTL characters", () => {- const counts = countStrongCharacters("React و next.js");- assert.equal(counts.ltr, "Reactnextjs".length);- assert.equal(counts.rtl, 1);- assert.deepEqual(countStrongCharacters("1234 ... ()"), { ltr: 0, rtl: 0 });-});--test("RTL-dominant paragraphs are rtl even when they open with English", () => {- // The first-strong rule would call this ltr; the majority script is Persian.- assert.equal(detectTextDirection(ENGLISH_OPEN_PERSIAN_BODY), "rtl");- assert.equal(detectTextDirection(PERSIAN_FIRST), "rtl");- assert.equal(detectTextDirection(ENGLISH_FIRST), "rtl");-});--test("LTR-dominant paragraphs are ltr even when they end with Persian", () => {- assert.equal(detectTextDirection("fix the bug بعدا"), "ltr");- assert.equal(detectTextDirection("plain english only"), "ltr");-});--test("paragraphs without strong characters stay auto", () => {- // Arabic-Indic digits are weak (AN), punctuation neutral — no strong runs.- assert.equal(detectTextDirection("۱۲۳۴ ... !"), "auto");+test("counts all Persian letters, including the review regressions", () => {+ assert.deepEqual(countStrongCharacters("پچژگ"), { ltr: 0, rtl: 4 });+ assert.deepEqual(countStrongCharacters("پژگچ"), { ltr: 0, rtl: 4 });+ assert.equal(directionAttr("hello چپ چپ چپ چپ چپ"), "rtl");+ const alphabet = "اآبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهی";+ assert.deepEqual(countStrongCharacters(alphabet), { ltr: 0, rtl: [...alphabet].length });+});++test("digits, punctuation, combining marks and bidi controls do not vote", () => {+ for (const text of ["... ؟ ؛", "123٤٥۶۷۸۹", "\u0301\u0651\u0652", "\u200c\u200d\u202a\u202b\u2066\u2067"]) {+ assert.deepEqual(countStrongCharacters(text), { ltr: 0, rtl: 0 });+ assert.equal(directionAttr(text), undefined);+ }+ assert.deepEqual(countStrongCharacters("hello 123 ۱۲۳ ؟ ؛ \u0651"), { ltr: 5, rtl: 0 });+ assert.equal(directionAttr("hello 123 ۱۲۳ ؟ ؛ \u0651"), "ltr");+ assert.deepEqual(countStrongCharacters("e\u0301 پ\u0651"), { ltr: 1, rtl: 1 });+ assert.deepEqual(countStrongCharacters("\u02b9\u02ba\u02c6\u02cf\u02ec\u0374\u2e2f\ua67f\ua717\ua71f\ua788"), { ltr: 0, rtl: 0 });+});++test("RTL letters include presentation forms and supplementary historic scripts", () => {+ for (const text of ["שלום", "ܐܒ", "ހށ", "ߊߋ", "𞤀𞤁", "𐤀𐤁", "𐴀𐴁", "ﭖﭺ", "𞸀"]) {+ assert.deepEqual(countStrongCharacters(text), { ltr: 0, rtl: [...text].length });+ assert.equal(directionAttr(text), "rtl");+ }+});++test("majority letters, not the opening word or numbers, set direction", () => {+ for (const text of ["hello این جمله فارسی است و باید راستبهچپ باشد", "این یک تست است با کلمه React و next.js در وسط جمله.", "rtl یه متن بنویس فارسی قاطی میشه یا نه رندوم ببینم"]) {+ assert.equal(detectTextDirection(text), "rtl");+ }+ for (const text of ["fix the bug بعدا", "plain english only", "hello ۱۲۳۴۵۶۷۸۹۰ ؟ ؛"]) {+ assert.equal(detectTextDirection(text), "ltr");+ }+ assert.equal(detectTextDirection("aپ"), "ltr");assert.equal(detectTextDirection(""), "auto");});--test("directionAttr omits dir for neutral text and emits rtl/ltr otherwise", () => {- assert.equal(directionAttr("۱۲۳۴ ... !"), undefined);- assert.equal(directionAttr(PERSIAN_FIRST), "rtl");- assert.equal(directionAttr("plain english"), "ltr");-});--test("markdown paragraph and list renderers carry the content-aware dir", async () => {- const markdownSource = await readFile(- new URL("../src/components/Markdown.tsx", import.meta.url),- "utf8",- );- assert.match(markdownSource, /p: BidiParagraph/);- assert.match(markdownSource, /li: BidiListItem/);- assert.match(markdownSource, /dir=\{directionAttr\(textOfChildren\(children\)\)\}/);- assert.match(markdownSource, /from "\.\.\/lib\/text-direction"/);-});--test("user message bubbles and inline runs are direction-aware", async () => {- const rowSource = await readFile(- new URL("../src/features/chat/transcript/MessageRow.tsx", import.meta.url),- "utf8",- );- assert.match(rowSource, /dir=\{userTextDirection\}/);- assert.match(rowSource, /directionAttr\(directories\.text\)/);-});--test("styles isolate inline runs and give the composer per-paragraph auto direction", async () => {- const styles = await readFile(- new URL("../src/styles/messages.css", import.meta.url),- "utf8",- );- const isolate = styles.match(- /\.message-user-text \.chat-command-chip[\s\S]*?unicode-bidi: isolate;/,- )?.[0] ?? "";- assert.match(isolate, /\.prose-chat a/);- assert.match(isolate, /\.prose-chat code/);- const editor = styles.match(/\.composer-input,\n\.message-edit-input \{[\s\S]*?\}/)?.[0] ?? "";- assert.match(editor, /unicode-bidi: plaintext;/);-});diff --git a/scripts/e2e-bidi.mjs b/scripts/e2e-bidi.mjsnew file mode 100644index 000000000..1ca60eec5--- /dev/null+++ b/scripts/e2e-bidi.mjs@@ -0,0 +1,56 @@+#!/usr/bin/env node+// Focused production-component browser regression; no Electron/native host needed.+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createRequire } from "node:module";+import { mkdtemp, readFile, cp, writeFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+const root = fileURLToPath(new URL("../", import.meta.url));+const require = createRequire(join(root, "packages/agent-runtime/package.json"));+const { build } = require("esbuild");+const temp = await mkdtemp(join(tmpdir(), "pi-bidi-"));+try {+ await build({+ stdin: { contents: `import { bidiDirectionProbe } from './scripts/e2e/bidi-direction';+ import { createInstance } from 'i18next';+ import { en } from '@pi-desktop/i18n';+ const i18n = createInstance();+ i18n.init({lng:'en',resources:{en:{translation:en}},interpolation:{escapeValue:false}})+ .then(() => bidiDirectionProbe(i18n))+ .then(result => document.body.textContent = 'BIDI_RESULT ' + JSON.stringify(result))+ .catch(error => document.body.textContent = 'BIDI_ERROR ' + error.stack);`, resolveDir: root, loader: "tsx" },+ outfile: join(temp, "probe.js"), bundle: true, platform: "browser", format: "iife", jsx: "automatic",+ define: { "process.env.NODE_ENV": '"production"', "import.meta.env": '{"DEV":false,"MODE":"production"}' },+ loader: { ".css": "empty" },+ 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")],+ plugins: [{ name: "local-url-assets", setup(builder) {+ builder.onResolve({ filter: /\?url$/ }, ({ path, resolveDir }) => ({ path: resolve(resolveDir, path.slice(0, -4)), namespace: "asset" }));+ builder.onLoad({ filter: /.*/, namespace: "asset" }, async ({ path }) => ({ contents: await readFile(path), loader: "file" }));+ } }],+ });+ const renderer = join(root, "apps/desktop/out/renderer");+ const html = await readFile(join(renderer, "index.html"), "utf8");+ const css = [...html.matchAll(/href="([^" ]+\.css)"/g)].map(match => match[1]);+ assert(css.length, "build desktop first");+ await cp(join(renderer, "assets"), join(temp, "assets"), { recursive: true });+ await writeFile(join(temp, "index.html"), `<!doctype html><meta charset="utf-8">${css.map(path => `<link rel="stylesheet" href="${path}">`).join("")}<body><script src="probe.js"></script>`);+ const binary = process.env.CHROMIUM_BINARY;+ assert(binary, "set CHROMIUM_BINARY to an installed Chromium/headless-shell binary");+ const child = spawn(binary, ["--no-sandbox", "--headless", "--disable-gpu", "--allow-file-access-from-files", "--dump-dom", "--virtual-time-budget=10000", `file://${join(temp, "index.html")}`], { stdio: ["ignore", "pipe", "pipe"] });+ let output = "", errors = "";+ child.stdout.on("data", chunk => output += chunk);+ child.stderr.on("data", chunk => errors += chunk);+ const timer = setTimeout(() => child.kill("SIGKILL"), 60000);+ const code = await new Promise((done, reject) => { child.on("error", reject); child.on("close", done); }).finally(() => clearTimeout(timer));+ assert.equal(code, 0, errors);+ const match = output.match(/BIDI_RESULT (\{[^<]+\})/);+ assert(match, output + errors);+ const result = JSON.parse(match[1].replaceAll(""", '"').replaceAll("&", "&"));+ assert.equal(result.ok, true);+ console.log("BIDI_RESULT " + JSON.stringify(result));+} finally {+ await rm(temp, { recursive: true, force: true });+}diff --git a/scripts/e2e/bidi-direction.tsx b/scripts/e2e/bidi-direction.tsxnew file mode 100644index 000000000..9652c48be--- /dev/null+++ b/scripts/e2e/bidi-direction.tsx@@ -0,0 +1,131 @@+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import type { RefObject } from "react";+import type { createInstance } from "i18next";+import { I18nextProvider } from "react-i18next";+import type { UiMessage } from "@pi-desktop/shared";+import { paintEditorValue, readEditorValue } from "../../apps/desktop/src/features/chat/composer/editor";+import { ComposerInput } from "../../apps/desktop/src/features/chat/composer/ComposerInput";+import { ChatTranscript } from "../../apps/desktop/src/features/chat/transcript/ChatTranscript";+import { useAppStore } from "../../apps/desktop/src/stores/app-store";++function assert(value: unknown, message: string): asserts value {+ if (!value) throw new Error(message);+}+const message = (id: string, role: UiMessage["role"], content: string): UiMessage => ({+ id, role, content, createdAt: "2026-09-13T00:00:00.000Z",+});++/** Exercise the production bubble, Markdown and composer in a real browser DOM. */+export async function bidiDirectionProbe(i18n: ReturnType<typeof createInstance>) {+ const host = document.createElement("div");+ host.style.cssText = "position:absolute;left:0;top:0;width:900px";+ document.body.append(host);+ const root = createRoot(host);+ const initialStore = useAppStore.getState();+ const sessionId = "bidi-direction-probe";+ const messages = [+ message("bidi-user", "user", "hello English paragraph 123!\n\nپژگچ این پاراگراف فارسی است ؟"),+ message("bidi-assistant", "assistant", "English **paragraph** 123!\n\nپژگچ **پاسخ** فارسی ؟ ؛\n\n- English item\n- پژگچ فارسی"),+ ];+ try {+ useAppStore.setState({ activeSessionId: sessionId, page: "chat" });+ flushSync(() => root.render(+ <I18nextProvider i18n={i18n}>+ <ChatTranscript sessionId={sessionId} messages={messages} isRunning={false} />+ </I18nextProvider>,+ ));+ const bubble = host.querySelector<HTMLElement>(".message-user-text");+ assert(bubble, "production user message bubble did not render");+ const bubbleDirections = [...bubble.querySelectorAll<HTMLElement>("span[dir]")]+ .map((element) => element.getAttribute("dir"));+ assert(+ bubbleDirections.includes("ltr") && bubbleDirections.includes("rtl"),+ `user message paragraphs did not get independent directions: ${bubbleDirections.join(",")}`,+ );+ const markdownParagraphs = [...host.querySelectorAll<HTMLElement>(".prose-chat p")];+ assert(markdownParagraphs.length >= 2, "production Markdown paragraphs did not render");+ assert(+ markdownParagraphs[0]?.dir === "ltr" && markdownParagraphs[1]?.dir === "rtl",+ `Markdown paragraph directions were ${markdownParagraphs.map((p) => p.dir).join(",")}`,+ );++ const composerHost = document.createElement("div");+ host.append(composerHost);+ const composerRoot = createRoot(composerHost);+ const inputRef = { current: null } as RefObject<HTMLDivElement | null>;+ flushSync(() => composerRoot.render(+ <ComposerInput+ inputRef={inputRef}+ value={"hello\n\nپژگچ"}+ placeholderText=""+ placeholderKey=""+ inputBlocked={false}+ pasting={false}+ enterToSend={true}+ runActive={false}+ composerAc={{ close() {}, open: false, hasItems: false, items: [], highlight: 0, setHighlight() {} } as never}+ onPaste={() => {}}+ onAcceptCompletion={() => {}}+ onSubmit={() => {}}+ onInsertNewline={() => {}}+ onInput={() => {}}+ onHistoryNavigate={() => false}+ onCompositionStart={() => {}}+ onCompositionEnd={() => {}}+ onSettledInput={() => {}}+ onFocus={() => {}}+ onBlur={() => {}}+ />+ ));+ const editor = composerHost.querySelector<HTMLElement>(".composer-input");+ assert(editor, "production composer did not render");+ const draft = "hello 123!\nپژگچ فارسی ؟";+ paintEditorValue(editor, draft, new Map(), () => "", () => {}, () => {}, () => {}, () => {});+ assert(readEditorValue(editor) === draft, "production editor changed the mixed draft");+ // Range geometry verifies visual order, not merely attributes or source text.+ const glyph = (element: Element, character: string) => {+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);+ while (walker.nextNode()) {+ const node = walker.currentNode;+ const offset = node.textContent?.indexOf(character) ?? -1;+ if (offset < 0) continue;+ const range = document.createRange();+ range.setStart(node, offset);+ range.setEnd(node, offset + character.length);+ const rect = range.getBoundingClientRect();+ assert(rect.width > 0, `glyph ${character} has no rendered geometry`);+ return rect.x;+ }+ throw new Error(`glyph ${character} missing`);+ };+ const composerOrder = {+ english: glyph(editor, "!") > glyph(editor, "h"),+ persian: glyph(editor, "؟") < glyph(editor, "پ"),+ };+ assert(composerOrder.english && composerOrder.persian, "composer punctuation order is wrong");+ const rtlBubble = bubble.querySelector<HTMLElement>('span[dir="rtl"]');+ assert(rtlBubble && getComputedStyle(rtlBubble).direction === "rtl", "bubble RTL paragraph has no RTL layout");+ assert(glyph(rtlBubble, "؟") < glyph(rtlBubble, "پ"), "bubble punctuation order is wrong");+ const listDirections = [...host.querySelectorAll<HTMLElement>(".prose-chat li")].map(item => item.dir);+ assert(listDirections.join(",") === "ltr,rtl", `Markdown list directions: ${listDirections}`);+ const emphasis = host.querySelector(".prose-chat strong");+ assert(emphasis && getComputedStyle(emphasis).unicodeBidi === "isolate", "inline Markdown is not isolated");+ assert(bubble.textContent === messages[0].content, "paragraph splitting changed user text");+ const rtlMarkdown = markdownParagraphs[1];+ assert(rtlMarkdown && glyph(rtlMarkdown, "؟") < glyph(rtlMarkdown, "پ"), "Markdown punctuation order is wrong");+ assert(+ getComputedStyle(editor).unicodeBidi === "plaintext",+ `composer unicode-bidi was ${getComputedStyle(editor).unicodeBidi}`,+ );+ assert(editor.getAttribute("contenteditable") === "true", "composer is not editable");+ const composerUnicodeBidi = getComputedStyle(editor).unicodeBidi;+ composerRoot.unmount();+ composerHost.remove();+ return { ok: true, bubbleDirections, markdownDirections: markdownParagraphs.map((p) => p.dir), composerUnicodeBidi, composerOrder };+ } finally {+ root.unmount();+ host.remove();+ useAppStore.setState({ activeSessionId: initialStore.activeSessionId, page: initialStore.page });+ }+}diff --git a/scripts/e2e/transcript-render.tsx b/scripts/e2e/transcript-render.tsxindex 1c0d220ae..6d270ff4e 100644--- a/scripts/e2e/transcript-render.tsx+++ b/scripts/e2e/transcript-render.tsx@@ -6,6 +6,7 @@ import { transcriptStatusProbe } from "./transcript-status";import { createRoot } from "react-dom/client";import { flushSync } from "react-dom";import { useState } from "react";+import { bidiDirectionProbe } from "./bidi-direction";import { createInstance } from "i18next";import { I18nextProvider } from "react-i18next";import { en } from "@pi-desktop/i18n";@@ -720,13 +721,15 @@ globalThis.transcriptRenderProbe = async () => {render([message("normal-user", "user", "Reply"), message("normal-answer", "assistant", "Complete answer")]);assert(!container.querySelector('.message-output-notice'), "normal answer has a truncation warning");+ const bidi = await bidiDirectionProbe(i18n);const statusLifecycle = await transcriptStatusProbe();const markdownLinks = await markdownLinkInteractionProbe(i18n);const contextMenuSubmenu = await contextMenuSubmenuInteractionProbe();const turnProcess = await turnProcessProbe();const autoCollapse = await transcriptAutoCollapseProbe();return {- ok: statusLifecycle.ok && markdownLinks.ok && contextMenuSubmenu.ok && turnProcess.ok,+ ok: bidi.ok && statusLifecycle.ok && markdownLinks.ok && contextMenuSubmenu.ok && turnProcess.ok,+ bidi,statusLifecycle,markdownLinks,contextMenuSubmenu,