A local-first multi-agent app development platform, built on PenguinHarness
feat(web): mentions show names, ticket paths become capsules, the organization status is a text pill (#753)
Yaowei Zhengd0d89fe6ed37
diff --git a/changelog/unreleased/2026-09-16-company-readable-names.md b/changelog/unreleased/2026-09-16-company-readable-names.mdnew file mode 100644index 00000000..d2cf6fa5--- /dev/null+++ b/changelog/unreleased/2026-09-16-company-readable-names.md@@ -0,0 +1,60 @@+# Company mode shows names and folders where it showed ids and paths++- **Date:** 2026-09-16+- **Type:** feature+- **Scope:** `web`+- **PR:** [#753](https://github.com/Prism-Shadow/penguin-harness/pull/753)++[中文版](2026-09-16-company-readable-names.zh.md)++Three company-mode surfaces stopped making people read machine spellings: an `@` picked in a+channel composer writes the Agent's name instead of its id, a data path in a ticket renders as a+folder capsule, and the organization's status sits beside its name as a text capsule.++## Mentions in the channel composer++- Picking from the `@` menu wrote the display name into the box (`@Ada Lovelace`), tinted the way+ a sent message's mention chip is, where it had written the id. The message sent still carries the+ id (`@ceo`, `@user:alice`, `@all`), so the server, delivery and `mention_not_member` did not+ change.+- A picked mention became one block. Backspace right after it or Delete right before it removed+ the whole name at once, and so did a word delete, a cut or a typed-over selection that reached+ into it. The caret stepped over the name, and a click or a selection that ended inside it moved+ to its edge. Ctrl+Z after that Backspace or Delete brought the mention back whole, and an input+ method's composition that reached into a name removed it when the composition ended.+- A copy, a cut or a drag of text holding picked mentions carried them along: pasted or dropped+ into a channel composer, each came back as a mention, while other apps received the names as+ plain text. A mention came back only when its name was still what that channel shows for its+ id, so `@Name` text from anywhere else stayed plain.+- A mention glued to the text around it (`x@Ada`, `@Ada.md`) went out with a space that sets its+ token apart, so it was still delivered, and so was an `@id` typed right after it (`@张三@ceo`).+ Employees who share a name stay apart, and a typed or pasted `@id` works as before.+- The menu also matched names typed in any script (`@张`), and an IME's Enter while composing after+ the `@` stopped picking a candidate.++## Paths in tickets++- The ticket dialog's goal, acceptance criteria, progress lines, result and blocked reason drew+ data paths as capsules: a folder or file glyph and the last segment, the full path on hover, and+ a click that copies the path exactly as written, the glyph turning into a check. The stored text+ did not change.+- A path is `<app_data_dir>/…`, or an absolute path that passes through the Project's+ `organizations/` or `agents/` directory, with `/`, `\` or both as separators, so the paths a+ Windows server writes (`C:\Users\…\.penguin\data\…`) count too. In prose it is made of ASCII+ file-name characters, so it stops at a space, CJK text or punctuation, and a trailing full stop+ stays outside it. A path that runs on through a non-ASCII segment (`…/workspace/调研报告.md`)+ or in from one (`C:\Users\张三\…`), and this server's own routes+ (`/api/projects/…/organizations/…`), stay text. An inline code span holding one path and nothing+ else becomes a capsule verbatim; fenced blocks, commands in code spans and link labels stay as+ written. A trailing separator, or a last segment without an extension, reads as a folder; a last+ segment with an extension, as a file.+- In the Markdown fields a path written with backslashes was copied as the source writes it,+ although Markdown reads a backslash before punctuation as an escape and drops it from the text.++## Organization status++- The organization switcher's trigger showed the status as a text capsule to the right of the name+ — 运行中 / 已暂停 / 配置无效, in English Running / Paused / Invalid configuration — in place of the+ dot before it. The name truncates first, and the status joined the trigger's accessible name.+- The English label for an organization that is not paused changed from "Active" to "Running"+ everywhere it appears.diff --git a/changelog/unreleased/2026-09-16-company-readable-names.zh.md b/changelog/unreleased/2026-09-16-company-readable-names.zh.mdnew file mode 100644index 00000000..a92a7e30--- /dev/null+++ b/changelog/unreleased/2026-09-16-company-readable-names.zh.md@@ -0,0 +1,42 @@+# 公司模式在原先显示 id 和路径的地方显示名称和文件夹++- **Date:** 2026-09-16+- **Type:** feature+- **Scope:** `web`+- **PR:** [#753](https://github.com/Prism-Shadow/penguin-harness/pull/753)++[English](2026-09-16-company-readable-names.md)++公司模式有三处不再让人读机器写法:在频道输入框里 `@` 选中的 Agent 写入名称而不是 id,工单里的数据路径渲染为文件夹胶囊,+组织状态以文字胶囊的形式放在组织名称旁边。++## 频道输入框里的提及++- 从 `@` 菜单选中后,输入框写入的是显示名称(`@Ada Lovelace`),并按已发送消息里提及标签的样子着色;此前写入的是 id。+ 发出的消息仍然携带 id(`@ceo`、`@user:alice`、`@all`),因此服务端、投递与 `mention_not_member` 均未改变。+- 选中的提及成为一个整体:在其后按退格或在其前按 Delete 一次删去整个名称,触及它的按词删除、剪切或输入覆盖选区同样整段删去;+ 光标跨过名称移动,落在名称内部的点击或选区端点移到其边缘。上述退格或 Delete 之后按 Ctrl+Z 可整段恢复该提及;+ 输入法组字触及名称时,在组字结束时整段删去。+- 复制、剪切或拖动含有已选提及的文字时,提及随之带走:粘贴或拖放进频道输入框后逐个恢复为提及,其他应用拿到的则是纯文本名称。+ 只有名称仍是该频道为其 id 显示的名称时才恢复为提及,因此来自别处的 `@名称` 文字仍是纯文本。+- 与前后文字紧贴的提及(`x@Ada`、`@Ada.md`)发送时以空格隔开其 token,照常投递;紧跟其后手动输入的 `@id`+ (`@张三@ceo`)同样投递。同名员工不会混淆,手动输入或粘贴的 `@id` 照旧可用。+- 菜单也能匹配以任意文字输入的名称(`@张`);在 `@` 之后用输入法组字时按 Enter 不再选中候选。++## 工单里的路径++- 工单弹窗中的目标、验收标准、进展、结果与阻塞原因把数据路径画成胶囊:文件夹或文件图标加最后一段名称,悬停显示完整路径,+ 点击按原样复制路径,图标随之变成对勾。存储的文本未改变。+- 路径指 `<app_data_dir>/…`,或经过该 Project 的 `organizations/`、`agents/` 目录的绝对路径,分隔符可以是 `/`、`\`+ 或二者混用,因此 Windows 服务端写出的路径(`C:\Users\…\.penguin\data\…`)同样计入。正文里的路径只由 ASCII+ 文件名字符组成,遇到空格、中日韩文字或标点即结束,句末的句点不计入路径。延续到非 ASCII 段的路径(`…/workspace/调研报告.md`)、+ 从非 ASCII 段延续而来的路径(`C:\Users\张三\…`)与本服务自己的路由(`/api/projects/…/organizations/…`)保持为文本。+ 只含一条路径的行内代码按原样变为胶囊;代码块、行内代码里的命令与链接文字保持原样。以分隔符结尾、或最后一段没有扩展名的读作文件夹;+ 最后一段带扩展名的读作文件。+- Markdown 字段里以反斜杠书写的路径按源文本原样复制,尽管 Markdown 会把标点前的反斜杠读作转义并从文本里去掉。++## 组织状态++- 组织切换器的触发按钮把状态显示为名称右侧的文字胶囊——运行中 / 已暂停 / 配置无效(英文为 Running / Paused /+ Invalid configuration)——取代名称前的圆点。空间不够时先截断名称,状态也并入了触发按钮的无障碍名称。+- 未暂停组织的英文标签在所有出现处由 "Active" 改为 "Running"。diff --git a/packages/web/e2e/company.spec.mjs b/packages/web/e2e/company.spec.mjsindex 5c68628d..af37e152 100644--- a/packages/web/e2e/company.spec.mjs+++ b/packages/web/e2e/company.spec.mjs@@ -296,6 +296,74 @@ test("company mode: create the organization, meet the CEO, see the board and the).toBe(true);+ // A mention picked from the @ menu shows the CEO's name in the box, tinted by the layer+ // behind it, and still goes out as the id. It is one block: the arrow keys step over it,+ // Shift+arrow selects all of it, Backspace at its end takes all of it and Ctrl+Z brings it+ // back tinted, and a cut pasted elsewhere in the box, or a drag to another spot, leaves it+ // a mention.+ const NAME = "@Plugin Marketplace CEO";+ const LEAD = " 请看信息架构 ";+ const tint = page.locator("[data-mention]");+ const selection = () => input.evaluate((el) => [el.selectionStart, el.selectionEnd]);+ await input.pressSequentially("@Plug");+ await expect(page.getByRole("option", { name: /Plugin Marketplace CEO/ })).toBeVisible();+ await input.press("Enter");+ await expect(input).toHaveValue(`${NAME} `);+ await expect(tint).toHaveText(NAME);+ await input.press("Backspace"); // the pick's trailing space+ await expect(input).toHaveValue(NAME);+ await input.press("ArrowLeft");+ await expect.poll(selection).toEqual([0, 0]);+ await input.press("ArrowRight");+ await expect.poll(selection).toEqual([NAME.length, NAME.length]);+ await input.press("Shift+ArrowLeft");+ await expect.poll(selection).toEqual([0, NAME.length]);+ await input.press("ArrowRight");+ await expect.poll(selection).toEqual([NAME.length, NAME.length]);+ await input.press("Backspace");+ await expect(input).toHaveValue("");+ await expect(tint).toHaveCount(0);+ await input.press("Control+z");+ await expect(input).toHaveValue(NAME);+ await expect(tint).toHaveText(NAME);++ await input.press("End");+ await input.pressSequentially(LEAD.trimEnd());+ await input.press("Home");+ await input.press("Shift+ArrowRight");+ await expect.poll(selection).toEqual([0, NAME.length]);+ await input.press("Control+x");+ await expect(input).toHaveValue(LEAD.trimEnd());+ await expect(tint).toHaveCount(0);+ await input.press("End");+ await input.pressSequentially(" ");+ await input.press("Control+v");+ await expect(input).toHaveValue(`${LEAD}${NAME}`);+ await expect(tint).toHaveText(NAME);++ // Dragged by its name back in front of the sentence: the box deletes it, then drops it.+ await input.press("Shift+ArrowLeft");+ await expect.poll(selection).toEqual([LEAD.length, LEAD.length + NAME.length]);+ const grab = await tint.boundingBox();+ const field = await input.boundingBox();+ const line = grab.y + grab.height / 2;+ await page.mouse.move(grab.x + grab.width / 2, line);+ await page.mouse.down();+ await page.mouse.move(field.x + 4, line, { steps: 8 });+ await page.mouse.up();+ await expect(input).toHaveValue(`${NAME}${LEAD}`);+ await expect(tint).toHaveText(NAME);+ await input.press("Enter");+ await expect(input).toHaveValue("");+ await expect+ .poll(async () => {+ const day = await (+ await page.request.get(api(`/organizations/${ORG}/channels/default_channel/messages`))+ ).json();+ return day.messages.find((m) => m.text === `@${ORG}_ceo${LEAD.trimEnd()}`)?.mentions;+ })+ .toEqual([`agent:${ORG}_ceo`]);+// A new channel: created from the channel list header's own "+", the dialog validates the// id here, the sidebar gains a row, and the view opens on it.await page.getByRole("button", { name: "新建频道", exact: true }).first().click();diff --git a/packages/web/src/features/company/channel-composer.tsx b/packages/web/src/features/company/channel-composer.tsxindex 5dec24d5..ba6ddbc5 100644--- a/packages/web/src/features/company/channel-composer.tsx+++ b/packages/web/src/features/company/channel-composer.tsx@@ -3,16 +3,46 @@* IME's accepting Enter never sends), the send button, and the `@` autocomplete — a portaled* panel above the box (through Dropdown's portal, so no ancestor's overflow clips it) listing* the channel's own members — employees with their titles, then people, then everyone —- * ranked against what was typed, walked with the arrow keys and picked with Enter or Tab. A- * pick types the bare id (`@ceo`), which is what the server resolves; Escape dismisses the- * panel for that token until it changes.+ * ranked against what was typed (by id or by name), walked with the arrow keys and picked with+ * Enter or Tab. Escape dismisses the panel for that token until it changes.+ *+ * A pick writes the name the message will render (`@Ada Lovelace`), not the id the server+ * resolves: the draft tracks each picked mention as a range and the send converts it back+ * (mention-draft.ts has the rules). A mention is one block — an edit that reaches into it+ * takes all of it, and the caret steps over it — tinted the way a sent chip is by a layer+ * drawn behind the transparent textarea: the same box, font and wrapping, with the text itself+ * invisible, so only the tint shows through and the textarea keeps native caret, selection,+ * IME and undo.+ *+ * The browser's undo stack is why the block's edits are made the way they are. A value written+ * from script leaves that stack stale: Ctrl+Z then does nothing, and a redo can bring back text+ * from before the write.+ *+ * - Backspace at a mention's end and Delete at its start are replaced, before the browser acts,+ * by a native delete of the whole mention — one step on that stack, so Ctrl+Z restores it.+ * - Any other edit that reaches into a mention (a word delete, a keyboard app's edit) is widened+ * after the fact and written back, which costs the undo steps before it.+ * - An undo or redo is never written back. It restores only text, so when that text is one the+ * draft held with mentions, a short history puts the mentions back.+ * - Nothing is written back while an input method is composing, since that breaks the+ * composition; the widening waits for compositionend.+ *+ * The clipboard carries a mention as its name, which notifies nobody. So a copy, a cut or a drag+ * of text that holds mentions also writes them in a clipboard type of this app's own, and a+ * paste or a drop of that text puts them back once the box has inserted it: the insertion stays+ * the browser's own, and so does its undo step. A cut deletes its selection itself, natively,+ * since writing the clipboard means cancelling the browser's cut.** The keys are named in the placeholder and nothing is rendered under the box, the way* development mode's chat input reads: a line of hint below the composer is read once and* then costs a row of the stream on every later visit.*/-import { useId, useLayoutEffect, useRef, useState } from "react";-import type { KeyboardEvent as ReactKeyboardEvent } from "react";+import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";+import type {+ ClipboardEvent as ReactClipboardEvent,+ DragEvent as ReactDragEvent,+ KeyboardEvent as ReactKeyboardEvent,+} from "react";import { S } from "../../lib/strings";import { ICON_GAP } from "../../lib/icon-scale";import { Button } from "../../components/ui/button";@@ -20,12 +50,31 @@ import { Dropdown } from "../../components/ui/dropdown";import { noAutofill } from "../../components/ui/input";import { PrincipalChip } from "./shared";import {- insertMention,mentionInsertId,+ mentionLabel,mentionQueryAt,rankMentionCandidates,} from "./channel-mentions";import type { MentionCandidate, MentionKind } from "./channel-mentions";+import {+ EMPTY_DRAFT,+ MENTION_CLIP_TYPE,+ draftApplyClip,+ draftApplyEdit,+ draftFollowEdit,+ draftInsertMention,+ draftRecall,+ draftRemember,+ draftSegments,+ draftSlice,+ draftSnapSelection,+ draftWireText,+ mentionCovers,+ mentionDeletedByKey,+ parseClip,+ serializeClip,+} from "./mention-draft";+import type { DraftClip, DraftHistory, MentionDraft } from "./mention-draft";/*** The box grows with the draft up to this many pixels, then scrolls inside — the same cap the@@ -36,6 +85,20 @@ import type { MentionCandidate, MentionKind } from "./channel-mentions";*/const MAX_BOX_PX = 160;+/**+ * The box's text metrics, shared by the textarea and the highlight layer behind it: any+ * difference in padding, border, font or line height would wrap the two differently and slide+ * the tint off its name.+ */+const BOX_METRICS = "rounded-md border px-3 py-[9px] text-sm leading-5";++/**+ * The native events React's onSelect reports for a selection a pointer made: it holds the event+ * back while a button is down and fires on release. Keys and input methods arrive as+ * `keydown`, `keyup` or `selectionchange`.+ */+const POINTER_SELECT = new Set(["mouseup", "contextmenu", "dragend"]);+function kindTitle(kind: MentionKind): string {if (kind === "employee") return S.company.channels.employees;if (kind === "member") return S.company.channels.members;@@ -52,21 +115,52 @@ export function ChannelComposer({/** Sends the draft; resolves true once it is in the stream (the draft is then cleared). */onSend: (text: string) => Promise<boolean>;}) {- const [text, setText] = useState("");+ const [draft, setDraft] = useState(EMPTY_DRAFT);+ const text = draft.text;const [caret, setCaret] = useState(0);const [highlight, setHighlight] = useState(0);/** The `start:query` token Escape dismissed the panel for; typing on changes the token and reopens it. */const [dismissed, setDismissed] = useState<string | null>(null);const [sending, setSending] = useState(false);const inputRef = useRef<HTMLTextAreaElement>(null);+ const layerRef = useRef<HTMLDivElement>(null);const listId = useId();+ const segments = useMemo(() => draftSegments(draft), [draft]);+ /** The rendered draft, for the native beforeinput listener. */+ const draftRef = useRef(draft);+ const draftHistory = useRef<DraftHistory>([]);+ /** Where the selection's focus stood after the last change: where a keyboard move starts from. */+ const focusAt = useRef(0);+ /** The caret to set once React has written a widened value back. */+ const pendingCaret = useRef<number | null>(null);+ /** The draft when an input method started composing; null while none is. */+ const composingFrom = useRef<MentionDraft | null>(null);+ /** The clip a paste or a drop is about to insert, and the input type that will insert it. */+ const incoming = useRef<{ inputType: string; clip: DraftClip } | null>(null);- const mention = mentionQueryAt(text, caret);+ // A caret right after a picked mention (its trailing space deleted) would read its name as+ // a query; an `@` inside a mention's name is not a new one either.+ const typed = mentionQueryAt(text, caret);+ const mention = typed !== null && !mentionCovers(draft, typed.start) ? typed : null;const suggestions = mention === null ? [] : rankMentionCandidates(candidates, mention.query);const tokenKey = mention === null ? null : `${mention.start}:${mention.query}`;const panelOpen = mention !== null && suggestions.length > 0 && dismissed !== tokenKey;const active = suggestions[Math.min(highlight, Math.max(0, suggestions.length - 1))];+ /**+ * Keeps the highlight layer on the textarea's lines: its scroll offset, and the width a+ * vertical scrollbar takes once the draft outgrows the cap — the layer has none of its own,+ * so without the extra padding it would wrap a few characters later than the box.+ */+ const syncLayer = () => {+ const el = inputRef.current;+ const layer = layerRef.current;+ if (!el || !layer) return;+ const scrollbar = el.offsetWidth - el.clientWidth - 2 * el.clientLeft;+ layer.style.paddingRight = scrollbar > 0 ? `calc(0.75rem + ${scrollbar}px)` : "";+ layer.scrollTop = el.scrollTop;+ };+// The box follows its content up to the cap, so a long draft stays in view without a// scrollbar appearing at the second line. `scrollHeight` is content + padding and the box// is border-box, so the border has to be added back — without it every line would be set@@ -82,13 +176,67 @@ export function ChannelComposer({el.style.height = "auto";const border = el.offsetHeight - el.clientHeight;el.style.height = `${Math.min(el.scrollHeight + border, MAX_BOX_PX)}px`;+ syncLayer();}, [text]);+ useLayoutEffect(() => {+ draftRef.current = draft;+ draftHistory.current = draftRemember(draftHistory.current, draft);+ const at = pendingCaret.current;+ if (at !== null) {+ pendingCaret.current = null;+ inputRef.current?.setSelectionRange(at, at);+ }+ }, [draft]);++ /** Takes an edit's result; a text that differs from what the box shows is written back, caret included. */+ const takeEdit = (result: { draft: MentionDraft; caret: number }, shown: string) => {+ setDraft(result.draft);+ setCaret(result.caret);+ focusAt.current = result.caret;+ if (result.draft.text !== shown) pendingCaret.current = result.caret;+ };++ // Backspace at a mention's end, Delete at its start: the whole mention, deleted natively.+ // React's onBeforeInput does not fire for deletions, hence the native listener; the refs keep+ // it current without re-attaching.+ useEffect(() => {+ const el = inputRef.current;+ if (el === null) return;+ const onBeforeInput = (e: InputEvent) => {+ if (!e.cancelable || composingFrom.current !== null) return;+ const span = mentionDeletedByKey(+ draftRef.current,+ e.inputType,+ el.selectionStart,+ el.selectionEnd,+ );+ if (span === null) return;+ e.preventDefault();+ el.setSelectionRange(span.start, span.end);+ // execCommand is deprecated but still the only way to edit onto the native undo stack;+ // the input event it fires reaches onChange as the key's own would have.+ if (document.execCommand?.("delete")) return;+ const value = el.value.slice(0, span.start) + el.value.slice(span.end);+ takeEdit(draftApplyEdit(draftRef.current, value, span.start), el.value);+ };+ el.addEventListener("beforeinput", onBeforeInput);+ return () => el.removeEventListener("beforeinput", onBeforeInput);+ }, []);++ /**+ * The name a mention of this token shows: exactly what a sent message's chip renders+ * (channel-markdown). A pick writes it, and a pasted mention must still read it.+ */+ const labelOf = (wire: string) => mentionLabel(wire, names, S.company.principalAll);+const pick = (c: MentionCandidate) => {if (mention === null) return;- const next = insertMention(text, mention.start, caret, mentionInsertId(c, candidates));- setText(next.text);+ const wire = mentionInsertId(c, candidates);+ const next = draftInsertMention(draft, mention.start, caret, labelOf(wire), wire);+ setDraft(next.draft);setCaret(next.caret);+ focusAt.current = next.caret;setHighlight(0);requestAnimationFrame(() => {const el = inputRef.current;@@ -100,13 +248,14 @@ export function ChannelComposer({};const send = async () => {- const body = text.trim();- if (body === "" || sending) return;+ if (text.trim() === "" || sending) return;+ const body = draftWireText(draft).trim();setSending(true);try {if (await onSend(body)) {- setText("");+ setDraft(EMPTY_DRAFT);setCaret(0);+ focusAt.current = 0;}} finally {setSending(false);@@ -126,7 +275,8 @@ export function ChannelComposer({setHighlight((h) => (h - 1 + suggestions.length) % suggestions.length);return;}- if (e.key === "Enter" || e.key === "Tab") {+ // Not while an IME is composing: its Enter accepts the candidate being typed after the @.+ if ((e.key === "Enter" || e.key === "Tab") && !e.nativeEvent.isComposing) {e.preventDefault();if (active) pick(active);return;@@ -140,6 +290,35 @@ export function ChannelComposer({}};+ // A copy or a cut of text that holds mentions writes the clipboard itself: the browser keeps+ // what a handler puts there only when the event is cancelled, and then writes nothing of its+ // own, so the plain text goes on beside the mentions. The cut's delete follows as one native+ // edit, as the browser's own cut would have been, so Ctrl+Z undoes it.+ const onCopyOrCut = (e: ReactClipboardEvent<HTMLTextAreaElement>) => {+ const el = e.currentTarget;+ const { selectionStart: from, selectionEnd: to } = el;+ const clip = draftSlice(draft, from, to);+ if (clip.mentions.length === 0) return;+ e.preventDefault();+ e.clipboardData.setData("text/plain", clip.text);+ e.clipboardData.setData(MENTION_CLIP_TYPE, serializeClip(clip));+ if (e.type !== "cut" || document.execCommand?.("delete")) return;+ takeEdit(draftApplyEdit(draft, el.value.slice(0, from) + el.value.slice(to), from), el.value);+ };++ // A paste or a drop: the clip's mentions, held until the box reports the insertion.+ const expectClip = (inputType: string, data: DataTransfer) => {+ const clip = parseClip(data.getData(MENTION_CLIP_TYPE), data.getData("text/plain"), labelOf);+ incoming.current = clip === null ? null : { inputType, clip };+ };++ // A drag keeps the browser's own `text/plain` and adds the mentions beside it.+ const onDragStart = (e: ReactDragEvent<HTMLTextAreaElement>) => {+ const el = e.currentTarget;+ const clip = draftSlice(draft, el.selectionStart, el.selectionEnd);+ if (clip.mentions.length > 0) e.dataTransfer.setData(MENTION_CLIP_TYPE, serializeClip(clip));+ };+const rows: Array<{ c: MentionCandidate; i: number; head: boolean }> = suggestions.map((c, i) => ({ c, i, head: i === 0 || suggestions[i - 1]!.kind !== c.kind }),);@@ -157,29 +336,105 @@ export function ChannelComposer({menuClass="w-80"focusOnOpen={false}button={- <textarea- ref={inputRef}- rows={1}- value={text}- placeholder={S.company.channels.placeholder}- aria-label={S.company.channels.placeholder}- aria-autocomplete="list"- aria-expanded={panelOpen}- aria-controls={panelOpen ? listId : undefined}- aria-activedescendant={- panelOpen && active ? `${listId}-${active.principal}` : undefined- }- disabled={sending}- {...noAutofill}- onChange={(e) => {- setText(e.target.value);- setCaret(e.target.selectionStart ?? e.target.value.length);- setHighlight(0);- }}- onSelect={(e) => setCaret(e.currentTarget.selectionStart ?? 0)}- onKeyDown={onKeyDown}- className="block max-h-40 min-h-10 w-full resize-none rounded-md border border-gray-300 bg-white px-3 py-[9px] text-sm leading-5 placeholder:text-gray-400 focus:border-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-400/30 disabled:opacity-60 dark:border-gray-700 dark:bg-gray-900 dark:placeholder:text-gray-500"- />+ <div className="relative rounded-md bg-white dark:bg-gray-900">+ <div+ ref={layerRef}+ aria-hidden+ className={`pointer-events-none absolute inset-0 overflow-hidden whitespace-pre-wrap break-words border-transparent text-transparent ${BOX_METRICS}`}+ >+ {segments.map((seg, i) =>+ seg.mention ? (+ <span+ key={i}+ data-mention=""+ className="rounded-sm bg-gray-200 ring-2 ring-gray-200 dark:bg-gray-700 dark:ring-gray-700"+ >+ {seg.text}+ </span>+ ) : (+ <span key={i}>{seg.text}</span>+ ),+ )}+ {/* A trailing newline only takes a line in the layer when something follows it. */}+ {"\u200b"}+ </div>+ <textarea+ ref={inputRef}+ rows={1}+ value={text}+ placeholder={S.company.channels.placeholder}+ aria-label={S.company.channels.placeholder}+ aria-autocomplete="list"+ aria-expanded={panelOpen}+ aria-controls={panelOpen ? listId : undefined}+ aria-activedescendant={+ panelOpen && active ? `${listId}-${active.principal}` : undefined+ }+ disabled={sending}+ {...noAutofill}+ onChange={(e) => {+ const value = e.target.value;+ // The end of the selection: an undo, a redo or a drop leaves what it inserted+ // selected, and the insertion ends there.+ const at = e.target.selectionEnd;+ const { inputType } = e.nativeEvent as InputEvent;+ setHighlight(0);+ // A drag within the box deletes (deleteByDrag) before it inserts, so a clip+ // waits for the insertion its paste or drop announced.+ const pending = incoming.current;+ const clip =+ pending !== null && pending.inputType === inputType ? pending.clip : null;+ if (clip !== null) incoming.current = null;+ const base = composingFrom.current;+ if (base === null && inputType !== "historyUndo" && inputType !== "historyRedo") {+ const pasted = clip === null ? null : draftApplyClip(draft, value, at, clip);+ takeEdit(pasted ?? draftApplyEdit(draft, value, at), value);+ return;+ }+ setDraft(+ base !== null+ ? draftFollowEdit(base, value, at)+ : (draftRecall(draftHistory.current, value) ??+ draftFollowEdit(draft, value, at)),+ );+ setCaret(at);+ focusAt.current = at;+ }}+ onCompositionStart={() => {+ composingFrom.current = draft;+ }}+ onCompositionEnd={(e) => {+ const base = composingFrom.current;+ composingFrom.current = null;+ if (base === null) return;+ const el = e.currentTarget;+ takeEdit(draftApplyEdit(base, el.value, el.selectionEnd), el.value);+ }}+ onSelect={(e) => {+ if (composingFrom.current !== null) return;+ const el = e.currentTarget;+ const backward = el.selectionDirection === "backward";+ const snapped = draftSnapSelection(+ draft,+ { start: el.selectionStart, end: el.selectionEnd, backward },+ POINTER_SELECT.has(e.nativeEvent.type) ? null : focusAt.current,+ );+ if (snapped.start !== el.selectionStart || snapped.end !== el.selectionEnd) {+ el.setSelectionRange(snapped.start, snapped.end, el.selectionDirection);+ }+ focusAt.current = backward ? snapped.start : snapped.end;+ setCaret(snapped.end);+ }}+ onCopy={onCopyOrCut}+ onCut={onCopyOrCut}+ onPaste={(e) => expectClip("insertFromPaste", e.clipboardData)}+ onDragStart={onDragStart}+ onDrop={(e) => expectClip("insertFromDrop", e.dataTransfer)}+ onScroll={syncLayer}+ onKeyDown={onKeyDown}+ className={`relative block max-h-40 min-h-10 w-full resize-none border-gray-300 bg-transparent placeholder:text-gray-400 focus:border-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-400/30 disabled:opacity-60 dark:border-gray-700 dark:placeholder:text-gray-500 ${BOX_METRICS}`}+ />+ </div>}><div id={listId} role="listbox" aria-label={S.company.channels.mentionPanel}>diff --git a/packages/web/src/features/company/channel-mentions.ts b/packages/web/src/features/company/channel-mentions.tsindex fd8b9e95..147ea664 100644--- a/packages/web/src/features/company/channel-mentions.ts+++ b/packages/web/src/features/company/channel-mentions.ts@@ -1,9 +1,10 @@/*** A channel's @-mentions (pure, unit tested): the candidates the composer offers — the* channel's own members, plus `all` — and how they rank against what was typed, the token- * being typed at the caret, what a pick types and how it is spliced into the draft, how a- * stored message is split into plain runs and mention runs for highlighting, and what a- * mention run displays and whether it addresses the reader. The token grammar mirrors the+ * being typed at the caret, what a pick sends (the draft that shows it by name is+ * mention-draft.ts), how a stored message is split into plain runs and mention runs for+ * highlighting, and what a mention run displays and whether it addresses the reader. The token+ * grammar mirrors the* server's extractMentionTokens — `@id`, `@agent:id`, `@user:id`, `@all` — and its* resolution order (an employee before a member of the same id), so what the composer* highlights is what the server delivers.@@ -74,7 +75,7 @@ export function rankMentionCandidates(}/**- * What a pick types after the `@`: an employee's bare id, a member's bare id — unless an+ * What a pick sends after the `@`: an employee's bare id, a member's bare id — unless an* employee shares it, in which case `user:` disambiguates, since the server resolves a bare* id to the employee first — and `all`.*/@@ -113,8 +114,9 @@ export function mentionIsMe(/*** The `@token` the caret sits at the end of, if any: the `@` must start the text or follow a- * character that cannot be part of an id, and the token runs unbroken to the caret. Null when- * the caret is not inside such a token (the panel then stays closed).+ * character that cannot be part of an id, and the token runs unbroken to the caret — letters+ * of any script, digits and `_:.-`, so a name typed in CJK searches too. Null when the caret+ * is not inside such a token (the panel then stays closed).*/export function mentionQueryAt(text: string,@@ -125,22 +127,10 @@ export function mentionQueryAt(if (at === -1) return null;if (at > 0 && /[A-Za-z0-9_@]/.test(before[at - 1]!)) return null;const query = before.slice(at + 1);- if (!/^[A-Za-z0-9_:.-]*$/.test(query)) return null;+ if (!/^[\p{L}\p{N}_:.-]*$/u.test(query)) return null;return { start: at, query };}-/** Replaces the token at `start`…`caret` with the principal and a trailing space; returns the new text and caret. */-export function insertMention(- text: string,- start: number,- caret: number,- principal: string,-): { text: string; caret: number } {- const inserted = `@${principal} `;- const next = text.slice(0, start) + inserted + text.slice(caret);- return { text: next, caret: start + inserted.length };-}-export interface TextRun {text: string;/** The mention token without its `@` (`agent:ceo`, `ceo`, `all`), or null for a plain run. */diff --git a/packages/web/src/features/company/mention-draft.ts b/packages/web/src/features/company/mention-draft.tsnew file mode 100644index 00000000..50a8d20d--- /dev/null+++ b/packages/web/src/features/company/mention-draft.ts@@ -0,0 +1,394 @@+/**+ * The channel composer's draft (pure, unit tested): the text the box shows, with a picked+ * mention written as `@<display name>`, and the mentions tracked as ranges over that text so+ * the message that is sent still carries the token the server resolves (`@ceo`,+ * `@user:alice`, `@all` — see channel-mentions.ts).+ *+ * Why ranges rather than matching names on send: names are not unique and may hold spaces or+ * CJK, so `@Alice Chen` cannot be read back to an id from the text alone. A range remembers+ * which candidate was picked.+ *+ * A picked mention is one block, so every tracked mention reads `@<name>` by construction:+ *+ * - An edit that reaches into a mention takes all of it. The box reports only its new value, so+ * the edit is recovered from that and widened to the whole mention (draftApplyEdit): Backspace+ * at its end, Delete at its start, a word or line delete, a cut, a drop or a keyboard app's+ * own edit — whatever made the edit, the mention goes in one piece.+ * - The caret never rests inside a mention, and a selection holds a mention whole or not at all+ * (draftSnapSelection), so typing lands before or after one.+ * - Text typed or pasted anywhere else only moves the mentions after it. A pasted `@Name` is+ * plain text; a typed or pasted `@id` is left as it is and the server resolves it as always.+ * - A copy, a cut or a drag of text that holds mentions carries them beside its plain text, in a+ * clipboard type of this app's own (draftSlice, serializeClip), so pasting or dropping that+ * text into a composer brings them back (parseClip, draftApplyClip). The plain text is the+ * names, which is what every other app gets and what would otherwise notify nobody.+ * - On send, a mention that touches text the server would read into its token gets a space on+ * that side (draftWireText), so both `x@Ada` and a typed `@id` right after a mention+ * (`@张三@ceo`) are delivered.+ */+import { mentionRuns } from "./channel-mentions";++export interface DraftMention {+ /** Offset of the `@` in the draft text. */+ start: number;+ /** The display name shown after the `@`, as it was when the mention was picked. */+ label: string;+ /** What the sent message carries after the `@`: a bare id, `user:<id>` or `all`. */+ wire: string;+}++export interface MentionDraft {+ text: string;+ /** Sorted by `start`, never overlapping, each reading `@<label>` in `text`. */+ mentions: readonly DraftMention[];+}++export const EMPTY_DRAFT: MentionDraft = { text: "", mentions: [] };++/** The offset just past a mention's last character. */+export const mentionEnd = (m: DraftMention): number => m.start + 1 + m.label.length;++/** An edit: the draft text's `from`…`to` replaced by `insert`. */+interface Edit {+ from: number;+ to: number;+ insert: string;+}++/**+ * The edit that turned `prev` into `next`, with the caret at the end of what was inserted. A+ * textarea reports only the new value, so the edit is the span between the longest common+ * prefix and suffix. Where that is ambiguous — an `a` typed after `@Ann` reads the same as one+ * typed after `@Anna` — the caret decides: an insertion ends where the caret stands, so the+ * common suffix cannot reach past it.+ */+function recoverEdit(prev: string, next: string, caret: number): Edit {+ const max = Math.min(prev.length, next.length);+ let suffix = 0;+ while (suffix < max && prev[prev.length - 1 - suffix] === next[next.length - 1 - suffix]) {+ suffix += 1;+ }+ suffix = Math.min(suffix, next.length - caret);+ let prefix = 0;+ const prefixMax = max - suffix;+ while (prefix < prefixMax && prev[prefix] === next[prefix]) prefix += 1;+ return {+ from: prefix,+ to: prev.length - suffix,+ insert: next.slice(prefix, next.length - suffix),+ };+}++/**+ * The edit grown to the whole of every mention it reaches into: one it overlaps, or one an+ * insertion lands strictly inside. An edit that only touches a mention's edge leaves it alone.+ * One pass is enough: growing to a mention's own edges cannot reach a neighbour.+ */+function widen(draft: MentionDraft, edit: Edit): Edit {+ let { from, to } = edit;+ for (const m of draft.mentions) {+ if (m.start < to && mentionEnd(m) > from) {+ from = Math.min(from, m.start);+ to = Math.max(to, mentionEnd(m));+ }+ }+ return { from, to, insert: edit.insert };+}++/** Applies an edit: a mention wholly before it stays, one wholly after it moves, any other is dropped. */+function splice(draft: MentionDraft, { from, to, insert }: Edit): MentionDraft {+ const delta = insert.length - (to - from);+ const mentions: DraftMention[] = [];+ for (const m of draft.mentions) {+ if (mentionEnd(m) <= from) mentions.push(m);+ else if (m.start >= to) mentions.push({ ...m, start: m.start + delta });+ }+ return { text: draft.text.slice(0, from) + insert + draft.text.slice(to), mentions };+}++/**+ * A stretch of a draft on its way through the clipboard: its text, and the mentions wholly inside+ * it with their offsets counted from its start.+ */+export interface DraftClip {+ text: string;+ mentions: readonly DraftMention[];+}++/**+ * Replaces `from`…`to` with the clip, widened like any edit, and tracks the clip's mentions; the+ * caret goes after the clip.+ */+function insertClip(+ draft: MentionDraft,+ from: number,+ to: number,+ clip: DraftClip,+): { draft: MentionDraft; caret: number } {+ const edit = widen(draft, { from, to, insert: clip.text });+ const next = splice(draft, edit);+ const mentions = [+ ...next.mentions,+ ...clip.mentions.map((m) => ({ ...m, start: m.start + edit.from })),+ ].sort((a, b) => a.start - b.start);+ return { draft: { text: next.text, mentions }, caret: edit.from + clip.text.length };+}++/**+ * Replaces the `@query` being typed (`start`…`caret`) with `@<label> ` and tracks the new+ * mention; returns the draft and the caret, which lands after the trailing space.+ */+export function draftInsertMention(+ draft: MentionDraft,+ start: number,+ caret: number,+ label: string,+ wire: string,+): { draft: MentionDraft; caret: number } {+ return insertClip(draft, start, caret, {+ text: `@${label} `,+ mentions: [{ start: 0, label, wire }],+ });+}++/**+ * The draft after the box's value became `next`, `caret` being the end of the box's selection.+ * An edit that reaches into a mention is widened to the whole of it; the text then differs+ * from `next` — the composer writes it back — and the returned caret follows the widened edit.+ * Otherwise the text is `next` and the caret is returned as given.+ */+export function draftApplyEdit(+ draft: MentionDraft,+ next: string,+ caret: number,+): { draft: MentionDraft; caret: number } {+ if (draft.text === next) return { draft, caret };+ const edit = widen(draft, recoverEdit(draft.text, next, caret));+ const edited = splice(draft, edit);+ return { draft: edited, caret: edited.text === next ? caret : edit.from + edit.insert.length };+}++/**+ * The draft for a value the composer must not write back — an input method still composing,+ * or an undo or redo the browser applied: the text is `next` exactly, and a mention the edit+ * reaches into is dropped rather than widened.+ */+export function draftFollowEdit(draft: MentionDraft, next: string, caret: number): MentionDraft {+ if (draft.text === next) return draft;+ return splice(draft, recoverEdit(draft.text, next, caret));+}++/**+ * The clipboard type a copy, a cut or a drag out of the composer carries its mentions in. It+ * rides beside the `text/plain` of the same text, which is the names; only a composer reads it.+ */+export const MENTION_CLIP_TYPE = "application/x-penguin-mentions";++/** The draft's `from`…`to`, for a copy, a cut or a drag: its text and every mention wholly inside it. */+export function draftSlice(draft: MentionDraft, from: number, to: number): DraftClip {+ return {+ text: draft.text.slice(from, to),+ mentions: draft.mentions+ .filter((m) => m.start >= from && mentionEnd(m) <= to)+ .map((m) => ({ ...m, start: m.start - from })),+ };+}++/** The clip as MENTION_CLIP_TYPE carries it: JSON of its text and mentions (`start`, `label`, `wire`). */+export function serializeClip(clip: DraftClip): string {+ return JSON.stringify({ text: clip.text, mentions: clip.mentions });+}++/**+ * The clip a MENTION_CLIP_TYPE payload carries, or null when there is nothing to bring back.+ *+ * - `plain` is the `text/plain` beside it, which is what the box inserts; the payload must be+ * that text (line endings aside, which the box normalizes), since its mentions are offsets+ * into it. A payload that does not parse, or whose mentions do not each read `@<label>` in+ * order, is null too.+ * - A mention comes back only when `labelOf` — the name a pick of its token writes — still gives+ * its label. The clipboard is shared with every other page and app, and a mention shows one+ * thing and sends another: this keeps it showing what it sends, and leaves one copied in+ * another organization, whose ids this one does not know, as the plain name.+ */+export function parseClip(+ payload: string,+ plain: string,+ labelOf: (wire: string) => string,+): DraftClip | null {+ let data: unknown;+ try {+ data = JSON.parse(payload);+ } catch {+ return null;+ }+ const { text, mentions } = (data ?? {}) as { text?: unknown; mentions?: unknown };+ if (typeof text !== "string" || !Array.isArray(mentions)) return null;+ if (text !== plain.replace(/\r\n?/g, "\n")) return null;+ const kept: DraftMention[] = [];+ let end = 0;+ for (const item of mentions as unknown[]) {+ const { start, label, wire } = (item ?? {}) as Record<string, unknown>;+ if (typeof start !== "number" || !Number.isInteger(start) || start < end) return null;+ if (typeof label !== "string" || typeof wire !== "string") return null;+ const m = { start, label, wire };+ end = mentionEnd(m);+ if (text.slice(start, end) !== `@${label}`) return null;+ if (labelOf(wire) === label) kept.push(m);+ }+ return kept.length === 0 ? null : { text, mentions: kept };+}++/**+ * The draft after a paste or a drop put `clip` into the box and its value became `next`, `caret`+ * being the end of the box's selection — the end of what was inserted, as after any insertion.+ * The clip's mentions come back with it, and a mention of the draft that the clip lands inside or+ * replaces part of goes whole, as in draftApplyEdit. Null when `next` is not the draft with the+ * clip put in front of the caret — the box inserted something else — and the caller takes the+ * edit as plain text.+ */+export function draftApplyClip(+ draft: MentionDraft,+ next: string,+ caret: number,+ clip: DraftClip,+): { draft: MentionDraft; caret: number } | null {+ const from = caret - clip.text.length;+ const to = caret + draft.text.length - next.length;+ if (from < 0 || to < from) return null;+ if (next !== draft.text.slice(0, from) + clip.text + draft.text.slice(to)) return null;+ return insertClip(draft, from, to, clip);+}++/**+ * The mention a Backspace right after it, or a Delete right before it, would reach into: the+ * span the composer deletes in the key's place as one native edit, so the browser's own undo+ * brings the whole name back. Null for every other edit, which draftApplyEdit widens instead.+ */+export function mentionDeletedByKey(+ draft: MentionDraft,+ inputType: string,+ selectionStart: number,+ selectionEnd: number,+): { start: number; end: number } | null {+ if (selectionStart !== selectionEnd) return null;+ const m = draft.mentions.find((x) =>+ inputType === "deleteContentBackward"+ ? mentionEnd(x) === selectionStart+ : inputType === "deleteContentForward" && x.start === selectionStart,+ );+ return m === undefined ? null : { start: m.start, end: mentionEnd(m) };+}++export interface DraftSelection {+ start: number;+ end: number;+ /** The focus — the end that moves — is `start`. */+ backward: boolean;+}++/**+ * The selection with neither end inside a mention.+ *+ * - When the keyboard (or an input method) moved the selection, `focusFrom` is where its focus+ * stood before: a focus that stepped into a mention goes on to the far edge, so the arrow keys+ * step over a mention and Shift+arrow grows or shrinks a selection by the whole of it.+ * - When a pointer placed it, `focusFrom` is null: a caret goes to the nearer edge, and a range+ * grows outward to hold every mention it cuts into (a drag, a double-click on part of a name).+ * - An end that did not move but that an edit left inside a mention grows outward too.+ */+export function draftSnapSelection(+ draft: MentionDraft,+ selection: DraftSelection,+ focusFrom: number | null,+): { start: number; end: number } {+ const snap = (offset: number, side: "start" | "end" | "caret", isFocus: boolean): number => {+ const m = draft.mentions.find((x) => x.start < offset && offset < mentionEnd(x));+ if (m === undefined) return offset;+ const before = m.start;+ const after = mentionEnd(m);+ if (isFocus && focusFrom !== null && focusFrom !== offset) {+ return focusFrom < offset ? after : before;+ }+ if (side === "start") return before;+ if (side === "end") return after;+ return offset - before < after - offset ? before : after;+ };+ const { start, end, backward } = selection;+ if (start === end) {+ const at = snap(start, "caret", true);+ return { start: at, end: at };+ }+ return { start: snap(start, "start", backward), end: snap(end, "end", !backward) };+}++/** Whether a tracked mention holds the character at `offset` (the composer opens no `@` panel there). */+export function mentionCovers(draft: MentionDraft, offset: number): boolean {+ return draft.mentions.some((m) => m.start <= offset && offset < mentionEnd(m));+}++/**+ * The text the send button posts: every mention as its token, everything else verbatim, with a+ * space wherever a token would otherwise not read as itself under the server's grammar+ * (mentionRuns mirrors it).+ *+ * - Before the `@`, when what precedes would glue it: a word character (`x@Ada`), or the tail+ * of another token that swallows the character the `@` needs in front of it (`@bob.@Ada`).+ * - After the token, when the draft goes on with characters that would extend the id+ * (`@Ada.md`), or with an `@` the converted id would glue — a typed `@id` right after a+ * CJK name reads as a mention in the draft, and must still read as one once the name is an id.+ */+export function draftWireText(draft: MentionDraft): string {+ let out = "";+ let last = 0;+ for (const m of draft.mentions) {+ out += draft.text.slice(last, m.start);+ if (mentionRuns(`${out}@${m.wire}`).at(-1)?.mention !== m.wire) out += " ";+ out += `@${m.wire}`;+ last = mentionEnd(m);+ const rest = draft.text.slice(last);+ if (mentionRuns(`@${m.wire}${rest}`)[0]?.mention !== m.wire || /^[.-]*@/.test(rest)) {+ out += " ";+ }+ }+ return out + draft.text.slice(last);+}++export interface DraftSegment {+ text: string;+ /** True for a mention's `@<label>`. */+ mention: boolean;+}++/** The draft split for the composer's highlight layer: plain runs and mentions, in order. */+export function draftSegments(draft: MentionDraft): DraftSegment[] {+ const out: DraftSegment[] = [];+ let last = 0;+ for (const m of draft.mentions) {+ if (m.start > last) out.push({ text: draft.text.slice(last, m.start), mention: false });+ out.push({ text: `@${m.label}`, mention: true });+ last = mentionEnd(m);+ }+ if (last < draft.text.length) out.push({ text: draft.text.slice(last), mention: false });+ return out;+}++/** How many drafts with mentions the composer keeps for undo and redo. */+const HISTORY_SIZE = 50;++/**+ * Recent drafts that held mentions, oldest first, one per text. An undo or redo gives back only+ * text; when that text is one of these, its mentions come back with it.+ */+export type DraftHistory = readonly MentionDraft[];++/** The history with `draft` added (a draft without mentions is not worth keeping). */+export function draftRemember(history: DraftHistory, draft: MentionDraft): DraftHistory {+ if (draft.mentions.length === 0) return history;+ return [...history.filter((d) => d.text !== draft.text), draft].slice(-HISTORY_SIZE);+}++/** The remembered draft whose text is `text`, if any. */+export function draftRecall(history: DraftHistory, text: string): MentionDraft | null {+ return history.find((d) => d.text === text) ?? null;+}diff --git a/packages/web/src/features/company/org-switcher.tsx b/packages/web/src/features/company/org-switcher.tsxindex dcde0c1f..38b37ac6 100644--- a/packages/web/src/features/company/org-switcher.tsx+++ b/packages/web/src/features/company/org-switcher.tsx@@ -1,7 +1,8 @@/*** The organization switcher that stands where the Project switcher stands in development- * mode. The trigger names the open organization with its status dot and, beneath it, the- * Project it belongs to; the menu lists every organization the user can reach, grouped by+ * mode. The trigger names the open organization with its status as a text capsule to the right+ * of the name (the name truncates, the capsule never does) and, beneath it, the Project it+ * belongs to; the menu lists every organization the user can reach, grouped by* Project with a check mark on the open one (picking one opens its overview), then the two* entries that make and shape one — "New organization" (success makes the new organization* the shell's current one and lands in its CEO's desk session) and "Organization settings".@@ -29,7 +30,7 @@ import {OrganizationSettingsDialog,useOrganizationCreated,} from "./org-dialogs";-import { OrgStatusDot } from "./shared";+import { OrgStatusDot, OrgStatusPill, orgStatusText } from "./shared";const menuItemClass = `flex w-full items-center ${ICON_GAP.menu} px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`;@@ -61,7 +62,7 @@ export function OrgSwitcher({ onNavigate }: { onNavigate?: () => void }) {const triggerTitle =current !== null- ? S.company.inProject(projectName(current.projectId), current.name)+ ? `${S.company.inProject(projectName(current.projectId), current.name)} · ${orgStatusText(current)}`: S.company.switcher;/*** What is waiting in this organization's channels, summed over the ones the user belongs@@ -98,7 +99,6 @@ export function OrgSwitcher({ onNavigate }: { onNavigate?: () => void }) {><span className="min-w-0 flex-1"><span className={`flex items-center ${ICON_GAP.row}`}>- {current !== null && <OrgStatusDot org={current} />}<span className="min-w-0 truncate text-base font-semibold leading-tight">{current !== null? current.name@@ -106,6 +106,13 @@ export function OrgSwitcher({ onNavigate }: { onNavigate?: () => void }) {? S.company.noOrganizations: S.common.loading}</span>+ {/* Never shrinks and never wraps: a CJK label would otherwise break per+ character before the name gave up a single letter. */}+ {current !== null && (+ <span className="shrink-0 whitespace-nowrap">+ <OrgStatusPill org={current} />+ </span>+ )}</span>{/* The Project the organization belongs to: the second line, so the name stays the headline. */}{current !== null && (diff --git a/packages/web/src/features/company/path-capsule.tsx b/packages/web/src/features/company/path-capsule.tsxnew file mode 100644index 00000000..84f64427--- /dev/null+++ b/packages/web/src/features/company/path-capsule.tsx@@ -0,0 +1,174 @@+/**+ * Data paths as folder capsules: a folder (or file) glyph and the last segment, the full path+ * on hover, and a click that copies it exactly as written. path-capsules.ts decides which+ * stretches of text are paths; this module draws them, in Markdown (`PathMarkdown`) and in+ * plain text (`PathText`). The stored text is never rewritten: the capsule is only how it is+ * drawn, and its click copies the path exactly as written.+ *+ * The copy follows the app's one copy affordance (copy-button.tsx): optimistic write, the+ * feedback shown at the control as the glyph swapping to the check and the tooltip flipping to+ * "copied", and a live region beside it for screen readers.+ *+ * In Markdown the pass works on the mdast the shared pipeline produced, so everything the+ * parser already decided holds: a path inside a fenced block or a link stays as it is, and a+ * path the parser split — `__init__` read as emphasis — is left whole as text rather than+ * capsuled in part. A path written with `\` is the exception: the parser took some of its+ * separators for escapes, so its capsule takes the path from the source (spellAsWritten). A+ * capsule reaches React as `<samp>`: no Markdown syntax and no KaTeX output produces one, so+ * claiming it in the components map collides with nothing.+ */+import { useMemo } from "react";+import type { ReactNode } from "react";+import type { Components, Options } from "react-markdown";+import { S } from "../../lib/strings";+import { ICON_SIZE } from "../../lib/icon-scale";+import { STAT_ICONS } from "../../lib/stat-icons";+import { CopiedStatus, useCopied } from "../../components/ui/copy-button";+import { GlyphIcon } from "../../components/ui/glyph-icon";+import { FOLDER_ICON } from "../../components/ui/group-list";+import { FILE_ICON } from "../../components/ui/icons";+import { Md } from "../chat/md";+import { codePath, pathKind, pathLabel, spellAsWritten, splitPaths } from "./path-capsules";+import type { PathScope } from "./path-capsules";++/** One data path as a capsule. */+export function PathCapsule({ path }: { path: string }) {+ const { copied, flash } = useCopied();+ const glyph = copied ? STAT_ICONS.check : pathKind(path) === "file" ? FILE_ICON : FOLDER_ICON;+ return (+ <>+ <button+ type="button"+ title={copied ? S.common.copied : S.company.pathCapsule.hint(path)}+ aria-label={S.company.pathCapsule.copy(path)}+ onClick={() => flash(path)}+ // Baseline-aligned on the label, so the capsule sits on the sentence's line; the glyph+ // centres itself instead of dragging the baseline down to its own bottom edge.+ className="inline-flex max-w-full items-baseline gap-1 rounded bg-gray-100 px-1 text-gray-700 transition-colors duration-150 hover:bg-gray-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-400/40 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700"+ >+ <GlyphIcon+ d={glyph}+ size={ICON_SIZE.inlineGlyph}+ className="self-center text-gray-500 dark:text-gray-400"+ />+ <span className="min-w-0 truncate">{pathLabel(path)}</span>+ </button>+ <CopiedStatus copied={copied} />+ </>+ );+}++/** Plain text with its data paths drawn as capsules. */+export function PathText({ text, scope }: { text: string; scope: PathScope }) {+ return (+ <>+ {splitPaths(text, scope).map((piece, i) =>+ piece.kind === "text" ? piece.text : <PathCapsule key={i} path={piece.path} />,+ )}+ </>+ );+}++/** The mdast shapes this pass touches, declared structurally rather than taking `@types/mdast` on. */+interface MdNode {+ type: string;+ value?: string;+ children?: MdNode[];+ position?: { start?: { offset?: number }; end?: { offset?: number } };+ data?: { hName?: string; hChildren?: Array<{ type: string; value: string }> };+}++const CAPSULE_TAG = "samp";++function capsuleNode(path: string): MdNode {+ return {+ type: "pathCapsule",+ data: { hName: CAPSULE_TAG, hChildren: [{ type: "text", value: path }] },+ };+}++/** Parents whose text is not prose to capsule: a link's label (a button cannot nest in an anchor). */+const SKIP = new Set(["link", "linkReference"]);++/** The Markdown a node was parsed from, or its own value when the node carries no position. */+function sourceOf(node: MdNode, source: string): string {+ const start = node.position?.start?.offset;+ const end = node.position?.end?.offset;+ return start === undefined || end === undefined ? (node.value ?? "") : source.slice(start, end);+}++function walk(parent: MdNode, scope: PathScope, source: string): void {+ const children = parent.children;+ if (!children) return;+ for (let i = 0; i < children.length; i += 1) {+ const node = children[i]!;+ if (node.type === "inlineCode" && typeof node.value === "string") {+ const path = codePath(node.value, scope);+ if (path !== null) children[i] = capsuleNode(path);+ continue;+ }+ if (node.type === "text" && typeof node.value === "string") {+ const pieces = splitPaths(node.value, scope);+ if (!pieces.some((p) => p.kind === "path")) continue;+ // A path touching the node's edge may run on into the sibling there — the parser split+ // it (`…/src/__init__.py` has an emphasis in the middle) — so it stays text. Only a bare+ // `/` or `\` can be the tail of such a split; `<app_data_dir>`, `~` and a drive letter+ // only ever start one.+ const first = pieces[0]!;+ const lastPiece = pieces[pieces.length - 1]!;+ if (+ first.kind === "path" &&+ /^[/\\]/.test(first.path) &&+ i > 0 &&+ children[i - 1]!.type !== "break"+ ) {+ pieces[0] = { kind: "text", text: first.path };+ }+ if (+ lastPiece.kind === "path" &&+ i < children.length - 1 &&+ children[i + 1]!.type !== "break"+ ) {+ pieces[pieces.length - 1] = { kind: "text", text: lastPiece.path };+ }+ const replaced = spellAsWritten(pieces, sourceOf(node, source)).map((p) =>+ p.kind === "path" ? capsuleNode(p.path) : { type: "text", value: p.text },+ );+ children.splice(i, 1, ...replaced);+ i += replaced.length - 1;+ continue;+ }+ if (!SKIP.has(node.type)) walk(node, scope, source);+ }+}++/** The remark pass: data paths in prose and whole-path inline code become capsule nodes. */+export function remarkPathCapsules(scope: PathScope) {+ return (tree: MdNode, file: { value?: unknown }): void =>+ walk(tree, scope, String(file.value ?? ""));+}++function textOf(children: ReactNode): string {+ if (typeof children === "string") return children;+ if (Array.isArray(children)) return children.map(textOf).join("");+ return "";+}++/** The `<samp>` the pass produced, as the capsule; its text is the path. */+function CapsuleNode({ children }: { children?: ReactNode }) {+ return <PathCapsule path={textOf(children)} />;+}++const PATH_COMPONENTS: Components = { [CAPSULE_TAG]: CapsuleNode };++/** Markdown with its data paths drawn as capsules. The caller supplies the `md-body` container. */+export function PathMarkdown({ text, scope }: { text: string; scope: PathScope }) {+ const { projectId } = scope;+ // A fresh plugin list is a new processor for react-markdown, so it is rebuilt only when the+ // Project changes.+ const plugins = useMemo<NonNullable<Options["remarkPlugins"]>>(+ () => [[remarkPathCapsules, { projectId }]],+ [projectId],+ );+ return <Md text={text} extraPlugins={plugins} components={PATH_COMPONENTS} />;+}diff --git a/packages/web/src/features/company/path-capsules.ts b/packages/web/src/features/company/path-capsules.tsnew file mode 100644index 00000000..2b213ea4--- /dev/null+++ b/packages/web/src/features/company/path-capsules.ts@@ -0,0 +1,167 @@+/**+ * Which stretches of a ticket's text are data paths, for the folder capsules the ticket dialog+ * draws over them (pure, unit tested). Employees write full paths into tickets on purpose — the+ * next session reads them to find the work — so a ticket is full of lines like+ * `<app_data_dir>/organizations/co_lab/workspace/experiments/dep-eval/`. The stored text never+ * changes; only what a person reads does.+ *+ * What counts as a path:+ *+ * - **Where it starts.** The `<app_data_dir>` placeholder followed by `/`, or an absolute path+ * (`/…`, `~/…`, `C:/…`) that runs through this Project's data directory — a+ * `/<projectId>/organizations/` or `/<projectId>/agents/` stretch, the real-path spelling of+ * the same place. Any other absolute path is left alone: in prose `/api/v1/tickets` is a+ * route, not a folder, and nothing but the data directory tells the two apart. This server's+ * own routes share that stretch (`/api/projects/<projectId>/organizations/…`), so a path that+ * starts at `/api/` is a route too.+ * - **Separators.** `/` or `\`, mixed as they come: a server on Windows hands its employees+ * workspaces like `C:\Users\ada\.penguin\data\<projectId>\organizations\…`. Every rule here+ * reads a `\` as a `/`, and a capsule still copies the path as written.+ * - **What it is made of, in prose.** Segments of ASCII letters, digits and `._~+=@%-`, plus+ * whole `<placeholder>` segments, separated by `/`. The path stops at anything else, so the+ * punctuation and CJK around it stay outside (`见<app_data_dir>/…/dep-eval/。`), and a+ * trailing `.` ends a sentence rather than a file name. File names are ASCII by the handbook's+ * convention; a space ends a path, since prose gives no way to tell where it would stop.+ * - **Where it runs on past that.** A path whose next segment is not ASCII+ * (`…/workspace/调研报告.md`, `…/workspace/实验/`) stays text: cut at the last ASCII+ * character, its capsule would name and copy the folder above the one written. The run of+ * letters after it counts as a segment when it goes on to a `/` or a file extension;+ * otherwise it is the sentence resuming (`…/handbook/里有说明`), and the path keeps its capsule.+ * The same holds at the other end: a bare `/` root right after a non-ASCII segment+ * (`C:\Users\张三\.penguin\…`) is the middle of a longer path, and stays text rather than+ * becoming a capsule that copies only its tail.+ * - **In code.** An inline code span that holds one path and nothing else is one path, taken+ * verbatim — the backticks already say where it ends, so any non-space character may appear+ * in it. A code span holding a command, and every fenced block, stays code.+ * - **Folder or file.** A trailing `/` is a folder; a last segment with an extension+ * (`report.md`, `run.v2.json`) is a file; anything else is a folder, since employees name+ * directories bare far more often than files.+ */++export interface PathScope {+ /** The Project the ticket belongs to: the directory an absolute path must pass through. */+ projectId: string;+}++export type PathPiece = { kind: "text"; text: string } | { kind: "path"; path: string };++const PLACEHOLDER_ROOT = "<app_data_dir>";++/** One segment of a prose path: plain characters, or a whole `<placeholder>`. */+const PROSE_SEGMENT = String.raw`(?:<[a-z][a-z0-9_]*>|[A-Za-z0-9._~+=@%-])+`;++/**+ * A candidate path in prose: a root, then a separator and a segment, repeated, then an optional+ * trailing separator. The lookbehinds keep a path from starting in the middle of a word; a bare+ * separator, `~` or drive root additionally may not follow a path character or a `:`, which is+ * what keeps a URL (`https://…`) and the inside of another path from reading as a root. The+ * placeholder cannot be mistaken for either, so `Output:<app_data_dir>/…` still starts a path.+ */+const PROSE_PATH = new RegExp(+ String.raw`(?:(?<![A-Za-z0-9_])<app_data_dir>|(?<![A-Za-z0-9._~+=@%/\\:-])(?:~|[A-Za-z]:)?)(?:[/\\]${PROSE_SEGMENT})+[/\\]?`,+ "g",+);++/** The whole of an inline code span, as one path: the same roots, any non-space segment. */+const CODE_PATH = /^(?:<app_data_dir>|~|[A-Za-z]:)?(?:[/\\][^\s/\\]+)+[/\\]?$/;++const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");++/** Whether a well-formed candidate starts at a root this module capsules. */+function rooted(path: string, scope: PathScope): boolean {+ const p = path.replace(/\\/g, "/");+ if (p.startsWith(`${PLACEHOLDER_ROOT}/`)) return true;+ if (p.startsWith("/api/")) return false;+ return new RegExp(`/${escapeRe(scope.projectId)}/(?:organizations|agents)(?:/|$)`).test(p);+}++/** Text right after a prose path that carries it on through a non-ASCII segment. */+const RUNS_ON = /^[\p{L}\p{N}_-]+(?:[/\\]|\.[A-Za-z0-9])/u;++/** Text right before a bare `/` or `\` root that the path runs in from: a non-ASCII segment. */+const RUNS_IN = /[/\\][\p{L}\p{N}_-]+$/u;++/** Drops the sentence's full stop(s) from a prose path; a trailing `/` survives them. */+function trimTrailing(path: string): string {+ return path.replace(/\.+$/, "");+}++/** Whether a path names something past its root: `<app_data_dir>/` alone is not a capsule. */+function hasSegment(path: string): boolean {+ return pathLabel(path) !== "";+}++/** Splits prose into text and path pieces, in order. Adjacent text is merged; empty text is never emitted. */+export function splitPaths(text: string, scope: PathScope): PathPiece[] {+ const out: PathPiece[] = [];+ let last = 0;+ const pushText = (value: string) => {+ if (value === "") return;+ const prev = out[out.length - 1];+ if (prev?.kind === "text") prev.text += value;+ else out.push({ kind: "text", text: value });+ };+ for (const m of text.matchAll(PROSE_PATH)) {+ const path = trimTrailing(m[0]);+ if (!rooted(path, scope) || !hasSegment(path)) continue;+ if (RUNS_ON.test(text.slice(m.index + m[0].length))) continue;+ if (/^[/\\]/.test(path) && RUNS_IN.test(text.slice(0, m.index))) continue;+ pushText(text.slice(last, m.index));+ out.push({ kind: "path", path });+ last = m.index + path.length;+ }+ pushText(text.slice(last));+ return out;+}++/** The path an inline code span holds, when it holds exactly one; null for anything else. */+export function codePath(code: string, scope: PathScope): string | null {+ const value = code.trim();+ if (!CODE_PATH.test(value) || !rooted(value, scope) || !hasSegment(value)) return null;+ return value;+}++/**+ * The capsule's label: the last segment, without the trailing `/`. Empty for the placeholder+ * alone — the one root a rooted candidate can stop at, since any other root has to run on+ * through the Project's data directory.+ */+export function pathLabel(path: string): string {+ const body = path.replace(/[/\\]+$/, "");+ const name = body.slice(Math.max(body.lastIndexOf("/"), body.lastIndexOf("\\")) + 1);+ return name === PLACEHOLDER_ROOT ? "" : name;+}++/** Folder or file, by the rule in this module's comment. */+export function pathKind(path: string): "folder" | "file" {+ if (/[/\\]$/.test(path)) return "folder";+ return /^.+\.[A-Za-z0-9]{1,10}$/.test(pathLabel(path)) ? "file" : "folder";+}++/** ASCII punctuation: the characters a Markdown backslash escape can stand before. */+const ESCAPABLE = /[!-/:-@[-`{-~]/;++/** A pattern for one character as Markdown source may write it: punctuation may carry an escape. */+const sourceChar = (c: string) => (ESCAPABLE.test(c) ? String.raw`\\?` : "") + escapeRe(c);++/**+ * Pieces split from the text of a Markdown node, with each path that holds a `\` spelled the+ * way the node's `source` writes it. Markdown reads a backslash before punctuation as an escape+ * and drops it, so `C:\Users\ada\.penguin\…` reaches the text as `C:\Users\ada.penguin\…` —+ * but in a path written with `\` that backslash was a separator, and the source has the path as+ * written. A path without a `\` keeps the text's spelling: there a backslash in the source can+ * only have been an escape (`co\_lab`). A path whose spelling the source does not hold (an+ * entity in it) keeps the text's too.+ */+export function spellAsWritten(pieces: PathPiece[], source: string): PathPiece[] {+ let from = 0;+ return pieces.map((piece) => {+ if (piece.kind !== "path" || !piece.path.includes("\\")) return piece;+ const spelling = new RegExp(Array.from(piece.path, sourceChar).join(""), "g");+ spelling.lastIndex = from;+ const m = spelling.exec(source);+ if (m === null) return piece;+ from = m.index + m[0].length;+ return { kind: "path", path: m[0] };+ });+}diff --git a/packages/web/src/features/company/shared.tsx b/packages/web/src/features/company/shared.tsxindex e8341e4e..c015a3f9 100644--- a/packages/web/src/features/company/shared.tsx+++ b/packages/web/src/features/company/shared.tsx@@ -114,6 +114,11 @@ function orgStatusLabel(kind: OrgStatusKind): string {return kind === "paused" ? S.company.statusPaused : S.company.statusActive;}+/** An organization's headline state in words, for an accessible name that has to carry it. */+export function orgStatusText(org: { status: OrgStatus; invalid?: string }): string {+ return orgStatusLabel(orgStatusKind(org));+}+const ORG_STATUS_BADGE: Record<OrgStatusKind, BadgeTone> = {invalid: "red",paused: "amber",@@ -130,7 +135,7 @@ export function OrgStatusPill({ org }: { org: { status: OrgStatus; invalid?: str);}-/** The same state as a 6px dot (the switcher's trigger and rows), its name in the tooltip and sr text. */+/** The same state as a 6px dot (the switcher's rows), its name in the tooltip and sr text. */export function OrgStatusDot({ org }: { org: { status: OrgStatus; invalid?: string } }) {const kind = orgStatusKind(org);const label = orgStatusLabel(kind);diff --git a/packages/web/src/features/company/shell-org-status.ts b/packages/web/src/features/company/shell-org-status.tsindex 444d74d0..9ea1fada 100644--- a/packages/web/src/features/company/shell-org-status.ts+++ b/packages/web/src/features/company/shell-org-status.ts@@ -1,8 +1,9 @@/**- * The shell's organization status marks (pure, unit tested): the tone the switcher's dot and- * the overview's status pill take, and what a session-list group should render given what- * the store holds for it — so the sidebar never shows a skeleton for a fetch that already- * failed.+ * The shell's organization status marks (pure, unit tested): the tone the switcher rows' status+ * dots take — the status pill (the switcher's trigger, the overview, settings) reads its colour+ * from shared.tsx's `ORG_STATUS_BADGE` instead — and what a session-list group should render+ * given what the store holds for it, so the sidebar never shows a skeleton for a fetch that+ * already failed.*/import type { Tone } from "../../lib/tone";diff --git a/packages/web/src/features/company/ticket-dialog.tsx b/packages/web/src/features/company/ticket-dialog.tsxindex 02c7b996..59c81a1c 100644--- a/packages/web/src/features/company/ticket-dialog.tsx+++ b/packages/web/src/features/company/ticket-dialog.tsx@@ -58,8 +58,8 @@ import { Modal } from "../../components/ui/modal";import { Skeleton } from "../../components/ui/skeleton";import { CopyButton, ROW_COPY_CLASS } from "../../components/ui/copy-button";import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";-import { Md } from "../chat/md";import { OrgSection } from "./org-layout";+import { PathMarkdown, PathText } from "./path-capsule";import {BlockedBadge,PrincipalChip,@@ -385,7 +385,7 @@ function TicketDialog({<p className="text-xs text-gray-400 dark:text-gray-500">{empty}</p>) : (<div className="md-body text-sm leading-relaxed text-gray-800 dark:text-gray-100">- <Md text={text} />+ <PathMarkdown text={text} scope={{ projectId }} /></div>);@@ -512,7 +512,7 @@ function TicketDialog({><span><span className="font-medium">{S.company.tickets.blockedReason}:</span>{" "}- {detail.blocked}+ <PathText text={detail.blocked ?? ""} scope={{ projectId }} /></span>{detail.blockedBy !== undefined && (<span className="inline-flex items-center gap-1.5">@@ -689,7 +689,7 @@ function TicketDialog({<ul className="md-body md-compact list-disc pl-5 text-sm text-gray-800 marker:text-gray-400 dark:text-gray-100 dark:marker:text-gray-500">{detail.progress.map((p, i) => (<li key={`${i}-${p}`}>- <Md text={p} />+ <PathMarkdown text={p} scope={{ projectId }} /></li>))}</ul>diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 2055595e..6f12050b 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -4001,7 +4001,7 @@ Scenarios:"deny-all": "Deny all",} as Record<string, string>,status: "Status",- statusActive: "Active",+ statusActive: "Running",statusPaused: "Paused",pause: "Pause organization",resume: "Resume organization",@@ -4021,6 +4021,11 @@ Scenarios:/** Principals as the chat and tickets name them. */principalSystem: "System",principalAll: "Everyone",+ /** A data path in a ticket drawn as a capsule: the hover names the whole path, a click copies it. */+ pathCapsule: {+ hint: (path: string): string => `${path}\nClick to copy the full path`,+ copy: (path: string): string => `Copy path ${path}`,+ },/** Spend against a budget, and the unbounded case. */spendOfBudget: (spend: string, budget: string): string => `${spend} / ${budget}`,noBudget: "Unbounded",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex ba12250e..9c046254 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -4037,6 +4037,11 @@ Benchmark:/** Principals as the chat and tickets name them. */principalSystem: "系统",principalAll: "所有人",+ /** A data path in a ticket drawn as a capsule: the hover names the whole path, a click copies it. */+ pathCapsule: {+ hint: (path: string): string => `${path}\n点击复制完整路径`,+ copy: (path: string): string => `复制路径 ${path}`,+ },/** Spend against a budget, and the unbounded case. */spendOfBudget: (spend: string, budget: string): string => `${spend} / ${budget}`,noBudget: "不限",diff --git a/packages/web/test/channel-mentions.test.ts b/packages/web/test/channel-mentions.test.tsindex 9040f1b9..91daf537 100644--- a/packages/web/test/channel-mentions.test.ts+++ b/packages/web/test/channel-mentions.test.ts@@ -7,7 +7,6 @@import { describe, expect, it } from "vitest";import {channelMentionCandidates,- insertMention,mentionCandidates,mentionInsertId,mentionIsMe,@@ -45,19 +44,16 @@ describe("mentionQueryAt", () => {expect(mentionQueryAt("@agent:c", 8)).toEqual({ start: 0, query: "agent:c" });});+ it("reads a name typed in any script, glued to CJK text before the @", () => {+ expect(mentionQueryAt("请@张", 3)).toEqual({ start: 1, query: "张" });+ expect(mentionQueryAt("@Ada", 4)).toEqual({ start: 0, query: "Ada" });+ });+it("is null when the @ is glued to a word, when a space breaks the token, or when there is none", () => {expect(mentionQueryAt("mail@ex", 7)).toBeNull();expect(mentionQueryAt("@ceo please", 11)).toBeNull();expect(mentionQueryAt("plain", 5)).toBeNull();- });-});--describe("insertMention", () => {- it("replaces the typed token with the principal and a trailing space, moving the caret after it", () => {- expect(insertMention("hi @ce there", 3, 6, "agent:ceo")).toEqual({- text: "hi @agent:ceo there",- caret: 14,- });+ expect(mentionQueryAt("@Ada, hi", 8)).toBeNull();});});diff --git a/packages/web/test/mention-draft.test.ts b/packages/web/test/mention-draft.test.tsnew file mode 100644index 00000000..e097bb26--- /dev/null+++ b/packages/web/test/mention-draft.test.ts@@ -0,0 +1,518 @@+/**+ * The channel composer's draft (features/company/mention-draft.ts): a picked mention shows the+ * name a sent message renders and still goes out as the token the server resolves. It is one+ * block — an edit that reaches into it takes all of it, the caret and the selection step over+ * it, an input method's edit waits for compositionend, an undo brings it back whole, and a copy,+ * a cut or a drag carries it through the clipboard — and the message sent separates it from any+ * text that would otherwise swallow its token.+ */+import { describe, expect, it } from "vitest";+import { mentionRuns } from "../src/features/company/channel-mentions";+import {+ EMPTY_DRAFT,+ draftApplyClip,+ draftApplyEdit,+ draftFollowEdit,+ draftInsertMention,+ draftRecall,+ draftRemember,+ draftSegments,+ draftSlice,+ draftSnapSelection,+ draftWireText,+ mentionCovers,+ mentionDeletedByKey,+ parseClip,+ serializeClip,+} from "../src/features/company/mention-draft";+import type { DraftHistory, MentionDraft } from "../src/features/company/mention-draft";++/** Types `value` at the end of the draft, the way a keystroke or a paste reports it. */+const typeAtEnd = (d: MentionDraft, value: string): MentionDraft =>+ draftApplyEdit(d, d.text + value, d.text.length + value.length).draft;++/** Types `@query` at the end, then picks the candidate. */+function pick(d: MentionDraft, query: string, label: string, wire: string): MentionDraft {+ const typed = typeAtEnd(d, `@${query}`);+ const start = typed.text.length - query.length - 1;+ return draftInsertMention(typed, start, typed.text.length, label, wire).draft;+}++/** The browser deleting `from`…`to` (a key, a cut, a drag out), which leaves the caret at `from`. */+const deleteSpan = (d: MentionDraft, from: number, to: number) =>+ draftApplyEdit(d, d.text.slice(0, from) + d.text.slice(to), from);++const tokens = (text: string) => mentionRuns(text).flatMap((r) => (r.mention ? [r.mention] : []));++/** `@Ada Lovelace please`: the mention is 0…13. */+const base = () => typeAtEnd(pick(EMPTY_DRAFT, "A", "Ada Lovelace", "ceo"), "please");++describe("inserting a mention", () => {+ it("shows the name with a trailing space, moves the caret past it, and sends the id", () => {+ const typed = typeAtEnd(EMPTY_DRAFT, "hi @ce");+ const { draft, caret } = draftInsertMention(typed, 3, 6, "Ada Lovelace", "ceo");+ expect(draft.text).toBe("hi @Ada Lovelace ");+ expect(caret).toBe(17);+ expect(draftWireText(draft)).toBe("hi @ceo ");+ });++ it("keeps the text after the caret when the pick lands mid-draft", () => {+ const d = draftApplyEdit(EMPTY_DRAFT, "hi @ce there", 6).draft;+ const { draft } = draftInsertMention(d, 3, 6, "Ada", "ceo");+ expect(draft.text).toBe("hi @Ada there");+ expect(draftWireText(draft)).toBe("hi @ceo there");+ });++ it("names in CJK and names with spaces send their ids, and the server grammar reads them back", () => {+ let d = pick(EMPTY_DRAFT, "张", "张三", "zhangsan");+ d = typeAtEnd(d, "和");+ d = pick(d, "Ada", "Ada Lovelace", "ceo");+ d = typeAtEnd(d, "请看一下。");+ expect(d.text).toBe("@张三 和@Ada Lovelace 请看一下。");+ const wire = draftWireText(d);+ expect(wire).toBe("@zhangsan 和@ceo 请看一下。");+ expect(tokens(wire)).toEqual(["zhangsan", "ceo"]);+ });++ it("keeps two employees who share a name apart, down to which one a Backspace removes", () => {+ let d = pick(EMPTY_DRAFT, "Al", "Alex", "dev_alex");+ d = pick(d, "Al", "Alex", "ops_alex");+ expect(d.text).toBe("@Alex @Alex ");+ expect(draftWireText(d)).toBe("@dev_alex @ops_alex ");+ const second = deleteSpan(d, 10, 11).draft;+ expect(second.text).toBe("@Alex ");+ expect(draftWireText(second)).toBe("@dev_alex ");+ const first = deleteSpan(d, 4, 5).draft;+ expect(first.text).toBe(" @Alex ");+ expect(draftWireText(first)).toBe(" @ops_alex ");+ });++ it("carries the disambiguated member and the everyone token as picked", () => {+ let d = pick(EMPTY_DRAFT, "al", "alice", "user:alice");+ d = pick(d, "", "所有人", "all");+ expect(d.text).toBe("@alice @所有人 ");+ expect(draftWireText(d)).toBe("@user:alice @all ");+ });++ it("marks where a picked mention sits, so no @ panel opens on its name", () => {+ const d = pick(typeAtEnd(EMPTY_DRAFT, "cc "), "A", "Ada", "ceo");+ expect(mentionCovers(d, 3)).toBe(true);+ expect(mentionCovers(d, 6)).toBe(true);+ expect(mentionCovers(d, 2)).toBe(false);+ expect(mentionCovers(d, 7)).toBe(false);+ });+});++describe("a mention is one block", () => {+ it("Backspace at its end removes all of it, the caret landing where it started", () => {+ const { draft, caret } = deleteSpan(base(), 12, 13);+ expect(draft).toEqual({ text: " please", mentions: [] });+ expect(caret).toBe(0);+ });++ it("Delete at its start removes all of it", () => {+ const { draft, caret } = deleteSpan(base(), 0, 1);+ expect(draft).toEqual({ text: " please", mentions: [] });+ expect(caret).toBe(0);+ });++ it("a character deleted beside it, outside it, leaves it whole", () => {+ let d = typeAtEnd(EMPTY_DRAFT, "cc ");+ d = typeAtEnd(pick(d, "A", "Ada", "ceo"), "x");+ expect(d.text).toBe("cc @Ada x");+ const before = deleteSpan(d, 2, 3); // Backspace at its start+ expect(before.draft.text).toBe("cc@Ada x");+ expect(before.draft.mentions).toHaveLength(1);+ const after = deleteSpan(d, 7, 8); // Delete at its end+ expect(after.draft.text).toBe("cc @Adax");+ expect(after.draft.mentions).toHaveLength(1);+ });++ it("a word delete, a cut or a drag that takes part of it takes all of it", () => {+ // Ctrl+Backspace after "Lovelace ": the browser deletes the word and the space.+ const word = draftApplyEdit(base(), "@Ada please", 5);+ expect(word.draft).toEqual({ text: "please", mentions: [] });+ expect(word.caret).toBe(0);+ // A cut of "da Lovelace pl", starting inside the name.+ const cut = deleteSpan(base(), 2, 16);+ expect(cut.draft).toEqual({ text: "ease", mentions: [] });+ });++ it("replacing a selection that cuts into it replaces all of it", () => {+ // "Love" selected and "x" typed over it.+ const { draft, caret } = draftApplyEdit(base(), "@Ada xlace please", 6);+ expect(draft).toEqual({ text: "x please", mentions: [] });+ expect(caret).toBe(1);+ });++ it("text dropped inside it replaces it", () => {+ const { draft, caret } = draftApplyEdit(base(), "@Ada LoXvelace please", 8);+ expect(draft).toEqual({ text: "X please", mentions: [] });+ expect(caret).toBe(1);+ });++ it("text typed or pasted at either edge, or anywhere else, only moves it", () => {+ let d = typeAtEnd(base(), " review");+ expect(draftWireText(d)).toBe("@ceo please review");+ const pasted = draftApplyEdit(d, `hey ${d.text}`, 4);+ expect(pasted.draft.text).toBe("hey @Ada Lovelace please review");+ expect(pasted.caret).toBe(4);+ expect(draftWireText(pasted.draft)).toBe("hey @ceo please review");+ d = draftApplyEdit(base(), "@Ada Lovelace, please", 14).draft;+ expect(d.mentions).toEqual([{ start: 0, label: "Ada Lovelace", wire: "ceo" }]);+ });++ it("an a typed after a name ending in a is typed after it, not inside it", () => {+ const d = pick(EMPTY_DRAFT, "An", "Anna", "anna_pm");+ const { draft } = draftApplyEdit(d, "@Annaa ", 6);+ expect(draft.mentions).toEqual([{ start: 0, label: "Anna", wire: "anna_pm" }]);+ });++ it("of two glued mentions, a Backspace between them removes only the one before", () => {+ let d = pick(EMPTY_DRAFT, "张", "张三", "zhangsan");+ d = draftApplyEdit(d, "@张三", 3).draft; // its trailing space deleted+ d = pick(d, "李", "李四", "lisi");+ expect(d.text).toBe("@张三@李四 ");+ const { draft } = deleteSpan(d, 2, 3);+ expect(draft.text).toBe("@李四 ");+ expect(draftWireText(draft)).toBe("@lisi ");+ });++ it("clearing the whole draft clears its mentions", () => {+ expect(draftApplyEdit(base(), "", 0).draft).toEqual(EMPTY_DRAFT);+ });++ it("a pasted @Name is plain text, a pasted @id is sent as typed", () => {+ let d = typeAtEnd(EMPTY_DRAFT, "@Ada Lovelace ");+ expect(d.mentions).toEqual([]);+ expect(draftWireText(d)).toBe("@Ada Lovelace ");+ d = typeAtEnd(d, "@ceo");+ expect(draftWireText(d)).toBe("@Ada Lovelace @ceo");+ });+});++describe("Backspace and Delete at an edge, as one native delete", () => {+ it("names the whole mention a Backspace right after it or a Delete right before it reaches", () => {+ const d = base();+ expect(mentionDeletedByKey(d, "deleteContentBackward", 13, 13)).toEqual({ start: 0, end: 13 });+ expect(mentionDeletedByKey(d, "deleteContentForward", 0, 0)).toEqual({ start: 0, end: 13 });+ });++ it("is null for a key away from an edge, a selection, or any other edit", () => {+ const d = base();+ expect(mentionDeletedByKey(d, "deleteContentBackward", 14, 14)).toBeNull();+ expect(mentionDeletedByKey(d, "deleteContentBackward", 0, 0)).toBeNull();+ expect(mentionDeletedByKey(d, "deleteContentForward", 13, 13)).toBeNull();+ expect(mentionDeletedByKey(d, "deleteContentBackward", 0, 13)).toBeNull();+ expect(mentionDeletedByKey(d, "deleteWordBackward", 13, 13)).toBeNull();+ expect(mentionDeletedByKey(d, "insertText", 13, 13)).toBeNull();+ });+});++describe("the caret and the selection", () => {+ const sel = (start: number, end: number, backward = false) => ({ start, end, backward });++ it("an arrow key steps over a mention in either direction", () => {+ const d = base();+ expect(draftSnapSelection(d, sel(1, 1), 0)).toEqual({ start: 13, end: 13 });+ expect(draftSnapSelection(d, sel(12, 12), 13)).toEqual({ start: 0, end: 0 });+ // A word jump that lands inside continues the same way.+ expect(draftSnapSelection(d, sel(4, 4), 0)).toEqual({ start: 13, end: 13 });+ });++ it("a click inside a mention puts the caret at the nearer edge", () => {+ const d = base();+ expect(draftSnapSelection(d, sel(11, 11), null)).toEqual({ start: 13, end: 13 });+ expect(draftSnapSelection(d, sel(2, 2), null)).toEqual({ start: 0, end: 0 });+ });++ it("a caret outside every mention stays put", () => {+ const d = base();+ expect(draftSnapSelection(d, sel(13, 13), 12)).toEqual({ start: 13, end: 13 });+ expect(draftSnapSelection(d, sel(16, 16), null)).toEqual({ start: 16, end: 16 });+ expect(draftSnapSelection(d, sel(14, 18), 18)).toEqual({ start: 14, end: 18 });+ });++ it("Shift+arrow grows a selection by the whole mention and shrinks it back", () => {+ const d = base();+ expect(draftSnapSelection(d, sel(0, 1), 0)).toEqual({ start: 0, end: 13 });+ expect(draftSnapSelection(d, sel(0, 12), 13)).toEqual({ start: 0, end: 0 });+ expect(draftSnapSelection(d, sel(12, 20, true), 13)).toEqual({ start: 0, end: 20 });+ expect(draftSnapSelection(d, sel(1, 20, true), 0)).toEqual({ start: 13, end: 20 });+ });++ it("a range a pointer made that cuts into a mention grows to hold all of it", () => {+ const d = base();+ // A double-click on "Ada", and a drag from inside the name into the next word.+ expect(draftSnapSelection(d, sel(1, 4), null)).toEqual({ start: 0, end: 13 });+ expect(draftSnapSelection(d, sel(6, 17), null)).toEqual({ start: 0, end: 17 });+ });++ it("an end that did not move but sits inside a mention grows outward", () => {+ const d = typeAtEnd(pick(typeAtEnd(EMPTY_DRAFT, "cc "), "A", "Ada", "ceo"), "go");+ expect(d.text).toBe("cc @Ada go");+ expect(draftSnapSelection(d, sel(5, 9), 9)).toEqual({ start: 3, end: 9 });+ });+});++describe("input methods", () => {+ it("while composing the draft follows the box without rewriting it; compositionend widens the edit", () => {+ const before = base();+ // A keyboard app that composes over "Lovelace" deletes its last letter.+ const composing = draftFollowEdit(before, "@Ada Lovelac please", 12);+ expect(composing).toEqual({ text: "@Ada Lovelac please", mentions: [] });+ // At compositionend the edit is judged against the draft the composition started from.+ const ended = draftApplyEdit(before, "@Ada Lovelac please", 12);+ expect(ended.draft).toEqual({ text: " please", mentions: [] });+ expect(ended.caret).toBe(0);+ });++ it("a composition beside a mention keeps it", () => {+ const before = pick(EMPTY_DRAFT, "张", "张三", "zhangsan");+ const composing = draftFollowEdit(before, "@张三 ni", 6);+ expect(composing.mentions).toEqual(before.mentions);+ const ended = draftApplyEdit(before, "@张三 你好", 6);+ expect(ended.draft.mentions).toEqual(before.mentions);+ expect(draftWireText(ended.draft)).toBe("@zhangsan 你好");+ });+});++describe("undo and redo", () => {+ it("text an undo, a redo or a drop leaves selected is placed by where the selection ends", () => {+ const d = base();+ // " please" selected and deleted …+ const deleted = deleteSpan(d, 13, 20).draft;+ expect(deleted.text).toBe("@Ada Lovelace");+ // … then Ctrl+Z puts it back with 13…20 selected: the edit ends at 20, beside the name.+ expect(draftFollowEdit(deleted, d.text, 20)).toEqual(d);+ expect(draftApplyEdit(deleted, d.text, 20)).toEqual({ draft: d, caret: 20 });+ });++ it("an undo that brings back a deleted mention's text brings the mention back", () => {+ const d = base();+ let history: DraftHistory = [];+ history = draftRemember(history, d);+ const deleted = deleteSpan(d, 12, 13).draft;+ history = draftRemember(history, deleted);+ expect(draftRecall(history, d.text)).toEqual(d);+ // Without the history the same undo only gets the text back.+ expect(draftFollowEdit(deleted, d.text, 13).mentions).toEqual([]);+ });++ it("the history keeps the latest draft per text, skips drafts without mentions, and stays short", () => {+ const ada = pick(EMPTY_DRAFT, "A", "Ada", "ceo");+ const other = pick(EMPTY_DRAFT, "A", "Ada", "ada_ops");+ let history = draftRemember(draftRemember([], ada), other);+ expect(history).toEqual([other]);+ expect(draftRemember(history, typeAtEnd(EMPTY_DRAFT, "plain"))).toBe(history);+ expect(draftRecall(history, "missing")).toBeNull();+ for (let i = 0; i < 60; i += 1) history = draftRemember(history, typeAtEnd(ada, `${i}`));+ expect(history).toHaveLength(50);+ expect(draftRecall(history, ada.text)).toBeNull();+ });+});++describe("the clipboard", () => {+ const names: Record<string, string> = { ceo: "Ada Lovelace", zhangsan: "张三" };+ /** The composer's labelOf: an employee's name, a member's id, the token itself for an unknown id. */+ const labelOf = (wire: string) => names[wire] ?? wire.replace(/^user:/, "");++ it("a copy carries the mentions wholly inside the selection, offsets relative to it", () => {+ const d = typeAtEnd(pick(typeAtEnd(EMPTY_DRAFT, "cc "), "A", "Ada Lovelace", "ceo"), "go");+ expect(d.text).toBe("cc @Ada Lovelace go");+ expect(draftSlice(d, 3, 19)).toEqual({+ text: "@Ada Lovelace go",+ mentions: [{ start: 0, label: "Ada Lovelace", wire: "ceo" }],+ });+ expect(draftSlice(d, 0, 3)).toEqual({ text: "cc ", mentions: [] });+ // A stretch cutting into a mention carries none of it; the selection snaps, so a copy never does.+ expect(draftSlice(d, 5, 19).mentions).toEqual([]);+ });++ it("serializes a clip and parses it back, CJK names and members included", () => {+ let d = pick(EMPTY_DRAFT, "张", "张三", "zhangsan");+ d = typeAtEnd(d, "和");+ d = pick(d, "Ada", "Ada Lovelace", "ceo");+ d = pick(d, "al", "alice", "user:alice");+ const clip = draftSlice(d, 0, d.text.length);+ expect(clip.mentions).toHaveLength(3);+ expect(parseClip(serializeClip(clip), clip.text, labelOf)).toEqual(clip);+ });++ it("reads a payload only beside its own text, whatever line endings the clipboard gave it", () => {+ const clip = draftSlice(base(), 0, 20);+ expect(parseClip(serializeClip(clip), "@Ada Lovelace pleas", labelOf)).toBeNull();+ const lines = { text: "@Ada Lovelace\nplease", mentions: clip.mentions };+ expect(parseClip(serializeClip(lines), "@Ada Lovelace\r\nplease", labelOf)).toEqual(lines);+ });++ it("reads a payload that does not parse, or whose mentions do not read @<label> in order, as no clip", () => {+ const text = "hi @Ada Lovelace";+ const ok = { start: 3, label: "Ada Lovelace", wire: "ceo" };+ const payload = (mentions: unknown) => JSON.stringify({ text, mentions });+ expect(parseClip(payload([ok]), text, labelOf)).toEqual({ text, mentions: [ok] });+ const bad = [+ "",+ "{",+ "null",+ "[]",+ JSON.stringify({ text }),+ JSON.stringify({ text: 1, mentions: [ok] }),+ payload("x"),+ payload([null]),+ payload([{ ...ok, start: "3" }]),+ payload([{ ...ok, start: 3.5 }]),+ payload([{ ...ok, start: -1 }]),+ payload([{ ...ok, start: 2 }]), // not where its @ is+ payload([{ ...ok, start: 30 }]), // past the end+ payload([{ ...ok, label: 7 }]),+ payload([{ ...ok, wire: null }]),+ payload([ok, ok]), // overlapping+ ];+ for (const p of bad) expect(parseClip(p, text, labelOf), p).toBeNull();+ });++ it("brings back only a mention whose label is still what its token shows here", () => {+ const text = "@Ada Lovelace @张三 @Grace";+ const mentions = [+ { start: 0, label: "Ada Lovelace", wire: "ceo" },+ // A name that would send someone else's token.+ { start: 14, label: "张三", wire: "ceo" },+ // Another organization's employee: this one does not know the id.+ { start: 18, label: "Grace", wire: "lab_grace" },+ ];+ expect(parseClip(JSON.stringify({ text, mentions }), text, labelOf)).toEqual({+ text,+ mentions: [mentions[0]],+ });+ const none = JSON.stringify({ text, mentions: mentions.slice(1) });+ expect(parseClip(none, text, labelOf)).toBeNull();+ });++ it("a cut pasted elsewhere is a mention again, and is sent by id", () => {+ const d = base();+ const clip = draftSlice(d, 0, 14);+ const cut = typeAtEnd(deleteSpan(d, 0, 14).draft, " ");+ expect(cut).toEqual({ text: "please ", mentions: [] });+ // The box inserts the text and leaves the caret after it.+ const pasted = draftApplyClip(cut, "please @Ada Lovelace ", 21, clip);+ expect(pasted).toEqual({+ draft: {+ text: "please @Ada Lovelace ",+ mentions: [{ start: 7, label: "Ada Lovelace", wire: "ceo" }],+ },+ caret: 21,+ });+ expect(draftWireText(pasted!.draft)).toBe("please @ceo ");+ // Pasted again right after itself: two mentions.+ const twice = draftApplyClip(pasted!.draft, `${pasted!.draft.text}${clip.text}`, 35, clip);+ expect(draftWireText(twice!.draft)).toBe("please @ceo @ceo ");+ });++ it("a paste over a selection replaces it", () => {+ const d = typeAtEnd(EMPTY_DRAFT, "hello world");+ const clip = draftSlice(base(), 0, 13);+ const pasted = draftApplyClip(d, "hello @Ada Lovelace", 19, clip);+ expect(pasted?.draft.mentions).toEqual([{ start: 6, label: "Ada Lovelace", wire: "ceo" }]);+ expect(pasted?.caret).toBe(19);+ });++ it("a drag within the box moves the mention: deleted where it was, a mention where it lands", () => {+ const d = base();+ const clip = draftSlice(d, 0, 13);+ // The box deletes the dragged text (deleteByDrag) …+ const deleted = draftApplyEdit(d, " please", 0).draft;+ expect(deleted).toEqual({ text: " please", mentions: [] });+ // … then inserts it where it lands, left selected (insertFromDrop).+ const dropped = draftApplyClip(deleted, " please@Ada Lovelace", 20, clip);+ expect(dropped?.draft.mentions).toEqual([{ start: 7, label: "Ada Lovelace", wire: "ceo" }]);+ expect(draftWireText(dropped!.draft)).toBe(" please @ceo");+ });++ it("a clip landing inside a mention replaces the whole of it", () => {+ const clip = draftSlice(pick(EMPTY_DRAFT, "张", "张三", "zhangsan"), 0, 3);+ const dropped = draftApplyClip(base(), "@Ada@张三 Lovelace please", 7, clip);+ expect(dropped).toEqual({+ draft: { text: "@张三 please", mentions: [{ start: 0, label: "张三", wire: "zhangsan" }] },+ caret: 3,+ });+ });++ it("is null when the box inserted something other than the clip in front of the caret", () => {+ const clip = draftSlice(base(), 0, 13);+ const d = typeAtEnd(EMPTY_DRAFT, "hi ");+ expect(draftApplyClip(d, "hi @Ada Lovelac", 15, clip)).toBeNull();+ expect(draftApplyClip(d, "hi @Ada Lovelace ", 18, clip)).toBeNull();+ expect(draftApplyClip(d, "hi @Ada Lovelace", 3, clip)).toBeNull();+ });+});++describe("the message sent", () => {+ it("a mention glued to a word before it goes out with a space before its token", () => {+ const d = pick(EMPTY_DRAFT, "A", "Ada", "ceo");+ const glued = draftApplyEdit(d, `x${d.text}`, 1).draft;+ expect(glued.mentions).toHaveLength(1);+ expect(draftWireText(glued)).toBe("x @ceo ");+ expect(tokens(draftWireText(glued))).toEqual(["ceo"]);+ });++ it("a letter or a file extension right after it is set apart; a full stop is not", () => {+ const d = pick(EMPTY_DRAFT, "A", "Ada", "ceo");+ expect(draftWireText(draftApplyEdit(d, "@Aday", 5).draft)).toBe("@ceo y");+ expect(draftWireText(draftApplyEdit(d, "@Ada.md", 7).draft)).toBe("@ceo .md");+ expect(draftWireText(draftApplyEdit(d, "@Ada.", 5).draft)).toBe("@ceo.");+ });++ it("text right after a CJK name never extends the id, so nothing is added", () => {+ const d = pick(EMPTY_DRAFT, "张", "张三", "zhangsan");+ const glued = draftApplyEdit(d, "@张三你好", 5).draft;+ expect(draftWireText(glued)).toBe("@zhangsan你好");+ expect(tokens(draftWireText(glued))).toEqual(["zhangsan"]);+ });++ it("an @id typed right after a CJK name still reaches its reader", () => {+ let d = pick(EMPTY_DRAFT, "张", "张三", "zhangsan");+ d = draftApplyEdit(d, "@张三", 3).draft; // trailing space deleted+ d = typeAtEnd(d, "@ceo ");+ expect(d.text).toBe("@张三@ceo ");+ expect(tokens(d.text)).toEqual(["ceo"]);+ expect(draftWireText(d)).toBe("@zhangsan @ceo ");+ expect(tokens(draftWireText(d))).toEqual(["zhangsan", "ceo"]);+ });++ it("two glued mentions both convert", () => {+ let d = pick(EMPTY_DRAFT, "张", "张三", "zhangsan");+ d = draftApplyEdit(d, "@张三", 3).draft;+ d = pick(d, "李", "李四", "lisi");+ expect(d.text).toBe("@张三@李四 ");+ expect(tokens(draftWireText(d))).toEqual(["zhangsan", "lisi"]);+ });++ it("a mention after a typed token whose full stop would swallow its @ is set apart", () => {+ const d = pick(typeAtEnd(EMPTY_DRAFT, "@bob."), "A", "Ada", "ceo");+ expect(d.text).toBe("@bob.@Ada ");+ expect(draftWireText(d)).toBe("@bob. @ceo ");+ expect(tokens(draftWireText(d))).toEqual(["bob", "ceo"]);+ });+});++describe("draftSegments", () => {+ it("splits the draft into plain runs and the mentions the highlight layer tints, glued ones included", () => {+ let d = typeAtEnd(EMPTY_DRAFT, "cc ");+ d = pick(d, "A", "Ada", "ceo");+ d = typeAtEnd(d, "and x");+ d = pick(d, "B", "Bob", "bob");+ expect(d.text).toBe("cc @Ada and x@Bob ");+ expect(draftSegments(d)).toEqual([+ { text: "cc ", mention: false },+ { text: "@Ada", mention: true },+ { text: " and x", mention: false },+ { text: "@Bob", mention: true },+ { text: " ", mention: false },+ ]);+ });++ it("is empty for an empty draft", () => {+ expect(draftSegments(EMPTY_DRAFT)).toEqual([]);+ });+});diff --git a/packages/web/test/path-capsules.test.ts b/packages/web/test/path-capsules.test.tsnew file mode 100644index 00000000..9e1fb34c--- /dev/null+++ b/packages/web/test/path-capsules.test.ts@@ -0,0 +1,305 @@+/**+ * Data paths in a ticket's text (features/company/path-capsules.ts and path-capsule.tsx): which+ * stretches are paths — the `<app_data_dir>` placeholder, an absolute path through this+ * Project's data directory, a code span holding one path — where one stops against the+ * punctuation and CJK around it, folder or file, and the capsules the ticket Markdown draws+ * for them (react-dom/server static markup, node env).+ */+import { describe, expect, it } from "vitest";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import {+ codePath,+ pathKind,+ pathLabel,+ spellAsWritten,+ splitPaths,+} from "../src/features/company/path-capsules";+import type { PathPiece } from "../src/features/company/path-capsules";+import { PathMarkdown, PathText } from "../src/features/company/path-capsule";+import { S } from "../src/lib/strings";++const scope = { projectId: "default_project" };+const LAB = "<app_data_dir>/organizations/co_research_paper_lab";+/** Where a server on Windows puts the same organization: a drive, backslashes, a dot directory. */+const WIN_LAB = String.raw`C:\Users\ada\.penguin\data\default_project\organizations\co_lab`;++/** A string as React writes it into an attribute. */+const attr = (s: string) =>+ s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);++/** How many capsules a render drew, told apart from other buttons (a code block's copy) by their accessible name. */+const capsuleCount = (html: string) =>+ html.split(`aria-label="${S.company.pathCapsule.copy("")}`).length - 1;++const paths = (text: string) =>+ splitPaths(text, scope).flatMap((p) => (p.kind === "path" ? [p.path] : []));++describe("splitPaths", () => {+ it("splits prose into text and path pieces, in order", () => {+ expect(splitPaths(`See ${LAB}/workspace/experiments/dep-eval/ for the runs.`, scope)).toEqual([+ { kind: "text", text: "See " },+ { kind: "path", path: `${LAB}/workspace/experiments/dep-eval/` },+ { kind: "text", text: " for the runs." },+ ]);+ });++ it("returns one text piece for text with no path", () => {+ expect(splitPaths("nothing here", scope)).toEqual([{ kind: "text", text: "nothing here" }]);+ expect(splitPaths("", scope)).toEqual([]);+ });++ it("keeps CJK text and full-width punctuation outside the path", () => {+ expect(paths(`结果写在${LAB}/workspace/report.md。`)).toEqual([`${LAB}/workspace/report.md`]);+ expect(paths(`见(${LAB}/workspace/exp/),然后`)).toEqual([`${LAB}/workspace/exp/`]);+ expect(paths(`目录:${LAB}/handbook/里有说明`)).toEqual([`${LAB}/handbook/`]);+ });++ it("leaves a sentence's trailing punctuation out of the path", () => {+ expect(paths(`Done in ${LAB}/workspace/exp.`)).toEqual([`${LAB}/workspace/exp`]);+ expect(paths(`(${LAB}/workspace/exp), next`)).toEqual([`${LAB}/workspace/exp`]);+ expect(paths(`${LAB}/workspace/a.csv, ${LAB}/workspace/b.csv; done`)).toEqual([+ `${LAB}/workspace/a.csv`,+ `${LAB}/workspace/b.csv`,+ ]);+ expect(paths(`"${LAB}/workspace/exp/"...`)).toEqual([`${LAB}/workspace/exp/`]);+ });++ it("finds several paths, in order", () => {+ const text = `Compare ${LAB}/workspace/v1/ and ${LAB}/workspace/v2/, then write <app_data_dir>/agents/co_lab_ceo/agent_state/AGENTS.md`;+ expect(paths(text)).toEqual([+ `${LAB}/workspace/v1/`,+ `${LAB}/workspace/v2/`,+ "<app_data_dir>/agents/co_lab_ceo/agent_state/AGENTS.md",+ ]);+ });++ it("takes an absolute path that runs through this Project's data directory", () => {+ const abs = "/home/ada/.penguin/data/default_project/organizations/co_lab/workspace/site/";+ expect(paths(`Built into ${abs} today`)).toEqual([abs]);+ expect(paths("~/.penguin/data/default_project/agents/co_lab_ceo/scratchpad/notes.md")).toEqual([+ "~/.penguin/data/default_project/agents/co_lab_ceo/scratchpad/notes.md",+ ]);+ expect(paths("C:/Users/ada/.penguin/data/default_project/organizations/co_lab/x.json")).toEqual(+ ["C:/Users/ada/.penguin/data/default_project/organizations/co_lab/x.json"],+ );+ });++ it("takes a Windows path, written with backslashes or with both separators", () => {+ const report = String.raw`${WIN_LAB}\workspace\report.md`;+ expect(paths(`结果在${report}。`)).toEqual([report]);+ const desk =+ String.raw`C:\Users\ada\.penguin\data\default_project\agents\co_lab_ceo\scratchpad` + "\\";+ expect(paths(`Notes in ${desk} for now`)).toEqual([desk]);+ const mixed = String.raw`C:\Users\ada/.penguin/data\default_project\organizations/co_lab\x.json`;+ expect(paths(`(${mixed})`)).toEqual([mixed]);+ const exp = String.raw`<app_data_dir>\organizations\co_lab\exp` + "\\";+ expect(paths(`Done in ${exp}.`)).toEqual([exp]);+ });++ it("leaves other Windows paths alone", () => {+ expect(paths(String.raw`C:\Users\ada\Documents\report.md`)).toEqual([]);+ expect(paths(String.raw`D:\penguin\other_project\organizations\co_lab\x`)).toEqual([]);+ });++ it("leaves other absolute paths, routes and URLs alone", () => {+ expect(paths("GET /api/v1/organizations/co_lab/tickets returns 200")).toEqual([]);+ expect(+ paths("GET /api/projects/default_project/organizations/co_lab/tickets/T-12 returned 404"),+ ).toEqual([]);+ expect(paths("/home/ada/.penguin/data/other_project/organizations/co_lab/x")).toEqual([]);+ expect(paths("https://example.test/default_project/organizations/co_lab/x")).toEqual([]);+ expect(paths("and/or 1/2 <app_data_dir>/")).toEqual([]);+ });++ it("does not start a path in the middle of a word, but does after a colon", () => {+ expect(paths(`prefix${LAB}/x`)).toEqual([]);+ expect(paths("key=/home/ada/default_project/organizations/co_lab/x")).toEqual([]);+ expect(paths(`Output:${LAB}/workspace/out/`)).toEqual([`${LAB}/workspace/out/`]);+ });++ it("stops at a space", () => {+ expect(paths(`${LAB}/workspace/my notes/`)).toEqual([`${LAB}/workspace/my`]);+ });++ it("leaves a path that runs on through a non-ASCII segment as text, rather than capsuling its parent", () => {+ expect(paths(`结果在 ${LAB}/workspace/调研报告.md`)).toEqual([]);+ expect(paths(`${LAB}/workspace/实验/`)).toEqual([]);+ expect(paths(`${LAB}/workspace/report实验.md`)).toEqual([]);+ expect(paths(`见 ${LAB}/workspace/exp/,数据在 ${LAB}/workspace/数据/a.csv`)).toEqual([+ `${LAB}/workspace/exp/`,+ ]);+ // Prose that resumes after a folder goes on to no `/` or extension, so the folder is kept.+ expect(paths(`目录:${LAB}/handbook/里有说明`)).toEqual([`${LAB}/handbook/`]);+ expect(paths(String.raw`${WIN_LAB}\workspace\调研\a.md`)).toEqual([]);+ });++ it("leaves the tail of a path that runs in from a non-ASCII segment as text", () => {+ const home =+ String.raw`C:\Users\张三\.penguin\data\default_project\organizations\co_lab\workspace` + "\\";+ expect(paths(home)).toEqual([]);+ expect(paths("/home/张三/.penguin/data/default_project/organizations/co_lab/x.md")).toEqual([]);+ // CJK right before a root is the sentence, not a segment: no separator comes before it.+ const site = "/home/ada/.penguin/data/default_project/organizations/co_lab/site/";+ expect(paths(`构建到${site}了`)).toEqual([site]);+ });++ it("keeps a whole <placeholder> segment inside the path", () => {+ expect(paths("<app_data_dir>/agents/<agent_id>/agent_state/skills/")).toEqual([+ "<app_data_dir>/agents/<agent_id>/agent_state/skills/",+ ]);+ });+});++describe("codePath", () => {+ it("reads a code span that is one path, verbatim", () => {+ expect(codePath(`${LAB}/workspace/exp/`, scope)).toBe(`${LAB}/workspace/exp/`);+ expect(codePath(` ${LAB}/workspace/实验/结果.md `, scope)).toBe(+ `${LAB}/workspace/实验/结果.md`,+ );+ expect(codePath(`${LAB}/workspace/v1.`, scope)).toBe(`${LAB}/workspace/v1.`);+ });++ it("leaves a command, a route and a bare word as code", () => {+ expect(codePath(`ls ${LAB}/workspace`, scope)).toBeNull();+ expect(codePath(`${LAB}/run.sh --fast`, scope)).toBeNull();+ expect(codePath("/api/v1/tickets", scope)).toBeNull();+ expect(codePath("/api/projects/default_project/agents/ceo/schedules", scope)).toBeNull();+ expect(codePath("penguin", scope)).toBeNull();+ expect(codePath(String.raw`dir ${WIN_LAB}\workspace`, scope)).toBeNull();+ });++ it("reads a code span holding one Windows path, verbatim", () => {+ const exp = String.raw`${WIN_LAB}\workspace\exp` + "\\";+ expect(codePath(exp, scope)).toBe(exp);+ const mixed = String.raw`C:\Users\ada/.penguin/data\default_project\agents\ceo/notes.md`;+ expect(codePath(mixed, scope)).toBe(mixed);+ });+});++describe("pathLabel and pathKind", () => {+ it("labels a path by its last segment", () => {+ expect(pathLabel(`${LAB}/workspace/experiments/dep-eval/`)).toBe("dep-eval");+ expect(pathLabel(`${LAB}/workspace/report.md`)).toBe("report.md");+ expect(pathLabel("<app_data_dir>/")).toBe("");+ });++ it("splits a Windows path on either separator", () => {+ expect(pathLabel(String.raw`${WIN_LAB}\workspace\report.md`)).toBe("report.md");+ expect(pathLabel(String.raw`${WIN_LAB}\workspace\dep-eval` + "\\")).toBe("dep-eval");+ expect(pathLabel(String.raw`${WIN_LAB}/workspace\x.json`)).toBe("x.json");+ expect(pathLabel(String.raw`${WIN_LAB}\workspace/x.json`)).toBe("x.json");+ });++ it("reads a trailing slash as a folder, an extension as a file, and anything else as a folder", () => {+ expect(pathKind(`${LAB}/workspace/dep-eval/`)).toBe("folder");+ expect(pathKind(`${LAB}/workspace/dep-eval`)).toBe("folder");+ expect(pathKind(`${LAB}/workspace/report.md`)).toBe("file");+ expect(pathKind(`${LAB}/workspace/run.v2.json`)).toBe("file");+ expect(pathKind(`${LAB}/workspace/archive.tar.gz/`)).toBe("folder");+ expect(pathKind(String.raw`${WIN_LAB}\workspace\archive.tar.gz` + "\\")).toBe("folder");+ expect(pathKind(String.raw`${WIN_LAB}\workspace\report.md`)).toBe("file");+ });+});++describe("spellAsWritten", () => {+ it("spells a path holding a backslash as the Markdown source does, any other as the text does", () => {+ const pieces: PathPiece[] = [+ { kind: "text", text: "see " },+ { kind: "path", path: String.raw`C:\x\ada.penguin\default_project\organizations\a` },+ { kind: "text", text: " and " },+ { kind: "path", path: "/x/default_project/organizations/co_lab" },+ ];+ const source = String.raw`see C:\x\ada\.penguin\default_project\organizations\a and /x/default_project/organizations/co\_lab`;+ expect(spellAsWritten(pieces, source)).toEqual([+ pieces[0],+ { kind: "path", path: String.raw`C:\x\ada\.penguin\default_project\organizations\a` },+ pieces[2],+ pieces[3],+ ]);+ // A spelling the source does not hold (an entity stood in for a character) keeps the text's.+ expect(spellAsWritten(pieces, "see C:\x")).toEqual(pieces);+ });+});++describe("ticket Markdown with capsules", () => {+ const render = (text: string) =>+ renderToStaticMarkup(createElement(PathMarkdown, { text, scope }));++ it("draws a path in prose as a capsule labelled by its last segment, the full path in the tooltip", () => {+ const html = render(`结果在 ${LAB}/workspace/experiments/dep-eval/。`);+ expect(capsuleCount(html)).toBe(1);+ expect(html).toContain(">dep-eval</span></button>");+ expect(html).toContain(`title="${LAB.replace(/</g, "<").replace(/>/g, ">")}`);+ expect(html).toContain("。");+ expect(html).not.toContain(+ "organizations/co_research_paper_lab/workspace/experiments/dep-eval/。",+ );+ });++ it("draws an inline code span holding one path as a capsule, and leaves a command as code", () => {+ const html = render(`Open \`${LAB}/workspace/a.md\` or run \`ls ${LAB}/workspace\``);+ expect(capsuleCount(html)).toBe(1);+ expect(html).toContain(">a.md</span></button>");+ expect(html).toContain(+ "<code>ls <app_data_dir>/organizations/co_research_paper_lab/workspace</code>",+ );+ });++ it("keeps a fenced block verbatim", () => {+ const html = render(`\`\`\`\n${LAB}/workspace/exp/\n\`\`\``);+ expect(capsuleCount(html)).toBe(0);+ expect(html).toContain("co_research_paper_lab/workspace/exp/");+ });++ it("keeps a link's label as text", () => {+ const html = render(`[${LAB}/workspace/exp/](https://example.test)`);+ expect(capsuleCount(html)).toBe(0);+ });++ it("finds paths inside list items and emphasis", () => {+ const html = render(`- **Data**: ${LAB}/workspace/data/\n- ${LAB}/workspace/b.csv`);+ expect(html).toContain(">data</span></button>");+ expect(html).toContain(">b.csv</span></button>");+ });++ it("leaves a path the parser split with emphasis whole as text rather than capsuling part of it", () => {+ const html = render(`${LAB}/workspace/src/__init__.py`);+ expect(capsuleCount(html)).toBe(0);+ });++ it("copies a Windows path in prose as written, though Markdown takes its `\\.` for an escape", () => {+ const report = String.raw`${WIN_LAB}\workspace\report.md`;+ const html = render(`结果在 ${report}。`);+ expect(capsuleCount(html)).toBe(1);+ expect(html).toContain(">report.md</span></button>");+ expect(html).toContain(`aria-label="${attr(S.company.pathCapsule.copy(report))}"`);+ expect(html).toContain("。");+ });++ it("copies a Windows path in a code span verbatim", () => {+ const desk = String.raw`${WIN_LAB}\workspace\exp` + "\\";+ const html = render(`Runs: \`${desk}\``);+ expect(capsuleCount(html)).toBe(1);+ expect(html).toContain(">exp</span></button>");+ expect(html).toContain(`aria-label="${attr(S.company.pathCapsule.copy(desk))}"`);+ });++ it("copies a path written with / as the text reads, without the source's escapes", () => {+ const html = render(String.raw`See ${LAB}/workspace/my\_notes/ now`);+ expect(capsuleCount(html)).toBe(1);+ const copied = S.company.pathCapsule.copy(`${LAB}/workspace/my_notes/`);+ expect(html).toContain(`aria-label="${attr(copied)}"`);+ });+});++describe("plain text with capsules", () => {+ it("draws the paths in a blocked reason and keeps the words around them", () => {+ const html = renderToStaticMarkup(+ createElement(PathText, { text: `等待 ${LAB}/workspace/gpu.lock 释放`, scope }),+ );+ expect(html).toContain("等待 ");+ expect(html).toContain(">gpu.lock</span></button>");+ expect(html).toContain(" 释放");+ });+});