Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

community(mark): mark messages + Marked inbox tab (server + DM)

Gus16c49d6084f7
diff --git a/src/daemon/src/runtime/runtimeSession.test.ts b/src/daemon/src/runtime/runtimeSession.test.ts
index 87dabc82b..035c48820 100644
--- a/src/daemon/src/runtime/runtimeSession.test.ts
+++ b/src/daemon/src/runtime/runtimeSession.test.ts
@@ -73,9 +73,20 @@ describe("ChildProcessRuntimeSession — real subprocess exit fills the physical
});
},
);
- expect(exitInfo.signal).toBe("SIGKILL");
- expect(exitInfo.code).toBeNull();
- expect(exitInfo.reason).toBe("runtime_exit");
+ if (process.platform === "win32") {
+ // Windows has no POSIX signals: process.kill(pid, "SIGKILL") routes through
+ // TerminateProcess, so Node reports signal=null (never "SIGKILL") — "which
+ // signal killed it" is a physical fact that does not exist on this platform.
+ // The cross-platform invariant this test actually guards (see file header) is
+ // that a non-requested death is tagged reason="runtime_exit", the shape the
+ // abnormal predicate reads; the signal NAME is a POSIX-only implementation detail.
+ expect(exitInfo.signal).toBeNull();
+ expect(exitInfo.reason).toBe("runtime_exit");
+ } else {
+ expect(exitInfo.signal).toBe("SIGKILL");
+ expect(exitInfo.code).toBeNull();
+ expect(exitInfo.reason).toBe("runtime_exit");
+ }
});
it("a real clean exit (code 0) emits code=0, null signal", async () => {
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.ts
index c84f68226..e1714a2dd 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -43,6 +43,7 @@ export * as communityInvite from "./queries/community/invite";
export * as communityReaction from "./queries/community/reaction";
export * as communityAttachment from "./queries/community/attachment";
export * as communityPin from "./queries/community/pin";
+export * as communityMessageMark from "./queries/community/mark";
export * as communityMention from "./queries/community/mention";
export * as communityReadState from "./queries/community/read-state";
export * as communityUserProfile from "./queries/community/user-profile";
diff --git a/src/shared/src/db/queries/community/dm.ts b/src/shared/src/db/queries/community/dm.ts
index 406b6c67d..b902422be 100644
--- a/src/shared/src/db/queries/community/dm.ts
+++ b/src/shared/src/db/queries/community/dm.ts
@@ -106,6 +106,34 @@ export async function createOrGetDM(
return channel;
}
+// The ids of every DM channel the user has access to (type='dm' channels where
+// they hold a relation='access' member row). DMs carry `server_id = NULL`, so
+// they are structurally absent from `listVisibleChannelIdsForUser` (which walks
+// the user's server memberships). A caller that needs DM messages in scope —
+// e.g. the Marked inbox tab, which spans DMs as well as server channels — unions
+// these ids in. Access-membership IS the DM visibility gate, so a mark in a DM
+// the user isn't a member of never surfaces.
+export async function listDmChannelIdsForUser(
+ db: Database,
+ userId: string
+): Promise<string[]> {
+ const rows = await db
+ .select({ channelId: communityChannelMember.channelId })
+ .from(communityChannelMember)
+ .innerJoin(
+ communityChannel,
+ eq(communityChannel.id, communityChannelMember.channelId)
+ )
+ .where(
+ and(
+ eq(communityChannelMember.userId, userId),
+ eq(communityChannelMember.relation, "access"),
+ eq(communityChannel.type, "dm")
+ )
+ );
+ return rows.map((r) => r.channelId);
+}
+
export async function listDMs(db: Database, userId: string) {
// DM channels the user holds an access row on, joined to the OTHER access
// member → user for display. Order by last_message_at DESC.
diff --git a/src/shared/src/db/queries/community/mark.ts b/src/shared/src/db/queries/community/mark.ts
new file mode 100644
index 000000000..42c8bdc9d
--- /dev/null
+++ b/src/shared/src/db/queries/community/mark.ts
@@ -0,0 +1,120 @@
+import { eq, and, inArray, desc } from "drizzle-orm";
+import { communityMessageMark, communityMessage } from "../../community-schema";
+import { user } from "../../schema";
+import type { Database } from "../../index";
+import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";
+
+// Idempotent mark. UNIQUE(userId, messageId) makes a re-mark a no-op, so
+// `onConflictDoNothing` keeps the toggle safe to call twice without a 409
+// round-trip (contract: /Gus/working #1004). channelId is stored for the
+// cascade + the phase-2 per-channel read; messageId alone is globally unique.
+export async function markMessage(
+ db: Database,
+ data: { userId: string; channelId: string; messageId: string }
+) {
+ await db
+ .insert(communityMessageMark)
+ .values({
+ userId: data.userId,
+ channelId: data.channelId,
+ messageId: data.messageId,
+ })
+ .onConflictDoNothing({
+ target: [communityMessageMark.userId, communityMessageMark.messageId],
+ });
+}
+
+// Self-scoped: only the marking user's own row is deletable. A DELETE targeting
+// someone else's mark on the same message matches 0 rows (no-op) — never touches
+// another user's private mark.
+export async function unmarkMessage(
+ db: Database,
+ data: { userId: string; messageId: string }
+) {
+ const [deleted] = await db
+ .delete(communityMessageMark)
+ .where(
+ and(
+ eq(communityMessageMark.userId, data.userId),
+ eq(communityMessageMark.messageId, data.messageId)
+ )
+ )
+ .returning();
+ return deleted ?? null;
+}
+
+// Single-row presence check for the ⋯-menu Mark/Unmark label. Self-scoped
+// (WHERE userId): answers "did *I* mark this", never "did anyone" — reading
+// another user's mark state would leak their private marks. Hits
+// UNIQUE(userId, messageId), so it's a one-row index lookup.
+export async function isMessageMarked(
+ db: Database,
+ userId: string,
+ messageId: string
+): Promise<boolean> {
+ const rows = await db
+ .select({ id: communityMessageMark.id })
+ .from(communityMessageMark)
+ .where(
+ and(
+ eq(communityMessageMark.userId, userId),
+ eq(communityMessageMark.messageId, messageId)
+ )
+ )
+ .limit(1);
+ return rows.length > 0;
+}
+
+// Cross-channel Marked list for the inbox tab. Scoped to the viewer's visible
+// channels in-query (NOT a post-fetch filter) so a mark in a private channel the
+// user has since left never surfaces — same guard as listUnreadMentions. Joins
+// communityMessage for the jump key (seq) + snapshot, and user for the author.
+// No denormalized seq on the mark row, so the join is required.
+export async function listMarksForUser(
+ db: Database,
+ userId: string,
+ opts: { limit?: number; visibleChannelIds?: string[] } = {}
+) {
+ const runQuery = (extra: ReturnType<typeof inArray>[] = []) => {
+ const q = db
+ .select({
+ mark: communityMessageMark,
+ message: communityMessage,
+ author: user,
+ })
+ .from(communityMessageMark)
+ .innerJoin(
+ communityMessage,
+ eq(communityMessageMark.messageId, communityMessage.id)
+ )
+ .innerJoin(user, eq(communityMessage.authorId, user.id))
+ .where(and(eq(communityMessageMark.userId, userId), ...extra))
+ // Newest-first — matches idx_mark_user_created.
+ .orderBy(desc(communityMessageMark.createdAt));
+ return opts.limit !== undefined ? q.limit(opts.limit) : q;
+ };
+
+ // No channel scoping → single query (callers that don't need the leak guard).
+ if (!opts.visibleChannelIds) {
+ return runQuery();
+ }
+ // `inArray(col, [])` is rejected by some drivers; an empty scope means nothing
+ // is visible, so return early.
+ if (opts.visibleChannelIds.length === 0) return [];
+
+ // `visibleChannelIds` is an unbounded authorization scope, so chunk the
+ // `inArray` under D1's param cap and merge: each chunk runs the same
+ // order+limit, then re-sort by createdAt desc + re-apply the limit so the
+ // global newest wins (not each chunk's newest). createdAt is in the
+ // projection, so the JS re-sort is exact.
+ const chunks = chunk(opts.visibleChannelIds, D1_MAX_IN_PARAMS);
+ const merged = (
+ await Promise.all(
+ chunks.map((ids) =>
+ runQuery([inArray(communityMessageMark.channelId, ids)])
+ )
+ )
+ ).flat();
+ merged.sort((a, b) => (a.mark.createdAt < b.mark.createdAt ? 1 : -1));
+ return opts.limit !== undefined ? merged.slice(0, opts.limit) : merged;
+}
diff --git a/src/web/src/app/api/community/inbox/marked/route.test.ts b/src/web/src/app/api/community/inbox/marked/route.test.ts
new file mode 100644
index 000000000..9eab82ff4
--- /dev/null
+++ b/src/web/src/app/api/community/inbox/marked/route.test.ts
@@ -0,0 +1,123 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockListMarksForUser = vi.fn()
+const mockGetChannelsByIds = vi.fn()
+const mockGetServersByIds = vi.fn()
+const mockListVisibleChannelIds = vi.fn()
+const mockListDmChannelIds = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityMessageMark: {
+ listMarksForUser: (...args: unknown[]) => mockListMarksForUser(...args),
+ },
+ communityChannel: {
+ getChannelsByIds: (...args: unknown[]) => mockGetChannelsByIds(...args),
+ listVisibleChannelIdsForUser: (...args: unknown[]) => mockListVisibleChannelIds(...args),
+ },
+ communityDm: {
+ listDmChannelIdsForUser: (...args: unknown[]) => mockListDmChannelIds(...args),
+ },
+ communityServer: {
+ getServersByIds: (...args: unknown[]) => mockGetServersByIds(...args),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { GET } from "./route"
+
+describe("GET /api/community/inbox/marked", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetChannelsByIds.mockResolvedValue([])
+ mockGetServersByIds.mockResolvedValue([])
+ mockListVisibleChannelIds.mockResolvedValue(["c1"])
+ mockListDmChannelIds.mockResolvedValue([])
+ })
+
+ it("scopes the query to the viewer's visible channels (no leak of left private channels)", async () => {
+ mockListMarksForUser.mockResolvedValue([])
+ await GET(new NextRequest("http://localhost/api/community/inbox/marked"))
+ const opts = mockListMarksForUser.mock.calls[0][2]
+ expect(opts.visibleChannelIds).toEqual(["c1"])
+ })
+
+ it("unions the viewer's DM channels into scope so marked DM messages are not filtered out", async () => {
+ // DM channels carry server_id=NULL and are absent from
+ // listVisibleChannelIdsForUser — without the union a marked DM message would
+ // be silently dropped from the Marked tab (Gus /Gus/working #1025).
+ mockListVisibleChannelIds.mockResolvedValue(["c1"])
+ mockListDmChannelIds.mockResolvedValue(["dm1"])
+ mockListMarksForUser.mockResolvedValue([])
+ await GET(new NextRequest("http://localhost/api/community/inbox/marked"))
+ const opts = mockListMarksForUser.mock.calls[0][2]
+ expect(opts.visibleChannelIds).toEqual(["c1", "dm1"])
+ })
+
+ it("hydrates server + channel names and carries the seq jump key + snapshot", async () => {
+ mockListMarksForUser.mockResolvedValue([
+ {
+ mark: { id: "mk1", channelId: "c1", createdAt: "2026-06-25T10:00:00Z" },
+ message: { id: "m1", seq: 42, content: "pinned thought", createdAt: "2026-06-25T09:00:00Z" },
+ author: { id: "u-alice", name: "Alice", email: "[email protected]", image: null },
+ },
+ ])
+ mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])
+ mockGetServersByIds.mockResolvedValue([{ id: "s1", name: "Server 1" }])
+
+ const res = await GET(new NextRequest("http://localhost/api/community/inbox/marked"))
+ const body = await res.json()
+ expect(body.marked).toHaveLength(1)
+ expect(body.marked[0]).toMatchObject({
+ id: "mk1",
+ server: "Server 1",
+ serverId: "s1",
+ channel: "general",
+ channelId: "c1",
+ // serverId + channelId locate the channel, m.seq jumps to the message —
+ // all three required for cross-channel navigation. seq lives inside `m`
+ // to match the frontend `Marked` type (m: Msg).
+ m: { id: "m1", authorId: "u-alice", authorName: "Alice", content: "pinned thought", seq: 42 },
+ })
+ })
+
+ it("returns empty marked array when none", async () => {
+ mockListMarksForUser.mockResolvedValue([])
+ const res = await GET(new NextRequest("http://localhost/api/community/inbox/marked"))
+ expect((await res.json()).marked).toEqual([])
+ })
+
+ it("clamps over-cap limit and forwards it to the query", async () => {
+ mockListMarksForUser.mockResolvedValue([])
+ const res = await GET(new NextRequest("http://localhost/api/community/inbox/marked?limit=99999"))
+ const body = await res.json()
+ expect(body.limit).toBe(200) // MAX_INBOX_PAGE_SIZE
+ expect(mockListMarksForUser).toHaveBeenCalledWith({}, "u1", { limit: 200, visibleChannelIds: ["c1"] })
+ })
+})
diff --git a/src/web/src/app/api/community/inbox/marked/route.ts b/src/web/src/app/api/community/inbox/marked/route.ts
new file mode 100644
index 000000000..62b2d9a99
--- /dev/null
+++ b/src/web/src/app/api/community/inbox/marked/route.ts
@@ -0,0 +1,93 @@
+import { withAuth } from "@/lib/middleware/auth"
+import { writeJSON } from "@/lib/middleware/helpers"
+import { getDb } from "@/lib/db"
+import {
+ queries,
+ DEFAULT_INBOX_PAGE_SIZE,
+ MAX_INBOX_PAGE_SIZE,
+ readOrStale,
+} from "@alook/shared"
+import { parseBoundedInt } from "@/lib/community/messages"
+import { avatarInitial } from "@/lib/community/avatar"
+
+// Cross-channel Marked tab: every message the current user has marked, newest
+// first. Scoped to the viewer's visible channels in-query (same guard as the
+// Mentions tab) so a mark in a private channel the user has since left never
+// leaks. Each row carries serverId + channelId + seq — the frontend needs all
+// three to navigate: serverId/channelId locate the channel, m.seq jumps to the
+// message (a marked message is usually outside the loaded window, so a
+// seq-less scroll would silently no-op).
+export const GET = withAuth(async (req, ctx) => {
+ const db = getDb(ctx.env.DB)
+ const url = new URL(req.url)
+ const limit = parseBoundedInt(
+ url.searchParams.get("limit"),
+ DEFAULT_INBOX_PAGE_SIZE,
+ MAX_INBOX_PAGE_SIZE,
+ )
+
+ type MarkRow = Awaited<ReturnType<typeof queries.communityMessageMark.listMarksForUser>>[number]
+ type ChannelRow = Awaited<ReturnType<typeof queries.communityChannel.getChannelsByIds>>[number]
+ type ServerRow = Awaited<ReturnType<typeof queries.communityServer.getServersByIds>>[number]
+ const { value: fetched, stale } = await readOrStale<{
+ rows: MarkRow[]
+ channels: ChannelRow[]
+ servers: ServerRow[]
+ }>(
+ async () => {
+ // The Marked tab spans DMs as well as server channels. DM channels carry
+ // server_id = NULL, so they're absent from listVisibleChannelIdsForUser
+ // (which walks server memberships) — union in the user's DM channels so a
+ // marked DM message isn't silently filtered out. Access-membership is the
+ // DM visibility gate in both helpers, so no cross-user leak.
+ const [serverChannelIds, dmChannelIds] = await Promise.all([
+ queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId),
+ queries.communityDm.listDmChannelIdsForUser(db, ctx.userId),
+ ])
+ const visibleChannelIds = [...serverChannelIds, ...dmChannelIds]
+ const rows = await queries.communityMessageMark.listMarksForUser(db, ctx.userId, {
+ limit,
+ visibleChannelIds,
+ })
+ const channelIds = [...new Set(rows.map((r) => r.mark.channelId))]
+ const channels = channelIds.length > 0 ? await queries.communityChannel.getChannelsByIds(db, channelIds) : []
+ const serverIds = [...new Set(channels.map((ch) => ch.serverId))]
+ const servers = serverIds.length > 0 ? await queries.communityServer.getServersByIds(db, serverIds) : []
+ return { rows, channels, servers }
+ },
+ { rows: [], channels: [], servers: [] },
+ { route: "community/inbox/marked" },
+ )
+ if (stale) {
+ return writeJSON({ marked: [], limit, stale: true })
+ }
+ const { rows, channels, servers } = fetched
+ const channelMap = new Map(channels.map((ch) => [ch.id, ch]))
+ const serverMap = new Map(servers.map((s) => [s.id, s]))
+
+ const marked = rows.map((row) => {
+ const ch = channelMap.get(row.mark.channelId)
+ const srv = ch ? serverMap.get(ch.serverId) : undefined
+ return {
+ id: row.mark.id,
+ server: srv ? srv.name : "Unknown",
+ serverId: ch?.serverId,
+ channel: ch ? ch.name : "Unknown",
+ channelId: row.mark.channelId,
+ m: {
+ id: row.message.id,
+ authorId: row.author.id,
+ authorName: row.author.name,
+ authorAvatar: row.author.image ?? avatarInitial(row.author.name),
+ content: row.message.content,
+ // seq is the jump key (Msg.seq) — a marked message is usually outside
+ // the loaded window, so a seq-less scroll silently no-ops. Lives inside
+ // `m` to match the frontend `Marked` type (m: Msg).
+ seq: row.message.seq,
+ createdAt: row.message.createdAt,
+ },
+ }
+ })
+
+ return writeJSON({ marked, limit })
+})
diff --git a/src/web/src/app/api/community/marks/[messageId]/route.test.ts b/src/web/src/app/api/community/marks/[messageId]/route.test.ts
new file mode 100644
index 000000000..374fe4ffe
--- /dev/null
+++ b/src/web/src/app/api/community/marks/[messageId]/route.test.ts
@@ -0,0 +1,83 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockUnmarkMessage = vi.fn()
+const mockIsMessageMarked = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityMessageMark: {
+ unmarkMessage: (...args: unknown[]) => mockUnmarkMessage(...args),
+ isMessageMarked: (...args: unknown[]) => mockIsMessageMarked(...args),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { DELETE, GET } from "./route"
+
+const ctx = { params: { messageId: "m1" } }
+
+describe("DELETE /api/community/marks/[messageId]", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("unmarks self-scoped to ctx.userId and returns ok", async () => {
+ mockUnmarkMessage.mockResolvedValue({ id: "mk1" })
+ const res = await DELETE(new NextRequest("http://localhost/api/community/marks/m1", { method: "DELETE" }), ctx)
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ ok: true })
+ expect(mockUnmarkMessage).toHaveBeenCalledWith({}, { userId: "u1", messageId: "m1" })
+ })
+
+ it("returns ok even when nothing was deleted (another user's mark = 0-row no-op)", async () => {
+ // unmarkMessage's WHERE is userId=ctx.userId AND messageId, so deleting a
+ // mark owned by someone else matches 0 rows — the route still returns ok
+ // (idempotent), never touching the other user's private mark.
+ mockUnmarkMessage.mockResolvedValue(null)
+ const res = await DELETE(new NextRequest("http://localhost/api/community/marks/m1", { method: "DELETE" }), ctx)
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ ok: true })
+ })
+})
+
+describe("GET /api/community/marks/[messageId]", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("returns {marked:true} when the current user marked the message", async () => {
+ mockIsMessageMarked.mockResolvedValue(true)
+ const res = await GET(new NextRequest("http://localhost/api/community/marks/m1"), ctx)
+ expect(await res.json()).toEqual({ marked: true })
+ // self-scoped: the query is asked "did u1 mark m1", never "did anyone".
+ expect(mockIsMessageMarked).toHaveBeenCalledWith({}, "u1", "m1")
+ })
+
+ it("returns {marked:false} when the current user has not marked it", async () => {
+ mockIsMessageMarked.mockResolvedValue(false)
+ const res = await GET(new NextRequest("http://localhost/api/community/marks/m1"), ctx)
+ expect(await res.json()).toEqual({ marked: false })
+ })
+})
diff --git a/src/web/src/app/api/community/marks/[messageId]/route.ts b/src/web/src/app/api/community/marks/[messageId]/route.ts
new file mode 100644
index 000000000..18968a0e7
--- /dev/null
+++ b/src/web/src/app/api/community/marks/[messageId]/route.ts
@@ -0,0 +1,38 @@
+import { NextRequest } from "next/server"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeJSON, writeError } from "@/lib/middleware/helpers"
+import { getDb } from "@/lib/db"
+import { queries } from "@alook/shared"
+
+// Toggle-off: unmark a message for the current user. Self-scoped — deletes only
+// ctx.userId's own row; another user's mark on the same message is untouched
+// (0-row no-op). Returns ok whether or not a row existed (idempotent).
+export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
+ const messageId = ctx.params?.messageId
+ if (!messageId) return writeError("missing message id", 400)
+
+ const db = getDb(ctx.env.DB)
+ await queries.communityMessageMark.unmarkMessage(db, {
+ userId: ctx.userId,
+ messageId,
+ })
+
+ return writeJSON({ ok: true })
+})
+
+// Menu-open check: is THIS message marked by the current user? Self-scoped
+// (WHERE userId=ctx.userId) — answers "did *I* mark it", never "did anyone",
+// so it can't leak another user's private mark state. One-row index lookup.
+export const GET = withAuth(async (_req: NextRequest, ctx) => {
+ const messageId = ctx.params?.messageId
+ if (!messageId) return writeError("missing message id", 400)
+
+ const db = getDb(ctx.env.DB)
+ const marked = await queries.communityMessageMark.isMessageMarked(
+ db,
+ ctx.userId,
+ messageId,
+ )
+
+ return writeJSON({ marked })
+})
diff --git a/src/web/src/app/api/community/marks/route.test.ts b/src/web/src/app/api/community/marks/route.test.ts
new file mode 100644
index 000000000..44fb92b70
--- /dev/null
+++ b/src/web/src/app/api/community/marks/route.test.ts
@@ -0,0 +1,111 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockMarkMessage = vi.fn()
+const mockGetMessage = vi.fn()
+const mockRequireChannelMember = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityMessageMark: {
+ markMessage: (...args: unknown[]) => mockMarkMessage(...args),
+ },
+ communityMessage: {
+ getMessage: (...args: unknown[]) => mockGetMessage(...args),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/community/permissions", () => ({
+ requireChannelMember: (...args: unknown[]) => mockRequireChannelMember(...args),
+}))
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { POST } from "./route"
+
+function postReq(body: unknown) {
+ return new NextRequest("http://localhost/api/community/marks", {
+ method: "POST",
+ body: JSON.stringify(body),
+ })
+}
+
+describe("POST /api/community/marks", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockRequireChannelMember.mockResolvedValue({ ok: true, value: { id: "c1" } })
+ mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1" })
+ mockMarkMessage.mockResolvedValue(undefined)
+ })
+
+ it("marks a visible message for the current user, self-scoped to ctx.userId", async () => {
+ const res = await POST(postReq({ channelId: "c1", messageId: "m1" }))
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ ok: true })
+ expect(mockMarkMessage).toHaveBeenCalledWith({}, {
+ userId: "u1",
+ channelId: "c1",
+ messageId: "m1",
+ })
+ })
+
+ it("is idempotent — a re-mark still returns ok (markMessage no-ops on conflict)", async () => {
+ // markMessage uses onConflictDoNothing, so the route does not 409; the
+ // second call is a plain ok, unlike pins which 409 on duplicate.
+ await POST(postReq({ channelId: "c1", messageId: "m1" }))
+ const res = await POST(postReq({ channelId: "c1", messageId: "m1" }))
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ ok: true })
+ })
+
+ it("404s when the message does not belong to the claimed channel", async () => {
+ mockGetMessage.mockResolvedValue({ id: "m1", channelId: "other" })
+ const res = await POST(postReq({ channelId: "c1", messageId: "m1" }))
+ expect(res.status).toBe(404)
+ expect(mockMarkMessage).not.toHaveBeenCalled()
+ })
+
+ it("404s when the message does not exist", async () => {
+ mockGetMessage.mockResolvedValue(null)
+ const res = await POST(postReq({ channelId: "c1", messageId: "m1" }))
+ expect(res.status).toBe(404)
+ expect(mockMarkMessage).not.toHaveBeenCalled()
+ })
+
+ it("forwards the channel-membership gate — a non-member cannot mark", async () => {
+ mockRequireChannelMember.mockResolvedValue({ ok: false, error: "forbidden", status: 403 })
+ const res = await POST(postReq({ channelId: "c1", messageId: "m1" }))
+ expect(res.status).toBe(403)
+ expect(mockGetMessage).not.toHaveBeenCalled()
+ expect(mockMarkMessage).not.toHaveBeenCalled()
+ })
+
+ it("400s on missing messageId or channelId", async () => {
+ expect((await POST(postReq({ channelId: "c1" }))).status).toBe(400)
+ expect((await POST(postReq({ messageId: "m1" }))).status).toBe(400)
+ })
+})
diff --git a/src/web/src/app/api/community/marks/route.ts b/src/web/src/app/api/community/marks/route.ts
new file mode 100644
index 000000000..9a07f0fc6
--- /dev/null
+++ b/src/web/src/app/api/community/marks/route.ts
@@ -0,0 +1,42 @@
+import { NextRequest } from "next/server"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeJSON, writeError } from "@/lib/middleware/helpers"
+import { getDb } from "@/lib/db"
+import { queries } from "@alook/shared"
+import { requireChannelMember } from "@/lib/community/permissions"
+
+// Toggle-on: mark a message for the current user. Self-scoped — the mark row is
+// always keyed to ctx.userId, never a body-supplied id. Idempotent: a re-mark
+// hits UNIQUE(userId, messageId) and no-ops (markMessage uses
+// onConflictDoNothing), so the client can call it without a 409 dance.
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ const db = getDb(ctx.env.DB)
+
+ let body: { channelId?: string; messageId?: string }
+ try {
+ body = await req.json()
+ } catch {
+ return writeError("invalid request body", 400)
+ }
+ if (!body.messageId) return writeError("missing messageId", 400)
+ if (!body.channelId) return writeError("missing channelId", 400)
+
+ // You can only mark a message you can see — gate on channel membership.
+ const auth = await requireChannelMember(db, body.channelId, ctx.userId)
+ if (!auth.ok) return writeError(auth.error, auth.status)
+
+ // The target message must belong to the channel the caller claims — prevents
+ // marking a message via a channel the caller can see but the message isn't in.
+ const target = await queries.communityMessage.getMessage(db, body.messageId)
+ if (!target || target.channelId !== body.channelId) {
+ return writeError("message not found", 404)
+ }
+
+ await queries.communityMessageMark.markMessage(db, {
+ userId: ctx.userId,
+ channelId: body.channelId,
+ messageId: body.messageId,
+ })
+
+ return writeJSON({ ok: true })
+})
diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
index aa2ee58af..a2edd3e1d 100644
--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
@@ -53,6 +53,7 @@ import {
useToggleReactionApi,
usePinMessage,
useUnpinMessage,
+ useToggleMark,
useCreateThread,
useCreateForumPost,
useUpdatePostTags,
@@ -445,6 +446,7 @@ function ChannelView() {
const toggleReactionApi = useToggleReactionApi()
const { mutate: pinMessageMutate } = usePinMessage()
const { mutate: unpinMessageMutate } = useUnpinMessage()
+ const toggleMark = useToggleMark()
const { mutateAsync: createThreadAsync } = useCreateThread()
const createForumPostMut = useCreateForumPost()
const updatePostTagsMut = useUpdatePostTags()
@@ -680,6 +682,23 @@ function ChannelView() {
return () => useCommunityStore.getState().registerUiHandlers({ jumpToSeq: undefined, openMessageContext: undefined })
}, [jumpToSeq, openMessageContext])
+ // Marked-tab (and any cross-channel) deep-link: a `?seq=<n>` on the URL opens
+ // the context sheet on that message. Unlike the `?msg=` mount-anchor path,
+ // this is an EFFECT keyed on the seq param — so it fires even when navigating
+ // to an ALREADY-MOUNTED channel page (Next reuses the component, so a
+ // mount-once useState read would miss the new param). The sheet reads by
+ // (channelId, seq) and cold-fetches its own window, so the target row need
+ // not be in the loaded list. We strip the param right after so a refresh/back
+ // doesn't re-open it, and re-arm cleanly for the next jump.
+ const seqParam = searchParams.get("seq")
+ useEffect(() => {
+ if (!seqParam) return
+ const seq = Number(seqParam)
+ if (!Number.isFinite(seq)) return
+ setContextTarget({ serverId, channelId, label: channelName, seq })
+ router.replace(`/c/channels/${params.serverId}/${channelId}`, { scroll: false })
+ }, [seqParam, serverId, channelId, channelName, router, params.serverId])
+
// Stable so it doesn't bust the memoized message rows; reads uiHandlers
// lazily through the actions ref (assigned just below).
const openProfile = useCallback<OpenProfile>((name, e, discriminator, userId) => {
@@ -762,6 +781,7 @@ function ChannelView() {
setRightPanel("pinned")
}
},
+ onMark: (id: string) => toggleMark(channelId, id),
onCreateThread: async (id: string) => {
const m = actionsCtxRef.current.messages.find((x) => x.id === id)
const name = deriveThreadName(m?.content, actionsCtxRef.current.channelName)
@@ -802,7 +822,7 @@ function ChannelView() {
// reads go through actionsCtxRef. This stability is load-bearing: an unstable
// messageActions busts MessageRow/Message's memo and re-renders every visible
// row on every commit (see message.tsx messagePropsEqual).
- }), [channelId, currentUser.id, toggleReactionApi, unpinMessageMutate, pinMessageMutate, createThreadAsync, doSend, router, params.serverId])
+ }), [channelId, currentUser.id, toggleReactionApi, unpinMessageMutate, pinMessageMutate, toggleMark, createThreadAsync, doSend, router, params.serverId])
const threadActions = useMemo(
() => ({ ...messageActions, onCreateThread: undefined }),
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index 3c79eb677..ab29ed3df 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -1,7 +1,7 @@
"use client"
import { useCallback, useEffect, useMemo, useState } from "react"
-import { useParams } from "next/navigation"
+import { useParams, useSearchParams } from "next/navigation"
import { toast } from "sonner"
import { toastApiError } from "@/lib/api/client"
import { useBreakpoint } from "@/hooks/use-mobile"
@@ -33,6 +33,7 @@ import {
useSendDmMessage,
useToggleReactionApi,
useUploadFile,
+ useToggleMark,
zipUploadResultsWithDimensions,
sendNonce,
} from "@/hooks/community/mutations"
@@ -106,7 +107,18 @@ function DmView() {
: (readSnapshot?.lastReadMessageId ?? null),
})
- const [contextSheetSeq, setContextSheetSeq] = useState<number | null>(null)
+ // Cross-navigation deep-link: a Marked-tab row for a DM message navigates
+ // here with `?seq=<n>` and we open the context sheet on that message. Read
+ // once at mount (frozen), mirroring the channel page's `?msg=` — a
+ // refresh/back doesn't re-trigger it. The DM view has no in-place scroll
+ // anchor, so the context sheet (seq → id + surrounding window) is the jump.
+ const searchParams = useSearchParams()
+ const [initialSeq] = useState<number | null>(() => {
+ const raw = searchParams.get("seq")
+ const n = raw ? Number(raw) : NaN
+ return Number.isFinite(n) ? n : null
+ })
+ const [contextSheetSeq, setContextSheetSeq] = useState<number | null>(initialSeq)
// DM composer has no "current server" — flatten every member server's
// channels into one cross-server candidate list so a `/`-ref can be
// dropped into a DM (see plan community-channel-ref.md §6).
@@ -183,6 +195,7 @@ function DmView() {
const sendDmMessage = useSendDmMessage()
const toggleReaction = useToggleReactionApi()
const uploadFile = useUploadFile()
+ const toggleMark = useToggleMark()
const goBack = useCallback(() => { uiHandlers.goBackMobile?.() }, [uiHandlers])
@@ -254,6 +267,8 @@ function DmView() {
const m = messages.find((x) => x.id === id)
if (m?.content) { navigator.clipboard?.writeText(m.content); toast("Copied to clipboard") }
},
+ // A DM is a channel (type='dm'), so its id IS the mark route's channelId.
+ onMark: (id: string) => toggleMark(dmId, id),
onRetry: (id: string) => {
const m = messages.find((x) => x.id === id)
if (m?.content) {
@@ -281,7 +296,7 @@ function DmView() {
a.download = url.split("/").pop() ?? "file"
a.click()
},
- }), [toggleReaction, dmId, currentUser.id, currentUser.name, currentUser.avatar, messages, sendDmMessage, uiHandlers])
+ }), [toggleReaction, toggleMark, dmId, currentUser.id, currentUser.name, currentUser.avatar, messages, sendDmMessage, uiHandlers])
// DM endpoint ignores mentionType. Replies are supported — the backend
// persists replyToId for DMs too.
@@ -371,6 +386,7 @@ function DmView() {
onReact={dmBlocked ? undefined : messageActions.onReact}
onReply={dmBlocked ? undefined : messageActions.onReply}
onCopy={messageActions.onCopy}
+ onMark={dmBlocked ? undefined : messageActions.onMark}
onRetry={dmBlocked ? undefined : messageActions.onRetry}
onPreviewImage={messageActions.onPreviewImage}
onDownloadFile={messageActions.onDownloadFile}
diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.ts
index 5900eed13..1f06ad547 100644
--- a/src/web/src/components/community/_types.ts
+++ b/src/web/src/components/community/_types.ts
@@ -298,6 +298,27 @@ export type Mention = {
m: Msg
}
+// A single per-user saved ("marked") message, as returned by
+// `/api/community/inbox/marked`. Cross-channel newest-first — each row carries
+// the serverId + channelId + seq needed to deep-link back to the message
+// (unlike a Mention, which only opens the channel, a Marked row jumps to the
+// exact message via the `?msg=<id>` deep-link). `id` is the mark row's own id,
+// used to unmark from the list.
+export type Marked = {
+ id: string // the mark row id (for DELETE / list removal)
+ // A DM has no server: `serverId` is null and `server` may be the peer's name
+ // or empty. The null serverId is the discriminator the jump uses — server
+ // rows deep-link via `?msg=`, DM rows navigate to `/c/me/<channelId>` and
+ // open the context sheet.
+ server: string
+ serverId: string | null
+ channel: string
+ // For a server message this is the channel id; for a DM it's the DM channel
+ // id, which is also the frontend `/c/me/<id>` route param.
+ channelId: string
+ m: Msg
+}
+
// A single unread thread / forum-post nested under its parent channel.
type UnreadChild = {
channelId: string
diff --git a/src/web/src/components/community/community-inbox-popover.tsx b/src/web/src/components/community/community-inbox-popover.tsx
index 5dcc226a4..9e575005f 100644
--- a/src/web/src/components/community/community-inbox-popover.tsx
+++ b/src/web/src/components/community/community-inbox-popover.tsx
@@ -1,12 +1,14 @@
-import { ChevronRight, Inbox, MoreHorizontal, Trash2 } from "lucide-react"
+import { Bookmark, ChevronRight, Inbox, MoreHorizontal, Trash2 } from "lucide-react"
import { stripInlineMarkup } from "@alook/shared"
import { EntityIcon } from "./entity-icon"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"
import { Skeleton } from "@/components/ui/skeleton"
import { Avatar } from "./avatar"
+import { ChannelIcon } from "./channel-icon"
import { EmptyState } from "./empty-state"
-import type { Mention, UnreadDm, UnreadServer } from "./_types"
+import { formatRelativeTime } from "./format-time"
+import type { Marked, Mention, UnreadDm, UnreadServer } from "./_types"
function MentionBadge({ count }: { count: number }) {
if (count <= 0) return null
@@ -98,7 +100,7 @@ function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention }: {
<div className="text-sm">
<span className="font-medium">{mn.m.authorName}</span>{" "}
<span className="text-xs text-muted-foreground">
- {mn.kind === "reply" ? "replied to you" : "mentioned you"} in {mn.server} · #{mn.channel}
+ {mn.kind === "reply" ? "replied to you" : "mentioned you"} in {mn.server} · <ChannelIcon className="inline h-[1em] w-auto align-[-0.1em]" />{mn.channel}
</span>
</div>
<div className="truncate text-sm text-muted-foreground">{stripInlineMarkup(mn.m.content ?? "")}</div>
@@ -123,31 +125,94 @@ function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention }: {
)
}
+function MarkedTab({ marked, loading, onOpenMarked, onUnmark }: {
+ marked: Marked[]
+ loading?: boolean
+ onOpenMarked?: (m: Marked) => void
+ onUnmark?: (messageId: string) => void
+}) {
+ return (
+ <div className="h-full overflow-y-auto thin-scrollbar p-3">
+ {loading && marked.length === 0 && <InboxRowsSkeleton />}
+ {!loading && marked.length === 0 && <EmptyState icon={Bookmark} label="No marked messages" />}
+ {marked.map((mk) => (
+ <div key={mk.id} className="group flex w-full items-start gap-3 rounded-md p-2 text-left hover:bg-accent">
+ <button onClick={() => onOpenMarked?.(mk)} className="flex min-w-0 flex-1 items-start gap-3 text-left">
+ <Avatar label={mk.m.authorAvatar ?? "?"} seed={mk.m.authorId} size={36} />
+ <div className="min-w-0 flex-1">
+ <div className="text-sm">
+ <span className="font-medium">{mk.m.authorName}</span>{" "}
+ <span className="text-xs text-muted-foreground">
+ in{" "}
+ {mk.serverId
+ ? <>{mk.server} · <ChannelIcon className="inline h-[1em] w-auto align-[-0.1em]" />{mk.channel}</>
+ : "DM"}
+ {mk.m.createdAt && <> · {formatRelativeTime(mk.m.createdAt)}</>}
+ </span>
+ </div>
+ <div className="truncate text-sm text-muted-foreground">{stripInlineMarkup(mk.m.content ?? "")}</div>
+ </div>
+ </button>
+ {onUnmark && (
+ <DropdownMenu>
+ <DropdownMenuTrigger render={<button className="mt-1 grid size-6 shrink-0 place-items-center rounded-md text-muted-foreground opacity-0 hover:bg-accent hover:text-foreground group-hover:opacity-100" aria-label="More" />}>
+ <MoreHorizontal className="size-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" sideOffset={4} className="w-36">
+ <DropdownMenuItem onClick={() => onUnmark(mk.m.id)}>
+ <Trash2 className="size-4" />
+ Unmark
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ ))}
+ </div>
+ )
+}
+
export function InboxPopover({
unreads,
unreadDms,
mentions,
+ marked,
+ markedLoading,
loading,
onOpenChannel,
onOpenDm,
onOpenMention,
+ onOpenMarked,
onDeleteMention,
+ onUnmark,
+ onMarkedTabSelected,
onMarkAllRead,
}: {
unreads: UnreadServer[]
unreadDms: UnreadDm[]
mentions: Mention[]
+ marked: Marked[]
+ markedLoading?: boolean
loading?: boolean
onOpenChannel?: (serverId: string, channelId: string) => void
onOpenDm?: (dmId: string) => void
onOpenMention?: (m: Mention) => void
+ onOpenMarked?: (m: Marked) => void
onDeleteMention?: (id: string) => void
+ onUnmark?: (messageId: string) => void
+ // Fired when the Marked tab becomes active — the shell uses this to enable
+ // the (lazy) marked-feed query only once the viewer actually opens the tab.
+ onMarkedTabSelected?: () => void
onMarkAllRead?: () => void
}) {
const hasUnreads = unreads.length > 0 || unreadDms.length > 0
const hasAnything = hasUnreads || mentions.length > 0
return (
- <Tabs defaultValue="unreads" className="flex h-112 flex-col">
+ <Tabs
+ defaultValue="unreads"
+ onValueChange={(v) => { if (v === "marked") onMarkedTabSelected?.() }}
+ className="flex h-112 flex-col"
+ >
<div className="flex items-center gap-2 px-3 pt-4">
<Inbox className="size-5" />
<h2 className="flex-1 text-lg font-semibold">Inbox</h2>
@@ -174,6 +239,7 @@ export function InboxPopover({
{mentions.length > 0 && <span className="size-1.5 rounded-full bg-primary" />}
</span>
</TabsTrigger>
+ <TabsTrigger value="marked">Marked</TabsTrigger>
</TabsList>
<TabsContent value="unreads" className="min-h-0 flex-1">
<UnreadsTab servers={unreads} dms={unreadDms} loading={loading} onOpenChannel={onOpenChannel} onOpenDm={onOpenDm} />
@@ -181,6 +247,9 @@ export function InboxPopover({
<TabsContent value="mentions" className="min-h-0 flex-1">
<MentionsTab mentions={mentions} loading={loading} onOpenMention={onOpenMention} onDeleteMention={onDeleteMention} />
</TabsContent>
+ <TabsContent value="marked" className="min-h-0 flex-1">
+ <MarkedTab marked={marked} loading={markedLoading} onOpenMarked={onOpenMarked} onUnmark={onUnmark} />
+ </TabsContent>
</Tabs>
)
}
diff --git a/src/web/src/components/community/message-context-sheet.tsx b/src/web/src/components/community/message-context-sheet.tsx
index fc8970fce..926257c9e 100644
--- a/src/web/src/components/community/message-context-sheet.tsx
+++ b/src/web/src/components/community/message-context-sheet.tsx
@@ -17,7 +17,7 @@ import { formatDateLabel } from "./format-time"
import { DateDivider } from "./dividers"
import { useCurrentUser } from "@/contexts/community/current-user"
import { useUiHandlers } from "@/stores/community"
-import { usePinMessage, useUnpinMessage, useCreateThread } from "@/hooks/community/mutations"
+import { usePinMessage, useUnpinMessage, useCreateThread, useToggleMark } from "@/hooks/community/mutations"
import type { Msg, OpenProfile, Reaction, RenderMsg } from "./_types"
import type { MessagesPage } from "@/hooks/community/use-messages"
@@ -158,6 +158,7 @@ export function MessageContextSheet({
const pinMessageMut = usePinMessage()
const unpinMessageMut = useUnpinMessage()
const createThreadMut = useCreateThread()
+ const toggleMark = useToggleMark()
const queryKey = useMemo(
() => ["messageContext", type, channelId, targetSeq] as const,
@@ -252,6 +253,13 @@ export function MessageContextSheet({
onReply({ id: m.id, authorName: m.authorName ?? "", text: m.content ?? "" })
}, [findMessage, onReply])
+ // Mark works for both channel and DM (unlike pin) — the sheet's channelId is
+ // the mark route's channelId for either. `useToggleMark` reads the per-message
+ // marked cache (populated when this row's menu opened) to pick POST vs DELETE.
+ const onMarkId = useCallback((id: string) => {
+ toggleMark(channelId, id)
+ }, [toggleMark, channelId])
+
const onPinId = useCallback((id: string) => {
if (type === "dm") return
const isPinned = pinnedIds?.has(id)
@@ -420,6 +428,7 @@ export function MessageContextSheet({
onReply={onReply ? onReplyId : undefined}
onCopy={onCopyId}
onPin={type === "channel" ? onPinId : undefined}
+ onMark={onMarkId}
onCreateThread={type === "channel" ? onCreateThreadId : undefined}
onPreviewImage={onPreviewImage}
onDownloadFile={onDownloadFile}
@@ -444,6 +453,7 @@ function ContextRows({
onReply,
onCopy,
onPin,
+ onMark,
onCreateThread,
onPreviewImage,
onDownloadFile,
@@ -460,6 +470,7 @@ function ContextRows({
onReply?: (id: string) => void
onCopy: (id: string) => void
onPin?: (id: string) => void
+ onMark?: (id: string) => void
onCreateThread?: (id: string) => void
onPreviewImage: (url: string) => void
onDownloadFile: (url: string) => void
@@ -501,6 +512,7 @@ function ContextRows({
onReactId={onReact}
onReplyId={onReply}
onPinId={onPin}
+ onMarkId={onMark}
onCreateThreadId={onCreateThread}
onCopyId={onCopy}
onPreviewImage={onPreviewImage}
diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsx
index af1232227..1a7107d7b 100644
--- a/src/web/src/components/community/message-list.tsx
+++ b/src/web/src/components/community/message-list.tsx
@@ -21,7 +21,7 @@ import type { Msg, OpenProfile } from "./_types"
export function MessageList({
channel, messages, loading, pinnedIds, newDividerBefore, typingUsers, onOpenThread, onOpenProfile,
onToggleReaction, onReact,
- onReply, onPin, onCreateThread, onCopy, onRetry, onPreviewImage, onDownloadFile,
+ onReply, onPin, onMark, onCreateThread, onCopy, onRetry, onPreviewImage, onDownloadFile,
resolveUserName, scrollToMessageId, hero, variant = "channel", onScrollRoot, viewerUserId, initialScrollReady = true,
hasMore, isFetchingOlder, onLoadOlder,
hasMoreNewer, isFetchingNewer, onLoadNewer, onJumpToPresent, unreadCount, onOpenContextSheet,
@@ -38,6 +38,7 @@ export function MessageList({
onReact?: (id: string, emoji: string) => void
onReply?: (id: string) => void
onPin?: (id: string) => void
+ onMark?: (id: string) => void
onCreateThread?: (id: string) => void
onCopy?: (id: string) => void
onRetry?: (id: string) => void
@@ -452,6 +453,7 @@ export function MessageList({
onReactId={onReact}
onReplyId={onReply}
onPinId={onPin}
+ onMarkId={onMark}
onCreateThreadId={onCreateThread}
onCopyId={onCopy}
onRetryId={onRetry}
diff --git a/src/web/src/components/community/message-menu.test.ts b/src/web/src/components/community/message-menu.test.ts
index 2c3ee23be..3d8748302 100644
--- a/src/web/src/components/community/message-menu.test.ts
+++ b/src/web/src/components/community/message-menu.test.ts
@@ -44,4 +44,30 @@ describe("messageMenuItems", () => {
expect(labels).toEqual(["Add Reaction", "Reply", "Create Thread", "Pin Message", "Copy Text", "Share as Image"])
expect(labels).not.toContain("sep")
})
+
+ it("includes Mark only when onMark is provided, and toggles label on `marked`", () => {
+ expect(messageMenuItems({}).some((it) => it.label === "Mark")).toBe(false)
+ // Unmarked (or state not yet resolved) → "Mark"; text-only like Pin.
+ const mark = messageMenuItems({ onMark: () => {} })
+ expect(mark.some((it) => it.label === "Mark")).toBe(true)
+ expect(mark.find((it) => it.label === "Mark")?.icon).toBeUndefined()
+ // Already marked → "Unmark".
+ const unmark = messageMenuItems({ onMark: () => {}, marked: true })
+ expect(unmark.some((it) => it.label === "Unmark")).toBe(true)
+ expect(unmark.some((it) => it.label === "Mark")).toBe(false)
+ })
+
+ it("wires the Mark/Unmark onClick to the same onMark handler", () => {
+ const onMark = vi.fn()
+ messageMenuItems({ onMark }).find((it) => it.label === "Mark")?.onClick?.()
+ messageMenuItems({ onMark, marked: true }).find((it) => it.label === "Unmark")?.onClick?.()
+ expect(onMark).toHaveBeenCalledTimes(2)
+ })
+
+ it("orders Mark right after Pin (both text-only, before Copy)", () => {
+ const labels = messageMenuItems({
+ onReply: () => {}, onPin: () => {}, onMark: () => {}, onCopy: () => {},
+ }).map((it) => it.label)
+ expect(labels).toEqual(["Reply", "Pin Message", "Mark", "Copy Text"])
+ })
})
diff --git a/src/web/src/components/community/message-menu.tsx b/src/web/src/components/community/message-menu.tsx
index fed9bde64..3f9309240 100644
--- a/src/web/src/components/community/message-menu.tsx
+++ b/src/web/src/components/community/message-menu.tsx
@@ -25,6 +25,8 @@ export function messageMenuItems(handlers: {
onReply?: () => void
onPin?: () => void
pinned?: boolean
+ onMark?: () => void
+ marked?: boolean
onCreateThread?: () => void
onCopy?: () => void
onShare?: () => void
@@ -38,6 +40,12 @@ export function messageMenuItems(handlers: {
if (handlers.onPin) items.push(handlers.pinned
? { label: "Unpin Message", onClick: handlers.onPin }
: { label: "Pin Message", onClick: handlers.onPin })
+ // Text-only like Pin. `marked` may still be resolving when the menu opens
+ // (lazy single-row read) — it defaults to false, so the label reads "Mark"
+ // and silently flips to "Unmark" once the read lands (no spinner, per Alli).
+ if (handlers.onMark) items.push(handlers.marked
+ ? { label: "Unmark", onClick: handlers.onMark }
+ : { label: "Mark", onClick: handlers.onMark })
if (handlers.onCopy) items.push({ label: "Copy Text", onClick: handlers.onCopy })
if (handlers.onShare) items.push({ label: "Share as Image", icon: Share, onClick: handlers.onShare })
return items
diff --git a/src/web/src/components/community/message-row.tsx b/src/web/src/components/community/message-row.tsx
index 53cc879e3..e97264d32 100644
--- a/src/web/src/components/community/message-row.tsx
+++ b/src/web/src/components/community/message-row.tsx
@@ -25,6 +25,7 @@ export interface MessageRowProps {
onReactId?: (id: string, emoji: string) => void
onReplyId?: (id: string) => void
onPinId?: (id: string) => void
+ onMarkId?: (id: string) => void
onCreateThreadId?: (id: string) => void
onCopyId?: (id: string) => void
onRetryId?: (id: string) => void
@@ -48,7 +49,7 @@ export interface MessageRowProps {
function MessageRowImpl(props: MessageRowProps) {
const {
m, pinned, highlighted, onOpenThread, onOpenProfile,
- onToggleReactionId, onReactId, onReplyId, onPinId, onCreateThreadId,
+ onToggleReactionId, onReactId, onReplyId, onPinId, onMarkId, onCreateThreadId,
onCopyId, onRetryId, onJumpToId, onPreviewImage, onDownloadFile,
resolveUserName, onImageLoad,
selectMode, selected, onToggleSelectId, onEnterSelectId, onShareSingleId,
@@ -66,6 +67,7 @@ function MessageRowImpl(props: MessageRowProps) {
const onReact = useCallback((emoji: string) => onReactId?.(id, emoji), [onReactId, id])
const onReply = useCallback(() => onReplyId?.(id), [onReplyId, id])
const onPin = useCallback(() => onPinId?.(id), [onPinId, id])
+ const onMark = useCallback(() => onMarkId?.(id), [onMarkId, id])
const onCreateThread = useCallback(() => onCreateThreadId?.(id), [onCreateThreadId, id])
const onCopy = useCallback(() => onCopyId?.(id), [onCopyId, id])
const onRetry = useCallback(() => onRetryId?.(id), [onRetryId, id])
@@ -91,6 +93,7 @@ function MessageRowImpl(props: MessageRowProps) {
onReact={onReactId ? onReact : undefined}
onReply={onReplyId ? onReply : undefined}
onPin={onPinId ? onPin : undefined}
+ onMark={onMarkId ? onMark : undefined}
onCreateThread={onCreateThreadId ? onCreateThread : undefined}
onCopy={onCopyId ? onCopy : undefined}
onRetry={onRetryId ? onRetry : undefined}
diff --git a/src/web/src/components/community/message.render.test.ts b/src/web/src/components/community/message.render.test.ts
index 894f5c525..4ae9cc717 100644
--- a/src/web/src/components/community/message.render.test.ts
+++ b/src/web/src/components/community/message.render.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
import React from "react"
import TestRenderer, { act } from "react-test-renderer"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { Message } from "./message"
import type { RenderMsg } from "./_types"
@@ -32,11 +33,18 @@ const genericMock = {
}
let renderCount = 0
-// A probe that counts how many times the body content actually renders by
-// wrapping the memoized Message; we detect bail-out by rendering Message with a
-// spy callback that increments on each real render via a child sentinel.
+// Message consumes query context (the lazy Mark/Unmark state read), so every
+// render tree is wrapped in a provider. A single shared client keeps the
+// wrapper element type stable across `.update()` so the memo behavior under
+// test isn't disturbed. Retries off + no network — the query stays idle
+// (`enabled` only flips true once a menu opens, which these trees don't do).
+const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
function makeTree(props: Parameters<typeof Message>[0]) {
- return React.createElement(Message, props)
+ return React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Message, props),
+ )
}
beforeEach(() => {
diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsx
index a200ea759..3022c4234 100644
--- a/src/web/src/components/community/message.tsx
+++ b/src/web/src/components/community/message.tsx
@@ -1,6 +1,7 @@
"use client"
import { memo, useState } from "react"
+import { useMessageMarked } from "@/hooks/community/use-inbox"
import type React from "react"
import {
MessagesSquare, UserPlus, SmilePlus, Reply,
@@ -47,7 +48,7 @@ export function messageCanShare(m: RenderMsg, compact?: boolean): boolean {
function MessageImpl({
m, compact, pinned, onOpenThread, onOpenProfile, onJumpReply,
- onToggleReaction, onReact, onReply, onPin, onCreateThread, onCopy, onRetry,
+ onToggleReaction, onReact, onReply, onPin, onMark, onCreateThread, onCopy, onRetry,
onPreviewImage, onDownloadFile, highlighted, resolveUserName, onImageLoad,
selectMode, selected, onToggleSelect, onEnterSelect, onShareSingle,
}: {
@@ -61,6 +62,10 @@ function MessageImpl({
onReact?: (emoji: string) => void
onReply?: () => void
onPin?: () => void
+ // Toggle this message in the viewer's private saved ("marked") set. The
+ // Mark/Unmark label is driven by a lazy per-message read (see `marked`
+ // below), so a channel never pre-loads mark state for every row.
+ onMark?: () => void
onCreateThread?: () => void
onCopy?: () => void
onRetry?: () => void
@@ -86,6 +91,16 @@ function MessageImpl({
}) {
// keep the hover toolbar pinned open while its ⋯ dropdown is open
const [toolbarOpen, setToolbarOpen] = useState(false)
+ // Right-click context-menu open state — tracked so the Mark/Unmark label's
+ // lazy read fires for the context menu too, not just the ⋯ dropdown.
+ const [contextOpen, setContextOpen] = useState(false)
+ // The Mark/Unmark label needs to know if THIS message is already in the
+ // viewer's saved set. That's a single indexed row read, fired lazily only
+ // while a menu that shows the item is open (never per-row on mount) — so a
+ // channel scroll doesn't pre-load mark state for every row. Defaults to
+ // "Mark"; flips to "Unmark" silently once the read resolves (no spinner).
+ const markMenuOpen = (toolbarOpen || contextOpen) && !!onMark
+ const { data: markedData } = useMessageMarked(m.id, markMenuOpen)
// Lazy-mount the row's Base UI overlay roots (ContextMenu / DropdownMenu /
// EmojiPicker Popover / reaction Tooltips). Eagerly mounting them per visible
// row was the bulk of the switch re-render storm (FloatingTree/MenuRoot ×1000s
@@ -112,6 +127,7 @@ function MessageImpl({
const menuHandlers = {
onAddReaction: onReact ? () => onReact("👍") : undefined,
onReply, onPin, pinned,
+ onMark, marked: markedData?.marked ?? false,
onCreateThread: m.thread ? undefined : onCreateThread,
onCopy,
// Share: enter multi-select (main list) if wired, else direct single-share
@@ -418,7 +434,7 @@ function MessageImpl({
// In select mode the row is a toggle target — no context menu / toolbar.
if (!interactive || !activated || selectMode) return row
return (
- <ContextMenu>
+ <ContextMenu onOpenChange={setContextOpen}>
<ContextMenuTrigger className="select-text" render={row} />
<ContextMenuContent className="w-48">
<MessageContextItems {...menuHandlers} />
@@ -472,6 +488,7 @@ function messagePropsEqual(prev: MessageProps, next: MessageProps): boolean {
prev.onReact === next.onReact &&
prev.onReply === next.onReply &&
prev.onPin === next.onPin &&
+ prev.onMark === next.onMark &&
prev.onCreateThread === next.onCreateThread &&
prev.onCopy === next.onCopy &&
prev.onRetry === next.onRetry &&
diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsx
index cd97cb1b2..110d68705 100644
--- a/src/web/src/components/community/shell-frame.tsx
+++ b/src/web/src/components/community/shell-frame.tsx
@@ -23,7 +23,7 @@ import { ProfileCard } from "./profile-card"
import { ImageLightbox } from "./image-lightbox"
import { ImageCropDialog } from "./image-crop-dialog"
import { validateIconSourceFile } from "@/lib/community/image-crop"
-import type { MobileZone, Profile, View } from "./_types"
+import type { Marked, MobileZone, Profile, View } from "./_types"
import { resolveProfileTarget, buildSelfProfile } from "./profile-lookup"
import { resolveProfilePresence } from "@/lib/community/presence"
import { avatarInitial } from "@/lib/community/avatar"
@@ -36,7 +36,7 @@ import { useServers } from "@/hooks/community/use-servers"
import { useFolders } from "@/hooks/community/use-folders"
import { useFriends } from "@/hooks/community/use-friends"
import { useServerMembers } from "@/hooks/community/use-server-members"
-import { useInboxUnreads, useInboxMentions } from "@/hooks/community/use-inbox"
+import { useInboxUnreads, useInboxMentions, useInboxMarked } from "@/hooks/community/use-inbox"
import { useInboxAutoCollapse } from "@/hooks/community/use-inbox-auto-collapse"
import {
useCreateServer,
@@ -51,6 +51,7 @@ import {
useCreateOrGetDm,
useMarkAllInboxRead,
useDeleteMention,
+ useUnmarkMessage,
useUpdateProfile,
useSendDmMessage,
useUploadUserAvatar,
@@ -113,6 +114,13 @@ export function ShellFrame({
const unreadDms = inboxUnreads.dms
const mentions = inboxMentions.mentions
const inboxLoading = inboxUnreads.isLoading || inboxMentions.isLoading
+ // Marked feed is lazy: it has no bell badge, so it only fetches once the
+ // viewer opens the Marked tab. `markedTabOpened` latches true on first open
+ // (the query then lives normally under communityKeys.inboxMarked()).
+ const [markedTabOpened, setMarkedTabOpened] = useState(false)
+ const inboxMarked = useInboxMarked(markedTabOpened)
+ const marked = inboxMarked.marked
+ const { mutate: unmarkMessageMutate } = useUnmarkMessage()
// Popover open-state + auto-collapse: the inbox closes itself once the row
// the viewer clicked leaves the list. See use-inbox-auto-collapse.
const inbox = useInboxAutoCollapse({ unreads: unreadFeed, unreadDms, mentions })
@@ -496,6 +504,27 @@ export function ShellFrame({
[router, watchInboxItem],
)
+ // A Marked row is cross-channel — clicking one navigates to the message's
+ // channel AND opens the context sheet on it (Gus: always land on the channel
+ // so you see WHERE the message lives, then the sheet shows it + its context;
+ // same feel as a DM row). Both surfaces use the same `?seq=<n>` deep-link the
+ // destination page reads to open its sheet — server rows go to
+ // `/c/channels/<s>/<c>`, DM rows to `/c/me/<channelId>` (a DM channel's id IS
+ // its `/c/me/<id>` route param). serverId (null ⇒ DM) picks the route only.
+ // `watchInboxItem` collapses the popover once the destination opens.
+ const openMarked = useCallback(
+ (mk: Marked) => {
+ watchInboxItem(`marked:${mk.id}`)
+ const seqQuery = mk.m.seq != null ? `?seq=${mk.m.seq}` : ""
+ if (mk.serverId) {
+ router.push(`/c/channels/${mk.serverId}/${mk.channelId}${seqQuery}`)
+ } else {
+ router.push(`/c/me/${mk.channelId}${seqQuery}`)
+ }
+ },
+ [router, watchInboxItem],
+ )
+
const openInboxDm = useCallback(
(dmId: string) => {
// Optimistic clear on `communityKeys.dms()` so the sidebar updates
@@ -521,14 +550,19 @@ export function ShellFrame({
unreads={unreadFeed}
unreadDms={unreadDms}
mentions={mentions}
+ marked={marked}
+ markedLoading={inboxMarked.isLoading}
loading={inboxLoading}
onOpenChannel={openServerChannel}
onOpenDm={openInboxDm}
onOpenMention={(mention) => {
if (mention.serverId && mention.channelId) openServerChannel(mention.serverId, mention.channelId, `mention:${mention.id}`)
}}
+ onOpenMarked={openMarked}
+ onMarkedTabSelected={() => setMarkedTabOpened(true)}
onMarkAllRead={() => { markAllInboxRead.mutate() }}
onDeleteMention={(id) => deleteMention.mutate({ mentionId: id })}
+ onUnmark={(messageId) => unmarkMessageMutate({ messageId })}
/>
)
const inboxHasUnread =
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index 95e3b8489..8b704b85a 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -14,6 +14,7 @@ import { useCommunityStore } from "@/stores/community"
import type { Msg, Attachment } from "@/components/community/_types"
import type { MessagesPage } from "@/hooks/community/use-messages"
import type { PinsResponse } from "@/hooks/community/use-channel-panels"
+import type { MarkedResponse, MessageMarkedResponse } from "@/hooks/community/use-inbox"
import type { MentionType } from "@alook/shared"
import { isBlocked } from "@alook/shared"
@@ -663,6 +664,107 @@ export function useUnpinMessage() {
})
}
+// ── Mark / unmark (per-user saved messages) ──────────────────────────────────
+//
+// mark ≠ pin: a pin is channel-scoped and shared; a mark is the viewer's own
+// private saved-messages set. So these hit a distinct per-user route
+// (`/api/community/marks`, self-scoped by ctx.userId server-side), never the
+// pins route. The ⋯ menu's Mark/Unmark label is driven by `useMessageMarked`
+// (a lazy single-row read on menu-open); these mutations flip that per-message
+// cache optimistically so the label updates instantly, and prune the Marked
+// list on unmark. POST is idempotent server-side (UNIQUE(userId,messageId)).
+
+export type MarkMessageArgs = { channelId: string; messageId: string }
+
+export function useMarkMessage() {
+ const queryClient = useQueryClient()
+ return useMutation<void, Error, MarkMessageArgs, { prev: MessageMarkedResponse | undefined }>({
+ mutationFn: async ({ channelId, messageId }) => {
+ await apiFetch(`/api/community/marks`, {
+ method: "POST",
+ body: JSON.stringify({ channelId, messageId }),
+ })
+ },
+ onMutate: async ({ messageId }) => {
+ const key = communityKeys.messageMarked(messageId)
+ await queryClient.cancelQueries({ queryKey: key })
+ const prev = queryClient.getQueryData<MessageMarkedResponse>(key)
+ queryClient.setQueryData<MessageMarkedResponse>(key, { marked: true })
+ return { prev }
+ },
+ onSuccess: () => {
+ // The Marked list gains a row — refetch it so the tab reflects the new
+ // save next time it's opened (list carries the enriched snapshot + seq
+ // we don't reconstruct locally).
+ void queryClient.invalidateQueries({ queryKey: communityKeys.inboxMarked() })
+ },
+ onError: (err, args, ctx) => {
+ queryClient.setQueryData(communityKeys.messageMarked(args.messageId), ctx?.prev)
+ toastApiError(err, "Failed to mark message")
+ },
+ })
+}
+
+export type UnmarkMessageArgs = { messageId: string }
+
+export function useUnmarkMessage() {
+ const queryClient = useQueryClient()
+ return useMutation<void, Error, UnmarkMessageArgs, {
+ prevMarked: MessageMarkedResponse | undefined
+ prevList: MarkedResponse | undefined
+ }>({
+ mutationFn: async ({ messageId }) => {
+ await apiFetch(`/api/community/marks/${messageId}`, { method: "DELETE" })
+ },
+ onMutate: async ({ messageId }) => {
+ const markedKey = communityKeys.messageMarked(messageId)
+ const listKey = communityKeys.inboxMarked()
+ await queryClient.cancelQueries({ queryKey: markedKey })
+ const prevMarked = queryClient.getQueryData<MessageMarkedResponse>(markedKey)
+ const prevList = queryClient.getQueryData<MarkedResponse>(listKey)
+ queryClient.setQueryData<MessageMarkedResponse>(markedKey, { marked: false })
+ // Drop the row from the Marked list immediately (list rows are keyed by
+ // the message id via `m.id`, mirroring useDeleteMention's optimistic prune).
+ queryClient.setQueryData<MarkedResponse | undefined>(listKey, (prev) =>
+ prev ? { ...prev, marked: prev.marked.filter((mk) => mk.m.id !== messageId) } : prev,
+ )
+ return { prevMarked, prevList }
+ },
+ onError: (err, args, ctx) => {
+ queryClient.setQueryData(communityKeys.messageMarked(args.messageId), ctx?.prevMarked)
+ if (ctx?.prevList) queryClient.setQueryData(communityKeys.inboxMarked(), ctx.prevList)
+ toastApiError(err, "Failed to unmark message")
+ },
+ })
+}
+
+/**
+ * Toggle a message's marked state with one call. Reads the per-message
+ * `messageMarked` cache — populated by `useMessageMarked` when the menu that
+ * fired this action opened — to decide POST (mark) vs DELETE (unmark). If the
+ * read hasn't landed yet (cache miss), defaults to marking, which is safe:
+ * POST is idempotent server-side, so a double-mark is a no-op rather than an
+ * error. Returns a stable callback for the message-actions bundle.
+ */
+export function useToggleMark() {
+ const queryClient = useQueryClient()
+ const { mutate: markMutate } = useMarkMessage()
+ const { mutate: unmarkMutate } = useUnmarkMessage()
+ return useCallback(
+ (channelId: string, messageId: string) => {
+ const cached = queryClient.getQueryData<MessageMarkedResponse>(
+ communityKeys.messageMarked(messageId),
+ )
+ if (cached?.marked) {
+ unmarkMutate({ messageId }, { onSuccess: () => toast("Removed from marked") })
+ } else {
+ markMutate({ channelId, messageId }, { onSuccess: () => toast("Message marked") })
+ }
+ },
+ [queryClient, markMutate, unmarkMutate],
+ )
+}
+
// ── Create thread ──────────────────────────────────────────────────────────
export type CreateThreadArgs = {
diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.ts
index e0083edff..e07e18542 100644
--- a/src/web/src/hooks/community/use-inbox.ts
+++ b/src/web/src/hooks/community/use-inbox.ts
@@ -3,7 +3,7 @@
import { useQuery, keepPreviousData, type UseQueryResult } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
-import type { UnreadServer, UnreadDm, Mention } from "@/components/community/_types"
+import type { UnreadServer, UnreadDm, Mention, Marked } from "@/components/community/_types"
class StaleReadError extends Error {
constructor() { super("stale D1 read"); this.name = "StaleReadError" }
@@ -17,6 +17,7 @@ function throwIfStale<T extends { stale?: boolean }>(v: T): T {
const EMPTY_UNREADS: readonly UnreadServer[] = Object.freeze([])
const EMPTY_DMS: readonly UnreadDm[] = Object.freeze([])
const EMPTY_MENTIONS: readonly Mention[] = Object.freeze([])
+const EMPTY_MARKED: readonly Marked[] = Object.freeze([])
/**
* The inbox popover shows two sibling feeds. Each has its own endpoint and
@@ -70,3 +71,54 @@ export function useInboxMentions(): UseQueryResult<MentionsResponse> & {
mentions: query.data?.mentions ?? (EMPTY_MENTIONS as Mention[]),
}
}
+
+export type MarkedResponse = { marked: Marked[] }
+
+const inboxMarkedQueryFn = () =>
+ apiFetch<MarkedResponse & { stale?: boolean }>("/api/community/inbox/marked").then(throwIfStale)
+
+/**
+ * The Marked feed is lazy — unlike unreads/mentions (which the shell reads
+ * eagerly to drive the bell badge), the Marked tab has no badge and only
+ * matters once the viewer opens it. Pass `enabled` = "is the Marked tab
+ * selected" so the fetch is deferred until then, per the plan's
+ * enabled-gate lazy-load.
+ */
+export function useInboxMarked(enabled: boolean): UseQueryResult<MarkedResponse> & {
+ marked: Marked[]
+} {
+ const query = useQuery({
+ queryKey: communityKeys.inboxMarked(),
+ queryFn: inboxMarkedQueryFn,
+ placeholderData: keepPreviousData,
+ enabled,
+ })
+ return {
+ ...query,
+ marked: query.data?.marked ?? (EMPTY_MARKED as Marked[]),
+ }
+}
+
+export type MessageMarkedResponse = { marked: boolean }
+
+const messageMarkedQueryFn = (messageId: string) => () =>
+ apiFetch<MessageMarkedResponse & { stale?: boolean }>(
+ `/api/community/marks/${messageId}`,
+ ).then(throwIfStale)
+
+/**
+ * Whether the viewer has marked one message — fetched lazily when its ⋯ menu
+ * opens (`enabled` = menu-open) so a channel never pre-loads mark state for
+ * every row. Single indexed row read; the result is cached per message id so
+ * re-opening the same menu doesn't re-query. Drives the Mark/Unmark label —
+ * the menu renders "Mark" first and silently flips to "Unmark" if this
+ * resolves marked (no spinner, per Alli).
+ */
+export function useMessageMarked(messageId: string, enabled: boolean): UseQueryResult<MessageMarkedResponse> {
+ return useQuery({
+ queryKey: communityKeys.messageMarked(messageId),
+ queryFn: messageMarkedQueryFn(messageId),
+ enabled,
+ staleTime: 30_000,
+ })
+}
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index d96cb6900..1b47a8cac 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -94,6 +94,15 @@ export const communityKeys = {
inbox: () => [...communityKeys.all, "inbox"] as const,
inboxUnreads: () => [...communityKeys.inbox(), "unreads"] as const,
inboxMentions: () => [...communityKeys.inbox(), "mentions"] as const,
+ // Per-user saved ("marked") messages, cross-channel newest-first. Nested
+ // under inbox() so the WS reconciliation `invalidateQueries({ queryKey:
+ // communityKeys.inbox() })` refreshes it alongside the other feeds.
+ inboxMarked: () => [...communityKeys.inbox(), "marked"] as const,
+ // Whether the viewer has marked a single message — fetched lazily when the
+ // message's ⋯ menu opens (drives the Mark/Unmark label). Keyed per message
+ // so re-opening the same menu reuses the cached answer.
+ messageMarked: (messageId: string) =>
+ [...communityKeys.all, "message", messageId, "marked"] as const,
// ── Social ──────────────────────────────────────────────────────────────
friends: () => [...communityKeys.all, "friends"] as const,