Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): preserve archived forum access and viewer permissions (#865)

Gener6d42bf9ba718
diff --git a/src/shared/src/db/queries/community/server.ts b/src/shared/src/db/queries/community/server.ts
index e8dbb7605..f49889c40 100644
--- a/src/shared/src/db/queries/community/server.ts
+++ b/src/shared/src/db/queries/community/server.ts
@@ -263,6 +263,7 @@ export async function listUserServers(db: Database, userId: string) {
ownerId: communityServer.ownerId,
createdAt: communityServer.createdAt,
role: communityServerMember.role,
+ memberId: communityServerMember.id,
railOrder: communityServerMember.railOrder,
// COALESCE has no ORM operator in this Drizzle version — the LEFT JOIN
// yields NULL for servers with zero unread mentions. Wrap the aggregate
diff --git a/src/shared/test/queries/community-notification-cursor-clear.test.ts b/src/shared/test/queries/community-notification-cursor-clear.test.ts
index b11f75199..f31e681fb 100644
--- a/src/shared/test/queries/community-notification-cursor-clear.test.ts
+++ b/src/shared/test/queries/community-notification-cursor-clear.test.ts
@@ -109,6 +109,7 @@ describe("notification setting read-state isolation contract", () => {
added_at TEXT NOT NULL
);
CREATE TABLE community_server_member (
+ id TEXT PRIMARY KEY,
server_id TEXT NOT NULL,
user_id TEXT NOT NULL,
joined_at TEXT NOT NULL,
@@ -146,8 +147,8 @@ describe("notification setting read-state isolation contract", () => {
('child-3', 'child', '2026-01-01T00:00:03Z', 3),
('sibling-4', 'sibling', '2026-01-01T00:00:04Z', 4),
('dm-5', 'dm', '2026-01-01T00:00:05Z', 5);
- INSERT INTO community_server_member (server_id, user_id, joined_at)
- VALUES ('server', 'u', '2025-01-01T00:00:00Z');
+ INSERT INTO community_server_member (id, server_id, user_id, joined_at)
+ VALUES ('membership-u', 'server', 'u', '2025-01-01T00:00:00Z');
INSERT INTO community_channel_member (channel_id, user_id, relation, added_at)
VALUES ('dm', 'u', 'access', '2025-01-01T00:00:00Z');
`);
@@ -175,6 +176,14 @@ describe("notification setting read-state isolation contract", () => {
ORDER BY channel_id
`).all();
+ it("returns the viewer's membership identity and current role without another member's role", async () => {
+ sqlite.prepare("UPDATE community_server_member SET role = 'admin' WHERE user_id = 'u'").run();
+ sqlite.prepare("INSERT INTO community_server_member (id, server_id, user_id, joined_at, role) VALUES ('membership-peer', 'server', 'peer', '2025-01-01T00:00:00Z', 'owner')").run();
+ const servers = await listUserServers(db, "u");
+ expect(servers).toHaveLength(1);
+ expect(servers[0]).toMatchObject({ id: "server", memberId: "membership-u", role: "admin" });
+ });
+
it("sets a server policy without manufacturing or advancing channel cursors", async () => {
sqlite.exec(`
INSERT INTO community_read_state
diff --git a/src/web/src/components/community/members/channel-member-view-model.dom.test.ts b/src/web/src/components/community/members/channel-member-view-model.dom.test.ts
index a83484ae8..33ad3193b 100644
--- a/src/web/src/components/community/members/channel-member-view-model.dom.test.ts
+++ b/src/web/src/components/community/members/channel-member-view-model.dom.test.ts
@@ -8,6 +8,7 @@ import { useAddableMembers, useChannelMembers } from "@/hooks/community/use-chan
const mocks = vi.hoisted(() => ({
serverMembers: [] as Array<Record<string, unknown>>,
+ viewerRole: "admin" as "owner" | "admin" | "member" | undefined,
serverMemberArgs: [] as Array<string | null>,
channelMembers: new Map<string, Array<Record<string, unknown>>>(),
channelQueryState: new Map<string, {
@@ -53,6 +54,9 @@ vi.mock("@/hooks/community/use-server-members", () => ({
}
},
}))
+vi.mock("@/hooks/community/use-servers", () => ({
+ useViewerServerRole: (serverId: string | null) => serverId ? mocks.viewerRole : undefined,
+}))
vi.mock("@/hooks/community/use-channel-members", () => ({
useChannelMembers: vi.fn((channelId: string, enabled = true) => {
const members = mocks.channelMembers.get(channelId) ?? []
@@ -189,6 +193,7 @@ function latestModel(): ReturnType<typeof useChannelMemberViewModel> {
describe("useChannelMemberViewModel", () => {
beforeEach(() => {
+ mocks.viewerRole = "admin"
mocks.serverMembers = [
member("viewer_1", "Viewer", { role: "admin" }),
member("alice_1", "Alice"),
@@ -263,6 +268,16 @@ describe("useChannelMemberViewModel", () => {
vi.clearAllMocks()
})
+ it("reads the qualified own role even when the member window excludes the viewer", () => {
+ mocks.serverMembers = [member("alice_1", "Alice")]
+ const renderer = rtlRender(renderHarness(props()))
+ expect(latestModel().myRole).toBe("admin")
+ mocks.viewerRole = undefined
+ renderer.rerender(renderHarness(props()))
+ expect(latestModel().myRole).toBeUndefined()
+ renderer.unmount()
+ })
+
it("uses the public server roster, excludes self, and keeps the raw-roster resolver stable across presence ticks", () => {
mocks.serverMembers = [
member("viewer_1", "Viewer", { role: "admin" }),
diff --git a/src/web/src/components/community/members/channel-member-view-model.tsx b/src/web/src/components/community/members/channel-member-view-model.tsx
index 23b49f90b..9ccc9be34 100644
--- a/src/web/src/components/community/members/channel-member-view-model.tsx
+++ b/src/web/src/components/community/members/channel-member-view-model.tsx
@@ -19,6 +19,7 @@ import {
useRemoveChannelMember,
} from "@/hooks/community/use-channel-members"
import { useServerMembers } from "@/hooks/community/use-server-members"
+import { useViewerServerRole } from "@/hooks/community/use-servers"
import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"
import {
useAddThreadParticipant,
@@ -96,6 +97,7 @@ export function useChannelMemberViewModel({
myRole: Role | undefined
} {
const membersHook = useServerMembers(accessAllowed && currentServer ? serverId : null)
+ const myRole = useViewerServerRole(accessAllowed && currentServer ? serverId : null, currentUser.id)
const source = useCommunityViewSource(`channel-members:${serverId}:${channelId}`, accessAllowed)
const originalView = useCallback((caller?: MemberOriginalView) => {
const local = source.capture()
@@ -312,7 +314,6 @@ export function useChannelMemberViewModel({
],
)
- const myRole = members.find((member) => member.userId === currentUser.id)?.role
const unitCreatorId = isChildChannel
? currentChannelMeta?.creatorId
: channelInServer?.creatorId
diff --git a/src/web/src/hooks/community/use-channel-metadata.dom.test.ts b/src/web/src/hooks/community/use-channel-metadata.dom.test.ts
index 638b4bb9c..dd1ddb71b 100644
--- a/src/web/src/hooks/community/use-channel-metadata.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-metadata.dom.test.ts
@@ -319,3 +319,23 @@ describe("DM history permission stays separate from metadata identity", () => {
route.unmount()
})
})
+
+
+describe("restored forum archive ambiguity", () => {
+ it("waits for current metadata instead of treating a persisted opener tag as channel denial", async () => {
+ const client = new QueryClient()
+ const post = { ...metadata, id: "post-1", serverId: "server-1", type: "thread", name: "Post", parentChannelId: "forum-1", parentMessageId: "opener-1" }
+ client.setQueryData(communityKeys.communityDbCollection("viewer", "channels"), [{ ...post, archived: true, tags: ["archived"], position: 0, muted: false, unread: false, pending: false }])
+ const { registry, wrapper } = await fixture(client)
+ const held = deferred<typeof post>()
+ apiFetch.mockReturnValue(held.promise)
+ const route = renderHook(() => useChannelMetadata("server-1", post.id), { wrapper })
+ expect(route.result.current.data?.archived).toBe(true)
+ expect(route.result.current.isArchived).toBe(false)
+ expect(route.result.current.isVerified).toBe(false)
+ await act(async () => held.resolve(post))
+ await waitFor(() => expect(route.result.current.isVerified).toBe(true))
+ expect(registry.collections.channels.get(post.id)).toMatchObject({ archived: false, tags: ["archived"] })
+ route.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/use-channel-metadata.ts b/src/web/src/hooks/community/use-channel-metadata.ts
index d8ecd531b..d15f46160 100644
--- a/src/web/src/hooks/community/use-channel-metadata.ts
+++ b/src/web/src/hooks/community/use-channel-metadata.ts
@@ -37,10 +37,12 @@ export function useChannelMetadata(serverId: string | null, channelId: string |
}, [accessEpoch, accountEpoch, viewerId, generation, channelId, revoked, query.data, queryClient, serverId])
const denied = typeof query.error === "object" && query.error !== null && "status" in query.error
&& (query.error.status === 403 || query.error.status === 404)
- const isVerified = !!query.data && query.data.id === channelId
+ const hasCurrentVerification = !!query.data && query.data.id === channelId
&& canonical?.serverId === serverId && query.data.verifiedEpoch === accessEpoch
&& !!query.data.verification && isChannelMetadataTokenCurrent(query.data.verification)
- && !revoked && !denied && !canonical?.archived && !canonical?.pending
+ && !revoked && !denied && !canonical?.pending
+ const isArchived = hasCurrentVerification && !!canonical?.archived
+ const isVerified = hasCurrentVerification && !canonical?.archived
const data = useMemo(() => canonical && canonical.id === channelId && canonical.serverId === serverId
? { ...canonical,
serverId,
@@ -54,5 +56,5 @@ export function useChannelMetadata(serverId: string | null, channelId: string |
creatorId: canonical.creatorId ?? null,
lastMessageAt: canonical.lastMessageAt ?? null }
: undefined, [canonical, channelId, query.data, serverId])
- return { ...query, data, isVerified, denied, canonical }
+ return { ...query, data, isVerified, isArchived, denied, canonical }
}
diff --git a/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts b/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
index 4b6def97f..e3742aa89 100644
--- a/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
@@ -214,6 +214,26 @@ describe("unresolved metadata terminal error and retry", () => {
if (status !== 401) expect(mocks.replace).toHaveBeenCalledWith("/c/channels/server-1")
})
+ it("keeps a legacy tag-derived archive bit pending without purging or revoking access", async () => {
+ const owner = getCommunityDbRegistry(client)!
+ owner.collections.channels.utils.writeUpsert([{ ...payload(), type: "thread", archived: true, tags: ["archived"], position: 0, muted: false, unread: false, pending: false }])
+ owner.collections.messages.utils.writeUpsert([{ id: "reply-1", channelId: "post-1", type: "chat", content: "kept" }])
+ const held = deferred()
+ mocks.apiFetch.mockReturnValue(held.promise)
+ await mount()
+ await until(() => mocks.apiFetch.mock.calls.length > 0)
+ expect(current.routeLifecycle).toBe("pending")
+ expect(mocks.replace).not.toHaveBeenCalled()
+ expect(owner.runtime.ws.actions.isChannelAccessRevoked("post-1", "server-1")).toBe(false)
+ expect(owner.collections.messages.get("reply-1")?.content).toBe("kept")
+ await act(async () => held.resolve(payload()))
+ await until(() => current.routeHydrated)
+ expect(owner.collections.channels.get("post-1")?.archived).toBe(false)
+ expect(owner.collections.channels.get("post-1")?.tags).toEqual(["archived"])
+ expect(mocks.replace).not.toHaveBeenCalled()
+ expect(owner.collections.messages.get("reply-1")?.content).toBe("kept")
+ })
+
it("does not retain a trusted route after an archived metadata response", async () => {
mocks.apiFetch.mockResolvedValue(payload())
await mount()
@@ -222,6 +242,8 @@ describe("unresolved metadata terminal error and retry", () => {
await act(async () => { await reconcileCommunityWsReconnect(client, 60_000) })
await until(() => !current.routeHydrated)
expect(current.routeLifecycle).not.toBe("ready")
+ expect(mocks.replace).toHaveBeenCalledOnce()
+ expect(getCommunityDbRegistry(client)!.runtime.ws.actions.isChannelAccessRevoked("post-1", "server-1")).toBe(true)
})
it("requires fresh metadata after reauthorization and can exit again on a later denial", async () => {
diff --git a/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts b/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
index a5e57f786..be5419607 100644
--- a/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
@@ -17,7 +17,7 @@ const mocks = vi.hoisted(() => ({
metaQuery: {
data: undefined as undefined | Record<string, unknown>,
error: null as unknown,
- isVerified: false,
+ isVerified: false, isArchived: false,
isError: false,
},
dbChannel: undefined as undefined | Record<string, unknown>,
@@ -96,7 +96,7 @@ beforeEach(async () => {
channels: [{ id: "forum-1", name: "Forum", type: "forum" }],
}],
}
- mocks.metaQuery = { data: undefined, error: null, isVerified: false, isError: false }
+ mocks.metaQuery = { data: undefined, error: null, isVerified: false, isArchived: false, isError: false }
mocks.dbChannel = undefined
})
@@ -178,7 +178,7 @@ describe("useChannelRouteModel subscription ownership", () => {
expect(renderer.container.querySelector("span")).toHaveAttribute("data-lifecycle", "pending")
expect(renderer.container.querySelector("span")).toHaveAttribute("data-parent-channel", "")
mocks.metaQuery = { data: { ...mocks.dbChannel, creatorId: null, lastMessageAt: null, createdAt: "", archived: false },
- error: null, isVerified: true, isError: false }
+ error: null, isVerified: true, isArchived: false, isError: false }
act(() => renderer.rerender(React.createElement(Harness)))
expect(renderer.container.querySelector("span")).toHaveAttribute("data-lifecycle", "ready")
expect(renderer.container.querySelector("span")).toHaveAttribute("data-creator-id", "")
@@ -231,7 +231,7 @@ describe("useChannelRouteModel subscription ownership", () => {
verifiedEpoch: 0,
},
error: null,
- isVerified: true,
+ isVerified: true, isArchived: false,
isError: false,
}
act(() => {
@@ -260,7 +260,7 @@ describe("useChannelRouteModel subscription ownership", () => {
activityAt: "2026-08-09T00:00:00.000Z",
verifiedEpoch: 0,
}
- mocks.metaQuery = { data: meta, error: null, isVerified: true, isError: false }
+ mocks.metaQuery = { data: meta, error: null, isVerified: true, isArchived: false, isError: false }
const storeListener = vi.fn()
const subscription = getCommunityRuntime(queryClient).ui.subscribe(storeListener)
const renderer = render(React.createElement(Harness))
@@ -269,7 +269,7 @@ describe("useChannelRouteModel subscription ownership", () => {
mocks.metaQuery = {
data: { ...meta },
error: null,
- isVerified: true,
+ isVerified: true, isArchived: false,
isError: false,
}
act(() => renderer.rerender(React.createElement(Harness)))
@@ -283,7 +283,7 @@ describe("useChannelRouteModel subscription ownership", () => {
mocks.metaQuery = {
data: undefined,
error: new Error("metadata unavailable"),
- isVerified: false,
+ isVerified: false, isArchived: false,
isError: true,
}
let renderer: ReturnType<typeof render>
@@ -310,7 +310,7 @@ describe("useChannelRouteModel subscription ownership", () => {
verifiedEpoch: 0,
},
error: null,
- isVerified: true,
+ isVerified: false, isArchived: true,
isError: false,
}
let renderer: ReturnType<typeof render>
@@ -345,7 +345,7 @@ describe("useChannelRouteModel subscription ownership", () => {
verifiedEpoch: 0,
},
error: null,
- isVerified: true,
+ isVerified: false, isArchived: true,
isError: false,
}
diff --git a/src/web/src/hooks/community/use-channel-route-model.ts b/src/web/src/hooks/community/use-channel-route-model.ts
index eb0a3164f..c09dbac69 100644
--- a/src/web/src/hooks/community/use-channel-route-model.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.ts
@@ -125,7 +125,7 @@ export function useChannelRouteModel(
const retryingMetadata = retryAttempt?.scope === retryScope
const metadataExit = metadataExited || isDefinitiveChildMetaFailure(metaQuery.error)
|| (metaQuery.error instanceof ApiError && metaQuery.error.status === 401)
- || !!metaQuery.data?.archived
+ || metaQuery.isArchived
const metadataError = !metaQuery.isVerified && !metadataExit
&& (metaQuery.isError || retryingMetadata)
const { refetch: refetchMetadata, isFetching: fetchingMetadata } = metaQuery
@@ -184,10 +184,10 @@ export function useChannelRouteModel(
}, [channelId, runtime])
useEffect(() => {
const denied = isDefinitiveChildMetaFailure(metaQuery.error)
- if (!isChild && !denied && !metaQuery.data?.archived) {
+ if (!isChild && !denied && !metaQuery.isArchived) {
return
}
- if (denied || metaQuery.data?.archived) {
+ if (denied || metaQuery.isArchived) {
if (metadataExited) return
setExitedMetadata({ owner: communityDb, scope: exitScope })
const store = runtime.ui.get()
@@ -214,7 +214,7 @@ export function useChannelRouteModel(
} else if (metaQuery.error) {
toastApiError(metaQuery.error, "Failed to load channel")
}
- }, [accountId, channelId, communityDb, isChild, metaQuery.data, metaQuery.error, metaQuery.isVerified, queryClient, renderableChannelMeta, router, runtime.ui, runtime.ws.actions, serverId, serverParam, metadataExited, exitScope, setExitedMetadata])
+ }, [accountId, channelId, communityDb, isChild, metaQuery.data, metaQuery.error, metaQuery.isVerified, metaQuery.isArchived, queryClient, renderableChannelMeta, router, runtime.ui, runtime.ws.actions, serverId, serverParam, metadataExited, exitScope, setExitedMetadata])
return {
...model,
routeHydrated: model.routeHydrated && metaQuery.isVerified,
diff --git a/src/web/src/hooks/community/use-forum-feed.dom.test.ts b/src/web/src/hooks/community/use-forum-feed.dom.test.ts
index 941ec9b16..6df571373 100644
--- a/src/web/src/hooks/community/use-forum-feed.dom.test.ts
+++ b/src/web/src/hooks/community/use-forum-feed.dom.test.ts
@@ -107,11 +107,12 @@ describe("forumFeedPageQueryFn", () => {
})
it("uses the archive tag as its own feed query", async () => {
- apiFetchMock.mockResolvedValue({ serverId: "server_1", parentType: "forum", threads: [], included: emptyIncluded, hasMore: false })
+ apiFetchMock.mockResolvedValue({ serverId: "server_1", parentType: "forum", threads: [{ id: "archived-post", name: "Post", creatorId: "author", messageCount: 1, parentMessageId: "opener", lastMessageAt: null, createdAt: "2026-10-04T00:00:00Z", activityAt: "2026-10-04T00:00:00Z" }], included: { ...emptyIncluded, tags: [{ messageId: "opener", tag: "archived" }] }, hasMore: false })
await forumFeedPageQueryFn("forum_one", "archived", client)({ pageParam: null })
const url = apiFetchMock.mock.calls[0]![0] as string
expect(new URL(url, "http://localhost").searchParams.get("tag")).toBe("archived")
+ expect(getCanonicalCommunityChannels(client).find((row) => row.id === "archived-post")).toMatchObject({ archived: false, tags: ["archived"] })
})
it("passes the query abort signal through to the request", async () => {
diff --git a/src/web/src/hooks/community/use-servers.dom.test.ts b/src/web/src/hooks/community/use-servers.dom.test.ts
index c4ed62500..b0a7dc8f9 100644
--- a/src/web/src/hooks/community/use-servers.dom.test.ts
+++ b/src/web/src/hooks/community/use-servers.dom.test.ts
@@ -4,11 +4,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
import { createCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"
import { CommunityDbProvider } from "@/lib/community-db/projections"
-import { captureCommunityLiveSnapshotToken, publishAccountAttentionSnapshot, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"
+import { captureCommunityLiveSnapshotToken, publishAccountAttentionSnapshot, publishCommunityLiveSnapshot, projectCommunityWsEventToDb, publishCommunityChannelDirectory } from "@/lib/community-db/sync"
import { communityKeys } from "@/lib/query-keys"
import { ApiError } from "@/lib/errors"
import { AccountUnreadProjection, getActiveAccountUnreadProjection } from "./account-unread-projection"
-import { serversQueryFn, serversProjectedQueryFn, serverProjectedQueryFn, useServers, useServer, type ServersResponse, type ServerDetail } from "./use-servers"
+import { serversQueryFn, serversProjectedQueryFn, serverProjectedQueryFn, useServers, useServer, useViewerServerRole, type ServersResponse, type ServerDetail } from "./use-servers"
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetchMock(...args) }))
@@ -454,3 +454,52 @@ describe("useServer / projected canonical detail", () => {
expect(apiFetchMock.mock.calls.some(([url]) => String(url).endsWith("/unreads"))).toBe(false)
})
})
+
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((done) => { resolve = done })
+ return { promise, resolve }
+}
+
+describe("qualified viewer server role", () => {
+ it("uses the live own membership before roster pagination and follows member-id-only demotion", async () => {
+ apiFetchMock.mockResolvedValue({ servers: [{ ...identity, role: "admin", memberId: "own-member" }] })
+ await fetchList()
+ const view = renderHook(() => useViewerServerRole(identity.id, "viewer"), { wrapper: Owner })
+ await waitFor(() => expect(view.result.current).toBe("admin"))
+ expect(apiFetchMock.mock.calls.map(([url]) => url)).toEqual(["/api/community/servers"])
+ act(() => publishCommunityChannelDirectory(client, { directory: [{ id: identity.id, name: identity.name, discriminator: identity.discriminator, channels: [] }], proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined } }))
+ expect(registry.collections.serverMemberships.get("srv_1:viewer")).toMatchObject({ role: "admin", memberId: "own-member" })
+ act(() => projectCommunityWsEventToDb(client, { type: "community:member.update", serverId: identity.id, memberId: "own-member", changes: { role: "member" } }))
+ await waitFor(() => expect(view.result.current).toBe("member"))
+ view.unmount()
+ })
+
+ it("retains a current own role when access to an unrelated channel is revoked", async () => {
+ apiFetchMock.mockResolvedValue({ servers: [{ ...identity, role: "admin", memberId: "own-member" }] })
+ await fetchList()
+ const view = renderHook(() => useViewerServerRole(identity.id, "viewer"), { wrapper: Owner })
+ await waitFor(() => expect(view.result.current).toBe("admin"))
+ act(() => registry.runtime.ws.actions.revokeChannelAccess("other-server", "other-channel"))
+ expect(view.result.current).toBe("admin")
+ view.unmount()
+ })
+
+ it("does not authorize a restored role, a revoked server or another viewer", async () => {
+ seedList()
+ registry.collections.serverMemberships.utils.writeUpsert([{ ...registry.collections.serverMemberships.get("srv_1:viewer")!, role: "admin" }])
+ const held = deferred<{ servers: Array<typeof identity & { role: string; memberId: string }> }>()
+ apiFetchMock.mockReturnValue(held.promise)
+ const view = renderHook(({ viewerId }) => useViewerServerRole(identity.id, viewerId), { wrapper: Owner, initialProps: { viewerId: "viewer" } })
+ expect(view.result.current).toBeUndefined()
+ await act(async () => { const request = fetchList(); held.resolve({ servers: [{ ...identity, role: "admin", memberId: "own-member" }] }); await request })
+ await waitFor(() => expect(view.result.current).toBe("admin"))
+ view.rerender({ viewerId: "other-account" })
+ expect(view.result.current).toBeUndefined()
+ view.rerender({ viewerId: "viewer" })
+ act(() => registry.runtime.ws.actions.revokeServerAccess(identity.id))
+ expect(view.result.current).toBeUndefined()
+ view.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.ts
index 89ad51f6f..ec084c731 100644
--- a/src/web/src/hooks/community/use-servers.ts
+++ b/src/web/src/hooks/community/use-servers.ts
@@ -19,7 +19,7 @@ import type { ServerRow } from "@/lib/community-db/schema"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { avatarInitial } from "@/lib/community/avatar"
-import { isServerOwner,UNCATEGORIZED_CATEGORY_ID } from "@alook/shared"
+import { isServerOwner,UNCATEGORIZED_CATEGORY_ID, type CommunityRole } from "@alook/shared"
import type { Server,Category,Channel } from "@/lib/community/models/navigation"
import {
getActiveAccountUnreadProjection,
@@ -29,6 +29,7 @@ type AccountUnreadScope,
type AccountUnreadSource,
} from "./account-unread-projection"
import { useCommunityWsStore } from "@/stores/community/ws"
+import { useCommunityRuntime } from "@/stores/community/runtime"
import { ApiError } from "@/lib/errors"
import { evictServerChannelScopes } from "./community-ws/scope-eviction"
import {
@@ -36,6 +37,7 @@ useAttentionScopes,
useOptionalCommunityDbRegistry,
useServerRailProjection,
useServerTreeProjection,
+useServerMemberRows,
} from "@/lib/community-db/projections"
import {
assertCommunityLiveSnapshotTokenCurrent,
@@ -58,6 +60,7 @@ type RawServerRow = {
icon: string | null
official?: boolean
role?: string
+ memberId?: string
mentions?: number
unread?: boolean
description?: string | null
@@ -93,6 +96,8 @@ export const serversQueryFn = async (
// absent — treat it as 0 rather than NaN.
mentions: s.mentions ?? 0,
isOwner: isServerOwner(s.role),
+ ...(["owner", "admin", "member"].includes(s.role ?? "") ? { role: s.role as CommunityRole } : {}),
+ ...(s.memberId ? { memberId: s.memberId } : {}),
icon: s.icon ?? null,
official: s.official === true,
...(s.unreadSources ? { unreadSources: s.unreadSources } : {}),
@@ -210,6 +215,25 @@ export function useServers(): UseQueryResult<string[]> & { servers: Server[]; is
// ── Single-server detail ─────────────────────────────────────────────────────
+export function useViewerServerRole(serverId: string | null, viewerId: string): CommunityRole | undefined {
+ const registry = useOptionalCommunityDbRegistry()
+ const runtime = useCommunityRuntime()
+ const { servers } = useServers()
+ const authority = useSelector(registry?.serverListAuthority ?? absentAuthority, (value) => value)
+ const ownerGeneration = useSelector(runtime.lifecycle, (state) => state.active ? state.generation : -1)
+ const memberships = useServerMemberRows(serverId, [viewerId])
+ const qualified = useCommunityWsStore((state) => !!authority
+ && authority.viewerId === viewerId && state.profileViewerId === viewerId
+ && authority.accountEpoch === state.profileAccountEpoch
+ && authority.ownerGeneration === ownerGeneration
+ && !!serverId && !state.revokedServerIds.has(serverId))
+ if (!qualified || viewerId !== registry?.accountId
+ || !servers.some((server) => server.id === serverId)) return undefined
+ const membership = memberships.find((row) => row.viewer && row.userId === viewerId)
+ const role = membership?.role
+ return role === "owner" || role === "admin" || role === "member" ? role : undefined
+}
+
export type ServerDetail = {
id: string
name: string
diff --git a/src/web/src/lib/community-db/sync.test.ts b/src/web/src/lib/community-db/sync.test.ts
index c59bf3604..6ecfe615c 100644
--- a/src/web/src/lib/community-db/sync.test.ts
+++ b/src/web/src/lib/community-db/sync.test.ts
@@ -2712,3 +2712,16 @@ describe("community DB sync", () => {
uninstall()
})
})
+
+
+describe("forum archive channel semantics", () => {
+ it("keeps opener archive tags separate when publishing embedded thread previews", async () => {
+ const db = await registry()
+ const message = { id: "opener", type: "chat" as const, content: "Post", thread: { id: "post", name: "Post", messageCount: 1, tags: ["archived"], participants: [] } }
+ ingestMessages(db, "forum", [message])
+ expect(db.collections.channels.get("post")).toMatchObject({ archived: false, tags: ["archived"] })
+ db.collections.channels.utils.writeUpsert([{ ...db.collections.channels.get("post")!, archived: true }])
+ ingestMessages(db, "forum", [{ ...message, thread: { ...message.thread, tags: [] } }])
+ expect(db.collections.channels.get("post")).toMatchObject({ archived: true, tags: [] })
+ })
+})
diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.ts
index 7a3aee4e4..c73a414e4 100644
--- a/src/web/src/lib/community-db/sync.ts
+++ b/src/web/src/lib/community-db/sync.ts
@@ -632,7 +632,8 @@ export function ingestServers(
id: serverMembershipKey(server.id, viewerId),
serverId: server.id,
userId: viewerId,
- role: server.isOwner ? "owner" : "member",
+ role: server.role ?? (server.isOwner ? "owner" : "member"),
+ ...(server.memberId ? { memberId: server.memberId } : {}),
viewer: true,
}))
: []
@@ -1069,7 +1070,7 @@ export function ingestMessages(
if (thread) {
const existing = collectionRows(registry, "channels", channelSchema).find((row) => row.id === thread.id)
const parent = collectionRows(registry, "channels", channelSchema).find((row) => row.id === channelId)
- upsertRows(registry, "channels", channelSchema, (row) => row.id, [{ ...existing, id: thread.id, serverId: existing?.serverId ?? parent?.serverId, categoryId: null, name: thread.name, type: "thread", parentChannelId: channelId, parentMessageId: message.id, creatorId: existing?.creatorId ?? null, position: existing?.position ?? 0, archived: thread.tags?.includes(FORUM_ARCHIVE_TAG) ?? existing?.archived ?? false, tags: thread.tags ?? existing?.tags ?? [], muted: existing?.muted ?? false, unread: existing?.unread ?? false, pending: false, messageCount: thread.messageCount, ...(thread.lastReplyAt ? { lastMessageAt: thread.lastReplyAt } : {}), ...(thread.preview !== undefined ? { preview: thread.preview } : {}), ...(thread.participantCount !== undefined ? { participantCount: thread.participantCount } : {}) }])
+ upsertRows(registry, "channels", channelSchema, (row) => row.id, [{ ...existing, id: thread.id, serverId: existing?.serverId ?? parent?.serverId, categoryId: null, name: thread.name, type: "thread", parentChannelId: channelId, parentMessageId: message.id, creatorId: existing?.creatorId ?? null, position: existing?.position ?? 0, archived: existing?.archived ?? false, tags: thread.tags ?? existing?.tags ?? [], muted: existing?.muted ?? false, unread: existing?.unread ?? false, pending: false, messageCount: thread.messageCount, ...(thread.lastReplyAt ? { lastMessageAt: thread.lastReplyAt } : {}), ...(thread.preview !== undefined ? { preview: thread.preview } : {}), ...(thread.participantCount !== undefined ? { participantCount: thread.participantCount } : {}) }])
}
return { ...fields, type: message.type ?? "chat", channelId, replyToId: message.replyTo?.id }
})
@@ -1109,6 +1110,7 @@ function ingestAttentionIncluded(
collectionRows(registry, "channels", channelSchema).map((row) => [row.id, row]),
)
const viewerId = registry.accountId
+ const existingMemberships = new Map(collectionRows(registry, "serverMemberships", serverMembershipSchema).map((row) => [row.id, row]))
const servers: ServerRow[] = (included?.servers ?? []).map((owner, position) => {
const existing = existingServers.get(owner.id)
return {
@@ -1158,10 +1160,11 @@ function ingestAttentionIncluded(
serverMembershipSchema,
(row) => row.id,
servers.map((server) => ({
+ ...existingMemberships.get(serverMembershipKey(server.id, viewerId)),
id: serverMembershipKey(server.id, viewerId),
serverId: server.id,
userId: viewerId,
- role: server.isOwner ? "owner" : "member",
+ role: existingMemberships.get(serverMembershipKey(server.id, viewerId))?.role ?? (server.isOwner ? "owner" : "member"),
viewer: true,
})),
)
@@ -1993,6 +1996,7 @@ export function publishCommunityChannelDirectory(
collectionRows(registry, "channels", channelSchema).map((row) => [row.id, row]),
)
const viewerId = registry.accountId
+ const existingMemberships = new Map(collectionRows(registry, "serverMemberships", serverMembershipSchema).map((row) => [row.id, row]))
const servers: ServerRow[] = publication.directory.map((server, position) => ({
id: server.id,
position: existingServers.get(server.id)?.position ?? position,
@@ -2043,10 +2047,11 @@ export function publishCommunityChannelDirectory(
serverMembershipSchema,
(row) => row.id,
servers.map((server) => ({
+ ...existingMemberships.get(serverMembershipKey(server.id, viewerId)),
id: serverMembershipKey(server.id, viewerId),
serverId: server.id,
userId: viewerId,
- role: server.isOwner ? "owner" : "member",
+ role: existingMemberships.get(serverMembershipKey(server.id, viewerId))?.role ?? (server.isOwner ? "owner" : "member"),
viewer: true,
})),
)
@@ -2366,7 +2371,7 @@ export function publishCommunityForumFeed(queryClient: QueryClient, forumChannel
...existing.get(thread.id), id: thread.id, serverId: page.serverId, categoryId: null, type: "thread", name: thread.name ?? "Post", creatorId: thread.creatorId,
parentChannelId: forumChannelId, parentMessageId: thread.parentMessageId, position: existing.get(thread.id)?.position ?? 0,
tags: page.included.tags.filter((tag) => tag.messageId === thread.parentMessageId).map((tag) => tag.tag),
- archived: page.included.tags.some((tag) => tag.messageId === thread.parentMessageId && tag.tag === FORUM_ARCHIVE_TAG), muted: existing.get(thread.id)?.muted ?? false, unread: existing.get(thread.id)?.unread ?? false, pending: false,
+ archived: existing.get(thread.id)?.archived ?? false, muted: existing.get(thread.id)?.muted ?? false, unread: existing.get(thread.id)?.unread ?? false, pending: false,
createdAt: thread.createdAt, messageCount: thread.messageCount ?? 0, lastMessageAt: thread.activityAt,
preview: page.included.firstMessages.find((message) => message.channelId === thread.id)?.content.slice(0, 100) ?? "",
participantCount: page.included.participants.find((participant) => participant.channelId === thread.id)?.participantCount ?? 0,
diff --git a/src/web/src/lib/community/models/navigation.ts b/src/web/src/lib/community/models/navigation.ts
index 947ffdcc7..84f5967da 100644
--- a/src/web/src/lib/community/models/navigation.ts
+++ b/src/web/src/lib/community/models/navigation.ts
@@ -1,4 +1,4 @@
-import type { ChannelType } from "@alook/shared"
+import type { ChannelType, CommunityRole } from "@alook/shared"
export type EntityKind = "text" | "forum" | "thread"
@@ -19,6 +19,8 @@ export type Server = {
mentionSources?: Array<{ channelId: string; count: number; lastSeq: number }>
official?: boolean
isOwner?: boolean
+ role?: CommunityRole
+ memberId?: string
icon?: string | null
}