Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(markdown): add table copy, CSV export and expanded preview
yuxinoaa0979a71363
diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsxindex 253829c8c..b203631e6 100644--- a/apps/desktop/src/components/Markdown.tsx+++ b/apps/desktop/src/components/Markdown.tsx@@ -38,6 +38,8 @@ import {} from "./icons";import { TooltipButton } from "./ui";import { ContextMenu, useContextMenu } from "./ContextMenu";+import { MarkdownTable } from "./MarkdownTable";+import { markdownTableData } from "../lib/markdown-table";import { api } from "../lib/api";import { openHttpUrl } from "../lib/open-http-url";import {@@ -396,6 +398,7 @@ function MermaidBlock({ code, ...position }: { code: string } & SourcePositionPrconst MarkdownBlockContext = createContext({closedFence: false,renderDiagrams: true,+ originalRaw: "",});const MarkdownBaseDirContext = createContext("");@@ -668,15 +671,21 @@ function MarkdownImage({}function Table({- node: _node,+ node,children,...rest-}: ComponentProps<"table"> & { node?: unknown }) {- return (+}: ComponentProps<"table"> & { node?: Parameters<typeof markdownTableData>[0] }) {+ const { originalRaw } = useContext(MarkdownBlockContext);+ const data = useMemo(+ () => node ? markdownTableData(node, originalRaw) : null,+ [node, originalRaw],+ );+ const table = (<div className="table-wrap"><table {...rest}>{children}</table></div>);+ return data ? <MarkdownTable {...data}>{table}</MarkdownTable> : table;}/** Inline audio player for audio URLs in markdown. */@@ -819,8 +828,9 @@ const Block = memo(function MarkdownBlock({() => ({closedFence: isClosedFencedCodeBlock(raw),renderDiagrams,+ originalRaw,}),- [raw, renderDiagrams],+ [raw, originalRaw, renderDiagrams],);const remarkPlugins = useMemo(() => [diff --git a/apps/desktop/src/components/MarkdownTable.tsx b/apps/desktop/src/components/MarkdownTable.tsxnew file mode 100644index 000000000..5ea332851--- /dev/null+++ b/apps/desktop/src/components/MarkdownTable.tsx@@ -0,0 +1,160 @@+import { useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { useBlockingOverlay } from "../lib/blocking-overlay";+import { useAppStore } from "../stores/app-store";+import { IconClose, IconCopy, IconDownload, IconPanelMaximize } from "./icons";+import { portalOverlay, TooltipButton } from "./ui";+import "../styles/markdown-table.css";++function TablePreview({ children, onClose }: {+ children: ReactNode;+ onClose: () => void;+}) {+ const { t } = useTranslation();+ const dialogRef = useRef<HTMLDivElement>(null);+ const closeRef = useRef<HTMLButtonElement>(null);+ useBlockingOverlay();+ useLayoutEffect(() => {+ const previousFocus = document.activeElement;+ const previousOverflow = document.body.style.overflow;+ document.body.style.overflow = "hidden";+ closeRef.current?.focus();+ return () => {+ document.body.style.overflow = previousOverflow;+ if (previousFocus instanceof HTMLElement && previousFocus.isConnected) previousFocus.focus();+ };+ }, []);+ const handleKeyDown = (event: KeyboardEvent) => {+ event.stopPropagation();+ if (event.key === "Escape") {+ event.preventDefault();+ onClose();+ }+ if (event.key !== "Tab") return;+ const focusable = dialogRef.current?.querySelectorAll<HTMLElement>(+ 'button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])',+ );+ if (!focusable?.length) return;+ const first = focusable[0];+ const last = focusable[focusable.length - 1];+ if (event.shiftKey && document.activeElement === first) {+ event.preventDefault();+ last.focus();+ } else if (!event.shiftKey && document.activeElement === last) {+ event.preventDefault();+ first.focus();+ }+ };+ return portalOverlay(+ <div+ className="overlay markdown-table-overlay"+ role="presentation"+ onKeyDown={handleKeyDown}+ onClick={(event) => {+ if (event.target === event.currentTarget) onClose();+ }}+ >+ <div+ ref={dialogRef}+ className="dialog markdown-table-preview"+ role="dialog"+ aria-modal="true"+ aria-label={t("chat.tablePreview")}+ >+ <header className="markdown-table-preview-head">+ <span>{t("chat.tablePreview")}</span>+ <TooltipButton+ ref={closeRef}+ type="button"+ className="icon-btn"+ tooltip={t("chat.closeTablePreview")}+ onClick={onClose}+ >+ <IconClose size={16} />+ </TooltipButton>+ </header>+ <div className="markdown-table-preview-body prose-chat">{children}</div>+ </div>+ </div>,+ );+}++export function MarkdownTable({ children, markdown, csv }: {+ children: ReactNode;+ markdown: string;+ csv: string;+}) {+ const { t } = useTranslation();+ const showToast = useAppStore((state) => state.showToast);+ const [preview, setPreview] = useState(false);+ const copy = async () => {+ try {+ await navigator.clipboard.writeText(markdown);+ showToast(t("chat.tableCopied"), { variant: "success" });+ } catch {+ showToast(t("chat.tableCopyFailed"), { variant: "error" });+ }+ };+ const download = () => {+ let url: string | undefined;+ const link = document.createElement("a");+ try {+ url = URL.createObjectURL(new Blob([csv], { type: "text/csv;charset=utf-8" }));+ link.href = url;+ link.download = "table.csv";+ document.body.append(link);+ link.click();+ } catch {+ showToast(t("chat.tableExportFailed"), { variant: "error" });+ } finally {+ link.remove();+ // Keep the URL alive until the browser has consumed the download click.+ if (url) {+ const downloadUrl = url;+ window.setTimeout(() => URL.revokeObjectURL(downloadUrl), 1000);+ }+ }+ };+ const toolbar = (expanded = false) => (+ <div className="markdown-table-actions" role="group" aria-label={t("chat.tableActions")}>+ <TooltipButton+ type="button"+ className="icon-btn"+ tooltip={t("chat.copyTableMarkdown")}+ onClick={() => void copy()}+ >+ <IconCopy size={14} />+ </TooltipButton>+ <TooltipButton+ type="button"+ className="icon-btn"+ tooltip={t("chat.exportTableCsv")}+ onClick={download}+ >+ <IconDownload size={14} />+ </TooltipButton>+ {!expanded ? (+ <TooltipButton+ type="button"+ className="icon-btn"+ tooltip={t("chat.tablePreview")}+ onClick={() => setPreview(true)}+ >+ <IconPanelMaximize size={14} />+ </TooltipButton>+ ) : null}+ </div>+ );+ return (+ <div className="markdown-table">+ {toolbar()}+ {children}+ {preview ? (+ <TablePreview onClose={() => setPreview(false)}>+ {toolbar(true)}+ {children}+ </TablePreview>+ ) : null}+ </div>+ );+}diff --git a/apps/desktop/src/lib/markdown-table.ts b/apps/desktop/src/lib/markdown-table.tsnew file mode 100644index 000000000..dcb257f93--- /dev/null+++ b/apps/desktop/src/lib/markdown-table.ts@@ -0,0 +1,74 @@+/** The sanitized HAST subset used by the Markdown table renderer. */+export interface TableNode {+ type: string;+ tagName?: string;+ value?: string;+ properties?: Record<string, unknown>;+ position?: { start: { offset?: number }; end: { offset?: number } };+ children?: TableNode[];+}++function rowsOf(node: TableNode): TableNode[] {+ return (node.children ?? []).flatMap((child) =>+ child.tagName === "tr" ? [child]+ : ["thead", "tbody", "tfoot"].includes(child.tagName ?? "") ? rowsOf(child) : [],+ );+}++function findMathSource(node: TableNode): string | undefined {+ if (node.tagName === "annotation") return (node.children ?? []).map(cellText).join("");+ for (const child of node.children ?? []) {+ const source = findMathSource(child);+ if (source !== undefined) return source;+ }+}++function cellText(node: TableNode): string {+ if (node.type === "text") return node.value ?? "";+ if (node.tagName === "br") return "\n";+ if (node.tagName === "img") return String(node.properties?.alt ?? "");+ if (["script", "style"].includes(node.tagName ?? "")) return "";+ // KaTeX emits both MathML and a visual tree. Export the formula once.+ if (Array.isArray(node.properties?.className) && node.properties.className.includes("katex")) {+ return findMathSource(node) ?? "";+ }+ return (node.children ?? []).map(cellText).join("");+}++function csvCell(value: string): string {+ // Spreadsheet applications may execute formula-leading values even in quotes.+ const numeric = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(value);+ const safe = !numeric && (/^\s*[=+\-@]/.test(value) || /^[\t\r\n]/.test(value))+ ? `'${value}` : value;+ return `"${safe.replace(/"/g, '""')}"`;+}++/** Export one table, without reading unrelated tables or duplicating UI labels. */+export function markdownTableData(node: TableNode, originalSource: string) {+ const tableStart = node.position?.start.offset;+ const htmlTable = tableStart !== undefined && /^<table\b/i.test(originalSource.slice(tableStart));+ const rows = rowsOf(node);+ const cells = rows.map((row) => (row.children ?? []).filter((cell) =>+ cell.tagName === "th" || cell.tagName === "td",+ ));+ const textRows = cells.map((row) => row.map(cellText));+ const markdownRows = rows.map((row, index) => {+ const start = row.position?.start.offset;+ const end = row.position?.end.offset;+ const source = start !== undefined && end !== undefined+ ? originalSource.slice(start, end).trim() : "";+ // Parser row slices omit blockquote/list indentation. Keep inline Markdown+ // and escaped pipes intact; raw HTML tables fall back to plain-text cells.+ if (source && !htmlTable) return source;+ return `| ${textRows[index].map((text) => text.replace(/\\/g, "\\\\")+ .replace(/\|/g, "\\|").replace(/\r?\n/g, "<br>")).join(" | ")} |`;+ });+ const divider = `| ${(cells[0] ?? []).map((cell) => {+ const align = cell.properties?.align;+ return align === "center" ? ":---:" : align === "right" ? "---:" : align === "left" ? ":---" : "---";+ }).join(" | ")} |`;+ return {+ markdown: markdownRows.length ? [markdownRows[0], divider, ...markdownRows.slice(1)].join("\n") : "",+ csv: `\uFEFF${textRows.map((row) => row.map(csvCell).join(",")).join("\r\n")}\r\n`,+ };+}diff --git a/apps/desktop/src/styles/markdown-table.css b/apps/desktop/src/styles/markdown-table.cssnew file mode 100644index 000000000..2af62758e--- /dev/null+++ b/apps/desktop/src/styles/markdown-table.css@@ -0,0 +1,51 @@+.markdown-table { min-width: 0; margin: 0.9em 0; }+.markdown-table-actions { display: flex; justify-content: flex-end; gap: 2px; margin-bottom: 4px; }+.markdown-table-actions .icon-btn { width: 28px; height: 28px; color: var(--ds-text-secondary); }+.markdown-table-actions .icon-btn:hover { color: var(--ds-text-primary); background: var(--ds-tile-hover); }+.prose-chat .markdown-table > .table-wrap { margin: 0; }++.overlay.markdown-table-overlay { padding: 16px; }+.dialog.markdown-table-preview {+ display: flex;+ flex-direction: column;+ width: min(1100px, calc(100vw - 32px));+ max-width: none;+ max-height: calc(100dvh - 32px);+ margin: auto;+ padding: 0;+ border: 1px solid var(--ds-border-default);+ border-radius: var(--radius-lg);+ color: var(--ds-text-primary);+ background: var(--ds-bg-elevated-opaque);+}+.markdown-table-preview-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ flex-shrink: 0;+ gap: 12px;+ padding: 12px 16px;+ font-size: var(--text-md);+ font-weight: var(--font-weight-medium);+}+.markdown-table-preview-body { min-height: 0; overflow: auto; padding: 0 16px 16px; }+.markdown-table-preview-body::-webkit-scrollbar-corner { background: transparent; }+.markdown-table-preview-body.prose-chat .table-wrap { margin: 0; overflow: visible; }+/* A reading preview keeps useful column widths and scrolls on small windows. */+.markdown-table-preview-body.prose-chat .table-wrap table {+ width: max-content;+ min-width: 100%;+}+.markdown-table-preview-body.prose-chat th,+.markdown-table-preview-body.prose-chat td {+ min-width: 8rem;+ max-width: 32rem;+ overflow-wrap: break-word;+}+.markdown-table-preview-body.prose-chat th {+ position: sticky;+ top: 0;+ z-index: 1;+ /* The inline table's translucent header would expose scrolling rows. */+ background: color-mix(in oklab, var(--ds-bg-elevated-opaque), var(--ds-text-primary) 8%);+}diff --git a/apps/desktop/test/fixtures/markdown-table-runner.cjs b/apps/desktop/test/fixtures/markdown-table-runner.cjsnew file mode 100644index 000000000..573a42d6b--- /dev/null+++ b/apps/desktop/test/fixtures/markdown-table-runner.cjs@@ -0,0 +1,107 @@+const { app, BrowserWindow, clipboard } = require("electron");+const assert = require("node:assert/strict");+const { readFileSync, writeFileSync } = require("node:fs");+const { join } = require("node:path");+const dir = process.env.PI_TABLE_TEST_DIR;+let passed = 0;+const watchdog = setTimeout(() => {+ console.error("Table interaction test exceeded 45 seconds");+ app.exit(1);+}, 45_000);+app.whenReady().then(async () => {+ const win = new BrowserWindow({ width: 1100, height: 800, show: true, webPreferences: { sandbox: true, contextIsolation: true } });+ // Keep the app shell's navigation restrictions at the download boundary.+ win.webContents.on("will-navigate", (event) => event.preventDefault());+ win.webContents.setWindowOpenHandler(() => ({ action: "deny" }));+ const evaluate = (source) => win.webContents.executeJavaScript(source, true);+ const wait = async (source) => {+ const deadline = Date.now() + 8000;+ while (!(await evaluate(source))) {+ if (Date.now() > deadline) {+ console.error(await evaluate('JSON.stringify({focus: document.hasFocus(), toast: window.tableFixture.toast(), buttons: [...document.querySelectorAll("button")].map(el => ({label: el.getAttribute("aria-label"), rect: el.getBoundingClientRect().toJSON()}))})'));+ throw new Error(`Timed out: ${source}`);+ }+ await new Promise((resolve) => setTimeout(resolve, 30));+ }+ };+ const check = (name, actual) => { assert.ok(actual, name); passed++; console.log(`PASS ${name}`); };+ const click = async (selector) => {+ win.focus();+ win.webContents.focus();+ await wait('document.hasFocus()');+ await evaluate('Promise.all(document.getAnimations().map(animation => animation.finished.catch(() => {})))');+ const point = await evaluate(`(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (!el) throw Error('Missing control'); el.scrollIntoView({block:'center'}); const r = el.getBoundingClientRect(); return {x:Math.round(r.x+r.width/2),y:Math.round(r.y+r.height/2)}; })()`);+ win.webContents.sendInputEvent({ type: "mouseDown", button: "left", clickCount: 1, ...point });+ win.webContents.sendInputEvent({ type: "mouseUp", button: "left", clickCount: 1, ...point });+ };+ const key = async (keyCode, modifiers = []) => {+ win.webContents.sendInputEvent({ type: "keyDown", keyCode, modifiers });+ win.webContents.sendInputEvent({ type: "keyUp", keyCode, modifiers });+ };+ await win.loadFile(join(dir, "index.html"));+ win.webContents.focus();+ await wait('document.querySelectorAll(".markdown-table").length === 2');+ check("production Markdown renders one toolbar per table", await evaluate('document.querySelectorAll(".markdown-table-actions").length === 2'));+ await click('.markdown-table button[aria-label="Copy table as Markdown"]');+ await wait('window.tableFixture.toast()?.message === "Table copied"');+ check("copy preserves this table's inline Markdown and alignment", clipboard.readText() === '| **Product** | Note |\n| :--- | ---: |\n| Pi | 你好, world |\n| ZCode | say "hi"<br>again |');+ const downloaded = new Promise((resolve, reject) => {+ win.webContents.session.once("will-download", (_event, item) => {+ item.setSavePath(join(dir, "table.csv"));+ item.once("done", (_e, state) => state === "completed" ? resolve() : reject(Error(state)));+ });+ });+ await click('.markdown-table button[aria-label="Download table as CSV"]');+ await downloaded;+ check("CSV download contains UTF-8, escaped quotes and cell line breaks", readFileSync(join(dir, "table.csv"), "utf8") === '\uFEFF"Product","Note"\r\n"Pi","你好, world"\r\n"ZCode","say ""hi""\nagain"\r\n');+ await click('.markdown-table button[aria-label="Expand table"]');+ await wait('Boolean(document.querySelector("[role=dialog]"))');+ check("preview uses modal semantics and masks native views", await evaluate('document.querySelector("[role=dialog]").getAttribute("aria-modal") === "true" && window.tableFixture.isBlockingOverlayActive()'));+ check("preview contains only its own table", await evaluate('document.querySelector("[role=dialog]").textContent.includes("你好") && !document.querySelector("[role=dialog]").textContent.includes("untouched")'));+ check("focus starts on close", await evaluate('document.activeElement.getAttribute("aria-label") === "Close table preview"'));+ await key("Tab", ["shift"]);+ check("Shift-Tab stays inside the modal", await evaluate('Boolean(document.activeElement.closest("[role=dialog]"))'));+ await key("Escape");+ await wait('!document.querySelector("[role=dialog]")');+ check("Escape returns focus to expand and releases the overlay", await evaluate('document.activeElement.getAttribute("aria-label") === "Expand table" && !window.tableFixture.isBlockingOverlayActive()'));+ await evaluate('window.tableFixture.render("| A |\\n| --- |\\n| initial |")');+ await click('button[aria-label="Expand table"]');+ await wait('Boolean(document.querySelector("[role=dialog]"))');+ await evaluate('window.tableFixture.render(window.tableFixture.source + "\\n| streamed |")');+ check("an open preview follows streamed rows", await evaluate('document.querySelector("[role=dialog]").textContent.includes("streamed")'));+ const previousToast = await evaluate('window.tableFixture.toast()?.id');+ await click('[role=dialog] button[aria-label="Copy table as Markdown"]');+ await wait(`window.tableFixture.toast()?.id !== ${JSON.stringify(previousToast)} && window.tableFixture.toast()?.message === "Table copied"`);+ check("copy in preview uses the latest rows", clipboard.readText().includes("streamed"));+ check("copy feedback is visible above the preview", await evaluate('(() => { const toast = [...document.querySelectorAll(".toast")].at(-1); const r = toast.getBoundingClientRect(); return document.elementsFromPoint(r.x + r.width / 2, r.y + r.height / 2).some(el => el === toast || el.closest(".toast") === toast); })()'));+ await click('button[aria-label="Close table preview"]');+ await wait('!document.querySelector("[role=dialog]")');+ await evaluate('window.tableFixture.render("| Product | Notes |\\n| --- | --- |\\n" + Array.from({length: 40}, (_, i) => `| Item ${i + 1} | A longer description to check wrapping 中文 |`).join("\\n"))');+ for (const theme of ["light", "dark"]) {+ win.setContentSize(360, 500);+ await evaluate(`window.tableFixture.render(window.tableFixture.source, "zh-CN", ${JSON.stringify(theme)})`);+ await click('button[aria-label="放大表格"]');+ await wait('Boolean(document.querySelector("[role=dialog]"))');+ check(`${theme} narrow preview stays within viewport`, await evaluate('(() => { const r = document.querySelector("[role=dialog]").getBoundingClientRect(); return r.left >= 0 && r.right <= innerWidth && r.top >= 0 && r.bottom <= innerHeight; })()'));+ check(`${theme} long table scrolls inside the preview`, await evaluate('(() => { const body = document.querySelector(".markdown-table-preview-body"); return body.scrollHeight > body.clientHeight && getComputedStyle(body).overflowY === "auto"; })()'));+ check(`${theme} narrow preview scrolls horizontally instead of crushing columns`, await evaluate('(() => { const body = document.querySelector(".markdown-table-preview-body"); const header = document.querySelector("[role=dialog] th"); const range = document.createRange(); range.selectNodeContents(header); return body.scrollWidth > body.clientWidth && range.getClientRects().length === 1; })()'));+ check(`${theme} sticky header is opaque`, await evaluate('(() => { const canvas = document.createElement("canvas"); const context = canvas.getContext("2d"); context.fillStyle = getComputedStyle(document.querySelector("[role=dialog] th")).backgroundColor; context.fillRect(0, 0, 1, 1); return context.getImageData(0, 0, 1, 1).data[3] === 255; })()'));+ await evaluate('document.querySelector(".markdown-table-preview-body").scrollTop = 150');+ check(`${theme} header stays visible while scrolling`, await evaluate('(() => { const body = document.querySelector(".markdown-table-preview-body").getBoundingClientRect(); const head = document.querySelector("[role=dialog] th").getBoundingClientRect(); return Math.abs(body.top - head.top) < 2; })()'));+ await evaluate('Promise.all(document.getAnimations().map(animation => animation.finished.catch(() => {}))).then(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))))');+ writeFileSync(join(dir, `${theme}-preview.png`), (await win.webContents.capturePage()).toPNG());+ await key("Escape");+ await wait('!document.querySelector("[role=dialog]")');+ }+ await evaluate('Object.defineProperty(navigator, "clipboard", {configurable:true,value:{writeText:async()=>{throw Error("denied")}}})');+ await click('button[aria-label="复制表格为 Markdown"]');+ await wait('window.tableFixture.toast()?.message === "无法复制表格"');+ check("clipboard denial produces an error instead of success", await evaluate('window.tableFixture.toast()?.variant === "error"'));+ await evaluate('URL.createObjectURL = () => { throw Error("unavailable") }; void 0');+ await click('button[aria-label="下载表格为 CSV"]');+ await wait('window.tableFixture.toast()?.message === "无法下载表格"');+ check("download setup failure produces an error", await evaluate('window.tableFixture.toast()?.variant === "error"'));+ console.log(`${passed} table interaction checks passed`);+ clearTimeout(watchdog);+ win.destroy(); app.exit(0);+}).catch((error) => { clearTimeout(watchdog); console.error(error); app.exit(1); });diff --git a/apps/desktop/test/fixtures/markdown-table.jsx b/apps/desktop/test/fixtures/markdown-table.jsxnew file mode 100644index 000000000..34f4cbc15--- /dev/null+++ b/apps/desktop/test/fixtures/markdown-table.jsx@@ -0,0 +1,27 @@+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import { createInstance } from "i18next";+import { I18nextProvider } from "react-i18next";+import { catalogs } from "@pi-desktop/i18n";+import { Markdown } from "../../src/components/Markdown";+import { ToastHost } from "../../src/components/Toast";+import { useAppStore } from "../../src/stores/app-store";+import { isBlockingOverlayActive } from "../../src/lib/blocking-overlay";++const i18n = createInstance();+await i18n.init({ lng: "en", resources: Object.fromEntries(+ ["en", "zh-CN"].map((locale) => [locale, { translation: catalogs[locale] }]),+), interpolation: { escapeValue: false } });+const root = createRoot(document.getElementById("root"));+window.tableFixture = {+ source: "Intro\n\n| **Product** | Note |\n| :--- | ---: |\n| Pi | 你好, world |\n| ZCode | say \"hi\"<br>again |\n\nSecond\n\n| Other |\n| --- |\n| untouched |",+ isBlockingOverlayActive,+ async render(source = this.source, locale = "en", theme = "light") {+ this.source = source;+ document.documentElement.dataset.theme = theme;+ await i18n.changeLanguage(locale);+ flushSync(() => root.render(<I18nextProvider i18n={i18n}><main className="prose-chat" style={{ padding: 24 }}><Markdown source={source} /></main><ToastHost /></I18nextProvider>));+ },+ toast: () => useAppStore.getState().toasts.at(-1),+};+await window.tableFixture.render();diff --git a/apps/desktop/test/markdown-table.test.mjs b/apps/desktop/test/markdown-table.test.mjsnew file mode 100644index 000000000..62a24e495--- /dev/null+++ b/apps/desktop/test/markdown-table.test.mjs@@ -0,0 +1,71 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import ReactMarkdown from "react-markdown";+import remarkGfm from "remark-gfm";+import remarkMath from "remark-math";+import rehypeRaw from "rehype-raw";+import rehypeSanitize from "rehype-sanitize";+import rehypeKatex from "rehype-katex";+import { markdownTableData } from "../src/lib/markdown-table.ts";++function exportsOf(source) {+ const tables = [];+ renderToStaticMarkup(createElement(ReactMarkdown, {+ remarkPlugins: [remarkGfm, remarkMath],+ rehypePlugins: [rehypeRaw, rehypeSanitize, rehypeKatex],+ components: { table({ node }) { tables.push(markdownTableData(node, source)); return null; } },+ }, source));+ return tables;+}++test("each table keeps its own Markdown formatting and column alignment", () => {+ const source = "Before\n\n| **Name** | Value |\n| :--- | ---: |\n| [Docs](https://example.com) | `a\\|b` |\n\nOther\n\n| Next |\n| --- |\n| 二 |";+ const [first, second] = exportsOf(source);+ assert.equal(first.markdown, "| **Name** | Value |\n| :--- | ---: |\n| [Docs](https://example.com) | `a\\|b` |");+ assert.equal(first.csv, '\uFEFF"Name","Value"\r\n"Docs","a|b"\r\n');+ assert.equal(second.markdown, "| Next |\n| --- |\n| 二 |");+ assert.equal(second.csv, '\uFEFF"Next"\r\n"二"\r\n');+});++test("quoted/list tables copy as standalone tables, including Windows line endings", () => {+ for (const source of [+ "> | A | B |\r\n> | --- | :---: |\r\n> | **one** | two |",+ "- Example\n\n | A | B |\n | --- | :---: |\n | **one** | two |",+ ]) {+ assert.equal(exportsOf(source)[0].markdown, "| A | B |\n| --- | :---: |\n| **one** | two |");+ }+});++test("CSV quotes delimiters, quotes, Unicode, empty cells and line breaks", () => {+ const [data] = exportsOf('| A | B | C |\n| --- | --- | --- |\n| 你好, world | say "hi"<br>again | |');+ assert.equal(data.csv, '\uFEFF"A","B","C"\r\n"你好, world","say ""hi""\nagain",""\r\n');+});++test("pipe-less Markdown rows may start with inline HTML", () => {+ const [data] = exportsOf('<em>Name</em> | Value\n--- | ---\n<strong>Pi</strong> | `code`');+ assert.equal(data.markdown, '<em>Name</em> | Value\n| --- | --- |\n<strong>Pi</strong> | `code`');+});++test("spreadsheet formulas are text while ordinary signed numbers stay numeric", () => {+ const [data] = exportsOf('| A | B | C | D |\n| --- | --- | --- | --- |\n| =SUM(1,2) | +cmd | @name | -2.5 |');+ assert.equal(data.csv, '\uFEFF"A","B","C","D"\r\n"\'=SUM(1,2)","\'+cmd","\'@name","-2.5"\r\n');+});++test("math is exported once and images contribute their alternative text", () => {+ const [data] = exportsOf('| Formula | Image |\n| --- | --- |\n| $a+b$ |  |');+ assert.equal(data.csv, '\uFEFF"Formula","Image"\r\n"a+b","diagram"\r\n');+});++test("raw HTML tables export sanitized visible text as a Markdown table", () => {+ const [data] = exportsOf('<table><tr><th>A</th><th>B</th></tr><tr><td>x|y</td><td>one<br>two<script>bad()</script></td></tr></table>');+ assert.equal(data.markdown, '| A | B |\n| --- | --- |\n| x\\|y | one<br>two |');+ assert.equal(data.csv, '\uFEFF"A","B"\r\n"x|y","one\ntwo"\r\n');+});++test("a streaming table exports the rows currently rendered", () => {+ const start = '| A |\n| --- |';+ assert.equal(exportsOf(start)[0].csv, '\uFEFF"A"\r\n');+ assert.equal(exportsOf(`${start}\n| next |`)[0].csv, '\uFEFF"A"\r\n"next"\r\n');+});diff --git a/docs/project/unreleased.md b/docs/project/unreleased.mdindex bc12e7a45..7a7a2a8cf 100644--- a/docs/project/unreleased.md+++ b/docs/project/unreleased.md@@ -1,5 +1,8 @@# Unreleased changes+- Copy individual Markdown tables, download them as CSV, or expand them for+ reading without leaving the conversation.+- The Composer reasoning slider now moves smoothly to clicked orkeyboard-selected levels, follows dragging immediately, and respectsreduced-motion settings. Rapid clicks redirect the animation; failed savesdiff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex e01aac822..72455cfc1 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -2001,6 +2001,24 @@ Renderer: `apps/desktop/src/components/Markdown.tsx` + `apps/desktop/src/lib/shiheight derives from `--composer-dock-height`, which the composer republishes asits draft grows, so dashes move without a marker change or a window resize.+#### Markdown table actions++Every rendered Markdown table has its own compact toolbar: Copy as Markdown,+Download as CSV, and Expand table. Copy preserves inline Markdown and column+alignment and produces a standalone table even inside a quote or list. CSV+contains the displayed cell text, UTF-8 with BOM, quoted fields, and CRLF rows;+quotes and cell line breaks are escaped, and formula-leading nonnumeric cells+are exported as text. Clipboard failures produce an error toast.++The expanded view uses a modal dialog with the existing theme tokens, a scrollable+table and opaque sticky headers, and copy/download controls. Columns retain+readable minimum widths; narrow previews scroll horizontally instead of crushing+short labels. It follows streamed rows,+contains keyboard focus, closes with Escape or Close, and restores focus to its+trigger. Native work-panel surfaces remain hidden while the modal is open.+Tables retain their existing inline layout and link/file actions. No editing,+sorting, new settings, persistence, or host protocol is introduced.+---## 9. ToolCallRowdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 39a771835..fe49670dc 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -14479,3 +14479,24 @@ the latest destination. These assertions measure work counts, not device FPS.- **Scenario:** Workspace identity.- **Expected:** Stored workspace bindings use the existing project canonicalization contract on both write and read. On Windows, slash direction, case, trailing separators and extended path prefixes do not hide a task from its own project's conversation. The distinction between missing legacy bindings and explicit null remains unchanged. Foreign-project tools cannot list or mutate bound tasks.- **Automation:** `node --experimental-strip-types scripts/e2e-scheduled-paths.mjs` uses an isolated real Host and SQLite profile. Inference is not sent to a live provider.++### E2E-MARKDOWN-table-actions++- **Setup**: Render a conversation containing two Markdown tables, including+ aligned columns, formatted text, Chinese text, commas, quotes, and `<br>` cells.+- **Steps**: Copy the first table; download its CSV; expand it; use copy inside+ the modal; close with Escape and with Close. Append a streamed row while the+ preview is open. Repeat the preview at a narrow width in light/dark themes+ and English/Chinese. Deny clipboard writes at the browser boundary.+- **Expected**: Actions operate only on their own table. Markdown retains inline+ syntax and alignment. CSV decodes as UTF-8 and preserves fields and line breaks.+ The modal fits the viewport, traps focus, updates streamed rows, blocks native+ work-panel surfaces, and returns focus on dismissal. Narrow previews keep short+ headers on one line and scroll horizontally; sticky headers fully cover the+ rows behind them. Failed copies report an+ error, not success. Existing table wrapping remains intact.+- **Automated coverage**: `node --test apps/desktop/test/markdown-table.test.mjs`+ and `node scripts/test-markdown-table.mjs` after building the desktop. The+ latter mounts the production Markdown component in an isolated Electron+ window and exercises real clipboard/download boundaries. It does not call a+ model or use the user's app profile.diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 023a9d62e..9cc334c69 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -1422,6 +1422,24 @@ Renderer: `apps/desktop/src/components/Markdown.tsx` + `apps/desktop/src/lib/s`content-visibility: auto` 和屏外美人鱼图延迟加载和布局,直到它们接近视口。+#### Markdown table actions++Every rendered Markdown table has its own compact toolbar: Copy as Markdown,+Download as CSV, and Expand table. Copy preserves inline Markdown and column+alignment and produces a standalone table even inside a quote or list. CSV+contains the displayed cell text, UTF-8 with BOM, quoted fields, and CRLF rows;+quotes and cell line breaks are escaped, and formula-leading nonnumeric cells+are exported as text. Clipboard failures produce an error toast.++The expanded view uses a modal dialog with the existing theme tokens, a scrollable+table and opaque sticky headers, and copy/download controls. Columns retain+readable minimum widths; narrow previews scroll horizontally instead of crushing+short labels. It follows streamed rows,+contains keyboard focus, closes with Escape or Close, and restores focus to its+trigger. Native work-panel surfaces remain hidden while the modal is open.+Tables retain their existing inline layout and link/file actions. No editing,+sorting, new settings, persistence, or host protocol is introduced.+---## 9. ToolCallRowdiff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 3015ed50a..d65bc3181 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -8632,3 +8632,24 @@ the latest destination. These assertions measure work counts, not device FPS.缺失的旧版绑定与显式 null 保持不同语义,其他项目不能查询或修改绑定任务。- **自动化**:`node --experimental-strip-types scripts/e2e-scheduled-paths.mjs`使用隔离的真实 Host 与 SQLite 配置,不向真实提供商发送推理请求。++### E2E-MARKDOWN-table-actions++- **Setup**: Render a conversation containing two Markdown tables, including+ aligned columns, formatted text, Chinese text, commas, quotes, and `<br>` cells.+- **Steps**: Copy the first table; download its CSV; expand it; use copy inside+ the modal; close with Escape and with Close. Append a streamed row while the+ preview is open. Repeat the preview at a narrow width in light/dark themes+ and English/Chinese. Deny clipboard writes at the browser boundary.+- **Expected**: Actions operate only on their own table. Markdown retains inline+ syntax and alignment. CSV decodes as UTF-8 and preserves fields and line breaks.+ The modal fits the viewport, traps focus, updates streamed rows, blocks native+ work-panel surfaces, and returns focus on dismissal. Narrow previews keep short+ headers on one line and scroll horizontally; sticky headers fully cover the+ rows behind them. Failed copies report an+ error, not success. Existing table wrapping remains intact.+- **Automated coverage**: `node --test apps/desktop/test/markdown-table.test.mjs`+ and `node scripts/test-markdown-table.mjs` after building the desktop. The+ latter mounts the production Markdown component in an isolated Electron+ window and exercises real clipboard/download boundaries. It does not call a+ model or use the user's app profile.diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex bf3a8c7de..94209bc7f 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -204,6 +204,14 @@ export const de = {sessionMissing: "Diese Sitzung existiert nicht mehr",},"chat": {+ "tableActions": "Tabellenaktionen",+ "copyTableMarkdown": "Tabelle als Markdown kopieren",+ "exportTableCsv": "Tabelle als CSV herunterladen",+ "tablePreview": "Tabelle vergrößern",+ "closeTablePreview": "Tabellenvorschau schließen",+ "tableCopied": "Tabelle kopiert",+ "tableCopyFailed": "Tabelle konnte nicht kopiert werden",+ "tableExportFailed": "Tabelle konnte nicht heruntergeladen werden",imagePreview: {title: "Bildvorschau",download: "Bild herunterladen",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 39010342e..e12de8f3f 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -211,6 +211,14 @@ export const en = {sessionMissing: "That session no longer exists",},chat: {+ tableActions: "Table actions",+ copyTableMarkdown: "Copy table as Markdown",+ exportTableCsv: "Download table as CSV",+ tablePreview: "Expand table",+ closeTablePreview: "Close table preview",+ tableCopied: "Table copied",+ tableCopyFailed: "Could not copy the table",+ tableExportFailed: "Could not download the table",imagePreview: {title: "Image preview",download: "Download image",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex c2f8087be..016305cdb 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -204,6 +204,14 @@ export const es = {sessionMissing: "Esa sesión ya no existe",},"chat": {+ "tableActions": "Acciones de tabla",+ "copyTableMarkdown": "Copiar tabla como Markdown",+ "exportTableCsv": "Descargar tabla como CSV",+ "tablePreview": "Ampliar tabla",+ "closeTablePreview": "Cerrar vista previa de la tabla",+ "tableCopied": "Tabla copiada",+ "tableCopyFailed": "No se pudo copiar la tabla",+ "tableExportFailed": "No se pudo descargar la tabla",imagePreview: {title: "Vista previa de imagen",download: "Descargar imagen",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex db98920a8..cd64fdceb 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -204,6 +204,14 @@ export const fr = {sessionMissing: "Cette session n'existe plus",},"chat": {+ "tableActions": "Actions du tableau",+ "copyTableMarkdown": "Copier le tableau en Markdown",+ "exportTableCsv": "Télécharger le tableau en CSV",+ "tablePreview": "Agrandir le tableau",+ "closeTablePreview": "Fermer l’aperçu du tableau",+ "tableCopied": "Tableau copié",+ "tableCopyFailed": "Impossible de copier le tableau",+ "tableExportFailed": "Impossible de télécharger le tableau",imagePreview: {title: "Aperçu de l’image",download: "Télécharger l’image",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 45baff3d5..5e618cd8b 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -213,6 +213,14 @@ export const ko = {sessionMissing: "해당 세션이 더 이상 존재하지 않습니다",},chat: {+ tableActions: "표 작업",+ copyTableMarkdown: "표를 Markdown으로 복사",+ exportTableCsv: "표를 CSV로 다운로드",+ tablePreview: "표 확대",+ closeTablePreview: "표 미리보기 닫기",+ tableCopied: "표가 복사되었습니다",+ tableCopyFailed: "표를 복사할 수 없습니다",+ tableExportFailed: "표를 다운로드할 수 없습니다",imagePreview: {title: "이미지 미리보기",download: "이미지 다운로드",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex c220b0870..972ae24d9 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -213,6 +213,14 @@ export const tr = {sessionMissing: "Bu oturum artık mevcut değil",},chat: {+ tableActions: "Tablo işlemleri",+ copyTableMarkdown: "Tabloyu Markdown olarak kopyala",+ exportTableCsv: "Tabloyu CSV olarak indir",+ tablePreview: "Tabloyu büyüt",+ closeTablePreview: "Tablo önizlemesini kapat",+ tableCopied: "Tablo kopyalandı",+ tableCopyFailed: "Tablo kopyalanamadı",+ tableExportFailed: "Tablo indirilemedi",imagePreview: {title: "Görsel önizlemesi",download: "Görseli indir",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 02dc5da61..22d155442 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -206,6 +206,14 @@ export const zhCN = {sessionMissing: "该会话已不存在",},chat: {+ tableActions: "表格操作",+ copyTableMarkdown: "复制表格为 Markdown",+ exportTableCsv: "下载表格为 CSV",+ tablePreview: "放大表格",+ closeTablePreview: "关闭表格预览",+ tableCopied: "表格已复制",+ tableCopyFailed: "无法复制表格",+ tableExportFailed: "无法下载表格",imagePreview: {title: "图片预览",download: "下载图片",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex d6f46a189..ebc78cbc4 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -206,6 +206,14 @@ export const zhTW = {sessionMissing: "該對話已不存在",},chat: {+ tableActions: "表格操作",+ copyTableMarkdown: "複製表格為 Markdown",+ exportTableCsv: "下載表格為 CSV",+ tablePreview: "放大表格",+ closeTablePreview: "關閉表格預覽",+ tableCopied: "已複製表格",+ tableCopyFailed: "無法複製表格",+ tableExportFailed: "無法下載表格",imagePreview: {title: "圖片預覽",download: "下載圖片",diff --git a/scripts/test-markdown-table.mjs b/scripts/test-markdown-table.mjsnew file mode 100644index 000000000..4d5deee75--- /dev/null+++ b/scripts/test-markdown-table.mjs@@ -0,0 +1,31 @@+/** Real Markdown/React in isolated Electron; clipboard and downloads use Chromium. */+import { createRequire } from "node:module";+import { spawn } from "node:child_process";+import { mkdtemp, readFile, writeFile, cp } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { repositoryRoot, resolveElectronBinary } from "./e2e/boot.mjs";++const root = repositoryRoot();+const temp = await mkdtemp(join(tmpdir(), "pi-markdown-table-"));+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");+await build({+ entryPoints: [join(root, "apps/desktop/test/fixtures/markdown-table.jsx")],+ outfile: join(temp, "fixture.js"), bundle: true, format: "esm", platform: "browser", jsx: "automatic",+ define: { "import.meta.env.DEV": "false", "process.env.NODE_ENV": '"production"' },+ loader: { ".css": "empty" },+});+const renderer = join(root, "apps/desktop/out/renderer");+const appHtml = await readFile(join(renderer, "index.html"), "utf8");+const csp = appHtml.match(/<meta[^>]+http-equiv="Content-Security-Policy"[^>]*>/i)?.[0];+if (!csp) throw new Error("Desktop renderer Content-Security-Policy is missing");+const styles = [...appHtml.matchAll(/href="([^" ]+\.css)"/g)].map((match) => match[1]);+if (!styles.length) throw new Error("Build the Desktop renderer before running the table test");+await cp(join(renderer, "assets"), join(temp, "assets"), { recursive: true });+await writeFile(join(temp, "index.html"), `<!doctype html><html><head><meta charset="utf-8">${csp}${styles.map((path) => `<link rel="stylesheet" href="${path}">`).join("")}</head><body><div id="root"></div><script type="module" src="./fixture.js"></script></body></html>`);+const env = { ...process.env, PI_TABLE_TEST_DIR: temp };+delete env.ELECTRON_RUN_AS_NODE;+const electron = process.env.PI_TABLE_ELECTRON ?? resolveElectronBinary(root).electronBinary;+const child = spawn(electron, [`--user-data-dir=${join(temp, "profile")}`, join(root, "apps/desktop/test/fixtures/markdown-table-runner.cjs")], { env, stdio: "inherit" });+process.exitCode = await new Promise((resolve, reject) => { child.on("exit", (code) => resolve(code ?? 1)); child.on("error", reject); });+console.log(`Table test artifacts: ${temp}`);