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): render mixed RTL/LTR paragraphs with content-aware direction
koeria1e2e43651e47
diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsxindex 9093a36d3..1f6e27660 100644--- a/apps/desktop/src/components/Markdown.tsx+++ b/apps/desktop/src/components/Markdown.tsx@@ -71,6 +71,7 @@ import { useReferencedImageDataUrl } from "../lib/use-referenced-image-data-url"import { absoluteImagePath, remarkLocalImagePaths } from "../lib/markdown-image-paths";import { remarkNormalizeWrappedMarkdownLinkDestinations } from "../lib/markdown-link-destinations";import { useOpenChatFileRef } from "../hooks/use-preview-target";+import { directionAttr } from "../lib/text-direction";import {useChatFileMenuItems,type ChatFileMenuTarget,@@ -833,8 +834,40 @@ const markdownComponents: Components = {audio: AudioBlock,video: VideoBlock,table: Table,+ p: BidiParagraph,+ li: BidiListItem,};+// #2388: mixed RTL/LTR paragraphs must not take their base direction from the+// first strong character alone. Each block paragraph picks its direction from+// the whole text (majority strong script), so a Persian paragraph that opens+// with an English word still reads right-to-left while embedded English runs,+// numbers, and code stay left-to-right inside it.+function textOfChildren(node: unknown): string {+ if (typeof node === "string") return node;+ if (typeof node === "number") return String(node);+ if (Array.isArray(node)) return node.map(textOfChildren).join("");+ if (+ node &&+ typeof node === "object" &&+ "props" in node &&+ node.props &&+ typeof node.props === "object" &&+ "children" in node.props+ ) {+ return textOfChildren(node.props.children);+ }+ return "";+}++function BidiParagraph({ children, ...rest }: ComponentProps<"p">) {+ return <p {...rest} dir={directionAttr(textOfChildren(children))}>{children}</p>;+}++function BidiListItem({ children, ...rest }: ComponentProps<"li">) {+ return <li {...rest} dir={directionAttr(textOfChildren(children))}>{children}</li>;+}+// The grammar the block splitter parses with, plus the renderer-only rewrite// of local image paths. `remarkLocalImagePaths` transforms URLs and moves no// block boundary, so the splitter has no reason to run it.diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsxindex 35cb8bfb6..ccce2584c 100644--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx@@ -39,6 +39,7 @@ import {useTranscriptMenu,} from "./TranscriptMenu";import { getExtraMessageAttachments } from "./extra-attachments";+import { directionAttr } from "../../../lib/text-direction";/*** The typed form of a Skill or `@agent` invocation (ADR 0346): each validated@@ -147,6 +148,13 @@ export const MessageRow = memo(function MessageRow({() => splitInlineContent(directories.text, message.attachments ?? []).parts,[message.attachments, directories.text],);+ // #2388: a Persian/Arabic paragraph opening with an English word must keep+ // its RTL base direction; direction follows the majority strong script, not+ // the first strong character.+ const userTextDirection = useMemo(+ () => directionAttr(directories.text),+ [directories.text],+ );const renderContentPart = (part: (typeof userContentParts)[number],index: number,@@ -337,7 +345,10 @@ export const MessageRow = memo(function MessageRow({</div>) : null}{directories.text || message.command ? (- <div className="message-user-text selectable">+ <div+ className="message-user-text selectable"+ dir={userTextDirection}+ >{editableUserMessage && message.command ? (<>{message.skillMentions?.length || message.agentMentions?.length ? (diff --git a/apps/desktop/src/lib/text-direction.ts b/apps/desktop/src/lib/text-direction.tsnew file mode 100644index 000000000..d44ccd225--- /dev/null+++ b/apps/desktop/src/lib/text-direction.ts@@ -0,0 +1,40 @@+/*+ * Content-aware paragraph direction for mixed RTL/LTR chat text (#2388).+ *+ * Relying on the first strong character (the `dir="auto"` / first-strong rule)+ * scrambles paragraphs that open with an English word but are otherwise+ * Persian/Arabic: the whole paragraph gets an LTR base direction and the RTL+ * runs, punctuation, and parentheses land on the wrong side. Instead we count+ * strong LTR and RTL characters and let the majority script pick the+ * paragraph's base direction; paragraphs without any strong character stay+ * 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;++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;+ return { ltr, rtl };+}++/**+ * Base direction for a paragraph of chat text. Returns "rtl" when RTL strong+ * characters outnumber LTR ones, "ltr" when LTR outnumber RTL, and "auto"+ * when neither script appears (punctuation-only or other neutral runs).+ */+export function detectTextDirection(text: string): TextDirection {+ const { ltr, rtl } = countStrongCharacters(text);+ if (rtl === 0 && ltr === 0) return "auto";+ return rtl > ltr ? "rtl" : "ltr";+}++/** Value for a `dir` attribute; undefined keeps the element direction-agnostic. */+export function directionAttr(text: string): "ltr" | "rtl" | undefined {+ const direction = detectTextDirection(text);+ return direction === "auto" ? undefined : direction;+}diff --git a/apps/desktop/src/styles/messages.css b/apps/desktop/src/styles/messages.cssindex feb93b7b4..325101675 100644--- a/apps/desktop/src/styles/messages.css+++ b/apps/desktop/src/styles/messages.css@@ -2005,6 +2005,25 @@line-height: inherit;}+/* #2388: inline chips and links inside a message are isolated runs — the+ surrounding RTL/LTR punctuation must not migrate across them. */+.message-user-text .chat-command-chip,+.message-user-text .chat-text-link,+.prose-chat a,+.prose-chat code,+.prose-chat strong,+.prose-chat em {+ unicode-bidi: isolate;+}++/* #2388: typed composer paragraphs follow the first strong character of the+ paragraph itself (per-paragraph auto direction), the standard editor+ behavior for mixed RTL/LTR drafts. */+.composer-input,+.message-edit-input {+ unicode-bidi: plaintext;+}+.message-row.session-message .message-col {width: min(100%, var(--chat-prose-max-width, 720px));max-width: 100%;diff --git a/apps/desktop/test/session-message-presentation.test.mjs b/apps/desktop/test/session-message-presentation.test.mjsindex ccfe7ef3a..d0b8398f0 100644--- a/apps/desktop/test/session-message-presentation.test.mjs+++ b/apps/desktop/test/session-message-presentation.test.mjs@@ -46,6 +46,7 @@ function loadComponent(name, extras = {}) {"../../../lib/remote-session-safety": { isRemoteSession, safeSessionSummary, sessionAllows },"../../../plugins/renderer-slots/use-slots": { useSlotSessionId: () => "local-session" },"../../../hooks/use-preview-target": { useOpenChatFileRef: () => () => {} },+ "../../../lib/text-direction": { directionAttr: () => undefined },"../../../lib/chat-links": { splitChatText: () => [] },"../../../components/Markdown": { Markdown: ({ source: text }) => text },"../../../components/icons": new Proxy({}, { get: () => Icon }),diff --git a/apps/desktop/test/session-reference-ui.test.mjs b/apps/desktop/test/session-reference-ui.test.mjsindex d3da4a338..22177314e 100644--- a/apps/desktop/test/session-reference-ui.test.mjs+++ b/apps/desktop/test/session-reference-ui.test.mjs@@ -83,6 +83,7 @@ const shared = load(new URL("../src/features/chat/transcript/shared.tsx", importuseOpenChatFileRef: () => () => {},useOpenPreviewTarget: () => undefined,},+ "../../../lib/text-direction": { directionAttr: () => undefined },"../../../hooks/use-chat-file-menu": { useChatFileMenu: () => ({}) },"../../../hooks/use-verified-chat-text": {// The real segmentation, so a session link in the body reaches its chip.@@ -125,6 +126,7 @@ const { MessageRow } = load(new URL("../src/features/chat/transcript/MessageRow."react-i18next": { useTranslation: () => ({ t, i18n: { language: locale } }) },"@pi-desktop/shared": await import("@pi-desktop/shared"),"../../../hooks/use-preview-target": { useOpenChatFileRef: () => () => {} },+ "../../../lib/text-direction": { directionAttr: () => undefined },"../../../lib/chat-links": { splitChatText: () => [] },"../../../components/Markdown": { Markdown: ({ source }) => source },"../../../components/icons": new Proxy({}, { get: () => Icon }),diff --git a/apps/desktop/test/text-direction.test.mjs b/apps/desktop/test/text-direction.test.mjsnew file mode 100644index 000000000..3bec97e1d--- /dev/null+++ b/apps/desktop/test/text-direction.test.mjs@@ -0,0 +1,77 @@+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");+ 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;/);+});