Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): improve ref rendering and agent guidance

Guse130ce746c45
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index 4f778db28..8d5e913fd 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -46,7 +46,9 @@ function identitySection(config: LaunchConfig): string {
"",
`Every Alook account is \`name#NNNN\`. Yours is \`${config.agentHandle}\`. ` +
"Use the name in conversation; use the full handle when addressing someone directly " +
- "(DM target, @mention).",
+ "(DM target, @mention). Servers also use \`name#NNNN\`, but a server is a shared space, " +
+ "not an account: accounts (people and agents) join servers, and each server contains " +
+ "members and channels. One account can belong to multiple servers.",
);
}
@@ -202,7 +204,7 @@ function messagingSection(): string {
"Use the `channel` field from a received message as `--target`. For an in-thread reply, use " +
"the thread-ref grammar described above.",
"",
- "Copyable refs must be standalone bare tokens. Examples:",
+ "Copyable ref examples:",
"/Alook#1234/chore",
"/Alook#1234/chore#28",
"/Alook#1234/chore/#28",
@@ -224,10 +226,9 @@ function messagingSection(): string {
"### Message formatting",
"",
"The app auto-renders inline tokens in a message body — channel refs, @mentions, and message " +
- "refs. Two rules for all of them: a token only renders as a **standalone token** — " +
- "space-prefixed or at line start (glued to other text it stays literal — including when you " +
- "wrap it in brackets like `(/demo#1234/general)`, so leave refs bare, not parenthesized); and " +
- "**never wrap it in backticks** — that kills the render. Otherwise write them as bare text.",
+ "refs. Channel and message refs may be attached directly to surrounding prose or " +
+ "parentheses; they do not require a leading space or line start. Keep @mentions as " +
+ "standalone tokens. **Never wrap refs or mentions in backticks** — that kills the render.",
"",
"- **Channel refs** render as clickable links.",
"- **Mentions** — `@name#NNNN` (e.g. `@alice#0001`) notifies that person and highlights the " +
@@ -260,6 +261,33 @@ function messagingSection(): string {
"combine into `/<server>/<channel>/#N` for an in-thread reply.",
"`content.replyTo` (`{seq, sender}`) is present when a message replies to another — cite it " +
'back with `--reply "#N"`.',
+ "`hint` is present when the containing surface changes how you should act. Follow it.",
+ ].join("\n");
+}
+
+function channelTypesSection(): string {
+ return [
+ "## Channel types",
+ "",
+ "`channel list` marks each top-level channel as `text` or `forum`. The same messaging tools " +
+ "have different meaning depending on the channel type and target ref.",
+ "",
+ "### Text channels",
+ "",
+ "- A text channel is a linear conversation. Send directly to its ref with `message send --target " +
+ "/<server>/<channel>`.",
+ "- A text-channel message may have a side thread at `/<server>/<channel>/#N`. Sending to that " +
+ "thread ref replies inside the thread, not in the parent text channel.",
+ "",
+ "### Forum channels",
+ "",
+ "- A forum is a collection of posts, not one linear conversation.",
+ "- Each top-level message in a forum is a post title. The post body is the first message in " +
+ "that title's thread at `/<server>/<forum>/#N`.",
+ "- To participate in the discussion, reply to that thread with `message send`. Inside the " +
+ "thread, messaging works like a normal text channel.",
+ "- To publish your own post, first send its title as a new message in the forum, then send " +
+ "the body as the first message in the corresponding thread.",
].join("\n");
}
@@ -504,6 +532,7 @@ export function buildCliSystemPrompt(config: LaunchConfig): string {
identitySection(config),
cliCommandsSection(),
messagingSection(),
+ channelTypesSection(),
visibilityAndReachSection(),
criticalRulesSection(),
executionModelSection(),
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 7e944f32a..478e23e30 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -159,6 +159,9 @@ export type Target =
* - `content` — `{ text }` today; an object (not a bare string) so future
* content kinds (attachments, embeds, …) can be added without
* breaking the shape.
+ * - `hint` — optional action guidance when the containing surface needs a
+ * different write target, such as moving from a forum title
+ * message into its discussion thread.
* - `time` — ISO-8601 timestamp.
* No `id`, no `type`.
*/
@@ -230,6 +233,8 @@ export interface Message {
/** Sender global handle (`name#0042`), e.g. "@gustavo#4821". */
sender: string;
content: MessageContent;
+ /** Read-side action guidance for the message's containing surface. */
+ hint?: string;
/** ISO-8601. */
time: string;
}
diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.ts
index 333ef5ffd..6cecd1c02 100644
--- a/src/shared/src/db/queries/community/agent-inbox.ts
+++ b/src/shared/src/db/queries/community/agent-inbox.ts
@@ -60,7 +60,12 @@ const AGENT_MESSAGE_COLUMNS = {
} as const;
/** One entry per distinct channel needing a `ChannelRef`. */
-type ScopeInfo = { ref: string; isThread: boolean; isDm: boolean };
+type ScopeInfo = {
+ ref: string;
+ isThread: boolean;
+ isDm: boolean;
+ isForum: boolean;
+};
/**
* Batch-resolve a set of channel ids into their `ChannelRef` path strings —
@@ -225,6 +230,7 @@ async function resolveScopeRefs(
ref,
isThread: emitType === "thread",
isDm,
+ isForum: storedType === "forum",
});
}
return out;
@@ -280,11 +286,17 @@ export async function toAgentMessages(
if (atts && atts.length > 0) content.attachments = atts;
const replyTo = r.replyToId ? replyByMessageId.get(r.replyToId) : undefined;
if (replyTo) content.replyTo = replyTo;
+ const forumReplyRef = scope.isForum ? `${channel}/${formatSeq(r.seq)}` : null;
return {
seq: formatSeq(r.seq),
channel,
sender,
content,
+ ...(forumReplyRef
+ ? {
+ hint: `This is a forum post, please reply in ${forumReplyRef}.`,
+ }
+ : {}),
time: r.createdAt,
};
});
diff --git a/src/shared/test/queries/community-agent-inbox.test.ts b/src/shared/test/queries/community-agent-inbox.test.ts
index 9801d2c57..e54defd44 100644
--- a/src/shared/test/queries/community-agent-inbox.test.ts
+++ b/src/shared/test/queries/community-agent-inbox.test.ts
@@ -93,7 +93,7 @@ describe("toAgentMessages", () => {
const db = createSequentialDb([
[{ id: "thread_1", name: "thread-x", serverId: "srv_1", parentChannelId: "ch_parent", parentMessageId: "m_root" }],
[{ id: "u_1", name: "Alice" }],
- [{ id: "ch_parent", name: "general" }],
+ [{ id: "ch_parent", name: "general", type: "text" }],
[{ id: "srv_1", name: "studio", discriminator: "0042" }],
[{ id: "m_root", seq: 7 }],
]);
@@ -103,6 +103,45 @@ describe("toAgentMessages", () => {
"viewer_1"
);
expect(msg!.channel).toBe(formatRef({ server: "studio#0042", channel: "general", threadRootSeq: 7 }));
+ expect(msg!.hint).toBeUndefined();
+ });
+
+ it("marks each top-level forum message with its lazy-created thread reply target", async () => {
+ const db = createSequentialDb([
+ [{ id: "forum_1", name: "ideas", type: "forum", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],
+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],
+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],
+ ]);
+ const [first, second] = await agentInbox.toAgentMessages(
+ db,
+ [
+ rawMsg({ id: "m_first", channelId: "forum_1", seq: 12 }),
+ rawMsg({ id: "m_second", channelId: "forum_1", seq: 13 }),
+ ],
+ "viewer_1"
+ );
+ expect(first).toMatchObject({
+ channel: "/studio#0042/ideas",
+ hint: "This is a forum post, please reply in /studio#0042/ideas/#12.",
+ });
+ expect(second).toMatchObject({
+ channel: "/studio#0042/ideas",
+ seq: "#13",
+ hint: "This is a forum post, please reply in /studio#0042/ideas/#13.",
+ });
+ });
+
+ it("treats a forum post thread as an ordinary thread with no extra hint", async () => {
+ const db = createSequentialDb([
+ [{ id: "post_1", name: "post-x", type: "thread", serverId: "srv_1", parentChannelId: "forum_1", parentMessageId: "m_root" }],
+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],
+ [{ id: "forum_1", name: "ideas", type: "forum" }],
+ [{ id: "srv_1", name: "studio", discriminator: "0042" }],
+ [{ id: "m_root", seq: 12 }],
+ ]);
+ const [msg] = await agentInbox.toAgentMessages(db, [rawMsg({ channelId: "post_1" })], "viewer_1");
+ expect(msg!.channel).toBe("/studio#0042/ideas/#12");
+ expect(msg!.hint).toBeUndefined();
});
it("hydrates a DM message, addressing the OTHER party (as a name#0042 handle) relative to viewerId", async () => {
@@ -124,6 +163,7 @@ describe("toAgentMessages", () => {
"viewer_1"
);
expect(msg!.channel).toBe(formatRef({ server: DM_SERVER, channel: "Bob#9999" }));
+ expect(msg!.hint).toBeUndefined();
});
it("fails the whole delivery without leaking an id when the scope can't be resolved", async () => {
diff --git a/src/web/src/components/community/channel-ref-pill.test.ts b/src/web/src/components/community/channel-ref-pill.test.ts
index e6ee8b9aa..64b4fb4aa 100644
--- a/src/web/src/components/community/channel-ref-pill.test.ts
+++ b/src/web/src/components/community/channel-ref-pill.test.ts
@@ -1,5 +1,8 @@
+import { createElement } from "react"
+import { renderToStaticMarkup } from "react-dom/server"
import { describe, it, expect } from "vitest"
import { describeChannelRefPillView } from "./channel-ref-pill"
+import { ChannelPill } from "./inline-marks"
import type { ResolvedChannelRef } from "@/lib/community/channel-ref"
const server = { id: "srv_1", name: "Studio" }
@@ -10,33 +13,30 @@ function resolved(overrides: Partial<ResolvedChannelRef> = {}): ResolvedChannelR
}
describe("describeChannelRefPillView", () => {
- it("resolved: null, directoryLoading: true → muted", () => {
+ it("resolved: null → muted", () => {
const view = describeChannelRefPillView({
ref: "/srv_1/chn_1",
resolved: null,
- directoryLoading: true,
thread: null,
currentServerId: "srv_1",
})
- expect(view).toEqual({ kind: "muted", label: "/srv_1/chn_1" })
+ expect(view).toEqual({ kind: "muted", label: "/srv_1/chn_1", showIcon: false })
})
- it("resolved: null, directoryLoading: false → plain with text equal to the original ref", () => {
+ it("resolved: null keeps the original ref as its muted label", () => {
const view = describeChannelRefPillView({
- ref: "/usr/bin/ls",
+ ref: "/studio#0042/general#42",
resolved: null,
- directoryLoading: false,
thread: null,
currentServerId: "srv_1",
})
- expect(view).toEqual({ kind: "plain", text: "/usr/bin/ls" })
+ expect(view).toEqual({ kind: "muted", label: "/studio#0042/general#42", showIcon: false })
})
it("resolved present, no threadRootSeq → pill, no serverPrefix when resolved.server.id === currentServerId", () => {
const view = describeChannelRefPillView({
ref: "/srv_1/chn_1",
resolved: resolved(),
- directoryLoading: false,
thread: null,
currentServerId: "srv_1",
})
@@ -56,7 +56,6 @@ describe("describeChannelRefPillView", () => {
const view = describeChannelRefPillView({
ref: "/srv_1/chn_1#42",
resolved: resolved({ seq: 42 }),
- directoryLoading: false,
thread: null,
currentServerId: "srv_1",
})
@@ -73,7 +72,6 @@ describe("describeChannelRefPillView", () => {
const view = describeChannelRefPillView({
ref: "/srv_1/chn_1",
resolved: resolved(),
- directoryLoading: false,
thread: null,
currentServerId: "srv_other",
})
@@ -89,7 +87,6 @@ describe("describeChannelRefPillView", () => {
const view = describeChannelRefPillView({
ref: "/srv_1/chn_1/#42",
resolved: resolved({ threadRootSeq: 42 }),
- directoryLoading: false,
thread: undefined,
currentServerId: "srv_1",
})
@@ -100,7 +97,6 @@ describe("describeChannelRefPillView", () => {
const view = describeChannelRefPillView({
ref: "/srv_1/chn_1/#42",
resolved: resolved({ threadRootSeq: 42 }),
- directoryLoading: false,
thread: { id: "thr_1", name: "Thread about X", parentSeq: 42 },
currentServerId: "srv_1",
})
@@ -116,7 +112,6 @@ describe("describeChannelRefPillView", () => {
const view = describeChannelRefPillView({
ref: "/srv_1/chn_1/#42",
resolved: resolved({ threadRootSeq: 42 }),
- directoryLoading: false,
thread: null,
currentServerId: "srv_1",
})
@@ -133,7 +128,6 @@ describe("describeChannelRefPillView", () => {
const view = describeChannelRefPillView({
ref: "/srv_1/chn_1/#42",
resolved: resolved({ threadRootSeq: 42 }),
- directoryLoading: false,
thread: null,
currentServerId: "srv_other",
})
@@ -146,7 +140,6 @@ describe("describeChannelRefPillView", () => {
const view = describeChannelRefPillView({
ref: "/srv_1/chn_1/#42",
resolved: resolved({ threadRootSeq: 42 }),
- directoryLoading: false,
thread: { id: "thr_1", name: "Thread about X", parentSeq: 42 },
currentServerId: "srv_1",
})
@@ -157,7 +150,6 @@ describe("describeChannelRefPillView", () => {
const view = describeChannelRefPillView({
ref: "/srv_1/chn_1/#5#42",
resolved: resolved({ threadRootSeq: 5, seq: 42 }),
- directoryLoading: false,
thread: { id: "thr_1", name: "Thread about X", parentSeq: 5 },
currentServerId: "srv_1",
})
@@ -174,7 +166,6 @@ describe("describeChannelRefPillView", () => {
const view = describeChannelRefPillView({
ref: "/srv_1/chn_1/#5#42",
resolved: resolved({ threadRootSeq: 5, seq: 42 }),
- directoryLoading: false,
thread: null,
currentServerId: "srv_1",
})
@@ -188,3 +179,16 @@ describe("describeChannelRefPillView", () => {
})
})
})
+
+describe("ChannelPill icon", () => {
+ it("shows the channel icon by default", () => {
+ const html = renderToStaticMarkup(createElement(ChannelPill, { muted: true }, "general"))
+ expect(html).toContain("<svg")
+ })
+
+ it("omits the channel icon when showIcon is false", () => {
+ const html = renderToStaticMarkup(createElement(ChannelPill, { muted: true, showIcon: false }, "/missing#0042/general"))
+ expect(html).not.toContain("<svg")
+ expect(html).toContain("/missing#0042/general")
+ })
+})
diff --git a/src/web/src/components/community/channel-ref-pill.tsx b/src/web/src/components/community/channel-ref-pill.tsx
index 1695a3524..92ddc69c8 100644
--- a/src/web/src/components/community/channel-ref-pill.tsx
+++ b/src/web/src/components/community/channel-ref-pill.tsx
@@ -10,8 +10,7 @@ import { useCommunityStore, useUiHandlers } from "@/stores/community"
import { tid } from "@/lib/community/testids"
export type ChannelRefPillView =
- | { kind: "plain"; text: string }
- | { kind: "muted"; label: string }
+ | { kind: "muted"; label: string; showIcon?: boolean }
| {
kind: "pill"
label: string
@@ -40,8 +39,9 @@ export type ChannelRefPillView =
*
* Decision table:
* - `resolved === null` (still loading OR genuinely unresolved) →
- * `directoryLoading ? "muted" : "plain"` (plain text = `ref`, untouched
- * fallback — never a broken-looking pill).
+ * `"muted"`, labelled with the raw ref and without a channel icon. The tokenizer only calls this
+ * component for discriminator-bearing channel/message-ref syntax, so a
+ * syntactic match remains visibly rendered even when its target is unknown.
* - `resolved` present, no `threadRootSeq` → `"pill"`, label =
* `resolved.channel.name`, `serverPrefix` set only when the ref points at
* a different server than the one currently open.
@@ -57,14 +57,13 @@ export type ChannelRefPillView =
export function describeChannelRefPillView(args: {
ref: string
resolved: ResolvedChannelRef | null
- directoryLoading: boolean
thread: { id: string; name: string; parentSeq?: number } | null | undefined
currentServerId: string | null
}): ChannelRefPillView {
- const { ref, resolved, directoryLoading, thread, currentServerId } = args
+ const { ref, resolved, thread, currentServerId } = args
if (!resolved) {
- return directoryLoading ? { kind: "muted", label: ref } : { kind: "plain", text: ref }
+ return { kind: "muted", label: ref, showIcon: false }
}
const serverPrefix = resolved.server.id !== currentServerId ? resolved.server.name : undefined
@@ -123,7 +122,7 @@ export function ChannelRefPill({ children }: { children?: React.ReactNode }) {
const currentServerId = useCommunityStore((s) => s.currentServerId)
const currentChannelId = useCommunityStore((s) => s.currentChannelId)
const uiHandlers = useUiHandlers()
- const { directory, isLoading: directoryLoading } = useChannelRefDirectory()
+ const { directory } = useChannelRefDirectory()
// The debt record's own verification (see finding #6) confirmed the
// network requests behind `useChannelRefDirectory`/`useThreads` already
@@ -142,13 +141,11 @@ export function ChannelRefPill({ children }: { children?: React.ReactNode }) {
const view = describeChannelRefPillView({
ref,
resolved,
- directoryLoading,
thread,
currentServerId,
})
- if (view.kind === "plain") return <>{view.text}</>
- if (view.kind === "muted") return <ChannelPill muted>{view.label}</ChannelPill>
+ if (view.kind === "muted") return <ChannelPill muted showIcon={view.showIcon}>{view.label}</ChannelPill>
// Click intent depends on what the ref points at (Gus #417):
// - A MESSAGE ref (`#N`) means "see that message's context", NOT "go to that
diff --git a/src/web/src/components/community/inline-marks.tsx b/src/web/src/components/community/inline-marks.tsx
index 774191a75..b358dc827 100644
--- a/src/web/src/components/community/inline-marks.tsx
+++ b/src/web/src/components/community/inline-marks.tsx
@@ -58,12 +58,14 @@ export function MentionPill({
// (rendered as a `<button>` when present, a `<span>` otherwise — same
// on/off pattern as `MentionPill`). `serverPrefix` renders a small
// "prefix /" segment before the name for cross-server refs. `muted` dims
-// the pill for the "still resolving" state (see `channel-ref-pill.tsx`).
+// the pill while loading or when syntax matched without a resolved target;
+// `showIcon` lets that unresolved state avoid implying a verified channel.
export function ChannelPill({
children,
onClick,
serverPrefix,
muted,
+ showIcon = true,
seqSuffix,
testId,
}: {
@@ -71,6 +73,7 @@ export function ChannelPill({
onClick?: (e: React.MouseEvent) => void
serverPrefix?: string
muted?: boolean
+ showIcon?: boolean
testId?: string
// A message ref (`/server/channel#N`): render the whole thing as ONE pill —
// channel name + `#N` inside — with a leading `#` glyph (instead of the `/`
@@ -89,9 +92,9 @@ export function ChannelPill({
].join(" ")
const content = (
<>
- {/* Always the channel glyph — a message ref still points AT a channel;
- the `#N` inside marks it as a specific message (Gus #370). */}
- <ChannelIcon className="shrink-0 text-xs" />
+ {/* Resolved and loading refs keep the channel glyph — a message ref still
+ points AT a channel, while a syntactic-only unresolved ref hides it. */}
+ {showIcon && <ChannelIcon className="shrink-0 text-xs" />}
{serverPrefix && (
<span className="shrink-0 text-muted-foreground transition-colors group-hover/pill:text-primary">{serverPrefix} /</span>
)}
diff --git a/src/web/src/lib/community/channel-ref.ts b/src/web/src/lib/community/channel-ref.ts
index aad23971a..1adb8116f 100644
--- a/src/web/src/lib/community/channel-ref.ts
+++ b/src/web/src/lib/community/channel-ref.ts
@@ -33,8 +33,8 @@ export type ResolvedChannelRef = {
* server for UI-internal navigation.
*
* Returns `null` on any miss (unknown server, unknown channel, or malformed
- * ref) — this is the false-positive guard the caller (`describeChannelRefPillView`)
- * relies on to fall back to plain text instead of rendering a broken pill.
+ * ref), preventing the caller from inventing a clickable target. Syntactically
+ * matched refs still render as muted pills while unresolved.
*/
export function resolveChannelRefBase(
directory: ChannelRefDirectory,
diff --git a/src/web/src/lib/community/chat-syntax-plugin.test.ts b/src/web/src/lib/community/chat-syntax-plugin.test.ts
index 0e6906989..0ba2e5cdd 100644
--- a/src/web/src/lib/community/chat-syntax-plugin.test.ts
+++ b/src/web/src/lib/community/chat-syntax-plugin.test.ts
@@ -126,15 +126,12 @@ describe("chatSyntaxPlugin — mention", () => {
})
describe("chatSyntaxPlugin — channelRef", () => {
- it("wraps /server/channel preceded by a space or at start-of-string", () => {
+ it("wraps /server/channel after prose, a space, or at start-of-string", () => {
expect(paragraphChildren(parse("see /studio#0042/general"))[1]).toMatchObject({ type: "channelRef", value: "/studio#0042/general" })
expect(paragraphChildren(parse("/studio#0042/general"))[0]).toMatchObject({ type: "channelRef", value: "/studio#0042/general" })
- })
-
- it("leaves text/studio#0042/general (no leading space) untouched", () => {
const children = paragraphChildren(parse("text/studio#0042/general"))
- expect(children).toHaveLength(1)
- expect(children[0]).toMatchObject({ type: "text", value: "text/studio#0042/general" })
+ expect(children.map((child) => child.type)).toEqual(["text", "channelRef"])
+ expect(children[1]).toMatchObject({ type: "channelRef", value: "/studio#0042/general" })
})
it("does NOT wrap a 3+-segment docs-style path — trailing /segment fails the terminator boundary", () => {
@@ -142,6 +139,29 @@ describe("chatSyntaxPlugin — channelRef", () => {
expect(paragraphChildren(parse("hit /docs/api/v1 first"))).toHaveLength(1)
})
+ it("does not restart a ref match at the second slash inside a path or URL", () => {
+ for (const text of [
+ "/api/studio#0042/general",
+ "/api/studio#0042/general/#5#42",
+ "https://studio#0042/general",
+ "//studio#0042/general",
+ ]) {
+ const children = paragraphChildren(parse(text))
+ expect(children.some((child) => child.type === "channelRef"), text).toBe(false)
+ }
+ })
+
+ it("still starts after non-slash prose and opening brackets", () => {
+ expect(paragraphChildren(parse("prefix/studio#0042/general"))[1]).toMatchObject({
+ type: "channelRef",
+ value: "/studio#0042/general",
+ })
+ expect(paragraphChildren(parse("see(/studio#0042/general)"))[1]).toMatchObject({
+ type: "channelRef",
+ value: "/studio#0042/general",
+ })
+ })
+
it("still wraps a 2-segment ref followed by punctuation (period, comma, close-paren)", () => {
const children = paragraphChildren(parse("see /studio#0042/general."))
expect(children.map((c) => c.type)).toEqual(["text", "channelRef", "text"])
@@ -172,13 +192,31 @@ describe("chatSyntaxPlugin — channelRef", () => {
expect(refs[0]).toMatchObject({ type: "channelRef", value: "/studio#0042/general#42" })
})
- it("does not wrap a mid-string path as a channelRef, and a bare #N is now plain text", () => {
- // The channelRef pass requires a leading space, so `text/.../#5#42` is NOT a
- // channelRef. And a bare `#42` is no longer a message ref (message-ref-
- // upgrade.md), so nothing pills — the whole run is plain text.
+ it("wraps a thread-message ref attached to prose while a bare #N stays plain text", () => {
const children = paragraphChildren(parse("text/studio#0042/general/#5#42"))
- expect(children.some((c) => c.type === "channelRef")).toBe(false)
- expect(children.every((c) => c.type === "text")).toBe(true)
+ expect(children.map((child) => child.type)).toEqual(["text", "channelRef"])
+ expect(children[1]).toMatchObject({ type: "channelRef", value: "/studio#0042/general/#5#42" })
+ })
+
+ it("wraps refs inside ASCII and full-width brackets without consuming the brackets", () => {
+ const ascii = paragraphChildren(parse("see(/studio#0042/general#42)"))
+ expect(ascii.map((child) => child.type)).toEqual(["text", "channelRef", "text"])
+ expect(ascii[1]).toMatchObject({ value: "/studio#0042/general#42" })
+ expect(ascii[2]).toMatchObject({ type: "text", value: ")" })
+
+ const cjk = paragraphChildren(parse("(/Gus#5994/架构/#722#17)"))
+ expect(cjk.map((child) => child.type)).toEqual(["text", "channelRef", "text"])
+ expect(cjk[0]).toMatchObject({ type: "text", value: "(" })
+ expect(cjk[1]).toMatchObject({ value: "/Gus#5994/架构/#722#17" })
+ expect(cjk[2]).toMatchObject({ type: "text", value: ")" })
+ })
+
+ it("wraps each ref when adjacent refs are separated only by punctuation", () => {
+ const children = paragraphChildren(parse("see(/studio#0042/general#42)、(/Gus#5994/架构/#722#17)"))
+ const refs = children.filter((child) => child.type === "channelRef")
+ expect(refs).toHaveLength(2)
+ expect(refs[0]).toMatchObject({ value: "/studio#0042/general#42" })
+ expect(refs[1]).toMatchObject({ value: "/Gus#5994/架构/#722#17" })
})
it("leaves a channel-ref-shaped path inside inline code literal", () => {
diff --git a/src/web/src/lib/community/chat-syntax-plugin.ts b/src/web/src/lib/community/chat-syntax-plugin.ts
index 66e07fffc..c8bf38f76 100644
--- a/src/web/src/lib/community/chat-syntax-plugin.ts
+++ b/src/web/src/lib/community/chat-syntax-plugin.ts
@@ -57,14 +57,15 @@ import type { SpoilerNode } from "./spoiler-syntax"
// Trailing `(?=\s|$|[REF_TERM])` boundary lookahead: a 2-segment path followed
// by ANOTHER `/segment` (e.g. `/api/user/123` in a docs URL) must NOT match —
// otherwise this regex would greedily take `/api/user` and orphan `/123` as
-// trailing text next to a broken pill. Leading `(?<=^|\s)` lookbehind
-// (verified empirically — a bare leading `\/` with no lookbehind would let
-// this match START mid-path, e.g. matching `/user/123` inside
-// `/api/user/123`): `" /channel-ref"` matches, `"text/channel-ref"` doesn't.
-// Both boundaries are zero-width lookaround (not capture groups) so
-// `findAndReplace` doesn't need to redistribute a leading/trailing text node
-// around the match the way the old string-splice regex's `(^|\s)` capture
-// group did. `u` flag for correct astral/emoji handling.
+// trailing text next to a broken pill. The leading guard permits a
+// discriminator-bearing ref after prose or an opening bracket, e.g.
+// `see(/Gus#5994/架构/#722#17)` and `text/Gus#5994/架构`, while preventing the
+// regex engine from restarting after an earlier slash in the same unbroken
+// path or URL (`/api/Gus#5994/架构`, `https://Gus#5994/架构`). Ref terminators
+// stop that backward scan so a second adjacent ref after punctuation still
+// matches. The trailing boundary
+// remains load-bearing so the match still ends at the exact ref. `u` flag for
+// correct astral/emoji handling.
const REF_TERM = ".,;:!?)\\]\\u3002\\uFF01\\uFF1F\\uFF1B\\uFF1A\\u3001\\uFF09\\u3011"
const REF_SEG = `[^\\s/#${REF_TERM}]+`
const HANDLE_SEG = `${REF_SEG}#\\d{4,}`
@@ -77,14 +78,15 @@ const HANDLE_SEG = `${REF_SEG}#\\d{4,}`
// (`/server#disc/channel/#N#M`) ref; the inner `#M` lives only
// on this slash branch.
// `REF_SEG` excludes `#`, so the 2nd segment stops at the `#` and the seq falls
-// cleanly into the suffix group. The leading `(?<=^|\s)` prefix-anchor means this
-// only ever matches a full path — never a bare `#` — which is what lets us drop
-// the old bare-`#N` MESSAGE_REF pass and root-solve the disambiguation Gus flagged.
-const CHANNEL_REF_RE = new RegExp(`(?<=^|\\s)(?:/${HANDLE_SEG}/${REF_SEG}|/\\.dm/${HANDLE_SEG})(?:#\\d+|/#\\d+(?:#\\d+)?)?(?=\\s|$|[${REF_TERM}])`, "gu")
-
-// A bare `/server` ref — one segment, no channel. Same boundary lookaround as
-// `CHANNEL_REF_RE` (leading `(?<=^|\s)`, trailing `REF_TERM`), which already
-// excludes being followed by another `/segment` — so this never double-matches
+// cleanly into the suffix group. The discriminator-bearing full path — never a
+// bare `#` — is what lets us drop the old bare-`#N` MESSAGE_REF pass and
+// root-solve the disambiguation Gus flagged.
+const CHANNEL_REF_RE = new RegExp(`(?<!/[^\\s${REF_TERM}]*)(?:/${HANDLE_SEG}/${REF_SEG}|/\\.dm/${HANDLE_SEG})(?:#\\d+|/#\\d+(?:#\\d+)?)?(?=\\s|$|[${REF_TERM}])`, "gu")
+
+// A bare `/server` ref — one segment, no channel. Unlike `CHANNEL_REF_RE`, this
+// intentionally keeps its leading `(?<=^|\s)` boundary; the current change is
+// scoped to channel/message refs. Its trailing `REF_TERM` boundary excludes
+// being followed by another `/segment` — so this never double-matches
// the first segment of a genuine `/server#disc/channel` ref (that trailing boundary
// fails when the next char is `/`, and the segment class backtracking can't
// produce a shorter match that satisfies it either, since every character up