Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): make forum posts addressable by agents (name-anchor ref)

Simone2cd8538e96ca
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index bb5576c32..b3076174a 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -660,6 +660,23 @@ describe("message emoji", () => {
expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/.dm/peer#0001", seq: 7, emoji: "πŸ™" });
});
+ it("forum-post ref β€” reacts to a message INSIDE the post (childChannelName kept, not the parent forum)", async () => {
+ const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));
+ setApiForTesting(stubApi({ reactAdd: reactAddSpy }));
+ await main(["message", "emoji", "--target", "/demo/ideas/my-post#4", "--emoji", "πŸ‘"]);
+ // channel is the POST scope (/demo/ideas/my-post), NOT the parent forum /demo/ideas.
+ expect(reactAddSpy).toHaveBeenCalledWith({ channel: "/demo/ideas/my-post", seq: 4, emoji: "πŸ‘" });
+ });
+
+ it("forum-post ref without a message seq β†’ error, reactAdd never called", async () => {
+ const reactAddSpy = vi.fn(async () => ({ ok: true as const, duplicate: false }));
+ setApiForTesting(stubApi({ reactAdd: reactAddSpy }));
+ await main(["message", "emoji", "--target", "/demo/ideas/my-post", "--emoji", "πŸ‘"]);
+ const env = parseEnvelope(cap.lines());
+ expect(env.error).toMatch(/needs a ref with a seq/);
+ expect(reactAddSpy).not.toHaveBeenCalled();
+ });
+
it("proxy error surfaces .hint alongside .error and reactAdd throws propagate", async () => {
setApiForTesting(
stubApi({
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index a88f9bb03..d3ed0a32c 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -230,10 +230,15 @@ async function cmdMessageEmoji(opts: Record<string, unknown>): Promise<unknown>
throw err;
}
+ // Rebuild the SCOPE ref (no pin-seq β€” that's passed separately as `seq`).
+ // A forum-post target (`/server/forum/post#N`) must keep its childChannelName
+ // so the reaction lands on the post, not its parent forum.
const channel =
- parsed.threadRootSeq !== undefined
- ? `/${parsed.server}/${parsed.channel}/#${parsed.threadRootSeq}`
- : `/${parsed.server}/${parsed.channel}`;
+ parsed.childChannelName !== undefined
+ ? `/${parsed.server}/${parsed.channel}/${parsed.childChannelName}`
+ : parsed.threadRootSeq !== undefined
+ ? `/${parsed.server}/${parsed.channel}/#${parsed.threadRootSeq}`
+ : `/${parsed.server}/${parsed.channel}`;
const res = await api.reactAdd({ channel, seq: parsed.seq, emoji });
return { target, emoji, duplicate: res.duplicate === true };
}
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 7ac10d0bb..8919d06f6 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -981,6 +981,16 @@ export interface ParsedRef {
server: string;
/** Channel name (or DM peer when `server === DM_SERVER`). */
channel: string;
+ /**
+ * Forum-post child-channel name when the ref addresses a forum post
+ * (`/server/forum/post`). A forum post is a `forum_post` child channel with
+ * no addressable root-message seq (unlike a thread), so it is anchored by its
+ * OWN name under the parent forum β€” `channel` is the forum, `childChannelName`
+ * is the post. May carry a `seq` (`/server/forum/post#N`) to pin a message
+ * inside the post, symmetric to the top-level `/server/channel#N` form.
+ * Mutually exclusive with `threadRootSeq`.
+ */
+ childChannelName?: string;
/** Thread root seq when the ref points into a thread (`/server/channel/#N`). */
threadRootSeq?: Seq;
/** Message seq when the ref pins a specific message (`/server/channel#N`). */
@@ -991,6 +1001,7 @@ export interface ParsedRef {
* Parse a path ref into its parts. Grammar:
* /<server>/<channel> β†’ { server, channel }
* /<server>/<channel>#N β†’ { server, channel, seq:N }
+ * /<server>/<forum>/<post> β†’ { server, channel:forum, childChannelName:post }
* /<server>/<channel>/#N β†’ { server, channel, threadRootSeq:N }
* /<server>/<channel>/#N#M β†’ { server, channel, threadRootSeq:N, seq:M }
* /.dm/<peer>[...] β†’ DM (server = ".dm", channel = peer, a
@@ -1016,6 +1027,28 @@ export function parseRef(ref: ChannelRef): ParsedRef {
const tail = parseThreadTail(parts[parts.length - 1]);
return { server, channel: parts[1], ...tail };
}
+
+ // Forum-post form: /server/forum/post β€” exactly 3 segments, third NOT
+ // starting with "#" (that's the thread form above). The post is anchored by
+ // its own name under the parent forum. An optional trailing "#N" pins a
+ // message seq WITHIN the post (`/server/forum/post#N`), symmetric to the
+ // top-level message form `/server/channel#N` β€” used by `message emoji` to
+ // react to a specific message inside a post. A 4th path segment is not
+ // addressable today β€” reject rather than silently truncate.
+ if (parts.length >= 3 && server !== DM_SERVER) {
+ if (parts.length > 3) {
+ throw new Error(`ref has too many segments: ${ref}`);
+ }
+ const postSeg = parts[2];
+ const hashIdx = postSeg.indexOf("#");
+ if (hashIdx >= 0) {
+ const postName = postSeg.slice(0, hashIdx);
+ if (!postName) throw new Error(`forum-post ref missing post name: ${ref}`);
+ return { server, channel: parts[1], childChannelName: postName, seq: parseSeq(postSeg.slice(hashIdx)) };
+ }
+ return { server, channel: parts[1], childChannelName: postSeg };
+ }
+
const chSeg = parts[1];
// DM-specific branch: a DM peer segment is a `name#0042` handle, not a bare
@@ -1082,22 +1115,35 @@ function parseThreadTail(segment: string): { threadRootSeq: Seq; seq?: Seq } {
/**
* Format a ParsedRef back to a path ref. Valid combinations:
* {} β†’ /server/channel
+ * { childChannelName } β†’ /server/channel/childChannelName (forum post)
+ * { childChannelName, seq } β†’ /server/channel/childChannelName#N (msg in a post)
* { threadRootSeq } β†’ /server/channel/#N
* { threadRootSeq, seq } β†’ /server/channel/#N#M
- * A bare `seq` (no `threadRootSeq`) is NOT supported β€” the message form
- * `/server/channel#N` puts `#N` on the channel segment, not on a trailing
- * path segment, and no caller needs to emit that shape via formatRef today.
+ * A bare `seq` (neither `threadRootSeq` nor `childChannelName`) is NOT
+ * supported β€” the top-level message form `/server/channel#N` puts `#N` on the
+ * channel segment, not on a trailing path segment, and no caller needs to emit
+ * that shape via formatRef today. `childChannelName` (forum post) is mutually
+ * exclusive with `threadRootSeq`, but MAY carry a `seq` to pin a message inside
+ * the post (`/server/forum/post#N`), symmetric to the top-level message form.
*/
export function formatRef(p: {
server: string;
channel: string;
+ childChannelName?: string;
threadRootSeq?: Seq;
seq?: Seq;
}): ChannelRef {
- if (p.seq !== undefined && p.threadRootSeq === undefined) {
- throw new Error("formatRef: seq without threadRootSeq is not supported");
+ if (p.childChannelName !== undefined && p.threadRootSeq !== undefined) {
+ throw new Error("formatRef: childChannelName is mutually exclusive with threadRootSeq");
+ }
+ if (p.seq !== undefined && p.threadRootSeq === undefined && p.childChannelName === undefined) {
+ throw new Error("formatRef: seq without threadRootSeq or childChannelName is not supported");
}
const base = `/${p.server}/${p.channel}`;
+ if (p.childChannelName !== undefined) {
+ const postBase = `${base}/${p.childChannelName}`;
+ return p.seq === undefined ? postBase : `${postBase}#${p.seq}`;
+ }
if (p.threadRootSeq === undefined) return base;
if (p.seq === undefined) return `${base}/#${p.threadRootSeq}`;
return `${base}/#${p.threadRootSeq}#${p.seq}`;
diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.ts
index 3ef97b814..773b3b537 100644
--- a/src/shared/src/db/queries/community/agent-inbox.ts
+++ b/src/shared/src/db/queries/community/agent-inbox.ts
@@ -203,6 +203,22 @@ async function resolveScopeRefs(
continue;
}
}
+ // Forum post: a `forum_post` child channel has a parent forum but NO
+ // parentMessageId (unlike a thread), so it's anchored by its own name under
+ // the forum: `/server/<forum>/<post>`. Without this it fell through to the
+ // top-level fallback below (`/server/<post-name>`), which the name resolver
+ // β€” top-level only β€” can never parse back, 404ing send/read/ack on the post.
+ if (ch.type === "forum_post" && ch.parentChannelId) {
+ const parent = parentChannelById.get(ch.parentChannelId);
+ if (parent) {
+ out.set(ch.id, {
+ ref: formatRef({ server: serverName, channel: parent.name, childChannelName: ch.name }),
+ isThread: false,
+ isDm: false,
+ });
+ continue;
+ }
+ }
out.set(ch.id, { ref: formatRef({ server: serverName, channel: ch.name }), isThread: false, isDm: false });
}
return out;
@@ -387,6 +403,23 @@ export async function resolveUnreadNoticeChannel(
return formatRef({ server: serverName, channel: parent.name, threadRootSeq: root.seq });
}
+ // Forum post: parent forum but no parentMessageId β€” anchor by the post's own
+ // name under the forum (`/server/<forum>/<post>`). A missing/serverless parent
+ // resolves to null (notice_channel_unresolvable) rather than a bogus ref, per
+ // this function's no-placeholder contract.
+ if (ch.type === "forum_post" && ch.parentChannelId) {
+ const parentRows = await db
+ .select({ name: communityChannel.name, serverId: communityChannel.serverId })
+ .from(communityChannel)
+ .where(eq(communityChannel.id, ch.parentChannelId))
+ .limit(1);
+ const parent = parentRows[0];
+ if (!parent || !parent.serverId) return null;
+ const serverName = await getServerName(db, parent.serverId);
+ if (!serverName) return null;
+ return formatRef({ server: serverName, channel: parent.name, childChannelName: ch.name });
+ }
+
if (!ch.serverId) return null;
const serverName = await getServerName(db, ch.serverId);
if (!serverName) return null;
diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.ts
index c1687a5cd..dab69b761 100644
--- a/src/shared/src/db/queries/community/channel.ts
+++ b/src/shared/src/db/queries/community/channel.ts
@@ -319,6 +319,69 @@ export async function getThreadChannelByParentMessage(
return row ? mapChannelRow(row) : null;
}
+/**
+ * Resolve a forum post by its name under a parent forum. A forum post is a
+ * `forum_post` child channel anchored by its own name (not a root-message seq
+ * like a thread), so `(parentChannelId, name, type='forum_post')` is its
+ * address. Returns ALL matches so the caller can disambiguate: post names are
+ * NOT unique within a forum (schema exempts child channels from the per-server
+ * unique index), so >1 row means an ambiguous ref the resolver must 400 on β€”
+ * never silently pick one.
+ */
+export async function getChildChannelByName(
+ db: Database,
+ parentChannelId: string,
+ name: string,
+ type = "forum_post"
+) {
+ const rows = await db
+ .select(CHANNEL_COLUMNS)
+ .from(communityChannel)
+ .where(
+ and(
+ eq(communityChannel.parentChannelId, parentChannelId),
+ eq(communityChannel.name, name),
+ eq(communityChannel.type, type)
+ )
+ );
+ return rows.map(mapChannelRow);
+}
+
+/**
+ * Dedupe a forum-post slug within its parent forum so the name anchor
+ * (`/server/forum/<post>`) is a real address. Post names are not covered by the
+ * per-server unique index (that's top-level channels only), so uniqueness is
+ * enforced here at create time, mirroring the discipline top-level channel
+ * names already follow: `ideas` β†’ `ideas-2` β†’ `ideas-3`. The input is already
+ * a slug (the caller `slugify`s the raw name β€” this only appends the numeric
+ * suffix on collision, never re-introduces `/`/`#`/whitespace). Best-effort
+ * against a read snapshot; the create path is single-writer per forum in
+ * practice, and a rare race just yields a second same-named post the resolver's
+ * ambiguity floor still handles safely.
+ */
+export async function dedupeChildChannelSlug(
+ db: Database,
+ parentChannelId: string,
+ baseSlug: string,
+ type = "forum_post"
+): Promise<string> {
+ const rows = await db
+ .select({ name: communityChannel.name })
+ .from(communityChannel)
+ .where(
+ and(
+ eq(communityChannel.parentChannelId, parentChannelId),
+ eq(communityChannel.type, type)
+ )
+ );
+ const taken = new Set(rows.map((r) => r.name));
+ if (!taken.has(baseSlug)) return baseSlug;
+ for (let n = 2; ; n++) {
+ const candidate = `${baseSlug}-${n}`;
+ if (!taken.has(candidate)) return candidate;
+ }
+}
+
/**
* Auto-create a thread channel rooted at `parentMessageId` inside
* `parentChannelId` (debt #10 β€” threads ARE channels). `type: "thread"` is
diff --git a/src/shared/test/community-cli-contract.test.ts b/src/shared/test/community-cli-contract.test.ts
index 236773680..f44295a04 100644
--- a/src/shared/test/community-cli-contract.test.ts
+++ b/src/shared/test/community-cli-contract.test.ts
@@ -137,6 +137,40 @@ describe("parseRef", () => {
seq: 42,
});
});
+
+ it('parses "/studio/ideas/my-post" as a forum-post ref (childChannelName)', () => {
+ expect(parseRef("/studio/ideas/my-post")).toEqual({
+ server: "studio",
+ channel: "ideas",
+ childChannelName: "my-post",
+ });
+ });
+
+ it("does not confuse a forum-post ref with a thread ref (3rd segment has no #)", () => {
+ // Thread: 3rd segment starts with "#". Post: it doesn't.
+ expect(parseRef("/studio/ideas/#5")).toEqual({ server: "studio", channel: "ideas", threadRootSeq: 5 });
+ expect(parseRef("/studio/ideas/notes")).toEqual({ server: "studio", channel: "ideas", childChannelName: "notes" });
+ });
+
+ it("throws on a 4th segment (posts have no deeper addressing today)", () => {
+ expect(() => parseRef("/studio/ideas/post/extra")).toThrow();
+ });
+
+ it('parses "/studio/ideas/post#3" β€” a message pinned inside a forum post', () => {
+ // Symmetric to the top-level message form /server/channel#N β€” used by
+ // `message emoji` to react to a specific message inside a post.
+ expect(parseRef("/studio/ideas/post#3")).toEqual({
+ server: "studio",
+ channel: "ideas",
+ childChannelName: "post",
+ seq: 3,
+ });
+ });
+
+ it("throws when a forum-post pin-seq ref has an empty post name (#N with no post)", () => {
+ expect(() => parseRef("/studio/ideas/#3")).not.toThrow(); // this is the THREAD form, still valid
+ expect(parseRef("/studio/ideas/#3")).toEqual({ server: "studio", channel: "ideas", threadRootSeq: 3 });
+ });
});
describe("formatRef", () => {
@@ -181,6 +215,34 @@ describe("formatRef", () => {
"/studio/general/#5",
);
});
+
+ it("formats a forum-post ref (childChannelName)", () => {
+ expect(formatRef({ server: "studio", channel: "ideas", childChannelName: "my-post" })).toBe(
+ "/studio/ideas/my-post",
+ );
+ });
+
+ it("round-trips a forum-post ref through parseRef", () => {
+ const input = { server: "studio", channel: "ideas", childChannelName: "my-post" };
+ expect(parseRef(formatRef(input))).toEqual(input);
+ });
+
+ it("formats a forum-post message ref (childChannelName + seq)", () => {
+ expect(formatRef({ server: "studio", channel: "ideas", childChannelName: "my-post", seq: 3 })).toBe(
+ "/studio/ideas/my-post#3",
+ );
+ });
+
+ it("round-trips a forum-post message ref through parseRef", () => {
+ const input = { server: "studio", channel: "ideas", childChannelName: "my-post", seq: 3 };
+ expect(parseRef(formatRef(input))).toEqual(input);
+ });
+
+ it("throws when childChannelName is combined with threadRootSeq (posts have no thread root)", () => {
+ expect(() =>
+ formatRef({ server: "studio", channel: "ideas", childChannelName: "p", threadRootSeq: 5 }),
+ ).toThrow();
+ });
});
describe("formatSeq / parseSeq", () => {
diff --git a/src/shared/test/queries/community-agent-inbox.test.ts b/src/shared/test/queries/community-agent-inbox.test.ts
index 30f9a0946..5a839374c 100644
--- a/src/shared/test/queries/community-agent-inbox.test.ts
+++ b/src/shared/test/queries/community-agent-inbox.test.ts
@@ -105,6 +105,28 @@ describe("toAgentMessages", () => {
expect(msg!.channel).toBe(formatRef({ server: "studio", channel: "general", threadRootSeq: 7 }));
});
+ it("hydrates a forum-post message with the name-anchor ref (/server/forum/post)", async () => {
+ // A forum_post has a parentChannelId (the forum) but NO parentMessageId
+ // (unlike a thread), so it must be anchored by its own name under the
+ // forum β€” NOT fall through to the top-level fallback `/server/<post-name>`
+ // (which the name resolver, top-level only, could never parse back).
+ // Call order: 1. channels (the post itself), 2. author names,
+ // 3. parentChannels (the forum), 4. servers. parentMessageIds is empty
+ // (null) so that select is skipped.
+ const db = createSequentialDb([
+ [{ id: "post_1", name: "my-post", type: "forum_post", serverId: "srv_1", parentChannelId: "forum_1", parentMessageId: null }],
+ [{ id: "u_1", name: "Alice" }],
+ [{ id: "forum_1", name: "ideas" }],
+ [{ id: "srv_1", name: "studio" }],
+ ]);
+ const [msg] = await agentInbox.toAgentMessages(
+ db,
+ [rawMsg({ channelId: "post_1" })],
+ "viewer_1"
+ );
+ expect(msg!.channel).toBe(formatRef({ server: "studio", channel: "ideas", childChannelName: "my-post" }));
+ });
+
it("hydrates a DM message, addressing the OTHER party (as a name#0042 handle) relative to viewerId", async () => {
// A DM is a type=dm channel now, so it flows through the SAME `channels`
// query as any other scope. Call order: 1. channels query (returns the
diff --git a/src/shared/test/queries/community-channel-threads.test.ts b/src/shared/test/queries/community-channel-threads.test.ts
index 35c2fcb04..297a75400 100644
--- a/src/shared/test/queries/community-channel-threads.test.ts
+++ b/src/shared/test/queries/community-channel-threads.test.ts
@@ -1,5 +1,22 @@
import { describe, it, expect, vi } from "vitest";
-import { createThreadChannel } from "../../src/db/queries/community/channel";
+import {
+ createThreadChannel,
+ getChildChannelByName,
+ dedupeChildChannelSlug,
+} from "../../src/db/queries/community/channel";
+
+// A single-select thenable-chain db (FIFO), for the child-channel helpers
+// which each issue exactly one `db.select(...)...`.
+function createSelectDb(rows: unknown[]) {
+ const methods = ["from", "where"];
+ const select = vi.fn(() => {
+ const chain: any = {};
+ for (const m of methods) chain[m] = vi.fn(() => chain);
+ chain.then = (resolve: any, reject: any) => Promise.resolve(rows).then(resolve, reject);
+ return chain;
+ });
+ return { select } as any;
+}
/**
* `createThreadChannel` mixes two `db.select()` round trips (parent-channel
@@ -113,3 +130,37 @@ describe("createThreadChannel", () => {
expect(db.__insertValues).not.toHaveBeenCalled();
});
});
+
+describe("getChildChannelByName", () => {
+ it("returns all matches (mapped rows) so the caller can detect ambiguity", async () => {
+ const db = createSelectDb([
+ { id: "post_1", name: "dupe", type: "forum_post", serverId: "srv_1", parentChannelId: "forum_1", forumTags: null },
+ { id: "post_2", name: "dupe", type: "forum_post", serverId: "srv_1", parentChannelId: "forum_1", forumTags: null },
+ ]);
+ const rows = await getChildChannelByName(db, "forum_1", "dupe");
+ expect(rows.map((r) => r.id)).toEqual(["post_1", "post_2"]);
+ });
+
+ it("returns [] when no post with that name exists under the forum", async () => {
+ const db = createSelectDb([]);
+ const rows = await getChildChannelByName(db, "forum_1", "ghost");
+ expect(rows).toEqual([]);
+ });
+});
+
+describe("dedupeChildChannelSlug", () => {
+ it("returns the base slug unchanged when no post in the forum uses it", async () => {
+ const db = createSelectDb([{ name: "other" }]);
+ expect(await dedupeChildChannelSlug(db, "forum_1", "ideas")).toBe("ideas");
+ });
+
+ it("appends -2 on the first collision", async () => {
+ const db = createSelectDb([{ name: "ideas" }]);
+ expect(await dedupeChildChannelSlug(db, "forum_1", "ideas")).toBe("ideas-2");
+ });
+
+ it("skips already-taken numbered suffixes (ideas, ideas-2 β†’ ideas-3)", async () => {
+ const db = createSelectDb([{ name: "ideas" }, { name: "ideas-2" }]);
+ expect(await dedupeChildChannelSlug(db, "forum_1", "ideas")).toBe("ideas-3");
+ });
+});
diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts b/src/web/src/app/api/community/channels/[id]/posts/route.test.ts
index f84568fdf..e8a1990ca 100644
--- a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/posts/route.test.ts
@@ -4,6 +4,7 @@ import { NextRequest } from "next/server"
const mockGetChannelForMember = vi.fn()
const mockResolveChannelAccessContext = vi.fn()
const mockCreateChannel = vi.fn()
+const mockDedupeChildChannelSlug = vi.fn(async (_db: unknown, _parent: unknown, slug: string) => slug)
const mockCreateMessage = vi.fn()
const mockGetMessage = vi.fn()
const mockGetUserSelf = vi.fn()
@@ -29,6 +30,7 @@ vi.mock("@alook/shared", async () => {
getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),
resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),
createChannel: (...a: unknown[]) => mockCreateChannel(...a),
+ dedupeChildChannelSlug: (...a: unknown[]) => mockDedupeChildChannelSlug(...a),
listChildChannels: (...a: unknown[]) => mockListChildChannels(...a),
// createCommunityMessage's private-channel scoping guard is only hit
// when there are mentions; the happy-path posts have none, so these
@@ -162,6 +164,27 @@ describe("POST /api/community/channels/[id]/posts β€” name normalization", () =>
expect(mockCreateChannel).not.toHaveBeenCalled()
})
+ it("dedupes the slug within the forum before creating (so the name anchor is unique)", async () => {
+ // The forum already has an "ideas" post β†’ dedupe yields "ideas-2".
+ mockDedupeChildChannelSlug.mockResolvedValueOnce("ideas-2")
+ mockCreateChannel.mockResolvedValue({
+ id: "post1",
+ name: "ideas-2",
+ createdAt: "2026-07-02T00:00:00.000Z",
+ })
+ const res = await POST(postReq({ name: "ideas", content: "hello" }), ctx)
+ expect(res.status).toBe(201)
+ // dedupe is called with the slugified base name under this forum...
+ expect(mockDedupeChildChannelSlug).toHaveBeenCalledWith(expect.anything(), "ch1", "ideas")
+ // ...and the DEDUPED name is what gets persisted.
+ expect(mockCreateChannel).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ name: "ideas-2" }),
+ )
+ const body = await res.json()
+ expect(body.post.name).toBe("ideas-2")
+ })
+
it("returns messageCount 0 in the response (body IS the first message, not a reply)", async () => {
mockCreateChannel.mockResolvedValue({
id: "post1",
diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.ts b/src/web/src/app/api/community/channels/[id]/posts/route.ts
index 6c92ab816..f5aba3eec 100644
--- a/src/web/src/app/api/community/channels/[id]/posts/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/posts/route.ts
@@ -141,12 +141,20 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
return writeError(`content must be ≀ ${MAX_MESSAGE_CONTENT_LENGTH} characters`, 400)
}
+ // Dedupe the slug within this forum so the post's name anchor
+ // (`/server/forum/<post>`) is a unique, resolvable address. Post names are
+ // NOT covered by the per-server unique index (top-level channels only), so
+ // uniqueness is enforced here, mirroring top-level channel naming: `ideas`
+ // β†’ `ideas-2` β†’ `ideas-3`. `name` is already slugified (no `/`/`#`/space),
+ // so the anchor round-trips cleanly through parseRef/formatRef.
+ const uniqueName = await queries.communityChannel.dedupeChildChannelSlug(db, channelId, name)
+
// Create child channel for the forum post. Tags are NOT set at creation β€”
// they're added afterward from the post card's tag dialog.
const postChannel = await queries.communityChannel.createChannel(db, {
serverId: channel.serverId,
parentChannelId: channelId,
- name,
+ name: uniqueName,
type: "forum_post",
creatorId: ctx.userId,
})
diff --git a/src/web/src/lib/community/resolve-ref.test.ts b/src/web/src/lib/community/resolve-ref.test.ts
index cc1ee40d9..5c5af3fb3 100644
--- a/src/web/src/lib/community/resolve-ref.test.ts
+++ b/src/web/src/lib/community/resolve-ref.test.ts
@@ -11,6 +11,7 @@ const mockResolveChannelByNameForMember = vi.fn()
const mockGetMessageByChannelAndSeq = vi.fn()
const mockGetThreadChannelByParentMessage = vi.fn()
const mockCreateThreadChannel = vi.fn()
+const mockGetChildChannelByName = vi.fn()
const mockIsUniqueConstraintError = vi.fn(() => false)
vi.mock("@alook/shared", async () => {
@@ -38,6 +39,7 @@ vi.mock("@alook/shared", async () => {
resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),
getThreadChannelByParentMessage: (...a: unknown[]) => mockGetThreadChannelByParentMessage(...a),
createThreadChannel: (...a: unknown[]) => mockCreateThreadChannel(...a),
+ getChildChannelByName: (...a: unknown[]) => mockGetChildChannelByName(...a),
},
communityMessage: {
getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),
@@ -240,6 +242,46 @@ describe("resolveTargetForMember", () => {
).rejects.toThrow("boom")
})
})
+
+ describe("forum-post refs (/server/forum/post)", () => {
+ beforeEach(() => {
+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])
+ // The parent forum resolves as a top-level channel.
+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "forum_1", name: "ideas" }])
+ })
+
+ it("resolves a forum post by name under its forum", async () => {
+ mockGetChildChannelByName.mockResolvedValue([{ id: "post_1", name: "my-post" }])
+ const res = await resolveTargetForMember(db, "u_1", "/studio/ideas/my-post")
+ expect(res).toEqual({ kind: "channel", channelId: "post_1" })
+ expect(mockGetChildChannelByName).toHaveBeenCalledWith(db, "forum_1", "my-post")
+ })
+
+ it("404 when no post with that name exists under the forum", async () => {
+ mockGetChildChannelByName.mockResolvedValue([])
+ const res = await resolveTargetForMember(db, "u_1", "/studio/ideas/ghost")
+ expect(res).toEqual({ error: 404, message: "post not found: ghost" })
+ })
+
+ it("400 ambiguous (never silently picks) when >1 post shares the name", async () => {
+ mockGetChildChannelByName.mockResolvedValue([
+ { id: "post_1", name: "dupe" },
+ { id: "post_2", name: "dupe" },
+ ])
+ const res = await resolveTargetForMember(db, "u_1", "/studio/ideas/dupe")
+ expect(res).toMatchObject({ error: 400 })
+ expect((res as { message: string }).message).toMatch(/ambiguous post name "dupe"/)
+ // Critically: no channelId is returned β€” the caller cannot mis-route.
+ expect(res).not.toHaveProperty("channelId")
+ })
+
+ it("404 when the parent forum itself doesn't resolve", async () => {
+ mockResolveChannelByNameForMember.mockResolvedValue([])
+ const res = await resolveTargetForMember(db, "u_1", "/studio/ideas/my-post")
+ expect(res).toEqual({ error: 404, message: "channel not found: ideas" })
+ expect(mockGetChildChannelByName).not.toHaveBeenCalled()
+ })
+ })
})
describe("resolveErrorResponse", () => {
diff --git a/src/web/src/lib/community/resolve-ref.ts b/src/web/src/lib/community/resolve-ref.ts
index adf1cce93..d989fcc19 100644
--- a/src/web/src/lib/community/resolve-ref.ts
+++ b/src/web/src/lib/community/resolve-ref.ts
@@ -105,6 +105,34 @@ export async function resolveTargetForMember(
if (matches.length === 0) return { error: 404, message: `channel not found: ${parsed.channel}` }
const channel = matches[0]!
+ // Forum-post form (`/server/forum/post`) β€” the resolved `channel` is the
+ // parent forum; descend to the `forum_post` child by name. Runs parallel to
+ // the thread branch below (do NOT fold them: a thread anchors on a root-msg
+ // seq, a post on its own name). Post names are NOT unique within a forum, so
+ // >1 match is an ambiguous ref β€” return 400 + candidates, NEVER silently pick
+ // one (mirrors the ambiguous-server-name behavior above). A forum post
+ // inherits its forum's access; `requireChannelMember`/`requireChannelAccess`
+ // at the call site climb `parentChannelId` to gate on the forum's roster.
+ if (parsed.childChannelName !== undefined) {
+ const posts = await queries.communityChannel.getChildChannelByName(db, channel.id, parsed.childChannelName)
+ if (posts.length === 0) {
+ return { error: 404, message: `post not found: ${parsed.childChannelName}` }
+ }
+ if (posts.length > 1) {
+ // Ambiguous: >1 post shares this name (only possible for legacy dupes
+ // predating create-time dedup). The red line is met by refusing β€” we
+ // NEVER silently pick one. A name-based hint can't disambiguate here
+ // (the candidates' name-anchor paths are identical), so we report the
+ // count instead of fabricating useless identical paths; a one-time
+ // slug-dedup migration on legacy posts is the clean fix (deferred).
+ return {
+ error: 400,
+ message: `ambiguous post name "${parsed.childChannelName}" in ${parsed.channel} β€” ${posts.length} posts share this name; rename the duplicates to address them by name`,
+ }
+ }
+ return { kind: "channel", channelId: posts[0]!.id }
+ }
+
if (parsed.threadRootSeq === undefined) {
return { kind: "channel", channelId: channel.id }
}