Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): order forum posts by creation

Gus2c049b4c2bf7
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.ts
index 971869497..ec86767e6 100644
--- a/src/shared/src/db/community-schema.ts
+++ b/src/shared/src/db/community-schema.ts
@@ -8,7 +8,7 @@ import {
primaryKey,
type SQLiteTableWithColumns,
} from "drizzle-orm/sqlite-core";
-import { sql } from "drizzle-orm";
+import { and, desc, eq, isNotNull, sql } from "drizzle-orm";
import { nanoid } from "nanoid";
import { user } from "./schema";
@@ -93,6 +93,9 @@ export const communityChannel: SQLiteTableWithColumns<any> = sqliteTable(
index("idx_channel_server_position").on(t.serverId, t.position),
index("idx_channel_server_last_message").on(t.serverId, t.lastMessageAt),
index("idx_channel_parent").on(t.parentChannelId),
+ index("idx_channel_forum_created")
+ .on(t.parentChannelId, desc(t.createdAt), desc(t.id))
+ .where(and(eq(t.type, "thread"), eq(t.archived, 0), isNotNull(t.parentMessageId))!),
// Partial unique — top-level channel names are unique per server.
// Source of truth: migration 0057_channel_unique_name.sql. Threads
// (parent_channel_id NOT NULL) are exempt by design.
diff --git a/src/shared/src/db/queries/community/thread.ts b/src/shared/src/db/queries/community/thread.ts
index f1fde4827..f8c656023 100644
--- a/src/shared/src/db/queries/community/thread.ts
+++ b/src/shared/src/db/queries/community/thread.ts
@@ -4,13 +4,7 @@ import { user } from "../../schema";
import type { Database } from "../../index";
import { chunk, maxRowsPerInsert, D1_MAX_IN_PARAMS } from "../_chunk";
import { type ParticipantSource } from "../../../constants/community";
-
-// SQLite's default TEXT ordering is BINARY. These values are ASCII ids / ISO
-// timestamps, so JS code-unit comparison matches the database byte order while
-// localeCompare does not (notably for case-sensitive nanoids such as A vs a).
-function compareSqliteBinary(a: string, b: string): number {
- return a < b ? -1 : a > b ? 1 : 0;
-}
+import { compareAsciiSqliteBinary } from "../../../lib/sqlite-binary";
// The NOTIFICATION set for a child thread — relation='notify' rows
// on `community_channel_member` (formerly the standalone
@@ -176,9 +170,9 @@ export async function listParticipantsForChannels(
.orderBy(asc(ranked.channelId), asc(ranked.addedAt), asc(ranked.userId));
}));
return batches.flat().sort((a, b) =>
- compareSqliteBinary(a.channelId, b.channelId) ||
- compareSqliteBinary(a.addedAt, b.addedAt) ||
- compareSqliteBinary(a.userId, b.userId)
+ compareAsciiSqliteBinary(a.channelId, b.channelId) ||
+ compareAsciiSqliteBinary(a.addedAt, b.addedAt) ||
+ compareAsciiSqliteBinary(a.userId, b.userId)
);
}
const batches = await Promise.all(channelIdChunks.map((ids) => db
@@ -296,14 +290,14 @@ export async function listParticipatingThreadIds(
return rows.map((r) => r.channelId);
}
-export type ForumActivityCursor = { activityAt: string; id: string };
+export type ForumCreatedAtCursor = { createdAt: string; id: string };
-export async function listForumThreadsByActivity(
+export async function listForumThreadsByCreatedAt(
db: Database,
params: {
parentChannelId: string;
tag?: string;
- cursor?: ForumActivityCursor;
+ cursor?: ForumCreatedAtCursor;
limit: number;
}
) {
@@ -316,9 +310,9 @@ export async function listForumThreadsByActivity(
];
if (params.cursor) {
conditions.push(or(
- lt(activityAt, params.cursor.activityAt),
+ lt(communityChannel.createdAt, params.cursor.createdAt),
and(
- eq(activityAt, params.cursor.activityAt),
+ eq(communityChannel.createdAt, params.cursor.createdAt),
lt(communityChannel.id, params.cursor.id)
)
)!);
@@ -354,7 +348,7 @@ export async function listForumThreadsByActivity(
)
)
.where(and(...conditions))
- .orderBy(desc(activityAt), desc(communityChannel.id))
+ .orderBy(desc(communityChannel.createdAt), desc(communityChannel.id))
.limit(params.limit);
}
@@ -362,7 +356,7 @@ export async function listForumThreadsByActivity(
.select(select)
.from(communityChannel)
.where(and(...conditions))
- .orderBy(desc(activityAt), desc(communityChannel.id))
+ .orderBy(desc(communityChannel.createdAt), desc(communityChannel.id))
.limit(params.limit);
}
@@ -490,9 +484,9 @@ export async function listParticipatingForumThreads(
return {
canonical: rows.sort((a, b) =>
- compareSqliteBinary(a.parentChannelId ?? "", b.parentChannelId ?? "") ||
- compareSqliteBinary(b.activityAt, a.activityAt) ||
- compareSqliteBinary(b.id, a.id)
+ compareAsciiSqliteBinary(a.parentChannelId ?? "", b.parentChannelId ?? "") ||
+ compareAsciiSqliteBinary(b.activityAt, a.activityAt) ||
+ compareAsciiSqliteBinary(b.id, a.id)
),
retained,
};
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 879260e6a..4f6da37bb 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -70,6 +70,7 @@ export type {
// Diagnostic report contract (neutral schemas/constants shared by HTTP, WS,
// daemon, and the D1 query layer).
export * from "./diagnostics-contract";
+export { compareAsciiSqliteBinary } from "./lib/sqlite-binary";
// Constants
export {
diff --git a/src/shared/src/lib/sqlite-binary.test.ts b/src/shared/src/lib/sqlite-binary.test.ts
new file mode 100644
index 000000000..4dced5140
--- /dev/null
+++ b/src/shared/src/lib/sqlite-binary.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vitest";
+import { compareAsciiSqliteBinary } from "./sqlite-binary";
+
+describe("compareAsciiSqliteBinary", () => {
+ it("matches SQLite BINARY descending order for mixed-case nanoids", () => {
+ const ids = [
+ "3kY1MAppCm6RYM4IvnXPN",
+ "XzKeKetmiRMJ16hwOrhSl",
+ "bc02tEwQaazjdPwrMuNih",
+ "kMRip4KDm4Ki2HU8vQ2qd",
+ ];
+
+ expect(ids.sort((left, right) => compareAsciiSqliteBinary(right, left))).toEqual([
+ "kMRip4KDm4Ki2HU8vQ2qd",
+ "bc02tEwQaazjdPwrMuNih",
+ "XzKeKetmiRMJ16hwOrhSl",
+ "3kY1MAppCm6RYM4IvnXPN",
+ ]);
+ });
+});
diff --git a/src/shared/src/lib/sqlite-binary.ts b/src/shared/src/lib/sqlite-binary.ts
new file mode 100644
index 000000000..f3ca869ca
--- /dev/null
+++ b/src/shared/src/lib/sqlite-binary.ts
@@ -0,0 +1,4 @@
+/** Matches SQLite BINARY ordering for the ASCII ids and ISO timestamps used by Alook. */
+export function compareAsciiSqliteBinary(left: string, right: string): number {
+ return left === right ? 0 : left < right ? -1 : 1;
+}
diff --git a/src/shared/test/queries/community-thread.test.ts b/src/shared/test/queries/community-thread.test.ts
index 5d64826a1..89f7c1d3c 100644
--- a/src/shared/test/queries/community-thread.test.ts
+++ b/src/shared/test/queries/community-thread.test.ts
@@ -15,7 +15,7 @@ describe("community/thread exports", () => {
});
});
-describe("listForumThreadsByActivity against real SQLite", () => {
+describe("listForumThreadsByCreatedAt against real SQLite", () => {
let sqlite: Sqlite.Database;
let db: ReturnType<typeof drizzle>;
@@ -44,6 +44,9 @@ describe("listForumThreadsByActivity against real SQLite", () => {
tag TEXT NOT NULL,
UNIQUE(message_id, tag)
);
+ CREATE INDEX idx_channel_forum_created
+ ON community_channel(parent_channel_id, created_at DESC, id DESC)
+ WHERE type = 'thread' AND archived = 0 AND parent_message_id IS NOT NULL;
CREATE TABLE user (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
@@ -66,7 +69,7 @@ describe("listForumThreadsByActivity against real SQLite", () => {
`);
insertChannel.run("t_new", "new activity", "thread", "forum_1", "m_new", 0, "2026-08-08T05:00:00.000Z", "2026-01-01T00:00:00.000Z");
insertChannel.run("t_tie_b", "tie b", "thread", "forum_1", "m_tie_b", 0, "2026-08-08T04:00:00.000Z", "2026-01-02T00:00:00.000Z");
- insertChannel.run("t_tie_a", "tie a", "thread", "forum_1", "m_tie_a", 0, "2026-08-08T04:00:00.000Z", "2026-01-03T00:00:00.000Z");
+ insertChannel.run("t_tie_a", "tie a", "thread", "forum_1", "m_tie_a", 0, "2026-08-08T04:00:00.000Z", "2026-01-02T00:00:00.000Z");
insertChannel.run("t_created", "created fallback", "thread", "forum_1", "m_created", 0, null, "2026-08-08T02:00:00.000Z");
insertChannel.run("t_archived", "archived", "thread", "forum_1", "m_archived", 1, "2026-08-09T00:00:00.000Z", "2026-01-01T00:00:00.000Z");
insertChannel.run("t_rootless", "rootless", "thread", "forum_1", null, 0, "2026-08-09T00:00:00.000Z", "2026-01-01T00:00:00.000Z");
@@ -81,30 +84,48 @@ describe("listForumThreadsByActivity against real SQLite", () => {
afterEach(() => sqlite.close());
- it("orders by activity and pages stable timestamp ties without overlap", async () => {
- const first = await threadQueries.listForumThreadsByActivity(db as never, {
+ it("keeps creation order when an older post has newer activity and pages ties without overlap", async () => {
+ const first = await threadQueries.listForumThreadsByCreatedAt(db as never, {
parentChannelId: "forum_1",
limit: 2,
});
- const second = await threadQueries.listForumThreadsByActivity(db as never, {
+ const second = await threadQueries.listForumThreadsByCreatedAt(db as never, {
parentChannelId: "forum_1",
- cursor: { activityAt: first[1]!.activityAt, id: first[1]!.id },
+ cursor: { createdAt: first[1]!.createdAt, id: first[1]!.id },
limit: 3,
});
- expect(first.map((row) => row.id)).toEqual(["t_new", "t_tie_b"]);
- expect(second.map((row) => row.id)).toEqual(["t_tie_a", "t_created"]);
- expect(second[1]!.activityAt).toBe("2026-08-08T02:00:00.000Z");
+ expect(first.map((row) => row.id)).toEqual(["t_created", "t_tie_b"]);
+ expect(second.map((row) => row.id)).toEqual(["t_tie_a", "t_new"]);
+ expect(second[1]!.activityAt).toBe("2026-08-08T05:00:00.000Z");
expect(new Set([...first, ...second].map((row) => row.id)).size).toBe(4);
});
- it("applies the tag and forum scope before the activity limit", async () => {
- const rows = await threadQueries.listForumThreadsByActivity(db as never, {
+ it("applies the tag and forum scope before the creation limit", async () => {
+ const rows = await threadQueries.listForumThreadsByCreatedAt(db as never, {
parentChannelId: "forum_1",
tag: "bug",
limit: 5,
});
- expect(rows.map((row) => row.id)).toEqual(["t_tie_a", "t_created"]);
+ expect(rows.map((row) => row.id)).toEqual(["t_created", "t_tie_a"]);
+ });
+
+ it("uses the forum creation index without a temp B-tree for the untagged feed", () => {
+ const plan = sqlite.prepare(`
+ EXPLAIN QUERY PLAN
+ SELECT id
+ FROM community_channel
+ WHERE parent_channel_id = ?
+ AND type = 'thread'
+ AND archived = 0
+ AND parent_message_id IS NOT NULL
+ ORDER BY created_at DESC, id DESC
+ LIMIT ?
+ `).all("forum_1", 50) as Array<{ detail: string }>;
+ const details = plan.map((row) => row.detail);
+
+ expect(details.some((detail) => detail.includes("USING INDEX idx_channel_forum_created"))).toBe(true);
+ expect(details.some((detail) => detail.includes("USE TEMP B-TREE"))).toBe(false);
});
it("preserves SQLite BINARY participant tie ordering for case-sensitive ids", async () => {
diff --git a/src/web/migrations/0087_forum_created_order_index.sql b/src/web/migrations/0087_forum_created_order_index.sql
new file mode 100644
index 000000000..6ca46010c
--- /dev/null
+++ b/src/web/migrations/0087_forum_created_order_index.sql
@@ -0,0 +1,3 @@
+CREATE INDEX idx_channel_forum_created
+ON community_channel(parent_channel_id, created_at DESC, id DESC)
+WHERE type = 'thread' AND archived = 0 AND parent_message_id IS NOT NULL;
diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts b/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
index 3255f7cbb..eb10ef3c9 100644
--- a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
@@ -17,7 +17,7 @@ const mockGetUser = vi.fn()
const mockListMessages = vi.fn()
const mockFilterMessageIdsByTag = vi.fn()
const mockListTagsForMessages = vi.fn()
-const mockListForumThreadsByActivity = vi.fn()
+const mockListForumThreadsByCreatedAt = vi.fn()
const mockListParticipantsForChannels = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -46,7 +46,7 @@ vi.mock("@alook/shared", async () => {
listTagsForMessages: (...a: unknown[]) => mockListTagsForMessages(...a),
},
communityThread: {
- listForumThreadsByActivity: (...a: unknown[]) => mockListForumThreadsByActivity(...a),
+ listForumThreadsByCreatedAt: (...a: unknown[]) => mockListForumThreadsByCreatedAt(...a),
listParticipantsForChannels: (...a: unknown[]) => mockListParticipantsForChannels(...a),
},
user: {
@@ -176,11 +176,19 @@ describe("GET /api/community/channels/[id]/threads", () => {
expect(mockFilterMessageIdsByTag).not.toHaveBeenCalled()
})
- it("returns an activity page with scoped included resources and an opaque next cursor", async () => {
- mockListForumThreadsByActivity.mockResolvedValue([
- { id: "t3", parentMessageId: "m3", activityAt: "2026-08-08T03:00:00.000Z" },
- { id: "t2", parentMessageId: "m2", activityAt: "2026-08-08T02:00:00.000Z" },
- { id: "t1", parentMessageId: "m1", activityAt: "2026-08-08T01:00:00.000Z" },
+ it.each(["activity", "newest", "createdat"])("rejects unsupported order=%s instead of falling through", async (order) => {
+ const res = await GET(req(`http://localhost/api/community/channels/c1/threads?order=${order}`), ctx)
+ expect(res.status).toBe(400)
+ expect(await res.json()).toEqual({ error: "invalid order" })
+ expect(mockListChildChannels).not.toHaveBeenCalled()
+ expect(mockListForumThreadsByCreatedAt).not.toHaveBeenCalled()
+ })
+
+ it("returns a created-order page with scoped included resources and an opaque next cursor", async () => {
+ mockListForumThreadsByCreatedAt.mockResolvedValue([
+ { id: "t3", parentMessageId: "m3", createdAt: "2026-08-08T03:00:00.000Z", activityAt: "2026-08-10T03:00:00.000Z" },
+ { id: "t2", parentMessageId: "m2", createdAt: "2026-08-08T02:00:00.000Z", activityAt: "2026-08-11T02:00:00.000Z" },
+ { id: "t1", parentMessageId: "m1", createdAt: "2026-08-08T01:00:00.000Z", activityAt: "2026-08-12T01:00:00.000Z" },
])
mockGetMessagesByIds.mockResolvedValue([{ id: "m3" }, { id: "m2" }])
mockGetFirstMessageByChannelIds.mockResolvedValue([{ channelId: "t3", content: "preview" }])
@@ -188,7 +196,7 @@ describe("GET /api/community/channels/[id]/threads", () => {
mockListParticipantsForChannels.mockResolvedValue([{ channelId: "t3", userId: "u1" }])
const res = await GET(req(
- "http://localhost/api/community/channels/c1/threads?order=activity&limit=2&include=parentMessage,firstMessage,tags,participants",
+ "http://localhost/api/community/channels/c1/threads?order=createdAt&limit=2&include=parentMessage,firstMessage,tags,participants",
), ctx)
expect(res.status).toBe(200)
const body = await res.json()
@@ -205,7 +213,7 @@ describe("GET /api/community/channels/[id]/threads", () => {
},
})
expect(body.nextCursor).toEqual(expect.any(String))
- expect(mockListForumThreadsByActivity).toHaveBeenCalledWith(expect.anything(), {
+ expect(mockListForumThreadsByCreatedAt).toHaveBeenCalledWith(expect.anything(), {
parentChannelId: "c1",
limit: 3,
})
@@ -213,25 +221,25 @@ describe("GET /api/community/channels/[id]/threads", () => {
expect(mockGetFirstMessageByChannelIds).toHaveBeenCalledWith(expect.anything(), ["t3", "t2"])
expect(mockListParticipantsForChannels).toHaveBeenCalledWith(expect.anything(), ["t3", "t2"], 5)
- mockListForumThreadsByActivity.mockResolvedValue([])
+ mockListForumThreadsByCreatedAt.mockResolvedValue([])
const next = await GET(req(
- `http://localhost/api/community/channels/c1/threads?order=activity&limit=2&cursor=${encodeURIComponent(body.nextCursor)}`,
+ `http://localhost/api/community/channels/c1/threads?order=createdAt&limit=2&cursor=${encodeURIComponent(body.nextCursor)}`,
), ctx)
expect(next.status).toBe(200)
- expect(mockListForumThreadsByActivity).toHaveBeenLastCalledWith(expect.anything(), {
+ expect(mockListForumThreadsByCreatedAt).toHaveBeenLastCalledWith(expect.anything(), {
parentChannelId: "c1",
- cursor: { activityAt: "2026-08-08T02:00:00.000Z", id: "t2" },
+ cursor: { createdAt: "2026-08-08T02:00:00.000Z", id: "t2" },
limit: 3,
})
})
- it("applies a normalized tag before activity pagination", async () => {
- mockListForumThreadsByActivity.mockResolvedValue([])
+ it("applies a normalized tag before created-order pagination", async () => {
+ mockListForumThreadsByCreatedAt.mockResolvedValue([])
const res = await GET(req(
- "http://localhost/api/community/channels/c1/threads?order=activity&tag=%20BUG%20&limit=5",
+ "http://localhost/api/community/channels/c1/threads?order=createdAt&tag=%20BUG%20&limit=5",
), ctx)
expect(res.status).toBe(200)
- expect(mockListForumThreadsByActivity).toHaveBeenCalledWith(expect.anything(), {
+ expect(mockListForumThreadsByCreatedAt).toHaveBeenCalledWith(expect.anything(), {
parentChannelId: "c1",
tag: "bug",
limit: 6,
@@ -240,34 +248,34 @@ describe("GET /api/community/channels/[id]/threads", () => {
expect(mockFilterMessageIdsByTag).not.toHaveBeenCalled()
})
- it("rejects malformed and cross-forum activity cursors without querying children", async () => {
+ it("rejects malformed and cross-forum created-order cursors without querying children", async () => {
const malformed = await GET(req(
- "http://localhost/api/community/channels/c1/threads?order=activity&cursor=not-a-cursor",
+ "http://localhost/api/community/channels/c1/threads?order=createdAt&cursor=not-a-cursor",
), ctx)
expect(malformed.status).toBe(400)
const foreignPayload = btoa(encodeURIComponent(JSON.stringify({
parentChannelId: "another-forum",
- activityAt: "2026-08-08T02:00:00.000Z",
+ createdAt: "2026-08-08T02:00:00.000Z",
id: "t2",
tag: null,
}))).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "")
const foreign = await GET(req(
- `http://localhost/api/community/channels/c1/threads?order=activity&cursor=${foreignPayload}`,
+ `http://localhost/api/community/channels/c1/threads?order=createdAt&cursor=${foreignPayload}`,
), ctx)
expect(foreign.status).toBe(400)
- expect(mockListForumThreadsByActivity).not.toHaveBeenCalled()
+ expect(mockListForumThreadsByCreatedAt).not.toHaveBeenCalled()
})
it("rejects unknown included resources before querying children", async () => {
const res = await GET(req(
- "http://localhost/api/community/channels/c1/threads?order=activity&include=parentMessage,secrets",
+ "http://localhost/api/community/channels/c1/threads?order=createdAt&include=parentMessage,secrets",
), ctx)
expect(res.status).toBe(400)
- expect(mockListForumThreadsByActivity).not.toHaveBeenCalled()
+ expect(mockListForumThreadsByCreatedAt).not.toHaveBeenCalled()
})
- it("does not query activity children when the forum access gate rejects the viewer", async () => {
+ it("does not query created-order children when the forum access gate rejects the viewer", async () => {
mockResolveChannelAccessContext.mockResolvedValue({
channel: { id: "c1", serverId: "s1", type: "forum" },
anchor: { id: "c1", serverId: "s1", type: "forum" },
@@ -277,10 +285,10 @@ describe("GET /api/community/channels/[id]/threads", () => {
isChannelMember: false,
})
const res = await GET(req(
- "http://localhost/api/community/channels/c1/threads?order=activity",
+ "http://localhost/api/community/channels/c1/threads?order=createdAt",
), ctx)
expect(res.status).toBe(403)
- expect(mockListForumThreadsByActivity).not.toHaveBeenCalled()
+ expect(mockListForumThreadsByCreatedAt).not.toHaveBeenCalled()
expect(mockGetMessagesByIds).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.ts b/src/web/src/app/api/community/channels/[id]/threads/route.ts
index d584d4e85..32c05935e 100644
--- a/src/web/src/app/api/community/channels/[id]/threads/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/threads/route.ts
@@ -5,7 +5,7 @@ import { getDb } from "@/lib/db"
import { isForum, queries, MAX_FORUM_TAG_LENGTH } from "@alook/shared"
import { requireChannelAccess } from "@/lib/community/permissions"
import { parseBoundedInt } from "@/lib/community/messages"
-import { encodeForumActivityCursor, parseForumActivityCursor } from "@/lib/community/forum-activity"
+import { encodeForumCreatedAtCursor, parseForumCreatedAtCursor } from "@/lib/community/forum-feed-cursor"
export const GET = withAuth(async (req: NextRequest, ctx) => {
const channelId = ctx.params?.id
@@ -27,9 +27,12 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
if (rawTag !== null && !tag) return writeError("tag is required", 400)
if (tag && tag.length > MAX_FORUM_TAG_LENGTH) return writeError(`tag must be ≤ ${MAX_FORUM_TAG_LENGTH} characters`, 400)
- if (req.nextUrl.searchParams.get("order") === "activity") {
+ const order = req.nextUrl.searchParams.get("order")
+ if (order !== null && order !== "createdAt") return writeError("invalid order", 400)
+
+ if (order === "createdAt") {
if (!isForum(access.value.channel.type)) return writeError("not a forum", 400)
- if (archived === true) return writeError("activity order only supports active threads", 400)
+ if (archived === true) return writeError("createdAt order only supports active threads", 400)
const includes = new Set(
(req.nextUrl.searchParams.get("include") ?? "")
.split(",")
@@ -41,13 +44,13 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
return writeError("invalid include", 400)
}
const pageSize = parseBoundedInt(req.nextUrl.searchParams.get("limit"), 50, 100)
- const cursor = parseForumActivityCursor(req.nextUrl.searchParams.get("cursor"), {
+ const cursor = parseForumCreatedAtCursor(req.nextUrl.searchParams.get("cursor"), {
parentChannelId: channelId,
tag: tag ?? null,
})
if (cursor === null) return writeError("invalid cursor", 400)
- const rows = await queries.communityThread.listForumThreadsByActivity(db, {
+ const rows = await queries.communityThread.listForumThreadsByCreatedAt(db, {
parentChannelId: channelId,
...(tag ? { tag } : {}),
...(cursor ? { cursor } : {}),
@@ -57,9 +60,9 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const threads = hasMore ? rows.slice(0, pageSize) : rows
const last = threads.at(-1)
const nextCursor = hasMore && last
- ? encodeForumActivityCursor({
+ ? encodeForumCreatedAtCursor({
parentChannelId: channelId,
- activityAt: last.activityAt,
+ createdAt: last.createdAt,
id: last.id,
tag: tag ?? null,
})
diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.ts b/src/web/src/app/api/community/servers/[id]/channels/route.ts
index ad2e42383..0c2bc3a24 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/route.ts
@@ -1,14 +1,10 @@
import { NextResponse, NextRequest } from "next/server"
import { getDb } from "@/lib/db"
-import { isForum, parseNameAndTag, queries } from "@alook/shared"
+import { compareAsciiSqliteBinary, isForum, parseNameAndTag, queries } from "@alook/shared"
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { buildServerChannelGroups } from "@/lib/community/list-channels"
import { requireServerMember } from "@/lib/community/permissions"
-function compareBinary(left: string, right: string): number {
- return left === right ? 0 : left < right ? -1 : 1
-}
-
/**
* GET /api/community/servers/[id]/channels — single-server channel list. Human
* callers receive the visible top-level tree, with one strict participating
@@ -102,9 +98,9 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
.slice(0, limitPerParent - 1),
retainedChannel,
].sort((a, b) =>
- compareBinary(a.parentChannelId ?? "", b.parentChannelId ?? "") ||
- compareBinary(b.activityAt, a.activityAt) ||
- compareBinary(b.id, a.id)
+ compareAsciiSqliteBinary(a.parentChannelId ?? "", b.parentChannelId ?? "") ||
+ compareAsciiSqliteBinary(b.activityAt, a.activityAt) ||
+ compareAsciiSqliteBinary(b.id, a.id)
)
}
return NextResponse.json({
diff --git a/src/web/src/components/community/channels/forum-view.scroll.test.ts b/src/web/src/components/community/channels/forum-view.scroll.test.ts
index 6b80961ac..9d2d45c77 100644
--- a/src/web/src/components/community/channels/forum-view.scroll.test.ts
+++ b/src/web/src/components/community/channels/forum-view.scroll.test.ts
@@ -75,7 +75,7 @@ describe("ForumView scroll anchoring", () => {
expect(scrollToIndex).toHaveBeenCalledWith(0, { align: "start" })
})
- it("loads older activity pages from the bottom sentinel without scroll-height compensation", async () => {
+ it("loads older feed pages from the bottom sentinel without scroll-height compensation", async () => {
const onLoadMore = vi.fn()
let view: ReactTestRenderer
await act(async () => {
diff --git a/src/web/src/hooks/community/forum-opener-title-reconciliation.test.ts b/src/web/src/hooks/community/forum-opener-title-reconciliation.test.ts
index 32bf3746d..395ae2671 100644
--- a/src/web/src/hooks/community/forum-opener-title-reconciliation.test.ts
+++ b/src/web/src/hooks/community/forum-opener-title-reconciliation.test.ts
@@ -60,7 +60,7 @@ function seedCanonicalCaches() {
parent: { authorName: "A", text: "Old title" },
}],
})
- queryClient.setQueryData(communityKeys.forumActivityFeed("forum_1", null), {
+ queryClient.setQueryData(communityKeys.forumFeed("forum_1", null), {
pages: [{
parentType: "forum",
serverId: "server_1",
@@ -95,7 +95,7 @@ function seedCanonicalCaches() {
describe("reconcileForumOpenerTitle", () => {
it("patches every exact forum title read model and repairs only exact network reads", async () => {
seedCanonicalCaches()
- const activityKey = communityKeys.forumActivityFeed("forum_1", null)
+ const feedKey = communityKeys.forumFeed("forum_1", null)
const cancel = vi.spyOn(queryClient, "cancelQueries")
const invalidate = vi.spyOn(queryClient, "invalidateQueries")
@@ -105,14 +105,14 @@ describe("reconcileForumOpenerTitle", () => {
expect(cancel).toHaveBeenCalledWith({ queryKey: communityKeys.threads("forum_1"), exact: true })
expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.inboxUnreads(), exact: true })
expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.threads("forum_1"), exact: true })
- expect(queryClient.getQueryState(activityKey)?.isInvalidated).toBe(false)
+ expect(queryClient.getQueryState(feedKey)?.isInvalidated).toBe(false)
expect(queryClient.getQueryData<any>(communityKeys.message("opener_1")).content).toBe("Full new title")
expect(queryClient.getQueryData<any>(communityKeys.channelMessages("forum_1")).pages[0].messages[0].content).toBe("Full new title")
expect(queryClient.getQueryData<any>(communityKeys.channelMessages("post_1")).pages[0].messages[0].content).toBe("Full new title")
expect(queryClient.getQueryData<any>(communityKeys.inboxUnreads()).servers[0].channels[0].children[0].channelName).toBe("Full new title")
expect(queryClient.getQueryData<any>(communityKeys.threads("forum_1")).threads[0].name).toBe("Full new title")
- expect(queryClient.getQueryData<any>(activityKey).pages[0].included.parentMessages[0].content).toBe("Full new title")
+ expect(queryClient.getQueryData<any>(feedKey).pages[0].included.parentMessages[0].content).toBe("Full new title")
expect(queryClient.getQueryData<any>(communityKeys.forumSidebarThreads("server_1")).threads[0].title).toBe("Full new title")
expect(queryClient.getQueryData<any>(communityKeys.forumOpenerHint("server_1", "opener_1")).content).toBe("Full new title")
})
diff --git a/src/web/src/hooks/community/forum-opener-title-reconciliation.ts b/src/web/src/hooks/community/forum-opener-title-reconciliation.ts
index 2c2707d16..15dc13bfe 100644
--- a/src/web/src/hooks/community/forum-opener-title-reconciliation.ts
+++ b/src/web/src/hooks/community/forum-opener-title-reconciliation.ts
@@ -5,7 +5,7 @@ import { communityKeys } from "@/lib/query-keys"
import type { MessagesPage, Msg } from "@/lib/community/models/message"
import type { UnreadServer } from "@/lib/community/models/inbox"
import type { ThreadsResponse } from "@/hooks/community/use-channel-panels"
-import type { ForumActivityPage } from "@/hooks/community/use-forum-feed"
+import type { ForumFeedPage } from "@/hooks/community/use-forum-feed"
import {
getForumSidebarBase,
patchForumSidebarTitleExact,
@@ -55,8 +55,8 @@ function patchInbox(
return touched ? { ...data, servers } : data
}
-function patchActivity(
- data: InfiniteData<ForumActivityPage> | undefined,
+function patchFeed(
+ data: InfiniteData<ForumFeedPage> | undefined,
identity: ForumOpenerTitleIdentity,
) {
if (!data) return data
@@ -156,9 +156,9 @@ export async function reconcileForumOpenerTitle(
(cache) => patchMessageContentInCache(cache, identity.openerMessageId, identity.content),
)
}
- queryClient.setQueriesData<InfiniteData<ForumActivityPage>>(
- { queryKey: [...communityKeys.threads(identity.forumChannelId), "activity"] },
- (data) => patchActivity(data, identity),
+ queryClient.setQueriesData<InfiniteData<ForumFeedPage>>(
+ { queryKey: [...communityKeys.threads(identity.forumChannelId), "feed"] },
+ (data) => patchFeed(data, identity),
)
queryClient.setQueryData<{ servers: UnreadServer[]; dms: unknown[] }>(
inboxKey,
diff --git a/src/web/src/hooks/community/mutations/forum.test.ts b/src/web/src/hooks/community/mutations/forum.test.ts
index 7b8fd5700..a68023d9e 100644
--- a/src/web/src/hooks/community/mutations/forum.test.ts
+++ b/src/web/src/hooks/community/mutations/forum.test.ts
@@ -129,13 +129,13 @@ describe("useCreateForumThread", () => {
const { useCreateForumThread } = await load()
useCreateForumThread()
capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [], pageParams: [] })
- capturedQc.setQueryData(communityKeys.forumActivityFeed("forum_1", null), { pages: [], pageParams: [] })
+ capturedQc.setQueryData(communityKeys.forumFeed("forum_1", null), { pages: [], pageParams: [] })
apiFetchMock.mockResolvedValueOnce({ threadId: "p_new" })
await runMutation({ nonce: "command_1", channelId: "forum_1", name: "n", content: "c" })
expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(true)
- expect(capturedQc.getQueryState(communityKeys.forumActivityFeed("forum_1", null))?.isInvalidated).toBe(true)
+ expect(capturedQc.getQueryState(communityKeys.forumFeed("forum_1", null))?.isInvalidated).toBe(true)
})
})
@@ -145,11 +145,11 @@ describe("useUpdatePostTags", () => {
useUpdatePostTags()
capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [], pageParams: [] })
const bugKey = [...communityKeys.channelMessages("forum_1"), "tag", "bug"] as const
- const activityAllKey = communityKeys.forumActivityFeed("forum_1", null)
- const activityBugKey = communityKeys.forumActivityFeed("forum_1", "bug")
+ const feedAllKey = communityKeys.forumFeed("forum_1", null)
+ const feedBugKey = communityKeys.forumFeed("forum_1", "bug")
capturedQc.setQueryData(bugKey, { pages: [], pageParams: [] })
- capturedQc.setQueryData(activityAllKey, { pages: [], pageParams: [] })
- capturedQc.setQueryData(activityBugKey, { pages: [], pageParams: [] })
+ capturedQc.setQueryData(feedAllKey, { pages: [], pageParams: [] })
+ capturedQc.setQueryData(feedBugKey, { pages: [], pageParams: [] })
capturedQc.setQueryData(communityKeys.forumTags("forum_1"), { tags: ["bug", "p0"] })
apiFetchMock.mockResolvedValueOnce({ tags: ["bug", "p0"] })
@@ -166,8 +166,8 @@ describe("useUpdatePostTags", () => {
})
expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(true)
expect(capturedQc.getQueryState(bugKey)?.isInvalidated).toBe(true)
- expect(capturedQc.getQueryState(activityAllKey)?.isInvalidated).toBe(true)
- expect(capturedQc.getQueryState(activityBugKey)?.isInvalidated).toBe(true)
+ expect(capturedQc.getQueryState(feedAllKey)?.isInvalidated).toBe(true)
+ expect(capturedQc.getQueryState(feedBugKey)?.isInvalidated).toBe(true)
expect(capturedQc.getQueryState(communityKeys.forumTags("forum_1"))?.isInvalidated).toBe(true)
})
@@ -177,7 +177,7 @@ describe("useUpdatePostTags", () => {
const feedBefore = { pages: [{ messages: [{ id: "m_p2" }] }], pageParams: [null] }
const tagsBefore = { tags: ["bug"] }
capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), feedBefore)
- capturedQc.setQueryData(communityKeys.forumActivityFeed("forum_1", null), feedBefore)
+ capturedQc.setQueryData(communityKeys.forumFeed("forum_1", null), feedBefore)
capturedQc.setQueryData(communityKeys.forumTags("forum_1"), tagsBefore)
apiFetchMock.mockRejectedValueOnce(new Error("500"))
@@ -191,7 +191,7 @@ describe("useUpdatePostTags", () => {
expect(capturedQc.getQueryData(communityKeys.channelMessages("forum_1"))).toEqual(feedBefore)
expect(capturedQc.getQueryData(communityKeys.forumTags("forum_1"))).toEqual(tagsBefore)
expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(false)
- expect(capturedQc.getQueryState(communityKeys.forumActivityFeed("forum_1", null))?.isInvalidated).toBe(false)
+ expect(capturedQc.getQueryState(communityKeys.forumFeed("forum_1", null))?.isInvalidated).toBe(false)
expect(capturedQc.getQueryState(communityKeys.forumTags("forum_1"))?.isInvalidated).toBe(false)
})
})
@@ -202,7 +202,7 @@ describe("useDeleteForumThread", () => {
useDeleteForumThread()
capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [], pageParams: [] })
- capturedQc.setQueryData(communityKeys.forumActivityFeed("forum_1", null), { pages: [], pageParams: [] })
+ capturedQc.setQueryData(communityKeys.forumFeed("forum_1", null), { pages: [], pageParams: [] })
const sidebarKey = communityKeys.forumSidebarThreads("server_1")
capturedQc.setQueryData(sidebarKey, {
channels: [], included: { parentMessages: [] }, serverNow: "2026-08-08T00:00:00.000Z",
@@ -215,7 +215,7 @@ describe("useDeleteForumThread", () => {
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/p2", { method: "DELETE" })
expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(true)
- expect(capturedQc.getQueryState(communityKeys.forumActivityFeed("forum_1", null))?.isInvalidated).toBe(true)
+ expect(capturedQc.getQueryState(communityKeys.forumFeed("forum_1", null))?.isInvalidated).toBe(true)
expect(capturedQc.getQueryData<{ threads: unknown[] }>(sidebarKey)?.threads).toEqual([])
})
@@ -225,12 +225,12 @@ describe("useDeleteForumThread", () => {
const before = { pages: [{ messages: [{ id: "m_p2" }] }], pageParams: [null] }
capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), before)
- capturedQc.setQueryData(communityKeys.forumActivityFeed("forum_1", null), before)
+ capturedQc.setQueryData(communityKeys.forumFeed("forum_1", null), before)
apiFetchMock.mockRejectedValueOnce(new Error("500"))
await runMutationExpectError({ serverId: "server_1", forumChannelId: "forum_1", threadId: "p2" })
expect(capturedQc.getQueryData(communityKeys.channelMessages("forum_1"))).toEqual(before)
- expect(capturedQc.getQueryData(communityKeys.forumActivityFeed("forum_1", null))).toEqual(before)
+ expect(capturedQc.getQueryData(communityKeys.forumFeed("forum_1", null))).toEqual(before)
})
})
diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.ts
index 9f963b4db..90c27242e 100644
--- a/src/web/src/hooks/community/mutations/messages.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.test.ts
@@ -193,10 +193,10 @@ describe("useEditMessage", () => {
it("invalidates only the exact Inbox and base threads reads after an opener edit", async () => {
const threads = communityKeys.threads("forum_1")
- const activity = communityKeys.forumActivityFeed("forum_1", "bug")
+ const feed = communityKeys.forumFeed("forum_1", "bug")
const inbox = communityKeys.inboxUnreads()
capturedQc.setQueryData(threads, { serverId: "s1", parentType: "forum", parentChannelId: "forum_1", threads: [] })
- capturedQc.setQueryData(activity, { pages: [], pageParams: [] })
+ capturedQc.setQueryData(feed, { pages: [], pageParams: [] })
capturedQc.setQueryData(inbox, { servers: [], dms: [] })
apiFetchMock.mockResolvedValueOnce(undefined)
const mod = await loadMod()
@@ -209,7 +209,7 @@ describe("useEditMessage", () => {
expect(capturedQc.getQueryState(threads)?.isInvalidated).toBe(true)
expect(capturedQc.getQueryState(inbox)?.isInvalidated).toBe(true)
- expect(capturedQc.getQueryState(activity)?.isInvalidated).toBe(false)
+ expect(capturedQc.getQueryState(feed)?.isInvalidated).toBe(false)
})
it("patches a loaded forum-sidebar title after the opener edit succeeds", async () => {
diff --git a/src/web/src/hooks/community/use-forum-feed.test.ts b/src/web/src/hooks/community/use-forum-feed.test.ts
index fd1c23469..6880f7fdb 100644
--- a/src/web/src/hooks/community/use-forum-feed.test.ts
+++ b/src/web/src/hooks/community/use-forum-feed.test.ts
@@ -6,9 +6,9 @@ vi.mock("@/lib/api/client", () => ({
}))
import {
- forumActivityPageQueryFn,
- mapForumActivityPages,
- type ForumActivityPage,
+ forumFeedPageQueryFn,
+ mapForumFeedPages,
+ type ForumFeedPage,
} from "./use-forum-feed"
const emptyIncluded = {
@@ -18,26 +18,26 @@ const emptyIncluded = {
participants: [],
}
-describe("forumActivityPageQueryFn", () => {
+describe("forumFeedPageQueryFn", () => {
beforeEach(() => apiFetchMock.mockReset())
- it("requests the canonical activity collection with includes, tag, and cursor", async () => {
+ it("requests the canonical created-order collection with includes, tag, and cursor", async () => {
apiFetchMock.mockResolvedValue({ threads: [], included: emptyIncluded, hasMore: false })
- await forumActivityPageQueryFn("forum_one", "bug")({ pageParam: "opaque cursor" })
+ await forumFeedPageQueryFn("forum_one", "bug")({ pageParam: "opaque cursor" })
const url = apiFetchMock.mock.calls[0]![0] as string
expect(url).toContain("/api/community/channels/forum_one/threads?")
const params = new URL(url, "http://localhost").searchParams
- expect(params.get("order")).toBe("activity")
+ expect(params.get("order")).toBe("createdAt")
expect(params.get("include")).toBe("parentMessage,firstMessage,tags,participants")
expect(params.get("tag")).toBe("bug")
expect(params.get("cursor")).toBe("opaque cursor")
})
})
-describe("mapForumActivityPages", () => {
- it("joins included resources, deduplicates pages, and keeps latest activity first", () => {
- const pages: ForumActivityPage[] = [
+describe("mapForumFeedPages", () => {
+ it("joins included resources, deduplicates pages, and keeps newest-created first", () => {
+ const pages: ForumFeedPage[] = [
{
serverId: "server_1",
parentType: "forum",
@@ -97,9 +97,9 @@ describe("mapForumActivityPages", () => {
},
]
- const result = mapForumActivityPages(pages)
- expect(result.map((thread) => thread.id)).toEqual(["t2", "t1"])
- expect(result[0]).toMatchObject({
+ const result = mapForumFeedPages(pages)
+ expect(result.map((thread) => thread.id)).toEqual(["t1", "t2"])
+ expect(result[1]).toMatchObject({
name: " Opener title ",
parentSeq: 42,
authorId: "u2",
@@ -113,7 +113,7 @@ describe("mapForumActivityPages", () => {
{ id: "u3", name: "Bob", avatar: "bob.png" },
],
})
- expect(result[1]).toMatchObject({
+ expect(result[0]).toMatchObject({
name: "fallback one",
authorId: "creator_1",
preview: "",
@@ -121,4 +121,41 @@ describe("mapForumActivityPages", () => {
participantCount: 0,
})
})
+
+ it("matches SQLite BINARY id ordering for equal-created mixed-case nanoids", () => {
+ const expectedIds = [
+ "kMRip4KDm4Ki2HU8vQ2qd",
+ "bc02tEwQaazjdPwrMuNih",
+ "XzKeKetmiRMJ16hwOrhSl",
+ "3kY1MAppCm6RYM4IvnXPN",
+ ]
+ const threads = expectedIds.map((id) => ({
+ id,
+ name: id,
+ creatorId: "creator",
+ messageCount: 0,
+ parentMessageId: null,
+ lastMessageAt: null,
+ createdAt: "2026-08-17T06:35:00.000Z",
+ activityAt: "2026-08-17T06:35:00.000Z",
+ }))
+ const pages: ForumFeedPage[] = [
+ {
+ serverId: "server_1",
+ parentType: "forum",
+ threads: threads.slice(2),
+ included: emptyIncluded,
+ hasMore: false,
+ },
+ {
+ serverId: "server_1",
+ parentType: "forum",
+ threads: threads.slice(0, 2),
+ included: emptyIncluded,
+ hasMore: false,
+ },
+ ]
+
+ expect(mapForumFeedPages(pages).map((thread) => thread.id)).toEqual(expectedIds)
+ })
})
diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.ts
index 8cf99f5b7..553a81e37 100644
--- a/src/web/src/hooks/community/use-forum-feed.ts
+++ b/src/web/src/hooks/community/use-forum-feed.ts
@@ -2,7 +2,7 @@
import { useCallback, useEffect, useMemo, useState } from "react"
import { useInfiniteQuery, type InfiniteData } from "@tanstack/react-query"
-import { DEFAULT_MESSAGE_PAGE_SIZE } from "@alook/shared"
+import { compareAsciiSqliteBinary, DEFAULT_MESSAGE_PAGE_SIZE } from "@alook/shared"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { avatarInitial } from "@/lib/community/avatar"
@@ -10,7 +10,7 @@ import { readForumTagSelection, validateForumTagSelection, writeForumTagSelectio
import type { ForumThread } from "@/lib/community/models/message"
import { useForumTags } from "./use-channel-panels"
-type ActivityThread = {
+type FeedThread = {
id: string
name: string | null
creatorId: string | null
@@ -41,10 +41,10 @@ type IncludedParticipant = {
participantCount?: number
}
-export type ForumActivityPage = {
+export type ForumFeedPage = {
serverId: string
parentType: string
- threads: ActivityThread[]
+ threads: FeedThread[]
included: {
parentMessages: IncludedMessage[]
firstMessages: IncludedFirstMessage[]
@@ -55,23 +55,24 @@ export type ForumActivityPage = {
nextCursor?: string
}
-export function forumActivityPageQueryFn(channelId: string, tag: string | null) {
+export function forumFeedPageQueryFn(channelId: string, tag: string | null) {
return ({ pageParam }: { pageParam: string | null }) => {
const params = new URLSearchParams({
- order: "activity",
+ order: "createdAt",
limit: String(DEFAULT_MESSAGE_PAGE_SIZE),
include: "parentMessage,firstMessage,tags,participants",
})
if (tag) params.set("tag", tag)
if (pageParam) params.set("cursor", pageParam)
- return apiFetch<ForumActivityPage>(
+ return apiFetch<ForumFeedPage>(
`/api/community/channels/${channelId}/threads?${params.toString()}`,
)
}
}
-export function mapForumActivityPages(pages: ForumActivityPage[]): ForumThread[] {
+export function mapForumFeedPages(pages: ForumFeedPage[]): ForumThread[] {
const byId = new Map<string, ForumThread>()
+ const createdAtById = new Map<string, string>()
for (const page of pages) {
const openerById = new Map(page.included.parentMessages.map((message) => [message.id, message]))
const firstByChannel = new Map(page.included.firstMessages.map((message) => [message.channelId, message]))
@@ -95,6 +96,7 @@ export function mapForumActivityPages(pages: ForumActivityPage[]): ForumThread[]
for (const thread of page.threads) {
if (byId.has(thread.id)) continue
+ createdAtById.set(thread.id, thread.createdAt)
const opener = thread.parentMessageId ? openerById.get(thread.parentMessageId) : undefined
const first = firstByChannel.get(thread.id)
byId.set(thread.id, {
@@ -118,8 +120,8 @@ export function mapForumActivityPages(pages: ForumActivityPage[]): ForumThread[]
}
}
return [...byId.values()].sort((a, b) => {
- const activity = b.lastMessageAt.localeCompare(a.lastMessageAt)
- return activity || b.id.localeCompare(a.id)
+ const createdAt = compareAsciiSqliteBinary(createdAtById.get(b.id)!, createdAtById.get(a.id)!)
+ return createdAt || compareAsciiSqliteBinary(b.id, a.id)
})
}
@@ -141,21 +143,21 @@ export function useForumFeed(_serverId: string, channelId: string) {
try { writeForumTagSelection(window.localStorage, channelId, next) } catch { }
}, [channelId])
const selectedTag = tag === "All" ? null : tag
- const queryKey = communityKeys.forumActivityFeed(channelId, selectedTag)
+ const queryKey = communityKeys.forumFeed(channelId, selectedTag)
const query = useInfiniteQuery<
- ForumActivityPage,
+ ForumFeedPage,
Error,
- InfiniteData<ForumActivityPage, string | null>,
+ InfiniteData<ForumFeedPage, string | null>,
typeof queryKey,
string | null
>({
queryKey,
- queryFn: forumActivityPageQueryFn(channelId, selectedTag),
+ queryFn: forumFeedPageQueryFn(channelId, selectedTag),
initialPageParam: null,
getNextPageParam: (lastPage) => lastPage.hasMore ? lastPage.nextCursor : undefined,
})
const posts = useMemo(
- () => mapForumActivityPages(query.data?.pages ?? []),
+ () => mapForumFeedPages(query.data?.pages ?? []),
[query.data?.pages],
)
diff --git a/src/web/src/lib/community/forum-activity.test.ts b/src/web/src/lib/community/forum-activity.test.ts
deleted file mode 100644
index 4e8806f66..000000000
--- a/src/web/src/lib/community/forum-activity.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { describe, expect, it } from "vitest"
-import { encodeForumActivityCursor, parseForumActivityCursor } from "./forum-activity"
-
-describe("forum activity cursor", () => {
- const value = {
- parentChannelId: "forum_1",
- activityAt: "2026-08-08T02:00:00.123Z",
- id: "thread_2",
- tag: "产品",
- }
-
- it("round-trips an opaque cursor within the same forum and tag scope", () => {
- const encoded = encodeForumActivityCursor(value)
- expect(encoded).not.toContain("forum_1")
- expect(parseForumActivityCursor(encoded, {
- parentChannelId: "forum_1",
- tag: "产品",
- })).toEqual({
- activityAt: "2026-08-08T02:00:00.123Z",
- id: "thread_2",
- })
- })
-
- it("rejects malformed, cross-forum, and cross-tag cursors", () => {
- const encoded = encodeForumActivityCursor(value)
- expect(parseForumActivityCursor("invalid", { parentChannelId: "forum_1", tag: "产品" })).toBeNull()
- expect(parseForumActivityCursor(encoded, { parentChannelId: "forum_2", tag: "产品" })).toBeNull()
- expect(parseForumActivityCursor(encoded, { parentChannelId: "forum_1", tag: "bug" })).toBeNull()
- })
-
- it("treats an absent cursor as the first page", () => {
- expect(parseForumActivityCursor(null, { parentChannelId: "forum_1", tag: null })).toBeUndefined()
- })
-})
diff --git a/src/web/src/lib/community/forum-feed-cursor.test.ts b/src/web/src/lib/community/forum-feed-cursor.test.ts
new file mode 100644
index 000000000..7994b2ed6
--- /dev/null
+++ b/src/web/src/lib/community/forum-feed-cursor.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest"
+import { encodeForumCreatedAtCursor, parseForumCreatedAtCursor } from "./forum-feed-cursor"
+
+describe("forum created-at cursor", () => {
+ const value = {
+ parentChannelId: "forum_1",
+ createdAt: "2026-08-08T02:00:00.123Z",
+ id: "thread_2",
+ tag: "产品",
+ }
+
+ it("round-trips an opaque cursor within the same forum and tag scope", () => {
+ const encoded = encodeForumCreatedAtCursor(value)
+ expect(encoded).not.toContain("forum_1")
+ expect(parseForumCreatedAtCursor(encoded, {
+ parentChannelId: "forum_1",
+ tag: "产品",
+ })).toEqual({
+ createdAt: "2026-08-08T02:00:00.123Z",
+ id: "thread_2",
+ })
+ })
+
+ it("rejects malformed, cross-forum, and cross-tag cursors", () => {
+ const encoded = encodeForumCreatedAtCursor(value)
+ expect(parseForumCreatedAtCursor("invalid", { parentChannelId: "forum_1", tag: "产品" })).toBeNull()
+ expect(parseForumCreatedAtCursor(encoded, { parentChannelId: "forum_2", tag: "产品" })).toBeNull()
+ expect(parseForumCreatedAtCursor(encoded, { parentChannelId: "forum_1", tag: "bug" })).toBeNull()
+ })
+
+ it("treats an absent cursor as the first page", () => {
+ expect(parseForumCreatedAtCursor(null, { parentChannelId: "forum_1", tag: null })).toBeUndefined()
+ })
+})
diff --git a/src/web/src/lib/community/forum-activity.ts b/src/web/src/lib/community/forum-feed-cursor.ts
similarity index 59%
rename from src/web/src/lib/community/forum-activity.ts
rename to src/web/src/lib/community/forum-feed-cursor.ts
index cdaf4b8ed..011cc9c7f 100644
--- a/src/web/src/lib/community/forum-activity.ts
+++ b/src/web/src/lib/community/forum-feed-cursor.ts
@@ -1,34 +1,34 @@
-export type ForumActivityCursor = {
+export type ForumCreatedAtCursor = {
parentChannelId: string
- activityAt: string
+ createdAt: string
id: string
tag: string | null
}
-export function encodeForumActivityCursor(cursor: ForumActivityCursor): string {
+export function encodeForumCreatedAtCursor(cursor: ForumCreatedAtCursor): string {
const ascii = encodeURIComponent(JSON.stringify(cursor))
return btoa(ascii).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "")
}
-export function parseForumActivityCursor(
+export function parseForumCreatedAtCursor(
raw: string | null,
scope: { parentChannelId: string; tag: string | null },
-): { activityAt: string; id: string } | null | undefined {
+): { createdAt: string; id: string } | null | undefined {
if (!raw) return undefined
try {
const base64 = raw.replaceAll("-", "+").replaceAll("_", "/")
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")
- const value = JSON.parse(decodeURIComponent(atob(padded))) as Partial<ForumActivityCursor>
+ const value = JSON.parse(decodeURIComponent(atob(padded))) as Partial<ForumCreatedAtCursor>
if (
value.parentChannelId !== scope.parentChannelId
|| value.tag !== scope.tag
- || typeof value.activityAt !== "string"
- || !Number.isFinite(Date.parse(value.activityAt))
- || new Date(value.activityAt).toISOString() !== value.activityAt
+ || typeof value.createdAt !== "string"
+ || !Number.isFinite(Date.parse(value.createdAt))
+ || new Date(value.createdAt).toISOString() !== value.createdAt
|| typeof value.id !== "string"
|| value.id.length === 0
) return null
- return { activityAt: value.activityAt, id: value.id }
+ return { createdAt: value.createdAt, id: value.id }
} catch {
return null
}
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index b3caff33f..f4d3fa05e 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -83,8 +83,8 @@ export const communityKeys = {
[...communityKeys.all, "channel", channelId, "pins"] as const,
threads: (channelId: string) =>
[...communityKeys.all, "channel", channelId, "threads"] as const,
- forumActivityFeed: (channelId: string, tag: string | null) =>
- [...communityKeys.threads(channelId), "activity", tag] as const,
+ forumFeed: (channelId: string, tag: string | null) =>
+ [...communityKeys.threads(channelId), "feed", tag] as const,
forumTags: (channelId: string) =>
[...communityKeys.all, "channel", channelId, "forum-tags"] as const,
// #3: the viewer's `communityReadState` row for a single channel, fetched