Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(community): simplify WebSocket delivery and domains (#431)

Gener2749ff7d401a
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index 2ff1d91bc..e4e401044 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -632,11 +632,6 @@ export type CommunityWsEvent =
| CommunityMachineRemoved
| CommunityBotAuditEvent
-/** Type guard: is this a community WS event? */
-export function isCommunityEvent(msg: { type: string }): msg is CommunityWsEvent {
- return msg.type.startsWith("community:")
-}
-
/** Constant map of every community WS event type string. */
export const WS_EVENTS = {
MESSAGE_CREATE: "community:message.create",
@@ -681,3 +676,17 @@ export const WS_EVENTS = {
MACHINE_REMOVED: "community:machine.removed",
BOT_AUDIT_EVENT: "community:bot.audit_event",
} as const
+
+type DeclaredCommunityEventType = (typeof WS_EVENTS)[keyof typeof WS_EVENTS]
+type ExactCommunityEventType = Exclude<CommunityWsEvent["type"], DeclaredCommunityEventType> extends never
+ ? Exclude<DeclaredCommunityEventType, CommunityWsEvent["type"]> extends never
+ ? CommunityWsEvent["type"]
+ : never
+ : never
+
+const COMMUNITY_EVENT_TYPES: ReadonlySet<string> = new Set<ExactCommunityEventType>(Object.values(WS_EVENTS))
+
+/** Type guard: is this a community WS event? */
+export function isCommunityEvent(msg: { type: string }): msg is CommunityWsEvent {
+ return COMMUNITY_EVENT_TYPES.has(msg.type)
+}
diff --git a/src/shared/src/db/queries/community/members-resolver.ts b/src/shared/src/db/queries/community/members-resolver.ts
index 1aa3f9289..3c025e81a 100644
--- a/src/shared/src/db/queries/community/members-resolver.ts
+++ b/src/shared/src/db/queries/community/members-resolver.ts
@@ -5,13 +5,19 @@ import {
} from "../../community-schema";
import type { Database } from "../../index";
import type { CommunityRole } from "../../../utils/community-roles";
-import { canManageServer } from "../../../utils/community-roles";
import {
+ canManageServer,
+ channelReach,
+ isStoredChannelType,
+} from "../../../utils/community-roles";
+import {
+ getChannelType,
getPrivateChannelAudienceUserIds,
isChannelPrivate,
listChannelMemberUserIds,
} from "./channel";
import { listMemberUserIds } from "./member";
+import { listThreadParticipantUserIds } from "./thread";
// The ACCESS scopes — units that own (or inherit) a stored/derived access
// roster. `forum` resolves like a top-level text channel (its own roster);
@@ -31,6 +37,43 @@ export type ScopeMember = {
source: MemberSource;
};
+export type ChannelRecipientQueryPhase =
+ | "channel-type"
+ | "thread-participants"
+ | "dm-members"
+ | "scope-members";
+
+export type ChannelRecipientQueryRunner = <T>(
+ phase: ChannelRecipientQueryPhase,
+ query: () => Promise<T>,
+) => Promise<T>;
+
+const runChannelRecipientQuery: ChannelRecipientQueryRunner = (_phase, query) => query();
+
+export async function resolveChannelRecipientUserIds(
+ db: Database,
+ channelId: string,
+ runQuery: ChannelRecipientQueryRunner = runChannelRecipientQuery,
+): Promise<string[]> {
+ const type = await runQuery("channel-type", () => getChannelType(db, channelId));
+ const reach = isStoredChannelType(type) ? channelReach(type) : "server-or-roster";
+ switch (reach) {
+ case "participant-set":
+ return runQuery("thread-participants", () => listThreadParticipantUserIds(db, channelId));
+ case "dm-pair":
+ return runQuery("dm-members", () => listChannelMemberUserIds(db, channelId));
+ case "server-or-roster":
+ return runQuery(
+ "scope-members",
+ () => resolveScopeMemberUserIds(db, { scope: "channel", scopeId: channelId }),
+ );
+ default: {
+ const _never: never = reach;
+ return _never;
+ }
+ }
+}
+
/**
* The single source of truth for "who can access this scope." Consolidates the
* public/private split for the ACCESS dimension:
diff --git a/src/shared/test/community-ws-events.test.ts b/src/shared/test/community-ws-events.test.ts
index f7563cf8a..18615ad86 100644
--- a/src/shared/test/community-ws-events.test.ts
+++ b/src/shared/test/community-ws-events.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { isCommunityEvent } from "../src/community-ws-events";
+import { isCommunityEvent, WS_EVENTS } from "../src/community-ws-events";
import type {
CommunityMachineCreated,
CommunityMachineUpdated,
@@ -7,19 +7,16 @@ import type {
} from "../src/community-ws-events";
describe("isCommunityEvent", () => {
- it("returns true for community:machine.created", () => {
- expect(isCommunityEvent({ type: "community:machine.created" })).toBe(true);
+ it("accepts every exact event declared by WS_EVENTS", () => {
+ expect(Object.values(WS_EVENTS)).toHaveLength(41);
+ for (const type of Object.values(WS_EVENTS)) {
+ expect(isCommunityEvent({ type })).toBe(true);
+ }
});
- it("returns true for community:machine.status", () => {
- expect(isCommunityEvent({ type: "community:machine.status" })).toBe(true);
- });
- it("returns true for community:machine.updated", () => {
- expect(isCommunityEvent({ type: "community:machine.updated" })).toBe(true);
- });
- it("returns true for community:machine.removed", () => {
- expect(isCommunityEvent({ type: "community:machine.removed" })).toBe(true);
- });
- it("returns false for non-community events", () => {
+
+ it("rejects unknown, approximate, and non-community event names", () => {
+ expect(isCommunityEvent({ type: "community:unknown" })).toBe(false);
+ expect(isCommunityEvent({ type: "community:message.create.extra" })).toBe(false);
expect(isCommunityEvent({ type: "foo:bar" })).toBe(false);
expect(isCommunityEvent({ type: "runtime.status" })).toBe(false);
});
diff --git a/src/shared/test/queries/community-members-resolver.test.ts b/src/shared/test/queries/community-members-resolver.test.ts
index 99f17679c..6bd9dbaf7 100644
--- a/src/shared/test/queries/community-members-resolver.test.ts
+++ b/src/shared/test/queries/community-members-resolver.test.ts
@@ -6,19 +6,28 @@ const mockIsChannelPrivate = vi.fn<() => Promise<boolean>>();
const mockGetPrivateChannelAudienceUserIds = vi.fn<() => Promise<string[]>>();
const mockListChannelMemberUserIds = vi.fn<() => Promise<string[]>>();
const mockListMemberUserIds = vi.fn<() => Promise<string[]>>();
+const mockGetChannelType = vi.fn<() => Promise<string | null>>();
+const mockListThreadParticipantUserIds = vi.fn<() => Promise<string[]>>();
vi.mock("../../src/db/queries/community/channel", () => ({
isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...(a as [])),
getPrivateChannelAudienceUserIds: (...a: unknown[]) =>
mockGetPrivateChannelAudienceUserIds(...(a as [])),
listChannelMemberUserIds: (...a: unknown[]) => mockListChannelMemberUserIds(...(a as [])),
+ getChannelType: (...a: unknown[]) => mockGetChannelType(...(a as [])),
}));
vi.mock("../../src/db/queries/community/member", () => ({
listMemberUserIds: (...a: unknown[]) => mockListMemberUserIds(...(a as [])),
}));
+vi.mock("../../src/db/queries/community/thread", () => ({
+ listThreadParticipantUserIds: (...a: unknown[]) =>
+ mockListThreadParticipantUserIds(...(a as [])),
+}));
+
import {
+ resolveChannelRecipientUserIds,
resolveScopeMemberUserIds,
resolveScopeMembers,
} from "../../src/db/queries/community/members-resolver";
@@ -60,6 +69,84 @@ const CHANNEL = "chan-1";
beforeEach(() => {
vi.clearAllMocks();
+ mockGetChannelType.mockResolvedValue("text");
+ mockListThreadParticipantUserIds.mockResolvedValue([]);
+ mockListChannelMemberUserIds.mockResolvedValue([]);
+ mockIsChannelPrivate.mockResolvedValue(false);
+ mockListMemberUserIds.mockResolvedValue([]);
+});
+
+describe("resolveChannelRecipientUserIds", () => {
+ const runWithPhaseLog = (phases: string[]) =>
+ async <T>(phase: string, query: () => Promise<T>): Promise<T> => {
+ phases.push(phase);
+ return query();
+ };
+
+ it("participant-set routes only to thread participants with ordered phases", async () => {
+ mockGetChannelType.mockResolvedValue("thread");
+ mockListThreadParticipantUserIds.mockResolvedValue(["p1", "p2"]);
+ const phases: string[] = [];
+
+ await expect(
+ resolveChannelRecipientUserIds({} as Database, CHANNEL, runWithPhaseLog(phases)),
+ ).resolves.toEqual(["p1", "p2"]);
+
+ expect(phases).toEqual(["channel-type", "thread-participants"]);
+ expect(mockListChannelMemberUserIds).not.toHaveBeenCalled();
+ expect(mockIsChannelPrivate).not.toHaveBeenCalled();
+ });
+
+ it("dm-pair routes only to channel access members", async () => {
+ mockGetChannelType.mockResolvedValue("dm");
+ mockListChannelMemberUserIds.mockResolvedValue(["u1", "u2"]);
+ const phases: string[] = [];
+
+ await expect(
+ resolveChannelRecipientUserIds({} as Database, CHANNEL, runWithPhaseLog(phases)),
+ ).resolves.toEqual(["u1", "u2"]);
+
+ expect(phases).toEqual(["channel-type", "dm-members"]);
+ expect(mockListThreadParticipantUserIds).not.toHaveBeenCalled();
+ expect(mockIsChannelPrivate).not.toHaveBeenCalled();
+ });
+
+ it("server-or-roster routes only to the existing scope resolver", async () => {
+ mockGetChannelType.mockResolvedValue("text");
+ mockListMemberUserIds.mockResolvedValue(["u1", "u2"]);
+ const phases: string[] = [];
+ const db = makeDb({ select: [[{ serverId: "srv-1" }]] });
+
+ await expect(resolveChannelRecipientUserIds(db, CHANNEL, runWithPhaseLog(phases)))
+ .resolves.toEqual(["u1", "u2"]);
+
+ expect(phases).toEqual(["channel-type", "scope-members"]);
+ expect(mockListThreadParticipantUserIds).not.toHaveBeenCalled();
+ expect(mockListChannelMemberUserIds).not.toHaveBeenCalled();
+ });
+
+ it.each(["unknown", null])("%s channel type uses the historical scope fallback", async (type) => {
+ mockGetChannelType.mockResolvedValue(type);
+ mockListMemberUserIds.mockResolvedValue(["fallback"]);
+ const phases: string[] = [];
+ const db = makeDb({ select: [[{ serverId: "srv-1" }]] });
+
+ await expect(resolveChannelRecipientUserIds(db, CHANNEL, runWithPhaseLog(phases)))
+ .resolves.toEqual(["fallback"]);
+ expect(phases).toEqual(["channel-type", "scope-members"]);
+ });
+
+ it("propagates a selected phase failure unchanged", async () => {
+ const failure = new Error("thread lookup failed");
+ mockGetChannelType.mockResolvedValue("thread");
+ mockListThreadParticipantUserIds.mockRejectedValue(failure);
+ const phases: string[] = [];
+
+ await expect(
+ resolveChannelRecipientUserIds({} as Database, CHANNEL, runWithPhaseLog(phases)),
+ ).rejects.toBe(failure);
+ expect(phases).toEqual(["channel-type", "thread-participants"]);
+ });
});
describe("resolveScopeMemberUserIds", () => {
diff --git a/src/web/playwright.config.ts b/src/web/playwright.config.ts
index 4efd14ef8..6f71fde6a 100644
--- a/src/web/playwright.config.ts
+++ b/src/web/playwright.config.ts
@@ -7,8 +7,10 @@ export default defineConfig({
testMatch: "**/*.spec.ts",
fullyParallel: false,
forbidOnly: !!process.env.CI,
- retries: process.env.CI ? 2 : 0,
- workers: process.env.CI ? 1 : undefined,
+ // The suite shares and mutates three seeded user accounts, so every run is
+ // single-worker and zero-retry; parallelism or retries would reuse state.
+ retries: 0,
+ workers: 1,
reporter: process.env.CI ? [["html", { open: "never" }], ["list"]] : "list",
globalSetup: "./src/test/e2e-ui/_setup/global-setup.ts",
globalTeardown: "./src/test/e2e-ui/_setup/global-teardown.ts",
@@ -16,7 +18,7 @@ export default defineConfig({
expect: { timeout: 10_000 },
use: {
baseURL: BASE_URL,
- trace: "on-first-retry",
+ trace: "retain-on-failure",
video: "retain-on-failure",
screenshot: "only-on-failure",
},
diff --git a/src/web/src/components/community/composer.send-lifecycle.test.ts b/src/web/src/components/community/composer.send-lifecycle.test.ts
new file mode 100644
index 000000000..ad3d22c98
--- /dev/null
+++ b/src/web/src/components/community/composer.send-lifecycle.test.ts
@@ -0,0 +1,185 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ useEditor: vi.fn(),
+ useFileAttachments: vi.fn(),
+}))
+
+vi.mock("@tiptap/react", () => ({
+ useEditor: (...args: unknown[]) => mocks.useEditor(...args),
+ EditorContent: () => null,
+}))
+
+vi.mock("@tiptap/starter-kit", () => ({
+ default: { configure: vi.fn(() => ({})) },
+}))
+
+vi.mock("@tiptap/extension-placeholder", () => ({
+ default: { configure: vi.fn(() => ({})) },
+}))
+
+vi.mock("@tiptap/pm/model", () => ({
+ DOMParser: { fromSchema: vi.fn() },
+}))
+
+vi.mock("@/lib/community/mention-extension", () => ({
+ buildCommunityMentionExtension: vi.fn(() => ({})),
+ detectMentionType: vi.fn(() => undefined),
+ EMPTY_MENTION_STATE: { items: [], selectedIndex: 0, command: null, rect: null },
+ rankMentionItems: vi.fn(() => []),
+}))
+
+vi.mock("@/lib/community/channel-ref-extension", () => ({
+ buildCommunityChannelRefExtension: vi.fn(() => ({})),
+ EMPTY_CHANNEL_REF_STATE: { items: [], selectedIndex: 0, command: null, rect: null },
+ rankChannelRefItems: vi.fn(() => []),
+ toChannelRefCommandProps: vi.fn(),
+}))
+
+vi.mock("@/hooks/use-file-attachments", () => ({
+ useFileAttachments: (...args: unknown[]) => mocks.useFileAttachments(...args),
+}))
+
+import { Composer, type ComposerProps } from "./composer"
+import type { PendingFile } from "@/hooks/use-file-attachments"
+
+describe("Composer committed send lifecycle", () => {
+ let firstEditorOptions: {
+ editorProps: {
+ handleKeyDown: (_view: unknown, event: KeyboardEvent) => boolean
+ }
+ } | undefined
+ let pendingFiles: PendingFile[]
+ let clearContent: ReturnType<typeof vi.fn>
+ let transferPendingFiles: ReturnType<typeof vi.fn>
+
+ beforeEach(() => {
+ firstEditorOptions = undefined
+ mocks.useEditor.mockReset()
+ mocks.useFileAttachments.mockReset()
+ pendingFiles = []
+ clearContent = vi.fn()
+ transferPendingFiles = vi.fn(() => pendingFiles)
+
+ const editor = {
+ isEmpty: false,
+ getText: vi.fn(() => "latest draft"),
+ getJSON: vi.fn(() => ({})),
+ commands: {
+ clearContent,
+ focus: vi.fn(),
+ setContent: vi.fn(),
+ },
+ chain: vi.fn(() => ({
+ focus: vi.fn(() => ({
+ insertContent: vi.fn(() => ({ run: vi.fn() })),
+ })),
+ })),
+ }
+
+ mocks.useEditor.mockImplementation((options) => {
+ firstEditorOptions ??= options
+ return editor
+ })
+ mocks.useFileAttachments.mockImplementation(() => ({
+ pendingFiles,
+ setPendingFiles: vi.fn(),
+ transferPendingFiles,
+ addPendingFiles: vi.fn(),
+ fileInputRef: { current: null },
+ handleFileSelect: vi.fn(),
+ removePendingFile: vi.fn(),
+ dragging: false,
+ handleDragEnter: vi.fn(),
+ handleDragLeave: vi.fn(),
+ handleDragOver: vi.fn(),
+ handleDrop: vi.fn(),
+ }))
+ })
+
+ it("routes the initially registered Enter handler through the latest attachments and callback", async () => {
+ const initialAccept = vi.fn(() => true)
+ const rejectedContexts: string[] = []
+ const rejectLatest = vi.fn(() => {
+ rejectedContexts.push("Latest reply")
+ return false
+ })
+ const acceptedLatest = vi.fn(() => true)
+ const baseProps = {
+ channel: "general",
+ context: "channel" as const,
+ members: [],
+ sendContract: "accepted" as const,
+ hideAttach: true,
+ hideEmoji: true,
+ }
+
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(Composer, {
+ ...baseProps,
+ onAcceptSend: initialAccept,
+ } satisfies ComposerProps))
+ })
+
+ const file = new File(["keep me"], "rejected.txt", { type: "text/plain" })
+ pendingFiles = [{ file, thumbnailUrl: null, thumbnailBlob: null }]
+ await act(async () => {
+ renderer.update(React.createElement(Composer, {
+ ...baseProps,
+ replyingTo: "Latest reply",
+ onAcceptSend: rejectLatest,
+ } satisfies ComposerProps))
+ })
+
+ const preventRejected = vi.fn()
+ await act(async () => {
+ expect(firstEditorOptions!.editorProps.handleKeyDown({} as never, {
+ key: "Enter",
+ shiftKey: false,
+ isComposing: false,
+ preventDefault: preventRejected,
+ } as unknown as KeyboardEvent)).toBe(true)
+ })
+
+ expect(preventRejected).toHaveBeenCalledOnce()
+ expect(initialAccept).not.toHaveBeenCalled()
+ expect(rejectLatest).toHaveBeenCalledWith(
+ "latest draft",
+ [{ file, previewObjectUrl: undefined, width: undefined, height: undefined }],
+ undefined,
+ )
+ expect(rejectedContexts).toEqual(["Latest reply"])
+ expect(clearContent).not.toHaveBeenCalled()
+ expect(transferPendingFiles).not.toHaveBeenCalled()
+ expect(JSON.stringify(renderer.toJSON())).toContain("rejected.txt")
+ expect(JSON.stringify(renderer.toJSON())).toContain("Latest reply")
+
+ await act(async () => {
+ renderer.update(React.createElement(Composer, {
+ ...baseProps,
+ replyingTo: "Latest reply",
+ onAcceptSend: acceptedLatest,
+ } satisfies ComposerProps))
+ })
+
+ await act(async () => {
+ firstEditorOptions!.editorProps.handleKeyDown({} as never, {
+ key: "Enter",
+ shiftKey: false,
+ isComposing: false,
+ preventDefault: vi.fn(),
+ } as unknown as KeyboardEvent)
+ })
+
+ expect(acceptedLatest).toHaveBeenCalledWith(
+ "latest draft",
+ [{ file, previewObjectUrl: undefined, width: undefined, height: undefined }],
+ undefined,
+ )
+ expect(clearContent).toHaveBeenCalledOnce()
+ expect(transferPendingFiles).toHaveBeenCalledOnce()
+ })
+})
diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsx
index dab06cd45..a20cf7088 100644
--- a/src/web/src/components/community/composer.tsx
+++ b/src/web/src/components/community/composer.tsx
@@ -191,6 +191,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
maxFileSize: MAX_ATTACHMENT_SIZE_BYTES,
})
const typingTimer = useRef<NodeJS.Timeout | null>(null)
+ const sendRef = useRef<() => void>(() => {})
// Draft cache key, held in a ref so the editor's `onUpdate` closure (captured
// once at build) always persists under the current scope. Restore is
@@ -333,7 +334,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
if (isForumThreadBody) {
if (event.key === "Enter" && event.shiftKey && !event.isComposing) {
event.preventDefault()
- send()
+ sendRef.current()
return true
}
return false
@@ -341,7 +342,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
event.preventDefault()
- send()
+ sendRef.current()
return true
}
return false
@@ -467,6 +468,10 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
setChannelRefPopup(EMPTY_CHANNEL_REF_STATE)
}
+ useEffect(() => {
+ sendRef.current = send
+ })
+
useImperativeHandle(ref, () => ({
focusEditor: () => { editor?.commands.focus("end") },
submitNow: () => {
diff --git a/src/web/src/hooks/community/community-ws/cache.test.ts b/src/web/src/hooks/community/community-ws/cache.test.ts
new file mode 100644
index 000000000..6ce29554e
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/cache.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from "vitest"
+import type {
+ CommunityReactionAdd,
+ CommunityReactionRemove,
+} from "@alook/shared"
+import type { Msg } from "@/components/community/_types"
+import {
+ applyReactionToCache,
+ applyReactionToMessage,
+ findCachedMessage,
+ patchApprovalInCache,
+ patchAuthorNameInCache,
+ patchMessageContentInCache,
+ removeThreadFromCache,
+ type PageCache,
+} from "./cache"
+
+function pageCache(...pages: Msg[][]): PageCache {
+ return {
+ pages: pages.map((messages) => ({ messages, hasMore: false })),
+ pageParams: pages.map(() => null),
+ }
+}
+
+describe("community WS cache helpers", () => {
+ it("preserves identity for undefined caches and misses", () => {
+ const cache = pageCache([{ id: "m_1", content: "one" }])
+ expect(patchAuthorNameInCache(undefined, "u_1", "New")).toBeUndefined()
+ expect(patchAuthorNameInCache(cache, "u_missing", "New")).toBe(cache)
+ expect(patchMessageContentInCache(cache, "m_missing", "New")).toBe(cache)
+ expect(removeThreadFromCache(cache, "thread_missing")).toBe(cache)
+ })
+
+ it("patches author names across pages without changing unrelated rows", () => {
+ const untouched = { id: "m_2", authorId: "u_2", authorName: "Other", content: "two" }
+ const cache = pageCache(
+ [{ id: "m_1", authorId: "u_1", authorName: "Old", content: "one" }, untouched],
+ [{ id: "m_3", authorId: "u_1", authorName: "Old", content: "three" }],
+ )
+
+ const result = patchAuthorNameInCache(cache, "u_1", "New")!
+
+ expect(result).not.toBe(cache)
+ expect(result.pages[0].messages[0].authorName).toBe("New")
+ expect(result.pages[0].messages[1]).toBe(untouched)
+ expect(result.pages[1].messages[0].authorName).toBe("New")
+ })
+
+ it("patches approval and content while preserving non-target rows", () => {
+ const other = { id: "m_2", content: "two" }
+ const cache = pageCache([{ id: "m_1", content: "one" }, other])
+ const profile = { id: "u_1", name: "User", discriminator: "0001", image: null }
+ const approval = {
+ friendshipId: "friendship_1",
+ status: "approved" as const,
+ waitingOn: null,
+ otherProfile: profile,
+ botProfile: { ...profile, id: "bot_1" },
+ }
+
+ const approved = patchApprovalInCache(cache, "m_1", approval)!
+ const edited = patchMessageContentInCache(approved, "m_1", "edited")!
+
+ expect(edited.pages[0].messages[0]).toMatchObject({ content: "edited", approval })
+ expect(edited.pages[0].messages[1]).toBe(other)
+ })
+
+ it("removes only rows whose thread id matches", () => {
+ const kept = { id: "m_2", thread: { id: "thread_2" } }
+ const cache = pageCache(
+ [{ id: "m_1", thread: { id: "thread_1" } }, kept],
+ [{ id: "m_3", thread: { id: "thread_1" } }],
+ )
+
+ const result = removeThreadFromCache(cache, "thread_1")!
+
+ expect(result.pages[0].messages).toEqual([kept])
+ expect(result.pages[1].messages).toEqual([])
+ })
+
+ it("adds, deduplicates, and removes reactions without mutating the source", () => {
+ const message: Msg = {
+ id: "m_1",
+ reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["u_1"] }],
+ }
+ const add: CommunityReactionAdd = {
+ type: "community:reaction.add",
+ channelId: "ch_1",
+ messageId: "m_1",
+ userId: "u_me",
+ emoji: "👍",
+ }
+ const remove: CommunityReactionRemove = {
+ type: "community:reaction.remove",
+ channelId: "ch_1",
+ messageId: "m_1",
+ userId: "u_me",
+ emoji: "👍",
+ }
+
+ const added = applyReactionToMessage(message, add, "u_me")
+ const duplicate = applyReactionToMessage(added, add, "u_me")
+ const removed = applyReactionToMessage(duplicate, remove, "u_me")
+
+ expect(message.reactions).toEqual([{ emoji: "👍", count: 1, me: false, userIds: ["u_1"] }])
+ expect(added.reactions).toEqual([{ emoji: "👍", count: 2, me: true, userIds: ["u_1", "u_me"] }])
+ expect(duplicate.reactions).toEqual(added.reactions)
+ expect(removed.reactions).toEqual([{ emoji: "👍", count: 1, me: false, userIds: ["u_1"] }])
+ })
+
+ it("patches a matching cached reaction and removes the last reaction", () => {
+ const cache = pageCache([{
+ id: "m_1",
+ reactions: [{ emoji: "🔥", count: 1, me: true, userIds: ["u_me"] }],
+ }])
+ const remove: CommunityReactionRemove = {
+ type: "community:reaction.remove",
+ channelId: "ch_1",
+ messageId: "m_1",
+ userId: "u_me",
+ emoji: "🔥",
+ }
+
+ const result = applyReactionToCache(cache, remove, "u_me")!
+
+ expect(result).not.toBe(cache)
+ expect(result.pages[0].messages[0].reactions).toEqual([])
+ })
+
+ it("finds messages across pages and returns undefined for misses", () => {
+ const target = { id: "m_2", content: "target" }
+ const cache = pageCache([{ id: "m_1" }], [target])
+ expect(findCachedMessage(cache, "m_2")).toBe(target)
+ expect(findCachedMessage(cache, "m_missing")).toBeUndefined()
+ expect(findCachedMessage(undefined, "m_1")).toBeUndefined()
+ })
+})
diff --git a/src/web/src/hooks/community/community-ws/cache.ts b/src/web/src/hooks/community/community-ws/cache.ts
new file mode 100644
index 000000000..09a4233cd
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/cache.ts
@@ -0,0 +1,149 @@
+import type { InfiniteData } from "@tanstack/react-query"
+import type {
+ CommunityReactionAdd,
+ CommunityReactionRemove,
+} from "@alook/shared"
+import type { Msg } from "@/components/community/_types"
+import type { MessagesPage } from "@/hooks/community/use-messages"
+
+export type PageCache = InfiniteData<MessagesPage>
+
+/**
+ * Patch every cached message authored by `userId` to the renamed
+ * `authorName` — `authorName` is a snapshot field written at send time
+ * (`communityMessage` doesn't store it; the live JOIN is `message.ts`'s
+ * `authorName: user.name`), so nothing else updates already-loaded message
+ * rows after a self-rename. Only touches rows that are actually cached in
+ * this client (open/previously-open channels & DMs) — a channel never
+ * loaded this session picks up the new name for free on its first real
+ * fetch, since that IS the live JOIN.
+ */
+export function patchAuthorNameInCache(cache: PageCache | undefined, userId: string, newName: string): PageCache | undefined {
+ if (!cache) return cache
+ let touched = false
+ const pages = cache.pages.map((p) => {
+ if (!p.messages.some((m) => m.authorId === userId)) return p
+ touched = true
+ return {
+ ...p,
+ messages: p.messages.map((m) => (m.authorId === userId ? { ...m, authorName: newName } : m)),
+ }
+ })
+ if (!touched) return cache
+ return { ...cache, pages }
+}
+
+/**
+ * Patch the `approval` payload of a single cached message — the client-side
+ * effect of a `MESSAGE_UPDATED` event. The card re-renders in its new
+ * state (approved/denied/superseded/waiting) without a refetch.
+ */
+export function patchApprovalInCache(
+ cache: PageCache | undefined,
+ messageId: string,
+ approval: Msg["approval"],
+): PageCache | undefined {
+ if (!cache) return cache
+ let touched = false
+ const pages = cache.pages.map((p) => {
+ if (!p.messages.some((m) => m.id === messageId)) return p
+ touched = true
+ return {
+ ...p,
+ messages: p.messages.map((m) => (m.id === messageId ? { ...m, approval } : m)),
+ }
+ })
+ if (!touched) return cache
+ return { ...cache, pages }
+}
+
+export function patchMessageContentInCache(cache: PageCache | undefined, messageId: string, content: string): PageCache | undefined {
+ if (!cache) return cache
+ let touched = false
+ const pages = cache.pages.map((page) => ({
+ ...page,
+ messages: page.messages.map((message) => {
+ if (message.id !== messageId) return message
+ touched = true
+ return { ...message, content }
+ }),
+ }))
+ return touched ? { ...cache, pages } : cache
+}
+
+export function removeThreadFromCache(cache: PageCache | undefined, threadId: string): PageCache | undefined {
+ if (!cache) return cache
+ let touched = false
+ const pages = cache.pages.map((page) => {
+ const messages = page.messages.filter((message) => message.thread?.id !== threadId)
+ if (messages.length === page.messages.length) return page
+ touched = true
+ return { ...page, messages }
+ })
+ return touched ? { ...cache, pages } : cache
+}
+
+export function applyReactionToCache(
+ cache: PageCache | undefined,
+ event: CommunityReactionAdd | CommunityReactionRemove,
+ viewerUserId: string | null,
+): PageCache | undefined {
+ if (!cache) return cache
+ let touched = false
+ const pages = cache.pages.map((p) => {
+ if (!p.messages.some((m) => m.id === event.messageId)) return p
+ touched = true
+ return {
+ ...p,
+ messages: p.messages.map((message) =>
+ message.id === event.messageId
+ ? applyReactionToMessage(message, event, viewerUserId)
+ : message),
+ }
+ })
+ if (!touched) return cache
+ return { ...cache, pages }
+}
+
+export function applyReactionToMessage(
+ message: Msg,
+ event: CommunityReactionAdd | CommunityReactionRemove,
+ viewerUserId: string | null,
+): Msg {
+ const reactions = (message.reactions ?? []).map((reaction) => ({
+ ...reaction,
+ userIds: [...(reaction.userIds ?? [])],
+ }))
+ if (event.type === "community:reaction.add") {
+ const existing = reactions.find((reaction) => reaction.emoji === event.emoji)
+ if (existing) {
+ if (!existing.userIds.includes(event.userId)) existing.userIds.push(event.userId)
+ existing.count = existing.userIds.length
+ if (viewerUserId && event.userId === viewerUserId) existing.me = true
+ } else {
+ reactions.push({
+ emoji: event.emoji,
+ count: 1,
+ me: !!viewerUserId && event.userId === viewerUserId,
+ userIds: [event.userId],
+ })
+ }
+ } else {
+ const index = reactions.findIndex((reaction) => reaction.emoji === event.emoji)
+ if (index !== -1) {
+ reactions[index].userIds = reactions[index].userIds.filter((id) => id !== event.userId)
+ reactions[index].count = reactions[index].userIds.length
+ if (viewerUserId && event.userId === viewerUserId) reactions[index].me = false
+ if (reactions[index].count <= 0) reactions.splice(index, 1)
+ }
+ }
+ return { ...message, reactions }
+}
+
+export function findCachedMessage(cache: PageCache | undefined, messageId: string): Msg | undefined {
+ for (const page of cache?.pages ?? []) {
+ const message = page.messages.find((row) => row.id === messageId)
+ if (message) return message
+ }
+ return undefined
+}
diff --git a/src/web/src/hooks/community/community-ws/handler-context.ts b/src/web/src/hooks/community/community-ws/handler-context.ts
new file mode 100644
index 000000000..c1256dff3
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/handler-context.ts
@@ -0,0 +1,53 @@
+import type { QueryClient } from "@tanstack/react-query"
+import type { useCommunityStore } from "@/stores/community"
+import type { useCommunityWsStore } from "@/stores/community/ws"
+
+export type Subscription = {
+ // The focused regular channel/thread.
+ channelId?: string
+ // The focused DM's channel id. A DM is a channel now; this slot keeps its
+ // name only to mark "the focused channel is a DM" so the handler routes its
+ // events into the `dmMessages` cache and the `dm:` typing scope.
+ dmConversationId?: string
+}
+
+/**
+ * Optional args — the community feature needs to know the viewer's userId so
+ * reactions from that user light up the "me" flag. Passing null keeps the
+ * hook usable in places where the viewer identity isn't yet loaded.
+ */
+export type UseCommunityWsOptions = {
+ viewerUserId?: string | null
+}
+
+export type CommunityWsHandlerContext = {
+ queryClient: QueryClient
+ communityStore: ReturnType<typeof useCommunityStore.getState>
+ wsStore: ReturnType<typeof useCommunityWsStore.getState>
+ sub: Subscription
+ viewerUserIdRef: { current: string | null }
+ matchesFocus: (event: { channelId?: string }) => boolean
+ scheduleInboxInvalidate: () => void
+}
+
+export type MessageEventContext = CommunityWsHandlerContext
+export type TypingEventContext = Pick<
+ CommunityWsHandlerContext,
+ "sub" | "viewerUserIdRef" | "matchesFocus"
+>
+export type StructureTreeEventContext = Pick<
+ CommunityWsHandlerContext,
+ "queryClient"
+>
+export type MembershipEventContext = Pick<
+ CommunityWsHandlerContext,
+ "queryClient" | "viewerUserIdRef"
+>
+export type SocialEventContext = Pick<
+ CommunityWsHandlerContext,
+ "queryClient" | "sub" | "viewerUserIdRef"
+>
+export type PresenceMachineEventContext = Pick<
+ CommunityWsHandlerContext,
+ "queryClient"
+>
diff --git a/src/web/src/hooks/community/community-ws/membership-events.test.ts b/src/web/src/hooks/community/community-ws/membership-events.test.ts
new file mode 100644
index 000000000..d37706293
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/membership-events.test.ts
@@ -0,0 +1,192 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import type { CommunityMemberJoin, CommunityMemberUpdate } from "@alook/shared"
+import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ capturedOnMessage,
+ capturedQueryClient,
+ cleanupCommunityWsHarness,
+ forumSidebarFixture,
+ mountHook,
+ resetCommunityWsHarness,
+} from "./test-harness"
+
+beforeEach(resetCommunityWsHarness)
+afterEach(cleanupCommunityWsHarness)
+
+describe("useCommunityWs — member events", () => {
+ it("patches the members cache with a join event", async () => {
+ await mountHook()
+ capturedQueryClient.setQueryData(communityKeys.members("srv_1"), {
+ pages: [{ members: [], hasMore: false, limit: 50, total: 0 }],
+ pageParams: [null],
+ })
+ const event: CommunityMemberJoin = {
+ type: "community:member.join",
+ serverId: "srv_1",
+ member: {
+ id: "mem_1",
+ userId: "u_1",
+ name: "n",
+ discriminator: "0000",
+ role: "member",
+ joinedAt: "2026-07-03T00:00:00.000Z",
+ },
+ }
+ capturedOnMessage!(event)
+ const cache = capturedQueryClient.getQueryData<{
+ pages: { members: { userId: string }[]; total: number }[]
+ }>(communityKeys.members("srv_1"))
+ expect(cache?.pages[0].members.map((m) => m.userId)).toEqual(["u_1"])
+ expect(cache?.pages[0].total).toBe(1)
+ })
+
+ it("a self-rename (member.update with userId + changes.nickname) patches authorName in every cached channel/DM message list", async () => {
+ await mountHook()
+ useMessageStreamStore.getState().dispatch(
+ { kind: "dm", id: "dm_overlay" },
+ {
+ type: "wsMessage",
+ message: {
+ id: "m_overlay",
+ seq: 9,
+ type: "chat",
+ authorId: "u_renamed",
+ authorName: "OldName",
+ content: "overlay only",
+ },
+ },
+ )
+
+ // Two message caches — one channel, one DM — each with a message
+ // authored by the renamed user and one by someone else. Both should
+ // update; the other author's row must stay untouched.
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{
+ messages: [
+ { id: "m_1", authorId: "u_renamed", authorName: "OldName", content: "hi" },
+ { id: "m_2", authorId: "u_other", authorName: "Someone Else", content: "yo" },
+ ],
+ hasMore: false,
+ }],
+ pageParams: [null],
+ })
+ capturedQueryClient.setQueryData(communityKeys.dmMessages("dm_1"), {
+ pages: [{
+ messages: [
+ { id: "m_3", authorId: "u_renamed", authorName: "OldName", content: "sup" },
+ ],
+ hasMore: false,
+ }],
+ pageParams: [null],
+ })
+
+ const event: CommunityMemberUpdate = {
+ type: "community:member.update",
+ serverId: "srv_1",
+ memberId: "mem_1",
+ userId: "u_renamed",
+ changes: { nickname: "NewName" },
+ }
+ capturedOnMessage!(event)
+
+ const channelCache = capturedQueryClient.getQueryData<{
+ pages: { messages: { id: string; authorName: string }[] }[]
+ }>(communityKeys.channelMessages("ch_1"))
+ expect(channelCache?.pages[0].messages).toEqual([
+ { id: "m_1", authorId: "u_renamed", authorName: "NewName", content: "hi" },
+ { id: "m_2", authorId: "u_other", authorName: "Someone Else", content: "yo" },
+ ])
+
+ const dmCache = capturedQueryClient.getQueryData<{
+ pages: { messages: { id: string; authorName: string }[] }[]
+ }>(communityKeys.dmMessages("dm_1"))
+ expect(dmCache?.pages[0].messages).toEqual([
+ { id: "m_3", authorId: "u_renamed", authorName: "NewName", content: "sup" },
+ ])
+ expect(
+ getMessageOverlay({ kind: "dm", id: "dm_overlay" }).liveById.get("m_overlay")?.authorName,
+ ).toBe("NewName")
+ })
+
+ it("a role-only member.update (no userId/nickname) does not touch any message cache", async () => {
+ await mountHook()
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{
+ messages: [{ id: "m_1", authorId: "u_1", authorName: "Name", content: "hi" }],
+ hasMore: false,
+ }],
+ pageParams: [null],
+ })
+
+ const event: CommunityMemberUpdate = {
+ type: "community:member.update",
+ serverId: "srv_1",
+ memberId: "mem_1",
+ changes: { role: "admin" },
+ }
+ capturedOnMessage!(event)
+
+ const cache = capturedQueryClient.getQueryData<{
+ pages: { messages: { id: string; authorName: string }[] }[]
+ }>(communityKeys.channelMessages("ch_1"))
+ expect(cache?.pages[0].messages).toEqual([
+ { id: "m_1", authorId: "u_1", authorName: "Name", content: "hi" },
+ ])
+ })
+})
+describe("useCommunityWs — channel.member_add/remove → invalidate rosters", () => {
+ it("member_add invalidates channelMembers AND threadParticipants for a child thread", async () => {
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ capturedOnMessage!({
+ type: "community:channel.member_add",
+ serverId: "srv_1",
+ channelId: "ch_1",
+ userId: "u_new",
+ })
+ const invalidated = (key: unknown) =>
+ spy.mock.calls.some((c) => JSON.stringify(c[0]?.queryKey) === JSON.stringify(key))
+ expect(invalidated(communityKeys.channelMembers("ch_1"))).toBe(true)
+ expect(invalidated(communityKeys.threadParticipants("ch_1"))).toBe(true)
+ })
+
+ it("member_remove invalidates threadParticipants too", async () => {
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ capturedOnMessage!({
+ type: "community:channel.member_remove",
+ serverId: "srv_1",
+ channelId: "ch_1",
+ userId: "u_gone",
+ })
+ expect(
+ spy.mock.calls.some(
+ (c) => JSON.stringify(c[0]?.queryKey) === JSON.stringify(communityKeys.threadParticipants("ch_1")),
+ ),
+ ).toBe(true)
+ })
+
+ it("adds/removes the viewer's participating child in the forum sidebar", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const key = communityKeys.forumSidebarThreadsView("srv_1", null)
+ capturedQueryClient.setQueryData(key, forumSidebarFixture())
+
+ capturedOnMessage!({
+ type: "community:channel.member_remove",
+ serverId: "srv_1",
+ channelId: "post_1",
+ userId: "u_me",
+ })
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)?.threads).toEqual([])
+
+ capturedQueryClient.setQueryData(key, forumSidebarFixture([]))
+ capturedOnMessage!({
+ type: "community:channel.member_add",
+ serverId: "srv_1",
+ channelId: "post_2",
+ userId: "u_me",
+ })
+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
+ })
+})
diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.ts
new file mode 100644
index 000000000..e939017b3
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/membership-events.ts
@@ -0,0 +1,168 @@
+import type { InfiniteData } from "@tanstack/react-query"
+import type {
+ CommunityMemberJoin,
+ CommunityMemberLeave,
+ CommunityMemberUpdate,
+ CommunityWsEvent,
+} from "@alook/shared"
+import { communityKeys } from "@/lib/query-keys"
+import { useMessageStreamStore } from "@/stores/community/message-stream"
+import {
+ patchCacheJoin,
+ patchCacheLeave,
+ patchCacheUpdate,
+ type MembersEnvelope,
+} from "@/hooks/community/use-server-members"
+import {
+ removeForumSidebarThread,
+ removeForumSidebarUnreadChild,
+ type ForumSidebarQueryData,
+} from "@/hooks/community/use-forum-sidebar-threads"
+import { patchAuthorNameInCache, type PageCache } from "@/hooks/community/community-ws/cache"
+import type { MembershipEventContext } from "@/hooks/community/community-ws/handler-context"
+
+type ChannelMemberEvent = Extract<
+ CommunityWsEvent,
+ { type: "community:channel.member_add" | "community:channel.member_remove" }
+>
+
+export function handleChannelMemberEvent(
+ event: ChannelMemberEvent,
+ { queryClient, viewerUserIdRef }: MembershipEventContext,
+) {
+ // Re-run the viewer-scoped server tree so the sidebar gains/loses the
+ // private channel. On REMOVE for the viewer, evict that channel's
+ // scoped caches so no private content lingers locally (mirrors the
+ // channel.delete eviction above).
+ if (
+ event.type === "community:channel.member_remove" &&
+ event.userId === viewerUserIdRef.current
+ ) {
+ removeForumSidebarUnreadChild(queryClient, event.serverId, event.channelId)
+ useMessageStreamStore.getState().removeScope({
+ kind: "channel",
+ id: event.channelId,
+ serverId: event.serverId,
+ })
+ queryClient.removeQueries({ queryKey: communityKeys.channelMessages(event.channelId) })
+ queryClient.removeQueries({ queryKey: communityKeys.pins(event.channelId) })
+ queryClient.removeQueries({ queryKey: communityKeys.threads(event.channelId) })
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: communityKeys.forumSidebarThreads(event.serverId) },
+ (data) => removeForumSidebarThread(data, event.channelId),
+ )
+ } else if (
+ event.type === "community:channel.member_add" &&
+ event.userId === viewerUserIdRef.current
+ ) {
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.forumSidebarThreads(event.serverId),
+ })
+ }
+ void queryClient.invalidateQueries({ queryKey: communityKeys.server(event.serverId) })
+ // Refetch the channel roster so an open private-channel Members drawer
+ // (and the manage-members dialog) reflect the add/remove live.
+ void queryClient.invalidateQueries({ queryKey: communityKeys.channelMembers(event.channelId) })
+ // The addable-members candidate pool is the complement of the roster —
+ // a peer's add/remove changes it too, so an open add dialog doesn't
+ // offer a just-added member (whose Add would 400) or hide a removed one.
+ void queryClient.invalidateQueries({ queryKey: communityKeys.channelAddableMembers(event.channelId) })
+ // A forum thread's "Add participant" emits this same MEMBER_ADD event —
+ // its Members panel is the participant set, so refetch it too. No-op
+ // for a plain channel (participants query disabled there).
+ void queryClient.invalidateQueries({ queryKey: communityKeys.threadParticipants(event.channelId) })
+}
+
+function finishMemberEvent(
+ event: CommunityMemberJoin | CommunityMemberLeave | CommunityMemberUpdate,
+ { queryClient }: MembershipEventContext,
+) {
+ // Membership just changed → the invite dialog's "friends who aren't
+ // in this server" list is stale. Cheap invalidation because the
+ // query is disabled unless the dialog is actually open.
+ if (event.type !== "community:member.update") {
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.invitableFriends(event.serverId),
+ })
+ }
+}
+
+export function handleMemberJoin(
+ event: CommunityMemberJoin,
+ context: MembershipEventContext,
+) {
+ const { queryClient } = context
+ const key = communityKeys.members(event.serverId)
+ queryClient.setQueryData<InfiniteData<MembersEnvelope> | undefined>(
+ key,
+ (cache) => patchCacheJoin(cache, event),
+ )
+ finishMemberEvent(event, context)
+}
+
+export function handleMemberLeave(
+ event: CommunityMemberLeave,
+ context: MembershipEventContext,
+) {
+ const { queryClient, viewerUserIdRef } = context
+ const key = communityKeys.members(event.serverId)
+ queryClient.setQueryData<InfiniteData<MembersEnvelope> | undefined>(
+ key,
+ (cache) => patchCacheLeave(cache, event),
+ )
+ // If the leaver is the viewer (kick from another tab / owner
+ // cascade), the viewer's server rail is stale — invalidate it
+ // so the layout's eject effect can detect the drop and route
+ // the user away from the now-forbidden URL.
+ if (event.userId === viewerUserIdRef.current) {
+ useMessageStreamStore.getState().removeServer(event.serverId)
+ // Rail LIST only (the layout's eject effect reads it to route the
+ // kicked viewer away). `exact` so a kick doesn't cascade-refetch
+ // every server's nested detail subtree.
+ void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })
+ }
+ finishMemberEvent(event, context)
+}
+
+export function handleMemberUpdate(
+ event: CommunityMemberUpdate,
+ context: MembershipEventContext,
+) {
+ const { queryClient } = context
+ const key = communityKeys.members(event.serverId)
+ queryClient.setQueryData<InfiniteData<MembersEnvelope> | undefined>(
+ key,
+ (cache) => patchCacheUpdate(cache, event),
+ )
+ // A self-rename carries `userId` + `changes.nickname` — patch
+ // every cached message list's `authorName` snapshot for that
+ // author. A role-only change has no `userId`/`nickname`, so
+ // this is a no-op for that case.
+ if (event.userId && event.changes.nickname) {
+ const userId = event.userId
+ const newName = event.changes.nickname
+ for (const cacheEntry of queryClient.getQueryCache().findAll({
+ predicate: (q) =>
+ q.queryKey[0] === "community"
+ && (q.queryKey[1] === "channel" || q.queryKey[1] === "dm")
+ && q.queryKey[3] === "messages",
+ })) {
+ queryClient.setQueryData<PageCache | undefined>(
+ cacheEntry.queryKey,
+ (cache) => patchAuthorNameInCache(cache, userId, newName),
+ )
+ }
+ const streamState = useMessageStreamStore.getState()
+ for (const entry of streamState.entries.values()) {
+ if (entry.scope.kind === "channel" && entry.scope.serverId !== event.serverId) continue
+ for (const message of entry.state.liveById.values()) {
+ if (message.authorId !== userId) continue
+ useMessageStreamStore.getState().dispatch(entry.scope, {
+ type: "liveRefreshed",
+ message: { ...message, authorName: newName },
+ })
+ }
+ }
+ }
+ finishMemberEvent(event, context)
+}
diff --git a/src/web/src/hooks/community/community-ws/message-events.test.ts b/src/web/src/hooks/community/community-ws/message-events.test.ts
new file mode 100644
index 000000000..b5eb5cbbf
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/message-events.test.ts
@@ -0,0 +1,694 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import type {
+ CommunityMessageCreate,
+ CommunityMessageEdited,
+ CommunityPinAdd,
+ CommunityReactionAdd,
+} from "@alook/shared"
+import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ capturedOnMessage,
+ capturedQueryClient,
+ cleanupCommunityWsHarness,
+ forumSidebarFixture,
+ markReadMutate,
+ messageCreate,
+ mountHook,
+ resetCommunityWsHarness,
+ resetHookMemoization,
+} from "./test-harness"
+
+beforeEach(resetCommunityWsHarness)
+afterEach(cleanupCommunityWsHarness)
+
+describe("useCommunityWs — message.create", () => {
+ it("patches a loaded forum-sidebar child activity without a refetch", async () => {
+ await mountHook()
+ const key = communityKeys.forumSidebarThreadsView("srv_1", null)
+ capturedQueryClient.setQueryData(key, forumSidebarFixture())
+ const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const event = {
+ ...messageCreate("post_1"),
+ serverId: "srv_1",
+ parentChannelId: "forum_1",
+ } satisfies CommunityMessageCreate
+
+ capturedOnMessage!(event)
+
+ const data = capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)
+ expect(data?.threads[0]).toMatchObject({
+ id: "post_1",
+ activityAt: "2026-07-03T00:00:00.000Z",
+ expiresAt: "2026-07-06T00:00:00.000Z",
+ })
+ expect(invalidateSpy).not.toHaveBeenCalledWith({ queryKey: communityKeys.forumSidebarThreads("srv_1") })
+ })
+
+ it("invalidates the forum-sidebar collection when the active child is not loaded", async () => {
+ await mountHook()
+ const key = communityKeys.forumSidebarThreadsView("srv_1", null)
+ capturedQueryClient.setQueryData(key, forumSidebarFixture([]))
+
+ capturedOnMessage!({
+ ...messageCreate("post_missing"),
+ serverId: "srv_1",
+ parentChannelId: "forum_1",
+ } satisfies CommunityMessageCreate)
+
+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
+ })
+
+ it("writes the channel overlay and leaves the base cache untouched when focused", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })
+
+ // Re-mount so the ref state picks up the subscription value.
+ resetHookMemoization()
+ await mountHook()
+
+ // Seed a page cache so setQueryData has something to patch.
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{ messages: [], hasMore: false }],
+ pageParams: [null],
+ })
+
+ capturedOnMessage!(messageCreate("ch_1"))
+
+ const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string; seq?: number }[] }[] }>(
+ communityKeys.channelMessages("ch_1"),
+ )
+ expect(cache?.pages[0].messages).toEqual([])
+ expect([...getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById]).toHaveLength(1)
+ })
+
+ it("heals a first-seen event replay once the focused serverId becomes available", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId(null)
+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })
+ resetHookMemoization()
+ await mountHook()
+
+ const event = messageCreate("ch_1")
+ capturedOnMessage!(event)
+ expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById).toHaveLength(0)
+
+ useCommunityStore.getState().setCurrentServerId("s1")
+ capturedOnMessage!(event)
+ expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById).toHaveLength(1)
+ })
+
+ it("keeps forum query variants base-only and stages a new opener in the overlay", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "forum_1" })
+ resetHookMemoization()
+ await mountHook()
+ const allKey = communityKeys.channelMessages("forum_1")
+ const bugKey = [...allKey, "tag", "bug"] as const
+ const empty = { pages: [{ messages: [], hasMore: false }], pageParams: [null] }
+ capturedQueryClient.setQueryData(allKey, empty)
+ capturedQueryClient.setQueryData(bugKey, empty)
+
+ capturedOnMessage!(messageCreate("forum_1"))
+
+ expect(capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(allKey)?.pages[0].messages).toHaveLength(0)
+ expect(capturedQueryClient.getQueryData<{ pages: { messages: unknown[] }[] }>(bugKey)?.pages[0].messages).toHaveLength(0)
+ expect(getMessageOverlay({ kind: "channel", id: "forum_1", serverId: "s1" }).liveById).toHaveLength(1)
+ })
+
+ it("does NOT patch a channel we aren't focused on", async () => {
+ await mountHook()
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_other"), {
+ pages: [{ messages: [], hasMore: false }],
+ pageParams: [null],
+ })
+ capturedOnMessage!(messageCreate("ch_other"))
+ const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
+ communityKeys.channelMessages("ch_other"),
+ )
+ expect(cache?.pages[0].messages).toEqual([])
+ })
+
+ it("invalidates channelMembers for a focused child channel", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ const store = useCommunityStore.getState()
+ store.setCurrentChannelId("ch_1")
+ store.setCurrentChannelMeta({ name: "thread", parentChannelId: "parent_1" })
+ store.subscribe({ channelId: "ch_1" })
+ resetHookMemoization()
+ await mountHook()
+
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ capturedOnMessage!(messageCreate("ch_1"))
+
+ expect(spy).toHaveBeenCalledWith({ queryKey: communityKeys.channelMembers("ch_1") })
+ expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.threadParticipants("ch_1") })
+ })
+
+ it("does NOT invalidate channelMembers for a focused top-level channel", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ const store = useCommunityStore.getState()
+ store.setCurrentChannelId("ch_1")
+ store.subscribe({ channelId: "ch_1" })
+ resetHookMemoization()
+ await mountHook()
+
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ capturedOnMessage!(messageCreate("ch_1"))
+
+ expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.channelMembers("ch_1") })
+ expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.threadParticipants("ch_1") })
+ })
+
+ it("does NOT invalidate channelMembers for an unfocused channel", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ const store = useCommunityStore.getState()
+ store.setCurrentChannelId("ch_1")
+ store.setCurrentChannelMeta({ name: "thread", parentChannelId: "parent_1" })
+ store.subscribe({ channelId: "ch_1" })
+ resetHookMemoization()
+ await mountHook()
+
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ capturedOnMessage!(messageCreate("ch_other"))
+
+ expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.channelMembers("ch_other") })
+ expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.threadParticipants("ch_other") })
+ })
+
+ it("dedupes by messageId — a repeat event is a no-op", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })
+ resetHookMemoization()
+ await mountHook()
+
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{ messages: [], hasMore: false }],
+ pageParams: [null],
+ })
+ capturedOnMessage!(messageCreate("ch_1"))
+ capturedOnMessage!(messageCreate("ch_1"))
+ capturedOnMessage!(messageCreate("ch_1"))
+ expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById.size).toBe(1)
+ })
+
+ it("caps the live page at MAX_LIVE_PAGE_MESSAGES, dropping the oldest entry", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })
+ resetHookMemoization()
+ await mountHook()
+
+ const MAX_LIVE_PAGE_MESSAGES = 500
+ const seeded = Array.from({ length: MAX_LIVE_PAGE_MESSAGES }, (_, i) => ({
+ id: `seed_${i}`,
+ content: "x",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ }))
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{ messages: seeded, hasMore: false }],
+ pageParams: [null],
+ })
+
+ capturedOnMessage!(messageCreate("ch_1", "new_message"))
+
+ const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
+ communityKeys.channelMessages("ch_1"),
+ )
+ const ids = cache?.pages[0].messages.map((m) => m.id) ?? []
+ expect(ids).toHaveLength(MAX_LIVE_PAGE_MESSAGES)
+ expect(ids[0]).toBe("seed_0")
+ expect(ids).not.toContain("new_message")
+ expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById.has("new_message")).toBe(true)
+ })
+
+ it("flips hasMore/hasMoreOlder to true when the head-slice discards history (legacy shape)", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })
+ resetHookMemoization()
+ await mountHook()
+
+ const MAX_LIVE_PAGE_MESSAGES = 500
+ const seeded = Array.from({ length: MAX_LIVE_PAGE_MESSAGES }, (_, i) => ({
+ id: `seed_${i}`,
+ content: "x",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ }))
+ // Legacy newest-mode envelope: only `hasMore` is defined.
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{ messages: seeded, hasMore: false }],
+ pageParams: [null],
+ })
+
+ capturedOnMessage!(messageCreate("ch_1", "new_message"))
+
+ const cache = capturedQueryClient.getQueryData<{
+ pages: { messages: { id: string }[]; hasMore?: boolean; hasMoreOlder?: boolean }[]
+ }>(communityKeys.channelMessages("ch_1"))
+ // Head-slice discarded seed_0; the "Load older" affordance must re-arm
+ // via `hasMore: true` (legacy shape had no `hasMoreOlder` so we don't
+ // synthesize it).
+ expect(cache?.pages[0].hasMore).toBe(false)
+ expect(cache?.pages[0].hasMoreOlder).toBeUndefined()
+ })
+
+ it("flips hasMoreOlder to true on head-slice for anchor-mode envelopes", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })
+ resetHookMemoization()
+ await mountHook()
+
+ const MAX_LIVE_PAGE_MESSAGES = 500
+ const seeded = Array.from({ length: MAX_LIVE_PAGE_MESSAGES }, (_, i) => ({
+ id: `seed_${i}`,
+ content: "x",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ }))
+ // Anchor-mode envelope: hasMoreOlder + hasMoreNewer, no `hasMore`.
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{ messages: seeded, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 42 }],
+ pageParams: [{ mode: "anchor", anchor: "seed_0" }],
+ })
+
+ capturedOnMessage!(messageCreate("ch_1", "new_message"))
+
+ const cache = capturedQueryClient.getQueryData<{
+ pages: { messages: { id: string }[]; hasMore?: boolean; hasMoreOlder?: boolean; hasMoreNewer?: boolean }[]
+ }>(communityKeys.channelMessages("ch_1"))
+ expect(cache?.pages[0].hasMoreOlder).toBe(false)
+ // We must NOT invent a legacy `hasMore` flag on an anchor envelope —
+ // the two shapes are mutually exclusive.
+ expect(cache?.pages[0].hasMore).toBeUndefined()
+ // `hasMoreNewer` untouched.
+ expect(cache?.pages[0].hasMoreNewer).toBe(false)
+ })
+
+ it("does not touch hasMore flags when the page hasn't been trimmed", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })
+ resetHookMemoization()
+ await mountHook()
+
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [
+ {
+ messages: [{ id: "seed_0", content: "x", createdAt: "t" }],
+ hasMoreOlder: false,
+ hasMoreNewer: false,
+ latestSeq: 1,
+ },
+ ],
+ pageParams: [null],
+ })
+ capturedOnMessage!(messageCreate("ch_1", "m_new"))
+ const cache = capturedQueryClient.getQueryData<{
+ pages: { hasMoreOlder?: boolean; hasMoreNewer?: boolean }[]
+ }>(communityKeys.channelMessages("ch_1"))
+ expect(cache?.pages[0].hasMoreOlder).toBe(false)
+ expect(cache?.pages[0].hasMoreNewer).toBe(false)
+ })
+
+ it("does not drop below the cap when the page isn't at capacity yet", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })
+ resetHookMemoization()
+ await mountHook()
+
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{ messages: [{ id: "seed_0", content: "x", createdAt: "t" }], hasMore: false }],
+ pageParams: [null],
+ })
+ capturedOnMessage!(messageCreate("ch_1", "m_new"))
+ const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
+ communityKeys.channelMessages("ch_1"),
+ )
+ expect(cache?.pages[0].messages.map((m) => m.id)).toEqual(["seed_0"])
+ expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById.has("m_new")).toBe(true)
+ })
+
+ it("does not schedule an inbox invalidate for viewer's own messages", async () => {
+ vi.useFakeTimers()
+ try {
+ await mountHook({ viewerUserId: "u_author" })
+ const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ capturedOnMessage!(messageCreate("ch_random"))
+ vi.advanceTimersByTime(1_000)
+ expect(invalidateSpy).not.toHaveBeenCalled()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it("debounces inbox invalidation — 10 messages ⇒ 1 invalidate call", async () => {
+ vi.useFakeTimers()
+ try {
+ await mountHook({ viewerUserId: "u_me" })
+ const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ for (let i = 0; i < 10; i++) capturedOnMessage!(messageCreate("ch_x", `m_${i}`))
+ // Before debounce window, no invalidate.
+ expect(invalidateSpy).not.toHaveBeenCalled()
+ // Advance past the debounce window — exactly one invalidate.
+ vi.advanceTimersByTime(500)
+ const inboxCalls = invalidateSpy.mock.calls.filter((c) => {
+ const key = c[0]?.queryKey
+ return Array.isArray(key) && key.includes("inbox")
+ })
+ expect(inboxCalls).toHaveLength(1)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+})
+describe("useCommunityWs — reactions", () => {
+ it("patches the message row's reactions in the channel cache", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [
+ {
+ messages: [
+ { id: "m_1", content: "x", reactions: [] },
+ ],
+ hasMore: false,
+ },
+ ],
+ pageParams: [null],
+ })
+ const event: CommunityReactionAdd = {
+ type: "community:reaction.add",
+ channelId: "ch_1",
+ messageId: "m_1",
+ userId: "u_other",
+ emoji: "👍",
+ }
+ capturedOnMessage!(event)
+ const cache = capturedQueryClient.getQueryData<{
+ pages: { messages: { id: string; reactions: { emoji: string; count: number; me: boolean }[] }[] }[]
+ }>(communityKeys.channelMessages("ch_1"))
+ expect(cache?.pages[0].messages[0].reactions).toEqual([
+ { emoji: "👍", count: 1, me: false, userIds: ["u_other"] },
+ ])
+ })
+
+ it("refreshes a focused DM row that exists only in the overlay", async () => {
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
+ await mountHook({ viewerUserId: "u_me" })
+ useMessageStreamStore.getState().dispatch(
+ { kind: "dm", id: "dm_1" },
+ {
+ type: "wsMessage",
+ message: {
+ id: "m_dm",
+ seq: 4,
+ type: "chat",
+ authorId: "u_other",
+ authorName: "Other",
+ content: "hi",
+ reactions: [],
+ },
+ },
+ )
+
+ capturedOnMessage!({
+ type: "community:reaction.add",
+ channelId: "dm_1",
+ messageId: "m_dm",
+ userId: "u_me",
+ emoji: "👍",
+ })
+
+ expect(getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.get("m_dm")?.reactions).toEqual([
+ { emoji: "👍", count: 1, me: true, userIds: ["u_me"] },
+ ])
+ })
+})
+
+describe("useCommunityWs — message.updated", () => {
+ it("refreshes approval fields on a focused DM row that exists only in the overlay", async () => {
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
+ await mountHook()
+ useMessageStreamStore.getState().dispatch(
+ { kind: "dm", id: "dm_1" },
+ {
+ type: "wsMessage",
+ message: { id: "m_dm", seq: 4, type: "chat", content: "approval" },
+ },
+ )
+ const profile = { id: "u_other", name: "Other", discriminator: "0001", image: null }
+ const approval = {
+ friendshipId: "friendship_1",
+ status: "approved" as const,
+ waitingOn: null,
+ otherProfile: profile,
+ botProfile: { ...profile, id: "bot_1", name: "Bot" },
+ }
+
+ capturedOnMessage!({
+ type: "community:message.updated",
+ channelId: "dm_1",
+ messageId: "m_dm",
+ approval,
+ })
+
+ expect(getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.get("m_dm")?.approval).toEqual(approval)
+ })
+})
+
+describe("useCommunityWs — pin.add", () => {
+ it("invalidates the channel's pin list", async () => {
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const event: CommunityPinAdd = {
+ type: "community:pin.add",
+ channelId: "ch_1",
+ messageId: "m_1",
+ }
+ capturedOnMessage!(event)
+ const pinsCalls = spy.mock.calls.filter((c) =>
+ JSON.stringify(c[0]?.queryKey ?? []).includes(`"pins"`) ||
+ // pins() nests under channel + channelId + pins
+ (Array.isArray(c[0]?.queryKey) && (c[0]!.queryKey as unknown[]).includes("pins")),
+ )
+ // At least one invalidate is against communityKeys.pins("ch_1").
+ expect(
+ pinsCalls.some((c) => {
+ const key = c[0]?.queryKey as unknown[] | undefined
+ return Array.isArray(key) && key.includes("ch_1") && key.includes("pins")
+ }),
+ ).toBe(true)
+ })
+})
+
+describe("useCommunityWs — DM message.create", () => {
+ it("writes the focused DM overlay, leaves Query base-only, and invalidates dms()", async () => {
+ vi.useFakeTimers()
+ try {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
+ resetHookMemoization()
+ await mountHook()
+
+ capturedQueryClient.setQueryData(communityKeys.dmMessages("dm_1"), {
+ pages: [{ messages: [], hasMore: false }],
+ pageParams: [null],
+ })
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ // A DM is a channel now — its message arrives as `message.create` keyed by
+ // the DM's channel id (which the subscription tracks in `dmConversationId`).
+ const event: CommunityMessageCreate = {
+ type: "community:message.create",
+ channelId: "dm_1",
+ message: {
+ id: "dm_m_1",
+ seq: 1,
+ authorId: "u_a",
+ authorName: "a",
+ content: "hi",
+ type: "chat",
+ seq: 1,
+ createdAt: "2026-07-03T00:00:00.000Z",
+ },
+ }
+ capturedOnMessage!(event)
+ const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string; seq?: number }[] }[] }>(
+ communityKeys.dmMessages("dm_1"),
+ )
+ expect(cache?.pages[0].messages).toEqual([])
+ const { getMessageOverlay } = await import("@/stores/community/message-stream")
+ expect(
+ [...getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.values()].map((message) => message.id),
+ ).toEqual(["dm_m_1"])
+ // The inbox + `dms()` invalidation is batched behind the inbox debounce.
+ vi.advanceTimersByTime(600)
+ expect(
+ spy.mock.calls.some((c) => {
+ const key = c[0]?.queryKey as unknown[] | undefined
+ return Array.isArray(key) && key.includes("dms")
+ }),
+ ).toBe(true)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it("heals an already-seen DM event into the overlay before seen dedupe returns", async () => {
+ const { useCommunityStore } = await import("@/stores/community")
+ const { useCommunityWsStore } = await import("@/stores/community/ws")
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
+ useCommunityWsStore.getState().markSeenMessage("dm_replay")
+ await mountHook()
+
+ capturedOnMessage!({
+ type: "community:message.create",
+ channelId: "dm_1",
+ message: {
+ id: "dm_replay",
+ seq: 12,
+ authorId: "u_a",
+ authorName: "a",
+ content: "replay",
+ type: "chat",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ },
+ })
+
+ expect(getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.has("dm_replay")).toBe(true)
+ })
+})
+
+describe("useCommunityWs — message edit refreshes forum opener summary", () => {
+ it("invalidates the parent thread list for an opener edit, but not for an ordinary reply", async () => {
+ await mountHook()
+ const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const opener: CommunityMessageEdited = {
+ type: "community:message.edited",
+ channelId: "post_1",
+ messageId: "opener_1",
+ content: "new title",
+ parentChannelId: "forum_1",
+ }
+ capturedQueryClient.setQueryData(communityKeys.message("opener_1"), {
+ id: "opener_1",
+ content: "old title",
+ })
+ const allKey = communityKeys.channelMessages("forum_1")
+ const bugKey = [...allKey, "tag", "bug"] as const
+ const forumPage = { pages: [{ messages: [{ id: "opener_1", content: "old title" }] }], pageParams: [null] }
+ capturedQueryClient.setQueryData(allKey, forumPage)
+ capturedQueryClient.setQueryData(bugKey, forumPage)
+ const sidebarKey = communityKeys.forumSidebarThreadsView("s1", null)
+ capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture())
+ capturedOnMessage!(opener)
+ expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: communityKeys.channelMessages("forum_1") })
+ expect(capturedQueryClient.getQueryState(allKey)?.isInvalidated).toBe(true)
+ expect(capturedQueryClient.getQueryState(bugKey)?.isInvalidated).toBe(true)
+ expect(capturedQueryClient.getQueryData<{ pages: { messages: { content: string }[] }[] }>(allKey)?.pages[0].messages[0].content).toBe("new title")
+ expect(capturedQueryClient.getQueryData<{ pages: { messages: { content: string }[] }[] }>(bugKey)?.pages[0].messages[0].content).toBe("new title")
+ expect(capturedQueryClient.getQueryData<{ content: string }>(communityKeys.message("opener_1"))?.content).toBe("new title")
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(sidebarKey)?.threads[0].title)
+ .toBe("new title")
+
+ invalidateSpy.mockClear()
+ capturedOnMessage!({
+ type: "community:message.edited",
+ channelId: "post_1",
+ messageId: "reply_1",
+ content: "edited reply",
+ } satisfies CommunityMessageEdited)
+ expect(invalidateSpy).not.toHaveBeenCalled()
+ })
+})
+
+describe("useCommunityWs — does NOT auto-mark-read on WS message.create", () => {
+ it("does NOT call markRead when a foreign-authored message lands in the focused channel", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_focused" })
+ resetHookMemoization()
+ await mountHook({ viewerUserId: "u_me" })
+
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_focused"), {
+ pages: [{ messages: [], hasMore: false }],
+ pageParams: [null],
+ })
+
+ const event: CommunityMessageCreate = {
+ type: "community:message.create",
+ channelId: "ch_focused",
+ message: {
+ id: "m_1",
+ authorId: "u_someone_else",
+ authorName: "them",
+ content: "hi",
+ seq: 1,
+ createdAt: "2026-07-03T00:00:00.000Z",
+ },
+ }
+ capturedOnMessage!(event)
+
+ expect(markReadMutate).not.toHaveBeenCalled()
+ })
+
+ it("does NOT call markRead when the message is authored by the viewer", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_focused" })
+ resetHookMemoization()
+ await mountHook({ viewerUserId: "u_me" })
+
+ const event: CommunityMessageCreate = {
+ type: "community:message.create",
+ channelId: "ch_focused",
+ message: {
+ id: "m_1",
+ authorId: "u_me",
+ authorName: "me",
+ content: "hi",
+ seq: 1,
+ createdAt: "2026-07-03T00:00:00.000Z",
+ },
+ }
+ capturedOnMessage!(event)
+
+ expect(markReadMutate).not.toHaveBeenCalled()
+ })
+
+ it("does NOT call markRead for a DM message.create either", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
+ resetHookMemoization()
+ await mountHook({ viewerUserId: "u_me" })
+
+ const event: CommunityMessageCreate = {
+ type: "community:message.create",
+ channelId: "dm_1",
+ message: {
+ id: "dm_m_1",
+ authorId: "u_a",
+ authorName: "a",
+ content: "hi",
+ type: "chat",
+ seq: 1,
+ createdAt: "2026-07-03T00:00:00.000Z",
+ },
+ }
+ capturedOnMessage!(event)
+
+ expect(markReadMutate).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.ts
new file mode 100644
index 000000000..0372f90cb
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/message-events.ts
@@ -0,0 +1,291 @@
+import type {
+ CommunityMessageCreate,
+ CommunityMessageUpdated,
+ CommunityPinAdd,
+ CommunityPinRemove,
+ CommunityReactionAdd,
+ CommunityReactionRemove,
+ CommunityWsEvent,
+} from "@alook/shared"
+import { communityKeys } from "@/lib/query-keys"
+import { projectCommunityMessageCreate } from "@/lib/community/message-wire"
+import type { CanonicalMessage } from "@/lib/community/message-stream"
+import { useCommunityStore } from "@/stores/community"
+import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
+import {
+ hasForumSidebarThread,
+ patchForumSidebarActivity,
+ patchForumSidebarTitle,
+ type ForumSidebarQueryData,
+} from "@/hooks/community/use-forum-sidebar-threads"
+import {
+ applyReactionToCache,
+ applyReactionToMessage,
+ findCachedMessage,
+ patchApprovalInCache,
+ patchMessageContentInCache,
+ type PageCache,
+} from "@/hooks/community/community-ws/cache"
+import { clearTypingIndicator, typingScopeKey } from "@/hooks/community/community-ws/typing"
+import type { MessageEventContext } from "@/hooks/community/community-ws/handler-context"
+
+type CommunityMessageEdited = Extract<
+ CommunityWsEvent,
+ { type: "community:message.edited" }
+>
+
+export function handleMessageCreate(
+ event: CommunityMessageCreate,
+ {
+ queryClient,
+ communityStore,
+ wsStore,
+ sub,
+ viewerUserIdRef,
+ scheduleInboxInvalidate,
+ }: MessageEventContext,
+) {
+ const projected = projectCommunityMessageCreate(event.message)
+ if (event.channelId === sub.channelId) {
+ const serverId = useCommunityStore.getState().currentServerId
+ if (serverId) {
+ useMessageStreamStore.getState().dispatch(
+ { kind: "channel", id: event.channelId, serverId },
+ { type: "wsMessage", message: projected },
+ )
+ }
+ }
+ if (event.channelId === sub.dmConversationId) {
+ useMessageStreamStore.getState().dispatch(
+ { kind: "dm", id: event.channelId },
+ { type: "wsMessage", message: projected },
+ )
+ }
+ if (wsStore.hasSeenMessage(event.message.id)) return
+ wsStore.markSeenMessage(event.message.id)
+ // Sending a message is an implicit typing.stop for its author —
+ // clear once we know this is a fresh message. Clearing before dedup
+ // would also clear on WS-reconnect replays of stale messages,
+ // briefly wiping a still-active heartbeat pill. Derive the scope
+ // from whether this channelId is the focused DM channel (`dm:`) or a
+ // regular channel (`ch:`) so the pill clears in the right bucket.
+ clearTypingIndicator(typingScopeKey(event, sub), event.message.authorId)
+
+ // Participation, not unread state, is the sidebar truth. A child
+ // message reaches every notify member even when muted; use its
+ // explicit server/parent metadata to re-rank a loaded row without a
+ // GET, or refetch when the active post is currently absent/expired.
+ if (event.serverId && event.parentChannelId) {
+ const key = communityKeys.forumSidebarThreads(event.serverId)
+ const cached = queryClient.getQueriesData<ForumSidebarQueryData>({ queryKey: key })
+ const loaded = cached.some(([, data]) => hasForumSidebarThread(data, event.channelId))
+ if (loaded) {
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: key },
+ (data) => patchForumSidebarActivity(
+ data,
+ event.channelId,
+ event.parentChannelId!,
+ event.message.createdAt,
+ ),
+ )
+ } else {
+ void queryClient.invalidateQueries({ queryKey: key })
+ }
+ }
+
+ // 1) A child channel enrolls its sender and mentioned users in its
+ // member set server-side, so refresh an open child roster live.
+ if (
+ event.channelId === sub.channelId &&
+ communityStore.currentChannelId === event.channelId &&
+ communityStore.currentChannelMeta?.parentChannelId
+ ) {
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.channelMembers(event.channelId),
+ })
+ }
+
+ // 2) Every message.create — regardless of focus — schedules a
+ // debounced inbox invalidation. Skip messages authored by the
+ // viewer since they never affect their own unreads.
+ const viewerId = viewerUserIdRef.current
+ if (event.message.authorId !== viewerId) {
+ scheduleInboxInvalidate()
+ }
+
+ // 3) Live channel-sidebar unread dot is NO LONGER flipped here.
+ // Unread is per-recipient and mute-gated on the server now, so it
+ // rides the dedicated `community:unread.bump` event (below) — a
+ // muted (`nothing`/unmentioned-`mentions`) channel must NOT light
+ // an unread dot even though its `message.create` still arrives
+ // (mute ≠ blindness: content syncs, the badge does not).
+
+ // Note: no auto-mark-read here. See #3 — the
+ // IntersectionObserver in `useChannelWatermark` advances the
+ // read pointer when a message actually becomes visible in the
+ // viewport. If the user is scrolled up reading history, their
+ // pointer must stay put; the WS handler cannot know whether the
+ // incoming message is on screen.
+
+}
+
+type ReactionEvent = CommunityReactionAdd | CommunityReactionRemove
+
+export function handleReactionEvent(
+ event: ReactionEvent,
+ { queryClient, viewerUserIdRef, sub }: MessageEventContext,
+) {
+ const viewerId = viewerUserIdRef.current
+ // A reaction event carries only `channelId` with no channel-vs-DM
+ // discriminator. A regular channel's cache lives under
+ // `channelMessages(id)`, a DM channel's under `dmMessages(id)` — patch
+ // both keys; the one that doesn't exist receives `undefined` and the
+ // updater returns it, a harmless no-op.
+ queryClient.setQueriesData<PageCache>(
+ { queryKey: communityKeys.channelMessages(event.channelId) },
+ (c) => applyReactionToCache(c, event, viewerId),
+ )
+ queryClient.setQueryData<PageCache>(
+ communityKeys.dmMessages(event.channelId),
+ (c) => applyReactionToCache(c, event, viewerId),
+ )
+ if (event.channelId === sub.channelId) {
+ const serverId = useCommunityStore.getState().currentServerId
+ if (serverId) {
+ const scope = { kind: "channel" as const, id: event.channelId, serverId }
+ const fallback = [...getMessageOverlay(scope).liveById.values()]
+ .find((message) => message.id === event.messageId)
+ if (fallback) {
+ const cached = findCachedMessage(
+ queryClient.getQueryData<PageCache>(communityKeys.channelMessages(event.channelId)),
+ event.messageId,
+ )
+ const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback
+ useMessageStreamStore.getState().dispatch(scope, {
+ type: "liveRefreshed",
+ message: applyReactionToMessage(source, event, viewerId) as CanonicalMessage,
+ })
+ }
+ }
+ }
+ if (event.channelId === sub.dmConversationId) {
+ const scope = { kind: "dm" as const, id: event.channelId }
+ const fallback = [...getMessageOverlay(scope).liveById.values()]
+ .find((message) => message.id === event.messageId)
+ if (fallback) {
+ const cached = findCachedMessage(
+ queryClient.getQueryData<PageCache>(communityKeys.dmMessages(event.channelId)),
+ event.messageId,
+ )
+ const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback
+ useMessageStreamStore.getState().dispatch(scope, {
+ type: "liveRefreshed",
+ message: applyReactionToMessage(source, event, viewerId) as CanonicalMessage,
+ })
+ }
+ }
+}
+
+export function handlePinEvent(
+ event: CommunityPinAdd | CommunityPinRemove,
+ { queryClient }: MessageEventContext,
+) {
+ void queryClient.invalidateQueries({ queryKey: communityKeys.pins(event.channelId) })
+}
+
+export function handleMessageUpdated(
+ event: CommunityMessageUpdated,
+ { queryClient, sub }: MessageEventContext,
+) {
+ // Folded from the old `dm.message_updated` — keyed by `channelId` (the
+ // DM's channel id). Patch the card's approval payload in the focused
+ // DM cache so it re-renders in its new state without a refetch.
+ if (event.channelId === sub.dmConversationId || event.channelId === sub.channelId) {
+ queryClient.setQueryData<PageCache>(
+ communityKeys.dmMessages(event.channelId),
+ (c) => patchApprovalInCache(c, event.messageId, event.approval),
+ )
+ queryClient.setQueryData<PageCache>(
+ communityKeys.channelMessages(event.channelId),
+ (c) => patchApprovalInCache(c, event.messageId, event.approval),
+ )
+ }
+ const overlayScopes = event.channelId === sub.dmConversationId
+ ? [{ kind: "dm" as const, id: event.channelId }]
+ : event.channelId === sub.channelId
+ ? (() => {
+ const serverId = useCommunityStore.getState().currentServerId
+ return serverId
+ ? [{ kind: "channel" as const, id: event.channelId, serverId }]
+ : []
+ })()
+ : []
+ for (const scope of overlayScopes) {
+ const fallback = [...getMessageOverlay(scope).liveById.values()]
+ .find((message) => message.id === event.messageId)
+ if (!fallback) continue
+ const key = scope.kind === "dm"
+ ? communityKeys.dmMessages(event.channelId)
+ : communityKeys.channelMessages(event.channelId)
+ const cached = findCachedMessage(
+ queryClient.getQueryData<PageCache>(key),
+ event.messageId,
+ )
+ const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback
+ useMessageStreamStore.getState().dispatch(scope, {
+ type: "liveRefreshed",
+ message: { ...source, approval: event.approval },
+ })
+ }
+ // When a card resolves (accepted/denied/superseded), the friend graph
+ // changed — invalidate friends + pending so the owner's lists reflect
+ // it. This is the owner's only signal in the J2 tail (Alice's accept
+ // dead-letters FRIEND_ACCEPT to the bot).
+ if (event.approval.status !== "pending" || event.approval.waitingOn !== "you") {
+ void queryClient.invalidateQueries({ queryKey: communityKeys.friends() })
+ }
+}
+
+export function handleMessageEdited(
+ event: CommunityMessageEdited,
+ { queryClient }: MessageEventContext,
+) {
+ queryClient.setQueryData<{ content: string }>(
+ communityKeys.message(event.messageId),
+ (message) => message ? { ...message, content: event.content } : message,
+ )
+ queryClient.setQueriesData<PageCache>(
+ { queryKey: communityKeys.channelMessages(event.channelId) },
+ (cache) => patchMessageContentInCache(cache, event.messageId, event.content),
+ )
+ queryClient.setQueryData<PageCache>(
+ communityKeys.dmMessages(event.channelId),
+ (cache) => patchMessageContentInCache(cache, event.messageId, event.content),
+ )
+ const streamStore = useMessageStreamStore.getState()
+ for (const entry of streamStore.entries.values()) {
+ if (entry.scope.id !== event.channelId) continue
+ streamStore.dispatch(entry.scope, {
+ type: "messageEdited",
+ messageId: event.messageId,
+ content: event.content,
+ })
+ }
+ if (event.parentChannelId) {
+ queryClient.setQueriesData<PageCache>(
+ { queryKey: communityKeys.channelMessages(event.parentChannelId) },
+ (cache) => patchMessageContentInCache(cache, event.messageId, event.content),
+ )
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.channelMessages(event.parentChannelId),
+ })
+ const serverId = useCommunityStore.getState().currentServerId
+ if (serverId) {
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: communityKeys.forumSidebarThreads(serverId) },
+ (data) => patchForumSidebarTitle(data, event.channelId, event.content),
+ )
+ }
+ }
+}
diff --git a/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts b/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts
new file mode 100644
index 000000000..18bcbfcdc
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts
@@ -0,0 +1,120 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import type {
+ CommunityMachineCreated,
+ CommunityMachineStatus,
+ CommunityPresenceUpdate,
+ CommunityStatusUpdate,
+} from "@alook/shared"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ capturedOnMessage,
+ capturedQueryClient,
+ cleanupCommunityWsHarness,
+ mountHook,
+ resetCommunityWsHarness,
+} from "./test-harness"
+
+beforeEach(resetCommunityWsHarness)
+afterEach(cleanupCommunityWsHarness)
+
+describe("useCommunityWs — presence → Zustand store, no cache", () => {
+ it("presence.update writes to useCommunityWsStore only", async () => {
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const event: CommunityPresenceUpdate = {
+ type: "community:presence.update",
+ userId: "u_pres",
+ online: true,
+ }
+ capturedOnMessage!(event)
+ const { useCommunityWsStore } = await import("@/stores/community/ws")
+ expect(useCommunityWsStore.getState().onlineUserIds.has("u_pres")).toBe(true)
+ // No cache touched.
+ expect(spy).not.toHaveBeenCalled()
+ })
+
+})
+describe("useCommunityWs — status.update → Zustand store, no cache", () => {
+ it("status.update writes to useCommunityWsStore only", async () => {
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const event: CommunityStatusUpdate = {
+ type: "community:status.update",
+ userId: "u_status",
+ statusEmoji: "🎧",
+ statusText: "Vibing",
+ }
+ capturedOnMessage!(event)
+ const { useCommunityWsStore } = await import("@/stores/community/ws")
+ expect(useCommunityWsStore.getState().userStatuses.get("u_status")).toEqual({
+ emoji: "🎧",
+ text: "Vibing",
+ })
+ // No cache touched.
+ expect(spy).not.toHaveBeenCalled()
+ })
+})
+
+describe("useCommunityWs — machines", () => {
+ it("machine.created upserts and stashes pending token", async () => {
+ await mountHook()
+ const created: CommunityMachineCreated = {
+ type: "community:machine.created",
+ tokenId: "cmt_abc",
+ machine: {
+ id: "m_1",
+ hostname: "h",
+ displayName: "d",
+ platform: "darwin",
+ arch: "arm64",
+ osRelease: "24",
+ daemonVersion: "0.1",
+ lastSeenAt: null,
+ status: "online",
+ availableRuntimes: [],
+ createdAt: "2026-07-03T00:00:00.000Z",
+ updatedAt: "2026-07-03T00:00:00.000Z",
+ },
+ }
+ capturedOnMessage!(created)
+ expect(
+ capturedQueryClient.getQueryData<{ machines: { id: string }[] }>(communityKeys.machines())?.machines,
+ ).toHaveLength(1)
+ const { useCommunityStore } = await import("@/stores/community")
+ expect(useCommunityStore.getState().pendingMachineTokenId).toBe("cmt_abc")
+ })
+
+ it("machine.status patches lastSeenAt/status only", async () => {
+ await mountHook()
+ capturedQueryClient.setQueryData(communityKeys.machines(), {
+ machines: [
+ {
+ id: "m_1",
+ hostname: "h",
+ displayName: "d",
+ platform: "darwin",
+ arch: "arm64",
+ osRelease: "24",
+ daemonVersion: "0.1",
+ lastSeenAt: null,
+ status: "online",
+ availableRuntimes: [],
+ createdAt: "",
+ updatedAt: "",
+ },
+ ],
+ })
+ const status: CommunityMachineStatus = {
+ type: "community:machine.status",
+ machineId: "m_1",
+ status: "offline",
+ lastSeenAt: "2026-07-03T00:00:00.000Z",
+ }
+ capturedOnMessage!(status)
+ const cache = capturedQueryClient.getQueryData<{ machines: { status: string; lastSeenAt: string | null }[] }>(
+ communityKeys.machines(),
+ )
+ expect(cache?.machines[0].status).toBe("offline")
+ expect(cache?.machines[0].lastSeenAt).toBe("2026-07-03T00:00:00.000Z")
+ })
+})
diff --git a/src/web/src/hooks/community/community-ws/presence-machine-events.ts b/src/web/src/hooks/community/community-ws/presence-machine-events.ts
new file mode 100644
index 000000000..1832b2948
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/presence-machine-events.ts
@@ -0,0 +1,105 @@
+import type {
+ CommunityBotAuditEvent,
+ CommunityMachineCreated,
+ CommunityMachineRemoved,
+ CommunityMachineStatus,
+ CommunityMachineSummary,
+ CommunityMachineUpdated,
+ CommunityPresenceUpdate,
+ CommunityStatusUpdate,
+} from "@alook/shared"
+import { communityKeys } from "@/lib/query-keys"
+import { useCommunityStore } from "@/stores/community"
+import { useCommunityWsStore } from "@/stores/community/ws"
+import type { MachinesResponse } from "@/hooks/community/use-machines"
+import type { PresenceMachineEventContext } from "@/hooks/community/community-ws/handler-context"
+
+// Presence has no query cache; write to the WS store.
+export function handlePresenceUpdate(event: CommunityPresenceUpdate) {
+ useCommunityWsStore.getState().setPresence(event.userId, event.online)
+}
+
+// Status uses the same WS-store overlay pattern as presence.
+export function handleStatusUpdate(event: CommunityStatusUpdate) {
+ useCommunityWsStore.getState().setUserStatus(event.userId, event.statusEmoji, event.statusText)
+}
+
+// Push audit events into the bounded ring; the audit-log hook filters and
+// prepends them into its React Query cache.
+export function handleBotAuditEvent(event: CommunityBotAuditEvent) {
+ useCommunityWsStore.getState().pushBotAuditEvent({
+ id: event.id,
+ botId: event.botId,
+ kind: event.kind,
+ payload: event.payload,
+ sessionId: event.sessionId ?? null,
+ launchId: event.launchId ?? null,
+ createdAt: event.createdAt,
+ })
+}
+
+export function handleMachineCreated(
+ event: CommunityMachineCreated,
+ { queryClient }: PresenceMachineEventContext,
+) {
+ queryClient.setQueryData<MachinesResponse | undefined>(
+ communityKeys.machines(),
+ (prev) => {
+ if (!prev) return { machines: [event.machine] }
+ const idx = prev.machines.findIndex((m) => m.id === event.machine.id)
+ if (idx === -1) return { ...prev, machines: [event.machine, ...prev.machines] }
+ const next = prev.machines.slice()
+ next[idx] = event.machine
+ return { ...prev, machines: next }
+ },
+ )
+ useCommunityStore.getState().setPendingMachineTokenId(event.tokenId)
+}
+
+export function handleMachineStatus(
+ event: CommunityMachineStatus,
+ { queryClient }: PresenceMachineEventContext,
+) {
+ queryClient.setQueryData<MachinesResponse | undefined>(
+ communityKeys.machines(),
+ (prev) =>
+ prev
+ ? {
+ ...prev,
+ machines: prev.machines.map((m) =>
+ m.id === event.machineId
+ ? { ...m, lastSeenAt: event.lastSeenAt, status: event.status }
+ : m,
+ ),
+ }
+ : prev,
+ )
+}
+
+export function handleMachineUpdated(
+ event: CommunityMachineUpdated,
+ { queryClient }: PresenceMachineEventContext,
+) {
+ queryClient.setQueryData<MachinesResponse | undefined>(
+ communityKeys.machines(),
+ (prev) => {
+ if (!prev) return { machines: [event.machine] }
+ const idx = prev.machines.findIndex((m) => m.id === event.machine.id)
+ if (idx === -1) return { ...prev, machines: [event.machine, ...prev.machines] }
+ const next: CommunityMachineSummary[] = prev.machines.slice()
+ next[idx] = event.machine
+ return { ...prev, machines: next }
+ },
+ )
+}
+
+export function handleMachineRemoved(
+ event: CommunityMachineRemoved,
+ { queryClient }: PresenceMachineEventContext,
+) {
+ queryClient.setQueryData<MachinesResponse | undefined>(
+ communityKeys.machines(),
+ (prev) =>
+ prev ? { ...prev, machines: prev.machines.filter((m) => m.id !== event.machineId) } : prev,
+ )
+}
diff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.ts
new file mode 100644
index 000000000..b000e1802
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts
@@ -0,0 +1,174 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ capturedOnReconnect,
+ capturedQueryClient,
+ cleanupCommunityWsHarness,
+ mountHook,
+ resetCommunityWsHarness,
+} from "./test-harness"
+
+beforeEach(resetCommunityWsHarness)
+afterEach(cleanupCommunityWsHarness)
+
+describe("useCommunityWs — resyncs machines on WS reconnect", () => {
+ it("invalidates communityKeys.machines() when the captured onReconnect fires", async () => {
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+
+ expect(capturedOnReconnect).not.toBeNull()
+ capturedOnReconnect!()
+
+ expect(
+ spy.mock.calls.some((c) => {
+ const key = c[0]?.queryKey as unknown[] | undefined
+ return Array.isArray(key) && key.includes("machines")
+ }),
+ ).toBe(true)
+ expect(spy).toHaveBeenCalledWith({
+ queryKey: [...communityKeys.all, "bot"],
+ exact: false,
+ })
+ })
+
+ it("invalidates the focused channel's messages + inbox on reconnect, but NOT the read-state snapshot", async () => {
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_focus" })
+
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+
+ expect(capturedOnReconnect).not.toBeNull()
+ capturedOnReconnect!()
+
+ const invalidatedKeys = spy.mock.calls.map(
+ (c) => c[0]?.queryKey as unknown[] | undefined,
+ )
+ // Focused channel messages — a legitimate top-up refetch that keeps data.
+ expect(
+ invalidatedKeys.some(
+ (k) =>
+ Array.isArray(k) &&
+ k[0] === "community" &&
+ k[1] === "channel" &&
+ k[2] === "ch_focus" &&
+ k[3] === "messages",
+ ),
+ ).toBe(true)
+ // Read-state snapshot MUST NOT be invalidated: the snapshot hook latches
+ // its first value (gcTime: 0, frozen ref) so a refetch can't move the
+ // "New" divider — it only flips `isFetching` back to true, which the
+ // channel page reads as loading and flashes a second skeleton mid-mount
+ // (the "skeleton → content → skeleton → top hero" refresh bug). See
+ // `handleReconnect`'s comment in use-community-ws.ts.
+ expect(
+ invalidatedKeys.some(
+ (k) =>
+ Array.isArray(k) &&
+ k[0] === "community" &&
+ k[1] === "channel" &&
+ k[2] === "ch_focus" &&
+ k[3] === "read-state-snapshot",
+ ),
+ ).toBe(false)
+ // Inbox
+ expect(
+ invalidatedKeys.some(
+ (k) => Array.isArray(k) && k[0] === "community" && k[1] === "inbox",
+ ),
+ ).toBe(true)
+ })
+
+ it("re-seeds the rail list + open server's detail on reconnect (inbox-dot-ws-driven ②)", async () => {
+ // Sidebar dots + rail mention badges are now driven by the live
+ // `unread.bump` patch, with no switch-refetch backing them. A bump dropped
+ // during the socket gap would leave them stale, so reconnect must re-seed
+ // both — else the cross-server dot fix silently rots after any disconnect.
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+
+ // handleReconnect reads currentServerId via getState() at call time.
+ expect(capturedOnReconnect).not.toBeNull()
+ capturedOnReconnect!()
+
+ const invalidatedKeys = spy.mock.calls.map(
+ (c) => c[0]?.queryKey as unknown[] | undefined,
+ )
+ // Rail LIST = communityKeys.servers() = ["community","servers"] (length 2).
+ expect(
+ invalidatedKeys.some(
+ (k) => Array.isArray(k) && k.length === 2 && k[0] === "community" && k[1] === "servers",
+ ),
+ ).toBe(true)
+ // Open server's DETAIL = communityKeys.server(id) = ["community","servers",id].
+ expect(
+ invalidatedKeys.some(
+ (k) =>
+ Array.isArray(k) &&
+ k[0] === "community" &&
+ k[1] === "servers" &&
+ k[2] === "srv_open",
+ ),
+ ).toBe(true)
+ })
+
+ it("invalidates the focused DM's messages on reconnect, but NOT its read-state snapshot", async () => {
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_focus" })
+
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+
+ expect(capturedOnReconnect).not.toBeNull()
+ capturedOnReconnect!()
+
+ const invalidatedKeys = spy.mock.calls.map(
+ (c) => c[0]?.queryKey as unknown[] | undefined,
+ )
+ expect(
+ invalidatedKeys.some(
+ (k) =>
+ Array.isArray(k) &&
+ k[0] === "community" &&
+ k[1] === "dm" &&
+ k[2] === "dm_focus" &&
+ k[3] === "messages",
+ ),
+ ).toBe(true)
+ // Read-state snapshot MUST NOT be invalidated — same rationale as the
+ // channel case (mirrors `useChannelReadStateSnapshot`'s freeze contract).
+ expect(
+ invalidatedKeys.some(
+ (k) =>
+ Array.isArray(k) &&
+ k[0] === "community" &&
+ k[1] === "dm" &&
+ k[2] === "dm_focus" &&
+ k[3] === "read-state-snapshot",
+ ),
+ ).toBe(false)
+ })
+
+ it("only invalidates the focused scope — no channel invalidation when only a DM is focused", async () => {
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_focus" })
+
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+
+ expect(capturedOnReconnect).not.toBeNull()
+ capturedOnReconnect!()
+
+ const invalidatedKeys = spy.mock.calls.map(
+ (c) => c[0]?.queryKey as unknown[] | undefined,
+ )
+ // No channel-scoped message invalidation should have fired.
+ expect(
+ invalidatedKeys.some(
+ (k) => Array.isArray(k) && k[1] === "channel" && k[3] === "messages",
+ ),
+ ).toBe(false)
+ })
+})
diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.ts
new file mode 100644
index 000000000..f35f8a181
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/reconnect.ts
@@ -0,0 +1,88 @@
+import type { QueryClient } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import { useCommunityStore } from "@/stores/community"
+
+/**
+ * Machines are WS-live-patched with no query refetch (see `use-machines.ts`)
+ * — but that only works while THIS browser tab's own socket stays connected.
+ * If the socket drops and an offline→online transition happens while it's
+ * down, the event never arrives and the card is stuck stale until a full
+ * page reload. Mirror `AgentProvider`'s reconnect pattern
+ * (`contexts/agent-context.tsx`): resync the machines query on every
+ * reconnect so a missed transition self-corrects within the reconnect
+ * window instead of requiring a manual reload.
+ *
+ * Same rationale for the focused channel/DM message stream after Commit C:
+ * the IDB persister rehydrates the cache from the last session, but the
+ * socket may have dropped WS `message.create` events while we were offline
+ * (or the tab was suspended). Invalidating the focused scope's message
+ * query on reconnect fires a top-up refetch — TanStack re-runs every
+ * page's `pageParam`, so anchor windows and newest-tail windows both
+ * catch up without any client-side `?since` bookkeeping.
+ *
+ * Do NOT invalidate the read-state SNAPSHOT here. The snapshot hook
+ * (`useChannelReadStateSnapshot`, `gcTime: 0`) latches its first resolved
+ * value in a ref and deliberately never updates it during a mount — that
+ * freeze is what keeps the "New" divider pinned while the watermark
+ * advances. Re-fetching it can't move the divider (the ref ignores the new
+ * value), but it DOES flip the hook's `isFetching` back to true, which the
+ * channel/DM pages read as `lastReadMessageId: undefined` →
+ * `useMessages.isLoading: true` → the whole view drops back to the loading
+ * skeleton. Because `onReconnect` fires once even on a fresh page load (a
+ * StrictMode / refresh double-connect makes the socket's second open run
+ * it ~1.5s in), that surfaced as a SECOND skeleton flash mid-mount —
+ * "skeleton → content → skeleton → scroll to the top hero" (the empty
+ * round-trip also burned the message list's one-shot mount-scroll gate;
+ * see `use-scroll-anchor.ts`'s re-arm-on-empty branch). Verified via live
+ * Playwright page-level trace: the second skeleton window lines up exactly
+ * with `readSnapshotFetching` going true at t≈1.75s. The message-query
+ * invalidation below is the legitimate top-up and keeps its data on
+ * screen; the divider is already correct from the first (frozen) snapshot,
+ * so nothing here needs the snapshot refetched.
+ */
+export function reconcileCommunityWsReconnect(queryClient: QueryClient) {
+ queryClient.invalidateQueries({ queryKey: communityKeys.machines() })
+ const sub = useCommunityStore.getState().subscription
+ if (sub.channelId) {
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.channelMessages(sub.channelId),
+ })
+ }
+ if (sub.dmConversationId) {
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.dmMessages(sub.dmConversationId),
+ })
+ // A DM message may have arrived while offline; the DM sidebar preview /
+ // unread flag is only reconciled on `message.create`, none of which land
+ // during the gap. Top it up on reconnect.
+ void queryClient.invalidateQueries({ queryKey: communityKeys.dms() })
+ }
+ // Inbox counts also need a refetch — unreads and mentions could have
+ // grown while offline and the live invalidator only fires on incoming
+ // `message.create` events, none of which arrive while the socket is
+ // down.
+ void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
+ // Sidebar unread dots + rail mention badges are now driven by the live
+ // `unread.bump` patch (inbox-dot-ws-driven plan) — no switch-refetch backs
+ // them anymore. A bump dropped during the socket gap would leave the dot /
+ // rail badge stale forever, so re-seed both on reconnect: the rail LIST
+ // (`servers()`, mention counts) and the open server's detail tree
+ // (`server(currentServerId)`, channel dots). `exact` on the list so it
+ // doesn't cascade-refetch every server's nested detail subtree.
+ void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })
+ const currentServerId = useCommunityStore.getState().currentServerId
+ if (currentServerId) {
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.server(currentServerId),
+ })
+ }
+ // Bot audit logs are WS-live-patched into the React Query cache; if
+ // the socket dropped, any events emitted during the gap never entered
+ // the store's ring and so never made it into the cache. Invalidating
+ // all bot audit-log pages on reconnect lets an open modal catch up.
+ void queryClient.invalidateQueries({
+ queryKey: [...communityKeys.all, "bot"],
+ // Fuzzy prefix match — communityKeys.botAuditLog is [all, "bot", botId, "audit-log"].
+ exact: false,
+ })
+}
diff --git a/src/web/src/hooks/community/community-ws/social-events.test.ts b/src/web/src/hooks/community/community-ws/social-events.test.ts
new file mode 100644
index 000000000..85bbbdc97
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/social-events.test.ts
@@ -0,0 +1,375 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import type {
+ CommunityFriendRequest,
+ CommunityMentionCreate,
+ CommunityMessageCreate,
+} from "@alook/shared"
+import { getMessageOverlay } from "@/stores/community/message-stream"
+import { communityKeys } from "@/lib/query-keys"
+import type { ServerDetail } from "../use-servers"
+import {
+ patchForumSidebarUnread,
+ reconcileForumSidebarUnreadFallbacks,
+ type ForumSidebarQueryData,
+ type ForumSidebarUnreadFallbackState,
+} from "../use-forum-sidebar-threads"
+import {
+ capturedOnMessage,
+ capturedQueryClient,
+ cleanupCommunityWsHarness,
+ forumSidebarFixture,
+ messageCreate,
+ mountHook,
+ resetCommunityWsHarness,
+ resetHookMemoization,
+ unreadBump,
+} from "./test-harness"
+
+beforeEach(resetCommunityWsHarness)
+afterEach(cleanupCommunityWsHarness)
+
+describe("useCommunityWs — message.create patches channel unread in the open server's cache", () => {
+ function serverDetailFixture(channelId: string) {
+ return {
+ id: "srv_open",
+ name: "Server",
+ description: "",
+ icon: null,
+ ownerId: "u_owner",
+ categories: [
+ { id: "cat_A", name: "Category A", channels: [{ id: channelId, name: "random", active: false, unread: false }] },
+ ],
+ }
+ }
+
+ it("flips the channel's unread to true on unread.bump when it belongs to the currently-open server's cached ServerDetail", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
+
+ capturedOnMessage!(unreadBump("ch_random", "u_me"))
+
+ const cache = capturedQueryClient.getQueryData<{
+ categories: { channels: { id: string; unread: boolean }[] }[]
+ }>(communityKeys.server("srv_open"))
+ expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_random", unread: true })
+ })
+
+ it("routes a child unread.bump to its loaded forum-sidebar row instead of the parent forum", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("forum_1"))
+ const sidebarKey = communityKeys.forumSidebarThreadsView("srv_open", null)
+ capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture())
+
+ capturedOnMessage!(unreadBump("post_1", "u_me", {
+ serverId: "srv_open",
+ railChannelId: "forum_1",
+ }))
+
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(sidebarKey)?.threads[0].unread)
+ .toBe(true)
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
+ communityKeys.server("srv_open"),
+ )?.categories[0].channels[0].unread).toBe(false)
+ expect(capturedQueryClient.getQueryData<ServerDetail>(
+ communityKeys.server("srv_open"),
+ )?.forumUnreadState?.forum_1?.childIds).toEqual(["post_1"])
+ })
+
+ it("falls back to the parent forum dot when the child has no locatable sidebar row", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("forum_1"))
+ capturedQueryClient.setQueryData(
+ communityKeys.forumSidebarThreadsView("srv_open", null),
+ forumSidebarFixture([]),
+ )
+
+ capturedOnMessage!(unreadBump("post_missing", "u_me", {
+ serverId: "srv_open",
+ railChannelId: "forum_1",
+ }))
+
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
+ communityKeys.server("srv_open"),
+ )?.categories[0].channels[0].unread).toBe(true)
+ expect(capturedQueryClient.getQueryData<ForumSidebarUnreadFallbackState>(
+ communityKeys.forumSidebarUnreadFallbacks("srv_open"),
+ )).toEqual({
+ forum_1: { baseUnread: false, childIds: ["post_missing"] },
+ })
+ })
+
+ it("moves message.create → unread.bump fallback ownership to the refetched child", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const serverKey = communityKeys.server("srv_open")
+ const sidebarKey = communityKeys.forumSidebarThreadsView("srv_open", null)
+ capturedQueryClient.setQueryData(serverKey, serverDetailFixture("forum_1"))
+ capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture([]))
+
+ capturedOnMessage!({
+ ...messageCreate("post_new"),
+ serverId: "srv_open",
+ parentChannelId: "forum_1",
+ } satisfies CommunityMessageCreate)
+ expect(capturedQueryClient.getQueryState(sidebarKey)?.isInvalidated).toBe(true)
+
+ capturedOnMessage!(unreadBump("post_new", "u_me", {
+ serverId: "srv_open",
+ railChannelId: "forum_1",
+ }))
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
+ serverKey,
+ )?.categories[0].channels[0].unread).toBe(true)
+
+ const refetched = forumSidebarFixture(["post_new"])
+ refetched.threads[0]!.unread = true
+ capturedQueryClient.setQueryData(sidebarKey, refetched)
+ reconcileForumSidebarUnreadFallbacks(capturedQueryClient, "srv_open", ["post_new"])
+
+ expect(capturedQueryClient.getQueryData<ForumSidebarQueryData>(sidebarKey)?.threads[0]?.unread).toBe(true)
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
+ serverKey,
+ )?.categories[0].channels[0].unread).toBe(false)
+
+ capturedQueryClient.setQueryData<ForumSidebarQueryData>(sidebarKey, (data) =>
+ patchForumSidebarUnread(data, "post_new", false),
+ )
+ expect(capturedQueryClient.getQueryData<ForumSidebarQueryData>(sidebarKey)?.threads[0]?.unread).toBe(false)
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
+ serverKey,
+ )?.categories[0].channels[0].unread).toBe(false)
+ })
+
+ it("message.create alone does NOT flip the sidebar unread (mute-gated bump is the only trigger now)", async () => {
+ // Regression pin: mute ≠ blindness. The message.create still arrives (and
+ // content syncs), but the unread dot is flipped ONLY by the server's
+ // per-recipient, mute-gated unread.bump — so a muted channel's message.create
+ // must NOT light the dot. Don't "fix" this back onto message.create.
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
+
+ capturedOnMessage!(messageCreate("ch_random"))
+
+ const cache = capturedQueryClient.getQueryData<{
+ categories: { channels: { id: string; unread: boolean }[] }[]
+ }>(communityKeys.server("srv_open"))
+ expect(cache?.categories[0].channels[0].unread).toBe(false)
+ })
+
+ it("does NOT flip unread on a bump addressed to a different user", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
+
+ capturedOnMessage!(unreadBump("ch_random", "someone_else"))
+
+ const cache = capturedQueryClient.getQueryData<{
+ categories: { channels: { id: string; unread: boolean }[] }[]
+ }>(communityKeys.server("srv_open"))
+ expect(cache?.categories[0].channels[0].unread).toBe(false)
+ })
+
+ it("does NOT flip unread for the currently-subscribed (active) channel", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ useCommunityStore.getState().subscribe({ channelId: "ch_random" })
+ resetHookMemoization()
+ await mountHook({ viewerUserId: "u_me" })
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
+
+ capturedOnMessage!(unreadBump("ch_random", "u_me"))
+
+ const cache = capturedQueryClient.getQueryData<{
+ categories: { channels: { id: string; unread: boolean }[] }[]
+ }>(communityKeys.server("srv_open"))
+ expect(cache?.categories[0].channels[0].unread).toBe(false)
+ })
+
+ it("is a no-op when the channel isn't present in the currently cached ServerDetail (different server / no cache)", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_other"))
+
+ expect(() => capturedOnMessage!(unreadBump("ch_random", "u_me"))).not.toThrow()
+
+ const cache = capturedQueryClient.getQueryData<{
+ categories: { channels: { id: string; unread: boolean }[] }[]
+ }>(communityKeys.server("srv_open"))
+ // Untouched — the fixture's own channel stays unread: false.
+ expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_other", unread: false })
+ })
+
+ it("does not crash and is a no-op when no server is currently open", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ expect(() => capturedOnMessage!(unreadBump("ch_random", "u_me"))).not.toThrow()
+ })
+
+ // ── inbox-dot-ws-driven ② : bump carries serverId / railChannelId / isMention ──
+
+ it("lights the dot on the bump's OWN serverId, even when a DIFFERENT server is open (the cross-server bug)", async () => {
+ // The core fix: previously the handler only patched the currently-open
+ // server, so a message in another server never lit its dot. With
+ // `serverId` on the bump we patch the right server's detail regardless of
+ // which one is focused.
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open") // a different server is focused
+ capturedQueryClient.setQueryData(communityKeys.server("srv_other"), serverDetailFixture("ch_bg"))
+
+ capturedOnMessage!(unreadBump("ch_bg", "u_me", { serverId: "srv_other" }))
+
+ const cache = capturedQueryClient.getQueryData<{
+ categories: { channels: { id: string; unread: boolean }[] }[]
+ }>(communityKeys.server("srv_other"))
+ expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_bg", unread: true })
+ })
+
+ it("lights the PARENT channel row for a thread bump (railChannelId), not the thread's own id", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ // The tree row is the parent channel; the thread has no independent row.
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_parent"))
+
+ // channelId = the thread's id (true scope), railChannelId = parent row.
+ capturedOnMessage!(unreadBump("ch_thread", "u_me", { serverId: "srv_open", railChannelId: "ch_parent" }))
+
+ const cache = capturedQueryClient.getQueryData<{
+ categories: { channels: { id: string; unread: boolean }[] }[]
+ }>(communityKeys.server("srv_open"))
+ expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_parent", unread: true })
+ })
+
+ it("suppresses the dot when the viewer is looking at the RAIL row (thread bump whose parent is open)", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ useCommunityStore.getState().subscribe({ channelId: "ch_parent" }) // parent row is open
+ resetHookMemoization()
+ await mountHook({ viewerUserId: "u_me" })
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_parent"))
+
+ capturedOnMessage!(unreadBump("ch_thread", "u_me", { serverId: "srv_open", railChannelId: "ch_parent" }))
+
+ const cache = capturedQueryClient.getQueryData<{
+ categories: { channels: { id: string; unread: boolean }[] }[]
+ }>(communityKeys.server("srv_open"))
+ expect(cache?.categories[0].channels[0].unread).toBe(false)
+ })
+
+ it("bumps the rail mention badge (servers() mentions +1) ONLY when isMention is set", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ capturedQueryClient.setQueryData(communityKeys.servers(), {
+ servers: [{ id: "srv_x", name: "X", initial: "X", active: false, mentions: 2, icon: null }],
+ })
+
+ // Plain unread (no isMention) → mention count unchanged.
+ capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x" }))
+ let servers = capturedQueryClient.getQueryData<{ servers: { id: string; mentions: number }[] }>(communityKeys.servers())
+ expect(servers?.servers[0].mentions).toBe(2)
+
+ // Mention → +1.
+ capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x", isMention: true }))
+ servers = capturedQueryClient.getQueryData<{ servers: { id: string; mentions: number }[] }>(communityKeys.servers())
+ expect(servers?.servers[0].mentions).toBe(3)
+ })
+
+ it("existing focused-channel message patch and debounced inbox invalidation still fire on message.create", async () => {
+ vi.useFakeTimers()
+ try {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ useCommunityStore.getState().subscribe({ channelId: "ch_focused" })
+ resetHookMemoization()
+ await mountHook({ viewerUserId: "u_me" })
+
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_focused"), {
+ pages: [{ messages: [], hasMore: false }],
+ pageParams: [null],
+ })
+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_focused"))
+ const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+
+ capturedOnMessage!(messageCreate("ch_focused"))
+ vi.advanceTimersByTime(500)
+
+ const messagesCache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
+ communityKeys.channelMessages("ch_focused"),
+ )
+ expect(messagesCache?.pages[0].messages).toEqual([])
+ expect(getMessageOverlay({ kind: "channel", id: "ch_focused", serverId: "s1" }).liveById.has("m_1")).toBe(true)
+ const inboxCalls = invalidateSpy.mock.calls.filter((c) => {
+ const key = c[0]?.queryKey
+ return Array.isArray(key) && key.includes("inbox")
+ })
+ expect(inboxCalls).toHaveLength(1)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+})
+describe("useCommunityWs — friend + mention → invalidate", () => {
+ it("friend.request invalidates communityKeys.friends()", async () => {
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const event: CommunityFriendRequest = {
+ type: "community:friend.request",
+ friendship: {
+ id: "f_1",
+ requesterId: "u_a",
+ addresseeId: "u_b",
+ status: "pending",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ },
+ }
+ capturedOnMessage!(event)
+ expect(
+ spy.mock.calls.some((c) => {
+ const key = c[0]?.queryKey as unknown[] | undefined
+ return Array.isArray(key) && key.includes("friends")
+ }),
+ ).toBe(true)
+ })
+
+ it("mention.create invalidates communityKeys.inbox() immediately (no debounce)", async () => {
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const event: CommunityMentionCreate = {
+ type: "community:mention.create",
+ userId: "u_1",
+ messageId: "m_1",
+ authorName: "A",
+ }
+ capturedOnMessage!(event)
+ expect(
+ spy.mock.calls.some((c) => {
+ const key = c[0]?.queryKey as unknown[] | undefined
+ return Array.isArray(key) && key.includes("inbox")
+ }),
+ ).toBe(true)
+ })
+
+ it("mention.create also invalidates communityKeys.servers() so the rail badge ticks", async () => {
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const event: CommunityMentionCreate = {
+ type: "community:mention.create",
+ userId: "u_1",
+ messageId: "m_1",
+ authorName: "A",
+ }
+ capturedOnMessage!(event)
+ const serversInvalidates = spy.mock.calls.filter((c) => {
+ const key = c[0]?.queryKey as unknown[] | undefined
+ return Array.isArray(key) && key.length === 2 && key[0] === "community" && key[1] === "servers"
+ })
+ expect(serversInvalidates).toHaveLength(1)
+ })
+})
diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.ts
new file mode 100644
index 000000000..f4dcb17a0
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/social-events.ts
@@ -0,0 +1,149 @@
+import type {
+ CommunityFriendAccept,
+ CommunityFriendBlock,
+ CommunityFriendReject,
+ CommunityFriendRemove,
+ CommunityFriendRequest,
+ CommunityMentionCreate,
+ CommunityWsEvent,
+} from "@alook/shared"
+import { communityKeys } from "@/lib/query-keys"
+import { useCommunityStore } from "@/stores/community"
+import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
+import type { ServersResponse, ServerDetail } from "@/hooks/community/use-servers"
+import {
+ hasForumSidebarThread,
+ patchForumSidebarUnread,
+ recordForumSidebarChildUnread,
+ setForumSidebarParentUnreadBase,
+ type ForumSidebarQueryData,
+} from "@/hooks/community/use-forum-sidebar-threads"
+import type { SocialEventContext } from "@/hooks/community/community-ws/handler-context"
+
+type CommunityUnreadBump = Extract<
+ CommunityWsEvent,
+ { type: "community:unread.bump" }
+>
+
+// Mute-gated on the server (only recipients whose effective level
+// delivers get this), so the sidebar unread dot flips ONLY here — a
+// muted channel's `message.create` no longer lights it. Skip the
+// currently-subscribed channel (dot suppressed there anyway) and never
+// for the viewer's own sends (the server excludes the author, but guard
+// defensively).
+export function handleUnreadBump(
+ event: CommunityUnreadBump,
+ { queryClient, viewerUserIdRef, sub }: SocialEventContext,
+) {
+ const viewerId = viewerUserIdRef.current
+ // `railChannelId` is the always-locatable fallback. A participating
+ // forum child now has its own nested row, so prefer that row when it
+ // is loaded; ordinary/expired children continue to light the parent.
+ const railChannelId = event.railChannelId ?? event.channelId
+ const targetServerId =
+ event.serverId ?? useCommunityStore.getState().currentServerId
+ const sidebarKey = targetServerId
+ ? communityKeys.forumSidebarThreads(targetServerId)
+ : null
+ const hasChildSidebarRow = !!sidebarKey && event.channelId !== railChannelId &&
+ queryClient.getQueriesData<ForumSidebarQueryData>({ queryKey: sidebarKey })
+ .some(([, data]) => hasForumSidebarThread(data, event.channelId))
+ const sidebarChannelId = hasChildSidebarRow ? event.channelId : railChannelId
+ // Suppress the dot for the channel the viewer is actually looking at
+ // (its unread clears on read anyway) — compare against the ROW being
+ // lit, so a thread bump whose parent is open still suppresses.
+ if (event.userId === viewerId && sidebarChannelId !== sub.channelId) {
+ // Channel-tree dot: patch the RIGHT server's detail. `serverId`
+ // (inbox-dot-ws-driven) lets an other-server message light its dot
+ // — previously only the open server was patched, so cross-server
+ // bumps never lit. Absent serverId (DM bump / older frame) → fall
+ // back to the currently-open server (backward-compatible).
+ if (hasChildSidebarRow && sidebarKey) {
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: sidebarKey },
+ (data) => patchForumSidebarUnread(data, event.channelId, true),
+ )
+ recordForumSidebarChildUnread(
+ queryClient,
+ targetServerId!,
+ railChannelId,
+ event.channelId,
+ true,
+ )
+ } else if (targetServerId) {
+ if (event.channelId !== railChannelId) {
+ recordForumSidebarChildUnread(
+ queryClient,
+ targetServerId,
+ railChannelId,
+ event.channelId,
+ )
+ } else {
+ const hasChildFallback = setForumSidebarParentUnreadBase(
+ queryClient,
+ targetServerId,
+ railChannelId,
+ true,
+ )
+ if (!hasChildFallback) {
+ queryClient.setQueryData<ServerDetail | undefined>(
+ communityKeys.server(targetServerId),
+ (cache) => patchChannelUnread(cache, railChannelId, true),
+ )
+ }
+ }
+ }
+ // Rail mention badge: the rail row carries only a `mentions` count
+ // (no separate unread dot — plain unread lives on the tree dot
+ // above). So bump the rail badge ONLY for a mention, on the right
+ // server row. Needs `serverId`; a DM/older frame without it can't
+ // locate a rail row, so skip (the tree dot / inbox still reflect it).
+ if (event.isMention && event.serverId) {
+ const bumpServerId = event.serverId
+ queryClient.setQueryData<ServersResponse | undefined>(
+ communityKeys.servers(),
+ (prev) =>
+ prev
+ ? {
+ ...prev,
+ servers: prev.servers.map((s) =>
+ s.id === bumpServerId
+ ? { ...s, mentions: s.mentions + 1 }
+ : s,
+ ),
+ }
+ : prev,
+ )
+ }
+ }
+}
+
+type FriendEvent =
+ | CommunityFriendRequest
+ | CommunityFriendAccept
+ | CommunityFriendReject
+ | CommunityFriendRemove
+ | CommunityFriendBlock
+
+export function handleFriendEvent(
+ _event: FriendEvent,
+ { queryClient }: SocialEventContext,
+) {
+ void queryClient.invalidateQueries({ queryKey: communityKeys.friends() })
+}
+
+export function handleMentionCreate(
+ _event: CommunityMentionCreate,
+ { queryClient }: SocialEventContext,
+) {
+ void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
+ // The server rail badge counts unread mentions per server; refresh
+ // it on every new mention. `exact: true` is essential: the mention
+ // count lives in the `servers()` LIST query, but members/presence/
+ // invites/audit-log/server(id) are all nested UNDER `servers()` in
+ // the key hierarchy — a non-exact invalidate prefix-matches and
+ // force-refetches that whole subtree (and invalidate overrides the
+ // staleTime: Infinity those carry). With an active bot in the server,
+ // every mention.create would otherwise storm-refetch all of them.
+ void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })
+}
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts
new file mode 100644
index 000000000..a8ac41a7d
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts
@@ -0,0 +1,464 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import type {
+ CommunityChannelCreate,
+ CommunityChannelDelete,
+ CommunityChildChannelCreate,
+ CommunityChildChannelUpdate,
+ CommunityServerDelete,
+ CommunityServerUpdate,
+} from "@alook/shared"
+import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ capturedOnMessage,
+ capturedQueryClient,
+ cleanupCommunityWsHarness,
+ forumSidebarFixture,
+ messageCreate,
+ mountHook,
+ resetCommunityWsHarness,
+ resetHookMemoization,
+} from "./test-harness"
+
+beforeEach(resetCommunityWsHarness)
+afterEach(cleanupCommunityWsHarness)
+
+describe("useCommunityWs — server.update patches server + list caches", () => {
+ it("applies name change to server(id) and servers()", async () => {
+ await mountHook()
+ capturedQueryClient.setQueryData(communityKeys.server("srv_1"), {
+ id: "srv_1",
+ name: "old",
+ description: "d",
+ icon: null,
+ ownerId: "u_1",
+ categories: [],
+ })
+ capturedQueryClient.setQueryData(communityKeys.servers(), {
+ servers: [
+ {
+ id: "srv_1",
+ name: "old",
+ initial: "O",
+ active: false,
+ unread: false,
+ mentions: 0,
+ },
+ ],
+ })
+ const event: CommunityServerUpdate = {
+ type: "community:server.update",
+ serverId: "srv_1",
+ changes: { name: "new" },
+ }
+ capturedOnMessage!(event)
+ expect(capturedQueryClient.getQueryData<{ name: string }>(communityKeys.server("srv_1"))).toMatchObject({
+ name: "new",
+ })
+ expect(
+ capturedQueryClient.getQueryData<{ servers: { name: string; initial: string }[] }>(
+ communityKeys.servers(),
+ )?.servers[0],
+ ).toMatchObject({ name: "new", initial: "N" })
+ })
+})
+describe("useCommunityWs — child channel events", () => {
+ it("child_create without a parentMessageId only invalidates threads", async () => {
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const event: CommunityChildChannelCreate = {
+ type: "community:channel.child_create",
+ parentChannelId: "ch_1",
+ channel: {
+ id: "ch_thread",
+ name: "t",
+ type: "thread",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ },
+ }
+ capturedOnMessage!(event)
+ const keys = spy.mock.calls.map((c) => c[0]?.queryKey as unknown[])
+ expect(keys.some((k) => k?.includes("threads"))).toBe(true)
+ expect(keys.some((k) => k?.includes("forum-threads"))).toBe(false)
+ expect(keys).not.toContainEqual(communityKeys.channelMessages("ch_1"))
+ })
+})
+
+describe("useCommunityWs — channel.* invalidates server(id)", () => {
+ it("channel.create invalidates server(serverId)", async () => {
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const event: CommunityChannelCreate = {
+ type: "community:channel.create",
+ serverId: "srv_1",
+ channel: {
+ id: "ch_new",
+ name: "n",
+ type: "text",
+ position: 0,
+ createdAt: "2026-07-03T00:00:00.000Z",
+ },
+ }
+ capturedOnMessage!(event)
+ expect(
+ spy.mock.calls.some((c) => {
+ const key = c[0]?.queryKey as unknown[] | undefined
+ return Array.isArray(key) && key.includes("srv_1")
+ }),
+ ).toBe(true)
+ })
+})
+
+describe("useCommunityWs — invite.create", () => {
+ it("invalidates only the matching server invite query", async () => {
+ await mountHook()
+ const matchingKey = communityKeys.invites("srv_1")
+ const otherKey = communityKeys.invites("srv_2")
+ capturedQueryClient.setQueryData(matchingKey, { invites: [] })
+ capturedQueryClient.setQueryData(otherKey, { invites: [] })
+
+ capturedOnMessage!({
+ type: "community:invite.create",
+ serverId: "srv_1",
+ invite: {
+ id: "invite_1",
+ token: "token_1",
+ createdAt: "2026-08-08T00:00:00.000Z",
+ },
+ })
+
+ expect(capturedQueryClient.getQueryState(matchingKey)?.isInvalidated).toBe(true)
+ expect(capturedQueryClient.getQueryState(otherKey)?.isInvalidated).toBe(false)
+ })
+})
+
+describe("useCommunityWs — channel.delete evicts channel-scoped caches", () => {
+ it("removes channelMessages, pins, and threads for the deleted channel", async () => {
+ await mountHook()
+ // Seed every canonical cache for the target channel so we can observe eviction.
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_dead"), {
+ pages: [{ messages: [{ id: "m_1" }], hasMore: false }],
+ pageParams: [null],
+ })
+ capturedQueryClient.setQueryData(communityKeys.pins("ch_dead"), { pins: [{ id: "p" }] })
+ capturedQueryClient.setQueryData(communityKeys.threads("ch_dead"), { threads: [{ id: "t" }] })
+ const sidebarKey = communityKeys.forumSidebarThreadsView("srv_1", null)
+ capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture(["ch_dead"]))
+
+ const event: CommunityChannelDelete = {
+ type: "community:channel.delete",
+ serverId: "srv_1",
+ channelId: "ch_dead",
+ }
+ capturedOnMessage!(event)
+
+ expect(capturedQueryClient.getQueryData(communityKeys.channelMessages("ch_dead"))).toBeUndefined()
+ expect(capturedQueryClient.getQueryData(communityKeys.pins("ch_dead"))).toBeUndefined()
+ expect(capturedQueryClient.getQueryData(communityKeys.threads("ch_dead"))).toBeUndefined()
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(sidebarKey)?.threads).toEqual([])
+ })
+})
+
+describe("useCommunityWs — child_create patches parent thread badge with count 0", () => {
+ it("message.create then child_create patches the opener into a forum card", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_parent" })
+ resetHookMemoization()
+ await mountHook()
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_parent"), {
+ pages: [{ messages: [], hasMore: false }],
+ pageParams: [null],
+ })
+ capturedOnMessage!(messageCreate("ch_parent", "m_parent"))
+
+ const event: CommunityChildChannelCreate = {
+ type: "community:channel.child_create",
+ parentChannelId: "ch_parent",
+ parentMessageId: "m_parent",
+ channel: {
+ id: "ch_thread",
+ name: "New thread",
+ type: "thread",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ },
+ }
+ capturedOnMessage!(event)
+
+ const cache = capturedQueryClient.getQueryData<{
+ pages: { messages: { id: string; thread?: { id: string; name: string; messageCount: number } }[] }[]
+ }>(communityKeys.channelMessages("ch_parent"))
+ expect(cache?.pages[0].messages).toEqual([])
+ const overlay = getMessageOverlay({ kind: "channel", id: "ch_parent", serverId: "s1" })
+ expect(overlay.liveById.get("m_parent")?.thread).toEqual({
+ id: "ch_thread",
+ name: "New thread",
+ messageCount: 0,
+ })
+ })
+
+ it("child_create then message.create invalidates and preserves the enriched forum card", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_parent" })
+ resetHookMemoization()
+ await mountHook()
+ const parentMessagesKey = communityKeys.channelMessages("ch_parent")
+ capturedQueryClient.setQueryData(parentMessagesKey, {
+ pages: [{ messages: [], hasMore: false }],
+ pageParams: [null],
+ })
+ const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const event: CommunityChildChannelCreate = {
+ type: "community:channel.child_create",
+ parentChannelId: "ch_parent",
+ parentMessageId: "m_parent",
+ channel: {
+ id: "ch_thread",
+ name: "New thread",
+ type: "thread",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ },
+ }
+
+ capturedOnMessage!(event)
+ expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: parentMessagesKey })
+
+ capturedQueryClient.setQueryData(parentMessagesKey, {
+ pages: [{
+ messages: [{
+ id: "m_parent",
+ content: "hello",
+ thread: { id: "ch_thread", name: "New thread", messageCount: 0 },
+ }],
+ hasMore: false,
+ }],
+ pageParams: [null],
+ })
+ capturedOnMessage!(messageCreate("ch_parent", "m_parent"))
+
+ const cache = capturedQueryClient.getQueryData<{
+ pages: { messages: { id: string; thread?: { id: string } }[] }[]
+ }>(parentMessagesKey)
+ expect(cache?.pages[0].messages).toHaveLength(1)
+ expect(cache?.pages[0].messages[0].thread?.id).toBe("ch_thread")
+ })
+
+ it("child_update still applies the reported messageCount unchanged", async () => {
+ await mountHook()
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_parent"), {
+ pages: [
+ {
+ messages: [
+ {
+ id: "m_parent",
+ content: "hello",
+ thread: { id: "ch_thread", name: "old", messageCount: 0 },
+ },
+ ],
+ hasMore: false,
+ },
+ ],
+ pageParams: [null],
+ })
+
+ const event: CommunityChildChannelUpdate = {
+ type: "community:channel.child_update",
+ parentChannelId: "ch_parent",
+ channelId: "ch_thread",
+ changes: { messageCount: 5 },
+ }
+ capturedOnMessage!(event)
+
+ const cache = capturedQueryClient.getQueryData<{
+ pages: { messages: { thread?: { messageCount: number } }[] }[]
+ }>(communityKeys.channelMessages("ch_parent"))
+ expect(cache?.pages[0].messages[0].thread?.messageCount).toBe(5)
+ })
+
+ it("child_update removes archived sidebar rows and invalidates on reopen", async () => {
+ await mountHook()
+ const key = communityKeys.forumSidebarThreadsView("s1", null)
+ capturedQueryClient.setQueryData(key, forumSidebarFixture(["ch_thread"]))
+
+ capturedOnMessage!({
+ type: "community:channel.child_update",
+ parentChannelId: "forum_1",
+ channelId: "ch_thread",
+ changes: { archived: true },
+ } satisfies CommunityChildChannelUpdate)
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)?.threads).toEqual([])
+
+ capturedOnMessage!({
+ type: "community:channel.child_update",
+ parentChannelId: "forum_1",
+ channelId: "ch_thread",
+ changes: { archived: false },
+ } satisfies CommunityChildChannelUpdate)
+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
+ })
+
+ it("child_update keeps newer thread fields from the current base row when refreshing fallback", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("s1")
+ const scope = { kind: "channel" as const, id: "ch_parent", serverId: "s1" }
+ useMessageStreamStore.getState().dispatch(scope, {
+ type: "wsMessage",
+ message: {
+ id: "m_parent",
+ seq: 1,
+ type: "chat",
+ authorId: "u1",
+ authorName: "Alice",
+ content: "hello",
+ createdAt: "2026-08-06T00:00:00.000Z",
+ thread: {
+ id: "ch_thread",
+ name: "fallback",
+ messageCount: 1,
+ lastReplyAt: "2026-08-06T00:00:01.000Z",
+ },
+ },
+ })
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_parent"), {
+ pages: [{
+ messages: [{
+ id: "m_parent",
+ seq: 1,
+ type: "chat",
+ authorId: "u1",
+ authorName: "Alice",
+ content: "hello",
+ createdAt: "2026-08-06T00:00:00.000Z",
+ thread: {
+ id: "ch_thread",
+ name: "base",
+ messageCount: 2,
+ lastReplyAt: "2026-08-06T00:00:02.000Z",
+ },
+ }],
+ hasMore: false,
+ }],
+ pageParams: [null],
+ })
+
+ capturedOnMessage!({
+ type: "community:channel.child_update",
+ parentChannelId: "ch_parent",
+ channelId: "ch_thread",
+ changes: { messageCount: 5 },
+ } satisfies CommunityChildChannelUpdate)
+
+ expect(getMessageOverlay(scope).liveById.get("m_parent")?.thread).toEqual({
+ id: "ch_thread",
+ name: "base",
+ messageCount: 5,
+ lastReplyAt: "2026-08-06T00:00:02.000Z",
+ })
+ })
+})
+
+describe("useCommunityWs — channel.delete refreshes the parent forum feed", () => {
+ it("invalidates the parent's message feed + threads list when parentChannelId is present", async () => {
+ await mountHook()
+ const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const allKey = communityKeys.channelMessages("forum_1")
+ const bugKey = [...allKey, "tag", "bug"] as const
+ const page = {
+ pages: [{ messages: [{ id: "opener_1", thread: { id: "post_1" } }], hasMore: false }],
+ pageParams: [null],
+ }
+ capturedQueryClient.setQueryData(allKey, page)
+ capturedQueryClient.setQueryData(bugKey, page)
+
+ const event: CommunityChannelDelete = {
+ type: "community:channel.delete",
+ serverId: "srv_1",
+ channelId: "post_1",
+ parentChannelId: "forum_1",
+ }
+ capturedOnMessage!(event)
+
+ const invalidatedKeys = invalidateSpy.mock.calls.map((c) => JSON.stringify(c[0]?.queryKey))
+ expect(invalidatedKeys).toContain(JSON.stringify(communityKeys.channelMessages("forum_1")))
+ expect(invalidatedKeys).toContain(JSON.stringify(communityKeys.threads("forum_1")))
+ expect(capturedQueryClient.getQueryData<{ pages: { messages: unknown[] }[] }>(allKey)?.pages[0].messages).toHaveLength(0)
+ expect(capturedQueryClient.getQueryData<{ pages: { messages: unknown[] }[] }>(bugKey)?.pages[0].messages).toHaveLength(0)
+ })
+
+ it("does not throw and still evicts own caches when parentChannelId is absent (legacy event)", async () => {
+ await mountHook()
+ // Seed the deleted channel's own message cache so we can assert eviction.
+ capturedQueryClient.setQueryData(communityKeys.channelMessages("post_1"), { pages: [], pageParams: [] })
+ const removeSpy = vi.spyOn(capturedQueryClient, "removeQueries")
+
+ const event: CommunityChannelDelete = {
+ type: "community:channel.delete",
+ serverId: "srv_1",
+ channelId: "post_1",
+ }
+ expect(() => capturedOnMessage!(event)).not.toThrow()
+
+ const removedKeys = removeSpy.mock.calls.map((c) => JSON.stringify(c[0]?.queryKey))
+ expect(removedKeys).toContain(JSON.stringify(communityKeys.channelMessages("post_1")))
+ })
+})
+
+describe("useCommunityWs — server.update icon removal", () => {
+ it("clears icon when changes.icon is null (does not fall back to the prior icon)", async () => {
+ await mountHook()
+ capturedQueryClient.setQueryData(communityKeys.server("srv_1"), {
+ id: "srv_1",
+ name: "n",
+ description: "d",
+ icon: "https://cdn/x.png",
+ ownerId: "u_1",
+ categories: [],
+ })
+ const event: CommunityServerUpdate = {
+ type: "community:server.update",
+ serverId: "srv_1",
+ changes: { icon: null },
+ }
+ capturedOnMessage!(event)
+ const detail = capturedQueryClient.getQueryData<{ icon: string | null }>(
+ communityKeys.server("srv_1"),
+ )
+ expect(detail?.icon).toBeNull()
+ })
+})
+
+describe("useCommunityWs — server.delete resets store when focused server dies", () => {
+ it("clears currentServerId + currentChannelId if the deleted server is currently focused", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_doomed")
+ useCommunityStore.getState().setCurrentChannelId("ch_1")
+
+ const event: CommunityServerDelete = {
+ type: "community:server.delete",
+ serverId: "srv_doomed",
+ }
+ capturedOnMessage!(event)
+
+ expect(useCommunityStore.getState().currentServerId).toBeNull()
+ expect(useCommunityStore.getState().currentChannelId).toBeNull()
+ })
+
+ it("does NOT touch the store when a different server is deleted", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_active")
+ useCommunityStore.getState().setCurrentChannelId("ch_1")
+
+ const event: CommunityServerDelete = {
+ type: "community:server.delete",
+ serverId: "srv_other",
+ }
+ capturedOnMessage!(event)
+
+ expect(useCommunityStore.getState().currentServerId).toBe("srv_active")
+ expect(useCommunityStore.getState().currentChannelId).toBe("ch_1")
+ })
+})
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.ts
new file mode 100644
index 000000000..96718a3f8
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.ts
@@ -0,0 +1,343 @@
+import type {
+ CommunityCategoryCreate,
+ CommunityCategoryDelete,
+ CommunityCategoryReorder,
+ CommunityCategoryUpdate,
+ CommunityChannelCreate,
+ CommunityChannelDelete,
+ CommunityChannelReorder,
+ CommunityChannelUpdate,
+ CommunityChildChannelCreate,
+ CommunityChildChannelUpdate,
+ CommunityInviteCreate,
+ CommunityServerDelete,
+ CommunityServerUpdate,
+} from "@alook/shared"
+import { communityKeys } from "@/lib/query-keys"
+import { avatarInitial } from "@/lib/community/avatar"
+import type { CanonicalMessage } from "@/lib/community/message-stream"
+import { useCommunityStore } from "@/stores/community"
+import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
+import type { ServersResponse, ServerDetail } from "@/hooks/community/use-servers"
+import {
+ patchForumSidebarActivity,
+ removeForumSidebarThread,
+ removeForumSidebarUnreadChild,
+ type ForumSidebarQueryData,
+} from "@/hooks/community/use-forum-sidebar-threads"
+import {
+ findCachedMessage,
+ removeThreadFromCache,
+ type PageCache,
+} from "@/hooks/community/community-ws/cache"
+import type { StructureTreeEventContext } from "@/hooks/community/community-ws/handler-context"
+
+export function handleChildChannelCreate(
+ event: CommunityChildChannelCreate,
+ { queryClient }: StructureTreeEventContext,
+) {
+ // Cheap invalidate for the child-thread lists. The parent
+ // messages list also needs an update because the parent message's
+ // thread indicator (`msg.thread`) changes — do a targeted
+ // setQueryData patch when we know parentMessageId.
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.threads(event.parentChannelId),
+ })
+ const parentMessagesKey = communityKeys.channelMessages(event.parentChannelId)
+ const parentMessages = queryClient.getQueryData<PageCache>(parentMessagesKey)
+ const openerCached = !!event.parentMessageId && parentMessages?.pages.some((page) =>
+ page.messages.some((message) => message.id === event.parentMessageId),
+ )
+ if (event.parentMessageId) {
+ queryClient.setQueriesData<PageCache>(
+ { queryKey: parentMessagesKey },
+ (cache) => {
+ if (!cache) return cache
+ let touched = false
+ const pages = cache.pages.map((p) => {
+ if (!p.messages.some((m) => m.id === event.parentMessageId)) return p
+ touched = true
+ return {
+ ...p,
+ messages: p.messages.map((m) =>
+ m.id === event.parentMessageId
+ ? {
+ ...m,
+ thread: {
+ id: event.channel.id,
+ name: event.channel.name,
+ // #4: a freshly-created child channel has no
+ // messages yet — `1` was a false claim that
+ // the create event carried the first message
+ // (it doesn't; the message arrives separately).
+ messageCount: 0,
+ },
+ }
+ : m,
+ ),
+ }
+ })
+ if (!touched) return cache
+ return { ...cache, pages }
+ },
+ )
+ const serverId = useCommunityStore.getState().currentServerId
+ if (serverId) {
+ const scope = { kind: "channel" as const, id: event.parentChannelId, serverId }
+ const fallback = [...getMessageOverlay(scope).liveById.values()]
+ .find((message) => message.id === event.parentMessageId)
+ if (fallback) {
+ const cached = findCachedMessage(
+ queryClient.getQueryData<PageCache>(communityKeys.channelMessages(event.parentChannelId)),
+ event.parentMessageId,
+ )
+ const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback
+ useMessageStreamStore.getState().dispatch(scope, {
+ type: "liveRefreshed",
+ message: {
+ ...source,
+ thread: { id: event.channel.id, name: event.channel.name, messageCount: 0 },
+ },
+ })
+ }
+ }
+ }
+ if (event.parentMessageId && !openerCached) {
+ void queryClient.invalidateQueries({ queryKey: parentMessagesKey })
+ }
+}
+
+export function handleChildChannelUpdate(
+ event: CommunityChildChannelUpdate,
+ { queryClient }: StructureTreeEventContext,
+) {
+ // Cheap invalidate for the child-thread lists. The parent
+ // messages list also needs an update because the parent message's
+ // thread indicator (`msg.thread`) changes — do a targeted
+ // setQueryData patch when we know parentMessageId.
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.threads(event.parentChannelId),
+ })
+ // child_update — sync counts/name on the parent message's thread
+ // indicator if the update carries them.
+ const changes = event.changes
+ const sidebarServerId = useCommunityStore.getState().currentServerId
+ if (sidebarServerId) {
+ const sidebarKey = communityKeys.forumSidebarThreads(sidebarServerId)
+ if (changes.archived === true) {
+ removeForumSidebarUnreadChild(queryClient, sidebarServerId, event.channelId)
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: sidebarKey },
+ (data) => removeForumSidebarThread(data, event.channelId),
+ )
+ } else if (changes.archived === false) {
+ void queryClient.invalidateQueries({ queryKey: sidebarKey })
+ } else if (changes.lastMessageAt) {
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: sidebarKey },
+ (data) => patchForumSidebarActivity(
+ data,
+ event.channelId,
+ event.parentChannelId,
+ changes.lastMessageAt!,
+ ),
+ )
+ }
+ }
+ if (changes.messageCount !== undefined || changes.name !== undefined) {
+ queryClient.setQueriesData<PageCache>(
+ { queryKey: communityKeys.channelMessages(event.parentChannelId) },
+ (cache) => {
+ if (!cache) return cache
+ let touched = false
+ const pages = cache.pages.map((p) => {
+ if (!p.messages.some((m) => m.thread?.id === event.channelId)) return p
+ touched = true
+ return {
+ ...p,
+ messages: p.messages.map((m) =>
+ m.thread?.id === event.channelId
+ ? {
+ ...m,
+ thread: {
+ ...m.thread,
+ ...(changes.name !== undefined ? { name: changes.name } : {}),
+ ...(changes.messageCount !== undefined
+ ? { messageCount: changes.messageCount }
+ : {}),
+ },
+ }
+ : m,
+ ),
+ }
+ })
+ if (!touched) return cache
+ return { ...cache, pages }
+ },
+ )
+ const serverId = useCommunityStore.getState().currentServerId
+ if (serverId) {
+ const scope = { kind: "channel" as const, id: event.parentChannelId, serverId }
+ const fallback = [...getMessageOverlay(scope).liveById.values()]
+ .find((message) => message.thread?.id === event.channelId)
+ if (fallback?.thread) {
+ const cached = findCachedMessage(
+ queryClient.getQueryData<PageCache>(communityKeys.channelMessages(event.parentChannelId)),
+ fallback.id,
+ )
+ const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback
+ useMessageStreamStore.getState().dispatch(scope, {
+ type: "liveRefreshed",
+ message: {
+ ...source,
+ thread: {
+ ...(source.thread ?? fallback.thread),
+ ...(changes.name !== undefined ? { name: changes.name } : {}),
+ ...(changes.messageCount !== undefined ? { messageCount: changes.messageCount } : {}),
+ },
+ },
+ })
+ }
+ }
+ }
+}
+
+export function handleServerUpdate(
+ event: CommunityServerUpdate,
+ { queryClient }: StructureTreeEventContext,
+) {
+ queryClient.setQueryData<ServerDetail | undefined>(
+ communityKeys.server(event.serverId),
+ (prev) =>
+ prev
+ ? {
+ ...prev,
+ name: event.changes.name ?? prev.name,
+ description: event.changes.description ?? prev.description,
+ // #8: icon can be explicitly cleared (null). `??` treats
+ // null the same as undefined, which would keep the old
+ // icon after a removal — check `undefined` explicitly.
+ icon:
+ event.changes.icon !== undefined
+ ? event.changes.icon
+ : prev.icon,
+ }
+ : prev,
+ )
+ queryClient.setQueryData<ServersResponse | undefined>(
+ communityKeys.servers(),
+ (prev) =>
+ prev
+ ? {
+ ...prev,
+ servers: prev.servers.map((s) =>
+ s.id === event.serverId
+ ? {
+ ...s,
+ ...(event.changes.name ? { name: event.changes.name, initial: avatarInitial(event.changes.name) } : {}),
+ ...(event.changes.icon !== undefined ? { icon: event.changes.icon ?? null } : {}),
+ }
+ : s,
+ ),
+ }
+ : prev,
+ )
+}
+
+export function handleServerDelete(
+ event: CommunityServerDelete,
+ { queryClient }: StructureTreeEventContext,
+) {
+ // Refresh the rail LIST only (drop the deleted server). `exact`
+ // so this doesn't cascade-refetch every other server's nested
+ // detail subtree; the deleted server's own subtree is cleared by
+ // the removeQueries below.
+ void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })
+ queryClient.removeQueries({ queryKey: communityKeys.server(event.serverId) })
+ // #10: if the deleted server is the one the viewer is looking at,
+ // the store pointers now dangle — reset them so the UI drops back
+ // to a safe default instead of rendering a ghost server/channel.
+ const store = useCommunityStore.getState()
+ useMessageStreamStore.getState().removeServer(event.serverId)
+ if (store.currentServerId === event.serverId) {
+ store.setCurrentServerId(null)
+ store.setCurrentChannelId(null)
+ }
+}
+
+type ChannelEvent =
+ | CommunityChannelCreate
+ | CommunityChannelUpdate
+ | CommunityChannelDelete
+ | CommunityChannelReorder
+
+export function handleChannelEvent(
+ event: ChannelEvent,
+ { queryClient }: StructureTreeEventContext,
+) {
+ // #3: on channel.delete, evict every channel-scoped cache before
+ // invalidating the server. Without this the messages/pins/threads/
+ // child-thread caches for the dead channel linger forever — a
+ // subsequent same-id revive (rare, but the server can reuse ids)
+ // would surface stale rows.
+ if (event.type === "community:channel.delete") {
+ removeForumSidebarUnreadChild(queryClient, event.serverId, event.channelId)
+ useMessageStreamStore.getState().removeScope({
+ kind: "channel",
+ id: event.channelId,
+ serverId: event.serverId,
+ })
+ queryClient.removeQueries({
+ queryKey: communityKeys.channelMessages(event.channelId),
+ })
+ queryClient.removeQueries({
+ queryKey: communityKeys.pins(event.channelId),
+ })
+ queryClient.removeQueries({
+ queryKey: communityKeys.threads(event.channelId),
+ })
+ queryClient.setQueriesData<ForumSidebarQueryData>(
+ { queryKey: communityKeys.forumSidebarThreads(event.serverId) },
+ (data) => removeForumSidebarThread(data, event.channelId),
+ )
+ // When a child thread is deleted, refresh the
+ // PARENT's list so the deleted card disappears from the feed on
+ // every client. Absent on older events / top-level channels.
+ if (event.parentChannelId) {
+ queryClient.setQueriesData<PageCache>(
+ { queryKey: communityKeys.channelMessages(event.parentChannelId) },
+ (cache) => removeThreadFromCache(cache, event.channelId),
+ )
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.channelMessages(event.parentChannelId),
+ })
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.threads(event.parentChannelId),
+ })
+ }
+ }
+ void queryClient.invalidateQueries({ queryKey: communityKeys.server(event.serverId) })
+}
+
+type CategoryEvent =
+ | CommunityCategoryCreate
+ | CommunityCategoryUpdate
+ | CommunityCategoryDelete
+ | CommunityCategoryReorder
+
+export function handleCategoryEvent(
+ event: CategoryEvent,
+ { queryClient }: StructureTreeEventContext,
+) {
+ void queryClient.invalidateQueries({ queryKey: communityKeys.server(event.serverId) })
+}
+
+export function handleInviteCreate(
+ event: CommunityInviteCreate,
+ { queryClient }: StructureTreeEventContext,
+) {
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.invites(event.serverId),
+ exact: true,
+ })
+}
diff --git a/src/web/src/hooks/community/community-ws/test-harness.ts b/src/web/src/hooks/community/community-ws/test-harness.ts
new file mode 100644
index 000000000..411192df3
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/test-harness.ts
@@ -0,0 +1,188 @@
+import { QueryClient } from "@tanstack/react-query"
+import type { CommunityMessageCreate } from "@alook/shared"
+import { vi } from "vitest"
+import type { UseUserWsOptions } from "@/lib/use-user-ws"
+import { useMessageStreamStore } from "@/stores/community/message-stream"
+
+type ShimCallback = (...args: unknown[]) => unknown
+
+let refs: Map<string, { current: unknown }> = new Map()
+let refCounter = 0
+let callbackMemo: Map<string, { fn: ShimCallback; deps: unknown[] }> = new Map()
+let callbackCounter = 0
+let pendingEffects: Array<() => void | (() => void)> = []
+let effectCleanups: Array<() => void> = []
+
+vi.mock("react", () => ({
+ useRef: (initial: unknown) => {
+ const id = `ref-${refCounter++}`
+ if (!refs.has(id)) refs.set(id, { current: initial })
+ return refs.get(id)!
+ },
+ useState: (initial: unknown) => [initial, () => { }],
+ useCallback: (fn: ShimCallback, deps: unknown[]) => {
+ const id = `cb-${callbackCounter++}`
+ const existing = callbackMemo.get(id)
+ if (existing && JSON.stringify(existing.deps) === JSON.stringify(deps)) {
+ return existing.fn
+ }
+ callbackMemo.set(id, { fn, deps })
+ return fn
+ },
+ useEffect: (fn: () => void | (() => void), _deps: unknown[]) => {
+ pendingEffects.push(fn)
+ },
+}))
+
+export function flushEffects() {
+ const effects = pendingEffects
+ pendingEffects = []
+ for (const fn of effects) {
+ const cleanup = fn()
+ if (typeof cleanup === "function") effectCleanups.push(cleanup)
+ }
+}
+
+export let capturedQueryClient: QueryClient
+vi.mock("@tanstack/react-query", async () => {
+ const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")
+ return {
+ ...actual,
+ useQueryClient: () => capturedQueryClient,
+ }
+})
+
+export let capturedOnMessage: ((msg: unknown) => void) | null = null
+export let capturedOnReconnect: (() => void) | null = null
+export let capturedUseUserWsOptions: UseUserWsOptions | undefined
+let stableSend: ReturnType<typeof vi.fn> = vi.fn()
+export let useUserWsCallCount = 0
+vi.mock("@/lib/use-user-ws", () => ({
+ useUserWs: (onMessage: (msg: unknown) => void, options?: UseUserWsOptions) => {
+ useUserWsCallCount += 1
+ capturedOnMessage = onMessage
+ capturedOnReconnect = options?.onReconnect ?? null
+ capturedUseUserWsOptions = options
+ return { send: stableSend }
+ },
+}))
+
+export const markReadMutate = vi.fn()
+vi.mock("@/hooks/community/mutations/messages", () => ({
+ useMarkChannelRead: () => ({ mutate: markReadMutate }),
+ flushPendingReads: () => { },
+}))
+
+export function resetHookMemoization() {
+ refCounter = 0
+ callbackCounter = 0
+}
+
+export function resetHookInstance() {
+ refs = new Map()
+ callbackMemo = new Map()
+ resetHookMemoization()
+}
+
+export function setStableSend(send: ReturnType<typeof vi.fn>) {
+ stableSend = send
+}
+
+export function getStableSend() {
+ return stableSend
+}
+
+function resetHarnessState() {
+ resetHookInstance()
+ pendingEffects = []
+ effectCleanups = []
+ capturedOnMessage = null
+ capturedOnReconnect = null
+ capturedUseUserWsOptions = undefined
+ capturedQueryClient = new QueryClient()
+ stableSend = vi.fn()
+ useUserWsCallCount = 0
+ markReadMutate.mockClear()
+}
+
+export async function mountHook(options?: { viewerUserId?: string | null } & Record<string, unknown>) {
+ const mod = await import("../use-community-ws")
+ return mod.useCommunityWs(options)
+}
+
+async function resetStore() {
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().reset()
+ useCommunityStore.getState().setCurrentServerId("s1")
+ const { useCommunityWsStore } = await import("@/stores/community/ws")
+ useCommunityWsStore.getState().reset()
+ useMessageStreamStore.getState().resetAll()
+ const mod = await import("../use-community-ws")
+ mod._resetActiveSend_forTesting()
+}
+
+export async function resetCommunityWsHarness() {
+ resetHarnessState()
+ await resetStore()
+}
+
+export async function cleanupCommunityWsHarness() {
+ flushEffects()
+ for (const cleanup of effectCleanups.splice(0).reverse()) cleanup()
+ await resetStore()
+ vi.clearAllTimers()
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+ resetHarnessState()
+}
+
+export function messageCreate(channelId: string, msgId = "m_1"): CommunityMessageCreate {
+ return {
+ type: "community:message.create",
+ channelId,
+ message: {
+ id: msgId,
+ type: "chat",
+ authorId: "u_author",
+ authorName: "author",
+ content: "hi",
+ seq: 1,
+ createdAt: "2026-07-03T00:00:00.000Z",
+ },
+ }
+}
+
+export function unreadBump(
+ channelId: string,
+ userId: string,
+ extra?: { serverId?: string; railChannelId?: string; isMention?: boolean },
+) {
+ return { type: "community:unread.bump" as const, userId, channelId, ...extra }
+}
+
+export function forumSidebarFixture(ids = ["post_1"]) {
+ return {
+ channels: ids.map((id) => ({
+ id,
+ name: `fallback-${id}`,
+ parentChannelId: "forum_1",
+ parentMessageId: `opener-${id}`,
+ activityAt: "2026-08-01T00:00:00.000Z",
+ expiresAt: "2026-08-04T00:00:00.000Z",
+ unread: false,
+ })),
+ included: { parentMessages: ids.map((id) => ({ id: `opener-${id}`, content: `title-${id}` })) },
+ serverNow: "2026-08-01T00:00:00.000Z",
+ serverClockOffsetMs: 0,
+ threads: ids.map((id) => ({
+ id,
+ parentChannelId: "forum_1",
+ parentMessageId: `opener-${id}`,
+ title: `title-${id}`,
+ activityAt: "2026-08-01T00:00:00.000Z",
+ expiresAt: "2026-08-04T00:00:00.000Z",
+ unread: false,
+ })),
+ }
+}
diff --git a/src/web/src/hooks/community/community-ws/typing-events.test.ts b/src/web/src/hooks/community/community-ws/typing-events.test.ts
new file mode 100644
index 000000000..9f63c8d92
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/typing-events.test.ts
@@ -0,0 +1,145 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import type { CommunityMessageCreate, CommunityTypingStart } from "@alook/shared"
+import {
+ capturedOnMessage,
+ cleanupCommunityWsHarness,
+ mountHook,
+ resetCommunityWsHarness,
+ resetHookMemoization,
+} from "./test-harness"
+
+beforeEach(resetCommunityWsHarness)
+afterEach(cleanupCommunityWsHarness)
+
+describe("useCommunityWs — typing.start honours focus (no DM leak)", () => {
+ it("does NOT surface a DM-only typing.start when the viewer is focused on a channel", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })
+ resetHookMemoization()
+ await mountHook()
+
+ const event: CommunityTypingStart = {
+ type: "community:typing.start",
+ channelId: "dm_other",
+ userId: "u_other",
+ }
+ capturedOnMessage!(event)
+
+ // Focus is on ch_1, so the unfocused DM channel's typing.start is dropped
+ // entirely — no scope gains a typer.
+ const state = useCommunityStore.getState()
+ expect(state.typingByScope.get("dm:dm_other")).toBeUndefined()
+ expect(state.typingByScope.get("ch:dm_other")).toBeUndefined()
+ expect(state.typingByScope.get("ch:ch_1")).toBeUndefined()
+ })
+
+ it("does surface a channel typing.start when the viewer is focused on that channel", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })
+ resetHookMemoization()
+ await mountHook()
+
+ const event: CommunityTypingStart = {
+ type: "community:typing.start",
+ channelId: "ch_1",
+ userId: "u_other",
+ }
+ capturedOnMessage!(event)
+
+ expect([...(useCommunityStore.getState().typingByScope.get("ch:ch_1")?.keys() ?? [])]).toEqual([
+ "u_other",
+ ])
+ })
+
+ it("typing.stop clears the focused scope immediately", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })
+ resetHookMemoization()
+ await mountHook({ viewerUserId: "u_me" })
+
+ capturedOnMessage!({
+ type: "community:typing.start",
+ channelId: "ch_1",
+ userId: "u_other",
+ })
+ capturedOnMessage!({
+ type: "community:typing.stop",
+ channelId: "ch_1",
+ userId: "u_other",
+ })
+
+ const state = useCommunityStore.getState()
+ expect(state.typingByScope.get("ch:ch_1")).toBeUndefined()
+ expect(state.typingTimers.has("ch:ch_1|u_other")).toBe(false)
+ })
+
+})
+describe("useCommunityWs — typing state is scoped per conversation", () => {
+ it("a DM typer lands only in the DM scope, never in a channel scope", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ // Viewer is focused on the DM when the peer starts typing.
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
+ resetHookMemoization()
+ await mountHook({ viewerUserId: "u_me" })
+
+ // A DM is a channel — typing arrives as `typing.start` keyed by the DM's
+ // channel id. The scope key resolves to `dm:` because the subscription's
+ // `dmConversationId` slot holds that channel id.
+ capturedOnMessage!({
+ type: "community:typing.start",
+ channelId: "dm_1",
+ userId: "u_peer",
+ })
+
+ const state = useCommunityStore.getState()
+ // The typer is confined to dm:dm_1 — a channel view reading ch:* sees nothing.
+ expect([...(state.typingByScope.get("dm:dm_1")?.keys() ?? [])]).toEqual(["u_peer"])
+ expect(state.typingByScope.get("ch:dm_1")).toBeUndefined()
+ // The 8s timer is keyed by (scope, user), not user alone.
+ expect(state.typingTimers.has("dm:dm_1|u_peer")).toBe(true)
+ })
+
+ it("bot DM reply (message.create on a DM channel) clears the DM pill, in the dm: scope", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_bot" })
+ resetHookMemoization()
+ await mountHook({ viewerUserId: "u_me" })
+
+ // Bot is "typing" in the DM (typing.start on the DM channel).
+ capturedOnMessage!({
+ type: "community:typing.start",
+ channelId: "dm_bot",
+ userId: "u_bot",
+ })
+ expect([...(useCommunityStore.getState().typingByScope.get("dm:dm_bot")?.keys() ?? [])]).toEqual([
+ "u_bot",
+ ])
+
+ // Its reply arrives as message.create on the same DM channel. The scope key
+ // must resolve to dm:dm_bot (via the subscription), clearing the pill — not
+ // leak into a ch: bucket.
+ capturedOnMessage!({
+ type: "community:message.create",
+ channelId: "dm_bot",
+ message: {
+ id: "m_bot_reply",
+ authorId: "u_bot",
+ authorName: "bot",
+ content: "done",
+ type: "chat",
+ seq: 1,
+ createdAt: "2026-07-03T00:00:00.000Z",
+ },
+ } as CommunityMessageCreate)
+
+ const state = useCommunityStore.getState()
+ expect(state.typingByScope.get("dm:dm_bot")).toBeUndefined()
+ expect(state.typingByScope.get("ch:dm_bot")).toBeUndefined()
+ expect(state.typingTimers.has("dm:dm_bot|u_bot")).toBe(false)
+ })
+})
diff --git a/src/web/src/hooks/community/community-ws/typing-events.ts b/src/web/src/hooks/community/community-ws/typing-events.ts
new file mode 100644
index 000000000..6536b6941
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/typing-events.ts
@@ -0,0 +1,37 @@
+import type { CommunityTypingStart, CommunityWsEvent } from "@alook/shared"
+import {
+ applyTypingIndicator,
+ clearTypingIndicator,
+ typingScopeKey,
+} from "@/hooks/community/community-ws/typing"
+import type { TypingEventContext } from "@/hooks/community/community-ws/handler-context"
+
+type CommunityTypingStop = Extract<
+ CommunityWsEvent,
+ { type: "community:typing.stop" }
+>
+
+export function handleTypingStart(
+ event: CommunityTypingStart,
+ { viewerUserIdRef, matchesFocus, sub }: TypingEventContext,
+) {
+ const userId = event.userId
+ const viewerId = viewerUserIdRef.current
+ if (viewerId && userId === viewerId) return
+ // Focus check: only surface typing for the currently-viewed target.
+ if (!matchesFocus(event)) return
+ applyTypingIndicator(typingScopeKey(event, sub), userId, event.name ?? null)
+}
+
+export function handleTypingStop(
+ event: CommunityTypingStop,
+ { viewerUserIdRef, matchesFocus, sub }: TypingEventContext,
+) {
+ // Symmetric with typing.start: only clear when focused on the same
+ // target so a stop for a different DM doesn't wipe the local pill.
+ const userId = event.userId
+ const viewerId = viewerUserIdRef.current
+ if (viewerId && userId === viewerId) return
+ if (!matchesFocus(event)) return
+ clearTypingIndicator(typingScopeKey(event, sub), userId)
+}
diff --git a/src/web/src/hooks/community/community-ws/typing.test.ts b/src/web/src/hooks/community/community-ws/typing.test.ts
new file mode 100644
index 000000000..67fca510d
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/typing.test.ts
@@ -0,0 +1,80 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { TYPING_INDICATOR_TIMEOUT_MS } from "@alook/shared"
+import { useCommunityStore } from "@/stores/community"
+import {
+ applyTypingIndicator,
+ clearTypingIndicator,
+ typingScopeKey,
+} from "./typing"
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ useCommunityStore.getState().reset()
+})
+
+afterEach(() => {
+ useCommunityStore.getState().reset()
+ vi.clearAllTimers()
+ vi.useRealTimers()
+})
+
+describe("community WS typing helpers", () => {
+ it("derives DM and channel scope keys from the focused subscription", () => {
+ expect(typingScopeKey({ channelId: "dm_1" }, { dmConversationId: "dm_1" })).toBe("dm:dm_1")
+ expect(typingScopeKey({ channelId: "ch_1" }, { channelId: "ch_1" })).toBe("ch:ch_1")
+ expect(typingScopeKey({ channelId: "dm_2" }, { dmConversationId: "dm_1" })).toBe("ch:dm_2")
+ })
+
+ it("stores names and null fallback values in isolated scopes", () => {
+ applyTypingIndicator("ch:ch_1", "u_named", "Alice")
+ applyTypingIndicator("dm:dm_1", "u_legacy", null)
+
+ const state = useCommunityStore.getState()
+ expect(state.typingByScope.get("ch:ch_1")?.get("u_named")).toBe("Alice")
+ expect(state.typingByScope.get("dm:dm_1")?.get("u_legacy")).toBeNull()
+ expect(state.typingTimers.has("ch:ch_1|u_named")).toBe(true)
+ expect(state.typingTimers.has("dm:dm_1|u_legacy")).toBe(true)
+ })
+
+ it("refreshes the timer without replacing an unchanged typing map", () => {
+ applyTypingIndicator("ch:ch_1", "u_1", "Alice")
+ const typingMap = useCommunityStore.getState().typingByScope
+ vi.advanceTimersByTime(TYPING_INDICATOR_TIMEOUT_MS / 2)
+
+ applyTypingIndicator("ch:ch_1", "u_1", "Alice")
+
+ expect(useCommunityStore.getState().typingByScope).toBe(typingMap)
+ vi.advanceTimersByTime(TYPING_INDICATOR_TIMEOUT_MS - 1)
+ expect(useCommunityStore.getState().typingByScope.get("ch:ch_1")?.has("u_1")).toBe(true)
+ vi.advanceTimersByTime(1)
+ expect(useCommunityStore.getState().typingByScope.get("ch:ch_1")).toBeUndefined()
+ })
+
+ it("expires one typer without disturbing another in the same scope", () => {
+ applyTypingIndicator("ch:ch_1", "u_1", "One")
+ vi.advanceTimersByTime(1000)
+ applyTypingIndicator("ch:ch_1", "u_2", "Two")
+
+ vi.advanceTimersByTime(TYPING_INDICATOR_TIMEOUT_MS - 1000)
+
+ const state = useCommunityStore.getState()
+ expect(state.typingByScope.get("ch:ch_1")?.has("u_1")).toBe(false)
+ expect(state.typingByScope.get("ch:ch_1")?.get("u_2")).toBe("Two")
+ expect(state.typingTimers.has("ch:ch_1|u_1")).toBe(false)
+ expect(state.typingTimers.has("ch:ch_1|u_2")).toBe(true)
+ })
+
+ it("clears timers and deletes a scope only after its last typer leaves", () => {
+ applyTypingIndicator("dm:dm_1", "u_1", "One")
+ applyTypingIndicator("dm:dm_1", "u_2", "Two")
+
+ clearTypingIndicator("dm:dm_1", "u_1")
+ expect(useCommunityStore.getState().typingByScope.get("dm:dm_1")?.has("u_1")).toBe(false)
+ expect(useCommunityStore.getState().typingByScope.get("dm:dm_1")?.has("u_2")).toBe(true)
+ expect(useCommunityStore.getState().typingTimers.has("dm:dm_1|u_1")).toBe(false)
+
+ clearTypingIndicator("dm:dm_1", "u_2")
+ expect(useCommunityStore.getState().typingByScope.get("dm:dm_1")).toBeUndefined()
+ expect(useCommunityStore.getState().typingTimers.has("dm:dm_1|u_2")).toBe(false)
+ })
+})
diff --git a/src/web/src/hooks/community/community-ws/typing.ts b/src/web/src/hooks/community/community-ws/typing.ts
new file mode 100644
index 000000000..00a802a8b
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/typing.ts
@@ -0,0 +1,89 @@
+import { TYPING_INDICATOR_TIMEOUT_MS } from "@alook/shared"
+import { useCommunityStore } from "@/stores/community"
+
+/**
+ * The conversation scope key an event belongs to. Every event carries a single
+ * `channelId` now (a DM is a channel), so the `dm:` / `ch:` prefix — which the
+ * DM page (`dm:<id>`) and channel page (`ch:<id>`) read via
+ * `useTypingUsersForScope` — is derived from the subscription: if the event's
+ * channelId is the focused DM channel, it's a `dm:` scope; otherwise `ch:`.
+ * Threads collapse to `ch:<channelId>`.
+ */
+export function typingScopeKey(
+ e: { channelId: string },
+ sub: { channelId?: string; dmConversationId?: string },
+): string {
+ return e.channelId === sub.dmConversationId ? `dm:${e.channelId}` : `ch:${e.channelId}`
+}
+
+// Timer map key: one auto-expire timer per (scope, user) pair.
+const timerKey = (scopeKey: string, userId: string) => `${scopeKey}|${userId}`
+
+/**
+ * Add userId to a conversation scope's typing set and start (or extend) an
+ * auto-expire timer. The timer removes the user from THAT scope after
+ * `TYPING_INDICATOR_TIMEOUT_MS` if no follow-up typing event arrives.
+ * No-ops the set write when the user is already typing in the scope (rule 2 —
+ * typing.start re-fires every ~3s).
+ */
+export function applyTypingIndicator(scopeKey: string, userId: string, name: string | null) {
+ useCommunityStore.setState((state) => {
+ const tKey = timerKey(scopeKey, userId)
+ const existing = state.typingTimers.get(tKey)
+ if (existing) clearTimeout(existing)
+ const timer = setTimeout(() => {
+ useCommunityStore.setState((s) => removeTypingUser(s, scopeKey, userId))
+ }, TYPING_INDICATOR_TIMEOUT_MS)
+ const nextTimers = new Map(state.typingTimers)
+ nextTimers.set(tKey, timer)
+
+ const current = state.typingByScope.get(scopeKey)
+ // Already typing here with the same known name — only the timer refreshed,
+ // leave the name map alone (avoids a needless re-render). Otherwise (new
+ // typer, or a name we didn't have before) write the entry.
+ if (current?.has(userId) && current.get(userId) === name) {
+ return { typingTimers: nextTimers }
+ }
+ const nextByScope = new Map(state.typingByScope)
+ nextByScope.set(scopeKey, new Map(current ?? []).set(userId, name))
+ return { typingByScope: nextByScope, typingTimers: nextTimers }
+ })
+}
+
+/**
+ * Immediately remove userId from a scope's typing set and cancel its pending
+ * timer. Called when the user sends a message — sending is an implicit
+ * typing.stop, and waiting for the 8s timeout leaves a ghost indicator hanging
+ * under the message that just arrived.
+ */
+export function clearTypingIndicator(scopeKey: string, userId: string) {
+ useCommunityStore.setState((state) => {
+ const tKey = timerKey(scopeKey, userId)
+ const existing = state.typingTimers.get(tKey)
+ if (!existing && !state.typingByScope.get(scopeKey)?.has(userId)) return {}
+ if (existing) clearTimeout(existing)
+ return removeTypingUser(state, scopeKey, userId)
+ })
+}
+
+/**
+ * Pure state patch: drop userId from `scopeKey`'s typing map (deleting the
+ * scope key when it empties, to avoid unbounded Map growth) and its
+ * `(scope, user)` timer. Shared by the auto-expire timer and the explicit clear.
+ */
+function removeTypingUser(
+ state: { typingByScope: Map<string, Map<string, string | null>>; typingTimers: Map<string, ReturnType<typeof setTimeout>> },
+ scopeKey: string,
+ userId: string,
+): Partial<{ typingByScope: Map<string, Map<string, string | null>>; typingTimers: Map<string, ReturnType<typeof setTimeout>> }> {
+ const nextTimers = new Map(state.typingTimers)
+ nextTimers.delete(timerKey(scopeKey, userId))
+ const current = state.typingByScope.get(scopeKey)
+ if (!current?.has(userId)) return { typingTimers: nextTimers }
+ const nextMap = new Map(current)
+ nextMap.delete(userId)
+ const nextByScope = new Map(state.typingByScope)
+ if (nextMap.size === 0) nextByScope.delete(scopeKey)
+ else nextByScope.set(scopeKey, nextMap)
+ return { typingByScope: nextByScope, typingTimers: nextTimers }
+}
diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.ts
index 5f0b74160..4f4271496 100644
--- a/src/web/src/hooks/community/use-community-ws.test.ts
+++ b/src/web/src/hooks/community/use-community-ws.test.ts
@@ -1,2304 +1,93 @@
/**
- * Community WS handler tests.
- *
- * The vitest environment is node (no jsdom), so we drive the hook body via a
- * minimal React shim — same approach as the pre-migration test file. The
- * hook now writes to the TanStack Query cache; we assert those writes rather
- * than callback invocations.
+ * Root Community WebSocket boundary and transport-ownership tests.
*/
-import { describe, it, expect, vi, beforeEach } from "vitest"
-import { QueryClient } from "@tanstack/react-query"
-import type {
- CommunityMessageCreate,
- CommunityMessageEdited,
- CommunityReactionAdd,
- CommunityMemberJoin,
- CommunityMemberUpdate,
- CommunityMachineCreated,
- CommunityMachineStatus,
- CommunityPresenceUpdate,
- CommunityStatusUpdate,
- CommunityMentionCreate,
- CommunityServerUpdate,
- CommunityServerDelete,
- CommunityChannelCreate,
- CommunityChannelDelete,
- CommunityChildChannelCreate,
- CommunityChildChannelUpdate,
- CommunityPinAdd,
- CommunityFriendRequest,
- CommunityTypingStart,
-} from "@alook/shared"
-import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
-import { communityKeys } from "@/lib/query-keys"
-import type { ServerDetail } from "./use-servers"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import {
- patchForumSidebarUnread,
- reconcileForumSidebarUnreadFallbacks,
- type ForumSidebarQueryData,
- type ForumSidebarUnreadFallbackState,
-} from "./use-forum-sidebar-threads"
-
-// ── React shim ───────────────────────────────────────────────────────────
-let refs: Map<string, { current: unknown }> = new Map()
-let refCounter = 0
-let stateCounter = 0
-let callbackMemo: Map<string, { fn: Function; deps: unknown[] }> = new Map()
-let callbackCounter = 0
-// Captured effect callbacks — tests can flush them via `flushEffects()`.
-let pendingEffects: Array<() => void> = []
-
-vi.mock("react", () => ({
- useRef: (initial: unknown) => {
- const id = `ref-${refCounter++}`
- if (!refs.has(id)) refs.set(id, { current: initial })
- return refs.get(id)!
- },
- useState: (initial: unknown) => [initial, () => { }],
- useCallback: (fn: Function, deps: unknown[]) => {
- const id = `cb-${callbackCounter++}`
- const existing = callbackMemo.get(id)
- if (existing && JSON.stringify(existing.deps) === JSON.stringify(deps)) {
- return existing.fn
- }
- callbackMemo.set(id, { fn, deps })
- return fn
- },
- useEffect: (fn: () => void, _deps: unknown[]) => {
- pendingEffects.push(fn)
- },
-}))
-
-function flushEffects() {
- const effects = pendingEffects
- pendingEffects = []
- for (const fn of effects) fn()
-}
-
-// Shared QueryClient instance the hook resolves via useQueryClient.
-let capturedQueryClient: QueryClient
-vi.mock("@tanstack/react-query", async () => {
- const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")
- return {
- ...actual,
- useQueryClient: () => capturedQueryClient,
- }
-})
-
-// Capture the callback passed into useUserWs so tests can drive it. The
-// `send` binding is stable across re-mounts within one test so the module-
-// level `activeSend` guard in `useCommunityWs` sees the same identity — a
-// fresh spy per mount would trip the double-mount detector on every remount.
-let capturedOnMessage: ((msg: unknown) => void) | null = null
-let capturedOnReconnect: (() => void) | null = null
-let stableSend: ReturnType<typeof vi.fn> = vi.fn()
-vi.mock("@/lib/use-user-ws", () => ({
- useUserWs: (onMessage: (msg: unknown) => void, options?: { onReconnect?: () => void }) => {
- capturedOnMessage = onMessage
- capturedOnReconnect = options?.onReconnect ?? null
- return { send: stableSend }
- },
-}))
-
-// #3: `useCommunityWs` no longer calls `useMarkChannelRead` — the WS-driven
-// auto-mark-read was replaced by the viewport IntersectionObserver in
-// `useChannelWatermark`. The mock still exists because `flushPendingReads`
-// is imported by the community store's `reset()`. The `markReadMutate` spy
-// is used by the regression test below that asserts the WS handler NEVER
-// invokes it, even for foreign-authored messages in the focused channel.
-const markReadMutate = vi.fn()
-vi.mock("@/hooks/community/mutations/messages", () => ({
- useMarkChannelRead: () => ({ mutate: markReadMutate }),
- flushPendingReads: () => { },
-}))
-
-function resetHarness() {
- refs = new Map()
- refCounter = 0
- stateCounter = 0
- callbackMemo = new Map()
- callbackCounter = 0
- pendingEffects = []
- capturedOnMessage = null
- capturedOnReconnect = null
- capturedQueryClient = new QueryClient()
- stableSend = vi.fn()
- markReadMutate.mockClear()
-}
-
-async function mountHook(options?: { viewerUserId?: string | null } & Record<string, unknown>) {
- const mod = await import("./use-community-ws")
- return mod.useCommunityWs(options)
-}
-
-// Reset store state before each test — the store is module-scoped.
-async function resetStore() {
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().reset()
- useCommunityStore.getState().setCurrentServerId("s1")
- const { useCommunityWsStore } = await import("@/stores/community/ws")
- useCommunityWsStore.getState().reset()
- useMessageStreamStore.getState().resetAll()
- const mod = await import("./use-community-ws")
- mod._resetActiveSend_forTesting()
-}
-
-beforeEach(async () => {
- resetHarness()
- await resetStore()
-})
-
-// ── Fixtures ─────────────────────────────────────────────────────────────
-
-function messageCreate(channelId: string, msgId = "m_1"): CommunityMessageCreate {
- return {
- type: "community:message.create",
- channelId,
- message: {
- id: msgId,
- seq: Number(msgId.match(/\d+$/)?.[0] ?? 1),
- type: "chat",
- authorId: "u_author",
- authorName: "author",
- content: "hi",
- seq: 1,
- createdAt: "2026-07-03T00:00:00.000Z",
- },
- }
-}
-
-function unreadBump(
- channelId: string,
- userId: string,
- extra?: { serverId?: string; railChannelId?: string; isMention?: boolean },
-) {
- return { type: "community:unread.bump" as const, userId, channelId, ...extra }
-}
-
-function forumSidebarFixture(ids = ["post_1"]) {
- return {
- channels: ids.map((id) => ({
- id,
- name: `fallback-${id}`,
- parentChannelId: "forum_1",
- parentMessageId: `opener-${id}`,
- activityAt: "2026-08-01T00:00:00.000Z",
- expiresAt: "2026-08-04T00:00:00.000Z",
- unread: false,
- })),
- included: { parentMessages: ids.map((id) => ({ id: `opener-${id}`, content: `title-${id}` })) },
- serverNow: "2026-08-01T00:00:00.000Z",
- serverClockOffsetMs: 0,
- threads: ids.map((id) => ({
- id,
- parentChannelId: "forum_1",
- parentMessageId: `opener-${id}`,
- title: `title-${id}`,
- activityAt: "2026-08-01T00:00:00.000Z",
- expiresAt: "2026-08-04T00:00:00.000Z",
- unread: false,
- })),
- }
-}
-
-describe("useCommunityWs — message.create", () => {
- it("patches a loaded forum-sidebar child activity without a refetch", async () => {
- await mountHook()
- const key = communityKeys.forumSidebarThreadsView("srv_1", null)
- capturedQueryClient.setQueryData(key, forumSidebarFixture())
- const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const event = {
- ...messageCreate("post_1"),
- serverId: "srv_1",
- parentChannelId: "forum_1",
- } satisfies CommunityMessageCreate
-
- capturedOnMessage!(event)
-
- const data = capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)
- expect(data?.threads[0]).toMatchObject({
- id: "post_1",
- activityAt: "2026-07-03T00:00:00.000Z",
- expiresAt: "2026-07-06T00:00:00.000Z",
- })
- expect(invalidateSpy).not.toHaveBeenCalledWith({ queryKey: communityKeys.forumSidebarThreads("srv_1") })
- })
-
- it("invalidates the forum-sidebar collection when the active child is not loaded", async () => {
- await mountHook()
- const key = communityKeys.forumSidebarThreadsView("srv_1", null)
- capturedQueryClient.setQueryData(key, forumSidebarFixture([]))
-
- capturedOnMessage!({
- ...messageCreate("post_missing"),
- serverId: "srv_1",
- parentChannelId: "forum_1",
- } satisfies CommunityMessageCreate)
-
- expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
- })
-
- it("writes the channel overlay and leaves the base cache untouched when focused", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_1" })
-
- // Re-mount so the ref state picks up the subscription value.
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
-
- // Seed a page cache so setQueryData has something to patch.
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
- pages: [{ messages: [], hasMore: false }],
- pageParams: [null],
- })
-
- capturedOnMessage!(messageCreate("ch_1"))
-
- const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string; seq?: number }[] }[] }>(
- communityKeys.channelMessages("ch_1"),
- )
- expect(cache?.pages[0].messages).toEqual([])
- expect([...getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById]).toHaveLength(1)
- })
-
- it("heals a first-seen event replay once the focused serverId becomes available", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId(null)
- useCommunityStore.getState().subscribe({ channelId: "ch_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
-
- const event = messageCreate("ch_1")
- capturedOnMessage!(event)
- expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById).toHaveLength(0)
-
- useCommunityStore.getState().setCurrentServerId("s1")
- capturedOnMessage!(event)
- expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById).toHaveLength(1)
- })
-
- it("keeps forum query variants base-only and stages a new opener in the overlay", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "forum_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
- const allKey = communityKeys.channelMessages("forum_1")
- const bugKey = [...allKey, "tag", "bug"] as const
- const empty = { pages: [{ messages: [], hasMore: false }], pageParams: [null] }
- capturedQueryClient.setQueryData(allKey, empty)
- capturedQueryClient.setQueryData(bugKey, empty)
-
- capturedOnMessage!(messageCreate("forum_1"))
-
- expect(capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(allKey)?.pages[0].messages).toHaveLength(0)
- expect(capturedQueryClient.getQueryData<{ pages: { messages: unknown[] }[] }>(bugKey)?.pages[0].messages).toHaveLength(0)
- expect(getMessageOverlay({ kind: "channel", id: "forum_1", serverId: "s1" }).liveById).toHaveLength(1)
- })
-
- it("does NOT patch a channel we aren't focused on", async () => {
- await mountHook()
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_other"), {
- pages: [{ messages: [], hasMore: false }],
- pageParams: [null],
- })
- capturedOnMessage!(messageCreate("ch_other"))
- const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
- communityKeys.channelMessages("ch_other"),
- )
- expect(cache?.pages[0].messages).toEqual([])
- })
-
- it("invalidates channelMembers for a focused child channel", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- const store = useCommunityStore.getState()
- store.setCurrentChannelId("ch_1")
- store.setCurrentChannelMeta({ name: "thread", parentChannelId: "parent_1" })
- store.subscribe({ channelId: "ch_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
-
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!(messageCreate("ch_1"))
-
- expect(spy).toHaveBeenCalledWith({ queryKey: communityKeys.channelMembers("ch_1") })
- expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.threadParticipants("ch_1") })
- })
-
- it("does NOT invalidate channelMembers for a focused top-level channel", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- const store = useCommunityStore.getState()
- store.setCurrentChannelId("ch_1")
- store.subscribe({ channelId: "ch_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
-
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!(messageCreate("ch_1"))
-
- expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.channelMembers("ch_1") })
- expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.threadParticipants("ch_1") })
- })
-
- it("does NOT invalidate channelMembers for an unfocused channel", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- const store = useCommunityStore.getState()
- store.setCurrentChannelId("ch_1")
- store.setCurrentChannelMeta({ name: "thread", parentChannelId: "parent_1" })
- store.subscribe({ channelId: "ch_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
-
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!(messageCreate("ch_other"))
-
- expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.channelMembers("ch_other") })
- expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.threadParticipants("ch_other") })
- })
-
- it("dedupes by messageId — a repeat event is a no-op", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
-
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
- pages: [{ messages: [], hasMore: false }],
- pageParams: [null],
- })
- capturedOnMessage!(messageCreate("ch_1"))
- capturedOnMessage!(messageCreate("ch_1"))
- capturedOnMessage!(messageCreate("ch_1"))
- expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById.size).toBe(1)
- })
-
- it("caps the live page at MAX_LIVE_PAGE_MESSAGES, dropping the oldest entry", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
-
- const MAX_LIVE_PAGE_MESSAGES = 500
- const seeded = Array.from({ length: MAX_LIVE_PAGE_MESSAGES }, (_, i) => ({
- id: `seed_${i}`,
- content: "x",
- createdAt: "2026-07-03T00:00:00.000Z",
- }))
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
- pages: [{ messages: seeded, hasMore: false }],
- pageParams: [null],
- })
-
- capturedOnMessage!(messageCreate("ch_1", "new_message"))
-
- const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
- communityKeys.channelMessages("ch_1"),
- )
- const ids = cache?.pages[0].messages.map((m) => m.id) ?? []
- expect(ids).toHaveLength(MAX_LIVE_PAGE_MESSAGES)
- expect(ids[0]).toBe("seed_0")
- expect(ids).not.toContain("new_message")
- expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById.has("new_message")).toBe(true)
- })
-
- it("flips hasMore/hasMoreOlder to true when the head-slice discards history (legacy shape)", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
-
- const MAX_LIVE_PAGE_MESSAGES = 500
- const seeded = Array.from({ length: MAX_LIVE_PAGE_MESSAGES }, (_, i) => ({
- id: `seed_${i}`,
- content: "x",
- createdAt: "2026-07-03T00:00:00.000Z",
- }))
- // Legacy newest-mode envelope: only `hasMore` is defined.
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
- pages: [{ messages: seeded, hasMore: false }],
- pageParams: [null],
- })
-
- capturedOnMessage!(messageCreate("ch_1", "new_message"))
-
- const cache = capturedQueryClient.getQueryData<{
- pages: { messages: { id: string }[]; hasMore?: boolean; hasMoreOlder?: boolean }[]
- }>(communityKeys.channelMessages("ch_1"))
- // Head-slice discarded seed_0; the "Load older" affordance must re-arm
- // via `hasMore: true` (legacy shape had no `hasMoreOlder` so we don't
- // synthesize it).
- expect(cache?.pages[0].hasMore).toBe(false)
- expect(cache?.pages[0].hasMoreOlder).toBeUndefined()
- })
-
- it("flips hasMoreOlder to true on head-slice for anchor-mode envelopes", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
-
- const MAX_LIVE_PAGE_MESSAGES = 500
- const seeded = Array.from({ length: MAX_LIVE_PAGE_MESSAGES }, (_, i) => ({
- id: `seed_${i}`,
- content: "x",
- createdAt: "2026-07-03T00:00:00.000Z",
- }))
- // Anchor-mode envelope: hasMoreOlder + hasMoreNewer, no `hasMore`.
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
- pages: [{ messages: seeded, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 42 }],
- pageParams: [{ mode: "anchor", anchor: "seed_0" }],
- })
-
- capturedOnMessage!(messageCreate("ch_1", "new_message"))
-
- const cache = capturedQueryClient.getQueryData<{
- pages: { messages: { id: string }[]; hasMore?: boolean; hasMoreOlder?: boolean; hasMoreNewer?: boolean }[]
- }>(communityKeys.channelMessages("ch_1"))
- expect(cache?.pages[0].hasMoreOlder).toBe(false)
- // We must NOT invent a legacy `hasMore` flag on an anchor envelope —
- // the two shapes are mutually exclusive.
- expect(cache?.pages[0].hasMore).toBeUndefined()
- // `hasMoreNewer` untouched.
- expect(cache?.pages[0].hasMoreNewer).toBe(false)
- })
-
- it("does not touch hasMore flags when the page hasn't been trimmed", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
-
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
- pages: [
- {
- messages: [{ id: "seed_0", content: "x", createdAt: "t" }],
- hasMoreOlder: false,
- hasMoreNewer: false,
- latestSeq: 1,
- },
- ],
- pageParams: [null],
- })
- capturedOnMessage!(messageCreate("ch_1", "m_new"))
- const cache = capturedQueryClient.getQueryData<{
- pages: { hasMoreOlder?: boolean; hasMoreNewer?: boolean }[]
- }>(communityKeys.channelMessages("ch_1"))
- expect(cache?.pages[0].hasMoreOlder).toBe(false)
- expect(cache?.pages[0].hasMoreNewer).toBe(false)
- })
-
- it("does not drop below the cap when the page isn't at capacity yet", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
-
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
- pages: [{ messages: [{ id: "seed_0", content: "x", createdAt: "t" }], hasMore: false }],
- pageParams: [null],
- })
- capturedOnMessage!(messageCreate("ch_1", "m_new"))
- const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
- communityKeys.channelMessages("ch_1"),
- )
- expect(cache?.pages[0].messages.map((m) => m.id)).toEqual(["seed_0"])
- expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById.has("m_new")).toBe(true)
- })
-
- it("does not schedule an inbox invalidate for viewer's own messages", async () => {
- vi.useFakeTimers()
- try {
- await mountHook({ viewerUserId: "u_author" })
- const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!(messageCreate("ch_random"))
- vi.advanceTimersByTime(1_000)
- expect(invalidateSpy).not.toHaveBeenCalled()
- } finally {
- vi.useRealTimers()
- }
- })
-
- it("debounces inbox invalidation — 10 messages ⇒ 1 invalidate call", async () => {
- vi.useFakeTimers()
- try {
- await mountHook({ viewerUserId: "u_me" })
- const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- for (let i = 0; i < 10; i++) capturedOnMessage!(messageCreate("ch_x", `m_${i}`))
- // Before debounce window, no invalidate.
- expect(invalidateSpy).not.toHaveBeenCalled()
- // Advance past the debounce window — exactly one invalidate.
- vi.advanceTimersByTime(500)
- const inboxCalls = invalidateSpy.mock.calls.filter((c) => {
- const key = c[0]?.queryKey
- return Array.isArray(key) && key.includes("inbox")
- })
- expect(inboxCalls).toHaveLength(1)
- } finally {
- vi.useRealTimers()
- }
- })
-})
-
-// ── Channel-sidebar live unread patch (plans/community-unread-indicators.md) ─
-describe("useCommunityWs — message.create patches channel unread in the open server's cache", () => {
- function serverDetailFixture(channelId: string) {
- return {
- id: "srv_open",
- name: "Server",
- description: "",
- icon: null,
- ownerId: "u_owner",
- categories: [
- { id: "cat_A", name: "Category A", channels: [{ id: channelId, name: "random", active: false, unread: false }] },
- ],
- }
- }
-
- it("flips the channel's unread to true on unread.bump when it belongs to the currently-open server's cached ServerDetail", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
-
- capturedOnMessage!(unreadBump("ch_random", "u_me"))
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_open"))
- expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_random", unread: true })
- })
-
- it("routes a child unread.bump to its loaded forum-sidebar row instead of the parent forum", async () => {
- await mountHook({ viewerUserId: "u_me" })
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("forum_1"))
- const sidebarKey = communityKeys.forumSidebarThreadsView("srv_open", null)
- capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture())
-
- capturedOnMessage!(unreadBump("post_1", "u_me", {
- serverId: "srv_open",
- railChannelId: "forum_1",
- }))
-
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(sidebarKey)?.threads[0].unread)
- .toBe(true)
- expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
- communityKeys.server("srv_open"),
- )?.categories[0].channels[0].unread).toBe(false)
- expect(capturedQueryClient.getQueryData<ServerDetail>(
- communityKeys.server("srv_open"),
- )?.forumUnreadState?.forum_1?.childIds).toEqual(["post_1"])
- })
-
- it("falls back to the parent forum dot when the child has no locatable sidebar row", async () => {
- await mountHook({ viewerUserId: "u_me" })
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("forum_1"))
- capturedQueryClient.setQueryData(
- communityKeys.forumSidebarThreadsView("srv_open", null),
- forumSidebarFixture([]),
- )
-
- capturedOnMessage!(unreadBump("post_missing", "u_me", {
- serverId: "srv_open",
- railChannelId: "forum_1",
- }))
-
- expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
- communityKeys.server("srv_open"),
- )?.categories[0].channels[0].unread).toBe(true)
- expect(capturedQueryClient.getQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("srv_open"),
- )).toEqual({
- forum_1: { baseUnread: false, childIds: ["post_missing"] },
- })
- })
-
- it("moves message.create → unread.bump fallback ownership to the refetched child", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const serverKey = communityKeys.server("srv_open")
- const sidebarKey = communityKeys.forumSidebarThreadsView("srv_open", null)
- capturedQueryClient.setQueryData(serverKey, serverDetailFixture("forum_1"))
- capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture([]))
-
- capturedOnMessage!({
- ...messageCreate("post_new"),
- serverId: "srv_open",
- parentChannelId: "forum_1",
- } satisfies CommunityMessageCreate)
- expect(capturedQueryClient.getQueryState(sidebarKey)?.isInvalidated).toBe(true)
-
- capturedOnMessage!(unreadBump("post_new", "u_me", {
- serverId: "srv_open",
- railChannelId: "forum_1",
- }))
- expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
- serverKey,
- )?.categories[0].channels[0].unread).toBe(true)
-
- const refetched = forumSidebarFixture(["post_new"])
- refetched.threads[0]!.unread = true
- capturedQueryClient.setQueryData(sidebarKey, refetched)
- reconcileForumSidebarUnreadFallbacks(capturedQueryClient, "srv_open", ["post_new"])
-
- expect(capturedQueryClient.getQueryData<ForumSidebarQueryData>(sidebarKey)?.threads[0]?.unread).toBe(true)
- expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
- serverKey,
- )?.categories[0].channels[0].unread).toBe(false)
-
- capturedQueryClient.setQueryData<ForumSidebarQueryData>(sidebarKey, (data) =>
- patchForumSidebarUnread(data, "post_new", false),
- )
- expect(capturedQueryClient.getQueryData<ForumSidebarQueryData>(sidebarKey)?.threads[0]?.unread).toBe(false)
- expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
- serverKey,
- )?.categories[0].channels[0].unread).toBe(false)
- })
-
- it("message.create alone does NOT flip the sidebar unread (mute-gated bump is the only trigger now)", async () => {
- // Regression pin: mute ≠ blindness. The message.create still arrives (and
- // content syncs), but the unread dot is flipped ONLY by the server's
- // per-recipient, mute-gated unread.bump — so a muted channel's message.create
- // must NOT light the dot. Don't "fix" this back onto message.create.
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
-
- capturedOnMessage!(messageCreate("ch_random"))
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_open"))
- expect(cache?.categories[0].channels[0].unread).toBe(false)
- })
-
- it("does NOT flip unread on a bump addressed to a different user", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
-
- capturedOnMessage!(unreadBump("ch_random", "someone_else"))
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_open"))
- expect(cache?.categories[0].channels[0].unread).toBe(false)
- })
-
- it("does NOT flip unread for the currently-subscribed (active) channel", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- useCommunityStore.getState().subscribe({ channelId: "ch_random" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook({ viewerUserId: "u_me" })
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
-
- capturedOnMessage!(unreadBump("ch_random", "u_me"))
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_open"))
- expect(cache?.categories[0].channels[0].unread).toBe(false)
- })
-
- it("is a no-op when the channel isn't present in the currently cached ServerDetail (different server / no cache)", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_other"))
-
- expect(() => capturedOnMessage!(unreadBump("ch_random", "u_me"))).not.toThrow()
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_open"))
- // Untouched — the fixture's own channel stays unread: false.
- expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_other", unread: false })
- })
-
- it("does not crash and is a no-op when no server is currently open", async () => {
- await mountHook({ viewerUserId: "u_me" })
- expect(() => capturedOnMessage!(unreadBump("ch_random", "u_me"))).not.toThrow()
- })
-
- // ── inbox-dot-ws-driven ② : bump carries serverId / railChannelId / isMention ──
-
- it("lights the dot on the bump's OWN serverId, even when a DIFFERENT server is open (the cross-server bug)", async () => {
- // The core fix: previously the handler only patched the currently-open
- // server, so a message in another server never lit its dot. With
- // `serverId` on the bump we patch the right server's detail regardless of
- // which one is focused.
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open") // a different server is focused
- capturedQueryClient.setQueryData(communityKeys.server("srv_other"), serverDetailFixture("ch_bg"))
-
- capturedOnMessage!(unreadBump("ch_bg", "u_me", { serverId: "srv_other" }))
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_other"))
- expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_bg", unread: true })
- })
-
- it("lights the PARENT channel row for a thread bump (railChannelId), not the thread's own id", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- // The tree row is the parent channel; the thread has no independent row.
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_parent"))
-
- // channelId = the thread's id (true scope), railChannelId = parent row.
- capturedOnMessage!(unreadBump("ch_thread", "u_me", { serverId: "srv_open", railChannelId: "ch_parent" }))
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_open"))
- expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_parent", unread: true })
- })
-
- it("suppresses the dot when the viewer is looking at the RAIL row (thread bump whose parent is open)", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- useCommunityStore.getState().subscribe({ channelId: "ch_parent" }) // parent row is open
- refCounter = 0; stateCounter = 0; callbackCounter = 0
- await mountHook({ viewerUserId: "u_me" })
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_parent"))
-
- capturedOnMessage!(unreadBump("ch_thread", "u_me", { serverId: "srv_open", railChannelId: "ch_parent" }))
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_open"))
- expect(cache?.categories[0].channels[0].unread).toBe(false)
- })
-
- it("bumps the rail mention badge (servers() mentions +1) ONLY when isMention is set", async () => {
- await mountHook({ viewerUserId: "u_me" })
- capturedQueryClient.setQueryData(communityKeys.servers(), {
- servers: [{ id: "srv_x", name: "X", initial: "X", active: false, mentions: 2, icon: null }],
- })
-
- // Plain unread (no isMention) → mention count unchanged.
- capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x" }))
- let servers = capturedQueryClient.getQueryData<{ servers: { id: string; mentions: number }[] }>(communityKeys.servers())
- expect(servers?.servers[0].mentions).toBe(2)
-
- // Mention → +1.
- capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x", isMention: true }))
- servers = capturedQueryClient.getQueryData<{ servers: { id: string; mentions: number }[] }>(communityKeys.servers())
- expect(servers?.servers[0].mentions).toBe(3)
- })
-
- it("existing focused-channel message patch and debounced inbox invalidation still fire on message.create", async () => {
- vi.useFakeTimers()
- try {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- useCommunityStore.getState().subscribe({ channelId: "ch_focused" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook({ viewerUserId: "u_me" })
-
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_focused"), {
- pages: [{ messages: [], hasMore: false }],
- pageParams: [null],
- })
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_focused"))
- const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
-
- capturedOnMessage!(messageCreate("ch_focused"))
- vi.advanceTimersByTime(500)
-
- const messagesCache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
- communityKeys.channelMessages("ch_focused"),
- )
- expect(messagesCache?.pages[0].messages).toEqual([])
- expect(getMessageOverlay({ kind: "channel", id: "ch_focused", serverId: "s1" }).liveById.has("m_1")).toBe(true)
- const inboxCalls = invalidateSpy.mock.calls.filter((c) => {
- const key = c[0]?.queryKey
- return Array.isArray(key) && key.includes("inbox")
- })
- expect(inboxCalls).toHaveLength(1)
- } finally {
- vi.useRealTimers()
- }
- })
-})
-
-describe("useCommunityWs — reactions", () => {
- it("patches the message row's reactions in the channel cache", async () => {
- await mountHook({ viewerUserId: "u_me" })
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
- pages: [
- {
- messages: [
- { id: "m_1", content: "x", reactions: [] },
- ],
- hasMore: false,
- },
- ],
- pageParams: [null],
- })
- const event: CommunityReactionAdd = {
- type: "community:reaction.add",
- channelId: "ch_1",
- messageId: "m_1",
- userId: "u_other",
- emoji: "👍",
- }
- capturedOnMessage!(event)
- const cache = capturedQueryClient.getQueryData<{
- pages: { messages: { id: string; reactions: { emoji: string; count: number; me: boolean }[] }[] }[]
- }>(communityKeys.channelMessages("ch_1"))
- expect(cache?.pages[0].messages[0].reactions).toEqual([
- { emoji: "👍", count: 1, me: false, userIds: ["u_other"] },
- ])
- })
-
- it("refreshes a focused DM row that exists only in the overlay", async () => {
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
- await mountHook({ viewerUserId: "u_me" })
- useMessageStreamStore.getState().dispatch(
- { kind: "dm", id: "dm_1" },
- {
- type: "wsMessage",
- message: {
- id: "m_dm",
- seq: 4,
- type: "chat",
- authorId: "u_other",
- authorName: "Other",
- content: "hi",
- reactions: [],
- },
- },
- )
-
- capturedOnMessage!({
- type: "community:reaction.add",
- channelId: "dm_1",
- messageId: "m_dm",
- userId: "u_me",
- emoji: "👍",
- })
-
- expect(getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.get("m_dm")?.reactions).toEqual([
- { emoji: "👍", count: 1, me: true, userIds: ["u_me"] },
- ])
- })
-})
-
-describe("useCommunityWs — message.updated", () => {
- it("refreshes approval fields on a focused DM row that exists only in the overlay", async () => {
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
- await mountHook()
- useMessageStreamStore.getState().dispatch(
- { kind: "dm", id: "dm_1" },
- {
- type: "wsMessage",
- message: { id: "m_dm", seq: 4, type: "chat", content: "approval" },
- },
- )
- const profile = { id: "u_other", name: "Other", discriminator: "0001", image: null }
- const approval = {
- friendshipId: "friendship_1",
- status: "approved" as const,
- waitingOn: null,
- otherProfile: profile,
- botProfile: { ...profile, id: "bot_1", name: "Bot" },
- }
-
- capturedOnMessage!({
- type: "community:message.updated",
- channelId: "dm_1",
- messageId: "m_dm",
- approval,
- })
-
- expect(getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.get("m_dm")?.approval).toEqual(approval)
- })
-})
-
-describe("useCommunityWs — pin.add", () => {
- it("invalidates the channel's pin list", async () => {
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const event: CommunityPinAdd = {
- type: "community:pin.add",
- channelId: "ch_1",
- messageId: "m_1",
- }
- capturedOnMessage!(event)
- const pinsCalls = spy.mock.calls.filter((c) =>
- JSON.stringify(c[0]?.queryKey ?? []).includes(`"pins"`) ||
- // pins() nests under channel + channelId + pins
- (Array.isArray(c[0]?.queryKey) && (c[0]!.queryKey as unknown[]).includes("pins")),
- )
- // At least one invalidate is against communityKeys.pins("ch_1").
- expect(
- pinsCalls.some((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.includes("ch_1") && key.includes("pins")
- }),
- ).toBe(true)
- })
-})
-
-describe("useCommunityWs — member events", () => {
- it("patches the members cache with a join event", async () => {
- await mountHook()
- capturedQueryClient.setQueryData(communityKeys.members("srv_1"), {
- pages: [{ members: [], hasMore: false, limit: 50, total: 0 }],
- pageParams: [null],
- })
- const event: CommunityMemberJoin = {
- type: "community:member.join",
- serverId: "srv_1",
- member: {
- id: "mem_1",
- userId: "u_1",
- name: "n",
- discriminator: "0000",
- role: "member",
- joinedAt: "2026-07-03T00:00:00.000Z",
- },
- }
- capturedOnMessage!(event)
- const cache = capturedQueryClient.getQueryData<{
- pages: { members: { userId: string }[]; total: number }[]
- }>(communityKeys.members("srv_1"))
- expect(cache?.pages[0].members.map((m) => m.userId)).toEqual(["u_1"])
- expect(cache?.pages[0].total).toBe(1)
- })
-
- it("a self-rename (member.update with userId + changes.nickname) patches authorName in every cached channel/DM message list", async () => {
- await mountHook()
- useMessageStreamStore.getState().dispatch(
- { kind: "dm", id: "dm_overlay" },
- {
- type: "wsMessage",
- message: {
- id: "m_overlay",
- seq: 9,
- type: "chat",
- authorId: "u_renamed",
- authorName: "OldName",
- content: "overlay only",
- },
- },
- )
-
- // Two message caches — one channel, one DM — each with a message
- // authored by the renamed user and one by someone else. Both should
- // update; the other author's row must stay untouched.
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
- pages: [{
- messages: [
- { id: "m_1", authorId: "u_renamed", authorName: "OldName", content: "hi" },
- { id: "m_2", authorId: "u_other", authorName: "Someone Else", content: "yo" },
- ],
- hasMore: false,
- }],
- pageParams: [null],
- })
- capturedQueryClient.setQueryData(communityKeys.dmMessages("dm_1"), {
- pages: [{
- messages: [
- { id: "m_3", authorId: "u_renamed", authorName: "OldName", content: "sup" },
- ],
- hasMore: false,
- }],
- pageParams: [null],
- })
-
- const event: CommunityMemberUpdate = {
- type: "community:member.update",
- serverId: "srv_1",
- memberId: "mem_1",
- userId: "u_renamed",
- changes: { nickname: "NewName" },
- }
- capturedOnMessage!(event)
-
- const channelCache = capturedQueryClient.getQueryData<{
- pages: { messages: { id: string; authorName: string }[] }[]
- }>(communityKeys.channelMessages("ch_1"))
- expect(channelCache?.pages[0].messages).toEqual([
- { id: "m_1", authorId: "u_renamed", authorName: "NewName", content: "hi" },
- { id: "m_2", authorId: "u_other", authorName: "Someone Else", content: "yo" },
- ])
-
- const dmCache = capturedQueryClient.getQueryData<{
- pages: { messages: { id: string; authorName: string }[] }[]
- }>(communityKeys.dmMessages("dm_1"))
- expect(dmCache?.pages[0].messages).toEqual([
- { id: "m_3", authorId: "u_renamed", authorName: "NewName", content: "sup" },
- ])
- expect(
- getMessageOverlay({ kind: "dm", id: "dm_overlay" }).liveById.get("m_overlay")?.authorName,
- ).toBe("NewName")
- })
-
- it("a role-only member.update (no userId/nickname) does not touch any message cache", async () => {
- await mountHook()
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {
- pages: [{
- messages: [{ id: "m_1", authorId: "u_1", authorName: "Name", content: "hi" }],
- hasMore: false,
- }],
- pageParams: [null],
- })
-
- const event: CommunityMemberUpdate = {
- type: "community:member.update",
- serverId: "srv_1",
- memberId: "mem_1",
- changes: { role: "admin" },
- }
- capturedOnMessage!(event)
-
- const cache = capturedQueryClient.getQueryData<{
- pages: { messages: { id: string; authorName: string }[] }[]
- }>(communityKeys.channelMessages("ch_1"))
- expect(cache?.pages[0].messages).toEqual([
- { id: "m_1", authorId: "u_1", authorName: "Name", content: "hi" },
- ])
- })
-})
-
-describe("useCommunityWs — channel.member_add/remove → invalidate rosters", () => {
- it("member_add invalidates channelMembers AND threadParticipants for a child thread", async () => {
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!({
- type: "community:channel.member_add",
- serverId: "srv_1",
- channelId: "ch_1",
- userId: "u_new",
- })
- const invalidated = (key: unknown) =>
- spy.mock.calls.some((c) => JSON.stringify(c[0]?.queryKey) === JSON.stringify(key))
- expect(invalidated(communityKeys.channelMembers("ch_1"))).toBe(true)
- expect(invalidated(communityKeys.threadParticipants("ch_1"))).toBe(true)
- })
-
- it("member_remove invalidates threadParticipants too", async () => {
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!({
- type: "community:channel.member_remove",
- serverId: "srv_1",
- channelId: "ch_1",
- userId: "u_gone",
- })
- expect(
- spy.mock.calls.some(
- (c) => JSON.stringify(c[0]?.queryKey) === JSON.stringify(communityKeys.threadParticipants("ch_1")),
- ),
- ).toBe(true)
- })
-
- it("adds/removes the viewer's participating child in the forum sidebar", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const key = communityKeys.forumSidebarThreadsView("srv_1", null)
- capturedQueryClient.setQueryData(key, forumSidebarFixture())
-
- capturedOnMessage!({
- type: "community:channel.member_remove",
- serverId: "srv_1",
- channelId: "post_1",
- userId: "u_me",
- })
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)?.threads).toEqual([])
-
- capturedQueryClient.setQueryData(key, forumSidebarFixture([]))
- capturedOnMessage!({
- type: "community:channel.member_add",
- serverId: "srv_1",
- channelId: "post_2",
- userId: "u_me",
- })
- expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
- })
-})
-
-describe("useCommunityWs — friend + mention → invalidate", () => {
- it("friend.request invalidates communityKeys.friends()", async () => {
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const event: CommunityFriendRequest = {
- type: "community:friend.request",
- friendship: {
- id: "f_1",
- requesterId: "u_a",
- addresseeId: "u_b",
- status: "pending",
- createdAt: "2026-07-03T00:00:00.000Z",
- },
- }
- capturedOnMessage!(event)
- expect(
- spy.mock.calls.some((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.includes("friends")
- }),
- ).toBe(true)
- })
-
- it("mention.create invalidates communityKeys.inbox() immediately (no debounce)", async () => {
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const event: CommunityMentionCreate = {
- type: "community:mention.create",
- userId: "u_1",
- messageId: "m_1",
- authorName: "A",
- }
- capturedOnMessage!(event)
- expect(
- spy.mock.calls.some((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.includes("inbox")
- }),
- ).toBe(true)
- })
-
- it("mention.create also invalidates communityKeys.servers() so the rail badge ticks", async () => {
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const event: CommunityMentionCreate = {
- type: "community:mention.create",
- userId: "u_1",
- messageId: "m_1",
- authorName: "A",
- }
- capturedOnMessage!(event)
- const serversInvalidates = spy.mock.calls.filter((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.length === 2 && key[0] === "community" && key[1] === "servers"
- })
- expect(serversInvalidates).toHaveLength(1)
- })
-})
-
-describe("useCommunityWs — presence → Zustand store, no cache", () => {
- it("presence.update writes to useCommunityWsStore only", async () => {
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const event: CommunityPresenceUpdate = {
- type: "community:presence.update",
- userId: "u_pres",
- online: true,
- }
- capturedOnMessage!(event)
- const { useCommunityWsStore } = await import("@/stores/community/ws")
- expect(useCommunityWsStore.getState().onlineUserIds.has("u_pres")).toBe(true)
- // No cache touched.
- expect(spy).not.toHaveBeenCalled()
- })
-})
-
-describe("useCommunityWs — status.update → Zustand store, no cache", () => {
- it("status.update writes to useCommunityWsStore only", async () => {
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const event: CommunityStatusUpdate = {
- type: "community:status.update",
- userId: "u_status",
- statusEmoji: "🎧",
- statusText: "Vibing",
- }
- capturedOnMessage!(event)
- const { useCommunityWsStore } = await import("@/stores/community/ws")
- expect(useCommunityWsStore.getState().userStatuses.get("u_status")).toEqual({
- emoji: "🎧",
- text: "Vibing",
- })
- // No cache touched.
- expect(spy).not.toHaveBeenCalled()
- })
-})
-
-describe("useCommunityWs — server.update patches server + list caches", () => {
- it("applies name change to server(id) and servers()", async () => {
- await mountHook()
- capturedQueryClient.setQueryData(communityKeys.server("srv_1"), {
- id: "srv_1",
- name: "old",
- description: "d",
- icon: null,
- ownerId: "u_1",
- categories: [],
- })
- capturedQueryClient.setQueryData(communityKeys.servers(), {
- servers: [
- {
- id: "srv_1",
- name: "old",
- initial: "O",
- active: false,
- unread: false,
- mentions: 0,
- },
- ],
- })
- const event: CommunityServerUpdate = {
- type: "community:server.update",
- serverId: "srv_1",
- changes: { name: "new" },
- }
- capturedOnMessage!(event)
- expect(capturedQueryClient.getQueryData<{ name: string }>(communityKeys.server("srv_1"))).toMatchObject({
- name: "new",
- })
- expect(
- capturedQueryClient.getQueryData<{ servers: { name: string; initial: string }[] }>(
- communityKeys.servers(),
- )?.servers[0],
- ).toMatchObject({ name: "new", initial: "N" })
- })
-})
-
-describe("useCommunityWs — machines", () => {
- it("machine.created upserts and stashes pending token", async () => {
- await mountHook()
- const created: CommunityMachineCreated = {
- type: "community:machine.created",
- tokenId: "cmt_abc",
- machine: {
- id: "m_1",
- hostname: "h",
- displayName: "d",
- platform: "darwin",
- arch: "arm64",
- osRelease: "24",
- daemonVersion: "0.1",
- lastSeenAt: null,
- status: "online",
- availableRuntimes: [],
- createdAt: "2026-07-03T00:00:00.000Z",
- updatedAt: "2026-07-03T00:00:00.000Z",
- },
- }
- capturedOnMessage!(created)
- expect(
- capturedQueryClient.getQueryData<{ machines: { id: string }[] }>(communityKeys.machines())?.machines,
- ).toHaveLength(1)
- const { useCommunityStore } = await import("@/stores/community")
- expect(useCommunityStore.getState().pendingMachineTokenId).toBe("cmt_abc")
- })
-
- it("machine.status patches lastSeenAt/status only", async () => {
- await mountHook()
- capturedQueryClient.setQueryData(communityKeys.machines(), {
- machines: [
- {
- id: "m_1",
- hostname: "h",
- displayName: "d",
- platform: "darwin",
- arch: "arm64",
- osRelease: "24",
- daemonVersion: "0.1",
- lastSeenAt: null,
- status: "online",
- availableRuntimes: [],
- createdAt: "",
- updatedAt: "",
- },
- ],
- })
- const status: CommunityMachineStatus = {
- type: "community:machine.status",
- machineId: "m_1",
- status: "offline",
- lastSeenAt: "2026-07-03T00:00:00.000Z",
- }
- capturedOnMessage!(status)
- const cache = capturedQueryClient.getQueryData<{ machines: { status: string; lastSeenAt: string | null }[] }>(
- communityKeys.machines(),
- )
- expect(cache?.machines[0].status).toBe("offline")
- expect(cache?.machines[0].lastSeenAt).toBe("2026-07-03T00:00:00.000Z")
- })
-})
-
-describe("useCommunityWs — child channel events", () => {
- it("child_create without a parentMessageId only invalidates threads", async () => {
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const event: CommunityChildChannelCreate = {
- type: "community:channel.child_create",
- parentChannelId: "ch_1",
- channel: {
- id: "ch_thread",
- name: "t",
- type: "thread",
- createdAt: "2026-07-03T00:00:00.000Z",
- },
- }
- capturedOnMessage!(event)
- const keys = spy.mock.calls.map((c) => c[0]?.queryKey as unknown[])
- expect(keys.some((k) => k?.includes("threads"))).toBe(true)
- expect(keys.some((k) => k?.includes("forum-threads"))).toBe(false)
- expect(keys).not.toContainEqual(communityKeys.channelMessages("ch_1"))
- })
-})
-
-describe("useCommunityWs — channel.* invalidates server(id)", () => {
- it("channel.create invalidates server(serverId)", async () => {
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const event: CommunityChannelCreate = {
- type: "community:channel.create",
- serverId: "srv_1",
- channel: {
- id: "ch_new",
- name: "n",
- type: "text",
- position: 0,
- createdAt: "2026-07-03T00:00:00.000Z",
- },
- }
- capturedOnMessage!(event)
- expect(
- spy.mock.calls.some((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.includes("srv_1")
- }),
- ).toBe(true)
- })
-})
-
-describe("useCommunityWs — DM message.create", () => {
- it("writes the focused DM overlay, leaves Query base-only, and invalidates dms()", async () => {
- vi.useFakeTimers()
- try {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
-
- capturedQueryClient.setQueryData(communityKeys.dmMessages("dm_1"), {
- pages: [{ messages: [], hasMore: false }],
- pageParams: [null],
- })
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- // A DM is a channel now — its message arrives as `message.create` keyed by
- // the DM's channel id (which the subscription tracks in `dmConversationId`).
- const event: CommunityMessageCreate = {
- type: "community:message.create",
- channelId: "dm_1",
- message: {
- id: "dm_m_1",
- seq: 1,
- authorId: "u_a",
- authorName: "a",
- content: "hi",
- type: "chat",
- seq: 1,
- createdAt: "2026-07-03T00:00:00.000Z",
- },
- }
- capturedOnMessage!(event)
- const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string; seq?: number }[] }[] }>(
- communityKeys.dmMessages("dm_1"),
- )
- expect(cache?.pages[0].messages).toEqual([])
- const { getMessageOverlay } = await import("@/stores/community/message-stream")
- expect(
- [...getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.values()].map((message) => message.id),
- ).toEqual(["dm_m_1"])
- // The inbox + `dms()` invalidation is batched behind the inbox debounce.
- vi.advanceTimersByTime(600)
- expect(
- spy.mock.calls.some((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.includes("dms")
- }),
- ).toBe(true)
- } finally {
- vi.useRealTimers()
- }
- })
-
- it("heals an already-seen DM event into the overlay before seen dedupe returns", async () => {
- const { useCommunityStore } = await import("@/stores/community")
- const { useCommunityWsStore } = await import("@/stores/community/ws")
- useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
- useCommunityWsStore.getState().markSeenMessage("dm_replay")
- await mountHook()
-
- capturedOnMessage!({
- type: "community:message.create",
- channelId: "dm_1",
- message: {
- id: "dm_replay",
- seq: 12,
- authorId: "u_a",
- authorName: "a",
- content: "replay",
- type: "chat",
- createdAt: "2026-07-03T00:00:00.000Z",
- },
- })
-
- expect(getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.has("dm_replay")).toBe(true)
- })
-})
+ capturedOnMessage,
+ capturedOnReconnect,
+ capturedQueryClient,
+ capturedUseUserWsOptions,
+ cleanupCommunityWsHarness,
+ flushEffects,
+ getStableSend,
+ mountHook,
+ resetCommunityWsHarness,
+ resetHookInstance,
+ setStableSend,
+ useUserWsCallCount,
+} from "./community-ws/test-harness"
+
+beforeEach(resetCommunityWsHarness)
+afterEach(cleanupCommunityWsHarness)
describe("useCommunityWs — non-community events bail", () => {
- it("malformed shape early-returns via isCommunityEvent", async () => {
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "setQueryData")
- capturedOnMessage!({ type: "task.updated", taskId: "t_1" })
- expect(spy).not.toHaveBeenCalled()
- })
-})
-
-// ── Regression #3 — channel.delete evicts channel-scoped caches ─────────
-describe("useCommunityWs — channel.delete evicts channel-scoped caches", () => {
- it("removes channelMessages, pins, and threads for the deleted channel", async () => {
- await mountHook()
- // Seed every canonical cache for the target channel so we can observe eviction.
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_dead"), {
- pages: [{ messages: [{ id: "m_1" }], hasMore: false }],
- pageParams: [null],
- })
- capturedQueryClient.setQueryData(communityKeys.pins("ch_dead"), { pins: [{ id: "p" }] })
- capturedQueryClient.setQueryData(communityKeys.threads("ch_dead"), { threads: [{ id: "t" }] })
- const sidebarKey = communityKeys.forumSidebarThreadsView("srv_1", null)
- capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture(["ch_dead"]))
-
- const event: CommunityChannelDelete = {
- type: "community:channel.delete",
- serverId: "srv_1",
- channelId: "ch_dead",
- }
- capturedOnMessage!(event)
-
- expect(capturedQueryClient.getQueryData(communityKeys.channelMessages("ch_dead"))).toBeUndefined()
- expect(capturedQueryClient.getQueryData(communityKeys.pins("ch_dead"))).toBeUndefined()
- expect(capturedQueryClient.getQueryData(communityKeys.threads("ch_dead"))).toBeUndefined()
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(sidebarKey)?.threads).toEqual([])
- })
-})
-
-// ── Regression #4 — child_create seeds messageCount: 0 ──────────────────
-describe("useCommunityWs — child_create patches parent thread badge with count 0", () => {
- it("message.create then child_create patches the opener into a forum card", async () => {
+ it("rejects non-community and unknown community-prefixed events", async () => {
await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_parent" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_parent"), {
- pages: [{ messages: [], hasMore: false }],
- pageParams: [null],
- })
- capturedOnMessage!(messageCreate("ch_parent", "m_parent"))
-
- const event: CommunityChildChannelCreate = {
- type: "community:channel.child_create",
- parentChannelId: "ch_parent",
- parentMessageId: "m_parent",
- channel: {
- id: "ch_thread",
- name: "New thread",
- type: "thread",
- createdAt: "2026-07-03T00:00:00.000Z",
- },
- }
- capturedOnMessage!(event)
-
- const cache = capturedQueryClient.getQueryData<{
- pages: { messages: { id: string; thread?: { id: string; name: string; messageCount: number } }[] }[]
- }>(communityKeys.channelMessages("ch_parent"))
- expect(cache?.pages[0].messages).toEqual([])
- const overlay = getMessageOverlay({ kind: "channel", id: "ch_parent", serverId: "s1" })
- expect(overlay.liveById.get("m_parent")?.thread).toEqual({
- id: "ch_thread",
- name: "New thread",
- messageCount: 0,
- })
- })
-
- it("child_create then message.create invalidates and preserves the enriched forum card", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_parent" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
- const parentMessagesKey = communityKeys.channelMessages("ch_parent")
- capturedQueryClient.setQueryData(parentMessagesKey, {
- pages: [{ messages: [], hasMore: false }],
- pageParams: [null],
- })
+ const setSpy = vi.spyOn(capturedQueryClient, "setQueryData")
const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const event: CommunityChildChannelCreate = {
- type: "community:channel.child_create",
- parentChannelId: "ch_parent",
- parentMessageId: "m_parent",
- channel: {
- id: "ch_thread",
- name: "New thread",
- type: "thread",
- createdAt: "2026-07-03T00:00:00.000Z",
- },
- }
-
- capturedOnMessage!(event)
- expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: parentMessagesKey })
-
- capturedQueryClient.setQueryData(parentMessagesKey, {
- pages: [{
- messages: [{
- id: "m_parent",
- content: "hello",
- thread: { id: "ch_thread", name: "New thread", messageCount: 0 },
- }],
- hasMore: false,
- }],
- pageParams: [null],
- })
- capturedOnMessage!(messageCreate("ch_parent", "m_parent"))
-
- const cache = capturedQueryClient.getQueryData<{
- pages: { messages: { id: string; thread?: { id: string } }[] }[]
- }>(parentMessagesKey)
- expect(cache?.pages[0].messages).toHaveLength(1)
- expect(cache?.pages[0].messages[0].thread?.id).toBe("ch_thread")
- })
-
- it("child_update still applies the reported messageCount unchanged", async () => {
- await mountHook()
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_parent"), {
- pages: [
- {
- messages: [
- {
- id: "m_parent",
- content: "hello",
- thread: { id: "ch_thread", name: "old", messageCount: 0 },
- },
- ],
- hasMore: false,
- },
- ],
- pageParams: [null],
- })
-
- const event: CommunityChildChannelUpdate = {
- type: "community:channel.child_update",
- parentChannelId: "ch_parent",
- channelId: "ch_thread",
- changes: { messageCount: 5 },
- }
- capturedOnMessage!(event)
-
- const cache = capturedQueryClient.getQueryData<{
- pages: { messages: { thread?: { messageCount: number } }[] }[]
- }>(communityKeys.channelMessages("ch_parent"))
- expect(cache?.pages[0].messages[0].thread?.messageCount).toBe(5)
- })
-
- it("child_update removes archived sidebar rows and invalidates on reopen", async () => {
- await mountHook()
- const key = communityKeys.forumSidebarThreadsView("s1", null)
- capturedQueryClient.setQueryData(key, forumSidebarFixture(["ch_thread"]))
-
- capturedOnMessage!({
- type: "community:channel.child_update",
- parentChannelId: "forum_1",
- channelId: "ch_thread",
- changes: { archived: true },
- } satisfies CommunityChildChannelUpdate)
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)?.threads).toEqual([])
-
- capturedOnMessage!({
- type: "community:channel.child_update",
- parentChannelId: "forum_1",
- channelId: "ch_thread",
- changes: { archived: false },
- } satisfies CommunityChildChannelUpdate)
- expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
- })
-
- it("child_update keeps newer thread fields from the current base row when refreshing fallback", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("s1")
- const scope = { kind: "channel" as const, id: "ch_parent", serverId: "s1" }
- useMessageStreamStore.getState().dispatch(scope, {
- type: "wsMessage",
- message: {
- id: "m_parent",
- seq: 1,
- type: "chat",
- authorId: "u1",
- authorName: "Alice",
- content: "hello",
- createdAt: "2026-08-06T00:00:00.000Z",
- thread: {
- id: "ch_thread",
- name: "fallback",
- messageCount: 1,
- lastReplyAt: "2026-08-06T00:00:01.000Z",
- },
- },
- })
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_parent"), {
- pages: [{
- messages: [{
- id: "m_parent",
- seq: 1,
- type: "chat",
- authorId: "u1",
- authorName: "Alice",
- content: "hello",
- createdAt: "2026-08-06T00:00:00.000Z",
- thread: {
- id: "ch_thread",
- name: "base",
- messageCount: 2,
- lastReplyAt: "2026-08-06T00:00:02.000Z",
- },
- }],
- hasMore: false,
- }],
- pageParams: [null],
- })
-
- capturedOnMessage!({
- type: "community:channel.child_update",
- parentChannelId: "ch_parent",
- channelId: "ch_thread",
- changes: { messageCount: 5 },
- } satisfies CommunityChildChannelUpdate)
-
- expect(getMessageOverlay(scope).liveById.get("m_parent")?.thread).toEqual({
- id: "ch_thread",
- name: "base",
- messageCount: 5,
- lastReplyAt: "2026-08-06T00:00:02.000Z",
- })
+ capturedOnMessage!({ type: "task.updated", taskId: "t_1" })
+ capturedOnMessage!({ type: "community:unknown", serverId: "srv_1" })
+ expect(setSpy).not.toHaveBeenCalled()
+ expect(invalidateSpy).not.toHaveBeenCalled()
})
})
-// ── Regression #5 — typing.start focus guard (DM leak) ──────────────────
-describe("useCommunityWs — typing.start honours focus (no DM leak)", () => {
- it("does NOT surface a DM-only typing.start when the viewer is focused on a channel", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
-
- const event: CommunityTypingStart = {
- type: "community:typing.start",
- channelId: "dm_other",
- userId: "u_other",
- }
- capturedOnMessage!(event)
-
- // Focus is on ch_1, so the unfocused DM channel's typing.start is dropped
- // entirely — no scope gains a typer.
- const state = useCommunityStore.getState()
- expect(state.typingByScope.get("dm:dm_other")).toBeUndefined()
- expect(state.typingByScope.get("ch:dm_other")).toBeUndefined()
- expect(state.typingByScope.get("ch:ch_1")).toBeUndefined()
+describe("useCommunityWs — public helper contracts", () => {
+ it("returns void after mounting the single root transport", async () => {
+ expect(await mountHook({ viewerUserId: "u_viewer" })).toBeUndefined()
})
- it("does surface a channel typing.start when the viewer is focused on that channel", async () => {
- await mountHook()
+ it("free subscribe/unsubscribe helpers preserve then clear both subscription slots", async () => {
+ const { communityWsSubscribe, communityWsUnsubscribe } = await import("./use-community-ws")
const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
+ const target = { channelId: "ch_contract", dmConversationId: "dm_contract" }
- const event: CommunityTypingStart = {
- type: "community:typing.start",
- channelId: "ch_1",
- userId: "u_other",
- }
- capturedOnMessage!(event)
+ communityWsSubscribe(target)
+ expect(useCommunityStore.getState().subscription).toEqual(target)
- expect([...(useCommunityStore.getState().typingByScope.get("ch:ch_1")?.keys() ?? [])]).toEqual([
- "u_other",
- ])
+ communityWsUnsubscribe()
+ expect(useCommunityStore.getState().subscription.channelId).toBeUndefined()
+ expect(useCommunityStore.getState().subscription.dmConversationId).toBeUndefined()
})
- it("stores the name the typing event carries (fixes 'Unknown member' when the typer isn't in the loaded roster)", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook()
-
- const event: CommunityTypingStart = {
- type: "community:typing.start",
- channelId: "ch_1",
- userId: "u_other",
- name: "Alice",
- discriminator: "0001",
- }
- capturedOnMessage!(event)
+ it("free typing helpers no-op before mount, throttle, and send again after reset", async () => {
+ const { communityWsResetTypingThrottle, communityWsSendTyping } = await import("./use-community-ws")
+ const target = { channelId: "ch_typing_contract" }
- // The name rides the event → the consumer renders it directly, no roster
- // lookup, so a typer outside the loaded roster page is no longer "Unknown".
- expect(useCommunityStore.getState().typingByScope.get("ch:ch_1")?.get("u_other")).toBe("Alice")
- })
+ communityWsSendTyping(target)
+ expect(getStableSend()).not.toHaveBeenCalled()
- it("stores null when the typing event carries no name (older server → consumer falls back to roster)", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
await mountHook()
-
- capturedOnMessage!({
- type: "community:typing.start",
- channelId: "ch_1",
- userId: "u_other",
- } as CommunityTypingStart)
-
- expect(useCommunityStore.getState().typingByScope.get("ch:ch_1")?.get("u_other")).toBeNull()
- })
-})
-
-// ── Typing scope isolation (per-conversation, no cross-leak) ────────────────
-describe("useCommunityWs — typing state is scoped per conversation", () => {
- it("a DM typer lands only in the DM scope, never in a channel scope", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- // Viewer is focused on the DM when the peer starts typing.
- useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook({ viewerUserId: "u_me" })
-
- // A DM is a channel — typing arrives as `typing.start` keyed by the DM's
- // channel id. The scope key resolves to `dm:` because the subscription's
- // `dmConversationId` slot holds that channel id.
- capturedOnMessage!({
+ flushEffects()
+ const send = getStableSend()
+ communityWsSendTyping(target)
+ communityWsSendTyping(target)
+ expect(send).toHaveBeenCalledOnce()
+ expect(send).toHaveBeenNthCalledWith(1, {
type: "community:typing.start",
- channelId: "dm_1",
- userId: "u_peer",
+ channelId: "ch_typing_contract",
})
- const state = useCommunityStore.getState()
- // The typer is confined to dm:dm_1 — a channel view reading ch:* sees nothing.
- expect([...(state.typingByScope.get("dm:dm_1")?.keys() ?? [])]).toEqual(["u_peer"])
- expect(state.typingByScope.get("ch:dm_1")).toBeUndefined()
- // The 8s timer is keyed by (scope, user), not user alone.
- expect(state.typingTimers.has("dm:dm_1|u_peer")).toBe(true)
- })
-
- it("bot DM reply (message.create on a DM channel) clears the DM pill, in the dm: scope", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ dmConversationId: "dm_bot" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook({ viewerUserId: "u_me" })
-
- // Bot is "typing" in the DM (typing.start on the DM channel).
- capturedOnMessage!({
+ communityWsResetTypingThrottle(target)
+ communityWsSendTyping(target)
+ expect(send).toHaveBeenCalledTimes(2)
+ expect(send).toHaveBeenNthCalledWith(2, {
type: "community:typing.start",
- channelId: "dm_bot",
- userId: "u_bot",
- })
- expect([...(useCommunityStore.getState().typingByScope.get("dm:dm_bot")?.keys() ?? [])]).toEqual([
- "u_bot",
- ])
-
- // Its reply arrives as message.create on the same DM channel. The scope key
- // must resolve to dm:dm_bot (via the subscription), clearing the pill — not
- // leak into a ch: bucket.
- capturedOnMessage!({
- type: "community:message.create",
- channelId: "dm_bot",
- message: {
- id: "m_bot_reply",
- authorId: "u_bot",
- authorName: "bot",
- content: "done",
- type: "chat",
- seq: 1,
- createdAt: "2026-07-03T00:00:00.000Z",
- },
- } as CommunityMessageCreate)
-
- const state = useCommunityStore.getState()
- expect(state.typingByScope.get("dm:dm_bot")).toBeUndefined()
- expect(state.typingByScope.get("ch:dm_bot")).toBeUndefined()
- expect(state.typingTimers.has("dm:dm_bot|u_bot")).toBe(false)
- })
-})
-
-// ── channel.delete invalidates the parent forum list (post deletion) ────────
-describe("useCommunityWs — channel.delete refreshes the parent forum feed", () => {
- it("invalidates the parent's message feed + threads list when parentChannelId is present", async () => {
- await mountHook()
- const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const allKey = communityKeys.channelMessages("forum_1")
- const bugKey = [...allKey, "tag", "bug"] as const
- const page = {
- pages: [{ messages: [{ id: "opener_1", thread: { id: "post_1" } }], hasMore: false }],
- pageParams: [null],
- }
- capturedQueryClient.setQueryData(allKey, page)
- capturedQueryClient.setQueryData(bugKey, page)
-
- const event: CommunityChannelDelete = {
- type: "community:channel.delete",
- serverId: "srv_1",
- channelId: "post_1",
- parentChannelId: "forum_1",
- }
- capturedOnMessage!(event)
-
- const invalidatedKeys = invalidateSpy.mock.calls.map((c) => JSON.stringify(c[0]?.queryKey))
- expect(invalidatedKeys).toContain(JSON.stringify(communityKeys.channelMessages("forum_1")))
- expect(invalidatedKeys).toContain(JSON.stringify(communityKeys.threads("forum_1")))
- expect(capturedQueryClient.getQueryData<{ pages: { messages: unknown[] }[] }>(allKey)?.pages[0].messages).toHaveLength(0)
- expect(capturedQueryClient.getQueryData<{ pages: { messages: unknown[] }[] }>(bugKey)?.pages[0].messages).toHaveLength(0)
- })
-
- it("does not throw and still evicts own caches when parentChannelId is absent (legacy event)", async () => {
- await mountHook()
- // Seed the deleted channel's own message cache so we can assert eviction.
- capturedQueryClient.setQueryData(communityKeys.channelMessages("post_1"), { pages: [], pageParams: [] })
- const removeSpy = vi.spyOn(capturedQueryClient, "removeQueries")
-
- const event: CommunityChannelDelete = {
- type: "community:channel.delete",
- serverId: "srv_1",
- channelId: "post_1",
- }
- expect(() => capturedOnMessage!(event)).not.toThrow()
-
- const removedKeys = removeSpy.mock.calls.map((c) => JSON.stringify(c[0]?.queryKey))
- expect(removedKeys).toContain(JSON.stringify(communityKeys.channelMessages("post_1")))
- })
-})
-
-describe("useCommunityWs — message edit refreshes forum opener summary", () => {
- it("invalidates the parent thread list for an opener edit, but not for an ordinary reply", async () => {
- await mountHook()
- const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const opener: CommunityMessageEdited = {
- type: "community:message.edited",
- channelId: "post_1",
- messageId: "opener_1",
- content: "new title",
- parentChannelId: "forum_1",
- }
- capturedQueryClient.setQueryData(communityKeys.message("opener_1"), {
- id: "opener_1",
- content: "old title",
- })
- const allKey = communityKeys.channelMessages("forum_1")
- const bugKey = [...allKey, "tag", "bug"] as const
- const forumPage = { pages: [{ messages: [{ id: "opener_1", content: "old title" }] }], pageParams: [null] }
- capturedQueryClient.setQueryData(allKey, forumPage)
- capturedQueryClient.setQueryData(bugKey, forumPage)
- const sidebarKey = communityKeys.forumSidebarThreadsView("s1", null)
- capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture())
- capturedOnMessage!(opener)
- expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: communityKeys.channelMessages("forum_1") })
- expect(capturedQueryClient.getQueryState(allKey)?.isInvalidated).toBe(true)
- expect(capturedQueryClient.getQueryState(bugKey)?.isInvalidated).toBe(true)
- expect(capturedQueryClient.getQueryData<{ pages: { messages: { content: string }[] }[] }>(allKey)?.pages[0].messages[0].content).toBe("new title")
- expect(capturedQueryClient.getQueryData<{ pages: { messages: { content: string }[] }[] }>(bugKey)?.pages[0].messages[0].content).toBe("new title")
- expect(capturedQueryClient.getQueryData<{ content: string }>(communityKeys.message("opener_1"))?.content).toBe("new title")
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(sidebarKey)?.threads[0].title)
- .toBe("new title")
-
- invalidateSpy.mockClear()
- capturedOnMessage!({
- type: "community:message.edited",
- channelId: "post_1",
- messageId: "reply_1",
- content: "edited reply",
- } satisfies CommunityMessageEdited)
- expect(invalidateSpy).not.toHaveBeenCalled()
- })
-})
-
-// ── #3 — WS message.create MUST NOT auto-mark-read ─────────────────────────
-// The IntersectionObserver in `useChannelWatermark` is authoritative: the
-// read pointer only advances when a message actually becomes visible in the
-// viewport. If the user is scrolled up reading history, a WS-delivered new
-// message must NOT touch the pointer — that's the whole point of the fix.
-describe("useCommunityWs — does NOT auto-mark-read on WS message.create", () => {
- it("does NOT call markRead when a foreign-authored message lands in the focused channel", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_focused" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook({ viewerUserId: "u_me" })
-
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_focused"), {
- pages: [{ messages: [], hasMore: false }],
- pageParams: [null],
- })
-
- const event: CommunityMessageCreate = {
- type: "community:message.create",
- channelId: "ch_focused",
- message: {
- id: "m_1",
- authorId: "u_someone_else",
- authorName: "them",
- content: "hi",
- seq: 1,
- createdAt: "2026-07-03T00:00:00.000Z",
- },
- }
- capturedOnMessage!(event)
-
- expect(markReadMutate).not.toHaveBeenCalled()
- })
-
- it("does NOT call markRead when the message is authored by the viewer", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_focused" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook({ viewerUserId: "u_me" })
-
- const event: CommunityMessageCreate = {
- type: "community:message.create",
- channelId: "ch_focused",
- message: {
- id: "m_1",
- authorId: "u_me",
- authorName: "me",
- content: "hi",
- seq: 1,
- createdAt: "2026-07-03T00:00:00.000Z",
- },
- }
- capturedOnMessage!(event)
-
- expect(markReadMutate).not.toHaveBeenCalled()
- })
-
- it("does NOT call markRead for a DM message.create either", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
- refCounter = 0
- stateCounter = 0
- callbackCounter = 0
- await mountHook({ viewerUserId: "u_me" })
-
- const event: CommunityMessageCreate = {
- type: "community:message.create",
- channelId: "dm_1",
- message: {
- id: "dm_m_1",
- authorId: "u_a",
- authorName: "a",
- content: "hi",
- type: "chat",
- seq: 1,
- createdAt: "2026-07-03T00:00:00.000Z",
- },
- }
- capturedOnMessage!(event)
-
- expect(markReadMutate).not.toHaveBeenCalled()
- })
-})
-
-// ── Regression #8 — server.update explicit-null icon clears the field ───
-describe("useCommunityWs — server.update icon removal", () => {
- it("clears icon when changes.icon is null (does not fall back to the prior icon)", async () => {
- await mountHook()
- capturedQueryClient.setQueryData(communityKeys.server("srv_1"), {
- id: "srv_1",
- name: "n",
- description: "d",
- icon: "https://cdn/x.png",
- ownerId: "u_1",
- categories: [],
+ channelId: "ch_typing_contract",
})
- const event: CommunityServerUpdate = {
- type: "community:server.update",
- serverId: "srv_1",
- changes: { icon: null },
- }
- capturedOnMessage!(event)
- const detail = capturedQueryClient.getQueryData<{ icon: string | null }>(
- communityKeys.server("srv_1"),
- )
- expect(detail?.icon).toBeNull()
- })
-})
-
-// ── Regression #10 — server.delete resets focused-server pointers ───────
-describe("useCommunityWs — server.delete resets store when focused server dies", () => {
- it("clears currentServerId + currentChannelId if the deleted server is currently focused", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_doomed")
- useCommunityStore.getState().setCurrentChannelId("ch_1")
-
- const event: CommunityServerDelete = {
- type: "community:server.delete",
- serverId: "srv_doomed",
- }
- capturedOnMessage!(event)
-
- expect(useCommunityStore.getState().currentServerId).toBeNull()
- expect(useCommunityStore.getState().currentChannelId).toBeNull()
- })
-
- it("does NOT touch the store when a different server is deleted", async () => {
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_active")
- useCommunityStore.getState().setCurrentChannelId("ch_1")
-
- const event: CommunityServerDelete = {
- type: "community:server.delete",
- serverId: "srv_other",
- }
- capturedOnMessage!(event)
-
- expect(useCommunityStore.getState().currentServerId).toBe("srv_active")
- expect(useCommunityStore.getState().currentChannelId).toBe("ch_1")
})
})
-// ── "stuck offline" fix — resync machines on WS reconnect ───────────────
-describe("useCommunityWs — resyncs machines on WS reconnect", () => {
- it("invalidates communityKeys.machines() when the captured onReconnect fires", async () => {
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
-
- expect(capturedOnReconnect).not.toBeNull()
- capturedOnReconnect!()
-
- expect(
- spy.mock.calls.some((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.includes("machines")
- }),
- ).toBe(true)
- })
-
- it("invalidates the focused channel's messages + inbox on reconnect, but NOT the read-state snapshot", async () => {
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "ch_focus" })
-
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
-
- expect(capturedOnReconnect).not.toBeNull()
- capturedOnReconnect!()
-
- const invalidatedKeys = spy.mock.calls.map(
- (c) => c[0]?.queryKey as unknown[] | undefined,
- )
- // Focused channel messages — a legitimate top-up refetch that keeps data.
- expect(
- invalidatedKeys.some(
- (k) =>
- Array.isArray(k) &&
- k[0] === "community" &&
- k[1] === "channel" &&
- k[2] === "ch_focus" &&
- k[3] === "messages",
- ),
- ).toBe(true)
- // Read-state snapshot MUST NOT be invalidated: the snapshot hook latches
- // its first value (gcTime: 0, frozen ref) so a refetch can't move the
- // "New" divider — it only flips `isFetching` back to true, which the
- // channel page reads as loading and flashes a second skeleton mid-mount
- // (the "skeleton → content → skeleton → top hero" refresh bug). See
- // `handleReconnect`'s comment in use-community-ws.ts.
- expect(
- invalidatedKeys.some(
- (k) =>
- Array.isArray(k) &&
- k[0] === "community" &&
- k[1] === "channel" &&
- k[2] === "ch_focus" &&
- k[3] === "read-state-snapshot",
- ),
- ).toBe(false)
- // Inbox
- expect(
- invalidatedKeys.some(
- (k) => Array.isArray(k) && k[0] === "community" && k[1] === "inbox",
- ),
- ).toBe(true)
- })
-
- it("re-seeds the rail list + open server's detail on reconnect (inbox-dot-ws-driven ②)", async () => {
- // Sidebar dots + rail mention badges are now driven by the live
- // `unread.bump` patch, with no switch-refetch backing them. A bump dropped
- // during the socket gap would leave them stale, so reconnect must re-seed
- // both — else the cross-server dot fix silently rots after any disconnect.
- await mountHook()
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
-
- // handleReconnect reads currentServerId via getState() at call time.
- expect(capturedOnReconnect).not.toBeNull()
- capturedOnReconnect!()
-
- const invalidatedKeys = spy.mock.calls.map(
- (c) => c[0]?.queryKey as unknown[] | undefined,
- )
- // Rail LIST = communityKeys.servers() = ["community","servers"] (length 2).
- expect(
- invalidatedKeys.some(
- (k) => Array.isArray(k) && k.length === 2 && k[0] === "community" && k[1] === "servers",
- ),
- ).toBe(true)
- // Open server's DETAIL = communityKeys.server(id) = ["community","servers",id].
- expect(
- invalidatedKeys.some(
- (k) =>
- Array.isArray(k) &&
- k[0] === "community" &&
- k[1] === "servers" &&
- k[2] === "srv_open",
- ),
- ).toBe(true)
- })
-
- it("invalidates the focused DM's messages on reconnect, but NOT its read-state snapshot", async () => {
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ dmConversationId: "dm_focus" })
-
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
-
- expect(capturedOnReconnect).not.toBeNull()
- capturedOnReconnect!()
-
- const invalidatedKeys = spy.mock.calls.map(
- (c) => c[0]?.queryKey as unknown[] | undefined,
- )
- expect(
- invalidatedKeys.some(
- (k) =>
- Array.isArray(k) &&
- k[0] === "community" &&
- k[1] === "dm" &&
- k[2] === "dm_focus" &&
- k[3] === "messages",
- ),
- ).toBe(true)
- // Read-state snapshot MUST NOT be invalidated — same rationale as the
- // channel case (mirrors `useChannelReadStateSnapshot`'s freeze contract).
- expect(
- invalidatedKeys.some(
- (k) =>
- Array.isArray(k) &&
- k[0] === "community" &&
- k[1] === "dm" &&
- k[2] === "dm_focus" &&
- k[3] === "read-state-snapshot",
- ),
- ).toBe(false)
- })
-
- it("only invalidates the focused scope — no channel invalidation when only a DM is focused", async () => {
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ dmConversationId: "dm_focus" })
-
+describe("useCommunityWs — double-mount detection", () => {
+ it("owns exactly one useUserWs call for one hook mount", async () => {
await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ expect(useUserWsCallCount).toBe(1)
+ expect(capturedOnMessage).not.toBeNull()
expect(capturedOnReconnect).not.toBeNull()
- capturedOnReconnect!()
-
- const invalidatedKeys = spy.mock.calls.map(
- (c) => c[0]?.queryKey as unknown[] | undefined,
- )
- // No channel-scoped message invalidation should have fired.
- expect(
- invalidatedKeys.some(
- (k) => Array.isArray(k) && k[1] === "channel" && k[3] === "messages",
- ),
- ).toBe(false)
+ expect(capturedUseUserWsOptions?.requestDaemonStatusOnAuth).toBe(false)
})
-})
-// ── Regression #15 — double-mount guard warns ───────────────────────────
-describe("useCommunityWs — double-mount detection", () => {
it("emits console.warn when a second instance mounts with a different send", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => { })
try {
@@ -2307,13 +96,10 @@ describe("useCommunityWs — double-mount detection", () => {
flushEffects()
// Simulate a second, independent hook site returning a different `send`
// by swapping the shared stub before the second mount.
- stableSend = vi.fn()
+ setStableSend(vi.fn())
// Reset ref counters so the shim hands out fresh refs (mimics a second
// hook site — not a re-render of the first).
- refs = new Map()
- refCounter = 0
- callbackMemo = new Map()
- callbackCounter = 0
+ resetHookInstance()
await mountHook()
flushEffects()
expect(
@@ -2332,10 +118,7 @@ describe("useCommunityWs — double-mount detection", () => {
await mountHook()
flushEffects()
// Re-mount with the SAME stableSend — should be a no-op for the guard.
- refs = new Map()
- refCounter = 0
- callbackMemo = new Map()
- callbackCounter = 0
+ resetHookInstance()
await mountHook()
flushEffects()
expect(
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index b0ad3c3ad..dc76a0975 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -1,74 +1,64 @@
"use client"
import { useCallback, useEffect, useRef } from "react"
-import { useQueryClient, type InfiniteData } from "@tanstack/react-query"
+import { useQueryClient } from "@tanstack/react-query"
import { useUserWs } from "@/lib/use-user-ws"
import { useCommunityStore } from "@/stores/community"
-import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
import { useCommunityWsStore } from "@/stores/community/ws"
import { communityKeys } from "@/lib/query-keys"
import {
- patchCacheJoin,
- patchCacheLeave,
- patchCacheUpdate,
- type MembersEnvelope,
-} from "@/hooks/community/use-server-members"
-import type { MessagesPage } from "@/hooks/community/use-messages"
-import type {
- CommunityWsEvent,
- CommunityMessageCreate,
- CommunityReactionAdd,
- CommunityReactionRemove,
- CommunityMachineSummary,
- CommunityTypingStart,
- CommunityPresenceUpdate,
- CommunityChildChannelCreate,
- CommunityChildChannelUpdate,
- CommunityMemberJoin,
- CommunityMemberLeave,
- CommunityMemberUpdate,
- CommunityChannelCreate,
- CommunityChannelUpdate,
- CommunityChannelDelete,
- CommunityChannelReorder,
- CommunityPinAdd,
- CommunityPinRemove,
- CommunityFriendRequest,
- CommunityFriendAccept,
- CommunityFriendReject,
- CommunityFriendRemove,
- CommunityFriendBlock,
- CommunityServerUpdate,
- CommunityServerDelete,
- CommunityCategoryCreate,
- CommunityCategoryUpdate,
- CommunityCategoryDelete,
- CommunityCategoryReorder,
- CommunityMentionCreate,
- CommunityMachineCreated,
- CommunityMachineStatus,
- CommunityMachineUpdated,
- CommunityMachineRemoved,
-} from "@alook/shared"
-import { isCommunityEvent, TYPING_INDICATOR_TIMEOUT_MS, TYPING_INDICATOR_THROTTLE_MS } from "@alook/shared"
-import type { Msg } from "@/components/community/_types"
-import { avatarInitial } from "@/lib/community/avatar"
-import { projectCommunityMessageCreate } from "@/lib/community/message-wire"
-import type { CanonicalMessage } from "@/lib/community/message-stream"
-import type { MachinesResponse } from "@/hooks/community/use-machines"
-import type { ServersResponse, ServerDetail } from "@/hooks/community/use-servers"
-import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
+ handleMessageCreate,
+ handleMessageEdited,
+ handleMessageUpdated,
+ handlePinEvent,
+ handleReactionEvent,
+} from "@/hooks/community/community-ws/message-events"
+import {
+ handleTypingStart,
+ handleTypingStop,
+} from "@/hooks/community/community-ws/typing-events"
+import {
+ handleCategoryEvent,
+ handleChannelEvent,
+ handleChildChannelCreate,
+ handleChildChannelUpdate,
+ handleInviteCreate,
+ handleServerDelete,
+ handleServerUpdate,
+} from "@/hooks/community/community-ws/structure-tree-events"
+import {
+ handleChannelMemberEvent,
+ handleMemberJoin,
+ handleMemberLeave,
+ handleMemberUpdate,
+} from "@/hooks/community/community-ws/membership-events"
+import {
+ handleFriendEvent,
+ handleMentionCreate,
+ handleUnreadBump,
+} from "@/hooks/community/community-ws/social-events"
import {
- hasForumSidebarThread,
- patchForumSidebarActivity,
- patchForumSidebarTitle,
- patchForumSidebarUnread,
- recordForumSidebarChildUnread,
- removeForumSidebarThread,
- removeForumSidebarUnreadChild,
- setForumSidebarParentUnreadBase,
- type ForumSidebarQueryData,
-} from "@/hooks/community/use-forum-sidebar-threads"
+ handleBotAuditEvent,
+ handleMachineCreated,
+ handleMachineRemoved,
+ handleMachineStatus,
+ handleMachineUpdated,
+ handlePresenceUpdate,
+ handleStatusUpdate,
+} from "@/hooks/community/community-ws/presence-machine-events"
+import { reconcileCommunityWsReconnect } from "@/hooks/community/community-ws/reconnect"
+import type {
+ CommunityWsHandlerContext,
+ Subscription,
+ UseCommunityWsOptions,
+} from "@/hooks/community/community-ws/handler-context"
+import type { CommunityWsEvent } from "@alook/shared"
+import { isCommunityEvent, TYPING_INDICATOR_THROTTLE_MS } from "@alook/shared"
+
+export type {
+ Subscription,
+ UseCommunityWsOptions,
+} from "@/hooks/community/community-ws/handler-context"
/**
* Community WebSocket handler.
@@ -97,202 +87,8 @@ import {
// message burst.
const INBOX_INVALIDATE_DEBOUNCE_MS = 500
-// ── Types (kept for backwards compat with any lingering imports) ─────────
-
-export type Subscription = {
- // The focused regular channel/thread.
- channelId?: string
- // The focused DM's channel id. A DM is a channel now; this slot keeps its
- // name only to mark "the focused channel is a DM" so the handler routes its
- // events into the `dmMessages` cache and the `dm:` typing scope.
- dmConversationId?: string
-}
-
-/**
- * DEPRECATED callback shape retained until the God-context (`contexts/
- * community/context.tsx`) is deleted in Step 4. The primary integration path
- * now writes state directly into the query cache and Zustand stores; callers
- * subscribe via `useQuery` and receive updates through those channels.
- *
- * Passing callbacks still fires them (in addition to the cache patches) so
- * legacy consumers don't observe silent regressions during the migration.
- */
-export type CommunityWsCallbacks = {
- onMessage?: (event: CommunityMessageCreate) => void
- onAnyMessage?: (event: CommunityMessageCreate) => void
- onReaction?: (event: CommunityReactionAdd | CommunityReactionRemove) => void
- onTyping?: (event: CommunityTypingStart) => void
- onPresence?: (event: CommunityPresenceUpdate) => void
- onChildChannel?: (event: CommunityChildChannelCreate | CommunityChildChannelUpdate) => void
- onMember?: (event: CommunityMemberJoin | CommunityMemberLeave | CommunityMemberUpdate) => void
- onChannel?: (event: CommunityChannelCreate | CommunityChannelUpdate | CommunityChannelDelete | CommunityChannelReorder) => void
- onPin?: (event: CommunityPinAdd | CommunityPinRemove) => void
- onFriend?: (event: CommunityFriendRequest | CommunityFriendAccept | CommunityFriendReject | CommunityFriendRemove | CommunityFriendBlock) => void
- onServer?: (event: CommunityServerUpdate | CommunityServerDelete) => void
- onCategory?: (event: CommunityCategoryCreate | CommunityCategoryUpdate | CommunityCategoryDelete | CommunityCategoryReorder) => void
- onMention?: (event: CommunityMentionCreate) => void
- onMachine?: (event: CommunityMachineCreated | CommunityMachineStatus | CommunityMachineUpdated | CommunityMachineRemoved) => void
-}
-
-// ── Cache patch helpers ───────────────────────────────────────────────────
-
-type PageCache = InfiniteData<MessagesPage>
-
-/**
- * Patch every cached message authored by `userId` to the renamed
- * `authorName` — `authorName` is a snapshot field written at send time
- * (`communityMessage` doesn't store it; the live JOIN is `message.ts`'s
- * `authorName: user.name`), so nothing else updates already-loaded message
- * rows after a self-rename. Only touches rows that are actually cached in
- * this client (open/previously-open channels & DMs) — a channel never
- * loaded this session picks up the new name for free on its first real
- * fetch, since that IS the live JOIN.
- */
-function patchAuthorNameInCache(cache: PageCache | undefined, userId: string, newName: string): PageCache | undefined {
- if (!cache) return cache
- let touched = false
- const pages = cache.pages.map((p) => {
- if (!p.messages.some((m) => m.authorId === userId)) return p
- touched = true
- return {
- ...p,
- messages: p.messages.map((m) => (m.authorId === userId ? { ...m, authorName: newName } : m)),
- }
- })
- if (!touched) return cache
- return { ...cache, pages }
-}
-
-/**
- * Patch the `approval` payload of a single cached message — the client-side
- * effect of a `MESSAGE_UPDATED` event. The card re-renders in its new
- * state (approved/denied/superseded/waiting) without a refetch.
- */
-function patchApprovalInCache(
- cache: PageCache | undefined,
- messageId: string,
- approval: Msg["approval"],
-): PageCache | undefined {
- if (!cache) return cache
- let touched = false
- const pages = cache.pages.map((p) => {
- if (!p.messages.some((m) => m.id === messageId)) return p
- touched = true
- return {
- ...p,
- messages: p.messages.map((m) => (m.id === messageId ? { ...m, approval } : m)),
- }
- })
- if (!touched) return cache
- return { ...cache, pages }
-}
-
-function patchMessageContentInCache(cache: PageCache | undefined, messageId: string, content: string): PageCache | undefined {
- if (!cache) return cache
- let touched = false
- const pages = cache.pages.map((page) => ({
- ...page,
- messages: page.messages.map((message) => {
- if (message.id !== messageId) return message
- touched = true
- return { ...message, content }
- }),
- }))
- return touched ? { ...cache, pages } : cache
-}
-
-function removeThreadFromCache(cache: PageCache | undefined, threadId: string): PageCache | undefined {
- if (!cache) return cache
- let touched = false
- const pages = cache.pages.map((page) => {
- const messages = page.messages.filter((message) => message.thread?.id !== threadId)
- if (messages.length === page.messages.length) return page
- touched = true
- return { ...page, messages }
- })
- return touched ? { ...cache, pages } : cache
-}
-
-function applyReactionToCache(
- cache: PageCache | undefined,
- event: CommunityReactionAdd | CommunityReactionRemove,
- viewerUserId: string | null,
-): PageCache | undefined {
- if (!cache) return cache
- let touched = false
- const pages = cache.pages.map((p) => {
- if (!p.messages.some((m) => m.id === event.messageId)) return p
- touched = true
- return {
- ...p,
- messages: p.messages.map((message) =>
- message.id === event.messageId
- ? applyReactionToMessage(message, event, viewerUserId)
- : message),
- }
- })
- if (!touched) return cache
- return { ...cache, pages }
-}
-
-function applyReactionToMessage(
- message: Msg,
- event: CommunityReactionAdd | CommunityReactionRemove,
- viewerUserId: string | null,
-): Msg {
- const reactions = (message.reactions ?? []).map((reaction) => ({
- ...reaction,
- userIds: [...(reaction.userIds ?? [])],
- }))
- if (event.type === "community:reaction.add") {
- const existing = reactions.find((reaction) => reaction.emoji === event.emoji)
- if (existing) {
- if (!existing.userIds.includes(event.userId)) existing.userIds.push(event.userId)
- existing.count = existing.userIds.length
- if (viewerUserId && event.userId === viewerUserId) existing.me = true
- } else {
- reactions.push({
- emoji: event.emoji,
- count: 1,
- me: !!viewerUserId && event.userId === viewerUserId,
- userIds: [event.userId],
- })
- }
- } else {
- const index = reactions.findIndex((reaction) => reaction.emoji === event.emoji)
- if (index !== -1) {
- reactions[index].userIds = reactions[index].userIds.filter((id) => id !== event.userId)
- reactions[index].count = reactions[index].userIds.length
- if (viewerUserId && event.userId === viewerUserId) reactions[index].me = false
- if (reactions[index].count <= 0) reactions.splice(index, 1)
- }
- }
- return { ...message, reactions }
-}
-
-function findCachedMessage(cache: PageCache | undefined, messageId: string): Msg | undefined {
- for (const page of cache?.pages ?? []) {
- const message = page.messages.find((row) => row.id === messageId)
- if (message) return message
- }
- return undefined
-}
-
// ── Public hook ────────────────────────────────────────────────────────────
-/**
- * Optional args — the community feature needs to know the viewer's userId so
- * reactions from that user light up the "me" flag. Passing null keeps the
- * hook usable in places where the viewer identity isn't yet loaded.
- */
-export type UseCommunityWsOptions = CommunityWsCallbacks & {
- viewerUserId?: string | null
-}
-
-// Overload for the new call-site: `useCommunityWs()` with no args — the hook
-// runs cache reconciliation and returns `{ subscribe, unsubscribe, sendTyping }`.
-// The legacy signature `useCommunityWs({ onMessage, ... })` still works during
-// the God-context migration; callbacks fire in addition to cache patches.
// Module-level slot for the currently-active WS `send`. The root-mounted
// `useCommunityWs` writes into this on connect so free helpers below can
// dispatch typing events without needing to re-mount the hook (which would
@@ -348,13 +144,11 @@ export function communityWsResetTypingThrottle(target: { channelId: string }) {
useCommunityStore.getState().lastTypingSent.delete(key)
}
-export function useCommunityWs(options?: UseCommunityWsOptions) {
+export function useCommunityWs(options?: UseCommunityWsOptions): void {
const queryClient = useQueryClient()
const viewerUserIdRef = useRef<string | null>(options?.viewerUserId ?? null)
- const callbacksRef = useRef<CommunityWsCallbacks>(options ?? {})
useEffect(() => {
viewerUserIdRef.current = options?.viewerUserId ?? null
- callbacksRef.current = options ?? {}
})
// #3: the previous WS-driven auto-mark-read (a `useMarkChannelRead()` call
@@ -390,7 +184,6 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
const communityStore = useCommunityStore.getState()
const sub = communityStore.subscription
const wsStore = useCommunityWsStore.getState()
- const cbs = callbacksRef.current
// A DM is a channel now — every message/typing/reaction event carries a
// single `channelId`. The subscription still tracks two slots so the
// handler can route a DM channel's events into the `dmMessages` cache vs
@@ -401,979 +194,102 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
if (!e.channelId) return false
return e.channelId === sub.channelId || e.channelId === sub.dmConversationId
}
+ const context: CommunityWsHandlerContext = {
+ queryClient,
+ communityStore,
+ wsStore,
+ sub,
+ viewerUserIdRef,
+ matchesFocus,
+ scheduleInboxInvalidate,
+ }
switch (event.type) {
- // ── Message create ──────────────────────────────────────────────
- case "community:message.create": {
- const projected = projectCommunityMessageCreate(event.message)
- if (event.channelId === sub.channelId) {
- const serverId = useCommunityStore.getState().currentServerId
- if (serverId) {
- useMessageStreamStore.getState().dispatch(
- { kind: "channel", id: event.channelId, serverId },
- { type: "wsMessage", message: projected },
- )
- }
- }
- if (event.channelId === sub.dmConversationId) {
- useMessageStreamStore.getState().dispatch(
- { kind: "dm", id: event.channelId },
- { type: "wsMessage", message: projected },
- )
- }
- if (wsStore.hasSeenMessage(event.message.id)) return
- wsStore.markSeenMessage(event.message.id)
- // Sending a message is an implicit typing.stop for its author —
- // clear once we know this is a fresh message. Clearing before dedup
- // would also clear on WS-reconnect replays of stale messages,
- // briefly wiping a still-active heartbeat pill. Derive the scope
- // from whether this channelId is the focused DM channel (`dm:`) or a
- // regular channel (`ch:`) so the pill clears in the right bucket.
- clearTypingIndicator(typingScopeKey(event, sub), event.message.authorId)
-
- // Participation, not unread state, is the sidebar truth. A child
- // message reaches every notify member even when muted; use its
- // explicit server/parent metadata to re-rank a loaded row without a
- // GET, or refetch when the active post is currently absent/expired.
- if (event.serverId && event.parentChannelId) {
- const key = communityKeys.forumSidebarThreads(event.serverId)
- const cached = queryClient.getQueriesData<ForumSidebarQueryData>({ queryKey: key })
- const loaded = cached.some(([, data]) => hasForumSidebarThread(data, event.channelId))
- if (loaded) {
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: key },
- (data) => patchForumSidebarActivity(
- data,
- event.channelId,
- event.parentChannelId!,
- event.message.createdAt,
- ),
- )
- } else {
- void queryClient.invalidateQueries({ queryKey: key })
- }
- }
-
- // 1) A child channel enrolls its sender and mentioned users in its
- // member set server-side, so refresh an open child roster live.
- if (
- event.channelId === sub.channelId &&
- communityStore.currentChannelId === event.channelId &&
- communityStore.currentChannelMeta?.parentChannelId
- ) {
- void queryClient.invalidateQueries({
- queryKey: communityKeys.channelMembers(event.channelId),
- })
- }
-
- // 2) Every message.create — regardless of focus — schedules a
- // debounced inbox invalidation. Skip messages authored by the
- // viewer since they never affect their own unreads.
- const viewerId = viewerUserIdRef.current
- if (event.message.authorId !== viewerId) {
- scheduleInboxInvalidate()
- }
-
- // 3) Live channel-sidebar unread dot is NO LONGER flipped here.
- // Unread is per-recipient and mute-gated on the server now, so it
- // rides the dedicated `community:unread.bump` event (below) — a
- // muted (`nothing`/unmentioned-`mentions`) channel must NOT light
- // an unread dot even though its `message.create` still arrives
- // (mute ≠ blindness: content syncs, the badge does not).
-
- // Note: no auto-mark-read here. See #3 — the
- // IntersectionObserver in `useChannelWatermark` advances the
- // read pointer when a message actually becomes visible in the
- // viewport. If the user is scrolled up reading history, their
- // pointer must stay put; the WS handler cannot know whether the
- // incoming message is on screen.
-
- // Legacy callback fanout — cache patches above are authoritative.
- cbs.onAnyMessage?.(event)
- if (matchesFocus(event)) cbs.onMessage?.(event)
- return
- }
-
- // ── Per-user unread/badge signal ─────────────────────────────────
- // Mute-gated on the server (only recipients whose effective level
- // delivers get this), so the sidebar unread dot flips ONLY here — a
- // muted channel's `message.create` no longer lights it. Skip the
- // currently-subscribed channel (dot suppressed there anyway) and never
- // for the viewer's own sends (the server excludes the author, but guard
- // defensively).
- case "community:unread.bump": {
- const viewerId = viewerUserIdRef.current
- // `railChannelId` is the always-locatable fallback. A participating
- // forum child now has its own nested row, so prefer that row when it
- // is loaded; ordinary/expired children continue to light the parent.
- const railChannelId = event.railChannelId ?? event.channelId
- const targetServerId =
- event.serverId ?? useCommunityStore.getState().currentServerId
- const sidebarKey = targetServerId
- ? communityKeys.forumSidebarThreads(targetServerId)
- : null
- const hasChildSidebarRow = !!sidebarKey && event.channelId !== railChannelId &&
- queryClient.getQueriesData<ForumSidebarQueryData>({ queryKey: sidebarKey })
- .some(([, data]) => hasForumSidebarThread(data, event.channelId))
- const sidebarChannelId = hasChildSidebarRow ? event.channelId : railChannelId
- // Suppress the dot for the channel the viewer is actually looking at
- // (its unread clears on read anyway) — compare against the ROW being
- // lit, so a thread bump whose parent is open still suppresses.
- if (event.userId === viewerId && sidebarChannelId !== sub.channelId) {
- // Channel-tree dot: patch the RIGHT server's detail. `serverId`
- // (inbox-dot-ws-driven) lets an other-server message light its dot
- // — previously only the open server was patched, so cross-server
- // bumps never lit. Absent serverId (DM bump / older frame) → fall
- // back to the currently-open server (backward-compatible).
- if (hasChildSidebarRow && sidebarKey) {
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: sidebarKey },
- (data) => patchForumSidebarUnread(data, event.channelId, true),
- )
- recordForumSidebarChildUnread(
- queryClient,
- targetServerId!,
- railChannelId,
- event.channelId,
- true,
- )
- } else if (targetServerId) {
- if (event.channelId !== railChannelId) {
- recordForumSidebarChildUnread(
- queryClient,
- targetServerId,
- railChannelId,
- event.channelId,
- )
- } else {
- const hasChildFallback = setForumSidebarParentUnreadBase(
- queryClient,
- targetServerId,
- railChannelId,
- true,
- )
- if (!hasChildFallback) {
- queryClient.setQueryData<ServerDetail | undefined>(
- communityKeys.server(targetServerId),
- (cache) => patchChannelUnread(cache, railChannelId, true),
- )
- }
- }
- }
- // Rail mention badge: the rail row carries only a `mentions` count
- // (no separate unread dot — plain unread lives on the tree dot
- // above). So bump the rail badge ONLY for a mention, on the right
- // server row. Needs `serverId`; a DM/older frame without it can't
- // locate a rail row, so skip (the tree dot / inbox still reflect it).
- if (event.isMention && event.serverId) {
- const bumpServerId = event.serverId
- queryClient.setQueryData<ServersResponse | undefined>(
- communityKeys.servers(),
- (prev) =>
- prev
- ? {
- ...prev,
- servers: prev.servers.map((s) =>
- s.id === bumpServerId
- ? { ...s, mentions: s.mentions + 1 }
- : s,
- ),
- }
- : prev,
- )
- }
- }
- return
- }
-
- // ── Reactions ───────────────────────────────────────────────────
+ case "community:message.create":
+ return handleMessageCreate(event, context)
+ case "community:unread.bump":
+ return handleUnreadBump(event, context)
case "community:reaction.add":
- case "community:reaction.remove": {
- const viewerId = viewerUserIdRef.current
- // A reaction event carries only `channelId` with no channel-vs-DM
- // discriminator. A regular channel's cache lives under
- // `channelMessages(id)`, a DM channel's under `dmMessages(id)` — patch
- // both keys; the one that doesn't exist receives `undefined` and the
- // updater returns it, a harmless no-op.
- queryClient.setQueriesData<PageCache>(
- { queryKey: communityKeys.channelMessages(event.channelId) },
- (c) => applyReactionToCache(c, event, viewerId),
- )
- queryClient.setQueryData<PageCache>(
- communityKeys.dmMessages(event.channelId),
- (c) => applyReactionToCache(c, event, viewerId),
- )
- if (event.channelId === sub.channelId) {
- const serverId = useCommunityStore.getState().currentServerId
- if (serverId) {
- const scope = { kind: "channel" as const, id: event.channelId, serverId }
- const fallback = [...getMessageOverlay(scope).liveById.values()]
- .find((message) => message.id === event.messageId)
- if (fallback) {
- const cached = findCachedMessage(
- queryClient.getQueryData<PageCache>(communityKeys.channelMessages(event.channelId)),
- event.messageId,
- )
- const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback
- useMessageStreamStore.getState().dispatch(scope, {
- type: "liveRefreshed",
- message: applyReactionToMessage(source, event, viewerId) as CanonicalMessage,
- })
- }
- }
- }
- if (event.channelId === sub.dmConversationId) {
- const scope = { kind: "dm" as const, id: event.channelId }
- const fallback = [...getMessageOverlay(scope).liveById.values()]
- .find((message) => message.id === event.messageId)
- if (fallback) {
- const cached = findCachedMessage(
- queryClient.getQueryData<PageCache>(communityKeys.dmMessages(event.channelId)),
- event.messageId,
- )
- const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback
- useMessageStreamStore.getState().dispatch(scope, {
- type: "liveRefreshed",
- message: applyReactionToMessage(source, event, viewerId) as CanonicalMessage,
- })
- }
- }
- if (matchesFocus(event)) cbs.onReaction?.(event)
- return
- }
-
- // ── Pins ────────────────────────────────────────────────────────
+ case "community:reaction.remove":
+ return handleReactionEvent(event, context)
case "community:pin.add":
- case "community:pin.remove": {
- void queryClient.invalidateQueries({ queryKey: communityKeys.pins(event.channelId) })
- if (matchesFocus(event)) cbs.onPin?.(event)
- return
- }
-
- // ── Typing (channel / thread / DM — all keyed by channelId) ──────
- case "community:typing.start": {
- const userId = event.userId
- const viewerId = viewerUserIdRef.current
- if (viewerId && userId === viewerId) return
- // Focus check: only surface typing for the currently-viewed target.
- if (!matchesFocus(event)) return
- applyTypingIndicator(typingScopeKey(event, sub), userId, event.name ?? null)
- cbs.onTyping?.(event)
- return
- }
-
- // ── Typing stop — explicit clear (bot turn-end path) ────────────
- // Symmetric with typing.start: only clear when focused on the same
- // target so a stop for a different DM doesn't wipe the local pill.
- case "community:typing.stop": {
- const userId = event.userId
- const viewerId = viewerUserIdRef.current
- if (viewerId && userId === viewerId) return
- if (!matchesFocus(event)) return
- clearTypingIndicator(typingScopeKey(event, sub), userId)
- return
- }
-
- // ── Child threads ──────────────────────────────────────────────
+ case "community:pin.remove":
+ return handlePinEvent(event, context)
+ case "community:typing.start":
+ return handleTypingStart(event, context)
+ case "community:typing.stop":
+ return handleTypingStop(event, context)
case "community:channel.child_create":
- case "community:channel.child_update": {
- // Cheap invalidate for the child-thread lists. The parent
- // messages list also needs an update because the parent message's
- // thread indicator (`msg.thread`) changes — do a targeted
- // setQueryData patch when we know parentMessageId.
- void queryClient.invalidateQueries({
- queryKey: communityKeys.threads(event.parentChannelId),
- })
- if (event.type === "community:channel.child_create") {
- const parentMessagesKey = communityKeys.channelMessages(event.parentChannelId)
- const parentMessages = queryClient.getQueryData<PageCache>(parentMessagesKey)
- const openerCached = !!event.parentMessageId && parentMessages?.pages.some((page) =>
- page.messages.some((message) => message.id === event.parentMessageId),
- )
- if (event.parentMessageId) {
- queryClient.setQueriesData<PageCache>(
- { queryKey: parentMessagesKey },
- (cache) => {
- if (!cache) return cache
- let touched = false
- const pages = cache.pages.map((p) => {
- if (!p.messages.some((m) => m.id === event.parentMessageId)) return p
- touched = true
- return {
- ...p,
- messages: p.messages.map((m) =>
- m.id === event.parentMessageId
- ? {
- ...m,
- thread: {
- id: event.channel.id,
- name: event.channel.name,
- // #4: a freshly-created child channel has no
- // messages yet — `1` was a false claim that
- // the create event carried the first message
- // (it doesn't; the message arrives separately).
- messageCount: 0,
- },
- }
- : m,
- ),
- }
- })
- if (!touched) return cache
- return { ...cache, pages }
- },
- )
- const serverId = useCommunityStore.getState().currentServerId
- if (serverId) {
- const scope = { kind: "channel" as const, id: event.parentChannelId, serverId }
- const fallback = [...getMessageOverlay(scope).liveById.values()]
- .find((message) => message.id === event.parentMessageId)
- if (fallback) {
- const cached = findCachedMessage(
- queryClient.getQueryData<PageCache>(communityKeys.channelMessages(event.parentChannelId)),
- event.parentMessageId,
- )
- const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback
- useMessageStreamStore.getState().dispatch(scope, {
- type: "liveRefreshed",
- message: {
- ...source,
- thread: { id: event.channel.id, name: event.channel.name, messageCount: 0 },
- },
- })
- }
- }
- }
- if (event.parentMessageId && !openerCached) {
- void queryClient.invalidateQueries({ queryKey: parentMessagesKey })
- }
- } else {
- // child_update — sync counts/name on the parent message's thread
- // indicator if the update carries them.
- const changes = event.changes
- const sidebarServerId = useCommunityStore.getState().currentServerId
- if (sidebarServerId) {
- const sidebarKey = communityKeys.forumSidebarThreads(sidebarServerId)
- if (changes.archived === true) {
- removeForumSidebarUnreadChild(queryClient, sidebarServerId, event.channelId)
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: sidebarKey },
- (data) => removeForumSidebarThread(data, event.channelId),
- )
- } else if (changes.archived === false) {
- void queryClient.invalidateQueries({ queryKey: sidebarKey })
- } else if (changes.lastMessageAt) {
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: sidebarKey },
- (data) => patchForumSidebarActivity(
- data,
- event.channelId,
- event.parentChannelId,
- changes.lastMessageAt!,
- ),
- )
- }
- }
- if (changes.messageCount !== undefined || changes.name !== undefined) {
- queryClient.setQueriesData<PageCache>(
- { queryKey: communityKeys.channelMessages(event.parentChannelId) },
- (cache) => {
- if (!cache) return cache
- let touched = false
- const pages = cache.pages.map((p) => {
- if (!p.messages.some((m) => m.thread?.id === event.channelId)) return p
- touched = true
- return {
- ...p,
- messages: p.messages.map((m) =>
- m.thread?.id === event.channelId
- ? {
- ...m,
- thread: {
- ...m.thread,
- ...(changes.name !== undefined ? { name: changes.name } : {}),
- ...(changes.messageCount !== undefined
- ? { messageCount: changes.messageCount }
- : {}),
- },
- }
- : m,
- ),
- }
- })
- if (!touched) return cache
- return { ...cache, pages }
- },
- )
- const serverId = useCommunityStore.getState().currentServerId
- if (serverId) {
- const scope = { kind: "channel" as const, id: event.parentChannelId, serverId }
- const fallback = [...getMessageOverlay(scope).liveById.values()]
- .find((message) => message.thread?.id === event.channelId)
- if (fallback?.thread) {
- const cached = findCachedMessage(
- queryClient.getQueryData<PageCache>(communityKeys.channelMessages(event.parentChannelId)),
- fallback.id,
- )
- const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback
- useMessageStreamStore.getState().dispatch(scope, {
- type: "liveRefreshed",
- message: {
- ...source,
- thread: {
- ...(source.thread ?? fallback.thread),
- ...(changes.name !== undefined ? { name: changes.name } : {}),
- ...(changes.messageCount !== undefined ? { messageCount: changes.messageCount } : {}),
- },
- },
- })
- }
- }
- }
- }
- cbs.onChildChannel?.(event)
- return
- }
-
- // ── Server ──────────────────────────────────────────────────────
+ return handleChildChannelCreate(event, context)
+ case "community:channel.child_update":
+ return handleChildChannelUpdate(event, context)
case "community:server.update":
- case "community:server.delete": {
- if (event.type === "community:server.update") {
- queryClient.setQueryData<ServerDetail | undefined>(
- communityKeys.server(event.serverId),
- (prev) =>
- prev
- ? {
- ...prev,
- name: event.changes.name ?? prev.name,
- description: event.changes.description ?? prev.description,
- // #8: icon can be explicitly cleared (null). `??` treats
- // null the same as undefined, which would keep the old
- // icon after a removal — check `undefined` explicitly.
- icon:
- event.changes.icon !== undefined
- ? event.changes.icon
- : prev.icon,
- }
- : prev,
- )
- queryClient.setQueryData<ServersResponse | undefined>(
- communityKeys.servers(),
- (prev) =>
- prev
- ? {
- ...prev,
- servers: prev.servers.map((s) =>
- s.id === event.serverId
- ? {
- ...s,
- ...(event.changes.name ? { name: event.changes.name, initial: avatarInitial(event.changes.name) } : {}),
- ...(event.changes.icon !== undefined ? { icon: event.changes.icon ?? null } : {}),
- }
- : s,
- ),
- }
- : prev,
- )
- } else {
- // Refresh the rail LIST only (drop the deleted server). `exact`
- // so this doesn't cascade-refetch every other server's nested
- // detail subtree; the deleted server's own subtree is cleared by
- // the removeQueries below.
- void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })
- queryClient.removeQueries({ queryKey: communityKeys.server(event.serverId) })
- // #10: if the deleted server is the one the viewer is looking at,
- // the store pointers now dangle — reset them so the UI drops back
- // to a safe default instead of rendering a ghost server/channel.
- const store = useCommunityStore.getState()
- useMessageStreamStore.getState().removeServer(event.serverId)
- if (store.currentServerId === event.serverId) {
- store.setCurrentServerId(null)
- store.setCurrentChannelId(null)
- }
- }
- cbs.onServer?.(event)
- return
- }
-
- // ── Channels / categories → refetch the server detail ───────────
+ return handleServerUpdate(event, context)
+ case "community:server.delete":
+ return handleServerDelete(event, context)
case "community:channel.create":
case "community:channel.update":
case "community:channel.delete":
case "community:channel.reorder":
+ return handleChannelEvent(event, context)
case "community:category.create":
case "community:category.update":
case "community:category.delete":
- case "community:category.reorder": {
- // #3: on channel.delete, evict every channel-scoped cache before
- // invalidating the server. Without this the messages/pins/threads/
- // child-thread caches for the dead channel linger forever — a
- // subsequent same-id revive (rare, but the server can reuse ids)
- // would surface stale rows.
- if (event.type === "community:channel.delete") {
- removeForumSidebarUnreadChild(queryClient, event.serverId, event.channelId)
- useMessageStreamStore.getState().removeScope({
- kind: "channel",
- id: event.channelId,
- serverId: event.serverId,
- })
- queryClient.removeQueries({
- queryKey: communityKeys.channelMessages(event.channelId),
- })
- queryClient.removeQueries({
- queryKey: communityKeys.pins(event.channelId),
- })
- queryClient.removeQueries({
- queryKey: communityKeys.threads(event.channelId),
- })
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: communityKeys.forumSidebarThreads(event.serverId) },
- (data) => removeForumSidebarThread(data, event.channelId),
- )
- // When a child thread is deleted, refresh the
- // PARENT's list so the deleted card disappears from the feed on
- // every client. Absent on older events / top-level channels.
- if (event.parentChannelId) {
- queryClient.setQueriesData<PageCache>(
- { queryKey: communityKeys.channelMessages(event.parentChannelId) },
- (cache) => removeThreadFromCache(cache, event.channelId),
- )
- void queryClient.invalidateQueries({
- queryKey: communityKeys.channelMessages(event.parentChannelId),
- })
- void queryClient.invalidateQueries({
- queryKey: communityKeys.threads(event.parentChannelId),
- })
- }
- }
- if ("serverId" in event) {
- void queryClient.invalidateQueries({ queryKey: communityKeys.server(event.serverId) })
- }
- if (event.type.startsWith("community:channel.")) {
- cbs.onChannel?.(event as CommunityChannelCreate | CommunityChannelUpdate | CommunityChannelDelete | CommunityChannelReorder)
- } else {
- cbs.onCategory?.(event as CommunityCategoryCreate | CommunityCategoryUpdate | CommunityCategoryDelete | CommunityCategoryReorder)
- }
- return
- }
-
- // ── Channel membership (private channels) ────────────────────────
- // Re-run the viewer-scoped server tree so the sidebar gains/loses the
- // private channel. On REMOVE for the viewer, evict that channel's
- // scoped caches so no private content lingers locally (mirrors the
- // channel.delete eviction above).
+ case "community:category.reorder":
+ return handleCategoryEvent(event, context)
case "community:channel.member_add":
- case "community:channel.member_remove": {
- if (
- event.type === "community:channel.member_remove" &&
- event.userId === viewerUserIdRef.current
- ) {
- removeForumSidebarUnreadChild(queryClient, event.serverId, event.channelId)
- useMessageStreamStore.getState().removeScope({
- kind: "channel",
- id: event.channelId,
- serverId: event.serverId,
- })
- queryClient.removeQueries({ queryKey: communityKeys.channelMessages(event.channelId) })
- queryClient.removeQueries({ queryKey: communityKeys.pins(event.channelId) })
- queryClient.removeQueries({ queryKey: communityKeys.threads(event.channelId) })
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: communityKeys.forumSidebarThreads(event.serverId) },
- (data) => removeForumSidebarThread(data, event.channelId),
- )
- } else if (
- event.type === "community:channel.member_add" &&
- event.userId === viewerUserIdRef.current
- ) {
- void queryClient.invalidateQueries({
- queryKey: communityKeys.forumSidebarThreads(event.serverId),
- })
- }
- void queryClient.invalidateQueries({ queryKey: communityKeys.server(event.serverId) })
- // Refetch the channel roster so an open private-channel Members drawer
- // (and the manage-members dialog) reflect the add/remove live.
- void queryClient.invalidateQueries({ queryKey: communityKeys.channelMembers(event.channelId) })
- // The addable-members candidate pool is the complement of the roster —
- // a peer's add/remove changes it too, so an open add dialog doesn't
- // offer a just-added member (whose Add would 400) or hide a removed one.
- void queryClient.invalidateQueries({ queryKey: communityKeys.channelAddableMembers(event.channelId) })
- // A forum thread's "Add participant" emits this same MEMBER_ADD event —
- // its Members panel is the participant set, so refetch it too. No-op
- // for a plain channel (participants query disabled there).
- void queryClient.invalidateQueries({ queryKey: communityKeys.threadParticipants(event.channelId) })
- return
- }
-
- // ── Members ─────────────────────────────────────────────────────
+ case "community:channel.member_remove":
+ return handleChannelMemberEvent(event, context)
case "community:member.join":
+ return handleMemberJoin(event, context)
case "community:member.leave":
- case "community:member.update": {
- const key = communityKeys.members(event.serverId)
- if (event.type === "community:member.join") {
- queryClient.setQueryData<InfiniteData<MembersEnvelope> | undefined>(
- key,
- (cache) => patchCacheJoin(cache, event),
- )
- } else if (event.type === "community:member.leave") {
- queryClient.setQueryData<InfiniteData<MembersEnvelope> | undefined>(
- key,
- (cache) => patchCacheLeave(cache, event),
- )
- // If the leaver is the viewer (kick from another tab / owner
- // cascade), the viewer's server rail is stale — invalidate it
- // so the layout's eject effect can detect the drop and route
- // the user away from the now-forbidden URL.
- if (event.userId === viewerUserIdRef.current) {
- useMessageStreamStore.getState().removeServer(event.serverId)
- // Rail LIST only (the layout's eject effect reads it to route the
- // kicked viewer away). `exact` so a kick doesn't cascade-refetch
- // every server's nested detail subtree.
- void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })
- }
- } else {
- queryClient.setQueryData<InfiniteData<MembersEnvelope> | undefined>(
- key,
- (cache) => patchCacheUpdate(cache, event),
- )
- // A self-rename carries `userId` + `changes.nickname` — patch
- // every cached message list's `authorName` snapshot for that
- // author. A role-only change has no `userId`/`nickname`, so
- // this is a no-op for that case.
- if (event.userId && event.changes.nickname) {
- const userId = event.userId
- const newName = event.changes.nickname
- for (const cacheEntry of queryClient.getQueryCache().findAll({
- predicate: (q) =>
- q.queryKey[0] === "community"
- && (q.queryKey[1] === "channel" || q.queryKey[1] === "dm")
- && q.queryKey[3] === "messages",
- })) {
- queryClient.setQueryData<PageCache | undefined>(
- cacheEntry.queryKey,
- (cache) => patchAuthorNameInCache(cache, userId, newName),
- )
- }
- const streamState = useMessageStreamStore.getState()
- for (const entry of streamState.entries.values()) {
- if (entry.scope.kind === "channel" && entry.scope.serverId !== event.serverId) continue
- for (const message of entry.state.liveById.values()) {
- if (message.authorId !== userId) continue
- useMessageStreamStore.getState().dispatch(entry.scope, {
- type: "liveRefreshed",
- message: { ...message, authorName: newName },
- })
- }
- }
- }
- }
- // Membership just changed → the invite dialog's "friends who aren't
- // in this server" list is stale. Cheap invalidation because the
- // query is disabled unless the dialog is actually open.
- if (event.type !== "community:member.update") {
- void queryClient.invalidateQueries({
- queryKey: communityKeys.invitableFriends(event.serverId),
- })
- }
- cbs.onMember?.(event)
- return
- }
-
- // ── Friends ─────────────────────────────────────────────────────
+ return handleMemberLeave(event, context)
+ case "community:member.update":
+ return handleMemberUpdate(event, context)
+ case "community:invite.create":
+ return handleInviteCreate(event, context)
case "community:friend.request":
case "community:friend.accept":
case "community:friend.reject":
case "community:friend.remove":
- case "community:friend.block": {
- void queryClient.invalidateQueries({ queryKey: communityKeys.friends() })
- cbs.onFriend?.(event)
- return
- }
-
- // ── Message updated (friend-approval card state change) ──────────
- // Folded from the old `dm.message_updated` — keyed by `channelId` (the
- // DM's channel id). Patch the card's approval payload in the focused
- // DM cache so it re-renders in its new state without a refetch.
- case "community:message.updated": {
- if (event.channelId === sub.dmConversationId || event.channelId === sub.channelId) {
- queryClient.setQueryData<PageCache>(
- communityKeys.dmMessages(event.channelId),
- (c) => patchApprovalInCache(c, event.messageId, event.approval),
- )
- queryClient.setQueryData<PageCache>(
- communityKeys.channelMessages(event.channelId),
- (c) => patchApprovalInCache(c, event.messageId, event.approval),
- )
- }
- const overlayScopes = event.channelId === sub.dmConversationId
- ? [{ kind: "dm" as const, id: event.channelId }]
- : event.channelId === sub.channelId
- ? (() => {
- const serverId = useCommunityStore.getState().currentServerId
- return serverId
- ? [{ kind: "channel" as const, id: event.channelId, serverId }]
- : []
- })()
- : []
- for (const scope of overlayScopes) {
- const fallback = [...getMessageOverlay(scope).liveById.values()]
- .find((message) => message.id === event.messageId)
- if (!fallback) continue
- const key = scope.kind === "dm"
- ? communityKeys.dmMessages(event.channelId)
- : communityKeys.channelMessages(event.channelId)
- const cached = findCachedMessage(
- queryClient.getQueryData<PageCache>(key),
- event.messageId,
- )
- const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback
- useMessageStreamStore.getState().dispatch(scope, {
- type: "liveRefreshed",
- message: { ...source, approval: event.approval },
- })
- }
- // When a card resolves (accepted/denied/superseded), the friend graph
- // changed — invalidate friends + pending so the owner's lists reflect
- // it. This is the owner's only signal in the J2 tail (Alice's accept
- // dead-letters FRIEND_ACCEPT to the bot).
- if (event.approval.status !== "pending" || event.approval.waitingOn !== "you") {
- void queryClient.invalidateQueries({ queryKey: communityKeys.friends() })
- }
- return
- }
-
- case "community:message.edited": {
- queryClient.setQueryData<{ content: string }>(
- communityKeys.message(event.messageId),
- (message) => message ? { ...message, content: event.content } : message,
- )
- queryClient.setQueriesData<PageCache>(
- { queryKey: communityKeys.channelMessages(event.channelId) },
- (cache) => patchMessageContentInCache(cache, event.messageId, event.content),
- )
- queryClient.setQueryData<PageCache>(
- communityKeys.dmMessages(event.channelId),
- (cache) => patchMessageContentInCache(cache, event.messageId, event.content),
- )
- const streamStore = useMessageStreamStore.getState()
- for (const entry of streamStore.entries.values()) {
- if (entry.scope.id !== event.channelId) continue
- streamStore.dispatch(entry.scope, {
- type: "messageEdited",
- messageId: event.messageId,
- content: event.content,
- })
- }
- if (event.parentChannelId) {
- queryClient.setQueriesData<PageCache>(
- { queryKey: communityKeys.channelMessages(event.parentChannelId) },
- (cache) => patchMessageContentInCache(cache, event.messageId, event.content),
- )
- void queryClient.invalidateQueries({
- queryKey: communityKeys.channelMessages(event.parentChannelId),
- })
- const serverId = useCommunityStore.getState().currentServerId
- if (serverId) {
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: communityKeys.forumSidebarThreads(serverId) },
- (data) => patchForumSidebarTitle(data, event.channelId, event.content),
- )
- }
- }
- return
- }
-
- // ── Presence — no cache; write to WS store ──────────────────────
- case "community:presence.update": {
- useCommunityWsStore.getState().setPresence(event.userId, event.online)
- cbs.onPresence?.(event)
- return
- }
-
- // ── Status — no cache; write to WS store (same overlay pattern as
- // presence above, see plans/profile-card.md) ────────────────────
- case "community:status.update": {
- useCommunityWsStore.getState().setUserStatus(event.userId, event.statusEmoji, event.statusText)
- return
- }
-
- // ── Bot audit event — push into the bounded ring; the audit-log
- // hook filters + prepends into its React Query cache. ────────────
- case "community:bot.audit_event": {
- useCommunityWsStore.getState().pushBotAuditEvent({
- id: event.id,
- botId: event.botId,
- kind: event.kind,
- payload: event.payload,
- sessionId: event.sessionId ?? null,
- launchId: event.launchId ?? null,
- createdAt: event.createdAt,
- })
- return
- }
-
- // ── Mentions ────────────────────────────────────────────────────
- case "community:mention.create": {
- void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
- // The server rail badge counts unread mentions per server; refresh
- // it on every new mention. `exact: true` is essential: the mention
- // count lives in the `servers()` LIST query, but members/presence/
- // invites/audit-log/server(id) are all nested UNDER `servers()` in
- // the key hierarchy — a non-exact invalidate prefix-matches and
- // force-refetches that whole subtree (and invalidate overrides the
- // staleTime: Infinity those carry). With an active bot in the server,
- // every mention.create would otherwise storm-refetch all of them.
- void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })
- cbs.onMention?.(event)
- return
- }
-
- // ── Machines ────────────────────────────────────────────────────
- case "community:machine.created": {
- queryClient.setQueryData<MachinesResponse | undefined>(
- communityKeys.machines(),
- (prev) => {
- if (!prev) return { machines: [event.machine] }
- const idx = prev.machines.findIndex((m) => m.id === event.machine.id)
- if (idx === -1) return { ...prev, machines: [event.machine, ...prev.machines] }
- const next = prev.machines.slice()
- next[idx] = event.machine
- return { ...prev, machines: next }
- },
- )
- useCommunityStore.getState().setPendingMachineTokenId(event.tokenId)
- cbs.onMachine?.(event)
- return
- }
- case "community:machine.status": {
- queryClient.setQueryData<MachinesResponse | undefined>(
- communityKeys.machines(),
- (prev) =>
- prev
- ? {
- ...prev,
- machines: prev.machines.map((m) =>
- m.id === event.machineId
- ? { ...m, lastSeenAt: event.lastSeenAt, status: event.status }
- : m,
- ),
- }
- : prev,
- )
- cbs.onMachine?.(event)
- return
- }
- case "community:machine.updated": {
- queryClient.setQueryData<MachinesResponse | undefined>(
- communityKeys.machines(),
- (prev) => {
- if (!prev) return { machines: [event.machine] }
- const idx = prev.machines.findIndex((m) => m.id === event.machine.id)
- if (idx === -1) return { ...prev, machines: [event.machine, ...prev.machines] }
- const next: CommunityMachineSummary[] = prev.machines.slice()
- next[idx] = event.machine
- return { ...prev, machines: next }
- },
- )
- cbs.onMachine?.(event)
- return
- }
- case "community:machine.removed": {
- queryClient.setQueryData<MachinesResponse | undefined>(
- communityKeys.machines(),
- (prev) =>
- prev ? { ...prev, machines: prev.machines.filter((m) => m.id !== event.machineId) } : prev,
- )
- cbs.onMachine?.(event)
- return
+ case "community:friend.block":
+ return handleFriendEvent(event, context)
+ case "community:message.updated":
+ return handleMessageUpdated(event, context)
+ case "community:message.edited":
+ return handleMessageEdited(event, context)
+ case "community:presence.update":
+ return handlePresenceUpdate(event)
+ case "community:status.update":
+ return handleStatusUpdate(event)
+ case "community:bot.audit_event":
+ return handleBotAuditEvent(event)
+ case "community:mention.create":
+ return handleMentionCreate(event, context)
+ case "community:machine.created":
+ return handleMachineCreated(event, context)
+ case "community:machine.status":
+ return handleMachineStatus(event, context)
+ case "community:machine.updated":
+ return handleMachineUpdated(event, context)
+ case "community:machine.removed":
+ return handleMachineRemoved(event, context)
+ default: {
+ const unhandledEvent: never = event
+ return unhandledEvent
}
}
},
[queryClient, scheduleInboxInvalidate],
)
- // Machines are WS-live-patched with no query refetch (see `use-machines.ts`)
- // — but that only works while THIS browser tab's own socket stays connected.
- // If the socket drops and an offline→online transition happens while it's
- // down, the event never arrives and the card is stuck stale until a full
- // page reload. Mirror `AgentProvider`'s reconnect pattern
- // (`contexts/agent-context.tsx`): resync the machines query on every
- // reconnect so a missed transition self-corrects within the reconnect
- // window instead of requiring a manual reload.
- //
- // Same rationale for the focused channel/DM message stream after Commit C:
- // the IDB persister rehydrates the cache from the last session, but the
- // socket may have dropped WS `message.create` events while we were offline
- // (or the tab was suspended). Invalidating the focused scope's message
- // query on reconnect fires a top-up refetch — TanStack re-runs every
- // page's `pageParam`, so anchor windows and newest-tail windows both
- // catch up without any client-side `?since` bookkeeping.
- //
- // Do NOT invalidate the read-state SNAPSHOT here. The snapshot hook
- // (`useChannelReadStateSnapshot`, `gcTime: 0`) latches its first resolved
- // value in a ref and deliberately never updates it during a mount — that
- // freeze is what keeps the "New" divider pinned while the watermark
- // advances. Re-fetching it can't move the divider (the ref ignores the new
- // value), but it DOES flip the hook's `isFetching` back to true, which the
- // channel/DM pages read as `lastReadMessageId: undefined` →
- // `useMessages.isLoading: true` → the whole view drops back to the loading
- // skeleton. Because `onReconnect` fires once even on a fresh page load (a
- // StrictMode / refresh double-connect makes the socket's second open run
- // it ~1.5s in), that surfaced as a SECOND skeleton flash mid-mount —
- // "skeleton → content → skeleton → scroll to the top hero" (the empty
- // round-trip also burned the message list's one-shot mount-scroll gate;
- // see `use-scroll-anchor.ts`'s re-arm-on-empty branch). Verified via live
- // Playwright page-level trace: the second skeleton window lines up exactly
- // with `readSnapshotFetching` going true at t≈1.75s. The message-query
- // invalidation below is the legitimate top-up and keeps its data on
- // screen; the divider is already correct from the first (frozen) snapshot,
- // so nothing here needs the snapshot refetched.
const handleReconnect = useCallback(() => {
- queryClient.invalidateQueries({ queryKey: communityKeys.machines() })
- const sub = useCommunityStore.getState().subscription
- if (sub.channelId) {
- void queryClient.invalidateQueries({
- queryKey: communityKeys.channelMessages(sub.channelId),
- })
- }
- if (sub.dmConversationId) {
- void queryClient.invalidateQueries({
- queryKey: communityKeys.dmMessages(sub.dmConversationId),
- })
- // A DM message may have arrived while offline; the DM sidebar preview /
- // unread flag is only reconciled on `message.create`, none of which land
- // during the gap. Top it up on reconnect.
- void queryClient.invalidateQueries({ queryKey: communityKeys.dms() })
- }
- // Inbox counts also need a refetch — unreads and mentions could have
- // grown while offline and the live invalidator only fires on incoming
- // `message.create` events, none of which arrive while the socket is
- // down.
- void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
- // Sidebar unread dots + rail mention badges are now driven by the live
- // `unread.bump` patch (inbox-dot-ws-driven plan) — no switch-refetch backs
- // them anymore. A bump dropped during the socket gap would leave the dot /
- // rail badge stale forever, so re-seed both on reconnect: the rail LIST
- // (`servers()`, mention counts) and the open server's detail tree
- // (`server(currentServerId)`, channel dots). `exact` on the list so it
- // doesn't cascade-refetch every server's nested detail subtree.
- void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })
- const currentServerId = useCommunityStore.getState().currentServerId
- if (currentServerId) {
- void queryClient.invalidateQueries({
- queryKey: communityKeys.server(currentServerId),
- })
- }
- // Bot audit logs are WS-live-patched into the React Query cache; if
- // the socket dropped, any events emitted during the gap never entered
- // the store's ring and so never made it into the cache. Invalidating
- // all bot audit-log pages on reconnect lets an open modal catch up.
- void queryClient.invalidateQueries({
- queryKey: [...communityKeys.all, "bot"],
- // Fuzzy prefix match — communityKeys.botAuditLog is [all, "bot", botId, "audit-log"].
- exact: false,
- })
+ reconcileCommunityWsReconnect(queryClient)
}, [queryClient])
- const { send } = useUserWs(handleMessage, { onReconnect: handleReconnect })
+ const { send } = useUserWs(handleMessage, {
+ onReconnect: handleReconnect,
+ requestDaemonStatusOnAuth: false,
+ })
// Publish the send binding so free helpers (`communityWsSendTyping`) can
// dispatch without holding a hook reference. Single-instance assumption
@@ -1397,40 +313,6 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
}
}, [send])
- // ── Public methods ───────────────────────────────────────────────────────
-
- /** Subscribe to a channel/thread/DM (writes to the Zustand store). */
- const subscribe = useCallback((target: Subscription) => {
- useCommunityStore.getState().subscribe(target)
- }, [])
-
- const unsubscribe = useCallback(() => {
- useCommunityStore.getState().unsubscribe()
- }, [])
-
- /**
- * Send a typing indicator. Client-side throttled per channelId (a DM is a
- * channel now). The DO also applies server-side dedup.
- */
- const sendTyping = useCallback(
- (target: { channelId: string }) => {
- const key = target.channelId
- if (!key) return
-
- const now = Date.now()
- const map = useCommunityStore.getState().lastTypingSent
- const lastSent = map.get(key) || 0
- if (now - lastSent < TYPING_INDICATOR_THROTTLE_MS) return
-
- // Mutate the map in place — no equality change, no re-render (nothing
- // subscribes to it). Keeping it in the store keeps the lifetime tied
- // to `reset()` on sign-out.
- map.set(key, now)
- send({ type: "community:typing.start", channelId: key })
- },
- [send],
- )
-
// Cleanup: flush the inbox debounce if the hook unmounts mid-window so the
// parent surface doesn't leave a scheduled fetch dangling.
useEffect(() => {
@@ -1441,99 +323,4 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
}
}
}, [])
-
- return {
- subscribe,
- unsubscribe,
- sendTyping,
- }
-}
-
-// ── Typing indicator helpers ─────────────────────────────────────────────────
-
-/**
- * The conversation scope key an event belongs to. Every event carries a single
- * `channelId` now (a DM is a channel), so the `dm:` / `ch:` prefix — which the
- * DM page (`dm:<id>`) and channel page (`ch:<id>`) read via
- * `useTypingUsersForScope` — is derived from the subscription: if the event's
- * channelId is the focused DM channel, it's a `dm:` scope; otherwise `ch:`.
- * Threads collapse to `ch:<channelId>`.
- */
-function typingScopeKey(
- e: { channelId: string },
- sub: { channelId?: string; dmConversationId?: string },
-): string {
- return e.channelId === sub.dmConversationId ? `dm:${e.channelId}` : `ch:${e.channelId}`
-}
-
-// Timer map key: one auto-expire timer per (scope, user) pair.
-const timerKey = (scopeKey: string, userId: string) => `${scopeKey}|${userId}`
-
-/**
- * Add userId to a conversation scope's typing set and start (or extend) an
- * auto-expire timer. The timer removes the user from THAT scope after
- * `TYPING_INDICATOR_TIMEOUT_MS` if no follow-up typing event arrives.
- * No-ops the set write when the user is already typing in the scope (rule 2 —
- * typing.start re-fires every ~3s).
- */
-function applyTypingIndicator(scopeKey: string, userId: string, name: string | null) {
- useCommunityStore.setState((state) => {
- const tKey = timerKey(scopeKey, userId)
- const existing = state.typingTimers.get(tKey)
- if (existing) clearTimeout(existing)
- const timer = setTimeout(() => {
- useCommunityStore.setState((s) => removeTypingUser(s, scopeKey, userId))
- }, TYPING_INDICATOR_TIMEOUT_MS)
- const nextTimers = new Map(state.typingTimers)
- nextTimers.set(tKey, timer)
-
- const current = state.typingByScope.get(scopeKey)
- // Already typing here with the same known name — only the timer refreshed,
- // leave the name map alone (avoids a needless re-render). Otherwise (new
- // typer, or a name we didn't have before) write the entry.
- if (current?.has(userId) && current.get(userId) === name) {
- return { typingTimers: nextTimers }
- }
- const nextByScope = new Map(state.typingByScope)
- nextByScope.set(scopeKey, new Map(current ?? []).set(userId, name))
- return { typingByScope: nextByScope, typingTimers: nextTimers }
- })
-}
-
-/**
- * Immediately remove userId from a scope's typing set and cancel its pending
- * timer. Called when the user sends a message — sending is an implicit
- * typing.stop, and waiting for the 8s timeout leaves a ghost indicator hanging
- * under the message that just arrived.
- */
-function clearTypingIndicator(scopeKey: string, userId: string) {
- useCommunityStore.setState((state) => {
- const tKey = timerKey(scopeKey, userId)
- const existing = state.typingTimers.get(tKey)
- if (!existing && !state.typingByScope.get(scopeKey)?.has(userId)) return {}
- if (existing) clearTimeout(existing)
- return removeTypingUser(state, scopeKey, userId)
- })
-}
-
-/**
- * Pure state patch: drop userId from `scopeKey`'s typing map (deleting the
- * scope key when it empties, to avoid unbounded Map growth) and its
- * `(scope, user)` timer. Shared by the auto-expire timer and the explicit clear.
- */
-function removeTypingUser(
- state: { typingByScope: Map<string, Map<string, string | null>>; typingTimers: Map<string, ReturnType<typeof setTimeout>> },
- scopeKey: string,
- userId: string,
-): Partial<{ typingByScope: Map<string, Map<string, string | null>>; typingTimers: Map<string, ReturnType<typeof setTimeout>> }> {
- const nextTimers = new Map(state.typingTimers)
- nextTimers.delete(timerKey(scopeKey, userId))
- const current = state.typingByScope.get(scopeKey)
- if (!current?.has(userId)) return { typingTimers: nextTimers }
- const nextMap = new Map(current)
- nextMap.delete(userId)
- const nextByScope = new Map(state.typingByScope)
- if (nextMap.size === 0) nextByScope.delete(scopeKey)
- else nextByScope.set(scopeKey, nextMap)
- return { typingByScope: nextByScope, typingTimers: nextTimers }
}
diff --git a/src/web/src/hooks/community/use-messages.activation-refetch.test.ts b/src/web/src/hooks/community/use-messages.activation-refetch.test.ts
new file mode 100644
index 000000000..81f2cfabd
--- /dev/null
+++ b/src/web/src/hooks/community/use-messages.activation-refetch.test.ts
@@ -0,0 +1,242 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import { useDmMessages, useMessages, type MessagesPage } from "./use-messages"
+import { useMessageStreamStore } from "@/stores/community/message-stream"
+
+const apiFetchMock = vi.fn()
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}))
+
+type Snapshot = { ids: string[]; isFetching: boolean }
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((done) => { resolve = done })
+ return { promise, resolve }
+}
+
+async function waitFor(predicate: () => boolean, tries = 40): Promise<void> {
+ for (let i = 0; i < tries; i++) {
+ if (predicate()) return
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 5))
+ })
+ }
+ expect(predicate()).toBe(true)
+}
+
+function DmCapture({ lastReadMessageId, onRender }: {
+ lastReadMessageId: string | null | undefined
+ onRender: (snapshot: Snapshot) => void
+}) {
+ const result = useDmMessages("dm_activation", { lastReadMessageId })
+ onRender({ ids: result.messages.map((message) => message.id), isFetching: result.isFetching })
+ return null
+}
+
+function ChannelCapture({ lastReadMessageId, onRender }: {
+ lastReadMessageId: string | null | undefined
+ onRender: (snapshot: Snapshot) => void
+}) {
+ const result = useMessages("ch_activation", { serverId: "server_1", lastReadMessageId })
+ onRender({ ids: result.messages.map((message) => message.id), isFetching: result.isFetching })
+ return null
+}
+
+function renderCapture(
+ queryClient: QueryClient,
+ element: React.ReactElement,
+): TestRenderer.ReactTestRenderer {
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(QueryClientProvider, { client: queryClient }, element),
+ )
+ })
+ return renderer
+}
+
+function updateCapture(
+ renderer: TestRenderer.ReactTestRenderer,
+ queryClient: QueryClient,
+ element: React.ReactElement,
+): void {
+ act(() => {
+ renderer.update(
+ React.createElement(QueryClientProvider, { client: queryClient }, element),
+ )
+ })
+}
+
+beforeEach(() => {
+ apiFetchMock.mockReset()
+ useMessageStreamStore.getState().resetAll()
+})
+
+describe("useMessagesInner — disabled-to-enabled cache revalidation", () => {
+ it("refetches a fresh persisted empty DM on activation and converges to server truth", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 5_000 } } })
+ queryClient.setQueryData(communityKeys.dmMessages("dm_activation"), {
+ pages: [{ messages: [], hasMore: false, latestSeq: 0 }],
+ pageParams: [{ mode: "newest" }],
+ })
+ const response = deferred<MessagesPage>()
+ apiFetchMock.mockReturnValue(response.promise)
+ const snapshots: Snapshot[] = []
+ const onRender = (snapshot: Snapshot) => { snapshots.push(snapshot) }
+
+ const renderer = renderCapture(
+ queryClient,
+ React.createElement(DmCapture, { lastReadMessageId: undefined, onRender }),
+ )
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ expect(snapshots.at(-1)?.ids).toEqual([])
+
+ updateCapture(
+ renderer,
+ queryClient,
+ React.createElement(DmCapture, { lastReadMessageId: null, onRender }),
+ )
+ await waitFor(() => apiFetchMock.mock.calls.length === 1)
+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/dm_activation/messages")
+
+ response.resolve({
+ messages: [{ id: "m_server", seq: 1, createdAt: "2026-08-09T00:00:00.000Z" }],
+ hasMore: false,
+ latestSeq: 1,
+ })
+ await waitFor(() => snapshots.at(-1)?.ids.includes("m_server") === true)
+ expect(snapshots.at(-1)?.ids).toEqual(["m_server"])
+ renderer.unmount()
+ })
+
+ it("keeps a fresh nonempty DM cache painted while activation refetches in the background", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 5_000 } } })
+ queryClient.setQueryData(communityKeys.dmMessages("dm_activation"), {
+ pages: [{
+ messages: [{ id: "m_cached", seq: 1, createdAt: "2026-08-09T00:00:00.000Z" }],
+ hasMore: false,
+ latestSeq: 1,
+ }],
+ pageParams: [{ mode: "newest" }],
+ })
+ const response = deferred<MessagesPage>()
+ apiFetchMock.mockReturnValue(response.promise)
+ const snapshots: Snapshot[] = []
+ const onRender = (snapshot: Snapshot) => { snapshots.push(snapshot) }
+
+ const renderer = renderCapture(
+ queryClient,
+ React.createElement(DmCapture, { lastReadMessageId: undefined, onRender }),
+ )
+ expect(snapshots.at(-1)?.ids).toEqual(["m_cached"])
+ expect(apiFetchMock).not.toHaveBeenCalled()
+
+ updateCapture(
+ renderer,
+ queryClient,
+ React.createElement(DmCapture, { lastReadMessageId: null, onRender }),
+ )
+ await waitFor(() => snapshots.some((snapshot) => snapshot.isFetching))
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ for (const snapshot of snapshots) expect(snapshot.ids.length).toBeGreaterThan(0)
+
+ response.resolve({
+ messages: [{ id: "m_server", seq: 2, createdAt: "2026-08-09T00:00:01.000Z" }],
+ hasMore: false,
+ latestSeq: 2,
+ })
+ await waitFor(() => snapshots.at(-1)?.ids.includes("m_server") === true)
+ for (const snapshot of snapshots) expect(snapshot.ids.length).toBeGreaterThan(0)
+ expect(snapshots.at(-1)?.ids).toEqual(["m_server"])
+ renderer.unmount()
+ })
+
+ it("revalidates the shared channel path without clearing or losing anchor pagination", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 5_000 } } })
+ const key = communityKeys.channelMessages("ch_activation")
+ queryClient.setQueryData(key, {
+ pages: [
+ {
+ messages: [{ id: "m_anchor", seq: 2, createdAt: "2026-08-09T00:00:01.000Z" }],
+ hasMoreOlder: true,
+ hasMoreNewer: false,
+ olderCursor: "cached-cursor",
+ },
+ {
+ messages: [{ id: "m_cached_old", seq: 1, createdAt: "2026-08-09T00:00:00.000Z" }],
+ hasMoreOlder: false,
+ hasMoreNewer: false,
+ },
+ ],
+ pageParams: [
+ { mode: "anchor", anchor: "m_anchor" },
+ { mode: "older", cursor: "cached-cursor" },
+ ],
+ })
+ const anchorResponse = deferred<MessagesPage>()
+ const olderResponse = deferred<MessagesPage>()
+ apiFetchMock.mockImplementation((url: string) => {
+ if (url.includes("?anchor=m_anchor")) return anchorResponse.promise
+ if (url.includes("?cursor=fresh-cursor")) return olderResponse.promise
+ throw new Error(`unexpected messages URL: ${url}`)
+ })
+ const snapshots: Snapshot[] = []
+ const onRender = (snapshot: Snapshot) => { snapshots.push(snapshot) }
+
+ const renderer = renderCapture(
+ queryClient,
+ React.createElement(ChannelCapture, { lastReadMessageId: undefined, onRender }),
+ )
+ expect(snapshots.at(-1)?.ids).toEqual(["m_cached_old", "m_anchor"])
+ expect(apiFetchMock).not.toHaveBeenCalled()
+
+ updateCapture(
+ renderer,
+ queryClient,
+ React.createElement(ChannelCapture, { lastReadMessageId: "m_anchor", onRender }),
+ )
+ await waitFor(() => apiFetchMock.mock.calls.length === 1)
+ expect(apiFetchMock).toHaveBeenNthCalledWith(
+ 1,
+ "/api/community/channels/ch_activation/messages?anchor=m_anchor",
+ )
+ for (const snapshot of snapshots) expect(snapshot.ids.length).toBeGreaterThan(0)
+
+ anchorResponse.resolve({
+ messages: [{ id: "m_anchor", seq: 3, createdAt: "2026-08-09T00:00:02.000Z" }],
+ hasMoreOlder: true,
+ hasMoreNewer: false,
+ olderCursor: "fresh-cursor",
+ latestSeq: 3,
+ })
+ await waitFor(() => apiFetchMock.mock.calls.length === 2)
+ expect(apiFetchMock).toHaveBeenNthCalledWith(
+ 2,
+ "/api/community/channels/ch_activation/messages?cursor=fresh-cursor",
+ )
+ for (const snapshot of snapshots) expect(snapshot.ids.length).toBeGreaterThan(0)
+
+ olderResponse.resolve({
+ messages: [{ id: "m_server_old", seq: 2, createdAt: "2026-08-09T00:00:01.000Z" }],
+ hasMoreOlder: false,
+ hasMoreNewer: false,
+ latestSeq: 3,
+ })
+ await waitFor(() => snapshots.at(-1)?.ids.includes("m_server_old") === true)
+ for (const snapshot of snapshots) expect(snapshot.ids.length).toBeGreaterThan(0)
+ expect(snapshots.at(-1)?.ids).toEqual(["m_server_old", "m_anchor"])
+ expect(queryClient.getQueryData(key)).toMatchObject({
+ pages: [{ messages: [{ id: "m_anchor" }] }, { messages: [{ id: "m_server_old" }] }],
+ pageParams: [
+ { mode: "anchor", anchor: "m_anchor" },
+ { mode: "older", cursor: "fresh-cursor" },
+ ],
+ })
+ renderer.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index b02e26a37..f86774192 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -136,15 +136,29 @@ export function mergeMessagesPages(pages: MessagesPage[]): Msg[] {
return out
}
-// Fix 4 window: how stale a hydrated cache may be before a mount fires an
-// invalidate. Short enough that a returning tab picks up fresh data on the
-// first paint, long enough that rapid channel switching within a single
-// session doesn't churn the network — the reconnect handler in
-// `useCommunityWs` covers longer offline gaps on its own.
-const STALE_HYDRATED_CACHE_MS = 30_000
+// Anchor-drift repair uses age only to decide whether a fetched anchor page
+// should merge into a trustworthy same-session window or replace an older
+// hydrated window. General mount freshness is owned by the query's
+// `staleTime: 0` contract below, not by this threshold.
+const ANCHOR_CACHE_FRESHNESS_MS = 30_000
type PageCache = InfiniteData<MessagesPage, MessagesPageParam>
+function cachedWindowNeedsAnchor(
+ pages: MessagesPage[] | undefined,
+ anchorId: string | null,
+): boolean {
+ if (!anchorId || !pages || pages.length === 0) return false
+ let hasMessages = false
+ for (const page of pages) {
+ for (const message of page.messages) {
+ hasMessages = true
+ if (message.id === anchorId) return false
+ }
+ }
+ return hasMessages
+}
+
type MessagesReturn = Omit<UseInfiniteQueryResult<PageCache, Error>, "isLoading"> & {
messages: Msg[]
latestSeq: number
@@ -254,6 +268,17 @@ function useMessagesInner(
return { mode: "newer", cursor }
},
enabled,
+ // Message bases are persisted, while accepted/session rows live in an
+ // in-memory overlay. Treat each ordinary active message query as stale so
+ // disabled→enabled activation revalidates even inside the global 5-second
+ // freshness window. TanStack keeps cached pages painted during the fetch.
+ // A nonempty window missing the resolved anchor is the one exception: Fix
+ // 3 below owns that repair and must fetch the NEW anchor page before any
+ // persisted pageParam can replace or discard the existing history.
+ staleTime: (cachedQuery) => cachedWindowNeedsAnchor(
+ (cachedQuery.state.data as PageCache | undefined)?.pages,
+ anchorId,
+ ) ? Infinity : 0,
})
// Flush any pending mark-read on scope switch / unmount so the 500ms
@@ -317,29 +342,13 @@ function useMessagesInner(
if (!anchorId) return
if (query.isFetching) return
if (query.isPending) return
- const pages = query.data?.pages
- if (!pages || pages.length === 0) return
- let messageCount = 0
- let anchorFound = false
- for (const p of pages) {
- messageCount += p.messages.length
- if (!anchorFound) {
- for (const m of p.messages) {
- if (m.id === anchorId) {
- anchorFound = true
- break
- }
- }
- }
- }
- if (messageCount === 0) return
- if (anchorFound) return
+ if (!cachedWindowNeedsAnchor(query.data?.pages, anchorId)) return
const resetKey = `${scopeId ?? ""}::${anchorId}`
if (anchorResetKeyRef.current === resetKey) return
anchorResetKeyRef.current = resetKey
const updatedAt = query.dataUpdatedAt
- const isFresh = !!updatedAt && Date.now() - updatedAt < STALE_HYDRATED_CACHE_MS
+ const isFresh = !!updatedAt && Date.now() - updatedAt < ANCHOR_CACHE_FRESHNESS_MS
// Both branches fetch a fresh anchor-centered page out of band and swap
// it in via `setQueryData` — NEITHER uses `resetQueries`. `resetQueries`
@@ -413,49 +422,6 @@ function useMessagesInner(
queryFn,
])
- // Fix 4 — staleness invalidate on mount / scope switch ONLY.
- //
- // When the cache is hydrated from IDB, `dataUpdatedAt` reflects the last
- // fetch of the previous session. TanStack won't refetch on mount for
- // infinite queries by default, so the client keeps rendering the stale
- // window even though `latestSeq` on the server may have advanced. On
- // mount, if the hydrated window is older than the freshness window, kick
- // off an invalidation — TanStack re-runs every persisted `pageParam` and
- // the fresh `latestSeq` in the server response drives `unreadCount` and
- // `hasMoreNewer` to the truth without any client bookkeeping.
- //
- // Fires EXACTLY ONCE per scope (channelId / dmId), gated by a scopeId ref.
- // Previously the effect had `query.dataUpdatedAt` in its dep list, which
- // re-evaluated on every fetch complete — including AFTER an optimistic
- // send stayed in-place past 30s of stillness. Any such re-eval could
- // invalidate the cache, refetch server pages, and drop the just-sent
- // (already reconciled) row visually before the WS broadcast caught up.
- // Locking to "one shot per scope" preserves the mount-time invariant
- // (hydrated-and-stale gets refreshed) without ever firing again for the
- // same open scope. WS reconnect + user-initiated navigation cover any
- // subsequent freshness needs.
- const staleCacheCheckedScopeRef = useRef<string | null>(null)
- useEffect(() => {
- if (!enabled) return
- if (!scopeId) return
- if (staleCacheCheckedScopeRef.current === scopeId) return
- if (query.isFetching) return
- if (query.isPending) return
- const updatedAt = query.dataUpdatedAt
- if (!updatedAt) return
- staleCacheCheckedScopeRef.current = scopeId
- if (Date.now() - updatedAt < STALE_HYDRATED_CACHE_MS) return
- void queryClient.invalidateQueries({ queryKey })
- }, [
- enabled,
- scopeId,
- query.dataUpdatedAt,
- query.isFetching,
- query.isPending,
- queryClient,
- queryKey,
- ])
-
const messages = useMemo<Msg[]>(() => {
if (!query.data) return []
return mergeMessagesPages(query.data.pages)
diff --git a/src/web/src/lib/broadcast.test.ts b/src/web/src/lib/broadcast.test.ts
index 165495840..42462364b 100644
--- a/src/web/src/lib/broadcast.test.ts
+++ b/src/web/src/lib/broadcast.test.ts
@@ -24,7 +24,7 @@ vi.mock("@alook/shared", async () => {
}
})
-import { wsDoFetch, broadcastToUser } from "./broadcast"
+import { wsDoFetch, broadcastToUser, broadcastToUsers } from "./broadcast"
const originalFetch = globalThis.fetch
const mockFetch = vi.fn<(...args: unknown[]) => Promise<Response>>()
@@ -237,8 +237,87 @@ describe("broadcastToUser", () => {
ctx: { waitUntil: mockCtxWaitUntil },
})
- await expect(broadcastToUser("u1", { type: "message:new" } as any)).resolves.toBeUndefined()
+ const message = { type: "message:new", raw: "unchanged" } as any
+ await expect(broadcastToUser("u1", message)).resolves.toBeUndefined()
+ expect(String(bindingFetch.mock.calls[0]?.[0])).toBe("http://internal/broadcast/user/u1")
+ expect(bindingFetch.mock.calls[0]?.[1]?.body).toBe(JSON.stringify(message))
expect(mockFetch).not.toHaveBeenCalled()
expect(mockWarn).not.toHaveBeenCalled()
})
})
+
+describe("broadcastToUsers", () => {
+ it("sends one bulk service-binding request with the exact shared payload and exclusion", async () => {
+ const bindingFetch = vi.fn(async () =>
+ new Response(JSON.stringify({ sent: 2 }), { status: 200 }),
+ )
+ const env = makeEnv(bindingFetch)
+ mockGetCloudflareContext.mockReturnValue({
+ env,
+ ctx: { waitUntil: mockCtxWaitUntil },
+ })
+ const message = { type: "community:message.create", channelId: "c1" } as any
+
+ await broadcastToUsers(["u1", "u2", "u3"], message, "u1")
+
+ expect(bindingFetch).toHaveBeenCalledTimes(1)
+ expect(mockFetch).not.toHaveBeenCalled()
+ expect(String(bindingFetch.mock.calls[0]?.[0])).toBe("http://internal/broadcast/users")
+ expect(bindingFetch.mock.calls[0]?.[1]).toEqual(expect.objectContaining({
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ userIds: ["u1", "u2", "u3"], message, excludeUserId: "u1" }),
+ }))
+ })
+
+ it("omits excludeUserId from the body when it is absent", async () => {
+ const bindingFetch = vi.fn(async () =>
+ new Response(JSON.stringify({ sent: 1 }), { status: 200 }),
+ )
+ const env = makeEnv(bindingFetch)
+ mockGetCloudflareContext.mockReturnValue({
+ env,
+ ctx: { waitUntil: mockCtxWaitUntil },
+ })
+ const message = { type: "community:member.update" } as any
+
+ await broadcastToUsers(["u1"], message)
+
+ const body = JSON.parse(String(bindingFetch.mock.calls[0]?.[1]?.body))
+ expect(body).toEqual({ userIds: ["u1"], message })
+ expect(body).not.toHaveProperty("excludeUserId")
+ })
+
+ it("falls back exactly once after one binding 5xx", async () => {
+ const bindingFetch = vi.fn(async () => new Response("boom", { status: 502 }))
+ mockFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 2 }), { status: 200 }))
+ const env = makeEnv(bindingFetch)
+ mockGetCloudflareContext.mockReturnValue({
+ env,
+ ctx: { waitUntil: mockCtxWaitUntil },
+ })
+
+ await broadcastToUsers(["u1", "u2"], { type: "community:member.update" } as any)
+
+ expect(bindingFetch).toHaveBeenCalledTimes(1)
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ expect(String(mockFetch.mock.calls[0]?.[0])).toBe("http://dev-ws:8789/broadcast/users")
+ })
+
+ it("falls back exactly once after one binding throw", async () => {
+ const bindingFetch = vi.fn(async () => {
+ throw new Error("binding down")
+ })
+ mockFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 2 }), { status: 200 }))
+ const env = makeEnv(bindingFetch)
+ mockGetCloudflareContext.mockReturnValue({
+ env,
+ ctx: { waitUntil: mockCtxWaitUntil },
+ })
+
+ await broadcastToUsers(["u1", "u2"], { type: "community:member.update" } as any)
+
+ expect(bindingFetch).toHaveBeenCalledTimes(1)
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/web/src/lib/broadcast.ts b/src/web/src/lib/broadcast.ts
index e2502a9f3..9e9eb0ea3 100644
--- a/src/web/src/lib/broadcast.ts
+++ b/src/web/src/lib/broadcast.ts
@@ -75,6 +75,18 @@ export function broadcastToUser(userId: string, message: WsMessage): Promise<voi
)
}
+export function broadcastToUsers(
+ userIds: string[],
+ message: WsMessage,
+ excludeUserId?: string,
+): Promise<void> {
+ return sendBroadcast(
+ "/broadcast/users",
+ JSON.stringify({ userIds, message, excludeUserId }),
+ { label: `users:${userIds.length}`, type: message.type },
+ )
+}
+
export function broadcastToDaemon(daemonId: string, message: DaemonPushMessage): Promise<{ sent: number }> {
const promise = doSend(
diff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.ts
index 2681bdae5..9e5576822 100644
--- a/src/web/src/lib/community/fanout.test.ts
+++ b/src/web/src/lib/community/fanout.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
+import { readFileSync } from "node:fs"
const mockGetCloudflareContext = vi.fn(() => ({ env: { DB: {} } }))
vi.mock("@opennextjs/cloudflare", () => ({
@@ -6,6 +7,8 @@ vi.mock("@opennextjs/cloudflare", () => ({
}))
const mockWarn = vi.fn()
+const mockWithD1Retry = vi.fn(async (fn: () => Promise<unknown>, _opts?: unknown) => fn())
+const mockResolveChannelRecipientUserIds = vi.fn(() => Promise.resolve([] as string[]))
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -17,6 +20,7 @@ vi.mock("@alook/shared", async () => {
error: vi.fn(),
debug: vi.fn(),
}),
+ withD1Retry: (...a: unknown[]) => mockWithD1Retry(...(a as [() => Promise<unknown>, unknown])),
queries: {
communityMember: {
listMembers: (...a: unknown[]) => mockListMembers(...a),
@@ -32,6 +36,7 @@ vi.mock("@alook/shared", async () => {
},
communityMembersResolver: {
resolveScopeMemberUserIds: (...a: unknown[]) => mockResolveScopeMemberUserIds(...a),
+ resolveChannelRecipientUserIds: (...a: unknown[]) => mockResolveChannelRecipientUserIds(...a),
},
communityThread: {
listThreadParticipantUserIds: (...a: unknown[]) => mockListThreadParticipantUserIds(...a),
@@ -51,8 +56,10 @@ vi.mock("../db", () => ({
}))
const mockBroadcastToUser = vi.fn()
+const mockBroadcastToUsers = vi.fn()
vi.mock("../broadcast", () => ({
broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),
+ broadcastToUsers: (...a: unknown[]) => mockBroadcastToUsers(...a),
}))
const mockEnqueueBotWakes = vi.fn()
@@ -80,6 +87,7 @@ import {
fanOutToDM,
fanOutStatusUpdate,
broadcastToUserSafe,
+ resolveChannelRecipients,
} from "./fanout"
import { WS_EVENTS } from "@alook/shared"
@@ -88,6 +96,9 @@ describe("fanOutToServerMembers", () => {
vi.clearAllMocks()
mockGetCloudflareContext.mockImplementation(() => ({ env: { DB: {} } }))
mockBroadcastToUser.mockResolvedValue(undefined)
+ mockBroadcastToUsers.mockResolvedValue(undefined)
+ mockWithD1Retry.mockImplementation(async (fn: () => Promise<unknown>, _opts?: unknown) => fn())
+ mockResolveChannelRecipientUserIds.mockResolvedValue([])
// Default to a non-thread channel so fan-out uses the shared resolver path;
// the thread test overrides this. (clearAllMocks resets call history, not
// the resolved-value impl, so re-assert the default each test.)
@@ -112,9 +123,13 @@ describe("fanOutToServerMembers", () => {
expect(mockListMemberUserIds).toHaveBeenCalledTimes(1)
expect(mockListMembers).not.toHaveBeenCalled()
- expect(mockBroadcastToUser).toHaveBeenCalledTimes(4)
- const targets = mockBroadcastToUser.mock.calls.map((c) => c[0]).sort()
- expect(targets).toEqual(["u2", "u3", "u4", "u5"])
+ expect(mockBroadcastToUsers).toHaveBeenCalledTimes(1)
+ expect(mockBroadcastToUsers).toHaveBeenCalledWith(
+ ["u1", "u2", "u3", "u4", "u5"],
+ expect.objectContaining({ type: WS_EVENTS.MEMBER_UPDATE }),
+ "u1",
+ )
+ expect(mockBroadcastToUser).not.toHaveBeenCalled()
})
it("broadcasts to every recipient when excludeUserId is absent", async () => {
@@ -127,11 +142,16 @@ describe("fanOutToServerMembers", () => {
changes: { role: "admin" },
})
- expect(mockBroadcastToUser).toHaveBeenCalledTimes(3)
+ expect(mockBroadcastToUsers).toHaveBeenCalledTimes(1)
+ expect(mockBroadcastToUsers).toHaveBeenCalledWith(
+ ["u1", "u2", "u3"],
+ expect.objectContaining({ type: WS_EVENTS.MEMBER_UPDATE }),
+ undefined,
+ )
})
- it("fanOutToChannel resolves recipients via the shared member resolver", async () => {
- mockResolveScopeMemberUserIds.mockResolvedValue(["u1", "u2"])
+ it("fanOutToChannel resolves recipients via the shared channel recipient resolver", async () => {
+ mockResolveChannelRecipientUserIds.mockResolvedValue(["u1", "u2"])
await fanOutToChannel("c1", {
type: WS_EVENTS.MESSAGE_CREATE,
@@ -139,23 +159,22 @@ describe("fanOutToServerMembers", () => {
message: {} as never,
} as never)
- expect(mockResolveScopeMemberUserIds).toHaveBeenCalledTimes(1)
- expect(mockResolveScopeMemberUserIds).toHaveBeenCalledWith(expect.anything(), {
- scope: "channel",
- scopeId: "c1",
- })
- // The old inline split (getChannel + isChannelPrivate) is gone.
+ expect(mockResolveChannelRecipientUserIds).toHaveBeenCalledTimes(1)
+ expect(mockResolveChannelRecipientUserIds).toHaveBeenCalledWith(
+ expect.anything(),
+ "c1",
+ expect.any(Function),
+ )
expect(mockGetChannel).not.toHaveBeenCalled()
expect(mockListMembers).not.toHaveBeenCalled()
- expect(mockBroadcastToUser).toHaveBeenCalledTimes(2)
+ expect(mockBroadcastToUsers).toHaveBeenCalledTimes(1)
})
it("fanOutToChannel routes a DM to its access members (not the empty server-scoped resolver)", async () => {
// Regression: a DM has server_id=NULL. Before the isDm branch, it fell
// through to resolveScopeMemberUserIds({scope:"channel"}) → WHERE
// server_id = NULL → [] → the peer never received the live message frame.
- mockGetChannelType.mockResolvedValue("dm")
- mockListChannelMemberUserIds.mockResolvedValue(["u1", "u2"])
+ mockResolveChannelRecipientUserIds.mockResolvedValue(["u1", "u2"])
await fanOutToChannel(
"dm1",
@@ -163,17 +182,20 @@ describe("fanOutToServerMembers", () => {
{ excludeUserId: "u1" },
)
- expect(mockListChannelMemberUserIds).toHaveBeenCalledWith(expect.anything(), "dm1")
- // Must NOT fall through to the server-scoped resolver (empty for a DM).
- expect(mockResolveScopeMemberUserIds).not.toHaveBeenCalled()
- // u1 excluded → only the peer receives the frame.
- expect(mockBroadcastToUser).toHaveBeenCalledTimes(1)
- expect(mockBroadcastToUser.mock.calls[0][0]).toBe("u2")
+ expect(mockResolveChannelRecipientUserIds).toHaveBeenCalledWith(
+ expect.anything(),
+ "dm1",
+ expect.any(Function),
+ )
+ expect(mockBroadcastToUsers).toHaveBeenCalledWith(
+ ["u1", "u2"],
+ expect.objectContaining({ type: WS_EVENTS.MESSAGE_CREATE }),
+ "u1",
+ )
})
it("fanOutToChannel routes a THREAD to its participant set (not the channel audience)", async () => {
- mockGetChannelType.mockResolvedValue("thread")
- mockListThreadParticipantUserIds.mockResolvedValue(["u1", "u2"])
+ mockResolveChannelRecipientUserIds.mockResolvedValue(["u1", "u2"])
await fanOutToChannel("t1", {
type: WS_EVENTS.MESSAGE_CREATE,
@@ -181,10 +203,69 @@ describe("fanOutToServerMembers", () => {
message: {} as never,
} as never)
- expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith(expect.anything(), "t1")
- // Thread fan-out must NOT fall back to the channel-audience resolver.
- expect(mockResolveScopeMemberUserIds).not.toHaveBeenCalled()
- expect(mockBroadcastToUser).toHaveBeenCalledTimes(2)
+ expect(mockResolveChannelRecipientUserIds).toHaveBeenCalledWith(
+ expect.anything(),
+ "t1",
+ expect.any(Function),
+ )
+ expect(mockBroadcastToUsers).toHaveBeenCalledTimes(1)
+ })
+
+ it("keeps Web type and selected-branch retries as two independently labelled phases", async () => {
+ const typeQuery = vi.fn(async () => "text")
+ const scopeQuery = vi.fn(async () => ["u1"])
+ mockResolveChannelRecipientUserIds.mockImplementationOnce(async (_db, _channelId, runQuery) => {
+ await runQuery("channel-type", typeQuery)
+ return runQuery("scope-members", scopeQuery)
+ })
+
+ await expect(resolveChannelRecipients({} as never, "c1")).resolves.toEqual(["u1"])
+
+ expect(mockWithD1Retry).toHaveBeenCalledTimes(2)
+ expect(mockWithD1Retry.mock.calls.map((call) => call[1])).toEqual([
+ { route: "fanout:channel-type" },
+ { route: "fanout:scope-members" },
+ ])
+ expect(typeQuery).toHaveBeenCalledTimes(1)
+ expect(scopeQuery).toHaveBeenCalledTimes(1)
+ })
+
+ it("stops after a type-phase failure without starting the recipient phase", async () => {
+ const failure = new Error("bad channel type")
+ const scopeQuery = vi.fn(async () => ["u1"])
+ mockResolveChannelRecipientUserIds.mockImplementationOnce(async (_db, _channelId, runQuery) => {
+ await runQuery("channel-type", async () => { throw failure })
+ return runQuery("scope-members", scopeQuery)
+ })
+
+ await expect(resolveChannelRecipients({} as never, "c1")).rejects.toBe(failure)
+ expect(mockWithD1Retry).toHaveBeenCalledTimes(1)
+ expect(mockWithD1Retry.mock.calls[0]?.[1]).toEqual({ route: "fanout:channel-type" })
+ expect(scopeQuery).not.toHaveBeenCalled()
+ })
+
+ it("retries only the selected branch without re-reading channel type", async () => {
+ const typeQuery = vi.fn(async () => "text")
+ const scopeQuery = vi.fn()
+ .mockRejectedValueOnce(new Error("SQLITE_BUSY"))
+ .mockResolvedValueOnce(["u1"])
+ mockWithD1Retry.mockImplementation(async (fn, opts) => {
+ if ((opts as { route?: string }).route !== "fanout:scope-members") return fn()
+ try { return await fn() } catch { return fn() }
+ })
+ mockResolveChannelRecipientUserIds.mockImplementationOnce(async (_db, _channelId, runQuery) => {
+ await runQuery("channel-type", typeQuery)
+ return runQuery("scope-members", scopeQuery)
+ })
+
+ await expect(resolveChannelRecipients({} as never, "c1")).resolves.toEqual(["u1"])
+ expect(typeQuery).toHaveBeenCalledTimes(1)
+ expect(scopeQuery).toHaveBeenCalledTimes(2)
+ })
+
+ it("contains no local reach classifier after delegating to shared", () => {
+ const source = readFileSync(new URL("./fanout.ts", import.meta.url), "utf8")
+ expect(source).not.toMatch(/\bchannelReach\b|\bisStoredChannelType\b|switch\s*\(\s*reach\s*\)/)
})
})
@@ -193,6 +274,7 @@ describe("fanOutStatusUpdate", () => {
vi.clearAllMocks()
mockGetCloudflareContext.mockImplementation(() => ({ env: { DB: {} } }))
mockBroadcastToUser.mockResolvedValue(undefined)
+ mockBroadcastToUsers.mockResolvedValue(undefined)
// Default to a non-thread channel so fan-out uses the shared resolver path;
// the thread test overrides this. (clearAllMocks resets call history, not
// the resolved-value impl, so re-assert the default each test.)
@@ -207,17 +289,17 @@ describe("fanOutStatusUpdate", () => {
expect(mockGetCoMemberUserIds).toHaveBeenCalledWith(expect.anything(), "self1")
expect(mockGetFriendUserIds).toHaveBeenCalledWith(expect.anything(), "self1")
- expect(mockBroadcastToUser).toHaveBeenCalledTimes(3)
- const targets = mockBroadcastToUser.mock.calls.map((c) => c[0]).sort()
- expect(targets).toEqual(["u1", "u2", "u3"])
- for (const call of mockBroadcastToUser.mock.calls) {
- expect(call[1]).toEqual({
+ expect(mockBroadcastToUsers).toHaveBeenCalledTimes(1)
+ expect(mockBroadcastToUsers).toHaveBeenCalledWith(
+ ["u1", "u2", "u3"],
+ {
type: "community:status.update",
userId: "self1",
statusEmoji: "🎧",
statusText: "Vibing",
- })
- }
+ },
+ undefined,
+ )
})
it("does not broadcast when the audience is empty", async () => {
@@ -226,7 +308,7 @@ describe("fanOutStatusUpdate", () => {
await fanOutStatusUpdate("self1", null, null)
- expect(mockBroadcastToUser).not.toHaveBeenCalled()
+ expect(mockBroadcastToUsers).not.toHaveBeenCalled()
})
it("never throws — absorbs a DB error and logs a warning", async () => {
@@ -253,11 +335,12 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
vi.clearAllMocks()
mockGetCloudflareContext.mockImplementation(() => ({ env: { DB: {} } }))
mockBroadcastToUser.mockResolvedValue(undefined)
+ mockBroadcastToUsers.mockResolvedValue(undefined)
mockEnqueueBotWakes.mockResolvedValue(undefined)
})
it("fanOutToChannel enqueues wakes using the same recipient list, minus excludeUserId", async () => {
- mockResolveScopeMemberUserIds.mockResolvedValue(["u1", "u2", "u3"])
+ mockResolveChannelRecipientUserIds.mockResolvedValue(["u1", "u2", "u3"])
await fanOutToChannel(
"c1",
@@ -275,7 +358,7 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
it("starts wake enqueue before a slow recipient broadcast settles", async () => {
let releaseBroadcast!: () => void
- mockBroadcastToUser.mockImplementation(
+ mockBroadcastToUsers.mockImplementation(
() => new Promise<void>((resolve) => {
releaseBroadcast = resolve
}),
@@ -296,19 +379,35 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
await pending
})
+ it("starts wake enqueue even when the bulk hop rejects", async () => {
+ mockBroadcastToUsers.mockRejectedValue(new Error("bulk down"))
+
+ await expect(fanOutToChannel(
+ "c1",
+ { type: WS_EVENTS.MESSAGE_CREATE, channelId: "c1", message: {} as never } as never,
+ {
+ excludeUserId: "u1",
+ recipients: ["u1", "u2"],
+ wakeMessageRow,
+ },
+ )).resolves.toBeUndefined()
+
+ expect(mockEnqueueBotWakes).toHaveBeenCalledTimes(1)
+ expect(mockBroadcastToUsers).toHaveBeenCalledTimes(1)
+ })
+
it("fire-and-forget fanOut registers its waitUntil before recipient resolution settles", async () => {
const waitUntil = vi.fn()
mockGetCloudflareContext.mockImplementation(() => ({
env: { DB: {} },
ctx: { waitUntil },
}))
- let releaseChannelType!: (type: string) => void
- mockGetChannelType.mockImplementationOnce(
- () => new Promise<string>((resolve) => {
- releaseChannelType = resolve
+ let releaseRecipients!: (ids: string[]) => void
+ mockResolveChannelRecipientUserIds.mockImplementationOnce(
+ () => new Promise<string[]>((resolve) => {
+ releaseRecipients = resolve
}),
)
- mockResolveScopeMemberUserIds.mockResolvedValue(["u1", "u2"])
const floatingFanout = fanOutToChannel(
"c1",
@@ -322,7 +421,7 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
expect(waitUntil).toHaveBeenCalledTimes(1)
expect(mockEnqueueBotWakes).not.toHaveBeenCalled()
- releaseChannelType("text")
+ releaseRecipients(["u1", "u2"])
await waitUntil.mock.calls[0]![0]
expect(mockEnqueueBotWakes).toHaveBeenCalledTimes(1)
await floatingFanout
@@ -348,7 +447,7 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
})
it("does not enqueue wakes when wakeMessageRow is omitted", async () => {
- mockResolveScopeMemberUserIds.mockResolvedValue(["u1", "u2"])
+ mockResolveChannelRecipientUserIds.mockResolvedValue(["u1", "u2"])
await fanOutToChannel("c1", {
type: WS_EVENTS.MESSAGE_CREATE,
@@ -360,7 +459,7 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
})
it("does not enqueue wakes for non-MESSAGE_CREATE events even with a wakeMessageRow", async () => {
- mockResolveScopeMemberUserIds.mockResolvedValue(["u1", "u2"])
+ mockResolveChannelRecipientUserIds.mockResolvedValue(["u1", "u2"])
await fanOutToChannel(
"c1",
@@ -377,7 +476,7 @@ describe("wake dispatch (minimal-wake-queue-unread-notice) — only fires for ME
})
it("a failing enqueueBotWakes does not reject fanOutToChannel", async () => {
- mockResolveScopeMemberUserIds.mockResolvedValue(["u1"])
+ mockResolveChannelRecipientUserIds.mockResolvedValue(["u1"])
mockEnqueueBotWakes.mockRejectedValue(new Error("queue down"))
await expect(
@@ -394,6 +493,38 @@ describe("fanout helpers absorb setup failures", () => {
beforeEach(() => {
vi.clearAllMocks()
mockBroadcastToUser.mockResolvedValue(undefined)
+ mockBroadcastToUsers.mockResolvedValue(undefined)
+ })
+
+ it("all shared-payload fanout helpers absorb a bulk rejection", async () => {
+ mockGetCloudflareContext.mockImplementation(() => ({ env: { DB: {} } }))
+ mockBroadcastToUsers.mockRejectedValue(new Error("bulk down"))
+ mockListMemberUserIds.mockResolvedValue(["u1"])
+ mockResolveChannelRecipientUserIds.mockResolvedValue(["u1"])
+ mockGetDM.mockResolvedValue({ id: "dm1" })
+ mockListChannelMemberUserIds.mockResolvedValue(["u1"])
+ mockGetCoMemberUserIds.mockResolvedValue(["u1"])
+ mockGetFriendUserIds.mockResolvedValue([])
+
+ await expect(fanOutToServerMembers("srv1", {
+ type: WS_EVENTS.MEMBER_UPDATE,
+ serverId: "srv1",
+ memberId: "m1",
+ changes: { role: "admin" },
+ })).resolves.toBeUndefined()
+ await expect(fanOutToChannel("c1", {
+ type: WS_EVENTS.MESSAGE_CREATE,
+ channelId: "c1",
+ message: {} as never,
+ } as never)).resolves.toBeUndefined()
+ await expect(fanOutToDM("dm1", {
+ type: WS_EVENTS.MESSAGE_CREATE,
+ channelId: "dm1",
+ message: {} as never,
+ } as never)).resolves.toBeUndefined()
+ await expect(fanOutStatusUpdate("u1", null, null)).resolves.toBeUndefined()
+
+ expect(mockBroadcastToUsers).toHaveBeenCalledTimes(4)
})
it("fanOutToServerMembers resolves and logs when getCloudflareContext throws", async () => {
diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.ts
index 87bd25cd5..bcbec7b6e 100644
--- a/src/web/src/lib/community/fanout.ts
+++ b/src/web/src/lib/community/fanout.ts
@@ -2,21 +2,21 @@
* Server-side fan-out helpers for community real-time events.
*
* Each function resolves the recipient set via D1 queries,
- * then POSTs the event to each user's per-user DO via the existing
- * broadcast service binding (WS_DO_WORKER -> /broadcast/user/<userId>).
+ * then sends one bounded bulk request through the existing broadcast
+ * service binding (WS_DO_WORKER -> /broadcast/users).
*
- * Uses the same `broadcastToUser` function that existing code uses,
- * ensuring consistent service-binding -> HTTP fallback behavior.
+ * The bulk helper uses the same service-binding -> HTTP fallback behavior
+ * as the compatibility single-user helper.
*
* Contract: these helpers absorb all failures internally and never reject.
* Routes call them as fire-and-forget statements without `.catch()`.
*/
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { queries, createLogger, WS_EVENTS, channelReach, isStoredChannelType, withD1Retry } from "@alook/shared"
+import { queries, createLogger, WS_EVENTS, withD1Retry } from "@alook/shared"
import type { CommunityWsEvent, Database } from "@alook/shared"
import { getDb } from "../db"
-import { broadcastToUser } from "../broadcast"
+import { broadcastToUser, broadcastToUsers } from "../broadcast"
import { enqueueBotWakes, type WakeMessageRow } from "./wake-producer"
const log = createLogger({ service: "community-fanout" })
@@ -59,43 +59,17 @@ async function getServerMemberUserIds(db: Database, serverId: string): Promise<s
* The split lives here so fan-out and bot-wake use the same recipient set.
*/
async function getChannelRecipientUserIds(db: Database, channelId: string): Promise<string[]> {
- const type = await withD1Retry(
- () => queries.communityChannel.getChannelType(db, channelId),
- { route: "fanout:channel-type" },
+ const retryRoute = {
+ "channel-type": "fanout:channel-type",
+ "thread-participants": "fanout:thread-participants",
+ "dm-members": "fanout:dm-members",
+ "scope-members": "fanout:scope-members",
+ } as const
+ return queries.communityMembersResolver.resolveChannelRecipientUserIds(
+ db,
+ channelId,
+ (phase, query) => withD1Retry(query, { route: retryRoute[phase] }),
)
- // Dispatch on the reach TRAIT, not a re-derived `isThread || isForumPost` /
- // `isDm` classification (B2 — the reach axis's single source). An unknown/null
- // type falls to `server-or-roster` (the historical default arm). The read side
- // here (who-receives) keys on the SAME reach value the send-path enroll keys on
- // (who-enrolls), so a participant-set channel's fan-out and its enroll can't
- // drift (red-line ③).
- const reach = isStoredChannelType(type) ? channelReach(type) : "server-or-roster"
- switch (reach) {
- case "participant-set":
- // Child thread: the unit's notify (participant) rows — the same set
- // the send-path enroll writes into.
- return withD1Retry(
- () => queries.communityThread.listThreadParticipantUserIds(db, channelId),
- { route: "fanout:thread-participants" },
- )
- case "dm-pair":
- // DM: its two relation='access' members (server_id is NULL, so it must not
- // fall through to the server-scoped resolver).
- return withD1Retry(
- () => queries.communityChannel.listChannelMemberUserIds(db, channelId),
- { route: "fanout:dm-members" },
- )
- case "server-or-roster":
- // Channel / forum: the access audience (public/private split).
- return withD1Retry(
- () => queries.communityMembersResolver.resolveScopeMemberUserIds(db, { scope: "channel", scopeId: channelId }),
- { route: "fanout:scope-members" },
- )
- default: {
- const _never: never = reach
- return _never
- }
- }
}
/**
@@ -315,17 +289,14 @@ async function broadcastToRecipients(
event: BroadcastableEvent,
excludeUserId?: string
): Promise<void> {
- const recipients = excludeUserId
- ? userIds.filter((id) => id !== excludeUserId)
- : userIds
-
- if (recipients.length === 0) return
-
- // Fire all broadcasts concurrently — non-blocking via waitUntil in broadcastToUser
- const promises = recipients.map((userId) =>
- broadcastToUser(userId, event).catch((err) => {
- log.warn("broadcastToRecipient failed", { userId, type: event.type, err: String(err) })
+ if (userIds.length === 0) return
+ try {
+ await broadcastToUsers(userIds, event, excludeUserId)
+ } catch (err) {
+ log.warn("broadcast_to_recipients_failed", {
+ recipientCount: userIds.length,
+ type: event.type,
+ err: String(err),
})
- )
- await Promise.all(promises)
+ }
}
diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.ts
index 4e7697393..b72bd4391 100644
--- a/src/web/src/lib/use-user-ws.test.ts
+++ b/src/web/src/lib/use-user-ws.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
import type { WsMessage } from "@alook/shared"
+import type { UseUserWsOptions } from "./use-user-ws"
// --- Mock WebSocket ---
class MockWebSocket {
@@ -42,6 +43,16 @@ let refs: Map<string, { current: unknown }> = new Map()
let refCounter = 0
let callbackMemo: Map<string, { fn: Function; deps: unknown[] }> = new Map()
let callbackCounter = 0
+let effectMemo: Map<string, {
+ deps: unknown[]
+ setup: () => (() => void) | void
+ cleanup?: () => void
+}> = new Map()
+let effectCounter = 0
+
+function depsEqual(left: unknown[], right: unknown[]) {
+ return left.length === right.length && left.every((value, index) => Object.is(value, right[index]))
+}
vi.mock("react", () => ({
useRef: (initial: unknown) => {
@@ -60,12 +71,41 @@ vi.mock("react", () => ({
callbackMemo.set(id, { fn, deps })
return fn
},
- useEffect: (fn: () => (() => void) | void, _deps: unknown[]) => {
+ useEffect: (fn: () => (() => void) | void, deps: unknown[]) => {
+ const id = `effect-${effectCounter++}`
+ const existing = effectMemo.get(id)
+ if (existing && depsEqual(existing.deps, deps)) return
const cleanup = fn()
+ effectMemo.set(id, { deps, setup: fn, cleanup: cleanup || undefined })
if (cleanup) effectCleanup = cleanup
},
}))
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ return { promise, resolve, reject }
+}
+
+async function flushPromises() {
+ await Promise.resolve()
+ await Promise.resolve()
+ await Promise.resolve()
+}
+
+function replayEffects() {
+ for (const effect of effectMemo.values()) effect.cleanup?.()
+ for (const effect of effectMemo.values()) {
+ const cleanup = effect.setup()
+ effect.cleanup = cleanup || undefined
+ if (cleanup) effectCleanup = cleanup
+ }
+}
+
function setupTokenFetch() {
mockFetch.mockResolvedValue({
ok: true,
@@ -81,6 +121,8 @@ function resetMockState() {
refCounter = 0
callbackMemo = new Map()
callbackCounter = 0
+ effectMemo = new Map()
+ effectCounter = 0
}
describe("useUserWs", () => {
@@ -93,10 +135,13 @@ describe("useUserWs", () => {
vi.useRealTimers()
})
- async function mountHook(onMessage: (msg: WsMessage) => void) {
+ async function mountHook(
+ onMessage: (msg: WsMessage) => void,
+ options?: UseUserWsOptions,
+ ) {
// Re-import to get fresh module with fresh mocks
const mod = await import("./use-user-ws")
- mod.useUserWs(onMessage)
+ mod.useUserWs(onMessage, options)
// Wait for async connect to complete
await vi.runAllTimersAsync()
return mod
@@ -116,6 +161,7 @@ describe("useUserWs", () => {
setupTokenFetch()
refCounter = 0
callbackCounter = 0
+ effectCounter = 0
mod.useUserWs(cb1)
const firstCallbackId = Array.from(callbackMemo.keys()).find(k => k.startsWith("cb-"))
@@ -124,6 +170,7 @@ describe("useUserWs", () => {
// Simulate second render with different callback
refCounter = 0
callbackCounter = 0
+ effectCounter = 0
mod.useUserWs(cb2)
const secondConnect = callbackMemo.get(firstCallbackId!)?.fn
@@ -132,6 +179,68 @@ describe("useUserWs", () => {
expect(firstConnect).toBe(secondConnect)
})
+ it.each<[string, UseUserWsOptions | undefined]>([
+ ["the option is omitted", undefined],
+ ["the option is explicitly true", { requestDaemonStatusOnAuth: true }],
+ ])("auth.ok sends the complete daemon-status frame when %s", async (_label, options) => {
+ setupTokenFetch()
+
+ const onMsg = vi.fn()
+ await mountHook(onMsg, options)
+
+ const ws = MockWebSocket.instances[0]
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+
+ expect(ws.sent).toEqual([
+ JSON.stringify({ type: "auth", token: "tok-123" }),
+ JSON.stringify({ type: "check_daemon_status" }),
+ ])
+ expect(onMsg).not.toHaveBeenCalled()
+ })
+
+ it("auth.ok suppresses daemon status and remains consumed when the option is false", async () => {
+ setupTokenFetch()
+
+ const onMsg = vi.fn()
+ await mountHook(onMsg, { requestDaemonStatusOnAuth: false })
+
+ const ws = MockWebSocket.instances[0]
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+
+ expect(ws.sent).toEqual([
+ JSON.stringify({ type: "auth", token: "tok-123" }),
+ ])
+ expect(onMsg).not.toHaveBeenCalled()
+ })
+
+ it("uses the latest option on the original socket without changing connect identity", async () => {
+ setupTokenFetch()
+
+ const onMsg = vi.fn()
+ const mod = await mountHook(onMsg, { requestDaemonStatusOnAuth: false })
+ const ws = MockWebSocket.instances[0]
+ ws.simulateOpen()
+ const firstConnect = callbackMemo.get("cb-1")?.fn
+
+ refCounter = 0
+ callbackCounter = 0
+ effectCounter = 0
+ mod.useUserWs(onMsg, { requestDaemonStatusOnAuth: true })
+ const secondConnect = callbackMemo.get("cb-1")?.fn
+
+ expect(secondConnect).toBe(firstConnect)
+ expect(MockWebSocket.instances).toEqual([ws])
+
+ ws.simulateMessage({ type: "auth.ok" })
+ expect(ws.sent).toEqual([
+ JSON.stringify({ type: "auth", token: "tok-123" }),
+ JSON.stringify({ type: "check_daemon_status" }),
+ ])
+ expect(onMsg).not.toHaveBeenCalled()
+ })
+
it("effect cleanup nullifies wsRef.current and calls .close() — subsequent onclose skips reconnect", async () => {
setupTokenFetch()
@@ -285,4 +394,77 @@ describe("useUserWs", () => {
// No new connection should have been created because the timer was cleared
expect(MockWebSocket.instances.length).toBe(instancesBefore)
})
+
+ it("cleanup invalidates a pending successful token request before socket creation", async () => {
+ const tokenResponse = deferred<{
+ ok: boolean
+ json: () => Promise<{ userId: string; token: string }>
+ }>()
+ mockFetch.mockReturnValue(tokenResponse.promise)
+
+ const mod = await import("./use-user-ws")
+ mod.useUserWs(vi.fn())
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+
+ effectCleanup?.()
+ tokenResponse.resolve({
+ ok: true,
+ json: () => Promise.resolve({ userId: "stale-user", token: "stale-token" }),
+ })
+ await flushPromises()
+ await vi.advanceTimersByTimeAsync(60_000)
+
+ expect(MockWebSocket.instances).toHaveLength(0)
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it("StrictMode replay keeps only the latest socket when token requests resolve out of order", async () => {
+ const firstTokenResponse = deferred<{
+ ok: boolean
+ json: () => Promise<{ userId: string; token: string }>
+ }>()
+ const secondTokenResponse = deferred<{
+ ok: boolean
+ json: () => Promise<{ userId: string; token: string }>
+ }>()
+ mockFetch
+ .mockReturnValueOnce(firstTokenResponse.promise)
+ .mockReturnValueOnce(secondTokenResponse.promise)
+
+ const mod = await import("./use-user-ws")
+ mod.useUserWs(vi.fn())
+ replayEffects()
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+
+ secondTokenResponse.resolve({
+ ok: true,
+ json: () => Promise.resolve({ userId: "latest-user", token: "latest-token" }),
+ })
+ await flushPromises()
+ firstTokenResponse.resolve({
+ ok: true,
+ json: () => Promise.resolve({ userId: "stale-user", token: "stale-token" }),
+ })
+ await flushPromises()
+
+ expect(MockWebSocket.instances).toHaveLength(1)
+ expect(MockWebSocket.instances[0]?.url).toContain("latest-user")
+ })
+
+ it("cleanup invalidates a pending failed token request before reconnect scheduling", async () => {
+ const tokenResponse = deferred<never>()
+ mockFetch.mockReturnValue(tokenResponse.promise)
+
+ const mod = await import("./use-user-ws")
+ mod.useUserWs(vi.fn())
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+
+ effectCleanup?.()
+ tokenResponse.reject(new Error("stale token failure"))
+ await flushPromises()
+ await vi.advanceTimersByTimeAsync(60_000)
+
+ expect(MockWebSocket.instances).toHaveLength(0)
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index 805da1aa7..9d67e565d 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -18,16 +18,26 @@ const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_M
*/
export type WsMessageIncoming = WsMessage & { [key: string]: unknown }
-export function useUserWs(onMessage: (msg: WsMessageIncoming) => void, options?: { onReconnect?: () => void }): { send: (msg: object) => void } {
+export type UseUserWsOptions = {
+ onReconnect?: () => void
+ requestDaemonStatusOnAuth?: boolean
+}
+
+export function useUserWs(
+ onMessage: (msg: WsMessageIncoming) => void,
+ options?: UseUserWsOptions,
+): { send: (msg: object) => void } {
const wsRef = useRef<WebSocket | null>(null)
const reconnectDelay = useRef(WS_RECONNECT_INIT)
const onMessageRef = useRef(onMessage)
const onReconnectRef = useRef(options?.onReconnect)
+ const requestDaemonStatusOnAuthRef = useRef(options?.requestDaemonStatusOnAuth ?? true)
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const hasConnectedBeforeRef = useRef(false)
const lastMessageAtRef = useRef(0)
const pingIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
const livenessIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
+ const connectionGenerationRef = useRef(0)
useEffect(() => {
onMessageRef.current = onMessage
@@ -37,34 +47,45 @@ export function useUserWs(onMessage: (msg: WsMessageIncoming) => void, options?:
onReconnectRef.current = options?.onReconnect
}, [options?.onReconnect])
+ useEffect(() => {
+ requestDaemonStatusOnAuthRef.current = options?.requestDaemonStatusOnAuth ?? true
+ }, [options?.requestDaemonStatusOnAuth])
+
const connectRef = useRef<(() => Promise<void>) | null>(null)
- const scheduleReconnect = useCallback(() => {
+ const scheduleReconnect = useCallback((generation: number) => {
+ if (generation !== connectionGenerationRef.current) return
const delay = Math.min(reconnectDelay.current, WS_RECONNECT_MAX)
reconnectDelay.current = Math.min(delay * 2, WS_RECONNECT_MAX)
reconnectTimerRef.current = setTimeout(() => {
+ if (generation !== connectionGenerationRef.current) return
void connectRef.current?.()
}, delay + Math.random() * 500)
}, [])
const connect = useCallback(async () => {
+ const generation = connectionGenerationRef.current + 1
+ connectionGenerationRef.current = generation
let userId: string
let authToken: string
let wsPort: number = WS_DO_PORT_DEFAULT
try {
const res = await fetch("/api/ws/token")
if (!res.ok) {
+ if (generation !== connectionGenerationRef.current) return
console.warn("[ws] token fetch failed:", res.status)
- scheduleReconnect()
+ scheduleReconnect(generation)
return
}
const body = await res.json() as { userId: string; token: string; wsPort?: number }
+ if (generation !== connectionGenerationRef.current) return
userId = body.userId
authToken = body.token
if (body.wsPort) wsPort = body.wsPort
} catch (err) {
+ if (generation !== connectionGenerationRef.current) return
console.warn("[ws] token fetch error:", err)
- scheduleReconnect()
+ scheduleReconnect(generation)
return
}
@@ -74,10 +95,12 @@ export function useUserWs(onMessage: (msg: WsMessageIncoming) => void, options?:
let ws: WebSocket
try {
+ if (generation !== connectionGenerationRef.current) return
ws = new WebSocket(url)
} catch (err) {
+ if (generation !== connectionGenerationRef.current) return
console.warn("[ws] WebSocket creation failed:", err)
- scheduleReconnect()
+ scheduleReconnect(generation)
return
}
wsRef.current = ws
@@ -109,7 +132,9 @@ export function useUserWs(onMessage: (msg: WsMessageIncoming) => void, options?:
try {
const msg = JSON.parse(e.data)
if (msg.type === "auth.ok") {
- ws.send(JSON.stringify({ type: "check_daemon_status" }))
+ if (requestDaemonStatusOnAuthRef.current) {
+ ws.send(JSON.stringify({ type: "check_daemon_status" }))
+ }
return
}
onMessageRef.current(msg as WsMessageIncoming)
@@ -122,7 +147,7 @@ export function useUserWs(onMessage: (msg: WsMessageIncoming) => void, options?:
if (ws !== wsRef.current) return
if (pingIntervalRef.current) { clearInterval(pingIntervalRef.current); pingIntervalRef.current = null }
if (livenessIntervalRef.current) { clearInterval(livenessIntervalRef.current); livenessIntervalRef.current = null }
- scheduleReconnect()
+ scheduleReconnect(generation)
}
}, [scheduleReconnect])
@@ -133,6 +158,7 @@ export function useUserWs(onMessage: (msg: WsMessageIncoming) => void, options?:
useEffect(() => {
connect()
return () => {
+ connectionGenerationRef.current += 1
if (reconnectTimerRef.current !== null) {
clearTimeout(reconnectTimerRef.current)
reconnectTimerRef.current = null
diff --git a/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts b/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts
index 3355def44..be172e2d9 100644
--- a/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts
+++ b/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts
@@ -10,6 +10,7 @@ test("server → channel → message", async ({ asUser }) => {
await createServer(page, `E2E Server ${Date.now()}`)
const channelUrl = page.url()
expect(channelUrl).toMatch(/\/c\/channels\/[^/]+\/[^/]+/)
+ const channelId = new URL(channelUrl).pathname.split("/").at(-1)!
const firstBody = `hello world ${Date.now()}`
const firstResponsePromise = page.waitForResponse((response) => {
@@ -75,20 +76,61 @@ test("server → channel → message", async ({ asUser }) => {
await expect(page.getByTestId(tid.message(firstPayload.message.id))).toHaveCount(1)
await expect(page.getByTestId(tid.message(imePayload.message.id))).toHaveCount(1)
+ // Force this reload through the network-backed query path while preserving
+ // the composer's localStorage draft. The app keeps this database open, so
+ // clear the persister store in-place rather than using deleteDatabase.
+ await page.evaluate(() => new Promise<void>((resolve, reject) => {
+ const open = indexedDB.open("keyval-store")
+ open.onerror = () => reject(open.error ?? new Error("failed to open query persister"))
+ open.onsuccess = () => {
+ const db = open.result
+ if (!db.objectStoreNames.contains("keyval")) {
+ db.close()
+ resolve()
+ return
+ }
+ let tx: IDBTransaction
+ try {
+ tx = db.transaction("keyval", "readwrite")
+ tx.objectStore("keyval").clear()
+ } catch (error) {
+ db.close()
+ reject(error)
+ return
+ }
+ tx.oncomplete = () => {
+ db.close()
+ resolve()
+ }
+ tx.onerror = () => {
+ const error = tx.error ?? new Error("failed to clear query persister")
+ db.close()
+ reject(error)
+ }
+ tx.onabort = () => {
+ const error = tx.error ?? new Error("query persister clear aborted")
+ db.close()
+ reject(error)
+ }
+ }
+ }))
+
let releaseMessages!: () => void
const messagesGate = new Promise<void>((resolve) => { releaseMessages = resolve })
- let intercepted = false
await page.route("**/api/community/channels/*/messages*", async (route) => {
if (route.request().method() !== "GET") {
await route.continue()
return
}
- intercepted = true
await messagesGate
await route.continue()
})
+ const messagesRequestPromise = page.waitForRequest((request) => {
+ return request.method() === "GET"
+ && new URL(request.url()).pathname === `/api/community/channels/${channelId}/messages`
+ }, { timeout: 45_000 })
await page.reload({ waitUntil: "commit" })
- await expect.poll(() => intercepted).toBe(true)
+ await messagesRequestPromise
releaseMessages()
await expect(composerEditable(page)).toContainText(draft)
await expect(page.getByTestId(tid.message(firstPayload.message.id))).toHaveCount(1)
@@ -111,20 +153,30 @@ test("server → channel → message", async ({ asUser }) => {
await page.keyboard.press("ControlOrMeta+A")
await page.keyboard.press("Backspace")
await page.evaluate(() => {
+ Object.defineProperty(window, "__messageStreamNonceCalls", {
+ configurable: true,
+ writable: true,
+ value: 0,
+ })
Object.defineProperty(window.crypto, "randomUUID", {
configurable: true,
- value: () => "00000000-0000-4000-8000-000000000001",
+ value: () => {
+ ;(window as unknown as { __messageStreamNonceCalls: number }).__messageStreamNonceCalls++
+ return "00000000-0000-4000-8000-000000000001"
+ },
})
})
let releasePendingSend!: () => void
const pendingSendGate = new Promise<void>((resolve) => { releasePendingSend = resolve })
let pendingSendIntercepted = false
let pendingSendCompleted = false
+ let pendingPostCount = 0
await page.route("**/api/community/channels/*/messages", async (route) => {
if (route.request().method() !== "POST") {
await route.continue()
return
}
+ pendingPostCount++
pendingSendIntercepted = true
await pendingSendGate
await route.fulfill({
@@ -139,6 +191,10 @@ test("server → channel → message", async ({ asUser }) => {
await page.keyboard.press("Enter")
await expect(restored).toHaveText("")
await expect.poll(() => pendingSendIntercepted).toBe(true)
+ await expect.poll(() => page.evaluate(() =>
+ (window as unknown as { __messageStreamNonceCalls: number }).__messageStreamNonceCalls,
+ )).toBe(1)
+ await expect.poll(() => pendingPostCount).toBe(1)
const rejectedDraft = `rejected draft ${Date.now()}`
await restored.pressSequentially(rejectedDraft)
@@ -160,7 +216,12 @@ test("server → channel → message", async ({ asUser }) => {
buffer: Buffer.from("keep me"),
})
await expect(page.getByText("rejected.txt", { exact: true })).toBeVisible()
+ await expect.poll(() => restored.evaluate((element) => document.activeElement === element)).toBe(true)
await page.keyboard.press("Enter")
+ await expect.poll(() => page.evaluate(() =>
+ (window as unknown as { __messageStreamNonceCalls: number }).__messageStreamNonceCalls,
+ )).toBe(2)
+ await expect.poll(() => pendingPostCount).toBe(1)
await expect(restored).toContainText(rejectedDraft)
await expect(page.getByText("rejected.txt", { exact: true })).toBeVisible()
await expect.poll(() => page.evaluate(() =>
@@ -172,5 +233,63 @@ test("server → channel → message", async ({ asUser }) => {
await page.unroute("**/api/community/channels/*/messages")
await page.goto("/c/me", { waitUntil: "commit" })
await page.goto(channelUrl, { waitUntil: "commit" })
- await expect(composerEditable(page)).toContainText(rejectedDraft)
+ const persisted = composerEditable(page)
+ await expect(persisted).toContainText(rejectedDraft)
+
+ await page.evaluate(() => {
+ Object.defineProperty(window.crypto, "randomUUID", {
+ configurable: true,
+ value: () => "00000000-0000-4000-8000-000000000002",
+ })
+ })
+ await page.locator('input[type="file"]').last().setInputFiles({
+ name: "accepted.txt",
+ mimeType: "text/plain",
+ buffer: Buffer.from("transfer me"),
+ })
+ await expect(page.getByText("accepted.txt", { exact: true })).toBeVisible()
+ await expect.poll(() => persisted.evaluate((element) => document.activeElement === element)).toBe(true)
+ const acceptedResponsePromise = page.waitForResponse((response) => {
+ const pathname = new URL(response.url()).pathname
+ return response.request().method() === "POST"
+ && /^\/api\/community\/channels\/[^/]+\/messages$/.test(pathname)
+ })
+ const acceptedUploadResponsePromise = page.waitForResponse((response) => {
+ const pathname = new URL(response.url()).pathname
+ return response.request().method() === "POST"
+ && /^\/api\/community\/channels\/[^/]+\/attachments$/.test(pathname)
+ })
+ await page.keyboard.press("Enter")
+ const acceptedUploadResponse = await acceptedUploadResponsePromise
+ expect(acceptedUploadResponse.ok()).toBe(true)
+ const acceptedAttachment = await acceptedUploadResponse.json() as {
+ id: string
+ filename: string
+ contentType: string
+ size: number
+ }
+ expect(acceptedAttachment).toEqual(expect.objectContaining({
+ filename: "accepted.txt",
+ contentType: "text/plain",
+ size: 11,
+ }))
+ const acceptedResponse = await acceptedResponsePromise
+ expect(acceptedResponse.status()).toBe(201)
+ const acceptedRequest = acceptedResponse.request().postDataJSON() as { attachments?: string[] }
+ expect(acceptedRequest.attachments).toEqual([acceptedAttachment.id])
+ const acceptedPayload = await acceptedResponse.json() as { message: { id: string } }
+ const attachmentPath = new URL(acceptedResponse.url()).pathname.replace(
+ /\/messages$/,
+ `/attachments/${acceptedAttachment.id}`,
+ )
+ const persistedAttachment = await page.request.get(attachmentPath)
+ expect(persistedAttachment.status()).toBe(200)
+ expect(persistedAttachment.headers()["content-type"]).toContain("text/plain")
+ expect((await persistedAttachment.body()).toString()).toBe("transfer me")
+ await expectMessageVisible(page, rejectedDraft)
+ const acceptedMessage = page.getByTestId(tid.message(acceptedPayload.message.id))
+ await expect(acceptedMessage).toHaveCount(1)
+ await expect(acceptedMessage.getByText("accepted.txt", { exact: true })).toBeVisible()
+ await expect(persisted).toHaveText("")
+ await expect(page.getByTestId(tid.composerInput).locator("../..").getByText("accepted.txt", { exact: true })).toHaveCount(0)
})
diff --git a/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts b/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts
index f70417f9a..3d146915c 100644
--- a/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts
+++ b/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts
@@ -22,12 +22,30 @@ test.describe.serial("multi-user realtime", () => {
const alice = await asUser("alice")
const bob = await asUser("bob")
await alice.page.goto(`/c/channels/${serverId}/${channelId}`)
+ const messagesPath = `/api/community/channels/${channelId}/messages`
+ const bobInitialMessagesPromise = bob.page.waitForResponse((response) => {
+ return response.request().method() === "GET"
+ && new URL(response.url()).pathname === messagesPath
+ })
await bob.page.goto(`/c/channels/${serverId}/${channelId}`)
await alice.page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })
await bob.page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })
+ // A committed channel URL can still be rendering its initial skeleton.
+ // Wait for Bob's message query and composer surface before Alice sends, so
+ // the final assertion proves realtime delivery rather than initial fetch.
+ const bobInitialMessages = await bobInitialMessagesPromise
+ expect(bobInitialMessages.status()).toBe(200)
+ await expect(composerEditable(bob.page)).toBeVisible()
+
const body = `live from alice ${Date.now()}`
+ const aliceMessagePromise = alice.page.waitForResponse((response) => {
+ return response.request().method() === "POST"
+ && new URL(response.url()).pathname === messagesPath
+ })
await sendMessage(alice.page, body)
+ const aliceMessage = await aliceMessagePromise
+ expect(aliceMessage.status()).toBe(201)
// Bob sees it without reloading.
await expectMessageVisible(bob.page, body)
})
diff --git a/src/web/src/test/e2e-ui/13-mentions.spec.ts b/src/web/src/test/e2e-ui/13-mentions.spec.ts
index 7d2f9ab86..a3771e763 100644
--- a/src/web/src/test/e2e-ui/13-mentions.spec.ts
+++ b/src/web/src/test/e2e-ui/13-mentions.spec.ts
@@ -78,25 +78,34 @@ test.describe.serial("mentions — mandatory discriminator", () => {
await mentionAndSend(page, carol.id, "msgCarol")
// Both messages render a single `@John Doe` pill with NO visible tag.
- const bobMsg = page.getByText("msgBob", { exact: false }).first()
- const carolMsg = page.getByText("msgCarol", { exact: false }).first()
+ const bobMsg = page.locator("[data-msg-id]").filter({ hasText: "msgBob" }).first()
+ const carolMsg = page.locator("[data-msg-id]").filter({ hasText: "msgCarol" }).first()
await expect(bobMsg).toBeVisible({ timeout: 15_000 })
await expect(carolMsg).toBeVisible({ timeout: 15_000 })
- // Wait for BOTH pills to exist before touching either — a bare `.nth(1)`
- // click would otherwise hang to the 60s test timeout if the second pill
- // hasn't rendered yet (the observed flake).
- const pills = page.locator("button", { hasText: "@John Doe" })
- await expect(pills).toHaveCount(2, { timeout: 15_000 })
- const bobPill = pills.first()
+ // Bind each pill to its marker-bearing message row. The canonical GET can
+ // reorder rows while a profile is loading, so a global live `nth` locator
+ // can otherwise retarget from Carol's pill back to Bob's.
+ const bobPill = bobMsg.getByRole("button", { name: "@John Doe", exact: true })
+ const carolPill = carolMsg.getByRole("button", { name: "@John Doe", exact: true })
+ await expect(bobPill).toHaveCount(1)
+ await expect(carolPill).toHaveCount(1)
await expect(bobPill).toBeVisible()
await expect(bobPill).not.toContainText("#")
// Click Bob's pill → the profile card shows Bob's discriminator, not Carol's.
const card = page.getByTestId(tid.profileCard)
+ const bobProfilePromise = page.waitForResponse((response) => {
+ return response.request().method() === "GET"
+ && new URL(response.url()).pathname === `/api/community/users/${userId("bob")}/profile`
+ })
await expect(async () => {
await bobPill.click({ timeout: 5_000 })
await expect(card).toBeVisible({ timeout: 5_000 })
}).toPass({ timeout: 30_000 })
+ // The card renders fallback member data before its exact user profile is
+ // enriched. Gate the discriminator oracle on that observable boundary.
+ const bobProfile = await bobProfilePromise
+ expect(bobProfile.status()).toBe(200)
await expect(card).toContainText(`#${bob.discriminator}`)
await expect(card).not.toContainText(`#${carol.discriminator}`)
// Dismiss the first card, then open the second pill's. The popover renders
@@ -105,7 +114,10 @@ test.describe.serial("mentions — mandatory discriminator", () => {
// guarantee the overlay has detached. Retry the whole dismiss→click so a
// transient interception (or a stray still-open card) re-presses Escape and
// tries again, instead of hanging the bare click to the 60s test timeout.
- const carolPill = pills.nth(1)
+ const carolProfilePromise = page.waitForResponse((response) => {
+ return response.request().method() === "GET"
+ && new URL(response.url()).pathname === `/api/community/users/${userId("carol")}/profile`
+ })
await expect(async () => {
if (await card.isVisible()) {
await page.keyboard.press("Escape")
@@ -114,6 +126,8 @@ test.describe.serial("mentions — mandatory discriminator", () => {
await carolPill.click({ timeout: 5_000 })
await expect(card).toBeVisible({ timeout: 5_000 })
}).toPass({ timeout: 30_000 })
+ const carolProfile = await carolProfilePromise
+ expect(carolProfile.status()).toBe(200)
await expect(card).toContainText(`#${carol.discriminator}`)
})
diff --git a/src/web/src/test/e2e-ui/_fixtures/actions.ts b/src/web/src/test/e2e-ui/_fixtures/actions.ts
index fd098a01e..ad7659ee7 100644
--- a/src/web/src/test/e2e-ui/_fixtures/actions.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/actions.ts
@@ -24,7 +24,7 @@ export async function createServer(page: Page, name: string, opts?: { autoDialog
await page.getByTestId(tid.createServerSubmit).click()
// Land on the new server's default channel.
- await page.waitForURL(/\/c\/channels\/[^/]+\/[^/]+/, { timeout: 20_000, waitUntil: "commit" })
+ await page.waitForURL(/\/c\/channels\/[^/]+\/[^/]+/, { timeout: 45_000, waitUntil: "commit" })
const m = page.url().match(/\/c\/channels\/([^/]+)\//)
if (!m) throw new Error(`createServer: no serverId in URL ${page.url()}`)
return m[1]
diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.ts
index 972413523..5550155a6 100644
--- a/src/ws-do/src/index.test.ts
+++ b/src/ws-do/src/index.test.ts
@@ -1,778 +1,108 @@
-import { describe, it, expect, vi, beforeEach } from "vitest"
-import { createMockDONamespace } from "./__mocks__/cf"
-
-// Mock ws-durable / rate-limit-do so the router import doesn't pull in cloudflare:workers
-vi.mock("./ws-durable", () => ({
- WebSocketDurableObject: class { },
-}))
-vi.mock("./rate-limit-do", () => ({
- RateLimitDurableObject: class { },
-}))
-
-const mockHashCredential = vi.fn(async (bearer: string) => `sha256:${bearer}`)
-const mockDoNameFromHash = vi.fn((hash: string) => hash.slice(0, 32))
-const mockGetActiveDoNamesForMachine = vi.fn(async (_db: unknown, _machineId: string) => [] as string[])
-
-vi.mock("@alook/shared", () => {
- const noopLogger = { debug: () => { }, info: () => { }, warn: () => { }, error: () => { }, child() { return this } }
- return {
- // Real WS event-type strings the DO reads at runtime (#5 T2 — ws-do
- // broadcasts now use WS_EVENTS.* instead of raw literals). Only the keys
- // this suite exercises are needed; values match @alook/shared.
- WS_EVENTS: {
- BOT_AUDIT_EVENT: "community:bot.audit_event",
- },
- createDb: () => ({}),
- createLogger: () => noopLogger,
- queries: {
- communityMachine: {
- hashCredential: (bearer: string) => mockHashCredential(bearer),
- doNameFromHash: (hash: string) => mockDoNameFromHash(hash),
- getActiveDoNamesForMachine: (db: unknown, machineId: string) => mockGetActiveDoNamesForMachine(db, machineId),
- },
- },
- }
-})
-
-import handler from "./index"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { readFileSync } from "node:fs"
+import {
+ createRouterTestContext,
+ loadRouter,
+ getSharedMocks,
+ type RouterHandler,
+ type RouterTestContext,
+} from "./routes/test-harness"
+
+const sharedMocks = getSharedMocks()
+const mockHashCredential = sharedMocks.hashCredential
+const mockDoNameFromHash = sharedMocks.doNameFromHash
+const mockGetActiveDoNamesForMachine = sharedMocks.getActiveDoNamesForMachine
+const loggerMocks = {
+ child: sharedMocks.loggerChild,
+ debug: sharedMocks.loggerDebug,
+}
describe("ws-do router", () => {
- let doMock: ReturnType<typeof createMockDONamespace>
- let env: { WS_DO: DurableObjectNamespace }
+ let handler: RouterHandler
+ let doMock: RouterTestContext["doMock"]
+ let rateLimitMock: RouterTestContext["rateLimitMock"]
+ let env: RouterTestContext["env"]
- beforeEach(() => {
+ beforeEach(async () => {
+ vi.resetModules()
vi.clearAllMocks()
- doMock = createMockDONamespace()
- env = { WS_DO: doMock.namespace } as unknown as { WS_DO: DurableObjectNamespace }
+ const context = createRouterTestContext()
+ doMock = context.doMock
+ rateLimitMock = context.rateLimitMock
+ env = context.env
+ handler = await loadRouter()
})
- describe("broadcast route", () => {
- it("forwards POST /broadcast/user/:userId to correct DO instance", async () => {
- doMock.stubFetch.mockResolvedValue(new Response("ok"))
- const req = new Request("http://localhost/broadcast/user/user-123", {
- method: "POST",
- body: JSON.stringify({ type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" }),
- })
-
- const res = await handler.fetch(req, env as any)
-
- expect(doMock.idFromName).toHaveBeenCalledWith("user:user-123")
- expect(doMock.get).toHaveBeenCalledWith("mock-do-id")
- expect(doMock.stubFetch).toHaveBeenCalled()
- const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
- expect(stubReq.url).toBe("http://internal/broadcast")
- expect(stubReq.method).toBe("POST")
- expect(res.status).toBe(200)
- })
- })
-
- describe("POST /internal/broadcast-bot-audit-event", () => {
- it("forwards a well-formed audit event to the owner's user-DO with the community:bot.audit_event shape", async () => {
- doMock.stubFetch.mockResolvedValue(new Response("ok"))
- const payload = {
- botId: "bot_1",
- ownerUserId: "owner_1",
- id: "evt_1",
- kind: "wake_trigger",
- payload: {
- messageId: "msg_1",
- channel: "/srv_1/general",
- seq: 7,
- senderId: "u_human",
- senderHandle: "@gustavo#0042",
- reason: "unread",
- },
- createdAt: "2026-07-23T00:00:00.000Z",
- }
- const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(payload),
- })
-
- const res = await handler.fetch(req, env as any)
-
- expect(res.status).toBe(204)
- expect(doMock.idFromName).toHaveBeenCalledWith("user:owner_1")
- const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
- expect(stubReq.url).toBe("http://internal/broadcast")
- const body = JSON.parse(await stubReq.text()) as Record<string, unknown>
- // Matches the shape ws-durable.ts emits for daemon-originating frames.
- expect(body.type).toBe("community:bot.audit_event")
- expect(body.botId).toBe("bot_1")
- expect(body.id).toBe("evt_1")
- expect(body.kind).toBe("wake_trigger")
- expect(body.createdAt).toBe(payload.createdAt)
- expect(body.payload).toEqual(payload.payload)
- })
-
- it("400s on invalid JSON", async () => {
- const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {
- method: "POST",
- body: "not json",
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(400)
- })
-
- it("400s on a payload missing required fields", async () => {
- const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ botId: "bot_1" }),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(400)
- })
-
- it("400s on an unknown kind (rejects browser-untypeable rows at the boundary)", async () => {
- const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- botId: "bot_1",
- ownerUserId: "owner_1",
- id: "evt_1",
- kind: "some_future_kind",
- payload: {},
- createdAt: "2026-07-23T00:00:00.000Z",
- }),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(400)
- })
-
- it("503s and never broadcasts when the DO fetch throws", async () => {
- doMock.stubFetch.mockRejectedValue(new Error("do down"))
- const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- botId: "bot_1",
- ownerUserId: "owner_1",
- id: "evt_1",
- kind: "wake_trigger",
- payload: {},
- createdAt: "2026-07-23T00:00:00.000Z",
- }),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(503)
- })
-
- it("accepts kind: 'model_changed' (guards the AUDIT_KINDS allowlist)", async () => {
- doMock.stubFetch.mockResolvedValue(new Response("ok"))
- const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- botId: "bot_1",
- ownerUserId: "owner_1",
- id: "evt_m",
- kind: "model_changed",
- payload: { from: "claude-opus-4-6", to: "claude-sonnet-4-6" },
- createdAt: "2026-07-26T00:00:00.000Z",
- }),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(204)
- const body = JSON.parse(await (doMock.stubFetch.mock.calls[0][0] as Request).text()) as Record<string, unknown>
- expect(body.kind).toBe("model_changed")
- expect(body.payload).toEqual({ from: "claude-opus-4-6", to: "claude-sonnet-4-6" })
- })
- })
-
- describe("POST /presence/users", () => {
- it("empty ids array short-circuits and performs zero DO fetches", async () => {
- const req = new Request("http://localhost/presence/users", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ids: [] }),
- })
-
- const res = await handler.fetch(req, env as any)
-
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ online: [] })
- expect(doMock.stubFetch).not.toHaveBeenCalled()
- })
-
- it("returns only online ids from mixed responses", async () => {
- doMock.stubFetch.mockImplementation((req: Request) => {
- // Round-robin: we can't tell which id -- rely on call order.
- const idx = doMock.stubFetch.mock.calls.length - 1
- const online = idx % 2 === 0 // u1 online, u2 offline, u3 online
- return Promise.resolve(new Response(JSON.stringify({ online }), { status: 200 }))
- })
-
- const req = new Request("http://localhost/presence/users", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ids: ["u1", "u2", "u3"] }),
- })
-
- const res = await handler.fetch(req, env as any)
- const body = await res.json() as { online: string[] }
-
- expect(res.status).toBe(200)
- expect(body.online.sort()).toEqual(["u1", "u3"])
- })
-
- it("returns empty online list when all ids are offline", async () => {
- doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ online: false }), { status: 200 }))
-
- const req = new Request("http://localhost/presence/users", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ids: ["a", "b", "c"] }),
- })
-
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ online: [] })
- })
-
- it("passes ?userId=<id> on every /check-user-online request — the target DO can't recover its own name from ctx (Fix 3)", async () => {
- doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ online: true }), { status: 200 }))
-
- const req = new Request("http://localhost/presence/users", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ids: ["bot-1", "human-2"] }),
- })
-
- await handler.fetch(req, env as any)
-
- const urls = doMock.stubFetch.mock.calls.map(([r]: [Request]) => r.url)
- expect(urls).toContain("http://internal/check-user-online?userId=bot-1")
- expect(urls).toContain("http://internal/check-user-online?userId=human-2")
- })
-
- it("returns 400 on malformed body — missing ids", async () => {
- const req = new Request("http://localhost/presence/users", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({}),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(400)
- })
-
- it("returns 400 on malformed body — ids is not an array", async () => {
- const req = new Request("http://localhost/presence/users", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ids: "u1" }),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(400)
- })
-
- it("returns 400 on malformed body — non-string entries", async () => {
- const req = new Request("http://localhost/presence/users", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ids: ["u1", 42, "u3"] }),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(400)
- })
-
- it("returns 400 on invalid JSON body", async () => {
- const req = new Request("http://localhost/presence/users", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: "not json",
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(400)
- })
-
- it("returns 400 when ids array exceeds cap", async () => {
- const ids = Array.from({ length: 1001 }, (_, i) => `u${i}`)
- const req = new Request("http://localhost/presence/users", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ids }),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(400)
- })
-
- it("tolerates a per-id DO fetch throwing — other ids still evaluated", async () => {
- let call = 0
- doMock.stubFetch.mockImplementation(() => {
- call++
- if (call === 1) return Promise.reject(new Error("boom"))
- return Promise.resolve(new Response(JSON.stringify({ online: true }), { status: 200 }))
- })
-
- const req = new Request("http://localhost/presence/users", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ids: ["u1", "u2", "u3"] }),
- })
- const res = await handler.fetch(req, env as any)
- const body = await res.json() as { online: string[] }
-
- expect(res.status).toBe(200)
- expect(body.online.sort()).toEqual(["u2", "u3"])
- })
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+ vi.resetModules()
+ doMock = undefined as unknown as RouterTestContext["doMock"]
+ rateLimitMock = undefined as unknown as RouterTestContext["rateLimitMock"]
+ env = undefined as unknown as RouterTestContext["env"]
+ handler = undefined as unknown as RouterHandler
})
- describe("compat: GET /presence/user/:uid", () => {
- it("still returns { online: boolean } (kept for rollout safety)", async () => {
- doMock.stubFetch.mockResolvedValue(
- new Response(JSON.stringify({ online: true }), { status: 200 })
- )
- const req = new Request("http://localhost/presence/user/user-789", { method: "GET" })
- const res = await handler.fetch(req, env as any)
+ describe("root contract", () => {
+ it("exports exactly the two Durable Object classes and the default fetch handler", async () => {
+ const routerModule = await import("./index")
- expect(doMock.idFromName).toHaveBeenCalledWith("user:user-789")
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ online: true })
- const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
- expect(stubReq.url).toBe("http://internal/check-user-online?userId=user-789")
+ expect(Object.keys(routerModule).sort()).toEqual([
+ "RateLimitDurableObject",
+ "WebSocketDurableObject",
+ "default",
+ ])
+ expect(Object.keys(routerModule.default)).toEqual(["fetch"])
})
- })
- describe("WebSocket route", () => {
- it("forwards GET with userId param to DO instance", async () => {
- doMock.stubFetch.mockResolvedValue(new Response(null, { status: 200 }))
- const req = new Request("http://localhost/?userId=user-456", {
- headers: { Upgrade: "websocket" },
+ it("falls through a known path with the wrong method to the websocket/default routing", async () => {
+ doMock.stubFetch.mockResolvedValue(new Response("fallback"))
+ const req = new Request("http://localhost/rate-limit/check?userId=user-fallback", {
+ method: "GET",
})
const res = await handler.fetch(req, env as any)
- expect(doMock.idFromName).toHaveBeenCalledWith("user:user-456")
- expect(doMock.get).toHaveBeenCalledWith("mock-do-id")
+ expect(doMock.idFromName).toHaveBeenCalledWith("user:user-fallback")
expect(doMock.stubFetch).toHaveBeenCalledWith(req)
+ expect(await res.text()).toBe("fallback")
})
- it("returns 400 when userId is missing", async () => {
- const req = new Request("http://localhost/", {
- headers: { Upgrade: "websocket" },
- })
-
- const res = await handler.fetch(req, env as any)
-
- expect(res.status).toBe(400)
- expect(await res.text()).toBe("userId required")
- expect(doMock.stubFetch).not.toHaveBeenCalled()
- })
- })
-
- describe("community-machine Bearer auth", () => {
- beforeEach(() => {
- mockHashCredential.mockClear()
- mockDoNameFromHash.mockClear()
- })
+ it("keeps every old handler in order and inserts bulk broadcast immediately after singular user", () => {
+ const source = readFileSync(new URL("./index.ts", import.meta.url), "utf8")
+ const orderedHandlers = [...source.matchAll(/response = await (handle\w+)\(context\)/g)]
+ .map((match) => match[1])
- it("names DO from sha256(bearer).slice(0,32) with zero D1 reads", async () => {
- mockHashCredential.mockResolvedValue("0".repeat(32) + "1".repeat(32))
- mockDoNameFromHash.mockReturnValue("0".repeat(32))
- doMock.stubFetch.mockResolvedValue(new Response(null, { status: 200 }))
- const req = new Request("http://localhost/", {
- headers: { Upgrade: "websocket", Authorization: "Bearer cmk_abc" },
- })
- const res = await handler.fetch(req, env as any)
- expect(mockHashCredential).toHaveBeenCalledWith("cmk_abc")
- expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:" + "0".repeat(32))
- expect(res.status).toBe(200)
+ expect(orderedHandlers).toEqual([
+ "handleDaemonBroadcast",
+ "handleUserBroadcast",
+ "handleUsersBroadcast",
+ "handleAuditBroadcast",
+ "handleBatchPresence",
+ "handleSinglePresence",
+ "handleMachinePush",
+ "handleMachineWake",
+ "handleMachineReset",
+ "handleMachineBatchReset",
+ "handleMachineModelSwitch",
+ "handleMachineProviderSwitch",
+ "handleMachineNap",
+ "handleMachineForceClose",
+ ])
})
- it("returns 400 for legacy ?token=cmt_ requests (no 426, no body)", async () => {
- const req = new Request("http://localhost/?token=cmt_legacy", {
- headers: { Upgrade: "websocket" },
+ it("sends a wrong-method bulk path through the existing upgrade fallback", async () => {
+ doMock.stubFetch.mockResolvedValue(new Response("fallback"))
+ const req = new Request("http://localhost/broadcast/users?userId=user-fallback", {
+ method: "GET",
})
- const res = await handler.fetch(req, env as any)
- // The 426 legacy branch was deleted; the request falls through to the
- // "no userId" branch, which 400s.
- expect(res.status).toBe(400)
- expect(doMock.get).not.toHaveBeenCalled()
- })
- it("routes missing Authorization without cmk_ to the default handler (no auth path)", async () => {
- const req = new Request("http://localhost/", {
- headers: { Upgrade: "websocket" },
- })
const res = await handler.fetch(req, env as any)
- // No userId → 400 (existing default). We assert we do NOT hit the
- // credential-hash path or touch a DO under community-machine:*.
- expect(mockHashCredential).not.toHaveBeenCalled()
- expect(res.status).toBe(400)
- })
- })
- describe("POST /community-machine/by-id/:machineId/forward-agent-wake", () => {
- beforeEach(() => {
- mockGetActiveDoNamesForMachine.mockReset()
- mockGetActiveDoNamesForMachine.mockResolvedValue([])
- })
-
- it("zero active doNames → { sent: 0 } without touching any DO", async () => {
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
- method: "POST",
- body: JSON.stringify({ type: "agent:wake" }),
- })
- const res = await handler.fetch(req, env as any)
-
- expect(mockGetActiveDoNamesForMachine).toHaveBeenCalledWith({}, "machine-1")
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ sent: 0 })
- expect(doMock.stubFetch).not.toHaveBeenCalled()
- })
-
- it("single active doName, daemon connected → forwards and aggregates sent count", async () => {
- mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])
- doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
-
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ type: "agent:wake", agentId: "bot-1" }),
- })
- const res = await handler.fetch(req, env as any)
-
- expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-abc")
- const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
- expect(stubReq.url).toBe("http://internal/forward-agent-wake")
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ sent: 1 })
- })
-
- it("daemon offline (DO reports { sent: 0 }) → does not count as delivered", async () => {
- mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])
- doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 0 }), { status: 200 }))
-
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
- method: "POST",
- body: JSON.stringify({ type: "agent:wake" }),
- })
- const res = await handler.fetch(req, env as any)
-
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ sent: 0 })
- })
-
- it("multi-doName fan-out: both DOs hit, aggregate sums delivered counts", async () => {
- mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b"])
- let call = 0
- doMock.stubFetch.mockImplementation(() => {
- call++
- const sent = call === 1 ? 0 : 1
- return Promise.resolve(new Response(JSON.stringify({ sent }), { status: 200 }))
- })
-
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
- method: "POST",
- body: JSON.stringify({ type: "agent:wake" }),
- })
- const res = await handler.fetch(req, env as any)
-
- expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-a")
- expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-b")
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ sent: 1 })
- })
-
- it("DO fetch throws — tolerated, other doNames still evaluated", async () => {
- mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b"])
- let call = 0
- doMock.stubFetch.mockImplementation(() => {
- call++
- if (call === 1) return Promise.reject(new Error("network error"))
- return Promise.resolve(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
- })
-
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
- method: "POST",
- body: JSON.stringify({ type: "agent:wake" }),
- })
- const res = await handler.fetch(req, env as any)
-
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ sent: 1 })
- })
-
- it("DO fetch throws with no delivery → retryable 503", async () => {
- mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a"])
- doMock.stubFetch.mockRejectedValue(new Error("network error"))
-
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
- method: "POST",
- body: JSON.stringify({ type: "agent:wake" }),
- })
- const res = await handler.fetch(req, env as any)
-
- expect(res.status).toBe(503)
- expect(await res.json()).toEqual({ error: "failed to forward agent wake" })
- })
-
- it("non-2xx or malformed DO responses with no delivery → retryable 503", async () => {
- mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b"])
- let call = 0
- doMock.stubFetch.mockImplementation(() => {
- call++
- if (call === 1) return Promise.resolve(new Response("oops", { status: 502 }))
- return Promise.resolve(new Response(JSON.stringify({ sent: "bad" }), { status: 200 }))
- })
-
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
- method: "POST",
- body: JSON.stringify({ type: "agent:wake" }),
- })
- const res = await handler.fetch(req, env as any)
-
- expect(res.status).toBe(503)
- expect(await res.json()).toEqual({ error: "failed to forward agent wake" })
- })
-
- it("DB lookup failure → retryable 503, not offline { sent: 0 }", async () => {
- mockGetActiveDoNamesForMachine.mockRejectedValue(new Error("d1 unreachable"))
-
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
- method: "POST",
- body: JSON.stringify({ type: "agent:wake" }),
- })
- const res = await handler.fetch(req, env as any)
-
- expect(res.status).toBe(503)
- expect(await res.json()).toEqual({ error: "failed to resolve machine" })
- expect(doMock.stubFetch).not.toHaveBeenCalled()
- })
- })
-
- describe("POST /community-machine/by-id/:machineId/forward-agent-reset", () => {
- const validBody = {
- agentId: "bot-1",
- config: { version: 1, runtime: "claude", model: { kind: "default" }, mode: { kind: "default" } },
- launchId: "l-1",
- }
-
- beforeEach(() => {
- mockGetActiveDoNamesForMachine.mockReset()
- mockGetActiveDoNamesForMachine.mockResolvedValue([])
- })
-
- it("rejects missing agentId with 400 without touching D1 or the DOs", async () => {
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-reset", {
- method: "POST",
- body: JSON.stringify({ config: validBody.config, launchId: "l-1" }),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(400)
- expect(mockGetActiveDoNamesForMachine).not.toHaveBeenCalled()
- expect(doMock.stubFetch).not.toHaveBeenCalled()
- })
-
- it("rejects extra unexpected fields with 400", async () => {
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-reset", {
- method: "POST",
- body: JSON.stringify({ ...validBody, sneaky: "value" }),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(400)
- expect(doMock.stubFetch).not.toHaveBeenCalled()
- })
-
- it("zero active doNames → { sent: 0 } without touching any DO", async () => {
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-reset", {
- method: "POST",
- body: JSON.stringify(validBody),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ sent: 0 })
- expect(doMock.stubFetch).not.toHaveBeenCalled()
- })
-
- it("well-formed body → forwards a { type:'agent:reset', ... } frame to each DO's /push and aggregates sent", async () => {
- mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])
- doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
-
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-reset", {
- method: "POST",
- body: JSON.stringify(validBody),
- })
- const res = await handler.fetch(req, env as any)
-
- expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-abc")
- const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
- expect(stubReq.url).toBe("http://internal/push")
- const forwardedBody = await stubReq.text()
- const parsed = JSON.parse(forwardedBody)
- expect(parsed).toEqual({ type: "agent:reset", agentId: "bot-1", config: validBody.config, launchId: "l-1" })
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ sent: 1 })
- })
- })
-
- describe("POST /community-machine/by-id/:machineId/forward-agent-model-switch", () => {
- // from/to are required for DO pending attribution; outer body has no `type`
- // — the inner DO endpoint `/push-model-switch` stamps the wire frame.
- const validBody = {
- agentId: "bot-1",
- config: { version: 1, runtime: "claude", model: { kind: "named", name: "claude-sonnet-4-6" }, mode: { kind: "default" } },
- launchId: "l-1",
- from: null as string | null,
- to: "claude-sonnet-4-6" as string | null,
- }
-
- beforeEach(() => {
- mockGetActiveDoNamesForMachine.mockReset()
- mockGetActiveDoNamesForMachine.mockResolvedValue([])
- })
-
- it("forwards attribution body to DO /push-model-switch (no type on inner body)", async () => {
- mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])
- doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-model-switch", {
- method: "POST",
- body: JSON.stringify(validBody),
- })
- const res = await handler.fetch(req, env as any)
- expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-abc")
- const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
- expect(stubReq.url).toBe("http://internal/push-model-switch")
- const parsed = JSON.parse(await stubReq.text())
- expect(parsed).toEqual({
- agentId: "bot-1",
- config: validBody.config,
- launchId: "l-1",
- from: null,
- to: "claude-sonnet-4-6",
- })
- expect(parsed.type).toBeUndefined()
- expect(parsed.config.model).toEqual({ kind: "named", name: "claude-sonnet-4-6" })
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ sent: 1 })
- })
-
- it("rejects an extra top-level key with 400 (allowlist parity with reset)", async () => {
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-model-switch", {
- method: "POST",
- body: JSON.stringify({ ...validBody, sneaky: "x" }),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(400)
- expect(doMock.stubFetch).not.toHaveBeenCalled()
- })
-
- it("rejects a missing/non-object config with 400", async () => {
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-model-switch", {
- method: "POST",
- body: JSON.stringify({ agentId: "bot-1", config: "nope", launchId: "l-1", from: null, to: "x" }),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(400)
- expect(mockGetActiveDoNamesForMachine).not.toHaveBeenCalled()
- expect(doMock.stubFetch).not.toHaveBeenCalled()
- })
-
- it("rejects missing from/to with 400", async () => {
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-model-switch", {
- method: "POST",
- body: JSON.stringify({
- agentId: "bot-1",
- config: validBody.config,
- launchId: "l-1",
- }),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(400)
- expect(doMock.stubFetch).not.toHaveBeenCalled()
- })
-
- it("zero active doNames → { sent: 0 } without erroring", async () => {
- const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-model-switch", {
- method: "POST",
- body: JSON.stringify(validBody),
- })
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ sent: 0 })
- expect(doMock.stubFetch).not.toHaveBeenCalled()
- })
- })
-
- describe("POST /community-machine/by-id/:machineId/forward-agent-provider-switch", () => {
- const validBody = {
- agentId: "bot-1",
- config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },
- launchId: "l-1",
- from: "claude",
- to: "codex",
- }
-
- beforeEach(() => {
- mockGetActiveDoNamesForMachine.mockReset()
- mockGetActiveDoNamesForMachine.mockResolvedValue([])
- })
-
- it("forwards attribution body to DO /push-provider-switch (no type on inner body)", async () => {
- mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])
- doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
- const req = new Request(
- "http://localhost/community-machine/by-id/machine-1/forward-agent-provider-switch",
- { method: "POST", body: JSON.stringify(validBody) },
- )
- const res = await handler.fetch(req, env as any)
- expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-abc")
- const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
- expect(stubReq.url).toBe("http://internal/push-provider-switch")
- const parsed = JSON.parse(await stubReq.text())
- expect(parsed).toEqual({
- agentId: "bot-1",
- config: validBody.config,
- launchId: "l-1",
- from: "claude",
- to: "codex",
- })
- expect(parsed.type).toBeUndefined()
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ sent: 1 })
- })
-
- it("rejects missing from/to with 400", async () => {
- const req = new Request(
- "http://localhost/community-machine/by-id/machine-1/forward-agent-provider-switch",
- {
- method: "POST",
- body: JSON.stringify({
- agentId: "bot-1",
- config: validBody.config,
- launchId: "l-1",
- }),
- },
- )
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(400)
- expect(doMock.stubFetch).not.toHaveBeenCalled()
- })
-
- it("zero active doNames → { sent: 0 }", async () => {
- const req = new Request(
- "http://localhost/community-machine/by-id/machine-1/forward-agent-provider-switch",
- { method: "POST", body: JSON.stringify(validBody) },
- )
- const res = await handler.fetch(req, env as any)
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ sent: 0 })
- expect(doMock.stubFetch).not.toHaveBeenCalled()
- })
- })
-
- describe("force-close routing", () => {
- it("keys the DO by the do_name suffix", async () => {
- doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ closed: 1 })))
- const doName = "a".repeat(32)
- const req = new Request(`http://localhost/community-machine/${doName}/force-close`, {
- method: "POST",
- })
- await handler.fetch(req, env as any)
- expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:" + doName)
+ expect(doMock.idFromName).toHaveBeenCalledWith("user:user-fallback")
+ expect(doMock.stubFetch).toHaveBeenCalledWith(req)
+ expect(await res.text()).toBe("fallback")
})
})
})
diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.ts
index b7520da1e..67cd62568 100644
--- a/src/ws-do/src/index.ts
+++ b/src/ws-do/src/index.ts
@@ -1,807 +1,69 @@
-import { createLogger, queries, WS_EVENTS } from "@alook/shared"
+import { handleAuditBroadcast } from "./routes/audit-broadcast"
+import { handleDaemonBroadcast, handleUserBroadcast, handleUsersBroadcast } from "./routes/broadcast"
+import { handleMachinePush, handleMachineWake } from "./routes/community-machine-delivery"
+import {
+ handleMachineBatchReset,
+ handleMachineForceClose,
+ handleMachineNap,
+ handleMachineReset,
+} from "./routes/community-machine-lifecycle"
+import { handleMachineModelSwitch, handleMachineProviderSwitch } from "./routes/community-machine-switch"
+import { handleHealth } from "./routes/health"
+import { handleBatchPresence, handleSinglePresence } from "./routes/presence"
+import { handleRateLimit } from "./routes/rate-limit"
+import { log, type RouterContext } from "./router-context"
+import { handleUpgrade } from "./routes/upgrade"
export { WebSocketDurableObject } from "./ws-durable"
export { RateLimitDurableObject } from "./rate-limit-do"
-const log = createLogger({ service: "ws-do" })
-
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url)
- if (url.pathname === "/health" && request.method === "GET") {
- return Response.json({ status: "ok" })
- }
-
- // Strongly-consistent, parameterized rate limiter. Every rate-limit
- // call site (community message send, auth OTP, future policies) hits
- // this single endpoint with a `{ name, key, windowMs, max }` payload
- // — one DO instance per (name, key) pair. Policy values come from the
- // shared `RATE_LIMITS` registry in `src/shared/src/lib/rate-limits.ts`
- // so ceilings live in one place, not scattered across route handlers.
- //
- // See `rate-limit-do.ts` for the counter logic.
- if (url.pathname === "/rate-limit/check" && request.method === "POST") {
- let body: unknown
- try {
- body = await request.json()
- } catch {
- return new Response("invalid json", { status: 400 })
- }
- const { name, key, windowMs, max } = (body ?? {}) as {
- name?: unknown
- key?: unknown
- windowMs?: unknown
- max?: unknown
- }
- if (typeof name !== "string" || name.length === 0) {
- return new Response("name required", { status: 400 })
- }
- if (typeof key !== "string" || key.length === 0) {
- return new Response("key required", { status: 400 })
- }
- const doId = env.RATE_LIMIT_DO.idFromName(name + ":" + key)
- const stub = env.RATE_LIMIT_DO.get(doId)
- return stub.fetch(
- new Request("http://internal/check", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ windowMs, max }),
- }),
- )
- }
-
- const traceId = request.headers.get("X-Trace-Id") ?? undefined
-
- const daemonBroadcast = url.pathname.match(/^\/broadcast\/daemon\/(.+)$/)
- if (daemonBroadcast && request.method === "POST") {
- const daemonId = daemonBroadcast[1]
- const reqLog = log.child({ traceId, daemonId })
- reqLog.debug("broadcasting to daemon")
-
- const doId = env.WS_DO.idFromName("daemon:" + daemonId)
- const stub = env.WS_DO.get(doId)
- return stub.fetch(new Request("http://internal/broadcast", { method: "POST", body: request.body, duplex: "half" } as RequestInit))
- }
-
- const userBroadcast = url.pathname.match(/^\/broadcast\/user\/(.+)$/)
- if (userBroadcast && request.method === "POST") {
- const userId = userBroadcast[1]
- const reqLog = log.child({ traceId, userId })
- reqLog.debug("broadcasting to user")
-
- const doId = env.WS_DO.idFromName("user:" + userId)
- const stub = env.WS_DO.get(doId)
- return stub.fetch(new Request("http://internal/broadcast", { method: "POST", body: request.body, duplex: "half" } as RequestInit))
- }
-
- // POST /internal/broadcast-bot-audit-event — the wake-worker calls this
- // right after `insertBotAuditWakeTrigger` writes a `wake_trigger` row, so
- // the owner's UI receives the audit-event WS frame in the same beat as
- // the D1 insert (matching the daemon-originating path at
- // `ws-durable.ts:906-915`). Reachable ONLY via service binding
- // (`WS_DO_WORKER: Fetcher` in wake-worker's wrangler.toml), so origin is
- // implicitly restricted to same-project workers.
- //
- // Body: { botId, ownerUserId, id, kind, payload, createdAt, sessionId?,
- // launchId? }. Everything except sessionId/launchId is required; the
- // handler validates shape and 400s on anything malformed, then forwards
- // the same `community:bot.audit_event` frame shape used at
- // `ws-durable.ts:906-915` to `broadcast/user/<ownerUserId>`.
- if (url.pathname === "/internal/broadcast-bot-audit-event" && request.method === "POST") {
- let body: unknown
- try {
- body = await request.json()
- } catch {
- return new Response("invalid json", { status: 400 })
- }
- const b = (body ?? {}) as {
- botId?: unknown
- ownerUserId?: unknown
- id?: unknown
- kind?: unknown
- payload?: unknown
- createdAt?: unknown
- sessionId?: unknown
- launchId?: unknown
- }
- if (
- typeof b.botId !== "string" ||
- typeof b.ownerUserId !== "string" ||
- typeof b.id !== "string" ||
- typeof b.kind !== "string" ||
- typeof b.createdAt !== "string" ||
- b.payload === undefined
- ) {
- return new Response("invalid payload", { status: 400 })
- }
- // Guard against a future caller shape-drift: only the four kinds the
- // browser understands are broadcastable. An unknown `kind` reaches the
- // owner UI as an untyped row (bot-activity-row.tsx renders it verbatim),
- // so reject at the boundary instead.
- const AUDIT_KINDS = new Set(["cli_invocation", "tool_call", "thinking", "wake_trigger", "session_reset", "model_changed"])
- if (!AUDIT_KINDS.has(b.kind)) {
- return new Response("invalid kind", { status: 400 })
- }
- const frame = {
- type: WS_EVENTS.BOT_AUDIT_EVENT,
- botId: b.botId,
- id: b.id,
- kind: b.kind,
- payload: b.payload,
- sessionId: typeof b.sessionId === "string" ? b.sessionId : null,
- launchId: typeof b.launchId === "string" ? b.launchId : null,
- createdAt: b.createdAt,
- }
- const doId = env.WS_DO.idFromName("user:" + b.ownerUserId)
- const stub = env.WS_DO.get(doId)
- try {
- await stub.fetch(
- new Request("http://internal/broadcast", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(frame),
- }),
- )
- } catch (err) {
- log.warn("internal_broadcast_bot_audit_event_failed", {
- err: String(err),
- ownerUserId: b.ownerUserId,
- botId: b.botId,
- })
- return new Response("broadcast failed", { status: 503 })
- }
- return new Response(null, { status: 204 })
- }
-
- // Bulk presence: fan out one DO fetch per id and return the online subset.
- // Consolidates web-worker subrequest budget to a single call regardless of
- // membership size.
- if (url.pathname === "/presence/users" && request.method === "POST") {
- let body: unknown
- try {
- body = await request.json()
- } catch {
- return new Response("invalid json", { status: 400 })
- }
- const ids = (body as { ids?: unknown })?.ids
- if (!Array.isArray(ids)) return new Response("ids must be an array", { status: 400 })
- if (ids.length > 1000) return new Response("too many ids", { status: 400 })
- if (!ids.every((id): id is string => typeof id === "string")) {
- return new Response("ids must be strings", { status: 400 })
- }
-
- const reqLog = log.child({ traceId, count: ids.length })
- reqLog.debug("bulk presence check")
-
- if (ids.length === 0) return Response.json({ online: [] })
-
- const results = await Promise.allSettled(
- ids.map((id) => {
- const doId = env.WS_DO.idFromName("user:" + id)
- const stub = env.WS_DO.get(doId)
- return stub.fetch(
- new Request(`http://internal/check-user-online?userId=${encodeURIComponent(id)}`)
- )
- })
- )
- const online: string[] = []
- for (let i = 0; i < results.length; i++) {
- const r = results[i]
- if (r.status !== "fulfilled" || !r.value.ok) continue
- try {
- const data = await r.value.json() as { online?: boolean; stale?: boolean }
- // Skip stale responses — a fail-closed `online:false` from D1 must
- // not be surfaced as authoritative offline to fan-out callers.
- if (data.stale) continue
- if (data.online) online.push(ids[i])
- } catch { /* skip */ }
- }
- return Response.json({ online })
- }
-
- // Per-user presence — dead in-tree, kept for rollout safety.
- const presenceCheck = url.pathname.match(/^\/presence\/user\/(.+)$/)
- if (presenceCheck && request.method === "GET") {
- const uid = presenceCheck[1]
- const doId = env.WS_DO.idFromName("user:" + uid)
- const stub = env.WS_DO.get(doId)
- return stub.fetch(
- new Request(`http://internal/check-user-online?userId=${encodeURIComponent(uid)}`)
- )
- }
-
- // POST /community-machine/by-id/<machineId>/push — push a bot event
- // (bot:added / bot:updated / bot:removed) to the daemon connection for
- // this machine. Looks up the live credential do_name via D1 and dispatches
- // to the corresponding DO. Best-effort — if the daemon is offline the DO
- // drops the event; cold-start warmup on reconnect re-syncs authoritative
- // state.
- const pushToMachine = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/push$/)
- if (pushToMachine && request.method === "POST") {
- const machineId = decodeURIComponent(pushToMachine[1])
- const reqLog = log.child({ traceId, machineId })
- reqLog.debug("pushing bot event to machine")
- // Look up the active `do_name` for this machineId via D1. Multiple
- // credentials may exist for a machine over time; we push to every live
- // one (there should be exactly one, but be robust).
- let doNames: string[] = []
- try {
- const shared = await import("@alook/shared")
- const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
- doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
- } catch {
- // If we can't reach D1 to resolve, silently drop — the daemon's
- // reconnect warmup will re-sync authoritative state.
- return Response.json({ sent: 0 })
- }
- if (doNames.length === 0) {
- return Response.json({ sent: 0 })
- }
- const bodyText = await request.text()
- let delivered = 0
- for (const dn of doNames) {
- const doId = env.WS_DO.idFromName("community-machine:" + dn)
- const stub = env.WS_DO.get(doId)
- try {
- const res = await stub.fetch(
- new Request("http://internal/push", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: bodyText,
- }),
- )
- if (res.ok) delivered++
- } catch {
- // best-effort
- }
- }
- return Response.json({ sent: delivered })
- }
-
- // POST /community-machine/by-id/<machineId>/forward-agent-wake — sibling
- // of the `/push` route above, for the minimal-wake-queue-unread-notice
- // wake path. Forwards an already-built `HostCommand` (`agent:wake`)
- // verbatim to every live DO for this machine's active credential(s),
- // then aggregates by parsing each DO's own `{ sent: N }` response —
- // unlike `/push`, we must NOT just count `res.ok`: a 200 with
- // `{ sent: 0 }` means that DO has no authenticated daemon socket at all,
- // which must not be reported as delivered.
- const forwardAgentWake = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-wake$/)
- if (forwardAgentWake && request.method === "POST") {
- const machineId = decodeURIComponent(forwardAgentWake[1])
- const reqLog = log.child({ traceId, machineId })
- reqLog.debug("forwarding agent:wake to machine")
-
- let doNames: string[] = []
- try {
- const shared = await import("@alook/shared")
- const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
- doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
- } catch (err) {
- reqLog.error("failed to resolve machine doNames for agent wake", { err })
- return Response.json({ error: "failed to resolve machine" }, { status: 503 })
- }
- if (doNames.length === 0) {
- return Response.json({ sent: 0 })
- }
- const bodyText = await request.text()
- let delivered = 0
- let transientFailure = false
- for (const dn of doNames) {
- const doId = env.WS_DO.idFromName("community-machine:" + dn)
- const stub = env.WS_DO.get(doId)
- try {
- const res = await stub.fetch(
- new Request("http://internal/forward-agent-wake", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: bodyText,
- }),
- )
- if (!res.ok) {
- transientFailure = true
- continue
- }
- const data = (await res.json()) as { sent?: unknown }
- if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {
- transientFailure = true
- continue
- }
- delivered += data.sent
- } catch {
- transientFailure = true
- }
- }
- if (delivered === 0 && transientFailure) {
- return Response.json({ error: "failed to forward agent wake" }, { status: 503 })
- }
- return Response.json({ sent: delivered })
- }
-
- // POST /community-machine/by-id/<machineId>/forward-agent-reset — owner-
- // triggered `agent:reset` push. Same shape as `/forward-agent-wake`: build
- // the HostCommand from a narrow payload (`{ agentId, config, launchId }`),
- // resolve the machine's active `do_names`, forward the frame to each DO's
- // `/push` route, and aggregate `{ sent }`. Rejects any extra field —
- // callers must use `pushAgentResetToMachine`.
- const forwardAgentReset = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-reset$/)
- if (forwardAgentReset && request.method === "POST") {
- const machineId = decodeURIComponent(forwardAgentReset[1])
- const reqLog = log.child({ traceId, machineId })
- reqLog.debug("forwarding agent:reset to machine")
-
- let payload: unknown
- try {
- payload = await request.json()
- } catch {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if (!payload || typeof payload !== "object") {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- const raw = payload as Record<string, unknown>
- const allowedKeys = new Set(["agentId", "config", "launchId"])
- for (const key of Object.keys(raw)) {
- if (!allowedKeys.has(key)) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- }
- const { agentId, config, launchId } = raw
- if (typeof agentId !== "string" || agentId.length === 0) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if (typeof launchId !== "string" || launchId.length === 0) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if (!config || typeof config !== "object") {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
-
- let doNames: string[] = []
- try {
- const shared = await import("@alook/shared")
- const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
- doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
- } catch (err) {
- reqLog.error("failed to resolve machine doNames for agent reset", { err })
- return Response.json({ error: "failed to resolve machine" }, { status: 503 })
- }
- if (doNames.length === 0) {
- return Response.json({ sent: 0 })
- }
- const frame = JSON.stringify({ type: "agent:reset", agentId, config, launchId })
- let delivered = 0
- let transientFailure = false
- for (const dn of doNames) {
- const doId = env.WS_DO.idFromName("community-machine:" + dn)
- const stub = env.WS_DO.get(doId)
- try {
- const res = await stub.fetch(
- new Request("http://internal/push", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: frame,
- }),
- )
- if (!res.ok) {
- transientFailure = true
- continue
- }
- const data = (await res.json()) as { sent?: unknown }
- if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {
- transientFailure = true
- continue
- }
- delivered += data.sent
- } catch {
- transientFailure = true
- }
- }
- if (delivered === 0 && transientFailure) {
- return Response.json({ error: "failed to forward agent reset" }, { status: 503 })
- }
- return Response.json({ sent: delivered })
- }
-
- // POST /community-machine/by-id/<machineId>/forward-batch-reset —
- // owner-triggered `machine:reset_all` push (batch reset all agents on the
- // machine in ONE frame, not N fanned-out agent:reset). Twin of
- // /forward-agent-reset: same doName resolution + `/push` fan-out + `{sent}`
- // aggregation, but the body is a `resets` array (each item the narrow
- // {agentId, config, launchId}) and the frame type is `machine:reset_all`.
- // Callers must use `pushBatchResetToMachine`.
- const forwardBatchReset = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-batch-reset$/)
- if (forwardBatchReset && request.method === "POST") {
- const machineId = decodeURIComponent(forwardBatchReset[1])
- const reqLog = log.child({ traceId, machineId })
- reqLog.debug("forwarding machine:reset_all to machine")
-
- let payload: unknown
- try {
- payload = await request.json()
- } catch {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if (!payload || typeof payload !== "object") {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- const raw = payload as Record<string, unknown>
- // Only `resets` allowed at the top level.
- for (const key of Object.keys(raw)) {
- if (key !== "resets") {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- }
- if (!Array.isArray(raw.resets)) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- // Validate each reset entry against the same narrow allowlist as
- // forward-agent-reset — no extra fields, all three required.
- const resets: Array<{ agentId: string; config: unknown; launchId: string }> = []
- for (const item of raw.resets) {
- if (!item || typeof item !== "object") {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- const r = item as Record<string, unknown>
- const allowedKeys = new Set(["agentId", "config", "launchId"])
- for (const key of Object.keys(r)) {
- if (!allowedKeys.has(key)) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- }
- if (typeof r.agentId !== "string" || r.agentId.length === 0) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if (typeof r.launchId !== "string" || r.launchId.length === 0) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if (!r.config || typeof r.config !== "object") {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- resets.push({ agentId: r.agentId, config: r.config, launchId: r.launchId })
- }
-
- let doNames: string[] = []
- try {
- const shared = await import("@alook/shared")
- const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
- doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
- } catch (err) {
- reqLog.error("failed to resolve machine doNames for batch reset", { err })
- return Response.json({ error: "failed to resolve machine" }, { status: 503 })
- }
- if (doNames.length === 0) {
- return Response.json({ sent: 0 })
- }
- const frame = JSON.stringify({ type: "machine:reset_all", resets })
- let delivered = 0
- let transientFailure = false
- for (const dn of doNames) {
- const doId = env.WS_DO.idFromName("community-machine:" + dn)
- const stub = env.WS_DO.get(doId)
- try {
- const res = await stub.fetch(
- new Request("http://internal/push", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: frame,
- }),
- )
- if (!res.ok) {
- transientFailure = true
- continue
- }
- const data = (await res.json()) as { sent?: unknown }
- if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {
- transientFailure = true
- continue
- }
- delivered += data.sent
- } catch {
- transientFailure = true
- }
- }
- if (delivered === 0 && transientFailure) {
- return Response.json({ error: "failed to forward batch reset" }, { status: 503 })
- }
- return Response.json({ sent: delivered })
- }
-
- // POST /community-machine/by-id/<machineId>/forward-agent-model-switch —
- // owner-triggered model switch. `from`/`to` stay server-side for completion
- // attribution; the machine DO forwards only the daemon's existing
- // `agent:model_switch` frame.
- const forwardAgentModelSwitch = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-model-switch$/)
- if (forwardAgentModelSwitch && request.method === "POST") {
- const machineId = decodeURIComponent(forwardAgentModelSwitch[1])
- const reqLog = log.child({ traceId, machineId })
- reqLog.debug("forwarding agent:model_switch to machine")
-
- let payload: unknown
- try {
- payload = await request.json()
- } catch {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if (!payload || typeof payload !== "object") {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- const raw = payload as Record<string, unknown>
- const allowedKeys = new Set(["agentId", "config", "launchId", "from", "to"])
- for (const key of Object.keys(raw)) {
- if (!allowedKeys.has(key)) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- }
- const { agentId, config, launchId, from, to } = raw
- if (typeof agentId !== "string" || agentId.length === 0) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if (typeof launchId !== "string" || launchId.length === 0) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if (!config || typeof config !== "object") {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if ((from !== null && typeof from !== "string") || (to !== null && typeof to !== "string")) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
-
- let doNames: string[] = []
- try {
- const shared = await import("@alook/shared")
- const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
- doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
- } catch (err) {
- reqLog.error("failed to resolve machine doNames for agent model switch", { err })
- return Response.json({ error: "failed to resolve machine" }, { status: 503 })
- }
- if (doNames.length === 0) {
- return Response.json({ sent: 0 })
- }
- const frame = JSON.stringify({ agentId, config, launchId, from, to })
- let delivered = 0
- let transientFailure = false
- for (const dn of doNames) {
- const doId = env.WS_DO.idFromName("community-machine:" + dn)
- const stub = env.WS_DO.get(doId)
- try {
- const res = await stub.fetch(
- new Request("http://internal/push-model-switch", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: frame,
- }),
- )
- if (!res.ok) {
- transientFailure = true
- continue
- }
- const data = (await res.json()) as { sent?: unknown }
- if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {
- transientFailure = true
- continue
- }
- delivered += data.sent
- } catch {
- transientFailure = true
- }
- }
- if (delivered === 0 && transientFailure) {
- return Response.json({ error: "failed to forward agent model switch" }, { status: 503 })
- }
- return Response.json({ sent: delivered })
- }
-
- const forwardAgentProviderSwitch = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-provider-switch$/)
- if (forwardAgentProviderSwitch && request.method === "POST") {
- const machineId = decodeURIComponent(forwardAgentProviderSwitch[1])
- const reqLog = log.child({ traceId, machineId })
-
- let payload: unknown
- try {
- payload = await request.json()
- } catch {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if (!payload || typeof payload !== "object") {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- const raw = payload as Record<string, unknown>
- const allowedKeys = new Set(["agentId", "config", "launchId", "from", "to"])
- for (const key of Object.keys(raw)) {
- if (!allowedKeys.has(key)) return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- const { agentId, config, launchId, from, to } = raw
- if (
- typeof agentId !== "string" || agentId.length === 0 ||
- typeof launchId !== "string" || launchId.length === 0 ||
- !config || typeof config !== "object" ||
- typeof from !== "string" || from.length === 0 ||
- typeof to !== "string" || to.length === 0
- ) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
-
- let doNames: string[] = []
- try {
- const shared = await import("@alook/shared")
- const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
- doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
- } catch (err) {
- reqLog.error("failed to resolve machine doNames for agent provider switch", { err })
- return Response.json({ error: "failed to resolve machine" }, { status: 503 })
- }
- if (doNames.length === 0) return Response.json({ sent: 0 })
-
- const frame = JSON.stringify({ agentId, config, launchId, from, to })
- let delivered = 0
- let transientFailure = false
- for (const dn of doNames) {
- const doId = env.WS_DO.idFromName("community-machine:" + dn)
- const stub = env.WS_DO.get(doId)
- try {
- const res = await stub.fetch(new Request("http://internal/push-provider-switch", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: frame,
- }))
- if (!res.ok) {
- transientFailure = true
- continue
- }
- const data = (await res.json()) as { sent?: unknown }
- if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {
- transientFailure = true
- continue
- }
- delivered += data.sent
- } catch {
- transientFailure = true
- }
- }
- if (delivered === 0 && transientFailure) {
- return Response.json({ error: "failed to forward agent provider switch" }, { status: 503 })
- }
- return Response.json({ sent: delivered })
- }
-
- // POST /community-machine/by-id/<machineId>/forward-agent-nap — agent
- // self-initiated `agent:nap` push. Twin of /forward-agent-reset but the
- // allowlist additionally carries the mandatory `handoff` string (the
- // agent's note to its reborn self, spliced into the rewake prompt). Same
- // doName resolution + `/push` fan-out + `{sent}` aggregation. Callers must
- // use `pushAgentNapToMachine`.
- const forwardAgentNap = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-nap$/)
- if (forwardAgentNap && request.method === "POST") {
- const machineId = decodeURIComponent(forwardAgentNap[1])
- const reqLog = log.child({ traceId, machineId })
- reqLog.debug("forwarding agent:nap to machine")
-
- let payload: unknown
- try {
- payload = await request.json()
- } catch {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if (!payload || typeof payload !== "object") {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- const raw = payload as Record<string, unknown>
- const allowedKeys = new Set(["agentId", "config", "launchId", "handoff"])
- for (const key of Object.keys(raw)) {
- if (!allowedKeys.has(key)) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- }
- const { agentId, config, launchId, handoff } = raw
- if (typeof agentId !== "string" || agentId.length === 0) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if (typeof launchId !== "string" || launchId.length === 0) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if (!config || typeof config !== "object") {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
- if (typeof handoff !== "string" || handoff.trim().length === 0) {
- return Response.json({ error: "invalid payload" }, { status: 400 })
- }
-
- let doNames: string[] = []
- try {
- const shared = await import("@alook/shared")
- const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
- doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
- } catch (err) {
- reqLog.error("failed to resolve machine doNames for agent nap", { err })
- return Response.json({ error: "failed to resolve machine" }, { status: 503 })
- }
- if (doNames.length === 0) {
- return Response.json({ sent: 0 })
- }
- const frame = JSON.stringify({ type: "agent:nap", agentId, config, launchId, handoff })
- let delivered = 0
- let transientFailure = false
- for (const dn of doNames) {
- const doId = env.WS_DO.idFromName("community-machine:" + dn)
- const stub = env.WS_DO.get(doId)
- try {
- const res = await stub.fetch(
- new Request("http://internal/push", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: frame,
- }),
- )
- if (!res.ok) {
- transientFailure = true
- continue
- }
- const data = (await res.json()) as { sent?: unknown }
- if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {
- transientFailure = true
- continue
- }
- delivered += data.sent
- } catch {
- transientFailure = true
- }
- }
- if (delivered === 0 && transientFailure) {
- return Response.json({ error: "failed to forward agent nap" }, { status: 503 })
- }
- return Response.json({ sent: delivered })
- }
-
- // POST /community-machine/<doName>/force-close — disconnect a daemon by
- // its DO-name suffix (first 32 hex of the credential hash). Callers look
- // the suffix up from `community_machine_credential.do_name`.
- const forceClose = url.pathname.match(/^\/community-machine\/([^/]+)\/force-close$/)
- if (forceClose && request.method === "POST") {
- const doName = decodeURIComponent(forceClose[1])
- const reqLog = log.child({ traceId, doName })
- reqLog.debug("force-closing community machine")
-
- const doId = env.WS_DO.idFromName("community-machine:" + doName)
- const stub = env.WS_DO.get(doId)
- return stub.fetch(new Request("http://internal/force-close", { method: "POST" }))
- }
-
- // Community-machine daemon WS upgrade — Bearer cmk_<credential> only.
- // Router names the DO from `sha256(bearer).slice(0,32)` without hitting
- // D1; the DO re-validates the full hash authoritatively on first accept.
- const authHeader = request.headers.get("Authorization")
- if (authHeader?.startsWith("Bearer cmk_")) {
- const bearer = authHeader.slice(7).trim()
- const hash = await queries.communityMachine.hashCredential(bearer)
- const doName = queries.communityMachine.doNameFromHash(hash)
- const reqLog = log.child({ traceId })
- reqLog.info("community machine websocket upgrade")
- const doId = env.WS_DO.idFromName("community-machine:" + doName)
- const stub = env.WS_DO.get(doId)
- return stub.fetch(request)
- }
-
- const daemonId = url.searchParams.get("daemonId")
- if (daemonId) {
- const reqLog = log.child({ traceId, daemonId })
- reqLog.info("daemon websocket upgrade")
-
- const doId = env.WS_DO.idFromName("daemon:" + daemonId)
- const stub = env.WS_DO.get(doId)
- return stub.fetch(request)
- }
-
- const userId = url.searchParams.get("userId")
- if (!userId) return new Response("userId required", { status: 400 })
-
- const reqLog = log.child({ traceId, userId })
- reqLog.info("websocket upgrade")
-
- const doId = env.WS_DO.idFromName("user:" + userId)
- const stub = env.WS_DO.get(doId)
- return stub.fetch(request)
+ let response = handleHealth(request, url)
+ if (response) return response
+
+ response = await handleRateLimit(request, env, url)
+ if (response) return response
+
+ const context: RouterContext = {
+ request,
+ env,
+ url,
+ traceId: request.headers.get("X-Trace-Id") ?? undefined,
+ log,
+ }
+
+ response = await handleDaemonBroadcast(context)
+ if (response) return response
+ response = await handleUserBroadcast(context)
+ if (response) return response
+ response = await handleUsersBroadcast(context)
+ if (response) return response
+ response = await handleAuditBroadcast(context)
+ if (response) return response
+ response = await handleBatchPresence(context)
+ if (response) return response
+ response = await handleSinglePresence(context)
+ if (response) return response
+ response = await handleMachinePush(context)
+ if (response) return response
+ response = await handleMachineWake(context)
+ if (response) return response
+ response = await handleMachineReset(context)
+ if (response) return response
+ response = await handleMachineBatchReset(context)
+ if (response) return response
+ response = await handleMachineModelSwitch(context)
+ if (response) return response
+ response = await handleMachineProviderSwitch(context)
+ if (response) return response
+ response = await handleMachineNap(context)
+ if (response) return response
+ response = await handleMachineForceClose(context)
+ if (response) return response
+
+ return handleUpgrade(context)
},
}
diff --git a/src/ws-do/src/router-context.ts b/src/ws-do/src/router-context.ts
new file mode 100644
index 000000000..7a164dfdc
--- /dev/null
+++ b/src/ws-do/src/router-context.ts
@@ -0,0 +1,11 @@
+import { createLogger, type Logger } from "@alook/shared"
+
+export const log = createLogger({ service: "ws-do" })
+
+export interface RouterContext {
+ request: Request
+ env: Env
+ url: URL
+ traceId: string | undefined
+ log: Logger
+}
diff --git a/src/ws-do/src/routes/audit-broadcast.test.ts b/src/ws-do/src/routes/audit-broadcast.test.ts
new file mode 100644
index 000000000..738bed915
--- /dev/null
+++ b/src/ws-do/src/routes/audit-broadcast.test.ts
@@ -0,0 +1,161 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ createRouterTestContext,
+ loadRouter,
+ getSharedMocks,
+ type RouterHandler,
+ type RouterTestContext,
+} from "./test-harness"
+
+const sharedMocks = getSharedMocks()
+const mockHashCredential = sharedMocks.hashCredential
+const mockDoNameFromHash = sharedMocks.doNameFromHash
+const mockGetActiveDoNamesForMachine = sharedMocks.getActiveDoNamesForMachine
+const loggerMocks = {
+ child: sharedMocks.loggerChild,
+ debug: sharedMocks.loggerDebug,
+}
+
+describe("ws-do router", () => {
+ let handler: RouterHandler
+ let doMock: RouterTestContext["doMock"]
+ let rateLimitMock: RouterTestContext["rateLimitMock"]
+ let env: RouterTestContext["env"]
+
+ beforeEach(async () => {
+ vi.resetModules()
+ vi.clearAllMocks()
+ const context = createRouterTestContext()
+ doMock = context.doMock
+ rateLimitMock = context.rateLimitMock
+ env = context.env
+ handler = await loadRouter()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+ vi.resetModules()
+ doMock = undefined as unknown as RouterTestContext["doMock"]
+ rateLimitMock = undefined as unknown as RouterTestContext["rateLimitMock"]
+ env = undefined as unknown as RouterTestContext["env"]
+ handler = undefined as unknown as RouterHandler
+ })
+
+ describe("POST /internal/broadcast-bot-audit-event", () => {
+ it("forwards a well-formed audit event to the owner's user-DO with the community:bot.audit_event shape", async () => {
+ doMock.stubFetch.mockResolvedValue(new Response("ok"))
+ const payload = {
+ botId: "bot_1",
+ ownerUserId: "owner_1",
+ id: "evt_1",
+ kind: "wake_trigger",
+ payload: {
+ messageId: "msg_1",
+ channel: "/srv_1/general",
+ seq: 7,
+ senderId: "u_human",
+ senderHandle: "@gustavo#0042",
+ reason: "unread",
+ },
+ createdAt: "2026-07-23T00:00:00.000Z",
+ }
+ const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ })
+
+ const res = await handler.fetch(req, env as any)
+
+ expect(res.status).toBe(204)
+ expect(doMock.idFromName).toHaveBeenCalledWith("user:owner_1")
+ const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
+ expect(stubReq.url).toBe("http://internal/broadcast")
+ const body = JSON.parse(await stubReq.text()) as Record<string, unknown>
+ // Matches the shape ws-durable.ts emits for daemon-originating frames.
+ expect(body.type).toBe("community:bot.audit_event")
+ expect(body.botId).toBe("bot_1")
+ expect(body.id).toBe("evt_1")
+ expect(body.kind).toBe("wake_trigger")
+ expect(body.createdAt).toBe(payload.createdAt)
+ expect(body.payload).toEqual(payload.payload)
+ })
+
+ it("400s on invalid JSON", async () => {
+ const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {
+ method: "POST",
+ body: "not json",
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ })
+
+ it("400s on a payload missing required fields", async () => {
+ const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ botId: "bot_1" }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ })
+
+ it("400s on an unknown kind (rejects browser-untypeable rows at the boundary)", async () => {
+ const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ botId: "bot_1",
+ ownerUserId: "owner_1",
+ id: "evt_1",
+ kind: "some_future_kind",
+ payload: {},
+ createdAt: "2026-07-23T00:00:00.000Z",
+ }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ })
+
+ it("503s and never broadcasts when the DO fetch throws", async () => {
+ doMock.stubFetch.mockRejectedValue(new Error("do down"))
+ const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ botId: "bot_1",
+ ownerUserId: "owner_1",
+ id: "evt_1",
+ kind: "wake_trigger",
+ payload: {},
+ createdAt: "2026-07-23T00:00:00.000Z",
+ }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(503)
+ })
+
+ it("accepts kind: 'model_changed' (guards the AUDIT_KINDS allowlist)", async () => {
+ doMock.stubFetch.mockResolvedValue(new Response("ok"))
+ const req = new Request("http://localhost/internal/broadcast-bot-audit-event", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ botId: "bot_1",
+ ownerUserId: "owner_1",
+ id: "evt_m",
+ kind: "model_changed",
+ payload: { from: "claude-opus-4-6", to: "claude-sonnet-4-6" },
+ createdAt: "2026-07-26T00:00:00.000Z",
+ }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(204)
+ const body = JSON.parse(await (doMock.stubFetch.mock.calls[0][0] as Request).text()) as Record<string, unknown>
+ expect(body.kind).toBe("model_changed")
+ expect(body.payload).toEqual({ from: "claude-opus-4-6", to: "claude-sonnet-4-6" })
+ })
+ })
+})
diff --git a/src/ws-do/src/routes/audit-broadcast.ts b/src/ws-do/src/routes/audit-broadcast.ts
new file mode 100644
index 000000000..c473169a9
--- /dev/null
+++ b/src/ws-do/src/routes/audit-broadcast.ts
@@ -0,0 +1,83 @@
+import { WS_EVENTS } from "@alook/shared"
+import type { RouterContext } from "../router-context"
+
+export async function handleAuditBroadcast({ request, env, url, log }: RouterContext): Promise<Response | null> {
+ // POST /internal/broadcast-bot-audit-event — the wake-worker calls this
+ // right after `insertBotAuditWakeTrigger` writes a `wake_trigger` row, so
+ // the owner's UI receives the audit-event WS frame in the same beat as
+ // the D1 insert (matching the daemon-originating path at
+ // `ws-durable.ts:906-915`). Reachable ONLY via service binding
+ // (`WS_DO_WORKER: Fetcher` in wake-worker's wrangler.toml), so origin is
+ // implicitly restricted to same-project workers.
+ //
+ // Body: { botId, ownerUserId, id, kind, payload, createdAt, sessionId?,
+ // launchId? }. Everything except sessionId/launchId is required; the
+ // handler validates shape and 400s on anything malformed, then forwards
+ // the same `community:bot.audit_event` frame shape used at
+ // `ws-durable.ts:906-915` to `broadcast/user/<ownerUserId>`.
+ if (url.pathname !== "/internal/broadcast-bot-audit-event" || request.method !== "POST") return null
+
+ let body: unknown
+ try {
+ body = await request.json()
+ } catch {
+ return new Response("invalid json", { status: 400 })
+ }
+ const b = (body ?? {}) as {
+ botId?: unknown
+ ownerUserId?: unknown
+ id?: unknown
+ kind?: unknown
+ payload?: unknown
+ createdAt?: unknown
+ sessionId?: unknown
+ launchId?: unknown
+ }
+ if (
+ typeof b.botId !== "string" ||
+ typeof b.ownerUserId !== "string" ||
+ typeof b.id !== "string" ||
+ typeof b.kind !== "string" ||
+ typeof b.createdAt !== "string" ||
+ b.payload === undefined
+ ) {
+ return new Response("invalid payload", { status: 400 })
+ }
+ // Guard against a future caller shape-drift: only the four kinds the
+ // browser understands are broadcastable. An unknown `kind` reaches the
+ // owner UI as an untyped row (bot-activity-row.tsx renders it verbatim),
+ // so reject at the boundary instead.
+ const AUDIT_KINDS = new Set(["cli_invocation", "tool_call", "thinking", "wake_trigger", "session_reset", "model_changed"])
+ if (!AUDIT_KINDS.has(b.kind)) {
+ return new Response("invalid kind", { status: 400 })
+ }
+ const frame = {
+ type: WS_EVENTS.BOT_AUDIT_EVENT,
+ botId: b.botId,
+ id: b.id,
+ kind: b.kind,
+ payload: b.payload,
+ sessionId: typeof b.sessionId === "string" ? b.sessionId : null,
+ launchId: typeof b.launchId === "string" ? b.launchId : null,
+ createdAt: b.createdAt,
+ }
+ const doId = env.WS_DO.idFromName("user:" + b.ownerUserId)
+ const stub = env.WS_DO.get(doId)
+ try {
+ await stub.fetch(
+ new Request("http://internal/broadcast", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(frame),
+ }),
+ )
+ } catch (err) {
+ log.warn("internal_broadcast_bot_audit_event_failed", {
+ err: String(err),
+ ownerUserId: b.ownerUserId,
+ botId: b.botId,
+ })
+ return new Response("broadcast failed", { status: 503 })
+ }
+ return new Response(null, { status: 204 })
+}
diff --git a/src/ws-do/src/routes/broadcast.test.ts b/src/ws-do/src/routes/broadcast.test.ts
new file mode 100644
index 000000000..bebc44788
--- /dev/null
+++ b/src/ws-do/src/routes/broadcast.test.ts
@@ -0,0 +1,285 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ createRouterTestContext,
+ loadRouter,
+ getSharedMocks,
+ type RouterHandler,
+ type RouterTestContext,
+} from "./test-harness"
+
+const sharedMocks = getSharedMocks()
+const mockHashCredential = sharedMocks.hashCredential
+const mockDoNameFromHash = sharedMocks.doNameFromHash
+const mockGetActiveDoNamesForMachine = sharedMocks.getActiveDoNamesForMachine
+const loggerMocks = {
+ child: sharedMocks.loggerChild,
+ debug: sharedMocks.loggerDebug,
+ info: sharedMocks.loggerInfo,
+ warn: sharedMocks.loggerWarn,
+}
+
+function makeBulkRequest(body: string): Request {
+ return new Request("http://localhost/broadcast/users", {
+ method: "POST",
+ headers: { "Content-Type": "application/json", "X-Trace-Id": "trace-bulk" },
+ body,
+ })
+}
+
+describe("ws-do router", () => {
+ let handler: RouterHandler
+ let doMock: RouterTestContext["doMock"]
+ let rateLimitMock: RouterTestContext["rateLimitMock"]
+ let env: RouterTestContext["env"]
+
+ beforeEach(async () => {
+ vi.resetModules()
+ vi.clearAllMocks()
+ const context = createRouterTestContext()
+ doMock = context.doMock
+ rateLimitMock = context.rateLimitMock
+ env = context.env
+ handler = await loadRouter()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+ vi.resetModules()
+ doMock = undefined as unknown as RouterTestContext["doMock"]
+ rateLimitMock = undefined as unknown as RouterTestContext["rateLimitMock"]
+ env = undefined as unknown as RouterTestContext["env"]
+ handler = undefined as unknown as RouterHandler
+ })
+
+ describe("broadcast route", () => {
+ it("preserves daemon routing, trace logging, streamed body, and the internal response", async () => {
+ doMock.stubFetch.mockResolvedValue(new Response("daemon-ok", {
+ status: 202,
+ headers: { "x-broadcast": "accepted" },
+ }))
+ const req = new Request("http://localhost/broadcast/daemon/daemon-42", {
+ method: "POST",
+ headers: { "X-Trace-Id": "trace-9" },
+ body: "stream-me",
+ })
+
+ const res = await handler.fetch(req, env as any)
+
+ expect(loggerMocks.child).toHaveBeenCalledWith({ traceId: "trace-9", daemonId: "daemon-42" })
+ expect(loggerMocks.debug).toHaveBeenCalledWith("broadcasting to daemon")
+ expect(doMock.idFromName).toHaveBeenCalledWith("daemon:daemon-42")
+ expect(doMock.get).toHaveBeenCalledWith("mock-do-id")
+ const internal = doMock.stubFetch.mock.calls[0][0] as Request
+ expect(internal.url).toBe("http://internal/broadcast")
+ expect(internal.method).toBe("POST")
+ expect(await internal.text()).toBe("stream-me")
+ expect(res.status).toBe(202)
+ expect(res.headers.get("x-broadcast")).toBe("accepted")
+ expect(await res.text()).toBe("daemon-ok")
+ })
+
+ it("forwards POST /broadcast/user/:userId to correct DO instance", async () => {
+ doMock.stubFetch.mockResolvedValue(new Response("ok"))
+ const body = JSON.stringify({ type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" })
+ const req = new Request("http://localhost/broadcast/user/user-123", {
+ method: "POST",
+ body,
+ })
+
+ const res = await handler.fetch(req, env as any)
+
+ expect(doMock.idFromName).toHaveBeenCalledWith("user:user-123")
+ expect(doMock.get).toHaveBeenCalledWith("mock-do-id")
+ expect(doMock.stubFetch).toHaveBeenCalled()
+ const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
+ expect(stubReq.url).toBe("http://internal/broadcast")
+ expect(stubReq.method).toBe("POST")
+ expect(await stubReq.text()).toBe(body)
+ expect(res.status).toBe(200)
+ })
+
+ it.each([
+ ["malformed JSON", "{"],
+ ["null body", "null"],
+ ["array body", "[]"],
+ ["missing userIds", JSON.stringify({ message: { type: "event" } })],
+ ["non-array userIds", JSON.stringify({ userIds: "u1", message: { type: "event" } })],
+ ["empty user id", JSON.stringify({ userIds: [""], message: { type: "event" } })],
+ ["non-string user id", JSON.stringify({ userIds: [1], message: { type: "event" } })],
+ ["missing message", JSON.stringify({ userIds: [] })],
+ ["null message", JSON.stringify({ userIds: [], message: null })],
+ ["array message", JSON.stringify({ userIds: [], message: [] })],
+ ["missing message type", JSON.stringify({ userIds: [], message: {} })],
+ ["empty message type", JSON.stringify({ userIds: [], message: { type: "" } })],
+ ["non-string message type", JSON.stringify({ userIds: [], message: { type: 1 } })],
+ ["null exclusion", JSON.stringify({ userIds: [], message: { type: "event" }, excludeUserId: null })],
+ ["empty exclusion", JSON.stringify({ userIds: [], message: { type: "event" }, excludeUserId: "" })],
+ ["non-string exclusion", JSON.stringify({ userIds: [], message: { type: "event" }, excludeUserId: 1 })],
+ ])("rejects %s before Durable Object access", async (_label, body) => {
+ const res = await handler.fetch(makeBulkRequest(body), env as any)
+
+ expect(res.status).toBe(400)
+ expect(doMock.idFromName).not.toHaveBeenCalled()
+ expect(doMock.get).not.toHaveBeenCalled()
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("rejects 1,001 raw duplicate ids before dedupe or Durable Object access", async () => {
+ const res = await handler.fetch(makeBulkRequest(JSON.stringify({
+ userIds: Array.from({ length: 1001 }, () => "duplicate"),
+ message: { type: "event" },
+ })), env as any)
+
+ expect(res.status).toBe(400)
+ expect(doMock.idFromName).not.toHaveBeenCalled()
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("accepts exactly 1,000 raw ids", async () => {
+ doMock.stubFetch.mockImplementation(async () =>
+ new Response(JSON.stringify({ sent: 1 }), { status: 200 }),
+ )
+ const res = await handler.fetch(makeBulkRequest(JSON.stringify({
+ userIds: Array.from({ length: 1000 }, (_, index) => `u${index}`),
+ message: { type: "event" },
+ })), env as any)
+
+ expect(res.status).toBe(200)
+ await expect(res.json()).resolves.toEqual({ sent: 1000 })
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(1000)
+ })
+
+ it("returns sent zero for an empty target list without namespace access", async () => {
+ const res = await handler.fetch(makeBulkRequest(JSON.stringify({
+ userIds: [],
+ message: { type: "event" },
+ })), env as any)
+
+ expect(res.status).toBe(200)
+ await expect(res.json()).resolves.toEqual({ sent: 0 })
+ expect(doMock.idFromName).not.toHaveBeenCalled()
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("returns sent zero when exclusion removes the only unique target", async () => {
+ const res = await handler.fetch(makeBulkRequest(JSON.stringify({
+ userIds: ["u1", "u1"],
+ message: { type: "event" },
+ excludeUserId: "u1",
+ })), env as any)
+
+ expect(res.status).toBe(200)
+ await expect(res.json()).resolves.toEqual({ sent: 0 })
+ expect(doMock.idFromName).not.toHaveBeenCalled()
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("dedupes in first-seen order, excludes afterward, serializes once, and creates fresh requests", async () => {
+ doMock.stubFetch.mockImplementation(async () =>
+ new Response(JSON.stringify({ sent: 1 }), { status: 200 }),
+ )
+ const request = makeBulkRequest(JSON.stringify({
+ userIds: ["u2", "u1", "u2", "u3", "u1"],
+ message: { type: "event", value: 7 },
+ excludeUserId: "u1",
+ }))
+ const stringify = vi.spyOn(JSON, "stringify")
+
+ const res = await handler.fetch(request, env as any)
+ const messageStringifyCount = stringify.mock.calls.filter(([value]) => (
+ typeof value === "object" && value !== null && !Array.isArray(value)
+ && (value as Record<string, unknown>).type === "event"
+ )).length
+
+ expect(res.status).toBe(200)
+ await expect(res.json()).resolves.toEqual({ sent: 2 })
+ expect(doMock.idFromName.mock.calls.map(([name]) => name)).toEqual(["user:u2", "user:u3"])
+ expect(doMock.get).toHaveBeenCalledTimes(2)
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(2)
+ const internalRequests = doMock.stubFetch.mock.calls.map(([internal]) => internal as Request)
+ expect(new Set(internalRequests).size).toBe(2)
+ expect(internalRequests.map((internal) => internal.url)).toEqual([
+ "http://internal/broadcast",
+ "http://internal/broadcast",
+ ])
+ expect(internalRequests.map((internal) => internal.method)).toEqual(["POST", "POST"])
+ await expect(Promise.all(internalRequests.map((internal) => internal.text()))).resolves.toEqual([
+ JSON.stringify({ type: "event", value: 7 }),
+ JSON.stringify({ type: "event", value: 7 }),
+ ])
+ expect(messageStringifyCount).toBe(1)
+ expect(loggerMocks.child).toHaveBeenCalledWith({
+ traceId: "trace-bulk",
+ rawCount: 5,
+ uniqueCount: 3,
+ targetCount: 2,
+ excludedCount: 1,
+ })
+ })
+
+ it.each([1, 40, 41, 81])(
+ "limits %i targets to sequential batches of at most forty",
+ async (targetCount) => {
+ let active = 0
+ let completed = 0
+ let maximum = 0
+ const startedAfterCompleted: number[] = []
+ doMock.stubFetch.mockImplementation(async () => {
+ startedAfterCompleted.push(completed)
+ active += 1
+ maximum = Math.max(maximum, active)
+ await Promise.resolve()
+ active -= 1
+ completed += 1
+ return new Response(JSON.stringify({ sent: 1 }), { status: 200 })
+ })
+ const userIds = Array.from({ length: targetCount }, (_, index) => `u${index}`)
+
+ const res = await handler.fetch(makeBulkRequest(JSON.stringify({
+ userIds,
+ message: { type: "event" },
+ })), env as any)
+
+ await expect(res.json()).resolves.toEqual({ sent: targetCount })
+ expect(maximum).toBe(Math.min(targetCount, 40))
+ if (targetCount > 40) expect(startedAfterCompleted[40]).toBe(40)
+ if (targetCount > 80) expect(startedAfterCompleted[80]).toBe(80)
+ },
+ )
+
+ it("continues after every failure shape and aggregates authenticated-tab sent counts", async () => {
+ doMock.stubFetch.mockImplementation(async () => {
+ const index = doMock.stubFetch.mock.calls.length - 1
+ if (index === 0) throw new Error("stub down")
+ if (index === 1) return new Response("no", { status: 503 })
+ if (index === 2) return new Response("not-json", { status: 200 })
+ if (index === 3) return new Response(JSON.stringify({ sent: -1 }), { status: 200 })
+ if (index === 4) return new Response(JSON.stringify({ sent: 2 }), { status: 200 })
+ return new Response(JSON.stringify({ sent: 3 }), { status: 200 })
+ })
+
+ const res = await handler.fetch(makeBulkRequest(JSON.stringify({
+ userIds: ["throws", "non-ok", "bad-json", "bad-sent", "good-two", "good-three"],
+ message: { type: "event" },
+ })), env as any)
+
+ expect(res.status).toBe(200)
+ await expect(res.json()).resolves.toEqual({ sent: 5 })
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(6)
+ expect(loggerMocks.warn.mock.calls.map(([, fields]) => (
+ fields as { failureKind?: string }
+ ).failureKind)).toEqual(["throw", "non-ok", "invalid-json", "invalid-sent"])
+ expect(loggerMocks.warn).toHaveBeenNthCalledWith(
+ 2,
+ "bulk user broadcast target failed",
+ expect.objectContaining({ userId: "non-ok", failureKind: "non-ok", status: 503 }),
+ )
+ expect(loggerMocks.info).toHaveBeenCalledWith(
+ "bulk user broadcast complete",
+ expect.objectContaining({ successCount: 2, failureCount: 4, sent: 5 }),
+ )
+ })
+ })
+})
diff --git a/src/ws-do/src/routes/broadcast.ts b/src/ws-do/src/routes/broadcast.ts
new file mode 100644
index 000000000..c35cc421f
--- /dev/null
+++ b/src/ws-do/src/routes/broadcast.ts
@@ -0,0 +1,152 @@
+import type { RouterContext } from "../router-context"
+
+const maxBulkUserIds = 1000
+const bulkBatchSize = 40
+
+type BulkBroadcastBody = {
+ userIds: string[]
+ message: Record<string, unknown> & { type: string }
+ excludeUserId?: string
+}
+
+type BulkTargetResult =
+ | { ok: true; sent: number }
+ | { ok: false; failureKind: "non-ok" | "invalid-json" | "invalid-sent"; status: number }
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value)
+}
+
+function isBulkBroadcastBody(value: unknown): value is BulkBroadcastBody {
+ if (!isRecord(value) || !Array.isArray(value.userIds)) return false
+ if (value.userIds.length > maxBulkUserIds) return false
+ if (value.userIds.some((userId) => typeof userId !== "string" || userId.length === 0)) return false
+ if (!isRecord(value.message) || typeof value.message.type !== "string" || value.message.type.length === 0) return false
+ if (
+ Object.prototype.hasOwnProperty.call(value, "excludeUserId")
+ && (typeof value.excludeUserId !== "string" || value.excludeUserId.length === 0)
+ ) return false
+ return true
+}
+
+function invalidBulkRequest(): Response {
+ return Response.json({ error: "Invalid bulk broadcast request" }, { status: 400 })
+}
+
+async function broadcastToBulkTarget(
+ env: Env,
+ userId: string,
+ messageBody: string,
+): Promise<BulkTargetResult> {
+ const doId = env.WS_DO.idFromName("user:" + userId)
+ const stub = env.WS_DO.get(doId)
+ const response = await stub.fetch(new Request("http://internal/broadcast", {
+ method: "POST",
+ body: messageBody,
+ }))
+ if (!response.ok) return { ok: false, failureKind: "non-ok", status: response.status }
+
+ let payload: unknown
+ try {
+ payload = await response.json()
+ } catch {
+ return { ok: false, failureKind: "invalid-json", status: response.status }
+ }
+ if (
+ !isRecord(payload)
+ || typeof payload.sent !== "number"
+ || !Number.isFinite(payload.sent)
+ || !Number.isInteger(payload.sent)
+ || payload.sent < 0
+ ) {
+ return { ok: false, failureKind: "invalid-sent", status: response.status }
+ }
+ return { ok: true, sent: payload.sent }
+}
+
+export async function handleDaemonBroadcast({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
+ const daemonBroadcast = url.pathname.match(/^\/broadcast\/daemon\/(.+)$/)
+ if (!daemonBroadcast || request.method !== "POST") return null
+
+ const daemonId = daemonBroadcast[1]
+ const reqLog = log.child({ traceId, daemonId })
+ reqLog.debug("broadcasting to daemon")
+
+ const doId = env.WS_DO.idFromName("daemon:" + daemonId)
+ const stub = env.WS_DO.get(doId)
+ return stub.fetch(new Request("http://internal/broadcast", { method: "POST", body: request.body, duplex: "half" } as RequestInit))
+}
+
+export async function handleUserBroadcast({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
+ const userBroadcast = url.pathname.match(/^\/broadcast\/user\/(.+)$/)
+ if (!userBroadcast || request.method !== "POST") return null
+
+ const userId = userBroadcast[1]
+ const reqLog = log.child({ traceId, userId })
+ reqLog.debug("broadcasting to user")
+
+ const doId = env.WS_DO.idFromName("user:" + userId)
+ const stub = env.WS_DO.get(doId)
+ return stub.fetch(new Request("http://internal/broadcast", { method: "POST", body: request.body, duplex: "half" } as RequestInit))
+}
+
+export async function handleUsersBroadcast({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
+ if (url.pathname !== "/broadcast/users" || request.method !== "POST") return null
+
+ let body: unknown
+ try {
+ body = await request.json()
+ } catch {
+ return invalidBulkRequest()
+ }
+ if (!isBulkBroadcastBody(body)) return invalidBulkRequest()
+
+ const uniqueUserIds = [...new Set(body.userIds)]
+ const targetUserIds = body.excludeUserId === undefined
+ ? uniqueUserIds
+ : uniqueUserIds.filter((userId) => userId !== body.excludeUserId)
+ const reqLog = log.child({
+ traceId,
+ rawCount: body.userIds.length,
+ uniqueCount: uniqueUserIds.length,
+ targetCount: targetUserIds.length,
+ excludedCount: uniqueUserIds.length - targetUserIds.length,
+ })
+ reqLog.debug("broadcasting to users")
+
+ const messageBody = JSON.stringify(body.message)
+ let successCount = 0
+ let failureCount = 0
+ let sent = 0
+
+ for (let start = 0; start < targetUserIds.length; start += bulkBatchSize) {
+ const batch = targetUserIds.slice(start, start + bulkBatchSize)
+ const results = await Promise.allSettled(
+ batch.map((userId) => broadcastToBulkTarget(env, userId, messageBody)),
+ )
+ for (const [index, result] of results.entries()) {
+ const userId = batch[index]
+ if (result.status === "rejected") {
+ failureCount += 1
+ reqLog.warn("bulk user broadcast target failed", {
+ userId,
+ failureKind: "throw",
+ err: String(result.reason),
+ })
+ } else if (!result.value.ok) {
+ failureCount += 1
+ reqLog.warn("bulk user broadcast target failed", {
+ userId,
+ failureKind: result.value.failureKind,
+ status: result.value.status,
+ })
+ } else {
+ successCount += 1
+ sent += result.value.sent
+ }
+ }
+ }
+
+ reqLog.info("bulk user broadcast complete", { successCount, failureCount, sent })
+ return Response.json({ sent })
+}
diff --git a/src/ws-do/src/routes/community-machine-delivery.test.ts b/src/ws-do/src/routes/community-machine-delivery.test.ts
new file mode 100644
index 000000000..0c07c0ea0
--- /dev/null
+++ b/src/ws-do/src/routes/community-machine-delivery.test.ts
@@ -0,0 +1,243 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ createRouterTestContext,
+ loadRouter,
+ getSharedMocks,
+ type RouterHandler,
+ type RouterTestContext,
+} from "./test-harness"
+
+const sharedMocks = getSharedMocks()
+const mockHashCredential = sharedMocks.hashCredential
+const mockDoNameFromHash = sharedMocks.doNameFromHash
+const mockGetActiveDoNamesForMachine = sharedMocks.getActiveDoNamesForMachine
+const loggerMocks = {
+ child: sharedMocks.loggerChild,
+ debug: sharedMocks.loggerDebug,
+}
+
+describe("ws-do router", () => {
+ let handler: RouterHandler
+ let doMock: RouterTestContext["doMock"]
+ let rateLimitMock: RouterTestContext["rateLimitMock"]
+ let env: RouterTestContext["env"]
+
+ beforeEach(async () => {
+ vi.resetModules()
+ vi.clearAllMocks()
+ const context = createRouterTestContext()
+ doMock = context.doMock
+ rateLimitMock = context.rateLimitMock
+ env = context.env
+ handler = await loadRouter()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+ vi.resetModules()
+ doMock = undefined as unknown as RouterTestContext["doMock"]
+ rateLimitMock = undefined as unknown as RouterTestContext["rateLimitMock"]
+ env = undefined as unknown as RouterTestContext["env"]
+ handler = undefined as unknown as RouterHandler
+ })
+
+ describe("POST /community-machine/by-id/:machineId/push", () => {
+ beforeEach(() => {
+ mockGetActiveDoNamesForMachine.mockReset()
+ mockGetActiveDoNamesForMachine.mockResolvedValue([])
+ })
+
+ it("treats a D1 lookup failure as best-effort { sent: 0 }", async () => {
+ mockGetActiveDoNamesForMachine.mockRejectedValue(new Error("d1 unavailable"))
+ const res = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/push",
+ { method: "POST", body: JSON.stringify({ type: "bot:updated" }) },
+ ), env as any)
+
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 0 })
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("returns { sent: 0 } without touching a DO when no active names exist", async () => {
+ const res = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/push",
+ { method: "POST", body: JSON.stringify({ type: "bot:removed" }) },
+ ), env as any)
+
+ expect(mockGetActiveDoNamesForMachine).toHaveBeenCalledWith({}, "machine-1")
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 0 })
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("decodes the machine id and best-effort fans the verbatim body to every active DO", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b", "do-c"])
+ doMock.stubFetch
+ .mockResolvedValueOnce(new Response("ok", { status: 200 }))
+ .mockResolvedValueOnce(new Response("offline", { status: 503 }))
+ .mockRejectedValueOnce(new Error("gone"))
+ const body = JSON.stringify({ type: "bot:added", botId: "bot-1" })
+ const res = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine%20one/push",
+ { method: "POST", body },
+ ), env as any)
+
+ expect(mockGetActiveDoNamesForMachine).toHaveBeenCalledWith({}, "machine one")
+ expect(doMock.idFromName.mock.calls.map(([name]) => name)).toEqual([
+ "community-machine:do-a",
+ "community-machine:do-b",
+ "community-machine:do-c",
+ ])
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(3)
+ const internal = doMock.stubFetch.mock.calls[0][0] as Request
+ expect(internal.url).toBe("http://internal/push")
+ expect(internal.method).toBe("POST")
+ expect(internal.headers.get("content-type")).toBe("application/json")
+ expect(await internal.text()).toBe(body)
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 1 })
+ })
+ })
+
+ describe("POST /community-machine/by-id/:machineId/forward-agent-wake", () => {
+ beforeEach(() => {
+ mockGetActiveDoNamesForMachine.mockReset()
+ mockGetActiveDoNamesForMachine.mockResolvedValue([])
+ })
+
+ it("zero active doNames → { sent: 0 } without touching any DO", async () => {
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
+ method: "POST",
+ body: JSON.stringify({ type: "agent:wake" }),
+ })
+ const res = await handler.fetch(req, env as any)
+
+ expect(mockGetActiveDoNamesForMachine).toHaveBeenCalledWith({}, "machine-1")
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 0 })
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("single active doName, daemon connected → forwards and aggregates sent count", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])
+ doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
+
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ type: "agent:wake", agentId: "bot-1" }),
+ })
+ const res = await handler.fetch(req, env as any)
+
+ expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-abc")
+ const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
+ expect(stubReq.url).toBe("http://internal/forward-agent-wake")
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 1 })
+ })
+
+ it("daemon offline (DO reports { sent: 0 }) → does not count as delivered", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])
+ doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 0 }), { status: 200 }))
+
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
+ method: "POST",
+ body: JSON.stringify({ type: "agent:wake" }),
+ })
+ const res = await handler.fetch(req, env as any)
+
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 0 })
+ })
+
+ it("multi-doName fan-out: both DOs hit, aggregate sums delivered counts", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b"])
+ let call = 0
+ doMock.stubFetch.mockImplementation(() => {
+ call++
+ const sent = call === 1 ? 0 : 1
+ return Promise.resolve(new Response(JSON.stringify({ sent }), { status: 200 }))
+ })
+
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
+ method: "POST",
+ body: JSON.stringify({ type: "agent:wake" }),
+ })
+ const res = await handler.fetch(req, env as any)
+
+ expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-a")
+ expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-b")
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 1 })
+ })
+
+ it("DO fetch throws — tolerated, other doNames still evaluated", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b"])
+ let call = 0
+ doMock.stubFetch.mockImplementation(() => {
+ call++
+ if (call === 1) return Promise.reject(new Error("network error"))
+ return Promise.resolve(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
+ })
+
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
+ method: "POST",
+ body: JSON.stringify({ type: "agent:wake" }),
+ })
+ const res = await handler.fetch(req, env as any)
+
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 1 })
+ })
+
+ it("DO fetch throws with no delivery → retryable 503", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a"])
+ doMock.stubFetch.mockRejectedValue(new Error("network error"))
+
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
+ method: "POST",
+ body: JSON.stringify({ type: "agent:wake" }),
+ })
+ const res = await handler.fetch(req, env as any)
+
+ expect(res.status).toBe(503)
+ expect(await res.json()).toEqual({ error: "failed to forward agent wake" })
+ })
+
+ it("non-2xx or malformed DO responses with no delivery → retryable 503", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b"])
+ let call = 0
+ doMock.stubFetch.mockImplementation(() => {
+ call++
+ if (call === 1) return Promise.resolve(new Response("oops", { status: 502 }))
+ return Promise.resolve(new Response(JSON.stringify({ sent: "bad" }), { status: 200 }))
+ })
+
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
+ method: "POST",
+ body: JSON.stringify({ type: "agent:wake" }),
+ })
+ const res = await handler.fetch(req, env as any)
+
+ expect(res.status).toBe(503)
+ expect(await res.json()).toEqual({ error: "failed to forward agent wake" })
+ })
+
+ it("DB lookup failure → retryable 503, not offline { sent: 0 }", async () => {
+ mockGetActiveDoNamesForMachine.mockRejectedValue(new Error("d1 unreachable"))
+
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-wake", {
+ method: "POST",
+ body: JSON.stringify({ type: "agent:wake" }),
+ })
+ const res = await handler.fetch(req, env as any)
+
+ expect(res.status).toBe(503)
+ expect(await res.json()).toEqual({ error: "failed to resolve machine" })
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/src/ws-do/src/routes/community-machine-delivery.ts b/src/ws-do/src/routes/community-machine-delivery.ts
new file mode 100644
index 000000000..0c7b12951
--- /dev/null
+++ b/src/ws-do/src/routes/community-machine-delivery.ts
@@ -0,0 +1,114 @@
+import { queries } from "@alook/shared"
+import type { RouterContext } from "../router-context"
+
+export async function handleMachinePush({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
+ // POST /community-machine/by-id/<machineId>/push — push a bot event
+ // (bot:added / bot:updated / bot:removed) to the daemon connection for
+ // this machine. Looks up the live credential do_name via D1 and dispatches
+ // to the corresponding DO. Best-effort — if the daemon is offline the DO
+ // drops the event; cold-start warmup on reconnect re-syncs authoritative
+ // state.
+ const pushToMachine = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/push$/)
+ if (!pushToMachine || request.method !== "POST") return null
+
+ const machineId = decodeURIComponent(pushToMachine[1])
+ const reqLog = log.child({ traceId, machineId })
+ reqLog.debug("pushing bot event to machine")
+ // Look up the active `do_name` for this machineId via D1. Multiple
+ // credentials may exist for a machine over time; we push to every live
+ // one (there should be exactly one, but be robust).
+ let doNames: string[] = []
+ try {
+ const shared = await import("@alook/shared")
+ const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
+ doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
+ } catch {
+ // If we can't reach D1 to resolve, silently drop — the daemon's
+ // reconnect warmup will re-sync authoritative state.
+ return Response.json({ sent: 0 })
+ }
+ if (doNames.length === 0) {
+ return Response.json({ sent: 0 })
+ }
+ const bodyText = await request.text()
+ let delivered = 0
+ for (const dn of doNames) {
+ const doId = env.WS_DO.idFromName("community-machine:" + dn)
+ const stub = env.WS_DO.get(doId)
+ try {
+ const res = await stub.fetch(
+ new Request("http://internal/push", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: bodyText,
+ }),
+ )
+ if (res.ok) delivered++
+ } catch {
+ // best-effort
+ }
+ }
+ return Response.json({ sent: delivered })
+}
+
+export async function handleMachineWake({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
+ // POST /community-machine/by-id/<machineId>/forward-agent-wake — sibling
+ // of the `/push` route above, for the minimal-wake-queue-unread-notice
+ // wake path. Forwards an already-built `HostCommand` (`agent:wake`)
+ // verbatim to every live DO for this machine's active credential(s),
+ // then aggregates by parsing each DO's own `{ sent: N }` response —
+ // unlike `/push`, we must NOT just count `res.ok`: a 200 with
+ // `{ sent: 0 }` means that DO has no authenticated daemon socket at all,
+ // which must not be reported as delivered.
+ const forwardAgentWake = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-wake$/)
+ if (!forwardAgentWake || request.method !== "POST") return null
+
+ const machineId = decodeURIComponent(forwardAgentWake[1])
+ const reqLog = log.child({ traceId, machineId })
+ reqLog.debug("forwarding agent:wake to machine")
+
+ let doNames: string[] = []
+ try {
+ const shared = await import("@alook/shared")
+ const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
+ doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
+ } catch (err) {
+ reqLog.error("failed to resolve machine doNames for agent wake", { err })
+ return Response.json({ error: "failed to resolve machine" }, { status: 503 })
+ }
+ if (doNames.length === 0) {
+ return Response.json({ sent: 0 })
+ }
+ const bodyText = await request.text()
+ let delivered = 0
+ let transientFailure = false
+ for (const dn of doNames) {
+ const doId = env.WS_DO.idFromName("community-machine:" + dn)
+ const stub = env.WS_DO.get(doId)
+ try {
+ const res = await stub.fetch(
+ new Request("http://internal/forward-agent-wake", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: bodyText,
+ }),
+ )
+ if (!res.ok) {
+ transientFailure = true
+ continue
+ }
+ const data = (await res.json()) as { sent?: unknown }
+ if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {
+ transientFailure = true
+ continue
+ }
+ delivered += data.sent
+ } catch {
+ transientFailure = true
+ }
+ }
+ if (delivered === 0 && transientFailure) {
+ return Response.json({ error: "failed to forward agent wake" }, { status: 503 })
+ }
+ return Response.json({ sent: delivered })
+}
diff --git a/src/ws-do/src/routes/community-machine-lifecycle.test.ts b/src/ws-do/src/routes/community-machine-lifecycle.test.ts
new file mode 100644
index 000000000..e2682a711
--- /dev/null
+++ b/src/ws-do/src/routes/community-machine-lifecycle.test.ts
@@ -0,0 +1,269 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ createRouterTestContext,
+ loadRouter,
+ getSharedMocks,
+ type RouterHandler,
+ type RouterTestContext,
+} from "./test-harness"
+
+const sharedMocks = getSharedMocks()
+const mockHashCredential = sharedMocks.hashCredential
+const mockDoNameFromHash = sharedMocks.doNameFromHash
+const mockGetActiveDoNamesForMachine = sharedMocks.getActiveDoNamesForMachine
+const loggerMocks = {
+ child: sharedMocks.loggerChild,
+ debug: sharedMocks.loggerDebug,
+}
+
+describe("ws-do router", () => {
+ let handler: RouterHandler
+ let doMock: RouterTestContext["doMock"]
+ let rateLimitMock: RouterTestContext["rateLimitMock"]
+ let env: RouterTestContext["env"]
+
+ beforeEach(async () => {
+ vi.resetModules()
+ vi.clearAllMocks()
+ const context = createRouterTestContext()
+ doMock = context.doMock
+ rateLimitMock = context.rateLimitMock
+ env = context.env
+ handler = await loadRouter()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+ vi.resetModules()
+ doMock = undefined as unknown as RouterTestContext["doMock"]
+ rateLimitMock = undefined as unknown as RouterTestContext["rateLimitMock"]
+ env = undefined as unknown as RouterTestContext["env"]
+ handler = undefined as unknown as RouterHandler
+ })
+
+ describe("POST /community-machine/by-id/:machineId/forward-agent-reset", () => {
+ const validBody = {
+ agentId: "bot-1",
+ config: { version: 1, runtime: "claude", model: { kind: "default" }, mode: { kind: "default" } },
+ launchId: "l-1",
+ }
+
+ beforeEach(() => {
+ mockGetActiveDoNamesForMachine.mockReset()
+ mockGetActiveDoNamesForMachine.mockResolvedValue([])
+ })
+
+ it("rejects missing agentId with 400 without touching D1 or the DOs", async () => {
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-reset", {
+ method: "POST",
+ body: JSON.stringify({ config: validBody.config, launchId: "l-1" }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ expect(mockGetActiveDoNamesForMachine).not.toHaveBeenCalled()
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("rejects extra unexpected fields with 400", async () => {
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-reset", {
+ method: "POST",
+ body: JSON.stringify({ ...validBody, sneaky: "value" }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("zero active doNames → { sent: 0 } without touching any DO", async () => {
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-reset", {
+ method: "POST",
+ body: JSON.stringify(validBody),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 0 })
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("well-formed body → forwards a { type:'agent:reset', ... } frame to each DO's /push and aggregates sent", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])
+ doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
+
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-reset", {
+ method: "POST",
+ body: JSON.stringify(validBody),
+ })
+ const res = await handler.fetch(req, env as any)
+
+ expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-abc")
+ const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
+ expect(stubReq.url).toBe("http://internal/push")
+ const forwardedBody = await stubReq.text()
+ const parsed = JSON.parse(forwardedBody)
+ expect(parsed).toEqual({ type: "agent:reset", agentId: "bot-1", config: validBody.config, launchId: "l-1" })
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 1 })
+ })
+ })
+
+ describe("POST /community-machine/by-id/:machineId/forward-batch-reset", () => {
+ const resets = [
+ {
+ agentId: "bot-1",
+ config: { version: 1, runtime: "claude", model: { kind: "default" }, mode: { kind: "default" } },
+ launchId: "launch-1",
+ },
+ {
+ agentId: "bot-2",
+ config: { version: 2, runtime: "codex", model: { kind: "named", name: "gpt-5" }, mode: { kind: "default" } },
+ launchId: "launch-2",
+ },
+ ]
+
+ beforeEach(() => {
+ mockGetActiveDoNamesForMachine.mockReset()
+ mockGetActiveDoNamesForMachine.mockResolvedValue([])
+ })
+
+ it("rejects both an invalid top-level shape and an invalid reset item", async () => {
+ const invalidTop = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-batch-reset",
+ { method: "POST", body: JSON.stringify({ resets, extra: true }) },
+ ), env as any)
+ const invalidItem = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-batch-reset",
+ { method: "POST", body: JSON.stringify({ resets: [{ ...resets[0], extra: true }] }) },
+ ), env as any)
+
+ expect(invalidTop.status).toBe(400)
+ expect(await invalidTop.json()).toEqual({ error: "invalid payload" })
+ expect(invalidItem.status).toBe(400)
+ expect(await invalidItem.json()).toEqual({ error: "invalid payload" })
+ expect(mockGetActiveDoNamesForMachine).not.toHaveBeenCalled()
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("returns { sent: 0 } without touching a DO when no active names exist", async () => {
+ const res = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-batch-reset",
+ { method: "POST", body: JSON.stringify({ resets }) },
+ ), env as any)
+
+ expect(mockGetActiveDoNamesForMachine).toHaveBeenCalledWith({}, "machine-1")
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 0 })
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("forwards the exact machine:reset_all frame and aggregates every delivered count", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b"])
+ doMock.stubFetch
+ .mockResolvedValueOnce(new Response(JSON.stringify({ sent: 2 }), { status: 200 }))
+ .mockResolvedValueOnce(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
+ const res = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-batch-reset",
+ { method: "POST", body: JSON.stringify({ resets }) },
+ ), env as any)
+
+ expect(doMock.idFromName.mock.calls.map(([name]) => name)).toEqual([
+ "community-machine:do-a",
+ "community-machine:do-b",
+ ])
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(2)
+ const internal = doMock.stubFetch.mock.calls[0][0] as Request
+ expect(internal.url).toBe("http://internal/push")
+ expect(internal.method).toBe("POST")
+ expect(internal.headers.get("content-type")).toBe("application/json")
+ expect(await internal.json()).toEqual({ type: "machine:reset_all", resets })
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 3 })
+ })
+
+ it("returns the exact retryable 503 when every active DO fails transiently", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b"])
+ doMock.stubFetch
+ .mockResolvedValueOnce(new Response("down", { status: 502 }))
+ .mockRejectedValueOnce(new Error("network"))
+ const res = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-batch-reset",
+ { method: "POST", body: JSON.stringify({ resets }) },
+ ), env as any)
+
+ expect(res.status).toBe(503)
+ expect(await res.json()).toEqual({ error: "failed to forward batch reset" })
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(2)
+ })
+ })
+
+ describe("POST /community-machine/by-id/:machineId/forward-agent-nap", () => {
+ const validBody = {
+ agentId: "bot-1",
+ config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },
+ launchId: "launch-1",
+ handoff: "Resume the queued review.",
+ }
+
+ beforeEach(() => {
+ mockGetActiveDoNamesForMachine.mockReset()
+ mockGetActiveDoNamesForMachine.mockResolvedValue([])
+ })
+
+ it("rejects a blank handoff with the exact invalid-payload response", async () => {
+ const res = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-agent-nap",
+ { method: "POST", body: JSON.stringify({ ...validBody, handoff: " " }) },
+ ), env as any)
+
+ expect(res.status).toBe(400)
+ expect(await res.json()).toEqual({ error: "invalid payload" })
+ expect(mockGetActiveDoNamesForMachine).not.toHaveBeenCalled()
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("returns { sent: 0 } without touching a DO when no active names exist", async () => {
+ const res = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-agent-nap",
+ { method: "POST", body: JSON.stringify(validBody) },
+ ), env as any)
+
+ expect(mockGetActiveDoNamesForMachine).toHaveBeenCalledWith({}, "machine-1")
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 0 })
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("forwards the exact agent:nap frame and aggregates every delivered count", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a", "do-b"])
+ doMock.stubFetch
+ .mockResolvedValueOnce(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
+ .mockResolvedValueOnce(new Response(JSON.stringify({ sent: 2 }), { status: 200 }))
+ const res = await handler.fetch(new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-agent-nap",
+ { method: "POST", body: JSON.stringify(validBody) },
+ ), env as any)
+
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(2)
+ const internal = doMock.stubFetch.mock.calls[0][0] as Request
+ expect(internal.url).toBe("http://internal/push")
+ expect(internal.method).toBe("POST")
+ expect(internal.headers.get("content-type")).toBe("application/json")
+ expect(await internal.json()).toEqual({ type: "agent:nap", ...validBody })
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 3 })
+ })
+ })
+
+ describe("force-close routing", () => {
+ it("keys the DO by the do_name suffix", async () => {
+ doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ closed: 1 })))
+ const doName = "a".repeat(32)
+ const req = new Request(`http://localhost/community-machine/${doName}/force-close`, {
+ method: "POST",
+ })
+ await handler.fetch(req, env as any)
+ expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:" + doName)
+ })
+ })
+})
diff --git a/src/ws-do/src/routes/community-machine-lifecycle.ts b/src/ws-do/src/routes/community-machine-lifecycle.ts
new file mode 100644
index 000000000..277c44a40
--- /dev/null
+++ b/src/ws-do/src/routes/community-machine-lifecycle.ts
@@ -0,0 +1,301 @@
+import { queries } from "@alook/shared"
+import type { RouterContext } from "../router-context"
+
+export async function handleMachineReset({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
+ // POST /community-machine/by-id/<machineId>/forward-agent-reset — owner-
+ // triggered `agent:reset` push. Same shape as `/forward-agent-wake`: build
+ // the HostCommand from a narrow payload (`{ agentId, config, launchId }`),
+ // resolve the machine's active `do_names`, forward the frame to each DO's
+ // `/push` route, and aggregate `{ sent }`. Rejects any extra field —
+ // callers must use `pushAgentResetToMachine`.
+ const forwardAgentReset = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-reset$/)
+ if (!forwardAgentReset || request.method !== "POST") return null
+
+ const machineId = decodeURIComponent(forwardAgentReset[1])
+ const reqLog = log.child({ traceId, machineId })
+ reqLog.debug("forwarding agent:reset to machine")
+
+ let payload: unknown
+ try {
+ payload = await request.json()
+ } catch {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (!payload || typeof payload !== "object") {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ const raw = payload as Record<string, unknown>
+ const allowedKeys = new Set(["agentId", "config", "launchId"])
+ for (const key of Object.keys(raw)) {
+ if (!allowedKeys.has(key)) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ }
+ const { agentId, config, launchId } = raw
+ if (typeof agentId !== "string" || agentId.length === 0) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (typeof launchId !== "string" || launchId.length === 0) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (!config || typeof config !== "object") {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+
+ let doNames: string[] = []
+ try {
+ const shared = await import("@alook/shared")
+ const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
+ doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
+ } catch (err) {
+ reqLog.error("failed to resolve machine doNames for agent reset", { err })
+ return Response.json({ error: "failed to resolve machine" }, { status: 503 })
+ }
+ if (doNames.length === 0) {
+ return Response.json({ sent: 0 })
+ }
+ const frame = JSON.stringify({ type: "agent:reset", agentId, config, launchId })
+ let delivered = 0
+ let transientFailure = false
+ for (const dn of doNames) {
+ const doId = env.WS_DO.idFromName("community-machine:" + dn)
+ const stub = env.WS_DO.get(doId)
+ try {
+ const res = await stub.fetch(
+ new Request("http://internal/push", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: frame,
+ }),
+ )
+ if (!res.ok) {
+ transientFailure = true
+ continue
+ }
+ const data = (await res.json()) as { sent?: unknown }
+ if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {
+ transientFailure = true
+ continue
+ }
+ delivered += data.sent
+ } catch {
+ transientFailure = true
+ }
+ }
+ if (delivered === 0 && transientFailure) {
+ return Response.json({ error: "failed to forward agent reset" }, { status: 503 })
+ }
+ return Response.json({ sent: delivered })
+}
+
+export async function handleMachineBatchReset({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
+ // POST /community-machine/by-id/<machineId>/forward-batch-reset —
+ // owner-triggered `machine:reset_all` push (batch reset all agents on the
+ // machine in ONE frame, not N fanned-out agent:reset). Twin of
+ // /forward-agent-reset: same doName resolution + `/push` fan-out + `{sent}`
+ // aggregation, but the body is a `resets` array (each item the narrow
+ // {agentId, config, launchId}) and the frame type is `machine:reset_all`.
+ // Callers must use `pushBatchResetToMachine`.
+ const forwardBatchReset = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-batch-reset$/)
+ if (!forwardBatchReset || request.method !== "POST") return null
+
+ const machineId = decodeURIComponent(forwardBatchReset[1])
+ const reqLog = log.child({ traceId, machineId })
+ reqLog.debug("forwarding machine:reset_all to machine")
+
+ let payload: unknown
+ try {
+ payload = await request.json()
+ } catch {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (!payload || typeof payload !== "object") {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ const raw = payload as Record<string, unknown>
+ // Only `resets` allowed at the top level.
+ for (const key of Object.keys(raw)) {
+ if (key !== "resets") {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ }
+ if (!Array.isArray(raw.resets)) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ // Validate each reset entry against the same narrow allowlist as
+ // forward-agent-reset — no extra fields, all three required.
+ const resets: Array<{ agentId: string; config: unknown; launchId: string }> = []
+ for (const item of raw.resets) {
+ if (!item || typeof item !== "object") {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ const r = item as Record<string, unknown>
+ const allowedKeys = new Set(["agentId", "config", "launchId"])
+ for (const key of Object.keys(r)) {
+ if (!allowedKeys.has(key)) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ }
+ if (typeof r.agentId !== "string" || r.agentId.length === 0) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (typeof r.launchId !== "string" || r.launchId.length === 0) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (!r.config || typeof r.config !== "object") {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ resets.push({ agentId: r.agentId, config: r.config, launchId: r.launchId })
+ }
+
+ let doNames: string[] = []
+ try {
+ const shared = await import("@alook/shared")
+ const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
+ doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
+ } catch (err) {
+ reqLog.error("failed to resolve machine doNames for batch reset", { err })
+ return Response.json({ error: "failed to resolve machine" }, { status: 503 })
+ }
+ if (doNames.length === 0) {
+ return Response.json({ sent: 0 })
+ }
+ const frame = JSON.stringify({ type: "machine:reset_all", resets })
+ let delivered = 0
+ let transientFailure = false
+ for (const dn of doNames) {
+ const doId = env.WS_DO.idFromName("community-machine:" + dn)
+ const stub = env.WS_DO.get(doId)
+ try {
+ const res = await stub.fetch(
+ new Request("http://internal/push", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: frame,
+ }),
+ )
+ if (!res.ok) {
+ transientFailure = true
+ continue
+ }
+ const data = (await res.json()) as { sent?: unknown }
+ if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {
+ transientFailure = true
+ continue
+ }
+ delivered += data.sent
+ } catch {
+ transientFailure = true
+ }
+ }
+ if (delivered === 0 && transientFailure) {
+ return Response.json({ error: "failed to forward batch reset" }, { status: 503 })
+ }
+ return Response.json({ sent: delivered })
+}
+
+export async function handleMachineNap({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
+ // POST /community-machine/by-id/<machineId>/forward-agent-nap — agent
+ // self-initiated `agent:nap` push. Twin of /forward-agent-reset but the
+ // allowlist additionally carries the mandatory `handoff` string (the
+ // agent's note to its reborn self, spliced into the rewake prompt). Same
+ // doName resolution + `/push` fan-out + `{sent}` aggregation. Callers must
+ // use `pushAgentNapToMachine`.
+ const forwardAgentNap = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-nap$/)
+ if (!forwardAgentNap || request.method !== "POST") return null
+
+ const machineId = decodeURIComponent(forwardAgentNap[1])
+ const reqLog = log.child({ traceId, machineId })
+ reqLog.debug("forwarding agent:nap to machine")
+
+ let payload: unknown
+ try {
+ payload = await request.json()
+ } catch {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (!payload || typeof payload !== "object") {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ const raw = payload as Record<string, unknown>
+ const allowedKeys = new Set(["agentId", "config", "launchId", "handoff"])
+ for (const key of Object.keys(raw)) {
+ if (!allowedKeys.has(key)) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ }
+ const { agentId, config, launchId, handoff } = raw
+ if (typeof agentId !== "string" || agentId.length === 0) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (typeof launchId !== "string" || launchId.length === 0) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (!config || typeof config !== "object") {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (typeof handoff !== "string" || handoff.trim().length === 0) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+
+ let doNames: string[] = []
+ try {
+ const shared = await import("@alook/shared")
+ const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
+ doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
+ } catch (err) {
+ reqLog.error("failed to resolve machine doNames for agent nap", { err })
+ return Response.json({ error: "failed to resolve machine" }, { status: 503 })
+ }
+ if (doNames.length === 0) {
+ return Response.json({ sent: 0 })
+ }
+ const frame = JSON.stringify({ type: "agent:nap", agentId, config, launchId, handoff })
+ let delivered = 0
+ let transientFailure = false
+ for (const dn of doNames) {
+ const doId = env.WS_DO.idFromName("community-machine:" + dn)
+ const stub = env.WS_DO.get(doId)
+ try {
+ const res = await stub.fetch(
+ new Request("http://internal/push", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: frame,
+ }),
+ )
+ if (!res.ok) {
+ transientFailure = true
+ continue
+ }
+ const data = (await res.json()) as { sent?: unknown }
+ if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {
+ transientFailure = true
+ continue
+ }
+ delivered += data.sent
+ } catch {
+ transientFailure = true
+ }
+ }
+ if (delivered === 0 && transientFailure) {
+ return Response.json({ error: "failed to forward agent nap" }, { status: 503 })
+ }
+ return Response.json({ sent: delivered })
+}
+
+export async function handleMachineForceClose({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
+ // POST /community-machine/<doName>/force-close — disconnect a daemon by
+ // its DO-name suffix (first 32 hex of the credential hash). Callers look
+ // the suffix up from `community_machine_credential.do_name`.
+ const forceClose = url.pathname.match(/^\/community-machine\/([^/]+)\/force-close$/)
+ if (!forceClose || request.method !== "POST") return null
+
+ const doName = decodeURIComponent(forceClose[1])
+ const reqLog = log.child({ traceId, doName })
+ reqLog.debug("force-closing community machine")
+
+ const doId = env.WS_DO.idFromName("community-machine:" + doName)
+ const stub = env.WS_DO.get(doId)
+ return stub.fetch(new Request("http://internal/force-close", { method: "POST" }))
+}
diff --git a/src/ws-do/src/routes/community-machine-switch.test.ts b/src/ws-do/src/routes/community-machine-switch.test.ts
new file mode 100644
index 000000000..a8adde7b3
--- /dev/null
+++ b/src/ws-do/src/routes/community-machine-switch.test.ts
@@ -0,0 +1,200 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ createRouterTestContext,
+ loadRouter,
+ getSharedMocks,
+ type RouterHandler,
+ type RouterTestContext,
+} from "./test-harness"
+
+const sharedMocks = getSharedMocks()
+const mockHashCredential = sharedMocks.hashCredential
+const mockDoNameFromHash = sharedMocks.doNameFromHash
+const mockGetActiveDoNamesForMachine = sharedMocks.getActiveDoNamesForMachine
+const loggerMocks = {
+ child: sharedMocks.loggerChild,
+ debug: sharedMocks.loggerDebug,
+}
+
+describe("ws-do router", () => {
+ let handler: RouterHandler
+ let doMock: RouterTestContext["doMock"]
+ let rateLimitMock: RouterTestContext["rateLimitMock"]
+ let env: RouterTestContext["env"]
+
+ beforeEach(async () => {
+ vi.resetModules()
+ vi.clearAllMocks()
+ const context = createRouterTestContext()
+ doMock = context.doMock
+ rateLimitMock = context.rateLimitMock
+ env = context.env
+ handler = await loadRouter()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+ vi.resetModules()
+ doMock = undefined as unknown as RouterTestContext["doMock"]
+ rateLimitMock = undefined as unknown as RouterTestContext["rateLimitMock"]
+ env = undefined as unknown as RouterTestContext["env"]
+ handler = undefined as unknown as RouterHandler
+ })
+
+ describe("POST /community-machine/by-id/:machineId/forward-agent-model-switch", () => {
+ // from/to are required for DO pending attribution; outer body has no `type`
+ // — the inner DO endpoint `/push-model-switch` stamps the wire frame.
+ const validBody = {
+ agentId: "bot-1",
+ config: { version: 1, runtime: "claude", model: { kind: "named", name: "claude-sonnet-4-6" }, mode: { kind: "default" } },
+ launchId: "l-1",
+ from: null as string | null,
+ to: "claude-sonnet-4-6" as string | null,
+ }
+
+ beforeEach(() => {
+ mockGetActiveDoNamesForMachine.mockReset()
+ mockGetActiveDoNamesForMachine.mockResolvedValue([])
+ })
+
+ it("forwards attribution body to DO /push-model-switch (no type on inner body)", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])
+ doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-model-switch", {
+ method: "POST",
+ body: JSON.stringify(validBody),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-abc")
+ const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
+ expect(stubReq.url).toBe("http://internal/push-model-switch")
+ const parsed = JSON.parse(await stubReq.text())
+ expect(parsed).toEqual({
+ agentId: "bot-1",
+ config: validBody.config,
+ launchId: "l-1",
+ from: null,
+ to: "claude-sonnet-4-6",
+ })
+ expect(parsed.type).toBeUndefined()
+ expect(parsed.config.model).toEqual({ kind: "named", name: "claude-sonnet-4-6" })
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 1 })
+ })
+
+ it("rejects an extra top-level key with 400 (allowlist parity with reset)", async () => {
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-model-switch", {
+ method: "POST",
+ body: JSON.stringify({ ...validBody, sneaky: "x" }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("rejects a missing/non-object config with 400", async () => {
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-model-switch", {
+ method: "POST",
+ body: JSON.stringify({ agentId: "bot-1", config: "nope", launchId: "l-1", from: null, to: "x" }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ expect(mockGetActiveDoNamesForMachine).not.toHaveBeenCalled()
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("rejects missing from/to with 400", async () => {
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-model-switch", {
+ method: "POST",
+ body: JSON.stringify({
+ agentId: "bot-1",
+ config: validBody.config,
+ launchId: "l-1",
+ }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("zero active doNames → { sent: 0 } without erroring", async () => {
+ const req = new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-model-switch", {
+ method: "POST",
+ body: JSON.stringify(validBody),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 0 })
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+ })
+
+ describe("POST /community-machine/by-id/:machineId/forward-agent-provider-switch", () => {
+ const validBody = {
+ agentId: "bot-1",
+ config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },
+ launchId: "l-1",
+ from: "claude",
+ to: "codex",
+ }
+
+ beforeEach(() => {
+ mockGetActiveDoNamesForMachine.mockReset()
+ mockGetActiveDoNamesForMachine.mockResolvedValue([])
+ })
+
+ it("forwards attribution body to DO /push-provider-switch (no type on inner body)", async () => {
+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-abc"])
+ doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ sent: 1 }), { status: 200 }))
+ const req = new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-agent-provider-switch",
+ { method: "POST", body: JSON.stringify(validBody) },
+ )
+ const res = await handler.fetch(req, env as any)
+ expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:do-abc")
+ const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
+ expect(stubReq.url).toBe("http://internal/push-provider-switch")
+ const parsed = JSON.parse(await stubReq.text())
+ expect(parsed).toEqual({
+ agentId: "bot-1",
+ config: validBody.config,
+ launchId: "l-1",
+ from: "claude",
+ to: "codex",
+ })
+ expect(parsed.type).toBeUndefined()
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 1 })
+ })
+
+ it("rejects missing from/to with 400", async () => {
+ const req = new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-agent-provider-switch",
+ {
+ method: "POST",
+ body: JSON.stringify({
+ agentId: "bot-1",
+ config: validBody.config,
+ launchId: "l-1",
+ }),
+ },
+ )
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("zero active doNames → { sent: 0 }", async () => {
+ const req = new Request(
+ "http://localhost/community-machine/by-id/machine-1/forward-agent-provider-switch",
+ { method: "POST", body: JSON.stringify(validBody) },
+ )
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 0 })
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/src/ws-do/src/routes/community-machine-switch.ts b/src/ws-do/src/routes/community-machine-switch.ts
new file mode 100644
index 000000000..44a9bc6b7
--- /dev/null
+++ b/src/ws-do/src/routes/community-machine-switch.ts
@@ -0,0 +1,165 @@
+import { queries } from "@alook/shared"
+import type { RouterContext } from "../router-context"
+
+export async function handleMachineModelSwitch({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
+ // POST /community-machine/by-id/<machineId>/forward-agent-model-switch —
+ // owner-triggered model switch. `from`/`to` stay server-side for completion
+ // attribution; the machine DO forwards only the daemon's existing
+ // `agent:model_switch` frame.
+ const forwardAgentModelSwitch = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-model-switch$/)
+ if (!forwardAgentModelSwitch || request.method !== "POST") return null
+
+ const machineId = decodeURIComponent(forwardAgentModelSwitch[1])
+ const reqLog = log.child({ traceId, machineId })
+ reqLog.debug("forwarding agent:model_switch to machine")
+
+ let payload: unknown
+ try {
+ payload = await request.json()
+ } catch {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (!payload || typeof payload !== "object") {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ const raw = payload as Record<string, unknown>
+ const allowedKeys = new Set(["agentId", "config", "launchId", "from", "to"])
+ for (const key of Object.keys(raw)) {
+ if (!allowedKeys.has(key)) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ }
+ const { agentId, config, launchId, from, to } = raw
+ if (typeof agentId !== "string" || agentId.length === 0) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (typeof launchId !== "string" || launchId.length === 0) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (!config || typeof config !== "object") {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if ((from !== null && typeof from !== "string") || (to !== null && typeof to !== "string")) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+
+ let doNames: string[] = []
+ try {
+ const shared = await import("@alook/shared")
+ const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
+ doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
+ } catch (err) {
+ reqLog.error("failed to resolve machine doNames for agent model switch", { err })
+ return Response.json({ error: "failed to resolve machine" }, { status: 503 })
+ }
+ if (doNames.length === 0) {
+ return Response.json({ sent: 0 })
+ }
+ const frame = JSON.stringify({ agentId, config, launchId, from, to })
+ let delivered = 0
+ let transientFailure = false
+ for (const dn of doNames) {
+ const doId = env.WS_DO.idFromName("community-machine:" + dn)
+ const stub = env.WS_DO.get(doId)
+ try {
+ const res = await stub.fetch(
+ new Request("http://internal/push-model-switch", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: frame,
+ }),
+ )
+ if (!res.ok) {
+ transientFailure = true
+ continue
+ }
+ const data = (await res.json()) as { sent?: unknown }
+ if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {
+ transientFailure = true
+ continue
+ }
+ delivered += data.sent
+ } catch {
+ transientFailure = true
+ }
+ }
+ if (delivered === 0 && transientFailure) {
+ return Response.json({ error: "failed to forward agent model switch" }, { status: 503 })
+ }
+ return Response.json({ sent: delivered })
+}
+
+export async function handleMachineProviderSwitch({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
+ const forwardAgentProviderSwitch = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-provider-switch$/)
+ if (!forwardAgentProviderSwitch || request.method !== "POST") return null
+
+ const machineId = decodeURIComponent(forwardAgentProviderSwitch[1])
+ const reqLog = log.child({ traceId, machineId })
+
+ let payload: unknown
+ try {
+ payload = await request.json()
+ } catch {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ if (!payload || typeof payload !== "object") {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ const raw = payload as Record<string, unknown>
+ const allowedKeys = new Set(["agentId", "config", "launchId", "from", "to"])
+ for (const key of Object.keys(raw)) {
+ if (!allowedKeys.has(key)) return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+ const { agentId, config, launchId, from, to } = raw
+ if (
+ typeof agentId !== "string" || agentId.length === 0 ||
+ typeof launchId !== "string" || launchId.length === 0 ||
+ !config || typeof config !== "object" ||
+ typeof from !== "string" || from.length === 0 ||
+ typeof to !== "string" || to.length === 0
+ ) {
+ return Response.json({ error: "invalid payload" }, { status: 400 })
+ }
+
+ let doNames: string[] = []
+ try {
+ const shared = await import("@alook/shared")
+ const db = shared.createDb((env as unknown as { DB: D1Database }).DB)
+ doNames = await queries.communityMachine.getActiveDoNamesForMachine(db, machineId)
+ } catch (err) {
+ reqLog.error("failed to resolve machine doNames for agent provider switch", { err })
+ return Response.json({ error: "failed to resolve machine" }, { status: 503 })
+ }
+ if (doNames.length === 0) return Response.json({ sent: 0 })
+
+ const frame = JSON.stringify({ agentId, config, launchId, from, to })
+ let delivered = 0
+ let transientFailure = false
+ for (const dn of doNames) {
+ const doId = env.WS_DO.idFromName("community-machine:" + dn)
+ const stub = env.WS_DO.get(doId)
+ try {
+ const res = await stub.fetch(new Request("http://internal/push-provider-switch", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: frame,
+ }))
+ if (!res.ok) {
+ transientFailure = true
+ continue
+ }
+ const data = (await res.json()) as { sent?: unknown }
+ if (typeof data.sent !== "number" || !Number.isFinite(data.sent) || data.sent < 0) {
+ transientFailure = true
+ continue
+ }
+ delivered += data.sent
+ } catch {
+ transientFailure = true
+ }
+ }
+ if (delivered === 0 && transientFailure) {
+ return Response.json({ error: "failed to forward agent provider switch" }, { status: 503 })
+ }
+ return Response.json({ sent: delivered })
+}
diff --git a/src/ws-do/src/routes/health.test.ts b/src/ws-do/src/routes/health.test.ts
new file mode 100644
index 000000000..6dc29466d
--- /dev/null
+++ b/src/ws-do/src/routes/health.test.ts
@@ -0,0 +1,54 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ createRouterTestContext,
+ loadRouter,
+ getSharedMocks,
+ type RouterHandler,
+ type RouterTestContext,
+} from "./test-harness"
+
+const sharedMocks = getSharedMocks()
+const mockHashCredential = sharedMocks.hashCredential
+const mockDoNameFromHash = sharedMocks.doNameFromHash
+const mockGetActiveDoNamesForMachine = sharedMocks.getActiveDoNamesForMachine
+const loggerMocks = {
+ child: sharedMocks.loggerChild,
+ debug: sharedMocks.loggerDebug,
+}
+
+describe("ws-do router", () => {
+ let handler: RouterHandler
+ let doMock: RouterTestContext["doMock"]
+ let rateLimitMock: RouterTestContext["rateLimitMock"]
+ let env: RouterTestContext["env"]
+
+ beforeEach(async () => {
+ vi.resetModules()
+ vi.clearAllMocks()
+ const context = createRouterTestContext()
+ doMock = context.doMock
+ rateLimitMock = context.rateLimitMock
+ env = context.env
+ handler = await loadRouter()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+ vi.resetModules()
+ doMock = undefined as unknown as RouterTestContext["doMock"]
+ rateLimitMock = undefined as unknown as RouterTestContext["rateLimitMock"]
+ env = undefined as unknown as RouterTestContext["env"]
+ handler = undefined as unknown as RouterHandler
+ })
+
+ describe("GET /health", () => {
+ it("returns the exact health response", async () => {
+ const res = await handler.fetch(new Request("http://localhost/health"), env as any)
+
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ status: "ok" })
+ })
+ })
+})
diff --git a/src/ws-do/src/routes/health.ts b/src/ws-do/src/routes/health.ts
new file mode 100644
index 000000000..1a9f9a470
--- /dev/null
+++ b/src/ws-do/src/routes/health.ts
@@ -0,0 +1,6 @@
+export function handleHealth(request: Request, url: URL): Response | null {
+ if (url.pathname === "/health" && request.method === "GET") {
+ return Response.json({ status: "ok" })
+ }
+ return null
+}
diff --git a/src/ws-do/src/routes/presence.test.ts b/src/ws-do/src/routes/presence.test.ts
new file mode 100644
index 000000000..4c43cd7c7
--- /dev/null
+++ b/src/ws-do/src/routes/presence.test.ts
@@ -0,0 +1,199 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ createRouterTestContext,
+ loadRouter,
+ getSharedMocks,
+ type RouterHandler,
+ type RouterTestContext,
+} from "./test-harness"
+
+const sharedMocks = getSharedMocks()
+const mockHashCredential = sharedMocks.hashCredential
+const mockDoNameFromHash = sharedMocks.doNameFromHash
+const mockGetActiveDoNamesForMachine = sharedMocks.getActiveDoNamesForMachine
+const loggerMocks = {
+ child: sharedMocks.loggerChild,
+ debug: sharedMocks.loggerDebug,
+}
+
+describe("ws-do router", () => {
+ let handler: RouterHandler
+ let doMock: RouterTestContext["doMock"]
+ let rateLimitMock: RouterTestContext["rateLimitMock"]
+ let env: RouterTestContext["env"]
+
+ beforeEach(async () => {
+ vi.resetModules()
+ vi.clearAllMocks()
+ const context = createRouterTestContext()
+ doMock = context.doMock
+ rateLimitMock = context.rateLimitMock
+ env = context.env
+ handler = await loadRouter()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+ vi.resetModules()
+ doMock = undefined as unknown as RouterTestContext["doMock"]
+ rateLimitMock = undefined as unknown as RouterTestContext["rateLimitMock"]
+ env = undefined as unknown as RouterTestContext["env"]
+ handler = undefined as unknown as RouterHandler
+ })
+
+ describe("POST /presence/users", () => {
+ it("empty ids array short-circuits and performs zero DO fetches", async () => {
+ const req = new Request("http://localhost/presence/users", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids: [] }),
+ })
+
+ const res = await handler.fetch(req, env as any)
+
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ online: [] })
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("returns only online ids from mixed responses", async () => {
+ doMock.stubFetch.mockImplementation((req: Request) => {
+ // Round-robin: we can't tell which id -- rely on call order.
+ const idx = doMock.stubFetch.mock.calls.length - 1
+ const online = idx % 2 === 0 // u1 online, u2 offline, u3 online
+ return Promise.resolve(new Response(JSON.stringify({ online }), { status: 200 }))
+ })
+
+ const req = new Request("http://localhost/presence/users", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids: ["u1", "u2", "u3"] }),
+ })
+
+ const res = await handler.fetch(req, env as any)
+ const body = await res.json() as { online: string[] }
+
+ expect(res.status).toBe(200)
+ expect(body.online.sort()).toEqual(["u1", "u3"])
+ })
+
+ it("returns empty online list when all ids are offline", async () => {
+ doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ online: false }), { status: 200 }))
+
+ const req = new Request("http://localhost/presence/users", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids: ["a", "b", "c"] }),
+ })
+
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ online: [] })
+ })
+
+ it("passes ?userId=<id> on every /check-user-online request — the target DO can't recover its own name from ctx (Fix 3)", async () => {
+ doMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ online: true }), { status: 200 }))
+
+ const req = new Request("http://localhost/presence/users", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids: ["bot-1", "human-2"] }),
+ })
+
+ await handler.fetch(req, env as any)
+
+ const urls = doMock.stubFetch.mock.calls.map(([r]) => (r as Request).url)
+ expect(urls).toContain("http://internal/check-user-online?userId=bot-1")
+ expect(urls).toContain("http://internal/check-user-online?userId=human-2")
+ })
+
+ it("returns 400 on malformed body — missing ids", async () => {
+ const req = new Request("http://localhost/presence/users", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({}),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ })
+
+ it("returns 400 on malformed body — ids is not an array", async () => {
+ const req = new Request("http://localhost/presence/users", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids: "u1" }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ })
+
+ it("returns 400 on malformed body — non-string entries", async () => {
+ const req = new Request("http://localhost/presence/users", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids: ["u1", 42, "u3"] }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ })
+
+ it("returns 400 on invalid JSON body", async () => {
+ const req = new Request("http://localhost/presence/users", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: "not json",
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ })
+
+ it("returns 400 when ids array exceeds cap", async () => {
+ const ids = Array.from({ length: 1001 }, (_, i) => `u${i}`)
+ const req = new Request("http://localhost/presence/users", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids }),
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(res.status).toBe(400)
+ })
+
+ it("tolerates a per-id DO fetch throwing — other ids still evaluated", async () => {
+ let call = 0
+ doMock.stubFetch.mockImplementation(() => {
+ call++
+ if (call === 1) return Promise.reject(new Error("boom"))
+ return Promise.resolve(new Response(JSON.stringify({ online: true }), { status: 200 }))
+ })
+
+ const req = new Request("http://localhost/presence/users", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids: ["u1", "u2", "u3"] }),
+ })
+ const res = await handler.fetch(req, env as any)
+ const body = await res.json() as { online: string[] }
+
+ expect(res.status).toBe(200)
+ expect(body.online.sort()).toEqual(["u2", "u3"])
+ })
+ })
+
+ describe("compat: GET /presence/user/:uid", () => {
+ it("still returns { online: boolean } (kept for rollout safety)", async () => {
+ doMock.stubFetch.mockResolvedValue(
+ new Response(JSON.stringify({ online: true }), { status: 200 })
+ )
+ const req = new Request("http://localhost/presence/user/user-789", { method: "GET" })
+ const res = await handler.fetch(req, env as any)
+
+ expect(doMock.idFromName).toHaveBeenCalledWith("user:user-789")
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ online: true })
+ const stubReq = doMock.stubFetch.mock.calls[0][0] as Request
+ expect(stubReq.url).toBe("http://internal/check-user-online?userId=user-789")
+ })
+ })
+})
diff --git a/src/ws-do/src/routes/presence.ts b/src/ws-do/src/routes/presence.ts
new file mode 100644
index 000000000..bf14259bb
--- /dev/null
+++ b/src/ws-do/src/routes/presence.ts
@@ -0,0 +1,62 @@
+import type { RouterContext } from "../router-context"
+
+export async function handleBatchPresence({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
+ // Bulk presence: fan out one DO fetch per id and return the online subset.
+ // Consolidates web-worker subrequest budget to a single call regardless of
+ // membership size.
+ if (url.pathname !== "/presence/users" || request.method !== "POST") return null
+
+ let body: unknown
+ try {
+ body = await request.json()
+ } catch {
+ return new Response("invalid json", { status: 400 })
+ }
+ const ids = (body as { ids?: unknown })?.ids
+ if (!Array.isArray(ids)) return new Response("ids must be an array", { status: 400 })
+ if (ids.length > 1000) return new Response("too many ids", { status: 400 })
+ if (!ids.every((id): id is string => typeof id === "string")) {
+ return new Response("ids must be strings", { status: 400 })
+ }
+
+ const reqLog = log.child({ traceId, count: ids.length })
+ reqLog.debug("bulk presence check")
+
+ if (ids.length === 0) return Response.json({ online: [] })
+
+ const results = await Promise.allSettled(
+ ids.map((id) => {
+ const doId = env.WS_DO.idFromName("user:" + id)
+ const stub = env.WS_DO.get(doId)
+ return stub.fetch(
+ new Request(`http://internal/check-user-online?userId=${encodeURIComponent(id)}`),
+ )
+ }),
+ )
+ const online: string[] = []
+ for (let i = 0; i < results.length; i++) {
+ const r = results[i]
+ if (r.status !== "fulfilled" || !r.value.ok) continue
+ try {
+ const data = await r.value.json() as { online?: boolean; stale?: boolean }
+ // Skip stale responses — a fail-closed `online:false` from D1 must
+ // not be surfaced as authoritative offline to fan-out callers.
+ if (data.stale) continue
+ if (data.online) online.push(ids[i])
+ } catch { /* skip */ }
+ }
+ return Response.json({ online })
+}
+
+export async function handleSinglePresence({ request, env, url }: RouterContext): Promise<Response | null> {
+ // Per-user presence — dead in-tree, kept for rollout safety.
+ const presenceCheck = url.pathname.match(/^\/presence\/user\/(.+)$/)
+ if (!presenceCheck || request.method !== "GET") return null
+
+ const uid = presenceCheck[1]
+ const doId = env.WS_DO.idFromName("user:" + uid)
+ const stub = env.WS_DO.get(doId)
+ return stub.fetch(
+ new Request(`http://internal/check-user-online?userId=${encodeURIComponent(uid)}`),
+ )
+}
diff --git a/src/ws-do/src/routes/rate-limit.test.ts b/src/ws-do/src/routes/rate-limit.test.ts
new file mode 100644
index 000000000..77e5ecddb
--- /dev/null
+++ b/src/ws-do/src/routes/rate-limit.test.ts
@@ -0,0 +1,103 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ createRouterTestContext,
+ loadRouter,
+ getSharedMocks,
+ type RouterHandler,
+ type RouterTestContext,
+} from "./test-harness"
+
+const sharedMocks = getSharedMocks()
+const mockHashCredential = sharedMocks.hashCredential
+const mockDoNameFromHash = sharedMocks.doNameFromHash
+const mockGetActiveDoNamesForMachine = sharedMocks.getActiveDoNamesForMachine
+const loggerMocks = {
+ child: sharedMocks.loggerChild,
+ debug: sharedMocks.loggerDebug,
+}
+
+describe("ws-do router", () => {
+ let handler: RouterHandler
+ let doMock: RouterTestContext["doMock"]
+ let rateLimitMock: RouterTestContext["rateLimitMock"]
+ let env: RouterTestContext["env"]
+
+ beforeEach(async () => {
+ vi.resetModules()
+ vi.clearAllMocks()
+ const context = createRouterTestContext()
+ doMock = context.doMock
+ rateLimitMock = context.rateLimitMock
+ env = context.env
+ handler = await loadRouter()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+ vi.resetModules()
+ doMock = undefined as unknown as RouterTestContext["doMock"]
+ rateLimitMock = undefined as unknown as RouterTestContext["rateLimitMock"]
+ env = undefined as unknown as RouterTestContext["env"]
+ handler = undefined as unknown as RouterHandler
+ })
+
+ describe("POST /rate-limit/check", () => {
+ it("returns the exact invalid-json response", async () => {
+ const res = await handler.fetch(new Request("http://localhost/rate-limit/check", {
+ method: "POST",
+ body: "not-json",
+ }), env as any)
+
+ expect(res.status).toBe(400)
+ expect(await res.text()).toBe("invalid json")
+ expect(rateLimitMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("requires a non-empty name", async () => {
+ const res = await handler.fetch(new Request("http://localhost/rate-limit/check", {
+ method: "POST",
+ body: JSON.stringify({ key: "user-1", windowMs: 1_000, max: 2 }),
+ }), env as any)
+
+ expect(res.status).toBe(400)
+ expect(await res.text()).toBe("name required")
+ expect(rateLimitMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("requires a non-empty key", async () => {
+ const res = await handler.fetch(new Request("http://localhost/rate-limit/check", {
+ method: "POST",
+ body: JSON.stringify({ name: "message", key: "", windowMs: 1_000, max: 2 }),
+ }), env as any)
+
+ expect(res.status).toBe(400)
+ expect(await res.text()).toBe("key required")
+ expect(rateLimitMock.stubFetch).not.toHaveBeenCalled()
+ })
+
+ it("targets the exact limiter DO and preserves the internal request contract", async () => {
+ rateLimitMock.stubFetch.mockResolvedValue(new Response(JSON.stringify({ allowed: true }), {
+ status: 201,
+ headers: { "x-rate-limit": "ok" },
+ }))
+ const res = await handler.fetch(new Request("http://localhost/rate-limit/check", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ name: "message", key: "user-1", windowMs: 12_345, max: 7 }),
+ }), env as any)
+
+ expect(rateLimitMock.idFromName).toHaveBeenCalledWith("message:user-1")
+ expect(rateLimitMock.get).toHaveBeenCalledWith("mock-do-id")
+ const internal = rateLimitMock.stubFetch.mock.calls[0][0] as Request
+ expect(internal.url).toBe("http://internal/check")
+ expect(internal.method).toBe("POST")
+ expect(internal.headers.get("content-type")).toBe("application/json")
+ expect(await internal.json()).toEqual({ windowMs: 12_345, max: 7 })
+ expect(res.status).toBe(201)
+ expect(res.headers.get("x-rate-limit")).toBe("ok")
+ expect(await res.json()).toEqual({ allowed: true })
+ })
+ })
+})
diff --git a/src/ws-do/src/routes/rate-limit.ts b/src/ws-do/src/routes/rate-limit.ts
new file mode 100644
index 000000000..def287f00
--- /dev/null
+++ b/src/ws-do/src/routes/rate-limit.ts
@@ -0,0 +1,43 @@
+export async function handleRateLimit(
+ request: Request,
+ env: Env,
+ url: URL,
+): Promise<Response | null> {
+ // Strongly-consistent, parameterized rate limiter. Every rate-limit
+ // call site (community message send, auth OTP, future policies) hits
+ // this single endpoint with a `{ name, key, windowMs, max }` payload
+ // — one DO instance per (name, key) pair. Policy values come from the
+ // shared `RATE_LIMITS` registry in `src/shared/src/lib/rate-limits.ts`
+ // so ceilings live in one place, not scattered across route handlers.
+ //
+ // See `rate-limit-do.ts` for the counter logic.
+ if (url.pathname !== "/rate-limit/check" || request.method !== "POST") return null
+
+ let body: unknown
+ try {
+ body = await request.json()
+ } catch {
+ return new Response("invalid json", { status: 400 })
+ }
+ const { name, key, windowMs, max } = (body ?? {}) as {
+ name?: unknown
+ key?: unknown
+ windowMs?: unknown
+ max?: unknown
+ }
+ if (typeof name !== "string" || name.length === 0) {
+ return new Response("name required", { status: 400 })
+ }
+ if (typeof key !== "string" || key.length === 0) {
+ return new Response("key required", { status: 400 })
+ }
+ const doId = env.RATE_LIMIT_DO.idFromName(name + ":" + key)
+ const stub = env.RATE_LIMIT_DO.get(doId)
+ return stub.fetch(
+ new Request("http://internal/check", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ windowMs, max }),
+ }),
+ )
+}
diff --git a/src/ws-do/src/routes/test-harness.ts b/src/ws-do/src/routes/test-harness.ts
new file mode 100644
index 000000000..6673cadfb
--- /dev/null
+++ b/src/ws-do/src/routes/test-harness.ts
@@ -0,0 +1,76 @@
+import { vi } from "vitest"
+import { createMockDONamespace } from "../__mocks__/cf"
+
+vi.mock("../ws-durable", () => ({
+ WebSocketDurableObject: class { },
+}))
+vi.mock("../rate-limit-do", () => ({
+ RateLimitDurableObject: class { },
+}))
+
+const sharedMocks = vi.hoisted(() => {
+ const hashCredential = vi.fn(async (bearer: string) => `sha256:${bearer}`)
+ const doNameFromHash = vi.fn((hash: string) => hash.slice(0, 32))
+ const getActiveDoNamesForMachine = vi.fn(async (_db: unknown, _machineId: string) => [] as string[])
+ const debug = vi.fn()
+ const info = vi.fn()
+ const warn = vi.fn()
+ const error = vi.fn()
+ const logger: Record<string, unknown> = { debug, info, warn, error }
+ const child = vi.fn(() => logger)
+ logger.child = child
+ return {
+ hashCredential,
+ doNameFromHash,
+ getActiveDoNamesForMachine,
+ logger,
+ loggerChild: child,
+ loggerDebug: debug,
+ loggerInfo: info,
+ loggerWarn: warn,
+ loggerError: error,
+ }
+})
+
+vi.mock("@alook/shared", () => ({
+ WS_EVENTS: {
+ BOT_AUDIT_EVENT: "community:bot.audit_event",
+ },
+ createDb: () => ({}),
+ createLogger: () => sharedMocks.logger,
+ queries: {
+ communityMachine: {
+ hashCredential: (bearer: string) => sharedMocks.hashCredential(bearer),
+ doNameFromHash: (hash: string) => sharedMocks.doNameFromHash(hash),
+ getActiveDoNamesForMachine: (db: unknown, machineId: string) => (
+ sharedMocks.getActiveDoNamesForMachine(db, machineId)
+ ),
+ },
+ },
+}))
+
+export interface RouterTestContext {
+ doMock: ReturnType<typeof createMockDONamespace>
+ rateLimitMock: ReturnType<typeof createMockDONamespace>
+ env: { WS_DO: DurableObjectNamespace; RATE_LIMIT_DO: DurableObjectNamespace }
+}
+
+export type RouterHandler = (typeof import("../index"))["default"]
+
+export function getSharedMocks(): typeof sharedMocks {
+ return sharedMocks
+}
+
+export function createRouterTestContext(): RouterTestContext {
+ const doMock = createMockDONamespace()
+ const rateLimitMock = createMockDONamespace()
+ const env = {
+ WS_DO: doMock.namespace,
+ RATE_LIMIT_DO: rateLimitMock.namespace,
+ } as unknown as RouterTestContext["env"]
+ return { doMock, rateLimitMock, env }
+}
+
+export async function loadRouter(): Promise<RouterHandler> {
+ return (await import("../index")).default
+}
diff --git a/src/ws-do/src/routes/upgrade.test.ts b/src/ws-do/src/routes/upgrade.test.ts
new file mode 100644
index 000000000..9dd4c0691
--- /dev/null
+++ b/src/ws-do/src/routes/upgrade.test.ts
@@ -0,0 +1,146 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ createRouterTestContext,
+ loadRouter,
+ getSharedMocks,
+ type RouterHandler,
+ type RouterTestContext,
+} from "./test-harness"
+
+const sharedMocks = getSharedMocks()
+const mockHashCredential = sharedMocks.hashCredential
+const mockDoNameFromHash = sharedMocks.doNameFromHash
+const mockGetActiveDoNamesForMachine = sharedMocks.getActiveDoNamesForMachine
+const loggerMocks = {
+ child: sharedMocks.loggerChild,
+ debug: sharedMocks.loggerDebug,
+}
+
+describe("ws-do router", () => {
+ let handler: RouterHandler
+ let doMock: RouterTestContext["doMock"]
+ let rateLimitMock: RouterTestContext["rateLimitMock"]
+ let env: RouterTestContext["env"]
+
+ beforeEach(async () => {
+ vi.resetModules()
+ vi.clearAllMocks()
+ const context = createRouterTestContext()
+ doMock = context.doMock
+ rateLimitMock = context.rateLimitMock
+ env = context.env
+ handler = await loadRouter()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+ vi.resetModules()
+ doMock = undefined as unknown as RouterTestContext["doMock"]
+ rateLimitMock = undefined as unknown as RouterTestContext["rateLimitMock"]
+ env = undefined as unknown as RouterTestContext["env"]
+ handler = undefined as unknown as RouterHandler
+ })
+
+ describe("WebSocket route", () => {
+ it("prioritizes community-machine Bearer auth over daemonId and userId", async () => {
+ mockHashCredential.mockResolvedValue("f".repeat(64))
+ mockDoNameFromHash.mockReturnValue("f".repeat(32))
+ doMock.stubFetch.mockResolvedValue(new Response(null, { status: 200 }))
+ const req = new Request("http://localhost/?daemonId=daemon-1&userId=user-1", {
+ headers: { Upgrade: "websocket", Authorization: "Bearer cmk_priority" },
+ })
+
+ const res = await handler.fetch(req, env as any)
+
+ expect(mockHashCredential).toHaveBeenCalledWith("cmk_priority")
+ expect(doMock.idFromName).toHaveBeenCalledTimes(1)
+ expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:" + "f".repeat(32))
+ expect(doMock.stubFetch).toHaveBeenCalledWith(req)
+ expect(res.status).toBe(200)
+ })
+
+ it("prioritizes daemonId over userId when no community-machine bearer is present", async () => {
+ doMock.stubFetch.mockResolvedValue(new Response(null, { status: 200 }))
+ const req = new Request("http://localhost/?daemonId=daemon-1&userId=user-1", {
+ headers: { Upgrade: "websocket" },
+ })
+
+ const res = await handler.fetch(req, env as any)
+
+ expect(mockHashCredential).not.toHaveBeenCalled()
+ expect(doMock.idFromName).toHaveBeenCalledTimes(1)
+ expect(doMock.idFromName).toHaveBeenCalledWith("daemon:daemon-1")
+ expect(doMock.stubFetch).toHaveBeenCalledWith(req)
+ expect(res.status).toBe(200)
+ })
+
+ it("forwards GET with userId param to DO instance", async () => {
+ doMock.stubFetch.mockResolvedValue(new Response(null, { status: 200 }))
+ const req = new Request("http://localhost/?userId=user-456", {
+ headers: { Upgrade: "websocket" },
+ })
+
+ const res = await handler.fetch(req, env as any)
+
+ expect(doMock.idFromName).toHaveBeenCalledWith("user:user-456")
+ expect(doMock.get).toHaveBeenCalledWith("mock-do-id")
+ expect(doMock.stubFetch).toHaveBeenCalledWith(req)
+ })
+
+ it("returns 400 when userId is missing", async () => {
+ const req = new Request("http://localhost/", {
+ headers: { Upgrade: "websocket" },
+ })
+
+ const res = await handler.fetch(req, env as any)
+
+ expect(res.status).toBe(400)
+ expect(await res.text()).toBe("userId required")
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ })
+ })
+
+ describe("community-machine Bearer auth", () => {
+ beforeEach(() => {
+ mockHashCredential.mockClear()
+ mockDoNameFromHash.mockClear()
+ })
+
+ it("names DO from sha256(bearer).slice(0,32) with zero D1 reads", async () => {
+ mockHashCredential.mockResolvedValue("0".repeat(32) + "1".repeat(32))
+ mockDoNameFromHash.mockReturnValue("0".repeat(32))
+ doMock.stubFetch.mockResolvedValue(new Response(null, { status: 200 }))
+ const req = new Request("http://localhost/", {
+ headers: { Upgrade: "websocket", Authorization: "Bearer cmk_abc" },
+ })
+ const res = await handler.fetch(req, env as any)
+ expect(mockHashCredential).toHaveBeenCalledWith("cmk_abc")
+ expect(doMock.idFromName).toHaveBeenCalledWith("community-machine:" + "0".repeat(32))
+ expect(res.status).toBe(200)
+ })
+
+ it("returns 400 for legacy ?token=cmt_ requests (no 426, no body)", async () => {
+ const req = new Request("http://localhost/?token=cmt_legacy", {
+ headers: { Upgrade: "websocket" },
+ })
+ const res = await handler.fetch(req, env as any)
+ // The 426 legacy branch was deleted; the request falls through to the
+ // "no userId" branch, which 400s.
+ expect(res.status).toBe(400)
+ expect(doMock.get).not.toHaveBeenCalled()
+ })
+
+ it("routes missing Authorization without cmk_ to the default handler (no auth path)", async () => {
+ const req = new Request("http://localhost/", {
+ headers: { Upgrade: "websocket" },
+ })
+ const res = await handler.fetch(req, env as any)
+ // No userId → 400 (existing default). We assert we do NOT hit the
+ // credential-hash path or touch a DO under community-machine:*.
+ expect(mockHashCredential).not.toHaveBeenCalled()
+ expect(res.status).toBe(400)
+ })
+ })
+})
diff --git a/src/ws-do/src/routes/upgrade.ts b/src/ws-do/src/routes/upgrade.ts
new file mode 100644
index 000000000..f16539cff
--- /dev/null
+++ b/src/ws-do/src/routes/upgrade.ts
@@ -0,0 +1,39 @@
+import { queries } from "@alook/shared"
+import type { RouterContext } from "../router-context"
+
+export async function handleUpgrade({ request, env, url, traceId, log }: RouterContext): Promise<Response> {
+ // Community-machine daemon WS upgrade — Bearer cmk_<credential> only.
+ // Router names the DO from `sha256(bearer).slice(0,32)` without hitting
+ // D1; the DO re-validates the full hash authoritatively on first accept.
+ const authHeader = request.headers.get("Authorization")
+ if (authHeader?.startsWith("Bearer cmk_")) {
+ const bearer = authHeader.slice(7).trim()
+ const hash = await queries.communityMachine.hashCredential(bearer)
+ const doName = queries.communityMachine.doNameFromHash(hash)
+ const reqLog = log.child({ traceId })
+ reqLog.info("community machine websocket upgrade")
+ const doId = env.WS_DO.idFromName("community-machine:" + doName)
+ const stub = env.WS_DO.get(doId)
+ return stub.fetch(request)
+ }
+
+ const daemonId = url.searchParams.get("daemonId")
+ if (daemonId) {
+ const reqLog = log.child({ traceId, daemonId })
+ reqLog.info("daemon websocket upgrade")
+
+ const doId = env.WS_DO.idFromName("daemon:" + daemonId)
+ const stub = env.WS_DO.get(doId)
+ return stub.fetch(request)
+ }
+
+ const userId = url.searchParams.get("userId")
+ if (!userId) return new Response("userId required", { status: 400 })
+
+ const reqLog = log.child({ traceId, userId })
+ reqLog.info("websocket upgrade")
+
+ const doId = env.WS_DO.idFromName("user:" + userId)
+ const stub = env.WS_DO.get(doId)
+ return stub.fetch(request)
+}
diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.ts
index ee636c3ea..da6f16b3a 100644
--- a/src/ws-do/src/ws-durable.test.ts
+++ b/src/ws-do/src/ws-durable.test.ts
@@ -1,2549 +1,20 @@
-import { describe, it, expect, vi, beforeEach } from "vitest"
-import { createMockCtx, createMockWebSocket } from "./__mocks__/cf"
+import { afterEach, beforeEach, describe, expect, it } from "vitest"
+import { createMockWebSocket } from "./__mocks__/cf"
+import {
+ cleanupHarness,
+ createDO,
+ mockGetBotBinding,
+ mockLogWarn,
+ mockUpdateProfile,
+ resetHarness,
+} from "./ws-durable/test-harness"
-// --- Cloudflare Workers globals that don't exist in Node ---
-
-// Replace the global Response with one that allows status 101 and a webSocket property
-class CFResponse {
- status: number
- webSocket: unknown
- private _body: BodyInit | null
- private _headers: Headers
-
- constructor(body: BodyInit | null = null, init: ResponseInit & { webSocket?: unknown } = {}) {
- this._body = body
- this._headers = new Headers(init.headers)
- this.status = init.status ?? 200
- this.webSocket = (init as { webSocket?: unknown }).webSocket
- }
-
- async text(): Promise<string> {
- if (this._body == null) return ""
- if (typeof this._body === "string") return this._body
- return ""
- }
-
- async json(): Promise<unknown> {
- return JSON.parse(await this.text())
- }
-
- get headers() { return this._headers }
-}
-
-globalThis.Response = CFResponse as unknown as typeof Response
-
-// WebSocketPair — creates a paired (client, server) mock
-globalThis.WebSocketPair = class {
- 0: ReturnType<typeof createMockWebSocket>
- 1: ReturnType<typeof createMockWebSocket>
- constructor() {
- this[0] = createMockWebSocket()
- this[1] = createMockWebSocket()
- }
-} as unknown as typeof WebSocketPair
-
-// WebSocketRequestResponsePair — used for the ping/pong auto-response
-globalThis.WebSocketRequestResponsePair = class {
- constructor(public request: string, public response: string) { }
-} as unknown as typeof WebSocketRequestResponsePair
-
-// --- Module mocks ---
-
-// Mock cloudflare:workers DurableObject base class
-vi.mock("cloudflare:workers", () => ({
- DurableObject: class {
- ctx: unknown
- env: unknown
- constructor(ctx: unknown, env: unknown) {
- this.ctx = ctx
- this.env = env
- }
- },
-}))
-
-// Mock @alook/shared
-const mockGetValidSession = vi.fn<(db: unknown, token: string) => Promise<string | null>>()
-const mockGetValidSessionWithIdentity = vi.fn<(db: unknown, token: string) => Promise<{ userId: string; name: string; discriminator: string } | null>>()
-const mockGetMachineTokenByToken = vi.fn()
-const mockGetLatestTokenForUser = vi.fn()
-const mockGetRuntimeIdsByDaemon = vi.fn()
-const mockGetMachineByDaemon = vi.fn().mockResolvedValue({ daemonId: "my-daemon", workspaceId: "sp_ws1" })
-const mockCreateDb = vi.fn().mockReturnValue({})
-const mockHashCredential = vi.fn(async (bearer: string) => `hash:${bearer}`)
-const mockFindCredentialByHash = vi.fn()
-const mockGetMachineByIdForUser = vi.fn()
-const mockUpsertMachineByMachineId = vi.fn()
-const mockTouchMachineHeartbeat = vi.fn()
-const mockMarkMachineOffline = vi.fn()
-const mockMarkMachineOnlineIfOffline = vi.fn()
-const mockGetCoMemberUserIds = vi.fn<(db: unknown, userId: string) => Promise<string[]>>().mockResolvedValue([])
-const mockGetFriendUserIds = vi.fn<(db: unknown, userId: string) => Promise<string[]>>().mockResolvedValue([])
-const mockGetChannelForMember = vi.fn()
-const mockListChannelMemberUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])
-const mockIsChannelPrivate = vi.fn<(db: unknown, channelId: string) => Promise<boolean>>().mockResolvedValue(false)
-const mockGetPrivateChannelAudienceUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])
-const mockResolveScopeMemberUserIds = vi.fn<(db: unknown, opts: { scope: string; scopeId: string }) => Promise<string[]>>().mockResolvedValue([])
-// Default: non-thread channel → typing uses the shared resolver path.
-const mockGetChannelType = vi.fn<(db: unknown, channelId: string) => Promise<string | null>>().mockResolvedValue("text")
-const mockListThreadParticipantUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])
-const mockGetDM = vi.fn()
-const mockListMembers = vi.fn()
-const mockListBotsForMachine = vi.fn<(db: unknown, machineId: string) => Promise<Array<{ id: string; name: string; discriminator: string; description: string }>>>().mockResolvedValue([])
-const mockIsBotOnline = vi.fn<(db: unknown, botUserId: string) => Promise<boolean>>().mockResolvedValue(false)
-const mockGetBotBinding = vi.fn<(db: unknown, botId: string) => Promise<{ machineId: string; runtime: string } | null>>().mockResolvedValue(null)
-const mockGetBotBindingWithOwner = vi.fn<(db: unknown, botId: string) => Promise<{ machineId: string; runtime: string; ownerUserId: string; name: string; discriminator: string } | null>>().mockResolvedValue(null)
-const mockInsertBotActivityEventAndPrune = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
-const mockInsertBotAuditSessionReset = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
-const mockInsertBotAuditNap = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
-const mockInsertBotAuditModelChanged = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
-const mockInsertBotAuditProviderChanged = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
-const mockTouchBotRefreshContext = vi.fn<(db: unknown, botId: string, now: string) => Promise<void>>().mockResolvedValue(undefined)
-const mockUpdateProfile = vi
- .fn<(db: unknown, userId: string, data: { statusEmoji?: string | null; statusText?: string | null }) => Promise<unknown>>()
- .mockResolvedValue({})
-const mockGetProfile = vi
- .fn<(db: unknown, userId: string) => Promise<{ statusEmoji: string | null; statusText: string | null } | null>>()
- .mockResolvedValue(null)
-const mockReconcileBotActivityFromRunningAgents = vi
- .fn<(db: unknown, machineId: string, runningAgentIds: string[]) => Promise<Array<{ botUserId: string; statusEmoji: string; statusText: string }>>>()
- .mockResolvedValue([])
-const mockGetUserInternal = vi.fn<(db: unknown, id: string) => Promise<{ isBot: boolean; ownerUserId: string | null } | null>>().mockResolvedValue(null)
-// mockToSummary now returns row.status verbatim — status is the source of
-// truth on the column, not a derivation from lastSeenAt. See
-// plans/community-machine-presence-fix.md.
-const mockToSummary = vi.fn((row: any) => ({
- id: row.id,
- hostname: row.hostname ?? "",
- displayName: row.displayName ?? row.hostname ?? "",
- platform: row.platform ?? "",
- arch: row.arch ?? "",
- osRelease: row.osRelease ?? "",
- daemonVersion: row.daemonVersion ?? "",
- lastSeenAt: row.lastSeenAt ?? null,
- status: (row.status as "online" | "offline") ?? "offline",
- availableRuntimes: row.availableRuntimes ?? [],
- createdAt: row.createdAt ?? "",
- updatedAt: row.updatedAt ?? "",
-}))
-
-vi.mock("@alook/shared", () => {
- const noopLogger = {
- debug: () => { },
- info: () => { },
- warn: () => { },
- error: () => { },
- child: () => noopLogger,
- }
- // Bare-minimum safeParse stubs — the DO only calls `.safeParse(msg)` and
- // reads `.success` / `.data`. Enough to route the test frames correctly
- // without pulling in zod (which isn't a direct dep of @alook/ws-do).
- const SessionErrorFrameSchema = {
- safeParse(v: unknown) {
- const m = v as { type?: unknown; code?: unknown; agentId?: unknown; launchId?: unknown; payload?: unknown }
- if (m?.type !== "session.error" || m?.code !== "runtime_not_available") {
- return { success: false } as const
- }
- return {
- success: true as const,
- data: {
- type: "session.error" as const,
- code: "runtime_not_available" as const,
- agentId: typeof m.agentId === "string" ? (m.agentId as string) : undefined,
- // launchId rides the frame now (Melisa's source half) — the DO uses
- // it to evict pending reset/nap attribution on cold-start branch A.
- launchId: typeof m.launchId === "string" ? (m.launchId as string) : undefined,
- payload: (m.payload as Record<string, unknown> | undefined) ?? undefined,
- },
- }
- },
- }
- // Mirror the shared HostReadyMessageSchema: the daemon's ready frame must be
- // FLAT (fields at top level), not wrapped in a `ready` key. A wrapped frame
- // is rejected — regression guard against the wire-shape mismatch we hit
- // when the daemon sent `{type:"ready", ready:{...}}` while the DO expected
- // flat top-level fields.
- const HostReadyMessageSchema = {
- safeParse(v: unknown) {
- const m = v as { type?: unknown; runtimeReport?: unknown; runningAgents?: unknown }
- if (m?.type !== "ready") return { success: false } as const
- if (!Array.isArray(m?.runtimeReport)) return { success: false } as const
- const data: Record<string, unknown> = {
- type: "ready",
- runtimeReport: m.runtimeReport,
- runningAgents: Array.isArray(m.runningAgents) ? m.runningAgents : [],
- }
- for (const k of ["hostname", "platform", "arch", "osRelease", "daemonVersion"]) {
- const val = (m as Record<string, unknown>)[k]
- if (typeof val === "string") data[k] = val
- }
- return { success: true as const, data }
- },
- }
- const AgentActivityMessageSchema = {
- safeParse(v: unknown) {
- const m = v as { type?: unknown; agentId?: unknown; state?: unknown }
- if (m?.type !== "agent_activity") return { success: false } as const
- if (typeof m.agentId !== "string") return { success: false } as const
- if (!["idle", "starting", "running", "stopping"].includes(m.state as string)) return { success: false } as const
- return { success: true as const, data: { type: "agent_activity" as const, agentId: m.agentId, state: m.state } }
- },
- }
- const AgentTypingMessageSchema = {
- safeParse(v: unknown) {
- const m = v as { type?: unknown; agentId?: unknown; channelId?: unknown }
- if (m?.type !== "agent_typing") return { success: false } as const
- if (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const
- if (typeof m.channelId !== "string" || m.channelId.length === 0) return { success: false } as const
- return {
- success: true as const,
- data: { type: "agent_typing" as const, agentId: m.agentId, channelId: m.channelId },
- }
- },
- }
- const AgentTypingStopMessageSchema = {
- safeParse(v: unknown) {
- const m = v as { type?: unknown; agentId?: unknown; channelId?: unknown }
- if (m?.type !== "agent_typing_stop") return { success: false } as const
- if (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const
- if (typeof m.channelId !== "string" || m.channelId.length === 0) return { success: false } as const
- return {
- success: true as const,
- data: { type: "agent_typing_stop" as const, agentId: m.agentId, channelId: m.channelId },
- }
- },
- }
- const AgentSessionMessageSchema = {
- safeParse(v: unknown) {
- const m = v as { type?: unknown; agentId?: unknown; sessionId?: unknown; launchId?: unknown }
- if (m?.type !== "agent_session") return { success: false } as const
- if (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const
- if (typeof m.sessionId !== "string" || m.sessionId.length === 0) return { success: false } as const
- if (typeof m.launchId !== "string" || m.launchId.length === 0) return { success: false } as const
- return {
- success: true as const,
- data: {
- type: "agent_session" as const,
- agentId: m.agentId,
- sessionId: m.sessionId,
- launchId: m.launchId,
- },
- }
- },
- }
- const HostBotAuditEventFrameSchema = {
- safeParse(v: unknown) {
- const m = v as { type?: unknown; agentId?: unknown; sessionId?: unknown; launchId?: unknown; event?: unknown }
- if (m?.type !== "bot_audit_event") return { success: false } as const
- if (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const
- const ev = m.event as { kind?: unknown; payload?: unknown }
- if (!ev || typeof ev !== "object") return { success: false } as const
- const kind = ev.kind
- const payload = ev.payload as Record<string, unknown> | undefined
- if (!payload || typeof payload !== "object") return { success: false } as const
- let ok = false
- if (kind === "cli_invocation") ok = typeof payload.subcommand === "string"
- else if (kind === "tool_call") ok = typeof payload.name === "string"
- else if (kind === "thinking")
- ok = typeof payload.text === "string" && typeof payload.truncated === "boolean" && typeof payload.chars === "number"
- if (!ok) return { success: false } as const
- return {
- success: true as const,
- data: {
- type: "bot_audit_event" as const,
- agentId: m.agentId,
- sessionId: typeof m.sessionId === "string" ? m.sessionId : m.sessionId === null ? null : undefined,
- launchId: typeof m.launchId === "string" ? m.launchId : m.launchId === null ? null : undefined,
- event: { kind, payload },
- },
- }
- },
- }
- return {
- // Real WS event-type strings the DO reads at runtime (#5 T2 — ws-do
- // broadcasts now use WS_EVENTS.* instead of raw literals). Values match
- // @alook/shared so the tests' `type: "community:*"` assertions still hold.
- WS_EVENTS: {
- TYPING_START: "community:typing.start",
- TYPING_STOP: "community:typing.stop",
- MACHINE_STATUS: "community:machine.status",
- MACHINE_UPDATED: "community:machine.updated",
- STATUS_UPDATE: "community:status.update",
- BOT_AUDIT_EVENT: "community:bot.audit_event",
- PRESENCE_UPDATE: "community:presence.update",
- },
- createDb: (d1: unknown) => mockCreateDb(d1),
- createLogger: () => noopLogger,
- withD1Retry: async <T>(fn: () => Promise<T>): Promise<T> => fn(),
- // Real reach-trait impls — fanOutTyping's recipient split dispatches on
- // channelReach (B2 reach axis single source) to route a thread to the
- // participant set, a dm to its members, else the access audience. Mirror
- // the real CHANNEL_TRAITS reach values + the stored-type guard.
- channelReach: (t: string) =>
- t === "thread"
- ? "participant-set"
- : t === "dm"
- ? "dm-pair"
- : "server-or-roster",
- isStoredChannelType: (t: unknown) =>
- t === "text" || t === "forum" || t === "thread" || t === "dm",
- // Minimal `readOrStale` shim — bypasses the classifier so tests can
- // inject arbitrary Error shapes at the query-fn boundary and observe
- // fail-closed semantics. Real production behavior (retry then fallback)
- // is covered by the shared `resilience.test.ts` suite.
- readOrStale: async <T>(
- fn: () => Promise<T>,
- fallback: T,
- _opts?: unknown,
- ): Promise<{ value: T; stale: boolean }> => {
- try { return { value: await fn(), stale: false } }
- catch { return { value: fallback, stale: true } }
- },
- COMMUNITY_MACHINE_HEARTBEAT_MS: 60_000,
- COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS: 120_000,
- SessionErrorFrameSchema,
- HostReadyMessageSchema,
- AgentActivityMessageSchema,
- AgentTypingMessageSchema,
- AgentTypingStopMessageSchema,
- AgentSessionMessageSchema,
- HostBotAuditEventFrameSchema,
- // Deterministic preset picker so the assertion can pin exact
- // `statusEmoji`/`statusText` values regardless of the injected `seed`.
- pickBotActivityPreset: (state: string) => {
- if (state === "running") return { emoji: "⚡", text: "Working on it" }
- if (state === "starting") return { emoji: "🌀", text: "Waking up" }
- if (state === "stopping") return { emoji: "🌙", text: "Wrapping up" }
- return { emoji: "💤", text: "Idle" }
- },
- RUNNING_PRESETS: [
- { emoji: "⚡", text: "Working on it" },
- { emoji: "🛠️", text: "Cooking" },
- { emoji: "🧠", text: "Thinking hard" },
- { emoji: "🔧", text: "Tinkering" },
- { emoji: "🚀", text: "On it" },
- { emoji: "🔥", text: "In the zone" },
- ],
- // Real impl of the write-path/reconciler guard — mirrors the shared module
- // over the presets emitted above (idle/starting/stopping + running pool).
- isBotActivityStatus: (emoji: string | null, text: string | null) => {
- if (emoji === null && text === null) return false
- const pairs = [
- { emoji: "💤", text: "Idle" },
- { emoji: "🌀", text: "Waking up" },
- { emoji: "🌙", text: "Wrapping up" },
- { emoji: "⚡", text: "Working on it" },
- { emoji: "🛠️", text: "Cooking" },
- { emoji: "🧠", text: "Thinking hard" },
- { emoji: "🔧", text: "Tinkering" },
- { emoji: "🚀", text: "On it" },
- { emoji: "🔥", text: "In the zone" },
- ]
- return pairs.some((p) => p.emoji === emoji && p.text === text)
- },
- queries: {
- session: {
- getValidSession: (db: unknown, token: string) => mockGetValidSession(db, token),
- getValidSessionWithIdentity: (db: unknown, token: string) => mockGetValidSessionWithIdentity(db, token),
- },
- machineToken: {
- getMachineTokenByToken: (...a: any[]) => mockGetMachineTokenByToken(...a),
- getLatestTokenForUser: (...a: any[]) => mockGetLatestTokenForUser(...a),
- },
- runtime: { getRuntimeIdsByDaemon: (...a: any[]) => mockGetRuntimeIdsByDaemon(...a) },
- machine: { getMachineByDaemon: (...a: any[]) => mockGetMachineByDaemon(...a) },
- communityMachine: {
- hashCredential: (bearer: string) => mockHashCredential(bearer),
- findCredentialByHash: (...a: any[]) => mockFindCredentialByHash(...a),
- getMachineByIdForUser: (...a: any[]) => mockGetMachineByIdForUser(...a),
- upsertMachineByMachineId: (...a: any[]) => mockUpsertMachineByMachineId(...a),
- touchMachineHeartbeat: (...a: any[]) => mockTouchMachineHeartbeat(...a),
- markMachineOffline: (...a: any[]) => mockMarkMachineOffline(...a),
- markMachineOnlineIfOffline: (...a: any[]) => mockMarkMachineOnlineIfOffline(...a),
- toSummary: (row: any) => mockToSummary(row),
- isBotOnline: (...a: [unknown, string]) => mockIsBotOnline(...a),
- reconcileBotActivityFromRunningAgents: (...a: any[]) =>
- mockReconcileBotActivityFromRunningAgents(...(a as [unknown, string, string[]])),
- },
- communityUserProfile: {
- updateProfile: (...a: any[]) =>
- mockUpdateProfile(...(a as [unknown, string, { statusEmoji?: string | null; statusText?: string | null }])),
- getProfile: (...a: any[]) => mockGetProfile(...(a as [unknown, string])),
- },
- communityMember: {
- getCoMemberUserIds: (...a: [unknown, string]) => mockGetCoMemberUserIds(...a),
- listMembers: (...a: any[]) => mockListMembers(...a),
- },
- communityFriendship: {
- getFriendUserIds: (...a: [unknown, string]) => mockGetFriendUserIds(...a),
- },
- communityChannel: {
- getChannelForMember: (...a: any[]) => mockGetChannelForMember(...a),
- getChannelType: (...a: any[]) => mockGetChannelType(...a),
- listChannelMemberUserIds: (...a: any[]) => mockListChannelMemberUserIds(...a),
- isChannelPrivate: (...a: any[]) => mockIsChannelPrivate(...a),
- getPrivateChannelAudienceUserIds: (...a: any[]) => mockGetPrivateChannelAudienceUserIds(...a),
- },
- communityMembersResolver: {
- resolveScopeMemberUserIds: (...a: any[]) => mockResolveScopeMemberUserIds(...a),
- },
- communityThread: {
- listThreadParticipantUserIds: (...a: any[]) => mockListThreadParticipantUserIds(...a),
- },
- communityDm: {
- getDM: (...a: any[]) => mockGetDM(...a),
- },
- communityBot: {
- listBotsForMachine: (...a: [unknown, string]) => mockListBotsForMachine(...a),
- getBotBinding: (...a: [unknown, string]) => mockGetBotBinding(...a),
- getBotBindingWithOwner: (...a: [unknown, string]) => mockGetBotBindingWithOwner(...a),
- touchBotRefreshContext: (...a: [unknown, string, string]) => mockTouchBotRefreshContext(...a),
- },
- communityBotAuditLog: {
- insertBotActivityEventAndPrune: (...a: any[]) => mockInsertBotActivityEventAndPrune(...a),
- insertBotAuditSessionReset: (...a: any[]) => mockInsertBotAuditSessionReset(...a),
- insertBotAuditNap: (...a: any[]) => mockInsertBotAuditNap(...a),
- insertBotAuditModelChanged: (...a: any[]) => mockInsertBotAuditModelChanged(...a),
- insertBotAuditProviderChanged: (...a: any[]) => mockInsertBotAuditProviderChanged(...a),
- },
- user: {
- getUserInternal: (...a: [unknown, string]) => mockGetUserInternal(...a),
- },
- },
- }
-})
-
-// Import after mocks
-import { WebSocketDurableObject } from "./ws-durable"
-
-const mockStubFetch = vi.fn().mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ sent: 1 })))
-const mockCheckAliveFetch = vi.fn().mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ alive: true })))
-
-function createDO() {
- const { ctx, getWebSockets, storage, store } = createMockCtx()
- const stubGet = vi.fn().mockReturnValue({ fetch: mockStubFetch })
- const env = {
- DB: {} as D1Database,
- WS_DO: {
- idFromName: vi.fn().mockReturnValue("mock-do-id"),
- get: stubGet,
- } as unknown as DurableObjectNamespace,
- RATE_LIMIT_DO: {} as DurableObjectNamespace,
- }
- const durable = new WebSocketDurableObject(ctx, env)
- return { durable, ctx, getWebSockets, env, stubGet, storage, store }
-}
-
-describe("WebSocketDurableObject", () => {
- beforeEach(() => {
- vi.clearAllMocks()
- // `clearAllMocks` doesn't undo a `mockResolvedValue` set by a prior test —
- // re-pin these two to their empty default so presence-audience tests
- // don't leak state into unrelated auth-flow tests.
- mockGetCoMemberUserIds.mockResolvedValue([])
- mockGetFriendUserIds.mockResolvedValue([])
- mockListBotsForMachine.mockResolvedValue([])
- mockIsBotOnline.mockResolvedValue(false)
- mockGetUserInternal.mockResolvedValue(null)
- mockIsChannelPrivate.mockResolvedValue(false)
- mockGetPrivateChannelAudienceUserIds.mockResolvedValue([])
- // Non-thread default so typing uses the shared resolver path; the
- // thread-typing test overrides this.
- mockGetChannelType.mockResolvedValue("text")
- mockListThreadParticipantUserIds.mockResolvedValue([])
- mockListChannelMemberUserIds.mockResolvedValue([])
- mockGetBotBinding.mockResolvedValue(null)
- mockUpdateProfile.mockResolvedValue({})
- mockGetProfile.mockResolvedValue(null)
- mockReconcileBotActivityFromRunningAgents.mockResolvedValue([])
- // Daemon-auth binds the token to a machine row for daemonId+workspace;
- // default to a present row so auth-flow success tests pass. Tests that
- // exercise a missing machine override this.
- mockGetMachineByDaemon.mockResolvedValue({ daemonId: "my-daemon", workspaceId: "sp_ws1" })
- })
-
- describe("fetch — WebSocket upgrade", () => {
- it("returns 101 for valid WebSocket upgrade", async () => {
- const { durable } = createDO()
- const req = new Request("http://internal/?userId=u1", {
- headers: { Upgrade: "websocket" },
- })
-
- const res = await durable.fetch(req)
-
- expect(res.status).toBe(101)
- expect((res as unknown as CFResponse).webSocket).toBeDefined()
- })
-
- it("returns 426 for non-WebSocket request", async () => {
- const { durable } = createDO()
- const req = new Request("http://internal/")
-
- const res = await durable.fetch(req)
-
- expect(res.status).toBe(426)
- })
-
- it("attaches an unauthenticated ConnectionState on upgrade", async () => {
- const { durable, ctx } = createDO()
- const req = new Request("http://internal/?userId=u1", {
- headers: { Upgrade: "websocket" },
- })
-
- await durable.fetch(req)
-
- const acceptCall = (ctx.acceptWebSocket as ReturnType<typeof vi.fn>).mock.calls[0]
- const serverWs = acceptCall[0]
- expect(serverWs.deserializeAttachment()).toEqual({ type: "user", userId: "", authenticated: false })
- })
- })
-
- describe("fetch — broadcast", () => {
- it("sends message to all authenticated connections", async () => {
- const { durable, ctx } = createDO()
-
- // Set up two WebSockets: one authenticated, one not
- const wsAuth = createMockWebSocket()
- wsAuth.serializeAttachment({ type: "user", userId: "u1", authenticated: true })
- const wsUnauth = createMockWebSocket()
- wsUnauth.serializeAttachment({ type: "user", userId: "", authenticated: false })
- ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsAuth, wsUnauth])
-
- const req = new Request("http://internal/broadcast", {
- method: "POST",
- body: JSON.stringify({ type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" }),
- })
-
- const res = await durable.fetch(req)
-
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ sent: 1 })
- expect(wsAuth.send).toHaveBeenCalledWith(
- JSON.stringify({ type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" })
- )
- expect(wsUnauth.send).not.toHaveBeenCalled()
- })
-
- it("returns sent: 0 when no connections exist", async () => {
- const { durable, ctx } = createDO()
- ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([])
-
- const req = new Request("http://internal/broadcast", {
- method: "POST",
- body: '{"type":"test"}',
- })
-
- const res = await durable.fetch(req)
-
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ sent: 0 })
- })
-
- it("skips connections that throw on send (already closed)", async () => {
- const { durable, ctx } = createDO()
-
- const wsOpen = createMockWebSocket(WebSocket.OPEN)
- wsOpen.serializeAttachment({ type: "user", userId: "u1", authenticated: true })
- const wsClosed = createMockWebSocket(WebSocket.CLOSED)
- wsClosed.serializeAttachment({ type: "user", userId: "u1", authenticated: true })
- wsClosed.send.mockImplementation(() => { throw new Error("Connection closed") })
- ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsOpen, wsClosed])
-
- const req = new Request("http://internal/broadcast", {
- method: "POST",
- body: '{"type":"test"}',
- })
-
- const res = await durable.fetch(req)
-
- expect(wsOpen.send).toHaveBeenCalled()
- expect(wsClosed.send).toHaveBeenCalled()
- expect(await res.json()).toEqual({ sent: 1 })
- })
- })
-
- describe("fetch — /check-user-online (bot-aware, keyed by ?userId=)", () => {
- // This DO instance is keyed by `user:<id>` (idFromName) but can't read
- // its own name back off `ctx` on this worker's pinned compatibility_date
- // — see plans/community-account-debt-fixes.md Fix 3 — so every caller
- // passes `?userId=` explicitly and the handler branches on it.
- it("answers via isBotOnline for a bot id, bypassing the live-socket check entirely", async () => {
- const { durable, ctx } = createDO()
- mockGetUserInternal.mockResolvedValue({ isBot: true } as any)
- mockIsBotOnline.mockResolvedValue(true)
- ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([])
-
- const res = await durable.fetch(new Request("http://internal/check-user-online?userId=bot-1"))
-
- expect(await res.json()).toEqual({ online: true })
- expect(mockGetUserInternal).toHaveBeenCalledWith({}, "bot-1")
- expect(mockIsBotOnline).toHaveBeenCalledWith({}, "bot-1")
- })
-
- it("answers false for a bot id with no bound machine or an offline one", async () => {
- const { durable } = createDO()
- mockGetUserInternal.mockResolvedValue({ isBot: true } as any)
- mockIsBotOnline.mockResolvedValue(false)
-
- const res = await durable.fetch(new Request("http://internal/check-user-online?userId=bot-1"))
-
- expect(await res.json()).toEqual({ online: false })
- })
-
- it("falls back to the live-socket check for a human id (regression: query-param change must not break humans)", async () => {
- const { durable, ctx } = createDO()
- mockGetUserInternal.mockResolvedValue({ isBot: false } as any)
- const wsAuth = createMockWebSocket()
- wsAuth.serializeAttachment({ type: "user", userId: "human-1", authenticated: true })
- ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsAuth])
-
- const res = await durable.fetch(new Request("http://internal/check-user-online?userId=human-1"))
-
- expect(await res.json()).toEqual({ online: true })
- expect(mockIsBotOnline).not.toHaveBeenCalled()
- })
-
- it("falls back to the live-socket check when userId is missing entirely", async () => {
- const { durable, ctx } = createDO()
- const wsAuth = createMockWebSocket()
- wsAuth.serializeAttachment({ type: "user", userId: "u1", authenticated: true })
- ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsAuth])
-
- const res = await durable.fetch(new Request("http://internal/check-user-online"))
-
- expect(await res.json()).toEqual({ online: true })
- expect(mockGetUserInternal).not.toHaveBeenCalled()
- })
-
- it("degrades to { online: false, stale: true } when D1 throws on the bot-online lookup", async () => {
- // Fail-closed via `readOrStale`: getUserInternal (or isBotOnline)
- // throwing on retry-exhaust must NOT surface as a 500 — the caller
- // reads `{ online: false, stale: true }` and moves on.
- const { durable } = createDO()
- mockGetUserInternal.mockRejectedValue(new Error("D1 down"))
-
- const res = await durable.fetch(new Request("http://internal/check-user-online?userId=bot-1"))
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ online: false, stale: true })
- })
- })
-
- describe("webSocketMessage — auth flow", () => {
- it("authenticates with valid token and sends auth.ok", async () => {
- const { durable } = createDO()
- mockGetValidSessionWithIdentity.mockResolvedValue({ userId: "user-42", name: "Ana", discriminator: "0012" })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
-
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))
-
- expect(mockGetValidSessionWithIdentity).toHaveBeenCalledWith({}, "valid-token")
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))
- expect(ws.deserializeAttachment()).toEqual({ type: "user", userId: "user-42", authenticated: true, name: "Ana", discriminator: "0012" })
- })
-
- it("closes with 1008 on invalid token", async () => {
- const { durable } = createDO()
- mockGetValidSessionWithIdentity.mockResolvedValue(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
-
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "bad" }))
-
- expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
- expect(ws.send).not.toHaveBeenCalled()
- })
-
- it("closes with 1008 when auth message has no token", async () => {
- const { durable } = createDO()
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
-
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth" }))
-
- expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
- expect(ws.send).not.toHaveBeenCalled()
- expect(mockGetValidSession).not.toHaveBeenCalled()
- })
-
- it("closes with 1008 when auth message has empty string token", async () => {
- const { durable } = createDO()
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
-
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "" }))
-
- expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
- expect(ws.send).not.toHaveBeenCalled()
- expect(mockGetValidSession).not.toHaveBeenCalled()
- })
-
- it("closes unauthenticated connection sending non-auth message", async () => {
- const { durable } = createDO()
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
-
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "some-event" }))
-
- expect(ws.close).toHaveBeenCalledWith(1008, "Not authenticated")
- })
-
- it("closes with 1008 when session token is expired (getValidSession returns null)", async () => {
- const { durable } = createDO()
- mockGetValidSessionWithIdentity.mockResolvedValue(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
-
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "expired-token" }))
-
- expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
- expect(ws.send).not.toHaveBeenCalled()
- expect(ws.deserializeAttachment()).toEqual({ type: "user", userId: "", authenticated: false })
- })
-
- it("closes on invalid JSON", async () => {
- const { durable } = createDO()
-
- const ws = createMockWebSocket()
-
- await durable.webSocketMessage(ws as any, "not-json")
-
- expect(ws.close).toHaveBeenCalledWith(1008, "Invalid JSON")
- })
-
- it("ignores binary messages", async () => {
- const { durable } = createDO()
-
- const ws = createMockWebSocket()
-
- await durable.webSocketMessage(ws as any, new ArrayBuffer(4))
-
- expect(ws.close).not.toHaveBeenCalled()
- expect(ws.send).not.toHaveBeenCalled()
- })
- })
-
- describe("presence audience — co-members ∪ friends (deduped)", () => {
- // Presence fan-out must reach friends who share no server, not just
- // co-members — that's the whole point of a friends list. Exercised
- // directly against the private helper/methods (bypassing the
- // fire-and-forget `.catch(() => {})` call sites in the auth flow) so
- // these assertions aren't racing an un-awaited promise.
- type PresenceInternals = {
- getPresenceAudience(userId: string): Promise<string[]>
- broadcastPresence(userId: string, online: boolean): Promise<void>
- sendPresenceSnapshot(ws: WebSocket, userId: string): Promise<void>
- }
-
- it("getPresenceAudience merges co-members and friends without duplicates", async () => {
- const { durable } = createDO()
- mockGetCoMemberUserIds.mockResolvedValue(["member-a", "shared-b"])
- mockGetFriendUserIds.mockResolvedValue(["shared-b", "friend-c"])
-
- const audience = await (durable as unknown as PresenceInternals).getPresenceAudience("user-1")
-
- expect(new Set(audience)).toEqual(new Set(["member-a", "shared-b", "friend-c"]))
- expect(audience).toHaveLength(3)
- expect(mockGetCoMemberUserIds).toHaveBeenCalledWith({}, "user-1")
- expect(mockGetFriendUserIds).toHaveBeenCalledWith({}, "user-1")
- })
-
- it("getPresenceAudience returns [] when the user has no co-members and no friends", async () => {
- const { durable } = createDO()
- mockGetCoMemberUserIds.mockResolvedValue([])
- mockGetFriendUserIds.mockResolvedValue([])
-
- const audience = await (durable as unknown as PresenceInternals).getPresenceAudience("user-1")
-
- expect(audience).toEqual([])
- })
-
- it("broadcastPresence fans out to a friend who shares no server", async () => {
- const { durable, env } = createDO()
- mockGetCoMemberUserIds.mockResolvedValue([])
- mockGetFriendUserIds.mockResolvedValue(["friend-c"])
- mockStubFetch.mockClear()
-
- await (durable as unknown as PresenceInternals).broadcastPresence("user-1", true)
-
- expect(env.WS_DO.idFromName).toHaveBeenCalledWith("user:friend-c")
- expect(mockStubFetch).toHaveBeenCalledTimes(1)
- const [req] = mockStubFetch.mock.calls[0] as [Request]
- expect(req.url).toBe("http://internal/broadcast")
- })
-
- it("broadcastPresence no-ops (no fetches) when co-members and friends are both empty", async () => {
- const { durable } = createDO()
- mockGetCoMemberUserIds.mockResolvedValue([])
- mockGetFriendUserIds.mockResolvedValue([])
- mockStubFetch.mockClear()
-
- await (durable as unknown as PresenceInternals).broadcastPresence("user-1", true)
-
- expect(mockStubFetch).not.toHaveBeenCalled()
- })
-
- it("sendPresenceSnapshot reports an online friend who shares no server", async () => {
- const { durable } = createDO()
- mockGetCoMemberUserIds.mockResolvedValue([])
- mockGetFriendUserIds.mockResolvedValue(["friend-c"])
- mockStubFetch.mockResolvedValue(
- new (globalThis.Response as any)(JSON.stringify({ online: true })),
- )
- const ws = createMockWebSocket()
-
- await (durable as unknown as PresenceInternals).sendPresenceSnapshot(ws as any, "user-1")
-
- expect(ws.send).toHaveBeenCalledWith(
- JSON.stringify({ type: "community:presence.update", userId: "friend-c", online: true }),
- )
- })
-
- // Regression (post-Fix-3 hotfix): a fresh bot has no server membership,
- // so co-members alone can be empty for it even while its bound machine
- // is genuinely online. The fix lives one layer down, in
- // `getFriendUserIds` itself (see `community-friendship.test.ts`) — the
- // owner↔own-bot implicit friendship it already returns for `listFriends`
- // /`areFriends` now also flows through here, so `getPresenceAudience`
- // needs no bot-specific branch at all; it just trusts whatever
- // `getFriendUserIds` (mocked as `mockGetFriendUserIds` above) says.
- })
-
- describe("notifyUserDO — bot fan-out on community:machine.status (Fix 3)", () => {
- // `notifyUserDO` is private; every `community:machine.status` emission in
- // this file funnels through it (the single choke point the plan calls
- // for), so exercising it directly here covers all 5 call sites without
- // duplicating their individual setup.
- type NotifyInternals = { notifyUserDO(userId: string, payload: unknown): Promise<void> }
-
- /** Collects `{ url, body }` for every `mockStubFetch` call so far. */
- async function capturedRequests(): Promise<Array<{ url: string; body: string }>> {
- return Promise.all(
- mockStubFetch.mock.calls.map(async ([req]) => ({
- url: (req as Request).url,
- body: await (req as Request).clone().text(),
- }))
- )
- }
-
- it("fans out community:presence.update(online: true) to every bot bound to the machine, beyond the owner notify", async () => {
- const { durable, env } = createDO()
- mockListBotsForMachine.mockResolvedValue([
- { id: "bot-1", name: "Bot One", discriminator: "0001", description: "" },
- { id: "bot-2", name: "Bot Two", discriminator: "0002", description: "" },
- ])
- mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
- mockGetFriendUserIds.mockResolvedValue([])
- mockStubFetch.mockClear()
-
- await (durable as unknown as NotifyInternals).notifyUserDO("owner-1", {
- type: "community:machine.status",
- machineId: "m1",
- status: "online",
- lastSeenAt: "2026-01-01T00:00:00.000Z",
- })
-
- expect(mockListBotsForMachine).toHaveBeenCalledWith({}, "m1")
- expect(env.WS_DO.idFromName).toHaveBeenCalledWith("user:owner-1")
- expect(env.WS_DO.idFromName).toHaveBeenCalledWith("user:viewer-1")
-
- const requests = await capturedRequests()
- // 1 owner notify (raw payload) + 1 broadcastPresence fetch per bot to the shared viewer.
- expect(requests).toHaveLength(3)
- expect(requests.filter((r) => r.body.includes('"userId":"bot-1"') && r.body.includes('"online":true'))).toHaveLength(1)
- expect(requests.filter((r) => r.body.includes('"userId":"bot-2"') && r.body.includes('"online":true'))).toHaveLength(1)
- })
-
- it("broadcasts online: false for every bound bot on a machine-offline transition", async () => {
- const { durable } = createDO()
- mockListBotsForMachine.mockResolvedValue([
- { id: "bot-1", name: "Bot One", discriminator: "0001", description: "" },
- ])
- mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
- mockGetFriendUserIds.mockResolvedValue([])
- mockStubFetch.mockClear()
-
- await (durable as unknown as NotifyInternals).notifyUserDO("owner-1", {
- type: "community:machine.status",
- machineId: "m1",
- status: "offline",
- lastSeenAt: "2026-01-01T00:00:00.000Z",
- })
-
- const requests = await capturedRequests()
- expect(requests.some((r) => r.body.includes('"userId":"bot-1"') && r.body.includes('"online":false'))).toBe(true)
- })
-
- it("a machine bound to zero bots triggers no extra broadcast beyond the owner notify", async () => {
- const { durable } = createDO()
- mockListBotsForMachine.mockResolvedValue([])
- mockStubFetch.mockClear()
-
- await (durable as unknown as NotifyInternals).notifyUserDO("owner-1", {
- type: "community:machine.status",
- machineId: "m1",
- status: "online",
- lastSeenAt: "2026-01-01T00:00:00.000Z",
- })
-
- expect(mockStubFetch).toHaveBeenCalledTimes(1) // owner notify only
- })
-
- it("does not call listBotsForMachine for a payload that isn't a community:machine.status transition", async () => {
- const { durable } = createDO()
- mockStubFetch.mockClear()
-
- await (durable as unknown as NotifyInternals).notifyUserDO("owner-1", {
- type: "community:machine.updated",
- machine: { id: "m1" },
- })
-
- expect(mockListBotsForMachine).not.toHaveBeenCalled()
- expect(mockStubFetch).toHaveBeenCalledTimes(1) // owner notify only
- })
-
- it("does not throw and skips the bot fan-out on a malformed/non-object payload", async () => {
- const { durable } = createDO()
- await expect(
- (durable as unknown as NotifyInternals).notifyUserDO("owner-1", "not-an-object")
- ).resolves.toBeUndefined()
- expect(mockListBotsForMachine).not.toHaveBeenCalled()
- })
-
- it("resolves cleanly when the owner-notify stub fetch rejects — the whole method is under try/catch, callers never see the throw", async () => {
- // Regression guard: the owner-notify `userStub.fetch(...)` used to
- // sit OUTSIDE the method's try/catch. A stub-fetch throw would
- // propagate through every caller's `.catch(() => {})` and skip the
- // bot fan-out entirely, contradicting the comment that claims the
- // failure would "at least be visible."
- const { durable } = createDO()
- mockStubFetch.mockClear()
- // First call is the owner notify — reject it. Subsequent calls
- // (bot fan-out per-audience-member) should still fire.
- mockStubFetch.mockRejectedValueOnce(new Error("stub unreachable"))
- mockListBotsForMachine.mockResolvedValue([
- { id: "bot-1", name: "Bot One", discriminator: "0001", description: "" },
- ])
- mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
- mockGetFriendUserIds.mockResolvedValue([])
-
- await expect(
- (durable as unknown as NotifyInternals).notifyUserDO("owner-1", {
- type: "community:machine.status",
- machineId: "m1",
- status: "online",
- lastSeenAt: "2026-01-01T00:00:00.000Z",
- })
- ).resolves.toBeUndefined()
-
- // Owner notify was attempted (and failed) — bot fan-out still ran.
- expect(mockListBotsForMachine).toHaveBeenCalledWith({}, "m1")
- // Owner notify + at least one broadcastPresence fetch to viewer-1.
- expect(mockStubFetch.mock.calls.length).toBeGreaterThanOrEqual(2)
- })
- })
-
- describe("webSocketMessage — daemon auth flow", () => {
- it("rejects daemon with pending token (not yet activated)", async () => {
- const { durable } = createDO()
- mockGetMachineTokenByToken.mockResolvedValue({
- id: "mt_1", userId: "u1", status: "pending", workspaceId: null,
- })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "", userId: "", authenticated: false })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "auth", machineToken: "al_pending123", daemonId: "my-daemon" }),
- )
-
- expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
- expect(mockGetRuntimeIdsByDaemon).not.toHaveBeenCalled()
- })
-
- it("authenticates daemon with active token (no runtime check in auth)", async () => {
- const { durable } = createDO()
- mockGetMachineTokenByToken.mockResolvedValue({
- id: "mt_1", userId: "u1", status: "active", workspaceId: "sp_ws1",
- })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "auth", machineToken: "al_active123", daemonId: "my-daemon" }),
- )
-
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))
- // Runtime presence is no longer part of auth — it must not gate the WS
- // connection (tasks route by workspaceId; runtimes may be mid-register).
- expect(mockGetRuntimeIdsByDaemon).not.toHaveBeenCalled()
- })
-
- it("authenticates daemon with active token even when it has no runtimes yet", async () => {
- const { durable } = createDO()
- mockGetMachineTokenByToken.mockResolvedValue({
- id: "mt_1", userId: "u1", status: "active", workspaceId: "sp_ws1",
- })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "auth", machineToken: "al_noruntimes", daemonId: "my-daemon" }),
- )
-
- // No-runtime is a valid state (not an auth failure) — auth.ok, no reject.
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))
- expect(ws.send).not.toHaveBeenCalledWith(JSON.stringify({ type: "error", code: "AUTH_REJECTED" }))
- })
-
- it("sends AUTH_REJECTED then closes on definitely-invalid token", async () => {
- const { durable } = createDO()
- mockGetMachineTokenByToken.mockResolvedValue(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "auth", machineToken: "al_dead", daemonId: "my-daemon" }),
- )
-
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "error", code: "AUTH_REJECTED" }))
- expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
- })
-
- it("closes WITHOUT AUTH_REJECTED on transient D1 failure (daemon must retry)", async () => {
- const { durable } = createDO()
- mockGetMachineTokenByToken.mockRejectedValue(new Error("D1 unavailable"))
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "auth", machineToken: "al_blip", daemonId: "my-daemon" }),
- )
-
- expect(ws.send).not.toHaveBeenCalledWith(JSON.stringify({ type: "error", code: "AUTH_REJECTED" }))
- expect(ws.close).toHaveBeenCalledWith(1011, "Auth temporarily unavailable")
- })
-
- it("rejects daemon with unknown token", async () => {
- const { durable } = createDO()
- mockGetMachineTokenByToken.mockResolvedValue(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "auth", machineToken: "al_unknown", daemonId: "my-daemon" }),
- )
-
- expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
- })
-
- it("rejects daemon with non-al_ prefixed token", async () => {
- const { durable } = createDO()
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "auth", machineToken: "bad_prefix", daemonId: "my-daemon" }),
- )
-
- expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
- expect(mockGetMachineTokenByToken).not.toHaveBeenCalled()
- })
- })
-
- describe("webSocketMessage — check_daemon_status (cross-DO)", () => {
- it("returns runtime.status online when daemon DO reports alive", async () => {
- const { durable, env } = createDO()
- mockGetLatestTokenForUser.mockResolvedValue({ hostname: "MyMachine.local" })
-
- const aliveStub = { fetch: vi.fn().mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ alive: true }))) }
- ; (env.WS_DO as any).get = vi.fn().mockReturnValue(aliveStub)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })
-
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
-
- expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("daemon:MyMachine.local")
- expect(ws.send).toHaveBeenCalledWith(
- JSON.stringify({ type: "runtime.status", status: "online", daemonId: "MyMachine.local" }),
- )
- })
-
- it("does not respond when daemon DO reports not alive", async () => {
- const { durable, env } = createDO()
- mockGetLatestTokenForUser.mockResolvedValue({ hostname: "MyMachine.local" })
-
- const deadStub = { fetch: vi.fn().mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ alive: false }))) }
- ; (env.WS_DO as any).get = vi.fn().mockReturnValue(deadStub)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })
-
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
-
- expect(ws.send).not.toHaveBeenCalled()
- })
-
- it("does not respond when no token/hostname found", async () => {
- const { durable } = createDO()
- mockGetLatestTokenForUser.mockResolvedValue(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })
-
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
-
- expect(ws.send).not.toHaveBeenCalled()
- })
- })
-
- describe("webSocketError", () => {
- it("closes with 1011", async () => {
- const { durable } = createDO()
-
- const ws = createMockWebSocket()
-
- await durable.webSocketError(ws as any, new Error("boom"))
-
- expect(ws.close).toHaveBeenCalledWith(1011, "Internal error")
- })
- })
-
- describe("community-machine — session.error overlay + optimistic clear", () => {
- beforeEach(() => {
- mockFindCredentialByHash.mockReset()
- mockGetMachineByIdForUser.mockReset()
- mockStubFetch.mockClear()
- })
-
- it("stashes lastRuntimeError overlay + fans out on session.error{runtime_not_available}", async () => {
- const { durable, store } = createDO()
- // Prime cached identity as if accept already ran.
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetMachineByIdForUser.mockResolvedValue({
- id: "cm_1",
- hostname: "host",
- availableRuntimes: [{ id: "codex" }],
- })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({
- type: "session.error",
- code: "runtime_not_available",
- agentId: "a1",
- payload: { requested: "gemini", available: ["codex"] },
- })
- await durable.webSocketMessage(ws as any, frame)
-
- const overlay = store.get("community-machine-runtime-error") as
- | { requested: string; available: string[]; at: string }
- | undefined
- expect(overlay).toBeDefined()
- expect(overlay?.requested).toBe("gemini")
- expect(overlay?.available).toEqual(["codex"])
-
- // Fan-out went to the user DO with the overlay attached.
- expect(mockStubFetch).toHaveBeenCalled()
- const call = mockStubFetch.mock.calls.find((c: any[]) =>
- (c[0] as Request).url.endsWith("/broadcast")
- )
- const body = JSON.parse(await (call![0] as Request).clone().text()) as {
- type: string
- machine: { lastRuntimeError?: { requested: string; available: string[] } }
- }
- expect(body.type).toBe("community:machine.updated")
- expect(body.machine.lastRuntimeError).toMatchObject({
- requested: "gemini",
- available: ["codex"],
- })
- })
-
- it("forceClose closes attachments and clears identity+overlay", async () => {
- const { durable, ctx, store, getWebSockets } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- store.set("community-machine-handle", { userId: "u_1", machineId: "cm_1" })
- store.set("community-machine-runtime-error", {
- requested: "gemini",
- available: [],
- at: "2026-07-06T00:00:00.000Z",
- })
- mockGetMachineByIdForUser.mockResolvedValue({
- id: "cm_1",
- hostname: "host",
- availableRuntimes: [],
- })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
- getWebSockets.mockReturnValue([ws])
-
- const req = new Request("http://internal/force-close", { method: "POST" })
- const res = await durable.fetch(req)
- expect(res.status).toBe(200)
- expect(ws.send).toHaveBeenCalled()
- expect(ws.close).toHaveBeenCalledWith(1008, "Revoked")
-
- // Cached identity + handle + overlay all cleared.
- expect(store.get("community-machine-identity")).toBeUndefined()
- expect(store.get("community-machine-handle")).toBeUndefined()
- expect(store.get("community-machine-runtime-error")).toBeUndefined()
- })
- })
-
- describe("community-machine — ready frame wire shape", () => {
- beforeEach(() => {
- mockUpsertMachineByMachineId.mockReset()
- mockStubFetch.mockClear()
- })
-
- // Regression guard: the daemon (WsControlChannel.reportReady) spreads
- // HostReady fields at the TOP LEVEL of the frame. If it ever regresses to
- // wrapping them under `ready:{...}`, the DO would silently drop every
- // ready and `last_seen_at` would never refresh. This test drives the exact
- // shape the daemon emits.
- it("accepts a flat daemon-shaped ready frame and calls upsertMachineByMachineId", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockUpsertMachineByMachineId.mockResolvedValue({
- machine: {
- id: "cm_1",
- hostname: "host",
- availableRuntimes: [{ id: "claude" }],
- status: "online",
- lastSeenAt: "2026-07-06T00:00:00.000Z",
- },
- priorLastSeenAt: "2026-07-05T00:00:00.000Z",
- priorAvailableRuntimes: [{ id: "claude" }],
- priorStatus: "offline",
- })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- // The wire frame the daemon actually sends — see WsControlChannel.reportReady.
- const frame = JSON.stringify({
- type: "ready",
- runtimeReport: [{ id: "claude", version: "1.0.0" }],
- runningAgents: [],
- hostname: "my-mac",
- platform: "darwin",
- arch: "arm64",
- osRelease: "23.0.0",
- daemonVersion: "0.1.0",
- })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockUpsertMachineByMachineId).toHaveBeenCalledTimes(1)
- const [, userId, machineId, meta] = mockUpsertMachineByMachineId.mock.calls[0]
- expect(userId).toBe("u_1")
- expect(machineId).toBe("cm_1")
- expect(meta).toMatchObject({
- hostname: "my-mac",
- platform: "darwin",
- arch: "arm64",
- osRelease: "23.0.0",
- daemonVersion: "0.1.0",
- availableRuntimes: [{ id: "claude", version: "1.0.0" }],
- })
- })
-
- it("silently drops a wrapped `{ready:{...}}` frame (legacy shape — regression guard)", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- // The (broken) wrapped shape — schema rejects → DO drops → no DB write.
- const frame = JSON.stringify({
- type: "ready",
- ready: {
- runtimeReport: [{ id: "claude" }],
- runningAgents: [],
- hostname: "my-mac",
- },
- })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockUpsertMachineByMachineId).not.toHaveBeenCalled()
- })
- })
-
- describe("community-machine — agent_activity frame", () => {
- beforeEach(() => {
- mockGetBotBinding.mockReset()
- mockUpdateProfile.mockReset().mockResolvedValue({})
- mockGetProfile.mockReset().mockResolvedValue(null)
- mockStubFetch.mockClear()
- })
-
- it("writes the translated statusEmoji/statusText via updateProfile and fans out community:status.update when the frame's machine owns the bot", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })
- mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" })
- await durable.webSocketMessage(ws as any, frame)
-
- // The (stubbed) `pickBotActivityPreset` returns a fixed pair for
- // "running" in this test — the assertion pins that exact pair.
- expect(mockUpdateProfile).toHaveBeenCalledWith(expect.anything(), "bot_1", {
- statusEmoji: "⚡",
- statusText: "Working on it",
- })
- const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
- expect(call).toBeDefined()
- const body = JSON.parse(await (call![0] as Request).clone().text()) as {
- type: string
- userId: string
- statusEmoji: string
- statusText: string
- }
- expect(body).toEqual({
- type: "community:status.update",
- userId: "bot_1",
- statusEmoji: "⚡",
- statusText: "Working on it",
- })
- })
-
- it("drops a frame naming a bot bound to a different machine — no DB write, no fan-out", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBinding.mockResolvedValue({ machineId: "cm_OTHER", runtime: "codex" })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockUpdateProfile).not.toHaveBeenCalled()
- expect(mockStubFetch).not.toHaveBeenCalled()
- })
-
- it("drops a frame for an unbound (unknown) bot — no DB write, no fan-out", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBinding.mockResolvedValue(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({ type: "agent_activity", agentId: "ghost_bot", state: "idle" })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockUpdateProfile).not.toHaveBeenCalled()
- expect(mockStubFetch).not.toHaveBeenCalled()
- })
-
- it("regression #3 — an owner-set custom status is NOT overwritten by a running frame (write-path guard); no DB write, no fan-out", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })
- // Prior status is a custom (non-preset) pair the owner set.
- mockGetProfile.mockResolvedValue({ statusEmoji: "🎨", statusText: "Painting" })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
-
- const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" })
- await durable.webSocketMessage(ws as any, frame)
-
- // Guard skips the write entirely — custom status survives, even though the
- // bot is working. This is what stops T6's heartbeat re-stomp every 5s.
- expect(mockUpdateProfile).not.toHaveBeenCalled()
- expect(mockStubFetch).not.toHaveBeenCalled()
- })
-
- it("regression #3b — a BRAND-NEW bot (profile row exists but status unset: emoji=null, text=\"\") still gets its status written", async () => {
- // `status_text` defaults to "" in the schema, so an unset status reads
- // back as (null, "") not (null, null). The custom-status guard must treat
- // that as "no status" (writable), NOT mistake "" for a custom status —
- // otherwise new bots never get a pill (the reported regression).
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })
- mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
- mockGetProfile.mockResolvedValue({ statusEmoji: null, statusText: "" })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
-
- const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockUpdateProfile).toHaveBeenCalledWith(expect.anything(), "bot_1", {
- statusEmoji: "⚡",
- statusText: "Working on it",
- })
- })
-
- it("regression #4 — a known idle preset still flips to running (guard didn't over-reach)", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })
- mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
- // Prior is the idle PRESET (pipeline-owned) — must remain writable.
- mockGetProfile.mockResolvedValue({ statusEmoji: "💤", statusText: "Idle" })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
-
- const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockUpdateProfile).toHaveBeenCalledWith(expect.anything(), "bot_1", {
- statusEmoji: "⚡",
- statusText: "Working on it",
- })
- })
-
- it("regression #4 — a known running preset still flips back to idle (guard didn't over-reach)", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })
- mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
- // Prior is a running PRESET — an idle frame must be allowed to overwrite it.
- mockGetProfile.mockResolvedValue({ statusEmoji: "⚡", statusText: "Working on it" })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
-
- const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "idle" })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockUpdateProfile).toHaveBeenCalledWith(expect.anything(), "bot_1", {
- statusEmoji: "💤",
- statusText: "Idle",
- })
- })
-
- it("drops the frame with phase='binding_check' when getBotBinding throws — socket stays open, no write", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBinding.mockRejectedValue(new Error("D1 down"))
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockUpdateProfile).not.toHaveBeenCalled()
- expect(mockStubFetch).not.toHaveBeenCalled()
- // Socket didn't close — the DO doesn't touch ws.close() on any per-frame D1 error.
- expect(ws.close as ReturnType<typeof vi.fn>).not.toHaveBeenCalled()
- })
- })
-
- describe("community-machine — agent_typing / agent_typing_stop frames", () => {
- beforeEach(() => {
- mockGetBotBindingWithOwner.mockReset()
- mockGetChannelForMember.mockReset()
- mockGetChannelType.mockReset()
- mockGetChannelType.mockResolvedValue("dm")
- mockListChannelMemberUserIds.mockReset()
- mockListChannelMemberUserIds.mockResolvedValue([])
- mockStubFetch.mockClear()
- })
-
- it("agent_typing: fans out community:typing.start to the DM peer when machine owns the bot and DM is valid", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBindingWithOwner.mockResolvedValue({
- machineId: "cm_1",
- runtime: "codex",
- ownerUserId: "u_1",
- name: "Bot",
- discriminator: "0007",
- })
- mockGetChannelForMember.mockResolvedValue({ id: "dm_1", serverId: null })
- mockGetChannelType.mockResolvedValue("dm")
- mockListChannelMemberUserIds.mockResolvedValue(["bot_1", "peer_1"])
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({
- type: "agent_typing",
- agentId: "bot_1",
- channelId: "dm_1",
- })
- await durable.webSocketMessage(ws as any, frame)
-
- const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
- expect(call).toBeDefined()
- const body = JSON.parse(await (call![0] as Request).clone().text()) as {
- type: string
- userId: string
- channelId: string
- name?: string
- discriminator?: string
- }
- // Bot path carries name/discriminator from the binding (getBotBindingWithOwner's
- // existing join) so the client renders the bot's name without a roster lookup.
- expect(body).toEqual({
- type: "community:typing.start",
- userId: "bot_1",
- channelId: "dm_1",
- name: "Bot",
- discriminator: "0007",
- })
- })
-
- it("agent_typing: drops a frame naming a bot bound to a different machine — no fan-out", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBindingWithOwner.mockResolvedValue({
- machineId: "cm_OTHER",
- runtime: "codex",
- ownerUserId: "u_1",
- name: "Bot",
- discriminator: "0007",
- })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({
- type: "agent_typing",
- agentId: "bot_1",
- channelId: "dm_1",
- })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockGetChannelForMember).not.toHaveBeenCalled()
- expect(mockStubFetch).not.toHaveBeenCalled()
- })
-
- it("agent_typing: drops a frame for a bot that is not a DM participant — no fan-out", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBindingWithOwner.mockResolvedValue({
- machineId: "cm_1",
- runtime: "codex",
- ownerUserId: "u_1",
- name: "Bot",
- discriminator: "0007",
- })
- // Bot isn't a member of the channel → getChannelForMember returns null,
- // so fanOutTyping bails before resolving recipients.
- mockGetChannelForMember.mockResolvedValue(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({
- type: "agent_typing",
- agentId: "bot_1",
- channelId: "dm_1",
- })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockStubFetch).not.toHaveBeenCalled()
- })
-
- it("agent_typing_stop: fans out community:typing.stop to the DM peer, excludes sender", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBindingWithOwner.mockResolvedValue({
- machineId: "cm_1",
- runtime: "codex",
- ownerUserId: "u_1",
- name: "Bot",
- discriminator: "0007",
- })
- mockGetChannelForMember.mockResolvedValue({ id: "dm_1", serverId: null })
- mockGetChannelType.mockResolvedValue("dm")
- mockListChannelMemberUserIds.mockResolvedValue(["bot_1", "peer_1"])
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({
- type: "agent_typing_stop",
- agentId: "bot_1",
- channelId: "dm_1",
- })
- await durable.webSocketMessage(ws as any, frame)
-
- const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
- expect(call).toBeDefined()
- const body = JSON.parse(await (call![0] as Request).clone().text()) as {
- type: string
- userId: string
- channelId: string
- }
- expect(body).toEqual({
- type: "community:typing.stop",
- userId: "bot_1",
- channelId: "dm_1",
- })
- // Sender exclusion: only the peer (peer_1) is targeted — a single
- // /broadcast call, addressed via the peer's user DO.
- expect(mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))).toHaveLength(1)
- })
- })
-
- describe("community-machine — bot_audit_event frame", () => {
- beforeEach(() => {
- mockGetBotBindingWithOwner.mockReset()
- mockInsertBotActivityEventAndPrune.mockReset()
- mockStubFetch.mockClear()
- })
-
- it("inserts + prunes atomically and notifies the OWNER only when the machine owns the bot", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBindingWithOwner.mockResolvedValue({
- machineId: "cm_1",
- runtime: "codex",
- ownerUserId: "owner_1",
- name: "Bot",
- discriminator: "0007",
- })
- mockInsertBotActivityEventAndPrune.mockResolvedValue({
- id: "bae_abc",
- createdAt: "2025-01-01T00:00:00.000Z",
- })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({
- type: "bot_audit_event",
- agentId: "bot_1",
- sessionId: "s_1",
- launchId: "l_1",
- event: { kind: "tool_call", payload: { name: "Read" } },
- })
- await durable.webSocketMessage(ws as any, frame)
-
- // Insert was called with server-derived payload (not trust-the-daemon).
- expect(mockInsertBotActivityEventAndPrune).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({
- botId: "bot_1",
- sessionId: "s_1",
- launchId: "l_1",
- kind: "tool_call",
- payload: JSON.stringify({ name: "Read" }),
- }),
- )
- // Owner is notified via notifyUserDO — request goes to `user:owner_1`
- // and the payload carries the full audit event including createdAt
- // stamped server-side.
- const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
- expect(call).toBeDefined()
- const body = JSON.parse(await (call![0] as Request).clone().text()) as {
- type: string
- botId: string
- id: string
- kind: string
- payload: unknown
- createdAt: string
- }
- expect(body).toEqual({
- type: "community:bot.audit_event",
- botId: "bot_1",
- id: "bae_abc",
- kind: "tool_call",
- payload: { name: "Read" },
- sessionId: "s_1",
- launchId: "l_1",
- createdAt: "2025-01-01T00:00:00.000Z",
- })
- })
-
- it("drops a frame naming a bot bound to a different machine — no insert, no fan-out", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBindingWithOwner.mockResolvedValue({
- machineId: "cm_OTHER",
- runtime: "codex",
- ownerUserId: "owner_1",
- name: "Bot",
- discriminator: "0007",
- })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({
- type: "bot_audit_event",
- agentId: "bot_1",
- event: { kind: "cli_invocation", payload: { subcommand: "send" } },
- })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockInsertBotActivityEventAndPrune).not.toHaveBeenCalled()
- expect(mockStubFetch).not.toHaveBeenCalled()
- })
-
- it("drops a frame for a soft-deleted/unknown bot — no insert, no fan-out", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBindingWithOwner.mockResolvedValue(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({
- type: "bot_audit_event",
- agentId: "ghost_bot",
- event: { kind: "thinking", payload: { text: "hmm", truncated: false, chars: 3 } },
- })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockInsertBotActivityEventAndPrune).not.toHaveBeenCalled()
- expect(mockStubFetch).not.toHaveBeenCalled()
- })
-
- it("does not fan out when the INSERT returns null (empty batch result)", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBindingWithOwner.mockResolvedValue({
- machineId: "cm_1",
- runtime: "codex",
- ownerUserId: "owner_1",
- name: "Bot",
- discriminator: "0007",
- })
- // Simulate the D1 batch returning no rows for the primary statement.
- mockInsertBotActivityEventAndPrune.mockResolvedValue(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({
- type: "bot_audit_event",
- agentId: "bot_1",
- event: { kind: "tool_call", payload: { name: "Read" } },
- })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockStubFetch).not.toHaveBeenCalled()
- })
-
- it("drops the frame with phase='write' when the insert throws — socket stays open, no fan-out", async () => {
- // This is the ws_frame_dropped_write category — the audit-loss SLO
- // signal. The DO must NOT close the socket, and no owner fan-out
- // should be emitted (the row was never persisted).
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockGetBotBindingWithOwner.mockResolvedValue({
- machineId: "cm_1",
- runtime: "codex",
- ownerUserId: "owner_1",
- name: "Bot",
- discriminator: "0007",
- })
- mockInsertBotActivityEventAndPrune.mockRejectedValue(new Error("D1 insert failed"))
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({
- type: "bot_audit_event",
- agentId: "bot_1",
- event: { kind: "tool_call", payload: { name: "Read" } },
- })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockStubFetch).not.toHaveBeenCalled()
- expect(ws.close as ReturnType<typeof vi.fn>).not.toHaveBeenCalled()
- })
- })
-
- describe("community-machine — reset/nap completion re-home (agent_session landing)", () => {
- beforeEach(() => {
- mockInsertBotAuditSessionReset.mockReset()
- mockInsertBotAuditNap.mockReset()
- mockInsertBotAuditModelChanged.mockReset()
- mockInsertBotAuditProviderChanged.mockReset()
- mockTouchBotRefreshContext.mockReset()
- mockGetBotBindingWithOwner.mockReset()
- mockStubFetch.mockClear()
- mockInsertBotAuditSessionReset.mockResolvedValue({ id: "bae_reset", createdAt: "2025-06-01T10:00:00.000Z" })
- mockInsertBotAuditNap.mockResolvedValue({ id: "bae_nap", createdAt: "2025-06-01T11:00:00.000Z" })
- mockInsertBotAuditModelChanged.mockResolvedValue({ id: "bae_model", createdAt: "2025-06-01T12:00:00.000Z" })
- mockInsertBotAuditProviderChanged.mockResolvedValue({ id: "bae_provider", createdAt: "2025-06-01T13:00:00.000Z" })
- mockTouchBotRefreshContext.mockResolvedValue(undefined)
- mockGetBotBindingWithOwner.mockResolvedValue({
- machineId: "cm_1",
- runtime: "codex",
- ownerUserId: "owner_1",
- name: "Bot",
- discriminator: "0007",
- })
- })
-
- function machineWs() {
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
- return ws
- }
-
- function seedIdentity(store: Map<string, unknown>) {
- store.set("community-machine-identity", { userId: "u_1", machineId: "cm_1", credentialHash: "0".repeat(64) })
- }
-
- // record-iff-sent>0: pending is only written when a live community-machine
- // socket accepts the forward. Seed one so /push and /push-*-switch tests
- // exercise the completion landing (offline → sent=0 → no pending).
- function onlineDaemon() {
- const { durable, store, getWebSockets } = createDO()
- seedIdentity(store)
- const daemon = machineWs()
- getWebSockets.mockReturnValue([daemon])
- return { durable, store, daemon }
- }
-
- // Helper: push a frame through /push (records pending attribution), matching
- // how the index worker forwards reset/nap frames to this DO.
- async function pushFrame(durable: any, body: unknown) {
- await durable.fetch(
- new (globalThis.Request as any)("http://internal/push", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- }),
- )
- }
-
- async function pushSwitch(durable: any, kind: "provider" | "model", body: Record<string, unknown>) {
- await durable.fetch(
- new (globalThis.Request as any)(`http://internal/push-${kind}-switch`, {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- }),
- )
- }
-
- function auditBroadcast() {
- return mockStubFetch.mock.calls
- .map((c: any[]) => c[0] as Request)
- .find((r: Request) => r.url.endsWith("/broadcast"))
- }
-
- it("single reset: agent_session writes session_reset audit + stamps awake in lockstep + broadcasts", async () => {
- const { durable } = onlineDaemon()
- // Dispatch: an agent:reset frame is forwarded → records launchId→single.
- await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
- // Completion: the reborn agent's agent_session lands.
- await durable.webSocketMessage(
- machineWs() as any,
- JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" }),
- )
-
- // Audit written server-side with the trigger derived from the endpoint.
- expect(mockInsertBotAuditSessionReset).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({ botId: "bot_1", launchId: "l_reset", trigger: "single" }),
- )
- expect(mockInsertBotAuditNap).not.toHaveBeenCalled()
- // LOCKSTEP invariant: touch uses the audit row's own createdAt, not another clock.
- expect(mockTouchBotRefreshContext).toHaveBeenCalledWith(expect.anything(), "bot_1", "2025-06-01T10:00:00.000Z")
- // Broadcast to the owner carries the session_reset event.
- const call = auditBroadcast()
- expect(call).toBeDefined()
- const body = JSON.parse(await (call!).clone().text()) as Record<string, unknown>
- expect(body).toEqual({
- type: "community:bot.audit_event",
- botId: "bot_1",
- id: "bae_reset",
- kind: "session_reset",
- payload: { trigger: "single" },
- sessionId: null,
- launchId: "l_reset",
- createdAt: "2025-06-01T10:00:00.000Z",
- })
- })
-
- it("two agent_session frames for the same launch write the reset audit ONCE (claim-first evict, no double record)", async () => {
- const { durable } = onlineDaemon()
- await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
- // Two agent_session frames arrive back-to-back for the SAME launch (e.g. a
- // runtime that announces its session twice). The pending trigger must be
- // consumed by the first → the second finds nothing → only ONE audit row.
- const frame = JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" })
- await durable.webSocketMessage(machineWs() as any, frame)
- await durable.webSocketMessage(machineWs() as any, frame)
-
- expect(mockInsertBotAuditSessionReset).toHaveBeenCalledTimes(1)
- })
-
- it("batch reset: each agent's agent_session writes session_reset with trigger reset_all", async () => {
- const { durable } = onlineDaemon()
- // Dispatch: ONE machine:reset_all frame carrying two launches.
- await pushFrame(durable, {
- type: "machine:reset_all",
- resets: [
- { agentId: "bot_1", config: {}, launchId: "l_a" },
- { agentId: "bot_2", config: {}, launchId: "l_b" },
- ],
- })
- // Both agents reborn — two agent_session frames.
- await durable.webSocketMessage(
- machineWs() as any,
- JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_a", launchId: "l_a" }),
- )
- await durable.webSocketMessage(
- machineWs() as any,
- JSON.stringify({ type: "agent_session", agentId: "bot_2", sessionId: "s_b", launchId: "l_b" }),
- )
-
- expect(mockInsertBotAuditSessionReset).toHaveBeenCalledTimes(2)
- expect(mockInsertBotAuditSessionReset).toHaveBeenNthCalledWith(
- 1,
- expect.anything(),
- expect.objectContaining({ botId: "bot_1", launchId: "l_a", trigger: "reset_all" }),
- )
- expect(mockInsertBotAuditSessionReset).toHaveBeenNthCalledWith(
- 2,
- expect.anything(),
- expect.objectContaining({ botId: "bot_2", launchId: "l_b", trigger: "reset_all" }),
- )
- expect(mockTouchBotRefreshContext).toHaveBeenCalledTimes(2)
- })
-
- it("nap: agent_session writes nap audit (trigger nap) + stamps awake in lockstep + broadcasts", async () => {
- const { durable } = onlineDaemon()
- await pushFrame(durable, { type: "agent:nap", agentId: "bot_1", config: {}, launchId: "l_nap", handoff: "note" })
- await durable.webSocketMessage(
- machineWs() as any,
- JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_nap" }),
- )
-
- expect(mockInsertBotAuditNap).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({ botId: "bot_1", launchId: "l_nap" }),
- )
- expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
- expect(mockTouchBotRefreshContext).toHaveBeenCalledWith(expect.anything(), "bot_1", "2025-06-01T11:00:00.000Z")
- const body = JSON.parse(await (auditBroadcast()!).clone().text()) as Record<string, unknown>
- expect(body).toMatchObject({ kind: "nap", payload: { trigger: "nap" }, launchId: "l_nap" })
- })
-
- it("fire-once: a replayed agent_session for the same launch writes nothing the second time", async () => {
- const { durable } = onlineDaemon()
- await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
- const frame = JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" })
- await durable.webSocketMessage(machineWs() as any, frame)
- await durable.webSocketMessage(machineWs() as any, frame) // replay
-
- // Exactly one write despite two agent_session frames — the pending entry
- // was consumed (deleted) on the first.
- expect(mockInsertBotAuditSessionReset).toHaveBeenCalledTimes(1)
- expect(mockTouchBotRefreshContext).toHaveBeenCalledTimes(1)
- })
-
- it("no pending launch: an ordinary agent_session (never a reset/nap) writes nothing", async () => {
- const { durable, store } = createDO()
- seedIdentity(store)
- // No /push recorded this launch — a plain wake session.
- await durable.webSocketMessage(
- machineWs() as any,
- JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_plain" }),
- )
- expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
- expect(mockInsertBotAuditNap).not.toHaveBeenCalled()
- expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
- })
-
- it("offline push (sent===0): records no pending — later agent_session writes nothing", async () => {
- const { durable, store, getWebSockets } = createDO()
- seedIdentity(store)
- getWebSockets.mockReturnValue([])
- await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_offline" })
- await durable.webSocketMessage(
- machineWs() as any,
- JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_offline" }),
- )
- expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
- expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
- })
-
- // Cecilia #1270: landing must dispatch by pending.kind — provider stamps
- // awake; model does not; payloads stay in their namespaces.
- it("provider_switch: agent_session writes provider_changed {from,to} + stamps awake (not model_changed)", async () => {
- const { durable } = onlineDaemon()
- await pushSwitch(durable, "provider", {
- agentId: "bot_1",
- config: { runtime: "codex" },
- launchId: "l_prov",
- from: "claude",
- to: "codex",
- })
- await durable.webSocketMessage(
- machineWs() as any,
- JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_prov" }),
- )
-
- expect(mockInsertBotAuditProviderChanged).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({ botId: "bot_1", launchId: "l_prov", from: "claude", to: "codex" }),
- )
- expect(mockInsertBotAuditModelChanged).not.toHaveBeenCalled()
- expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
- expect(mockTouchBotRefreshContext).toHaveBeenCalledWith(expect.anything(), "bot_1", "2025-06-01T13:00:00.000Z")
- const body = JSON.parse(await (auditBroadcast()!).clone().text()) as Record<string, unknown>
- expect(body).toMatchObject({
- kind: "provider_changed",
- payload: { from: "claude", to: "codex" },
- launchId: "l_prov",
- })
- })
-
- // Cecilia #1279: provider PATCH clears model as a binding side-effect, but
- // landing must emit exactly one provider_changed — never a sibling model_changed.
- it("provider_switch with cleared model in config → exactly one provider_changed, zero model_changed", async () => {
- const { durable } = onlineDaemon()
- await pushSwitch(durable, "provider", {
- agentId: "bot_1",
- // Mirrors route after provider switch: runtime flipped + model null→default.
- config: { runtime: "codex", model: { kind: "default" } },
- launchId: "l_prov_clear_model",
- from: "claude",
- to: "codex",
- })
- await durable.webSocketMessage(
- machineWs() as any,
- JSON.stringify({
- type: "agent_session",
- agentId: "bot_1",
- sessionId: "s_new",
- launchId: "l_prov_clear_model",
- }),
- )
-
- expect(mockInsertBotAuditProviderChanged).toHaveBeenCalledTimes(1)
- expect(mockInsertBotAuditProviderChanged).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({
- botId: "bot_1",
- launchId: "l_prov_clear_model",
- from: "claude",
- to: "codex",
- }),
- )
- expect(mockInsertBotAuditModelChanged).not.toHaveBeenCalled()
- expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
- const broadcasts = mockStubFetch.mock.calls
- .map((c: any[]) => c[0] as Request)
- .filter((r: Request) => r.url.endsWith("/broadcast"))
- expect(broadcasts).toHaveLength(1)
- const body = JSON.parse(await broadcasts[0]!.clone().text()) as Record<string, unknown>
- expect(body.kind).toBe("provider_changed")
- expect(body.kind).not.toBe("model_changed")
- })
-
- it("model_switch: agent_session writes model_changed {from,to} and does NOT stamp awake", async () => {
- const { durable } = onlineDaemon()
- await pushSwitch(durable, "model", {
- agentId: "bot_1",
- config: { model: { kind: "named", name: "opus" } },
- launchId: "l_model",
- from: null,
- to: "opus",
- })
- await durable.webSocketMessage(
- machineWs() as any,
- JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_model" }),
- )
-
- expect(mockInsertBotAuditModelChanged).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({ botId: "bot_1", launchId: "l_model", from: null, to: "opus" }),
- )
- expect(mockInsertBotAuditProviderChanged).not.toHaveBeenCalled()
- expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
- const body = JSON.parse(await (auditBroadcast()!).clone().text()) as Record<string, unknown>
- expect(body).toMatchObject({
- kind: "model_changed",
- payload: { from: null, to: "opus" },
- launchId: "l_model",
- })
- })
-
- it("cold-start fail branch B (agent_wake_ack error): evicts pending, no audit/awake, and a later replayed agent_session stays silent", async () => {
- const { durable } = onlineDaemon()
- await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
- // Enroll fail / spawn threw → wake_ack error for this launch.
- await durable.webSocketMessage(
- machineWs() as any,
- JSON.stringify({ type: "agent_wake_ack", agentId: "bot_1", launchId: "l_reset", status: "error", error: { code: "spawn_threw", message: "boom" } }),
- )
- // If (impossibly) an agent_session arrives later, the entry is already gone
- // → nothing written. This is the red-line-② positive proof.
- await durable.webSocketMessage(
- machineWs() as any,
- JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" }),
- )
- expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
- expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
- })
-
- it("cold-start fail branch A (session.error runtime_not_available): evicts pending, no audit/awake", async () => {
- const { durable } = onlineDaemon()
- await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
- // Runtime not installed → session.error carrying the launchId (Melisa's source half).
- await durable.webSocketMessage(
- machineWs() as any,
- JSON.stringify({ type: "session.error", code: "runtime_not_available", agentId: "bot_1", launchId: "l_reset", payload: { requested: "codex", available: [] } }),
- )
- await durable.webSocketMessage(
- machineWs() as any,
- JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" }),
- )
- expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
- expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
- })
- })
-
- describe("community-machine — ready frame reconciles bot activity", () => {
- beforeEach(() => {
- mockUpsertMachineByMachineId.mockReset()
- mockReconcileBotActivityFromRunningAgents.mockReset().mockResolvedValue([])
- mockStubFetch.mockClear()
- })
-
- it("a ready frame whose runningAgents disagrees with persisted state fans out community:status.update for each cleared bot", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockUpsertMachineByMachineId.mockResolvedValue({
- machine: {
- id: "cm_1",
- hostname: "host",
- availableRuntimes: [],
- status: "online",
- lastSeenAt: "2026-07-13T00:00:00.000Z",
- },
- priorLastSeenAt: "2026-07-12T00:00:00.000Z",
- priorAvailableRuntimes: [],
- priorStatus: "online",
- })
- mockReconcileBotActivityFromRunningAgents.mockResolvedValue([
- { botUserId: "bot_1", statusEmoji: "💤", statusText: "Idle" },
- { botUserId: "bot_2", statusEmoji: "💤", statusText: "Idle" },
- ])
- mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({
- type: "ready",
- runtimeReport: [],
- runningAgents: [],
- })
- await durable.webSocketMessage(ws as any, frame)
-
- expect(mockReconcileBotActivityFromRunningAgents).toHaveBeenCalledWith(expect.anything(), "cm_1", [])
- const activityCalls = mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
- const bodies = await Promise.all(activityCalls.map((c: any[]) => (c[0] as Request).clone().text()))
- const parsed = bodies.map((b) => JSON.parse(b)).filter((b) => b.type === "community:status.update")
- expect(parsed).toEqual(
- expect.arrayContaining([
- { type: "community:status.update", userId: "bot_1", statusEmoji: "💤", statusText: "Idle" },
- { type: "community:status.update", userId: "bot_2", statusEmoji: "💤", statusText: "Idle" },
- ])
- )
- })
-
- it("emits no status.update fan-out when reconciliation finds no changes", async () => {
- const { durable, store } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- mockUpsertMachineByMachineId.mockResolvedValue({
- machine: {
- id: "cm_1",
- hostname: "host",
- availableRuntimes: [],
- status: "online",
- lastSeenAt: "2026-07-13T00:00:00.000Z",
- },
- priorLastSeenAt: "2026-07-12T00:00:00.000Z",
- priorAvailableRuntimes: [],
- priorStatus: "online",
- })
- mockReconcileBotActivityFromRunningAgents.mockResolvedValue([])
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- const frame = JSON.stringify({ type: "ready", runtimeReport: [], runningAgents: [] })
- await durable.webSocketMessage(ws as any, frame)
-
- const activityCalls = mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
- const bodies = await Promise.all(activityCalls.map((c: any[]) => (c[0] as Request).clone().text()))
- const parsed = bodies.map((b) => JSON.parse(b)).filter((b) => b.type === "community:status.update")
- expect(parsed).toEqual([])
- })
- })
-
- describe("community-machine — webSocketClose presence lifecycle", () => {
- // These tests cover the "graceful daemon quit → immediate offline" fix.
- // See plans/community-machine-presence-fix.md § Server transitions.
- it("flips status=offline via credential-scoped markMachineOffline and broadcasts on real transition", async () => {
- const { durable, store, ctx } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- // Arm a placeholder alarm so we can check deleteAlarm ran.
- await ctx.storage.setAlarm(Date.now() + 90_000)
- mockMarkMachineOffline.mockResolvedValueOnce({
- id: "cm_1",
- userId: "u_1",
- status: "offline",
- lastSeenAt: "2026-07-06T00:00:00.000Z",
- })
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- await durable.webSocketClose(ws as any)
-
- expect(mockMarkMachineOffline).toHaveBeenCalledTimes(1)
- const [, args] = mockMarkMachineOffline.mock.calls[0]!
- expect(args).toMatchObject({
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "0".repeat(64),
- })
- // Broadcast fired via notifyUserDO → user DO's /broadcast endpoint.
- expect(mockStubFetch).toHaveBeenCalled()
- // Alarm was cleaned up and storage keys deleted.
- expect(ctx.storage.deleteAlarm).toHaveBeenCalled()
- expect(store.has("community-machine-identity")).toBe(false)
- expect(store.has("community-machine-handle")).toBe(false)
- })
-
- it("null return (credential revoked or already offline) does NOT broadcast and leaves the alarm armed", async () => {
- const { durable, store, ctx } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "revoked",
- })
- mockMarkMachineOffline.mockResolvedValueOnce(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- mockStubFetch.mockClear()
- await durable.webSocketClose(ws as any)
-
- expect(mockMarkMachineOffline).toHaveBeenCalledTimes(1)
- // No broadcast fired — the guarded UPDATE returned zero rows.
- expect(mockStubFetch).not.toHaveBeenCalled()
- // Alarm armed as the safety-net fallback (setAlarm was called; not deleted).
- expect(ctx.storage.setAlarm).toHaveBeenCalled()
- expect(ctx.storage.deleteAlarm).not.toHaveBeenCalled()
- // Storage keys retained — a different DO instance may own the row now.
- expect(store.has("community-machine-identity")).toBe(true)
- })
-
- it("missing IDENTITY_KEY (never fully accepted) is a clean no-op — no markMachineOffline, no alarm", async () => {
- const { durable, store, ctx } = createDO()
- // No identity in storage.
- expect(store.has("community-machine-identity")).toBe(false)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
-
- // Clear any setAlarm calls made during createDO setup.
- ; (ctx.storage.setAlarm as any).mockClear?.()
-
- await durable.webSocketClose(ws as any)
-
- expect(mockMarkMachineOffline).not.toHaveBeenCalled()
- // No alarm armed — with no identity there's nothing recoverable to do.
- // HANDLE_KEY is written alongside IDENTITY_KEY, so if identity is gone
- // the alarm has no state to act on either.
- expect(ctx.storage.setAlarm).not.toHaveBeenCalled()
- })
- })
-
- describe("community-machine — alarm presence + backfill", () => {
- it("live-WS + status=offline row: markMachineOnlineIfOffline flips it back online and broadcasts (post-deploy backfill)", async () => {
- const { durable, store, getWebSockets, ctx } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "abc",
- })
-
- // Attach a live authenticated community-machine WS.
- const ws = createMockWebSocket()
- ws.serializeAttachment({
- type: "community-machine",
- machineId: "cm_1",
- userId: "u_1",
- authenticated: true,
- })
- getWebSockets.mockReturnValue([ws])
-
- mockTouchMachineHeartbeat.mockResolvedValueOnce({
- lastSeenAt: "now",
- priorLastSeenAt: "earlier",
- })
- mockMarkMachineOnlineIfOffline.mockResolvedValueOnce({
- id: "cm_1",
- userId: "u_1",
- status: "online",
- lastSeenAt: "now",
- })
-
- mockStubFetch.mockClear()
- await durable.alarm()
-
- expect(mockTouchMachineHeartbeat).toHaveBeenCalledTimes(1)
- expect(mockMarkMachineOnlineIfOffline).toHaveBeenCalledTimes(1)
- // Broadcast fired for the offline→online transition.
- expect(mockStubFetch).toHaveBeenCalled()
- // Alarm rescheduled for the next heartbeat tick.
- expect(ctx.storage.setAlarm).toHaveBeenCalled()
- })
-
- it("live-WS + status=online row (steady state): no broadcast fires (double-broadcast regression guard)", async () => {
- const { durable, store, getWebSockets, ctx } = createDO()
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "abc",
- })
+describe("WebSocketDurableObject", () => {
+ beforeEach(() => resetHarness())
+ afterEach(() => cleanupHarness())
+ describe("C2c characterization — machine frames", () => {
+ function machineWs() {
const ws = createMockWebSocket()
ws.serializeAttachment({
type: "community-machine",
@@ -2551,268 +22,21 @@ describe("WebSocketDurableObject", () => {
userId: "u_1",
authenticated: true,
})
- getWebSockets.mockReturnValue([ws])
-
- mockTouchMachineHeartbeat.mockResolvedValueOnce({
- lastSeenAt: "now",
- priorLastSeenAt: "earlier",
- })
- // Guarded UPDATE returns zero rows — row is already online.
- mockMarkMachineOnlineIfOffline.mockResolvedValueOnce(null)
-
- mockStubFetch.mockClear()
- await durable.alarm()
-
- expect(mockTouchMachineHeartbeat).toHaveBeenCalledTimes(1)
- // No broadcast — the guarded UPDATE returned zero rows.
- expect(mockStubFetch).not.toHaveBeenCalled()
- // Alarm rescheduled.
- expect(ctx.storage.setAlarm).toHaveBeenCalled()
- })
-
- it("no-live-WS + stale row: markMachineOffline flips + broadcasts + cleans HANDLE_KEY / IDENTITY_KEY", async () => {
- const { durable, store, getWebSockets, ctx } = createDO()
- // No live WS.
- getWebSockets.mockReturnValue([])
- store.set("community-machine-handle", { userId: "u_1", machineId: "cm_1" })
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "abc",
- })
- // Stale row — lastSeenAt is more than 120s (mocked threshold) ago.
- mockGetMachineByIdForUser.mockResolvedValueOnce({
- id: "cm_1",
- userId: "u_1",
- status: "online",
- lastSeenAt: new Date(Date.now() - 200_000).toISOString(),
- availableRuntimes: [],
- })
- mockMarkMachineOffline.mockResolvedValueOnce({
- id: "cm_1",
- userId: "u_1",
- status: "offline",
- lastSeenAt: "now",
- })
-
- mockStubFetch.mockClear()
- await durable.alarm()
-
- expect(mockMarkMachineOffline).toHaveBeenCalledTimes(1)
- expect(mockStubFetch).toHaveBeenCalled()
- expect(store.has("community-machine-handle")).toBe(false)
- expect(store.has("community-machine-identity")).toBe(false)
- // No further alarm reschedule after the terminal offline flip.
- // (setAlarm may have been called on the earlier setup path; we assert
- // deleteAlarm was NOT called since alarm() doesn't need to explicitly
- // delete — it just doesn't reschedule.)
- expect(ctx.storage.deleteAlarm).not.toHaveBeenCalled()
- })
-
- it("no-live-WS + stale row + no identity (mid-lifecycle wipe): still broadcasts offline using stored handle so UI sees the transition", async () => {
- const { durable, store, getWebSockets, ctx } = createDO()
- getWebSockets.mockReturnValue([])
- // HANDLE_KEY is present (written at accept) but IDENTITY_KEY was
- // wiped mid-lifecycle. The stale-flip branch can't run the
- // credential-scoped UPDATE, but must still broadcast so the UI
- // reflects the transition.
- store.set("community-machine-handle", { userId: "u_1", machineId: "cm_1" })
- expect(store.has("community-machine-identity")).toBe(false)
-
- mockGetMachineByIdForUser.mockResolvedValueOnce({
- id: "cm_1",
- userId: "u_1",
- status: "online",
- lastSeenAt: new Date(Date.now() - 200_000).toISOString(),
- availableRuntimes: [],
- })
-
- mockStubFetch.mockClear()
- await durable.alarm()
-
- // DB flip skipped (no identity to scope the credential guard).
- expect(mockMarkMachineOffline).not.toHaveBeenCalled()
- // But the UI broadcast MUST still fire — otherwise the machine
- // chip stays green until reload.
- expect(mockStubFetch).toHaveBeenCalled()
- // Storage keys dropped — this DO's presence lifecycle is done.
- expect(store.has("community-machine-handle")).toBe(false)
- expect(ctx.storage.deleteAlarm).not.toHaveBeenCalled()
- })
-
- it("no-live-WS + fresh row: reschedules alarm to exact stale moment, no broadcast, no DB flip", async () => {
- const { durable, store, getWebSockets, ctx } = createDO()
- getWebSockets.mockReturnValue([])
- store.set("community-machine-handle", { userId: "u_1", machineId: "cm_1" })
- store.set("community-machine-identity", {
- userId: "u_1",
- machineId: "cm_1",
- credentialHash: "abc",
- })
- // Fresh row — lastSeenAt is 10s ago.
- mockGetMachineByIdForUser.mockResolvedValueOnce({
- id: "cm_1",
- userId: "u_1",
- status: "online",
- lastSeenAt: new Date(Date.now() - 10_000).toISOString(),
- availableRuntimes: [],
- })
-
- mockStubFetch.mockClear()
- await durable.alarm()
-
- expect(mockMarkMachineOffline).not.toHaveBeenCalled()
- expect(mockStubFetch).not.toHaveBeenCalled()
- // Storage keys retained; alarm rescheduled precisely to the stale moment.
- expect(store.has("community-machine-handle")).toBe(true)
- expect(store.has("community-machine-identity")).toBe(true)
- expect(ctx.storage.setAlarm).toHaveBeenCalled()
- })
- })
-
- describe("webSocketMessage — community:typing.start authz (fanOutTyping)", () => {
- // fanOutTyping runs fire-and-forget (`.catch()`, not awaited) inside
- // webSocketMessage, so `await durable.webSocketMessage(...)` alone
- // doesn't guarantee its internal DB-then-broadcast chain has settled.
- // Flush a macrotask so all pending microtasks (getDM/getChannelForMember
- // → listMembers → Promise.all(fetch)) drain before asserting.
- const flush = () => new Promise((resolve) => setTimeout(resolve, 0))
-
- it("does not fan out or broadcast when sender is not a member of the target channel", async () => {
- const { durable, env } = createDO()
- mockGetChannelForMember.mockResolvedValueOnce(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "chan-private" }),
- )
- await flush()
-
- expect(mockGetChannelForMember).toHaveBeenCalledWith(expect.anything(), "chan-private", "attacker")
- expect(mockListMembers).not.toHaveBeenCalled()
- expect((env.WS_DO as any).get).not.toHaveBeenCalled()
- expect(mockStubFetch).not.toHaveBeenCalled()
- })
-
- it("fans out to other server members when sender IS a channel member", async () => {
- const { durable, env } = createDO()
- mockGetChannelForMember.mockResolvedValueOnce({ id: "chan-1", serverId: "server-1" })
- // Recipient resolution now goes through the shared member resolver — a
- // public channel resolves to every server member (sender included).
- mockResolveScopeMemberUserIds.mockResolvedValueOnce(["member-1", "member-2", "sender-1"])
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "chan-1" }),
- )
- await flush()
-
- expect(mockGetChannelForMember).toHaveBeenCalledWith(expect.anything(), "chan-1", "sender-1")
- expect(mockResolveScopeMemberUserIds).toHaveBeenCalledWith(expect.anything(), {
- scope: "channel",
- scopeId: "chan-1",
- })
- // Sender is excluded from recipients — only the other 2 members get a broadcast POST.
- expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:member-1")
- expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:member-2")
- expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:sender-1")
- expect(mockStubFetch).toHaveBeenCalledTimes(2)
- })
-
- it("private channel: fans out to the channel audience, not all server members", async () => {
- const { durable, env } = createDO()
- mockGetChannelForMember.mockResolvedValueOnce({ id: "chan-p", serverId: "server-1" })
- // The resolver applies the public/private split internally — a private
- // channel resolves to its audience (creator + added member + admin).
- mockResolveScopeMemberUserIds.mockResolvedValueOnce(["sender-1", "member-1"])
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "chan-p" }),
- )
- await flush()
-
- expect(mockResolveScopeMemberUserIds).toHaveBeenCalledWith(expect.anything(), {
- scope: "channel",
- scopeId: "chan-p",
- })
- expect(mockListMembers).not.toHaveBeenCalled()
- // Only the non-sender audience member gets a broadcast POST.
- expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:member-1")
- expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:sender-1")
- expect(mockStubFetch).toHaveBeenCalledTimes(1)
- })
-
- it("thread: typing fans out to PARTICIPANTS, not the channel audience", async () => {
- const { durable, env } = createDO()
- mockGetChannelForMember.mockResolvedValueOnce({ id: "t-1", serverId: "server-1" })
- mockGetChannelType.mockResolvedValueOnce("thread")
- mockListThreadParticipantUserIds.mockResolvedValueOnce(["sender-1", "part-1"])
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "t-1" }),
- )
- await flush()
-
- expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith(expect.anything(), "t-1")
- // Thread typing must NOT fall back to the channel-audience resolver.
- expect(mockResolveScopeMemberUserIds).not.toHaveBeenCalled()
- expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:part-1")
- expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:sender-1")
- expect(mockStubFetch).toHaveBeenCalledTimes(1)
- })
-
- it("does not fan out when sender is not a participant of the target DM", async () => {
- const { durable, env } = createDO()
- // A DM is a type=dm channel now; a non-member sender can't see it, so
- // getChannelForMember returns null and fanOutTyping bails.
- mockGetChannelForMember.mockResolvedValueOnce(null)
-
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })
-
- await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "dm-1" }),
- )
- await flush()
-
- expect(mockGetChannelForMember).toHaveBeenCalledWith(expect.anything(), "dm-1", "attacker")
- expect((env.WS_DO as any).get).not.toHaveBeenCalled()
- expect(mockStubFetch).not.toHaveBeenCalled()
- })
-
- it("fans out to the other participant when sender IS a DM participant", async () => {
- const { durable, env } = createDO()
- mockGetChannelForMember.mockResolvedValueOnce({ id: "dm-1", serverId: null })
- mockGetChannelType.mockResolvedValueOnce("dm")
- mockListChannelMemberUserIds.mockResolvedValueOnce(["alice", "bob"])
+ return ws
+ }
- const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true })
+ it("drops inbound frames before parsing when the cached identity is missing", async () => {
+ const { durable, storage } = createDO()
await durable.webSocketMessage(
- ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "dm-1" }),
+ machineWs() as any,
+ JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" }),
)
- await flush()
- expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:bob")
- expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:alice")
- expect(mockStubFetch).toHaveBeenCalledTimes(1)
+ expect(storage.get).toHaveBeenCalledWith("community-machine-identity")
+ expect(mockGetBotBinding).not.toHaveBeenCalled()
+ expect(mockUpdateProfile).not.toHaveBeenCalled()
+ expect(mockLogWarn).toHaveBeenCalledWith("community machine message with no cached identity")
})
})
})
diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.ts
index f141bf4f8..1c45cbdf2 100644
--- a/src/ws-do/src/ws-durable.ts
+++ b/src/ws-do/src/ws-durable.ts
@@ -1,99 +1,39 @@
import { DurableObject } from "cloudflare:workers"
+import { createLogger } from "@alook/shared"
+import type { WsDurableContext } from "./ws-durable/internal"
import {
- createDb,
- queries,
- createLogger,
- readOrStale,
- COMMUNITY_MACHINE_HEARTBEAT_MS,
- COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS,
- HostReadyMessageSchema,
- SessionErrorFrameSchema,
- AgentActivityMessageSchema,
- AgentTypingMessageSchema,
- AgentTypingStopMessageSchema,
- AgentSessionMessageSchema,
- HostBotAuditEventFrameSchema,
- pickBotActivityPreset,
- RUNNING_PRESETS,
- isBotActivityStatus,
- channelReach,
- isStoredChannelType,
- WS_EVENTS,
- withD1Retry,
-} from "@alook/shared"
-import type { CommunityMachineRuntime, CommunityMachineSummary } from "@alook/shared"
-
-/**
- * Order-normalized JSON for comparing two runtime lists. Includes `status`
- * and `lastError` in the canonical form so a runtime flipping healthy →
- * unhealthy (with the same id + version) still trips the diff and fans out
- * `community:machine.updated`. See plans/community-machine-presence-fix.md.
- */
-function canonicalRuntimes(list: CommunityMachineRuntime[]): string {
- const sorted = [...list].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
- return JSON.stringify(
- sorted.map((r) => ({
- id: r.id,
- ...(r.version !== undefined ? { version: r.version } : {}),
- status: r.status ?? "healthy",
- ...(r.lastError !== undefined ? { lastError: r.lastError } : {}),
- }))
- )
-}
+ acceptUserWebSocket,
+ handleUserFetch,
+ handleWebSocketClose,
+ handleWebSocketError,
+ handleWebSocketMessage,
+} from "./ws-durable/user-auth"
+import {
+ broadcastPresence,
+ broadcastToAudience,
+ fanOutTyping,
+ fanOutTypingStop,
+ getPresenceAudience,
+ notifyUserDO,
+ sendPresenceSnapshot,
+} from "./ws-durable/presence-typing"
+import {
+ acceptCommunityMachineWebSocket,
+ handleMachineControlFetch,
+} from "./ws-durable/machine-control"
+import {
+ handleCommunityMachineClose,
+ handleMachineAlarm,
+} from "./ws-durable/machine-lifecycle"
+import { handleCommunityMachineMessage } from "./ws-durable/machine-frames"
+import { recordPendingRestarts } from "./ws-durable/machine-restart"
+import {
+ clearRuntimeErrorOverlay,
+ fanOutMachineUpdated,
+} from "./ws-durable/machine-ready"
const log = createLogger({ service: "ws-do" })
-type ConnectionState =
- | { type: "user"; userId: string; authenticated: boolean; name?: string; discriminator?: string }
- | { type: "daemon"; daemonId: string; userId: string; authenticated: boolean }
- | {
- type: "community-machine"
- machineId: string
- userId: string
- authenticated: boolean
- }
-
-/**
- * Persisted identity for the community-machine connection. Written once at
- * accept and read by every subsequent frame + alarm — the DB is only touched
- * for the ONE authentication lookup, not for each `ready`/heartbeat.
- */
-interface CommunityMachineIdentity {
- userId: string
- machineId: string
- credentialHash: string
-}
-
-interface CommunityMachineHandle {
- userId: string
- machineId: string
-}
-
-/** DO storage keys. */
-const IDENTITY_KEY = "community-machine-identity"
-const HANDLE_KEY = "community-machine-handle"
-const RUNTIME_ERROR_KEY = "community-machine-runtime-error"
-// Per-launch restart attribution. Written only when a reset, nap, model switch,
-// or provider switch reaches this machine's daemon; read + deleted when the
-// resulting `agent_session` lands. ctx.storage, NOT an
-// in-memory Map: the DO can hibernate between dispatch and agent_session, and
-// a dropped entry would make a real reset silently write nothing (fire-once
-// reads it as "never dispatched"). See plans/reset-nap-completion-rehome.md §6.
-const RESTART_PENDING_PREFIX = "reset-pending:"
-const restartPendingKey = (launchId: string) => RESTART_PENDING_PREFIX + launchId
-
-type ResetTrigger = "single" | "reset_all" | "nap"
-type RestartAttribution =
- | { kind: "session_reset"; trigger: "single" | "reset_all" }
- | { kind: "nap" }
- | { kind: "model_switch"; from: string | null; to: string | null }
- | { kind: "provider_switch"; from: string; to: string }
-
-function normalizeRestartAttribution(value: ResetTrigger | RestartAttribution): RestartAttribution {
- if (typeof value !== "string") return value
- return value === "nap" ? { kind: "nap" } : { kind: "session_reset", trigger: value }
-}
-
export class WebSocketDurableObject extends DurableObject<Env> {
/**
* Ephemeral typing dedup: channelId -> userId -> last timestamp.
@@ -104,170 +44,37 @@ export class WebSocketDurableObject extends DurableObject<Env> {
/** Typing dedup window: 8 seconds */
private static readonly TYPING_DEDUP_MS = 8_000
- async fetch(request: Request): Promise<Response> {
- const url = new URL(request.url)
-
- if (url.pathname === "/broadcast" && request.method === "POST") {
- const body = await request.text()
- const sent = this.broadcast(body)
- return new Response(JSON.stringify({ sent }), {
- headers: { "Content-Type": "application/json" },
- })
- }
-
- if (url.pathname === "/check-alive") {
- const hasAuthDaemon = this.ctx.getWebSockets().some(ws => {
- const s = ws.deserializeAttachment() as ConnectionState
- return s?.type === "daemon" && s.authenticated
- })
- return new Response(JSON.stringify({ alive: hasAuthDaemon }), {
- headers: { "Content-Type": "application/json" },
- })
- }
-
- if (url.pathname === "/check-user-online") {
- // This DO instance is keyed by `user:<targetUserId>` (see `idFromName`
- // at every call site below), but a DO can't recover its own name from
- // `ctx` on this worker's pinned compatibility_date (see
- // plans/community-account-debt-fixes.md Fix 3) — so the caller passes
- // the id explicitly instead. A bot has no WebSocket of its own; its
- // "online" is `isBotOnline` (bound machine's status), not a live-socket
- // check.
- //
- // Check the local WS attachments FIRST — that's D1-free, and a live
- // authenticated user socket is authoritative "online" regardless of
- // whether the target turns out to be a bot. Only when no live socket
- // is attached do we consult D1 to see if this is a bot whose presence
- // is derived from a bound machine's status.
- //
- // D1 reads fail-closed via `readOrStale`: a transient outage on the
- // bot branch yields `{ online: false, stale: true }`. The live-WS
- // early return is unaffected — a D1 blip must NOT flip a real,
- // connected human user offline.
- const targetUserId = url.searchParams.get("userId")
- const hasAuthUser = this.ctx.getWebSockets().some(ws => {
- const s = ws.deserializeAttachment() as ConnectionState
- return s?.type === "user" && s.authenticated
- })
- if (hasAuthUser) {
- return new Response(JSON.stringify({ online: true }), {
- headers: { "Content-Type": "application/json" },
- })
- }
- if (targetUserId) {
- const db = createDb(this.env.DB)
- const { value, stale } = await readOrStale<{ isBotResolved: boolean; online: boolean }>(
- async () => {
- const target = await queries.user.getUserInternal(db, targetUserId)
- if (target?.isBot) {
- const online = await queries.communityMachine.isBotOnline(db, targetUserId)
- return { isBotResolved: true, online }
- }
- return { isBotResolved: false, online: false }
- },
- { isBotResolved: false, online: false },
- { route: "ws-do/check-user-online" },
- )
- if (stale) {
- return new Response(JSON.stringify({ online: false, stale: true }), {
- headers: { "Content-Type": "application/json" },
- })
- }
- if (value.isBotResolved) {
- return new Response(JSON.stringify({ online: value.online }), {
- headers: { "Content-Type": "application/json" },
- })
- }
- }
- return new Response(JSON.stringify({ online: false }), {
- headers: { "Content-Type": "application/json" },
- })
- }
-
- if (url.pathname === "/force-close" && request.method === "POST") {
- const closed = await this.forceCloseCommunityMachine()
- return new Response(JSON.stringify({ closed }), {
- headers: { "Content-Type": "application/json" },
- })
- }
+ private static readonly SUBREQUEST_BATCH_SIZE = 40
- if (url.pathname === "/push" && request.method === "POST") {
- // Forward a bot:* frame (or any host-command frame) to the connected
- // daemon. Best-effort — if the daemon isn't connected, drops silently.
- // Cold-start warmup on reconnect re-syncs authoritative state.
- const body = await request.text()
- // Reset/nap/reset_all frames pass through here on their way to the daemon.
- // Persist attribution only when at least one daemon socket received them.
- // Starting the storage write before yielding keeps a fast completion
- // behind the Durable Object input gate.
- const sent = this.forwardToCommunityMachine(body)
- if (sent > 0) await this.recordPendingRestarts(body)
- return new Response(JSON.stringify({ sent }), {
- headers: { "Content-Type": "application/json" },
- })
+ private domainContext(): WsDurableContext {
+ return {
+ ctx: this.ctx,
+ env: this.env,
+ log,
+ typingDedup: this.typingDedup,
+ typingDedupMs: WebSocketDurableObject.TYPING_DEDUP_MS,
+ subrequestBatchSize: WebSocketDurableObject.SUBREQUEST_BATCH_SIZE,
}
+ }
- if (
- request.method === "POST" &&
- (url.pathname === "/push-model-switch" || url.pathname === "/push-provider-switch")
- ) {
- let payload: unknown
- try {
- payload = await request.json()
- } catch {
- return new Response(JSON.stringify({ sent: 0 }), { status: 400 })
- }
- if (!payload || typeof payload !== "object") {
- return new Response(JSON.stringify({ sent: 0 }), { status: 400 })
- }
- const raw = payload as Record<string, unknown>
- const { agentId, config, launchId, from, to } = raw
- if (
- typeof agentId !== "string" || agentId.length === 0 ||
- typeof launchId !== "string" || launchId.length === 0 ||
- !config || typeof config !== "object"
- ) {
- return new Response(JSON.stringify({ sent: 0 }), { status: 400 })
- }
- const providerSwitch = url.pathname === "/push-provider-switch"
- if (
- providerSwitch
- ? typeof from !== "string" || from.length === 0 || typeof to !== "string" || to.length === 0
- : (from !== null && typeof from !== "string") || (to !== null && typeof to !== "string")
- ) {
- return new Response(JSON.stringify({ sent: 0 }), { status: 400 })
- }
- const frame = JSON.stringify({
- type: providerSwitch ? "agent:reset" : "agent:model_switch",
- agentId,
- config,
- launchId,
- })
- const sent = this.forwardToCommunityMachine(frame)
- if (sent > 0) {
- const attribution: RestartAttribution = providerSwitch
- ? { kind: "provider_switch", from: from as string, to: to as string }
- : { kind: "model_switch", from: from as string | null, to: to as string | null }
- await this.ctx.storage.put<RestartAttribution>(restartPendingKey(launchId), attribution)
- }
- return new Response(JSON.stringify({ sent }), {
- headers: { "Content-Type": "application/json" },
- })
- }
+ async fetch(request: Request): Promise<Response> {
+ const url = new URL(request.url)
- if (url.pathname === "/forward-agent-wake" && request.method === "POST") {
- // Forward an `agent:wake` frame to the connected daemon and clear
- // any lastRuntimeError overlay optimistically (with a fan-out) so the
- // web card stops rendering the stale error immediately. If the daemon
- // replies with another `session.error`, the overlay is re-stashed on
- // the next inbound frame.
- const body = await request.text()
- const sent = this.forwardToCommunityMachine(body)
- await this.clearRuntimeErrorOverlay().catch(() => { })
- return new Response(JSON.stringify({ sent }), {
- headers: { "Content-Type": "application/json" },
- })
- }
+ const userResponse = await handleUserFetch(this.domainContext(), request, url)
+ if (userResponse) return userResponse
+
+ const machineResponse = await handleMachineControlFetch(
+ this.domainContext(),
+ request,
+ url,
+ {
+ recordPendingRestarts: (body) => recordPendingRestarts(this.domainContext(), body),
+ clearRuntimeErrorOverlay: () => clearRuntimeErrorOverlay(this.domainContext()),
+ fanOutMachineUpdated: (userId, machineId) =>
+ fanOutMachineUpdated(this.domainContext(), userId, machineId),
+ },
+ )
+ if (machineResponse) return machineResponse
if (request.headers.get("Upgrade") !== "websocket") {
return new Response("Expected WebSocket", { status: 426 })
@@ -280,1266 +87,47 @@ export class WebSocketDurableObject extends DurableObject<Env> {
// ctx.storage for the rest of the connection's life.
const authHeader = request.headers.get("Authorization")
if (authHeader?.startsWith("Bearer cmk_")) {
- return this.acceptCommunityMachine(authHeader.slice(7).trim())
- }
-
- const pair = new WebSocketPair()
- const [client, server] = Object.values(pair)
-
- this.ctx.acceptWebSocket(server)
-
- server.serializeAttachment({ type: "user", userId: "", authenticated: false } as ConnectionState)
-
- this.ctx.setWebSocketAutoResponse(
- new WebSocketRequestResponsePair("ping", "pong")
- )
-
- return new Response(null, { status: 101, webSocket: client })
- }
-
- private async acceptCommunityMachine(bearer: string): Promise<Response> {
- // Look up by full sha256 hash. Cached identity in ctx.storage lets every
- // subsequent frame skip D1 entirely. On network flake the DB throws —
- // reject with 503 so the daemon reconnects via the normal path.
- const db = createDb(this.env.DB)
- const hash = await queries.communityMachine.hashCredential(bearer)
- let auth: {
- credentialId: string
- userId: string
- machineId: string
- credentialHash: string
- doName: string
- } | null = null
- try {
- auth = await queries.communityMachine.findCredentialByHash(db, hash)
- } catch (err) {
- log.warn("community machine auth lookup threw", { err: String(err) })
- return new Response("auth lookup unavailable", { status: 503 })
- }
- if (!auth) {
- // 401 BEFORE `acceptWebSocket` — no socket enters ready state, no
- // alarm scheduled, no ctx.storage writes.
- return new Response("credential revoked or unknown", { status: 401 })
- }
-
- const pair = new WebSocketPair()
- const [client, server] = Object.values(pair)
- this.ctx.acceptWebSocket(server)
-
- server.serializeAttachment({
- type: "community-machine",
- machineId: auth.machineId,
- userId: auth.userId,
- authenticated: true,
- } as ConnectionState)
-
- const identity: CommunityMachineIdentity = {
- userId: auth.userId,
- machineId: auth.machineId,
- credentialHash: auth.credentialHash,
- }
- await this.ctx.storage.put(IDENTITY_KEY, identity)
- // Write the offline-detection handle at accept, BEFORE arming the alarm,
- // so `alarm()` can always resolve identity even if `ready` never lands.
- await this.ctx.storage.put<CommunityMachineHandle>(HANDLE_KEY, {
- userId: auth.userId,
- machineId: auth.machineId,
- })
-
- // Note: do NOT setWebSocketAutoResponse — the daemon uses WS-protocol
- // pings, which CF runtime answers transparently.
- await this.scheduleHeartbeatAlarm()
-
- return new Response(null, { status: 101, webSocket: client })
- }
-
- /**
- * Close every community-machine attachment and drop cached identity /
- * runtime-error state, then fan out a `machine.updated` clearing the
- * lastRuntimeError overlay. Called via /force-close from the web-side
- * revoke path (which resolves the DO name from `credential.do_name`).
- */
- private async forceCloseCommunityMachine(): Promise<number> {
- const identity = await this.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)
- let closed = 0
- for (const ws of this.ctx.getWebSockets()) {
- const s = ws.deserializeAttachment() as ConnectionState
- if (s?.type === "community-machine") {
- try {
- ws.send(JSON.stringify({ type: "error", code: "AUTH_REJECTED" }))
- ws.close(1008, "Revoked")
- closed++
- } catch { /* ok */ }
- }
- }
- // Drop cached state so a future accept-then-reject leaves nothing behind.
- await this.ctx.storage.delete(IDENTITY_KEY)
- await this.ctx.storage.delete(HANDLE_KEY)
- const hadError = (await this.ctx.storage.get(RUNTIME_ERROR_KEY)) !== undefined
- await this.ctx.storage.delete(RUNTIME_ERROR_KEY)
- // If we knew the user, clear any stale lastRuntimeError overlay from the
- // web card by re-fanning the summary with no overlay.
- if (identity && hadError) {
- await this.fanOutMachineUpdated(identity.userId, identity.machineId).catch(() => { })
+ return acceptCommunityMachineWebSocket(this.domainContext(), authHeader.slice(7).trim())
}
- return closed
- }
- private rejectCommunityMachine(ws: WebSocket, reason: string): void {
- try {
- ws.send(JSON.stringify({ type: "error", code: "AUTH_REJECTED", reason }))
- } catch { /* ok */ }
- try { ws.close(1008, "Unauthorized") } catch { /* ok */ }
- }
-
- private async scheduleHeartbeatAlarm(): Promise<void> {
- const current = await this.ctx.storage.getAlarm()
- const want = Date.now() + COMMUNITY_MACHINE_HEARTBEAT_MS
- if (current == null || current > want) {
- await this.ctx.storage.setAlarm(want)
- }
+ return acceptUserWebSocket(this.domainContext())
}
async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
- if (typeof message !== "string") return
-
- let parsed: unknown
- try { parsed = JSON.parse(message) } catch { ws.close(1008, "Invalid JSON"); return }
-
- const state = ws.deserializeAttachment() as ConnectionState
-
- if (state?.type === "community-machine") {
- await this.handleCommunityMachineMessage(parsed)
- return
- }
-
- const msg = parsed as { type: string; token?: string; machineToken?: string; daemonId?: string }
-
- if (msg.type === "auth") {
- if (msg.machineToken && msg.daemonId) {
- const authResult = await this.validateMachineToken(msg.machineToken, msg.daemonId)
- if (authResult.kind === "invalid") {
- // Definitely-dead token — tell the daemon so it stops using it
- // (AUTH_REJECTED is its trigger to mark the workspace auth-failed),
- // then close.
- log.warn("daemon websocket auth rejected", { daemonId: msg.daemonId })
- try { ws.send(JSON.stringify({ type: "error", code: "AUTH_REJECTED" })) } catch { /* ok */ }
- ws.close(1008, "Unauthorized")
- return
- }
- if (authResult.kind === "transient") {
- // Infra blip, not a token problem. Plain close (NO AUTH_REJECTED)
- // so the daemon reconnects with backoff and does not drop the
- // workspace.
- log.warn("daemon websocket auth transient failure", { daemonId: msg.daemonId })
- ws.close(1011, "Auth temporarily unavailable")
- return
- }
- ws.serializeAttachment({ type: "daemon", daemonId: msg.daemonId, userId: authResult.userId, authenticated: true } as ConnectionState)
- log.info("daemon websocket authenticated", { daemonId: msg.daemonId })
- ws.send(JSON.stringify({ type: "auth.ok" }))
-
- this.notifyUserDO(authResult.userId, { type: "runtime.status", status: "online", daemonId: msg.daemonId }).catch(() => { })
- return
- }
-
- if (!msg.token) {
- ws.close(1008, "Unauthorized")
- return
- }
- const identity = await this.validateToken(msg.token)
- if (!identity) {
- log.warn("websocket auth failed")
- ws.close(1008, "Unauthorized")
- return
- }
- const { userId, name, discriminator } = identity
- const wasOnline = this.countAuthenticatedUserConnections(userId) > 0
- ws.serializeAttachment({ type: "user", userId, authenticated: true, name, discriminator } as ConnectionState)
- log.info("websocket authenticated", { userId })
- ws.send(JSON.stringify({ type: "auth.ok" }))
- if (!wasOnline) {
- this.broadcastPresence(userId, true).catch(() => { })
- }
- // Send presence snapshot of online co-members + friends
- this.sendPresenceSnapshot(ws, userId).catch(() => { })
- return
- }
-
- if (!state.authenticated) {
- ws.close(1008, "Not authenticated")
- return
- }
-
- if (msg.type === "check_daemon_status" && state.type === "user") {
- const daemonId = await this.getDaemonIdForUser(state.userId)
- if (daemonId) {
- try {
- const daemonDoId = this.env.WS_DO.idFromName("daemon:" + daemonId)
- const daemonStub = this.env.WS_DO.get(daemonDoId)
- const resp = await daemonStub.fetch(new Request("http://internal/check-alive"))
- const { alive } = await resp.json() as { alive: boolean }
- if (alive) {
- ws.send(JSON.stringify({ type: "runtime.status", status: "online", daemonId }))
- }
- } catch {
- log.debug("check_daemon_status: failed to reach daemon DO", { daemonId })
- }
- }
- return
- }
-
- // ── Community: typing.start — dedup and fan-out ─────────────────────────
- if (msg.type === WS_EVENTS.TYPING_START && state.type === "user") {
- const typingMsg = parsed as {
- type: string
- channelId?: string
- }
- const scopeKey = typingMsg.channelId
- if (!scopeKey) return
-
- // Per-user dedup: drop if last event from same user < 8s ago
- const now = Date.now()
- let scopeMap = this.typingDedup.get(scopeKey)
- if (!scopeMap) {
- scopeMap = new Map()
- this.typingDedup.set(scopeKey, scopeMap)
- }
- const lastTs = scopeMap.get(state.userId) || 0
- if (now - lastTs < WebSocketDurableObject.TYPING_DEDUP_MS) return
- scopeMap.set(state.userId, now)
-
- // Prune stale scopes to prevent unbounded growth
- if (this.typingDedup.size > 200) {
- for (const [key, map] of this.typingDedup) {
- let allStale = true
- for (const ts of map.values()) {
- if (now - ts < WebSocketDurableObject.TYPING_DEDUP_MS * 4) {
- allStale = false
- break
- }
- }
- if (allStale) this.typingDedup.delete(key)
- }
- }
-
- // Fan out: resolve recipients and POST to their user DOs.
- // The typing event is forwarded to the recipients' DOs which deliver it
- // via their existing broadcast path. The DO here only handles dedup.
- // Actual fan-out is performed by the web API layer that calls fanOutToChannel.
- // However, for typing events sent directly over WS (not via REST), we fan out here.
- // `name`/`discriminator` ride from the connection state (stamped once at
- // auth) so the recipient renders the sender's name without a roster
- // lookup — no per-event DB. Undefined on a pre-existing connection that
- // predates this field; the client falls back to roster resolution then.
- const event = JSON.stringify({
- type: WS_EVENTS.TYPING_START,
- channelId: typingMsg.channelId,
- userId: state.userId,
- name: state.name,
- discriminator: state.discriminator,
- })
-
- // Resolve recipients and broadcast
- this.fanOutTyping(state.userId, typingMsg.channelId, event).catch((err) => {
- log.warn("community:typing.start fan-out failed", { err: String(err) })
- })
- return
- }
+ await handleWebSocketMessage(
+ this.domainContext(),
+ ws,
+ message,
+ (parsed) => handleCommunityMachineMessage(
+ this.domainContext(),
+ parsed,
+ {
+ fanOutMachineUpdated: (userId, machineId) =>
+ fanOutMachineUpdated(this.domainContext(), userId, machineId),
+ notifyUser: (userId, payload) => this.notifyUserDO(userId, payload),
+ },
+ ),
+ )
}
async webSocketClose(ws: WebSocket): Promise<void> {
- const state = ws.deserializeAttachment() as ConnectionState
- if (state?.type === "daemon" && state.authenticated) {
- log.info("daemon websocket closed", { daemonId: state.daemonId })
- this.notifyUserDO(state.userId, { type: "runtime.status", status: "offline", daemonId: state.daemonId }).catch(() => { })
- }
- if (state?.type === "user" && state.authenticated) {
- const remaining = this.countAuthenticatedUserConnections(state.userId) - 1
- if (remaining <= 0) {
- this.broadcastPresence(state.userId, false).catch(() => { })
- }
- }
- if (state?.type === "community-machine" && state.authenticated) {
- log.info("community machine websocket closed", { machineId: state.machineId, userId: state.userId })
- // Presence source of truth: the WS connection. On close, flip the row
- // status='online' → 'offline' scoped by the credential hash the DO owns.
- // The scope guard ensures a rotated-credential reconnect (which lands
- // on a DIFFERENT DO instance) is not clobbered by this DO's late close.
- //
- // See plans/community-machine-presence-fix.md for the full model.
- const identity = await this.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)
- if (!identity) {
- // No identity means we never fully accepted this connection (auth
- // failed before we cached it) OR the DO was already cleaned up. No
- // recoverable work for the alarm path here — HANDLE_KEY is written
- // alongside IDENTITY_KEY, so if identity is gone the alarm has
- // nothing to act on. Drop and return.
- return
- }
- try {
- const db = createDb(this.env.DB)
- const flipped = await queries.communityMachine.markMachineOffline(db, {
- userId: identity.userId,
- machineId: identity.machineId,
- credentialHash: identity.credentialHash,
- })
- if (flipped) {
- // Real transition — broadcast + clean up storage. Alarm no longer needed.
- await this.notifyUserDO(identity.userId, {
- type: WS_EVENTS.MACHINE_STATUS,
- machineId: identity.machineId,
- status: "offline",
- lastSeenAt: flipped.lastSeenAt ?? new Date().toISOString(),
- }).catch(() => { })
- await this.ctx.storage.deleteAlarm()
- await this.ctx.storage.delete(HANDLE_KEY)
- await this.ctx.storage.delete(IDENTITY_KEY)
- } else {
- // No transition happened: row is already offline OR the credential
- // was revoked (rotation → another DO owns this machine now). Leave
- // storage alone; the alarm safety net catches any edge cases.
- await this.ctx.storage.setAlarm(Date.now() + COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS)
- }
- } catch (err) {
- log.warn("markMachineOffline failed on webSocketClose", { err: String(err) })
- // D1 error — leave the alarm armed so the safety-net path can retry.
- await this.ctx.storage.setAlarm(Date.now() + COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS)
- }
- }
- }
-
- async alarm(): Promise<void> {
- const sockets = this.ctx.getWebSockets()
- const liveMachines: Array<{ userId: string; machineId: string }> = []
- for (const ws of sockets) {
- const s = ws.deserializeAttachment() as ConnectionState
- if (s?.type === "community-machine" && s.authenticated) {
- liveMachines.push({ userId: s.userId, machineId: s.machineId })
- }
- }
-
- if (liveMachines.length > 0) {
- // Connection still live — refresh last_seen_at, then defense-in-depth:
- // opportunistically flip status='offline' → 'online' if the row is
- // stale-offline (e.g. hibernated across a deploy). Broadcast only on a
- // real transition; the steady state (status already online) is a no-op.
- const db = createDb(this.env.DB)
- const identity = await this.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)
- for (const m of liveMachines) {
- try {
- await queries.communityMachine.touchMachineHeartbeat(db, m.userId, m.machineId)
- } catch { /* ok */ }
- if (identity && identity.userId === m.userId && identity.machineId === m.machineId) {
- try {
- const backfilled = await queries.communityMachine.markMachineOnlineIfOffline(db, {
- userId: identity.userId,
- machineId: identity.machineId,
- credentialHash: identity.credentialHash,
- })
- if (backfilled) {
- await this.notifyUserDO(identity.userId, {
- type: WS_EVENTS.MACHINE_STATUS,
- machineId: identity.machineId,
- status: "online",
- lastSeenAt: backfilled.lastSeenAt ?? new Date().toISOString(),
- }).catch(() => { })
- }
- } catch (err) {
- log.warn("markMachineOnlineIfOffline (alarm live-WS) failed", { err: String(err) })
- }
- }
- }
- await this.ctx.storage.setAlarm(Date.now() + COMMUNITY_MACHINE_HEARTBEAT_MS)
- return
- }
-
- // No live community-machine WS — flip the row to offline if it's stale,
- // otherwise reschedule the alarm to the exact moment the row goes stale.
- const stored = await this.ctx.storage.get<CommunityMachineHandle>(HANDLE_KEY)
- if (!stored) return
- const identity = await this.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)
- const db = createDb(this.env.DB)
- const machine = await queries.communityMachine.getMachineByIdForUser(
- db,
- stored.userId,
- stored.machineId
+ await handleWebSocketClose(
+ this.domainContext(),
+ ws,
+ (state) => handleCommunityMachineClose(this.domainContext(), state),
)
- if (!machine) {
- // Row was deleted — drop the handle so we don't keep waking up forever.
- await this.ctx.storage.delete(HANDLE_KEY)
- await this.ctx.storage.delete(IDENTITY_KEY)
- return
- }
- const lastSeen = machine.lastSeenAt ? Date.parse(machine.lastSeenAt) : 0
- const elapsed = Date.now() - lastSeen
- if (elapsed >= COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS) {
- // Stale enough — flip status='online' → 'offline' via the credential-scoped
- // query, broadcast only on real transition. If no identity is cached (e.g.
- // storage was wiped mid-lifecycle), fall back to a plain broadcast so the
- // UI still surfaces the transition even if the DB write skipped.
- if (identity) {
- try {
- const flipped = await queries.communityMachine.markMachineOffline(db, {
- userId: identity.userId,
- machineId: identity.machineId,
- credentialHash: identity.credentialHash,
- })
- if (flipped) {
- await this.notifyUserDO(stored.userId, {
- type: WS_EVENTS.MACHINE_STATUS,
- machineId: stored.machineId,
- status: "offline",
- lastSeenAt: flipped.lastSeenAt ?? new Date().toISOString(),
- }).catch(() => { })
- }
- } catch (err) {
- log.warn("markMachineOffline (alarm stale-flip) failed", { err: String(err) })
- }
- } else {
- // Identity was wiped mid-lifecycle but HANDLE_KEY still points at a
- // real row that is now stale. We can't run the credential-scoped
- // UPDATE, but the UI should still see the offline transition —
- // otherwise the machine chip stays green until reload. Broadcast
- // using the row's own lastSeenAt.
- await this.notifyUserDO(stored.userId, {
- type: WS_EVENTS.MACHINE_STATUS,
- machineId: stored.machineId,
- status: "offline",
- lastSeenAt: machine.lastSeenAt ?? new Date().toISOString(),
- }).catch(() => { })
- }
- // In either branch, this DO's presence lifecycle is done. Drop storage
- // so a future connection on the same DO name starts clean.
- await this.ctx.storage.delete(HANDLE_KEY)
- await this.ctx.storage.delete(IDENTITY_KEY)
- return
- }
- // Not stale yet — wake up again precisely when it will be.
- await this.ctx.storage.setAlarm(Date.now() + (COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS - elapsed))
- }
-
- /**
- * Shared scaffold for every daemon-reported bot frame (agent_activity,
- * agent_typing, agent_typing_stop, bot_audit_event):
- *
- * 1. resolve binding → if the query throws, log `phase=binding_check`
- * under `ws_frame_dropped` and drop (never `_write` — the write
- * never ran and this is a security-adjacent lookup failure).
- * 2. verify ownership → drop with a plain warn if `binding.machineId`
- * doesn't match this DO's identity (frame-supplied agentId can't
- * be trusted).
- * 3. run the frame-specific write → if it throws, log `phase=write`
- * under `writeCategory` (`ws_frame_dropped_write` for audit events
- * feeding the SLO, `ws_frame_dropped` for everything else).
- *
- * Centralized here so a new frame type CAN'T ship with the wrong log
- * category or a missing phase tag — the whole reason the discipline
- * exists.
- */
- private async handleFrameForBoundBot<B>(args: {
- frameType: string
- agentId: string
- machineId: string
- writeCategory?: "ws_frame_dropped" | "ws_frame_dropped_write"
- resolveBinding: () => Promise<B | null | undefined>
- isMatch: (binding: B) => boolean
- write: (binding: B) => Promise<void>
- }): Promise<void> {
- const { frameType, agentId, machineId, resolveBinding, isMatch, write } = args
- const writeCategory = args.writeCategory ?? "ws_frame_dropped"
-
- let binding: B | null | undefined
- try {
- binding = await resolveBinding()
- } catch (err) {
- log.warn("ws_frame_dropped", {
- category: "ws_frame_dropped",
- frame_type: frameType,
- phase: "binding_check",
- agentId,
- machineId,
- err: err instanceof Error ? err : new Error(String(err)),
- })
- return
- }
- if (!binding || !isMatch(binding)) {
- log.warn(`${frameType} frame for a bot not bound to this machine — dropped`, {
- agentId,
- machineId,
- })
- return
- }
- try {
- await write(binding)
- } catch (err) {
- log.warn("ws_frame_dropped", {
- category: writeCategory,
- frame_type: frameType,
- phase: "write",
- agentId,
- machineId,
- err: err instanceof Error ? err : new Error(String(err)),
- })
- }
- }
-
- private async handleCommunityMachineMessage(parsed: unknown): Promise<void> {
- // Identity lives in ctx.storage — one D1 lookup at accept, zero here.
- const identity = await this.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)
- if (!identity) {
- log.warn("community machine message with no cached identity")
- return
- }
-
- // Agent command ack frames — daemon → server reply protocol. New in v0.2.
- // `agent_wake_ack` means "daemon accepted/handled the wake command," NOT
- // "process started" (a wake may spawn, notify an already-running
- // process, or coalesce for later — see `HostControlChannel.reportWakeAck`).
- // `agent_stopped_ack` carries `status: "ok" | "error"` + optional
- // `{ code, message }`. No persistent write: there is no
- // `communityAgentRuntime` table (checked) and adding one is scope creep.
- // Log for observability only; owner-visible surfacing goes through the
- // daemon-side error propagation to the bot process (which can DM the
- // owner). `agent_deliver_ack` no longer exists — the server never
- // decides start-vs-deliver, so there is nothing for the daemon to ack
- // beyond the wake command itself.
- if (
- parsed && typeof parsed === "object" && "type" in parsed &&
- typeof (parsed as { type: unknown }).type === "string" &&
- (
- (parsed as { type: string }).type === "agent_wake_ack" ||
- (parsed as { type: string }).type === "agent_stopped_ack"
- )
- ) {
- const ack = parsed as {
- type: string
- agentId?: string
- launchId?: string
- status?: string
- error?: { code?: string; message?: string }
- }
- if (ack.status === "error") {
- log.warn("agent command ack error", {
- machineId: identity.machineId,
- type: ack.type,
- agentId: ack.agentId,
- code: ack.error?.code,
- message: ack.error?.message,
- })
- // Cold-start failure branch B (enroll fail / spawn threw): the reborn
- // agent will never emit `agent_session`, so evict any pending
- // reset/nap attribution for this launch — leaving it would leak an
- // entry in ctx.storage forever, and (correctly) no audit/awake is ever
- // written for a reset that never completed (red line ②). Branch A
- // (runtime_not_available) arrives as `session.error` below.
- if (ack.type === "agent_wake_ack" && typeof ack.launchId === "string" && ack.launchId.length > 0) {
- await this.evictPendingReset(ack.launchId)
- }
- } else if (ack.status === "ok") {
- log.debug("agent command ack ok", {
- machineId: identity.machineId,
- type: ack.type,
- agentId: ack.agentId,
- })
- }
- return
- }
-
- // `session.error` — daemon reports an unsupported runtime request.
- // Overlay it on the summary so the web card renders the error inline;
- // no DB writes (this is DO-local state).
- const sessionErrorParse = SessionErrorFrameSchema.safeParse(parsed)
- if (sessionErrorParse.success && sessionErrorParse.data.code === "runtime_not_available") {
- const payload = sessionErrorParse.data.payload ?? {}
- const requested = typeof payload.requested === "string" ? payload.requested : ""
- const availableRaw = Array.isArray(payload.available) ? payload.available : []
- const available = availableRaw.filter((v): v is string => typeof v === "string")
- const overlay = { requested, available, at: new Date().toISOString() }
- await this.ctx.storage.put(RUNTIME_ERROR_KEY, overlay)
- // Cold-start failure branch A (runtime not installed): the agent never
- // reborns, so evict any pending reset/nap attribution for this launch —
- // the twin of the `agent_wake_ack` error evict above. This is the branch
- // that would otherwise leak (a runtime-missing reset of a bound-idle
- // agent is the common batch-reset failure — Blair #922). `launchId` is
- // carried on the frame now (Melisa's source half).
- const launchId = sessionErrorParse.data.launchId
- if (typeof launchId === "string" && launchId.length > 0) {
- await this.evictPendingReset(launchId)
- }
- await this.fanOutMachineUpdated(identity.userId, identity.machineId).catch(() => { })
- return
- }
-
- // `agent_activity` — daemon reports a bot's derived activity state.
- // Translated INTO the same `statusEmoji`/`statusText` fields humans use
- // (so bots and humans share one status pipeline end-to-end and the
- // client never branches on "is this a bot") and fanned out via
- // `community:status.update`. `running` picks a fun preset once here
- // and persists it, so every viewer sees the same phrase for that
- // episode — no client-side randomization, no jitter on re-open.
- //
- // Verify the reporting machine actually owns this bot before writing —
- // never trust the frame-supplied agentId blindly, matching how other
- // frames on this channel trust `identity` but not frame-supplied ids.
- const activityParse = AgentActivityMessageSchema.safeParse(parsed)
- if (activityParse.success) {
- const { agentId, state } = activityParse.data
- const db = createDb(this.env.DB)
- await this.handleFrameForBoundBot({
- frameType: "agent_activity",
- agentId,
- machineId: identity.machineId,
- resolveBinding: () => queries.communityBot.getBotBinding(db, agentId),
- isMatch: (binding) => binding.machineId === identity.machineId,
- write: async () => {
- const prior = await withD1Retry(
- () => queries.communityUserProfile.getProfile(db, agentId),
- { route: "ws-do:agent-activity-profile-read" },
- )
- const priorEmoji = prior?.statusEmoji ?? null
- // `status_text` defaults to "" (schema), so an unset status reads back
- // as (null, "") not (null, null). Normalize "" → null so "no status"
- // is treated uniformly as writable, not mistaken for a custom status.
- const priorText = prior?.statusText ? prior.statusText : null
- // The activity pipeline only owns pills it wrote itself. If the bot
- // carries an owner-set custom status (a non-preset pair), leave it —
- // matches the reconciler's declared intent and stops the heartbeat
- // re-assert from stomping a custom status every interval. An empty
- // pair (no status yet) is still writable.
- if (
- (priorEmoji !== null || priorText !== null) &&
- !isBotActivityStatus(priorEmoji, priorText)
- )
- return
- const priorIsRunning =
- priorEmoji !== null &&
- RUNNING_PRESETS.some((p) => p.emoji === priorEmoji && p.text === priorText)
- // For `running`, reuse the currently-persisted preset if it's already
- // one of the running variants — matches the "one phrase per episode"
- // invariant instead of re-rolling on every derived running transition
- // (turn_end → idle → wake → running fires this repeatedly).
- const preset =
- state === "running" && priorIsRunning
- ? { emoji: priorEmoji as string, text: priorText as string }
- : pickBotActivityPreset(state, Math.random())
- if (preset.emoji === priorEmoji && preset.text === priorText) return
- await withD1Retry(
- () => queries.communityUserProfile.updateProfile(db, agentId, {
- statusEmoji: preset.emoji,
- statusText: preset.text,
- }),
- { route: "ws-do:agent-activity-profile" },
- )
- await this.broadcastToAudience(agentId, {
- type: WS_EVENTS.STATUS_UPDATE,
- userId: agentId,
- statusEmoji: preset.emoji,
- statusText: preset.text,
- })
- },
- })
- return
- }
-
- // `agent_typing` / `agent_typing_stop` — daemon reports the bot is (or
- // stopped) actively working on a DM. Fan out `community:typing.start` /
- // `community:typing.stop` to the DM's peer. Deliberately does NOT traverse
- // the client-inbound 8s dedup gate at ws-durable.ts:367-419 — daemon meters
- // cadence (5s heartbeat), so gating here would cause pill flicker every
- // ~3s. Client-side auto-expire (`TYPING_INDICATOR_TIMEOUT_MS = 8000`)
- // recovers if a heartbeat is dropped.
- const typingParse = AgentTypingMessageSchema.safeParse(parsed)
- if (typingParse.success) {
- const { agentId, channelId } = typingParse.data
- const db = createDb(this.env.DB)
- await this.handleFrameForBoundBot({
- frameType: "agent_typing",
- agentId,
- machineId: identity.machineId,
- resolveBinding: () => withD1Retry(
- () => queries.communityBot.getBotBindingWithOwner(db, agentId),
- { route: "ws-do:agent-typing-binding" },
- ),
- isMatch: (binding) => binding.machineId === identity.machineId,
- write: async (binding) => {
- // Channel membership is enforced inside `fanOutTyping` — no need to
- // pre-query here at 5s cadence. `name`/`discriminator` ride from the
- // binding (already read above) so the client renders the bot's name
- // without a roster lookup — no per-event DB.
- const event = JSON.stringify({
- type: WS_EVENTS.TYPING_START,
- channelId,
- userId: agentId,
- name: binding.name,
- discriminator: binding.discriminator,
- })
- await this.fanOutTyping(agentId, channelId, event)
- },
- })
- return
- }
- const typingStopParse = AgentTypingStopMessageSchema.safeParse(parsed)
- if (typingStopParse.success) {
- const { agentId, channelId } = typingStopParse.data
- const db = createDb(this.env.DB)
- await this.handleFrameForBoundBot({
- frameType: "agent_typing_stop",
- agentId,
- machineId: identity.machineId,
- resolveBinding: () => withD1Retry(
- () => queries.communityBot.getBotBindingWithOwner(db, agentId),
- { route: "ws-do:agent-typing-stop-binding" },
- ),
- isMatch: (binding) => binding.machineId === identity.machineId,
- // Channel membership enforced inside `fanOutTypingStop`.
- write: () => this.fanOutTypingStop(agentId, channelId),
- })
- return
- }
-
- // `agent_session` — the restarted agent is really up and has a session. This
- // is the completion signal for a reset, nap, model switch, or provider switch: if this launch has pending
- // attribution (recorded at dispatch in `/push`), write its audit + awake
- // stamp + broadcast NOW (not at dispatch), then consume the entry so a
- // replayed `agent_session` for the same launch can't double-write
- // (fire-once, §6.1). A launch with no pending entry (an ordinary wake, or
- // an already-consumed reset) falls through with no write.
- const sessionParse = AgentSessionMessageSchema.safeParse(parsed)
- if (sessionParse.success) {
- const { agentId, launchId } = sessionParse.data
- // CLAIM-then-write: read the pending trigger AND consume it up front, in
- // one turn before any `await` on the write path. Two `agent_session`
- // frames for the same launch can arrive back-to-back (e.g. codex used to
- // announce a thread twice → two frames); the OLD order (get → await
- // write → evict) let both read a non-null trigger before either evicted →
- // both wrote the reset audit (the "two identical reset records" bug).
- // Deleting immediately after the get makes the claim atomic within this
- // object's single-threaded turn: the second frame reads null and returns.
- // (normalizer dedup removes the double-frame SOURCE; this makes the
- // consume race-proof for any future double-frame, cross-runtime.)
- const stored = await this.ctx.storage.get<ResetTrigger | RestartAttribution>(restartPendingKey(launchId))
- if (!stored) return
- const attribution = normalizeRestartAttribution(stored)
- await this.evictPendingReset(launchId)
- const db = createDb(this.env.DB)
- await this.handleFrameForBoundBot({
- frameType: "agent_session",
- agentId,
- machineId: identity.machineId,
- writeCategory: "ws_frame_dropped_write",
- resolveBinding: () => withD1Retry(
- () => queries.communityBot.getBotBindingWithOwner(db, agentId),
- { route: "ws-do:agent-session-binding" },
- ),
- isMatch: (binding) => binding.machineId === identity.machineId,
- write: async (binding) => {
- // Per-kind audit — nap and reset stay distinct kinds so my-bots reads
- // "slept" vs "was reset" (red line ④). actorId never travels: reset
- // is owner-only, so the actor IS the bot owner, resolved right here
- // from the binding (red line ⑥ — attribution stays server-side).
- const inserted = attribution.kind === "nap"
- ? await queries.communityBotAuditLog.insertBotAuditNap(db, { botId: agentId, launchId })
- : attribution.kind === "session_reset"
- ? await queries.communityBotAuditLog.insertBotAuditSessionReset(db, {
- botId: agentId,
- launchId,
- trigger: attribution.trigger,
- })
- : attribution.kind === "model_switch"
- ? await queries.communityBotAuditLog.insertBotAuditModelChanged(db, {
- botId: agentId,
- launchId,
- from: attribution.from,
- to: attribution.to,
- })
- : await queries.communityBotAuditLog.insertBotAuditProviderChanged(db, {
- botId: agentId,
- launchId,
- from: attribution.from,
- to: attribution.to,
- })
- if (!inserted) return
- // Stamp awake (lastRefreshContextAt) in lockstep with the audit row,
- // using the row's createdAt so the my-bots "Awake Nh" indicator can
- // never drift from the audit event.
- if (attribution.kind !== "model_switch") {
- await queries.communityBot.touchBotRefreshContext(db, agentId, inserted.createdAt)
- }
- const payload = attribution.kind === "nap"
- ? { trigger: "nap" }
- : attribution.kind === "session_reset"
- ? { trigger: attribution.trigger }
- : { from: attribution.from, to: attribution.to }
- await this.notifyUserDO(binding.ownerUserId, {
- type: WS_EVENTS.BOT_AUDIT_EVENT,
- botId: agentId,
- id: inserted.id,
- kind: attribution.kind === "provider_switch"
- ? "provider_changed"
- : attribution.kind === "model_switch"
- ? "model_changed"
- : attribution.kind,
- payload,
- sessionId: null,
- launchId,
- createdAt: inserted.createdAt,
- }).catch(() => { })
- },
- })
- // (pending entry already consumed above, before the write — claim-first.)
- return
- }
-
- // `bot_audit_event` — daemon reports a bot activity event (cli_invocation,
- // tool_call, or thinking). Insert + rolling-500 prune land atomically via
- // `db.batch`; server stamps `createdAt` (never trust the daemon clock).
- // Fan the resulting row out to the OWNER ONLY (never `broadcastToAudience`
- // — that would leak per-bot activity to co-members + friends).
- const auditParse = HostBotAuditEventFrameSchema.safeParse(parsed)
- if (auditParse.success) {
- const frame = auditParse.data
- // Serialize BEFORE the shared scaffold — a non-serializable payload
- // (BigInt, circular ref, function) throwing here has nothing to do
- // with the audit-loss SLO and must not be logged under
- // `ws_frame_dropped_write`.
- let payload: string
- try {
- payload = JSON.stringify(frame.event.payload)
- } catch (err) {
- log.warn("ws_frame_dropped", {
- category: "ws_frame_dropped",
- frame_type: "bot_audit_event",
- phase: "serialize",
- agentId: frame.agentId,
- machineId: identity.machineId,
- err: err instanceof Error ? err : new Error(String(err)),
- })
- return
- }
- const db = createDb(this.env.DB)
- await this.handleFrameForBoundBot({
- frameType: "bot_audit_event",
- agentId: frame.agentId,
- machineId: identity.machineId,
- // `ws_frame_dropped_write` — the audit-loss SLO category. Emitted at
- // full-rate ingest via ws-do's `head_sampling_rate = 1.0` so a
- // low-rate drift doesn't hide behind 10% sampling. Binding-check
- // failures stay on the plain `ws_frame_dropped` category via the
- // helper's default.
- writeCategory: "ws_frame_dropped_write",
- resolveBinding: () => withD1Retry(
- () => queries.communityBot.getBotBindingWithOwner(db, frame.agentId),
- { route: "ws-do:bot-audit-binding" },
- ),
- isMatch: (binding) => binding.machineId === identity.machineId,
- write: async (binding) => {
- const inserted = await queries.communityBotAuditLog.insertBotActivityEventAndPrune(db, {
- botId: frame.agentId,
- sessionId: frame.sessionId ?? null,
- launchId: frame.launchId ?? null,
- kind: frame.event.kind,
- payload,
- })
- if (!inserted) return
- await this.notifyUserDO(binding.ownerUserId, {
- type: WS_EVENTS.BOT_AUDIT_EVENT,
- botId: frame.agentId,
- id: inserted.id,
- kind: frame.event.kind,
- payload: frame.event.payload,
- sessionId: frame.sessionId ?? null,
- launchId: frame.launchId ?? null,
- createdAt: inserted.createdAt,
- }).catch(() => { })
- },
- })
- return
- }
-
- // Otherwise: only `ready` frames drive DB updates. Zod-parse strictly —
- // legacy `runtimes: string[]`-only frames from pre-refactor daemons fail
- // validation and are silently dropped; MIN_CLI_VERSION will squeeze them
- // out on the next reconnect.
- const readyParse = HostReadyMessageSchema.safeParse(parsed)
- if (!readyParse.success) return
- const ready = readyParse.data
- try {
- const hostname = ready.hostname ?? ""
- const platform = ready.platform ?? ""
- const arch = ready.arch ?? ""
- const daemonVersion = ready.daemonVersion ?? ""
- const osRelease = ready.osRelease ?? ""
- const availableRuntimes: CommunityMachineRuntime[] = ready.runtimeReport
-
- const db = createDb(this.env.DB)
- const result = await queries.communityMachine.upsertMachineByMachineId(
- db,
- identity.userId,
- identity.machineId,
- { hostname, platform, arch, daemonVersion, osRelease, availableRuntimes }
- )
- if (!result) {
- // The machine row was deleted (or race) between credential validation
- // and this update — bail. The row will not be re-created here; the
- // daemon will be evicted on the next credential lookup via cascade.
- log.warn("community machine row missing on ready", { machineId: identity.machineId })
- return
- }
- const { machine, priorAvailableRuntimes, priorStatus } = result
-
- // Coarse safety net for an `agent_activity` frame dropped mid-disconnect —
- // clear any bot on this machine whose current status pill looks like a
- // stale system-written activity pill AND who the daemon reports is NOT
- // running now. Live `agent_activity` pushes handle every non-`idle`
- // transition; the reconciler only ever writes `Idle`. Owner-set custom
- // statuses (identified by not matching the known bot presets) are left
- // alone. See plans/community-bot-status-telemetry.md.
- const activityChanges = await queries.communityMachine.reconcileBotActivityFromRunningAgents(
- db,
- machine.id,
- ready.runningAgents
- )
- await Promise.allSettled(
- activityChanges.map(({ botUserId, statusEmoji, statusText }) =>
- this.broadcastToAudience(botUserId, {
- type: WS_EVENTS.STATUS_UPDATE,
- userId: botUserId,
- statusEmoji,
- statusText,
- })
- )
- )
-
- const summary = await this.summaryWithOverlay(machine)
- // Refresh the offline-detection handle in case metadata changed. Handle
- // was written at accept; this is idempotent.
- await this.ctx.storage.put<CommunityMachineHandle>(HANDLE_KEY, {
- userId: identity.userId,
- machineId: machine.id,
- })
-
- // NOTE: `community:machine.created` is emitted by the /activate route,
- // not here — activation is the single source of the create event and
- // carries the pairing token the client needs to reconcile its pending
- // state. Here we only handle status transitions and runtime drift.
- //
- // Broadcast the online transition ONLY when the row actually flipped
- // offline → online. `priorStatus` is the pre-upsert column value returned
- // by upsertMachineByMachineId; the upsert unconditionally sets
- // status='online', so `priorStatus !== 'online'` is the exact transition.
- if (priorStatus !== "online") {
- await this.notifyUserDO(identity.userId, {
- type: WS_EVENTS.MACHINE_STATUS,
- machineId: machine.id,
- status: "online",
- lastSeenAt: machine.lastSeenAt ?? new Date().toISOString(),
- }).catch(() => { })
- }
-
- // Runtime-drift diff. Canonicalized form now includes status/lastError
- // so a runtime flipping healthy → unhealthy on subsequent ready frames
- // (e.g. ENOENT hit at spawn time) fans out `community:machine.updated`.
- const priorCanonical = canonicalRuntimes(priorAvailableRuntimes ?? [])
- const nextCanonical = canonicalRuntimes(availableRuntimes)
- if (priorCanonical !== nextCanonical) {
- await this.notifyUserDO(identity.userId, {
- type: WS_EVENTS.MACHINE_UPDATED,
- machine: summary,
- }).catch(() => { })
- }
-
- await this.scheduleHeartbeatAlarm()
- } catch (err) {
- log.warn("ws_frame_dropped", {
- category: "ws_frame_dropped",
- frame_type: "ready",
- phase: "write",
- machineId: identity.machineId,
- err: err instanceof Error ? err : new Error(String(err)),
- })
- }
- }
-
- /**
- * Compose a summary + the current DO-local `lastRuntimeError` overlay (if
- * any). The overlay is transient — cleared optimistically when the DO
- * forwards `agent:wake` to the daemon, and on `forceClose`.
- */
- private async summaryWithOverlay(
- row: Parameters<typeof queries.communityMachine.toSummary>[0]
- ): Promise<CommunityMachineSummary> {
- const base = queries.communityMachine.toSummary(row)
- const overlay = await this.ctx.storage.get<{
- requested: string
- available: string[]
- at: string
- }>(RUNTIME_ERROR_KEY)
- return overlay ? { ...base, lastRuntimeError: overlay } : base
- }
-
- /**
- * Send a frame to the connected community-machine daemon (if any). Used by
- * `agent:wake` forwarding (minimal-wake-queue-unread-notice plan §3) — the
- * `alook-wake-worker` consumer POSTs an already-built `agent:wake`
- * `HostCommand` to `/forward-agent-wake`, which routes here.
- */
- private forwardToCommunityMachine(message: string): number {
- let sent = 0
- for (const ws of this.ctx.getWebSockets()) {
- const state = ws.deserializeAttachment() as ConnectionState
- if (state?.type === "community-machine" && state.authenticated) {
- try {
- ws.send(message)
- sent++
- } catch { /* ok */ }
- }
- }
- return sent
- }
-
- /**
- * Record pending reset/nap attribution from a frame about to be forwarded to
- * the daemon. Each launchId → its trigger, keyed by the frame type:
- * - `agent:reset` → one launch, trigger `single`
- * - `machine:reset_all` → N launches (resets[]), trigger `reset_all`
- * - `agent:nap` → one launch, trigger `nap`
- * Any other frame type is a no-op. The entry is consumed (deleted) when the
- * reborn `agent_session` lands, or evicted on a cold-start failure frame
- * (`agent_wake_ack` error / `session.error`). Best-effort parse — a malformed
- * frame just records nothing and forwards as before.
- */
- private async recordPendingRestarts(body: string): Promise<void> {
- let frame: unknown
- try {
- frame = JSON.parse(body)
- } catch {
- return
- }
- if (!frame || typeof frame !== "object") return
- const f = frame as { type?: unknown }
- const put = async (launchId: unknown, attribution: RestartAttribution) => {
- if (typeof launchId !== "string" || launchId.length === 0) return
- await this.ctx.storage.put<RestartAttribution>(restartPendingKey(launchId), attribution)
- }
- if (f.type === "agent:reset") {
- await put((f as { launchId?: unknown }).launchId, { kind: "session_reset", trigger: "single" })
- } else if (f.type === "agent:nap") {
- await put((f as { launchId?: unknown }).launchId, { kind: "nap" })
- } else if (f.type === "machine:reset_all") {
- const resets = (f as { resets?: unknown }).resets
- if (Array.isArray(resets)) {
- for (const r of resets) {
- if (r && typeof r === "object") {
- await put((r as { launchId?: unknown }).launchId, { kind: "session_reset", trigger: "reset_all" })
- }
- }
- }
- }
- }
-
- /** Drop a pending restart entry (consumed on completion, or evicted on failure). */
- private async evictPendingReset(launchId: string): Promise<void> {
- await this.ctx.storage.delete(restartPendingKey(launchId))
- }
-
- /** Optimistic overlay clear — no-op when nothing is stashed. */
- private async clearRuntimeErrorOverlay(): Promise<void> {
- const overlay = await this.ctx.storage.get(RUNTIME_ERROR_KEY)
- if (overlay === undefined) return
- await this.ctx.storage.delete(RUNTIME_ERROR_KEY)
- const identity = await this.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)
- if (!identity) return
- await this.fanOutMachineUpdated(identity.userId, identity.machineId).catch(() => { })
- }
-
- /**
- * Fan out a fresh `community:machine.updated` for the row + current
- * overlay state. Used by session.error stash, optimistic clear on
- * `agent:wake`, and forceClose.
- */
- private async fanOutMachineUpdated(userId: string, machineId: string): Promise<void> {
- const db = createDb(this.env.DB)
- const row = await queries.communityMachine.getMachineByIdForUser(db, userId, machineId)
- if (!row) return
- const summary = await this.summaryWithOverlay(row)
- await this.notifyUserDO(userId, {
- type: WS_EVENTS.MACHINE_UPDATED,
- machine: summary,
- })
}
async webSocketError(ws: WebSocket, error: unknown): Promise<void> {
- log.error("websocket error", { err: error instanceof Error ? error : String(error) })
- try { ws.close(1011, "Internal error") } catch { }
+ await handleWebSocketError(this.domainContext(), ws, error)
}
- private broadcast(message: string): number {
- let sent = 0
- for (const ws of this.ctx.getWebSockets()) {
- const state = ws.deserializeAttachment() as ConnectionState
- if (state.authenticated) {
- try {
- ws.send(message)
- sent++
- } catch { }
- }
- }
- return sent
+ async alarm(): Promise<void> {
+ await handleMachineAlarm(this.domainContext())
}
private async notifyUserDO(userId: string, payload: unknown): Promise<void> {
- // Every one of the 5 call sites wraps this whole method in
- // `.catch(() => {})` (fire-and-forget — a presence hiccup must never
- // block the machine-status write it rides on), which means an
- // unhandled throw ANYWHERE inside vanishes with zero trace. Own
- // try/catch + log around the WHOLE body — including the primary owner
- // notify — so a real failure is at least visible instead of silently
- // degrading to "you have to refresh to see the update."
- //
- // The primary owner notify (`userStub.fetch`) and the bot-presence
- // fan-out below are independent: a failed owner notify must NOT skip
- // the bot fan-out, and vice versa. Each has its own inner try so one
- // can't cascade into the other.
- try {
- const userDoId = this.env.WS_DO.idFromName("user:" + userId)
- const userStub = this.env.WS_DO.get(userDoId)
- try {
- await userStub.fetch(new Request("http://internal/broadcast", {
- method: "POST",
- body: JSON.stringify(payload),
- }))
- } catch (err) {
- log.error("notifyUserDO: owner notify failed", { err: String(err), userId })
- }
-
- // Single choke point for every `community:machine.status` emission (see
- // plans/community-account-debt-fixes.md Fix 3) — a bot has no WS of its
- // own, so its online/offline flip otherwise only ever reaches its owner
- // via the fetch above. Fan the same transition out through the exact
- // audience-based pipeline human presence already uses, for every bot
- // bound to this machine.
- try {
- const status = this.machineStatusPayload(payload)
- if (!status) return
- const db = createDb(this.env.DB)
- const bots = await queries.communityBot.listBotsForMachine(db, status.machineId)
- if (bots.length === 0) return
- await Promise.allSettled(
- bots.map((bot) => this.broadcastPresence(bot.id, status.online))
- )
- } catch (err) {
- log.error("notifyUserDO: bot presence fan-out failed", { err: String(err), userId })
- }
- } catch (err) {
- log.error("notifyUserDO: unexpected failure", { err: String(err), userId })
- }
- }
-
- /** Runtime type-guard — `notifyUserDO`'s `payload` is `unknown` by design. */
- private machineStatusPayload(payload: unknown): { machineId: string; online: boolean } | null {
- if (typeof payload !== "object" || payload === null) return null
- const p = payload as { type?: unknown; machineId?: unknown; status?: unknown }
- if (p.type !== WS_EVENTS.MACHINE_STATUS) return null
- if (typeof p.machineId !== "string") return null
- if (p.status !== "online" && p.status !== "offline") return null
- return { machineId: p.machineId, online: p.status === "online" }
- }
-
- private async getDaemonIdForUser(userId: string): Promise<string | null> {
- const db = createDb(this.env.DB)
- const token = await queries.machineToken.getLatestTokenForUser(db, userId)
- return token?.hostname || null
- }
-
- private async validateToken(
- token: string,
- ): Promise<{ userId: string; name: string; discriminator: string } | null> {
- const db = createDb(this.env.DB)
- // Resolve name/discriminator alongside the userId (one join) so the
- // connection state can carry them — typing fan-out then stamps the name
- // into the event without a per-event DB lookup. Runs once per WS auth.
- return queries.session.getValidSessionWithIdentity(db, token)
- }
-
- /**
- * Three-state machine-token validation. The daemon marks a workspace
- * auth-failed only on `invalid`, so a transient D1 failure must NEVER be
- * reported as `invalid` — it maps to `transient` (plain close, no
- * AUTH_REJECTED) so the daemon retries instead of dropping the workspace.
- *
- * - `valid` — token exists, active, has a workspace, AND owns the
- * daemon it is connecting as (a machine row for
- * daemonId+workspace exists). The daemonId is an
- * unauthenticated URL param that selects the DO instance,
- * so without this bind ANY valid token could authenticate
- * as ANOTHER tenant's daemon socket and receive that
- * daemon's task/file broadcasts. Machine-level (not runtime-
- * level) so a workspace mid-registration with 0 runtimes is
- * still valid — the machine row is written at register time.
- * - `invalid` — token doesn't exist, isn't active, or doesn't own this
- * daemon. Definitely dead / not authorized.
- * - `transient` — D1 threw. Infra blip, not a token problem.
- */
- private async validateMachineToken(
- token: string,
- daemonId: string,
- ): Promise<
- | { kind: "valid"; userId: string }
- | { kind: "invalid" }
- | { kind: "transient" }
- > {
- if (!token.startsWith("al_")) return { kind: "invalid" }
- try {
- const db = createDb(this.env.DB)
- const mt = await queries.machineToken.getMachineTokenByToken(db, token)
- if (!mt || mt.status !== "active" || !mt.workspaceId) return { kind: "invalid" }
- const machine = await queries.machine.getMachineByDaemon(db, daemonId, mt.workspaceId)
- if (!machine) return { kind: "invalid" }
- return { kind: "valid", userId: mt.userId }
- } catch (err) {
- log.warn("daemon websocket auth lookup threw", { err: String(err) })
- return { kind: "transient" }
- }
- }
-
- /**
- * Fan out a typing event to the appropriate recipients.
- * For channel/thread: resolve channel -> server -> members.
- * For DM: resolve the 2 participants.
- * Excludes the sender.
- *
- * Authorization: the sender must actually be a member of the target
- * channel's server (or a participant of the target DM) before we resolve
- * recipients — otherwise anyone who merely knows a channel/DM id could
- * make their client "type" into a scope they have no access to. Both
- * branches fold the check into the same query that already resolves the
- * fan-out target, so this adds no extra DB round-trip versus before.
- */
- /**
- * The typing-broadcast recipient set for a channel — the SAME reach
- * recipient-split as the message fan-out (`fanout.ts` getChannelRecipientUserIds).
- * Both dispatch on the channel type's reach trait (`channelReach`) so typing
- * reaches exactly whom a message would; they can't drift (B2 reach axis single
- * source — this was previously a hand-copied `isThread||isForumPost` split in
- * BOTH fanOutTyping and fanOutTypingStop, the reach rule's 7th/8th copies).
- * Does not exclude the sender — the callers filter that.
- */
- private async typingRecipientUserIds(db: ReturnType<typeof createDb>, channelId: string): Promise<string[]> {
- const channelType = await queries.communityChannel.getChannelType(db, channelId)
- const reach = isStoredChannelType(channelType) ? channelReach(channelType) : "server-or-roster"
- switch (reach) {
- case "participant-set":
- return queries.communityThread.listThreadParticipantUserIds(db, channelId)
- case "dm-pair":
- return queries.communityChannel.listChannelMemberUserIds(db, channelId)
- case "server-or-roster":
- return queries.communityMembersResolver.resolveScopeMemberUserIds(db, { scope: "channel", scopeId: channelId })
- default: {
- const _never: never = reach
- return _never
- }
- }
+ await notifyUserDO(this.domainContext(), userId, payload)
}
private async fanOutTyping(
@@ -1547,45 +135,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {
channelId?: string,
event?: string
): Promise<void> {
- if (!event || !channelId) return
- const db = createDb(this.env.DB)
- let recipientUserIds: string[] = []
-
- // getChannelForMember returns null when senderUserId can't see the
- // channel — same authz the HTTP layer enforces via requireChannelMember
- // (src/web/src/lib/community/permissions.ts). For a DM (type=dm) it
- // resolves via the sender's relation='access' member row.
- const membership = await withD1Retry(
- () => queries.communityChannel.getChannelForMember(db, channelId, senderUserId),
- { route: "ws-do:agent-typing-membership" },
- )
- if (!membership) {
- log.warn("fanOutTyping: sender not a channel member", { senderUserId, channelId })
- return
- }
- // Recipient set — the shared reach recipient-split (same as message
- // fan-out), then exclude the sender.
- recipientUserIds = await withD1Retry(
- () => this.typingRecipientUserIds(db, channelId),
- { route: "ws-do:agent-typing-recipients" },
- )
- recipientUserIds = recipientUserIds.filter((id) => id !== senderUserId)
- if (recipientUserIds.length === 0) return
-
- // POST to each user's DO broadcast endpoint (batched to stay under subrequest limit)
- for (let i = 0; i < recipientUserIds.length; i += WebSocketDurableObject.SUBREQUEST_BATCH_SIZE) {
- const batch = recipientUserIds.slice(i, i + WebSocketDurableObject.SUBREQUEST_BATCH_SIZE)
- await Promise.all(
- batch.map((userId) => {
- const doId = this.env.WS_DO.idFromName("user:" + userId)
- const stub = this.env.WS_DO.get(doId)
- return stub.fetch(new Request("http://internal/broadcast", {
- method: "POST",
- body: event,
- })).catch(() => { })
- })
- )
- }
+ await fanOutTyping(this.domainContext(), senderUserId, channelId, event)
}
/**
@@ -1598,56 +148,11 @@ export class WebSocketDurableObject extends DurableObject<Env> {
senderUserId: string,
channelId: string,
): Promise<void> {
- const db = createDb(this.env.DB)
- const membership = await withD1Retry(
- () => queries.communityChannel.getChannelForMember(db, channelId, senderUserId),
- { route: "ws-do:agent-typing-stop-membership" },
- )
- if (!membership) {
- log.warn("fanOutTypingStop: sender not a channel member", { senderUserId, channelId })
- return
- }
- let recipientUserIds = await withD1Retry(
- () => this.typingRecipientUserIds(db, channelId),
- { route: "ws-do:agent-typing-stop-recipients" },
- )
- recipientUserIds = recipientUserIds.filter((id) => id !== senderUserId)
- if (recipientUserIds.length === 0) return
- const body = JSON.stringify({
- type: WS_EVENTS.TYPING_STOP,
- channelId,
- userId: senderUserId,
- })
- for (let i = 0; i < recipientUserIds.length; i += WebSocketDurableObject.SUBREQUEST_BATCH_SIZE) {
- const batch = recipientUserIds.slice(i, i + WebSocketDurableObject.SUBREQUEST_BATCH_SIZE)
- await Promise.all(
- batch.map((userId) => {
- const doId = this.env.WS_DO.idFromName("user:" + userId)
- const stub = this.env.WS_DO.get(doId)
- return stub.fetch(new Request("http://internal/broadcast", {
- method: "POST",
- body,
- })).catch(() => { })
- })
- )
- }
+ await fanOutTypingStop(this.domainContext(), senderUserId, channelId)
}
- private countAuthenticatedUserConnections(userId: string): number {
- let count = 0
- for (const ws of this.ctx.getWebSockets()) {
- const state = ws.deserializeAttachment() as ConnectionState
- if (state?.type === "user" && state.authenticated && state.userId === userId) {
- count++
- }
- }
- return count
- }
-
- private static readonly SUBREQUEST_BATCH_SIZE = 40
-
private async broadcastPresence(userId: string, online: boolean): Promise<void> {
- await this.broadcastToAudience(userId, { type: WS_EVENTS.PRESENCE_UPDATE, userId, online })
+ await broadcastPresence(this.domainContext(), userId, online)
}
/**
@@ -1657,32 +162,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {
* `community:bot.activity`) share the same batched-fetch loop.
*/
private async broadcastToAudience(userId: string, payload: unknown): Promise<void> {
- const audience = await this.getPresenceAudience(userId)
- if (audience.length === 0) return
- const body = JSON.stringify(payload)
- for (let i = 0; i < audience.length; i += WebSocketDurableObject.SUBREQUEST_BATCH_SIZE) {
- const batch = audience.slice(i, i + WebSocketDurableObject.SUBREQUEST_BATCH_SIZE)
- await Promise.allSettled(
- batch.map((memberId) => {
- const doId = this.env.WS_DO.idFromName("user:" + memberId)
- const stub = this.env.WS_DO.get(doId)
- return stub.fetch(new Request("http://internal/broadcast", {
- method: "POST",
- body,
- }))
- })
- )
- }
- }
-
- private async getCoMembers(userId: string): Promise<string[]> {
- const db = createDb(this.env.DB)
- return queries.communityMember.getCoMemberUserIds(db, userId)
- }
-
- private async getFriendIds(userId: string): Promise<string[]> {
- const db = createDb(this.env.DB)
- return queries.communityFriendship.getFriendUserIds(db, userId)
+ await broadcastToAudience(this.domainContext(), userId, payload)
}
/**
@@ -1697,41 +177,10 @@ export class WebSocketDurableObject extends DurableObject<Env> {
* co-member gets one fetch, not two.
*/
private async getPresenceAudience(userId: string): Promise<string[]> {
- const [coMembers, friends] = await Promise.all([
- this.getCoMembers(userId),
- this.getFriendIds(userId),
- ])
- return [...new Set([...coMembers, ...friends])]
+ return getPresenceAudience(this.domainContext(), userId)
}
private async sendPresenceSnapshot(ws: WebSocket, userId: string): Promise<void> {
- const audience = await this.getPresenceAudience(userId)
- if (audience.length === 0) return
- const onlineIds: string[] = []
- for (let i = 0; i < audience.length; i += WebSocketDurableObject.SUBREQUEST_BATCH_SIZE) {
- const batch = audience.slice(i, i + WebSocketDurableObject.SUBREQUEST_BATCH_SIZE)
- const checks = await Promise.allSettled(
- batch.map(async (memberId) => {
- const doId = this.env.WS_DO.idFromName("user:" + memberId)
- const stub = this.env.WS_DO.get(doId)
- const resp = await stub.fetch(
- new Request(`http://internal/check-user-online?userId=${encodeURIComponent(memberId)}`)
- )
- // On a stale response the callee could not resolve the target's
- // presence — skip rather than treating `online: false` as truth
- // (that would flip real-online contacts to offline on every
- // D1 blip during snapshot).
- const data = await resp.json() as { online: boolean; stale?: boolean }
- if (data.stale) return null
- return data.online ? memberId : null
- })
- )
- for (const r of checks) {
- if (r.status === "fulfilled" && r.value) onlineIds.push(r.value)
- }
- }
- for (const id of onlineIds) {
- ws.send(JSON.stringify({ type: WS_EVENTS.PRESENCE_UPDATE, userId: id, online: true }))
- }
+ await sendPresenceSnapshot(this.domainContext(), ws, userId)
}
}
diff --git a/src/ws-do/src/ws-durable/bound-bot-frame.ts b/src/ws-do/src/ws-durable/bound-bot-frame.ts
new file mode 100644
index 000000000..ba5a07594
--- /dev/null
+++ b/src/ws-do/src/ws-durable/bound-bot-frame.ts
@@ -0,0 +1,59 @@
+import type { WsDurableContext } from "./internal"
+
+/**
+ * Shared scaffold for every daemon-reported bot frame:
+ * resolve the binding, verify machine ownership, then run the write.
+ * Binding failures stay under `ws_frame_dropped` with
+ * `phase=binding_check`; write failures use the requested category with
+ * `phase=write`. Centralizing this prevents new frame types from shipping
+ * with a missing phase or the audit-write SLO category on the wrong phase.
+ */
+export async function handleFrameForBoundBot<B>(
+ context: WsDurableContext,
+ args: {
+ frameType: string
+ agentId: string
+ machineId: string
+ writeCategory?: "ws_frame_dropped" | "ws_frame_dropped_write"
+ resolveBinding: () => Promise<B | null | undefined>
+ isMatch: (binding: B) => boolean
+ write: (binding: B) => Promise<void>
+ },
+): Promise<void> {
+ const { frameType, agentId, machineId, resolveBinding, isMatch, write } = args
+ const writeCategory = args.writeCategory ?? "ws_frame_dropped"
+
+ let binding: B | null | undefined
+ try {
+ binding = await resolveBinding()
+ } catch (err) {
+ context.log.warn("ws_frame_dropped", {
+ category: "ws_frame_dropped",
+ frame_type: frameType,
+ phase: "binding_check",
+ agentId,
+ machineId,
+ err: err instanceof Error ? err : new Error(String(err)),
+ })
+ return
+ }
+ if (!binding || !isMatch(binding)) {
+ context.log.warn(`${frameType} frame for a bot not bound to this machine — dropped`, {
+ agentId,
+ machineId,
+ })
+ return
+ }
+ try {
+ await write(binding)
+ } catch (err) {
+ context.log.warn("ws_frame_dropped", {
+ category: writeCategory,
+ frame_type: frameType,
+ phase: "write",
+ agentId,
+ machineId,
+ err: err instanceof Error ? err : new Error(String(err)),
+ })
+ }
+}
diff --git a/src/ws-do/src/ws-durable/internal.ts b/src/ws-do/src/ws-durable/internal.ts
new file mode 100644
index 000000000..55bf12ad3
--- /dev/null
+++ b/src/ws-do/src/ws-durable/internal.ts
@@ -0,0 +1,52 @@
+import type { Logger } from "@alook/shared"
+
+export type ConnectionState =
+ | { type: "user"; userId: string; authenticated: boolean; name?: string; discriminator?: string }
+ | { type: "daemon"; daemonId: string; userId: string; authenticated: boolean }
+ | {
+ type: "community-machine"
+ machineId: string
+ userId: string
+ authenticated: boolean
+ }
+
+export type UserConnectionState = Extract<ConnectionState, { type: "user" }>
+export type CommunityMachineConnectionState = Extract<ConnectionState, { type: "community-machine" }>
+
+export interface CommunityMachineIdentity {
+ userId: string
+ machineId: string
+ credentialHash: string
+}
+
+export interface CommunityMachineHandle {
+ userId: string
+ machineId: string
+}
+
+export const IDENTITY_KEY = "community-machine-identity"
+export const HANDLE_KEY = "community-machine-handle"
+export const RUNTIME_ERROR_KEY = "community-machine-runtime-error"
+const RESTART_PENDING_PREFIX = "reset-pending:"
+export const restartPendingKey = (launchId: string) => RESTART_PENDING_PREFIX + launchId
+
+export type ResetTrigger = "single" | "reset_all" | "nap"
+export type RestartAttribution =
+ | { kind: "session_reset"; trigger: "single" | "reset_all" }
+ | { kind: "nap" }
+ | { kind: "model_switch"; from: string | null; to: string | null }
+ | { kind: "provider_switch"; from: string; to: string }
+
+export function normalizeRestartAttribution(value: ResetTrigger | RestartAttribution): RestartAttribution {
+ if (typeof value !== "string") return value
+ return value === "nap" ? { kind: "nap" } : { kind: "session_reset", trigger: value }
+}
+
+export interface WsDurableContext {
+ readonly ctx: DurableObjectState
+ readonly env: Env
+ readonly log: Logger
+ readonly typingDedup: Map<string, Map<string, number>>
+ readonly typingDedupMs: number
+ readonly subrequestBatchSize: number
+}
diff --git a/src/ws-do/src/ws-durable/machine-control.test.ts b/src/ws-do/src/ws-durable/machine-control.test.ts
new file mode 100644
index 000000000..62adccb06
--- /dev/null
+++ b/src/ws-do/src/ws-durable/machine-control.test.ts
@@ -0,0 +1,323 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { createMockWebSocket } from "../__mocks__/cf"
+import {
+ CFResponse,
+ cleanupHarness,
+ createDO,
+ flushAsyncWork,
+ mockCheckAliveFetch,
+ mockCreateDb,
+ mockFindCredentialByHash,
+ mockGetBotBinding,
+ mockGetBotBindingWithOwner,
+ mockGetChannelForMember,
+ mockGetChannelType,
+ mockGetCoMemberUserIds,
+ mockGetDM,
+ mockGetFriendUserIds,
+ mockGetLatestTokenForUser,
+ mockGetMachineByDaemon,
+ mockGetMachineByIdForUser,
+ mockGetMachineTokenByToken,
+ mockGetPrivateChannelAudienceUserIds,
+ mockGetProfile,
+ mockGetRuntimeIdsByDaemon,
+ mockGetUserInternal,
+ mockGetValidSession,
+ mockGetValidSessionWithIdentity,
+ mockHashCredential,
+ mockInsertBotActivityEventAndPrune,
+ mockInsertBotAuditModelChanged,
+ mockInsertBotAuditNap,
+ mockInsertBotAuditProviderChanged,
+ mockInsertBotAuditSessionReset,
+ mockIsBotOnline,
+ mockIsChannelPrivate,
+ mockListBotsForMachine,
+ mockListChannelMemberUserIds,
+ mockListMembers,
+ mockListThreadParticipantUserIds,
+ mockMarkMachineOffline,
+ mockMarkMachineOnlineIfOffline,
+ mockReconcileBotActivityFromRunningAgents,
+ mockResolveScopeMemberUserIds,
+ mockStubFetch,
+ mockToSummary,
+ mockTouchBotRefreshContext,
+ mockTouchMachineHeartbeat,
+ mockUpdateProfile,
+ mockUpsertMachineByMachineId,
+ resetHarness
+} from "./test-harness"
+
+describe("WebSocketDurableObject", () => {
+ beforeEach(() => resetHarness())
+ afterEach(() => cleanupHarness())
+
+ describe("community-machine — session.error overlay + optimistic clear", () => {
+ beforeEach(() => {
+ mockFindCredentialByHash.mockReset()
+ mockGetMachineByIdForUser.mockReset()
+ mockStubFetch.mockClear()
+ })
+
+ it("forceClose closes attachments and clears identity+overlay", async () => {
+ const { durable, ctx, store, getWebSockets } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ store.set("community-machine-handle", { userId: "u_1", machineId: "cm_1" })
+ store.set("community-machine-runtime-error", {
+ requested: "gemini",
+ available: [],
+ at: "2026-07-06T00:00:00.000Z",
+ })
+ mockGetMachineByIdForUser.mockResolvedValue({
+ id: "cm_1",
+ hostname: "host",
+ availableRuntimes: [],
+ })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ getWebSockets.mockReturnValue([ws])
+
+ const req = new Request("http://internal/force-close", { method: "POST" })
+ const res = await durable.fetch(req)
+ expect(res.status).toBe(200)
+ expect(ws.send).toHaveBeenCalled()
+ expect(ws.close).toHaveBeenCalledWith(1008, "Revoked")
+
+ // Cached identity + handle + overlay all cleared.
+ expect(store.get("community-machine-identity")).toBeUndefined()
+ expect(store.get("community-machine-handle")).toBeUndefined()
+ expect(store.get("community-machine-runtime-error")).toBeUndefined()
+ })
+ })
+
+ describe("C2b characterization — machine control", () => {
+ const auth = {
+ credentialId: "cred_1",
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "f".repeat(64),
+ doName: "do_1",
+ }
+
+ beforeEach(() => {
+ mockHashCredential.mockReset().mockImplementation(async (bearer: string) => `hash:${bearer}`)
+ mockFindCredentialByHash.mockReset()
+ })
+
+ it("accepts cmk credentials in exact lookup, socket, attachment, storage, and alarm order", async () => {
+ vi.spyOn(Date, "now").mockReturnValue(1_000_000)
+ mockFindCredentialByHash.mockResolvedValue(auth)
+ const { durable, ctx, storage } = createDO()
+
+ const response = await durable.fetch(new Request("http://internal/", {
+ headers: {
+ Upgrade: "websocket",
+ Authorization: "Bearer cmk_secret",
+ },
+ })) as unknown as CFResponse
+
+ expect(response.status).toBe(101)
+ expect(mockHashCredential).toHaveBeenCalledWith("cmk_secret")
+ expect(mockFindCredentialByHash).toHaveBeenCalledWith({}, "hash:cmk_secret")
+ expect(ctx.acceptWebSocket).toHaveBeenCalledTimes(1)
+ const server = (ctx.acceptWebSocket as ReturnType<typeof vi.fn>).mock.calls[0]![0]
+ expect(server.serializeAttachment).toHaveBeenCalledWith({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ expect(storage.put.mock.calls).toEqual([
+ ["community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "f".repeat(64),
+ }],
+ ["community-machine-handle", { userId: "u_1", machineId: "cm_1" }],
+ ])
+ expect(storage.setAlarm).toHaveBeenCalledWith(1_060_000)
+ const order = [
+ mockHashCredential.mock.invocationCallOrder[0],
+ mockFindCredentialByHash.mock.invocationCallOrder[0],
+ (ctx.acceptWebSocket as ReturnType<typeof vi.fn>).mock.invocationCallOrder[0],
+ server.serializeAttachment.mock.invocationCallOrder[0],
+ storage.put.mock.invocationCallOrder[0],
+ storage.put.mock.invocationCallOrder[1],
+ storage.getAlarm.mock.invocationCallOrder[0],
+ storage.setAlarm.mock.invocationCallOrder[0],
+ ]
+ expect(order).toEqual([...order].sort((a, b) => a - b))
+ })
+
+ it("returns 503 before accepting or persisting when cmk auth lookup throws", async () => {
+ mockFindCredentialByHash.mockRejectedValue(new Error("d1 unavailable"))
+ const { durable, ctx, storage } = createDO()
+
+ const response = await durable.fetch(new Request("http://internal/", {
+ headers: { Upgrade: "websocket", Authorization: "Bearer cmk_secret" },
+ }))
+
+ expect(response.status).toBe(503)
+ expect(ctx.acceptWebSocket).not.toHaveBeenCalled()
+ expect(storage.put).not.toHaveBeenCalled()
+ expect(storage.setAlarm).not.toHaveBeenCalled()
+ })
+
+ it("returns 401 before accepting or persisting a revoked cmk credential", async () => {
+ mockFindCredentialByHash.mockResolvedValue(null)
+ const { durable, ctx, storage } = createDO()
+
+ const response = await durable.fetch(new Request("http://internal/", {
+ headers: { Upgrade: "websocket", Authorization: "Bearer cmk_revoked" },
+ }))
+
+ expect(response.status).toBe(401)
+ expect(ctx.acceptWebSocket).not.toHaveBeenCalled()
+ expect(storage.put).not.toHaveBeenCalled()
+ expect(storage.setAlarm).not.toHaveBeenCalled()
+ })
+
+ it("retains an existing heartbeat alarm that fires earlier than the requested target", async () => {
+ vi.spyOn(Date, "now").mockReturnValue(1_000_000)
+ mockFindCredentialByHash.mockResolvedValue(auth)
+ const { durable, storage } = createDO()
+ await storage.setAlarm(1_030_000)
+ storage.setAlarm.mockClear()
+
+ const response = await durable.fetch(new Request("http://internal/", {
+ headers: { Upgrade: "websocket", Authorization: "Bearer cmk_secret" },
+ }))
+
+ expect(response.status).toBe(101)
+ expect(storage.getAlarm).toHaveBeenCalledTimes(1)
+ expect(storage.setAlarm).not.toHaveBeenCalled()
+ expect(await storage.getAlarm()).toBe(1_030_000)
+ })
+
+ it("sets a null or later alarm to the exact heartbeat target", async () => {
+ vi.spyOn(Date, "now").mockReturnValue(2_000_000)
+ mockFindCredentialByHash.mockResolvedValue(auth)
+ const first = createDO()
+
+ await first.durable.fetch(new Request("http://internal/", {
+ headers: { Upgrade: "websocket", Authorization: "Bearer cmk_first" },
+ }))
+ expect(first.storage.setAlarm).toHaveBeenCalledWith(2_060_000)
+
+ const second = createDO()
+ await second.storage.setAlarm(2_120_000)
+ second.storage.setAlarm.mockClear()
+ await second.durable.fetch(new Request("http://internal/", {
+ headers: { Upgrade: "websocket", Authorization: "Bearer cmk_second" },
+ }))
+ expect(second.storage.setAlarm).toHaveBeenCalledWith(2_060_000)
+ })
+
+ it("rejects malformed model and provider switch JSON before forwarding or storage", async () => {
+ const { durable, getWebSockets, storage } = createDO()
+
+ const model = await durable.fetch(new Request("http://internal/push-model-switch", {
+ method: "POST",
+ body: "{",
+ }))
+ const provider = await durable.fetch(new Request("http://internal/push-provider-switch", {
+ method: "POST",
+ body: "{",
+ }))
+
+ expect([model.status, provider.status]).toEqual([400, 400])
+ expect(getWebSockets).not.toHaveBeenCalled()
+ expect(storage.put).not.toHaveBeenCalled()
+ })
+
+ it("rejects model and provider switches with missing required fields before forwarding or storage", async () => {
+ const { durable, getWebSockets, storage } = createDO()
+ const request = (path: string) => new Request(`http://internal${path}`, {
+ method: "POST",
+ body: JSON.stringify({ agentId: "a_1", launchId: "l_1" }),
+ })
+
+ const model = await durable.fetch(request("/push-model-switch"))
+ const provider = await durable.fetch(request("/push-provider-switch"))
+
+ expect([model.status, provider.status]).toEqual([400, 400])
+ expect(getWebSockets).not.toHaveBeenCalled()
+ expect(storage.put).not.toHaveBeenCalled()
+ })
+
+ it("rejects invalid model and provider from/to values before forwarding or storage", async () => {
+ const { durable, getWebSockets, storage } = createDO()
+ const model = await durable.fetch(new Request("http://internal/push-model-switch", {
+ method: "POST",
+ body: JSON.stringify({ agentId: "a_1", config: {}, launchId: "l_1", from: 1, to: null }),
+ }))
+ const provider = await durable.fetch(new Request("http://internal/push-provider-switch", {
+ method: "POST",
+ body: JSON.stringify({ agentId: "a_1", config: {}, launchId: "l_2", from: "", to: "next" }),
+ }))
+
+ expect([model.status, provider.status]).toEqual([400, 400])
+ expect(getWebSockets).not.toHaveBeenCalled()
+ expect(storage.put).not.toHaveBeenCalled()
+ })
+
+ it("returns the forward-wake send count when optimistic overlay clearing rejects", async () => {
+ const { durable, getWebSockets, storage } = createDO()
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ getWebSockets.mockReturnValue([ws])
+ storage.get.mockRejectedValueOnce(new Error("storage unavailable"))
+ const body = JSON.stringify({ type: "agent:wake", agentId: "a_1" })
+
+ const response = await durable.fetch(new Request("http://internal/forward-agent-wake", {
+ method: "POST",
+ body,
+ }))
+
+ await expect(response.json()).resolves.toEqual({ sent: 1 })
+ expect(ws.send).toHaveBeenCalledWith(body)
+ })
+
+ it("best-effort force-close counts only sockets whose send and close both complete", async () => {
+ const { durable, getWebSockets } = createDO()
+ const sendFails = createMockWebSocket()
+ const closeFails = createMockWebSocket()
+ const completes = createMockWebSocket()
+ for (const ws of [sendFails, closeFails, completes]) {
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ }
+ sendFails.send.mockImplementation(() => { throw new Error("send failed") })
+ closeFails.close.mockImplementation(() => { throw new Error("close failed") })
+ getWebSockets.mockReturnValue([sendFails, closeFails, completes])
+
+ const response = await durable.fetch(new Request("http://internal/force-close", { method: "POST" }))
+
+ await expect(response.json()).resolves.toEqual({ closed: 1 })
+ expect(sendFails.close).not.toHaveBeenCalled()
+ expect(closeFails.close).toHaveBeenCalledWith(1008, "Revoked")
+ expect(completes.close).toHaveBeenCalledWith(1008, "Revoked")
+ })
+ })
+})
diff --git a/src/ws-do/src/ws-durable/machine-control.ts b/src/ws-do/src/ws-durable/machine-control.ts
new file mode 100644
index 000000000..4723d98d5
--- /dev/null
+++ b/src/ws-do/src/ws-durable/machine-control.ts
@@ -0,0 +1,199 @@
+import { createDb, queries } from "@alook/shared"
+import {
+ HANDLE_KEY,
+ IDENTITY_KEY,
+ RUNTIME_ERROR_KEY,
+ restartPendingKey,
+} from "./internal"
+import type {
+ CommunityMachineHandle,
+ CommunityMachineIdentity,
+ ConnectionState,
+ RestartAttribution,
+ WsDurableContext,
+} from "./internal"
+import { scheduleHeartbeatAlarm } from "./machine-lifecycle"
+
+export type MachineControlHooks = Readonly<{
+ recordPendingRestarts: (body: string) => Promise<void>
+ clearRuntimeErrorOverlay: () => Promise<void>
+ fanOutMachineUpdated: (userId: string, machineId: string) => Promise<void>
+}>
+
+export async function handleMachineControlFetch(
+ context: WsDurableContext,
+ request: Request,
+ url: URL,
+ hooks: MachineControlHooks,
+): Promise<Response | null> {
+ if (url.pathname === "/force-close" && request.method === "POST") {
+ const closed = await forceCloseCommunityMachine(context, hooks.fanOutMachineUpdated)
+ return new Response(JSON.stringify({ closed }), {
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+
+ if (url.pathname === "/push" && request.method === "POST") {
+ const body = await request.text()
+ const sent = forwardToCommunityMachine(context, body)
+ if (sent > 0) await hooks.recordPendingRestarts(body)
+ return new Response(JSON.stringify({ sent }), {
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+
+ if (
+ request.method === "POST" &&
+ (url.pathname === "/push-model-switch" || url.pathname === "/push-provider-switch")
+ ) {
+ let payload: unknown
+ try {
+ payload = await request.json()
+ } catch {
+ return new Response(JSON.stringify({ sent: 0 }), { status: 400 })
+ }
+ if (!payload || typeof payload !== "object") {
+ return new Response(JSON.stringify({ sent: 0 }), { status: 400 })
+ }
+ const raw = payload as Record<string, unknown>
+ const { agentId, config, launchId, from, to } = raw
+ if (
+ typeof agentId !== "string" || agentId.length === 0 ||
+ typeof launchId !== "string" || launchId.length === 0 ||
+ !config || typeof config !== "object"
+ ) {
+ return new Response(JSON.stringify({ sent: 0 }), { status: 400 })
+ }
+ const providerSwitch = url.pathname === "/push-provider-switch"
+ if (
+ providerSwitch
+ ? typeof from !== "string" || from.length === 0 || typeof to !== "string" || to.length === 0
+ : (from !== null && typeof from !== "string") || (to !== null && typeof to !== "string")
+ ) {
+ return new Response(JSON.stringify({ sent: 0 }), { status: 400 })
+ }
+ const frame = JSON.stringify({
+ type: providerSwitch ? "agent:reset" : "agent:model_switch",
+ agentId,
+ config,
+ launchId,
+ })
+ const sent = forwardToCommunityMachine(context, frame)
+ if (sent > 0) {
+ const attribution: RestartAttribution = providerSwitch
+ ? { kind: "provider_switch", from: from as string, to: to as string }
+ : { kind: "model_switch", from: from as string | null, to: to as string | null }
+ await context.ctx.storage.put<RestartAttribution>(restartPendingKey(launchId), attribution)
+ }
+ return new Response(JSON.stringify({ sent }), {
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+
+ if (url.pathname === "/forward-agent-wake" && request.method === "POST") {
+ const body = await request.text()
+ const sent = forwardToCommunityMachine(context, body)
+ await hooks.clearRuntimeErrorOverlay().catch(() => { })
+ return new Response(JSON.stringify({ sent }), {
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+
+ return null
+}
+
+export async function acceptCommunityMachineWebSocket(
+ context: WsDurableContext,
+ bearer: string,
+): Promise<Response> {
+ const db = createDb(context.env.DB)
+ const hash = await queries.communityMachine.hashCredential(bearer)
+ let auth: {
+ credentialId: string
+ userId: string
+ machineId: string
+ credentialHash: string
+ doName: string
+ } | null = null
+ try {
+ auth = await queries.communityMachine.findCredentialByHash(db, hash)
+ } catch (err) {
+ context.log.warn("community machine auth lookup threw", { err: String(err) })
+ return new Response("auth lookup unavailable", { status: 503 })
+ }
+ if (!auth) {
+ return new Response("credential revoked or unknown", { status: 401 })
+ }
+
+ const pair = new WebSocketPair()
+ const [client, server] = Object.values(pair)
+ context.ctx.acceptWebSocket(server)
+
+ server.serializeAttachment({
+ type: "community-machine",
+ machineId: auth.machineId,
+ userId: auth.userId,
+ authenticated: true,
+ } as ConnectionState)
+
+ const identity: CommunityMachineIdentity = {
+ userId: auth.userId,
+ machineId: auth.machineId,
+ credentialHash: auth.credentialHash,
+ }
+ await context.ctx.storage.put(IDENTITY_KEY, identity)
+ await context.ctx.storage.put<CommunityMachineHandle>(HANDLE_KEY, {
+ userId: auth.userId,
+ machineId: auth.machineId,
+ })
+ await scheduleHeartbeatAlarm(context)
+
+ return new Response(null, { status: 101, webSocket: client })
+}
+
+async function forceCloseCommunityMachine(
+ context: WsDurableContext,
+ fanOutMachineUpdated: (userId: string, machineId: string) => Promise<void>,
+): Promise<number> {
+ const identity = await context.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)
+ let closed = 0
+ for (const ws of context.ctx.getWebSockets()) {
+ const s = ws.deserializeAttachment() as ConnectionState
+ if (s?.type === "community-machine") {
+ try {
+ ws.send(JSON.stringify({ type: "error", code: "AUTH_REJECTED" }))
+ ws.close(1008, "Revoked")
+ closed++
+ } catch { /* ok */ }
+ }
+ }
+ await context.ctx.storage.delete(IDENTITY_KEY)
+ await context.ctx.storage.delete(HANDLE_KEY)
+ const hadError = (await context.ctx.storage.get(RUNTIME_ERROR_KEY)) !== undefined
+ await context.ctx.storage.delete(RUNTIME_ERROR_KEY)
+ if (identity && hadError) {
+ await fanOutMachineUpdated(identity.userId, identity.machineId).catch(() => { })
+ }
+ return closed
+}
+
+function rejectCommunityMachine(ws: WebSocket, reason: string): void {
+ try {
+ ws.send(JSON.stringify({ type: "error", code: "AUTH_REJECTED", reason }))
+ } catch { /* ok */ }
+ try { ws.close(1008, "Unauthorized") } catch { /* ok */ }
+}
+
+function forwardToCommunityMachine(context: WsDurableContext, message: string): number {
+ let sent = 0
+ for (const ws of context.ctx.getWebSockets()) {
+ const state = ws.deserializeAttachment() as ConnectionState
+ if (state?.type === "community-machine" && state.authenticated) {
+ try {
+ ws.send(message)
+ sent++
+ } catch { /* ok */ }
+ }
+ }
+ return sent
+}
diff --git a/src/ws-do/src/ws-durable/machine-frames.test.ts b/src/ws-do/src/ws-durable/machine-frames.test.ts
new file mode 100644
index 000000000..5dc35fdc5
--- /dev/null
+++ b/src/ws-do/src/ws-durable/machine-frames.test.ts
@@ -0,0 +1,500 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { createMockWebSocket } from "../__mocks__/cf"
+import {
+ CFResponse,
+ cleanupHarness,
+ createDO,
+ flushAsyncWork,
+ mockCheckAliveFetch,
+ mockCreateDb,
+ mockFindCredentialByHash,
+ mockGetBotBinding,
+ mockGetBotBindingWithOwner,
+ mockGetChannelForMember,
+ mockGetChannelType,
+ mockGetCoMemberUserIds,
+ mockGetDM,
+ mockGetFriendUserIds,
+ mockGetLatestTokenForUser,
+ mockGetMachineByDaemon,
+ mockGetMachineByIdForUser,
+ mockGetMachineTokenByToken,
+ mockGetPrivateChannelAudienceUserIds,
+ mockGetProfile,
+ mockGetRuntimeIdsByDaemon,
+ mockGetUserInternal,
+ mockGetValidSession,
+ mockGetValidSessionWithIdentity,
+ mockHashCredential,
+ mockInsertBotActivityEventAndPrune,
+ mockInsertBotAuditModelChanged,
+ mockInsertBotAuditNap,
+ mockInsertBotAuditProviderChanged,
+ mockInsertBotAuditSessionReset,
+ mockIsBotOnline,
+ mockIsChannelPrivate,
+ mockListBotsForMachine,
+ mockListChannelMemberUserIds,
+ mockListMembers,
+ mockListThreadParticipantUserIds,
+ mockLogDebug,
+ mockLogWarn,
+ mockMarkMachineOffline,
+ mockMarkMachineOnlineIfOffline,
+ mockReconcileBotActivityFromRunningAgents,
+ mockResolveScopeMemberUserIds,
+ mockStubFetch,
+ mockToSummary,
+ mockTouchBotRefreshContext,
+ mockTouchMachineHeartbeat,
+ mockUpdateProfile,
+ mockUpsertMachineByMachineId,
+ resetHarness
+} from "./test-harness"
+
+describe("WebSocketDurableObject", () => {
+ beforeEach(() => resetHarness())
+ afterEach(() => cleanupHarness())
+
+ describe("community-machine — session.error overlay + optimistic clear", () => {
+ beforeEach(() => {
+ mockFindCredentialByHash.mockReset()
+ mockGetMachineByIdForUser.mockReset()
+ mockStubFetch.mockClear()
+ })
+
+ it("stashes lastRuntimeError overlay + fans out on session.error{runtime_not_available}", async () => {
+ const { durable, store } = createDO()
+ // Prime cached identity as if accept already ran.
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetMachineByIdForUser.mockResolvedValue({
+ id: "cm_1",
+ hostname: "host",
+ availableRuntimes: [{ id: "codex" }],
+ })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({
+ type: "session.error",
+ code: "runtime_not_available",
+ agentId: "a1",
+ payload: { requested: "gemini", available: ["codex"] },
+ })
+ await durable.webSocketMessage(ws as any, frame)
+
+ const overlay = store.get("community-machine-runtime-error") as
+ | { requested: string; available: string[]; at: string }
+ | undefined
+ expect(overlay).toBeDefined()
+ expect(overlay?.requested).toBe("gemini")
+ expect(overlay?.available).toEqual(["codex"])
+
+ // Fan-out went to the user DO with the overlay attached.
+ expect(mockStubFetch).toHaveBeenCalled()
+ const call = mockStubFetch.mock.calls.find((c: any[]) =>
+ (c[0] as Request).url.endsWith("/broadcast")
+ )
+ const body = JSON.parse(await (call![0] as Request).clone().text()) as {
+ type: string
+ machine: { lastRuntimeError?: { requested: string; available: string[] } }
+ }
+ expect(body.type).toBe("community:machine.updated")
+ expect(body.machine.lastRuntimeError).toMatchObject({
+ requested: "gemini",
+ available: ["codex"],
+ })
+ })
+ })
+
+ describe("community-machine — ready frame wire shape", () => {
+ beforeEach(() => {
+ mockUpsertMachineByMachineId.mockReset()
+ mockStubFetch.mockClear()
+ })
+
+ // Regression guard: the daemon (WsControlChannel.reportReady) spreads
+ // HostReady fields at the TOP LEVEL of the frame. If it ever regresses to
+ // wrapping them under `ready:{...}`, the DO would silently drop every
+ // ready and `last_seen_at` would never refresh. This test drives the exact
+ // shape the daemon emits.
+ it("accepts a flat daemon-shaped ready frame and calls upsertMachineByMachineId", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockUpsertMachineByMachineId.mockResolvedValue({
+ machine: {
+ id: "cm_1",
+ hostname: "host",
+ availableRuntimes: [{ id: "claude" }],
+ status: "online",
+ lastSeenAt: "2026-07-06T00:00:00.000Z",
+ },
+ priorLastSeenAt: "2026-07-05T00:00:00.000Z",
+ priorAvailableRuntimes: [{ id: "claude" }],
+ priorStatus: "offline",
+ })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ // The wire frame the daemon actually sends — see WsControlChannel.reportReady.
+ const frame = JSON.stringify({
+ type: "ready",
+ runtimeReport: [{ id: "claude", version: "1.0.0" }],
+ runningAgents: [],
+ hostname: "my-mac",
+ platform: "darwin",
+ arch: "arm64",
+ osRelease: "23.0.0",
+ daemonVersion: "0.1.0",
+ })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockUpsertMachineByMachineId).toHaveBeenCalledTimes(1)
+ const [, userId, machineId, meta] = mockUpsertMachineByMachineId.mock.calls[0]
+ expect(userId).toBe("u_1")
+ expect(machineId).toBe("cm_1")
+ expect(meta).toMatchObject({
+ hostname: "my-mac",
+ platform: "darwin",
+ arch: "arm64",
+ osRelease: "23.0.0",
+ daemonVersion: "0.1.0",
+ availableRuntimes: [{ id: "claude", version: "1.0.0" }],
+ })
+ })
+
+ it("silently drops a wrapped `{ready:{...}}` frame (legacy shape — regression guard)", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ // The (broken) wrapped shape — schema rejects → DO drops → no DB write.
+ const frame = JSON.stringify({
+ type: "ready",
+ ready: {
+ runtimeReport: [{ id: "claude" }],
+ runningAgents: [],
+ hostname: "my-mac",
+ },
+ })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockUpsertMachineByMachineId).not.toHaveBeenCalled()
+ })
+ })
+
+ describe("community-machine — ready frame reconciles bot activity", () => {
+ beforeEach(() => {
+ mockUpsertMachineByMachineId.mockReset()
+ mockReconcileBotActivityFromRunningAgents.mockReset().mockResolvedValue([])
+ mockStubFetch.mockClear()
+ })
+
+ it("a ready frame whose runningAgents disagrees with persisted state fans out community:status.update for each cleared bot", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockUpsertMachineByMachineId.mockResolvedValue({
+ machine: {
+ id: "cm_1",
+ hostname: "host",
+ availableRuntimes: [],
+ status: "online",
+ lastSeenAt: "2026-07-13T00:00:00.000Z",
+ },
+ priorLastSeenAt: "2026-07-12T00:00:00.000Z",
+ priorAvailableRuntimes: [],
+ priorStatus: "online",
+ })
+ mockReconcileBotActivityFromRunningAgents.mockResolvedValue([
+ { botUserId: "bot_1", statusEmoji: "💤", statusText: "Idle" },
+ { botUserId: "bot_2", statusEmoji: "💤", statusText: "Idle" },
+ ])
+ mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({
+ type: "ready",
+ runtimeReport: [],
+ runningAgents: [],
+ })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockReconcileBotActivityFromRunningAgents).toHaveBeenCalledWith(expect.anything(), "cm_1", [])
+ const activityCalls = mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
+ const bodies = await Promise.all(activityCalls.map((c: any[]) => (c[0] as Request).clone().text()))
+ const parsed = bodies.map((b) => JSON.parse(b)).filter((b) => b.type === "community:status.update")
+ expect(parsed).toEqual(
+ expect.arrayContaining([
+ { type: "community:status.update", userId: "bot_1", statusEmoji: "💤", statusText: "Idle" },
+ { type: "community:status.update", userId: "bot_2", statusEmoji: "💤", statusText: "Idle" },
+ ])
+ )
+ })
+
+ it("emits no status.update fan-out when reconciliation finds no changes", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockUpsertMachineByMachineId.mockResolvedValue({
+ machine: {
+ id: "cm_1",
+ hostname: "host",
+ availableRuntimes: [],
+ status: "online",
+ lastSeenAt: "2026-07-13T00:00:00.000Z",
+ },
+ priorLastSeenAt: "2026-07-12T00:00:00.000Z",
+ priorAvailableRuntimes: [],
+ priorStatus: "online",
+ })
+ mockReconcileBotActivityFromRunningAgents.mockResolvedValue([])
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({ type: "ready", runtimeReport: [], runningAgents: [] })
+ await durable.webSocketMessage(ws as any, frame)
+
+ const activityCalls = mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
+ const bodies = await Promise.all(activityCalls.map((c: any[]) => (c[0] as Request).clone().text()))
+ const parsed = bodies.map((b) => JSON.parse(b)).filter((b) => b.type === "community:status.update")
+ expect(parsed).toEqual([])
+ })
+ })
+
+ describe("C2c characterization — machine frames", () => {
+ beforeEach(() => {
+ mockGetMachineByIdForUser.mockReset().mockResolvedValue(null)
+ mockUpsertMachineByMachineId.mockReset()
+ mockReconcileBotActivityFromRunningAgents.mockReset().mockResolvedValue([])
+ mockStubFetch.mockClear()
+ })
+
+ function machineWs() {
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ return ws
+ }
+
+ function seedIdentity(store: Map<string, unknown>) {
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ }
+
+ it("observes ok command acknowledgements without persistence", async () => {
+ const { durable, store, storage } = createDO()
+ seedIdentity(store)
+
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_wake_ack", agentId: "bot_1", launchId: "l_1", status: "ok" }),
+ )
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_stopped_ack", agentId: "bot_1", launchId: "l_1", status: "ok" }),
+ )
+
+ expect(mockLogDebug).toHaveBeenCalledTimes(2)
+ expect(storage.put).not.toHaveBeenCalled()
+ expect(storage.delete).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("does not evict pending attribution for stopped errors or malformed wake launch ids", async () => {
+ const { durable, store, storage } = createDO()
+ seedIdentity(store)
+ store.set("reset-pending:l_stopped", { kind: "session_reset", trigger: "single" })
+ store.set("reset-pending:l_wake", { kind: "nap" })
+
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({
+ type: "agent_stopped_ack",
+ agentId: "bot_1",
+ launchId: "l_stopped",
+ status: "error",
+ error: { code: "stop_failed", message: "boom" },
+ }),
+ )
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({
+ type: "agent_wake_ack",
+ agentId: "bot_1",
+ launchId: 42,
+ status: "error",
+ error: { code: "spawn_failed", message: "boom" },
+ }),
+ )
+
+ expect(store.get("reset-pending:l_stopped")).toEqual({ kind: "session_reset", trigger: "single" })
+ expect(store.get("reset-pending:l_wake")).toEqual({ kind: "nap" })
+ expect(storage.delete).not.toHaveBeenCalled()
+ })
+
+ it("normalizes malformed session-error payload fields without evicting a bogus launch", async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date("2026-08-08T00:00:00.000Z"))
+ const { durable, store, storage } = createDO()
+ seedIdentity(store)
+ store.set("reset-pending:l_keep", { kind: "nap" })
+
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({
+ type: "session.error",
+ code: "runtime_not_available",
+ launchId: 42,
+ payload: { requested: 42, available: ["codex", 7, null] },
+ }),
+ )
+
+ expect(store.get("community-machine-runtime-error")).toEqual({
+ requested: "",
+ available: ["codex"],
+ at: "2026-08-08T00:00:00.000Z",
+ })
+ expect(store.get("reset-pending:l_keep")).toEqual({ kind: "nap" })
+ expect(storage.delete).not.toHaveBeenCalled()
+ })
+
+ it("stops ready processing before reconciliation, handle storage, and alarm when the row is missing", async () => {
+ const { durable, store, storage } = createDO()
+ seedIdentity(store)
+ mockUpsertMachineByMachineId.mockResolvedValue(null)
+
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "ready", runtimeReport: [], runningAgents: [] }),
+ )
+
+ expect(mockReconcileBotActivityFromRunningAgents).not.toHaveBeenCalled()
+ expect(storage.put).not.toHaveBeenCalled()
+ expect(storage.setAlarm).not.toHaveBeenCalled()
+ })
+
+ it("classifies ready write failures while keeping the socket open", async () => {
+ const { durable, store } = createDO()
+ seedIdentity(store)
+ mockUpsertMachineByMachineId.mockRejectedValue(new Error("D1 unavailable"))
+ const ws = machineWs()
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "ready", runtimeReport: [], runningAgents: [] }),
+ )
+
+ expect(ws.close).not.toHaveBeenCalled()
+ expect(mockLogWarn).toHaveBeenCalledWith(
+ "ws_frame_dropped",
+ expect.objectContaining({
+ category: "ws_frame_dropped",
+ frame_type: "ready",
+ phase: "write",
+ machineId: "cm_1",
+ }),
+ )
+ })
+
+ it("emits machine.updated for status or lastError drift and emits nothing for steady runtimes", async () => {
+ const { durable, store } = createDO()
+ seedIdentity(store)
+ const baseMachine = {
+ id: "cm_1",
+ hostname: "host",
+ availableRuntimes: [{ id: "codex", version: "1", status: "unhealthy", lastError: "ENOENT" }],
+ status: "online",
+ lastSeenAt: "2026-08-08T00:00:00.000Z",
+ }
+ mockUpsertMachineByMachineId.mockResolvedValue({
+ machine: baseMachine,
+ priorLastSeenAt: "2026-08-07T00:00:00.000Z",
+ priorAvailableRuntimes: [{ id: "codex", version: "1", status: "healthy" }],
+ priorStatus: "online",
+ })
+
+ const driftFrame = JSON.stringify({
+ type: "ready",
+ runtimeReport: [{ id: "codex", version: "1", status: "unhealthy", lastError: "ENOENT" }],
+ runningAgents: [],
+ })
+ await durable.webSocketMessage(machineWs() as any, driftFrame)
+
+ const driftBodies = await Promise.all(
+ mockStubFetch.mock.calls.map((call: any[]) => (call[0] as Request).clone().json() as Promise<any>),
+ )
+ expect(driftBodies.filter((body) => body.type === "community:machine.updated")).toHaveLength(1)
+ expect(driftBodies.filter((body) => body.type === "community:machine.status")).toHaveLength(0)
+
+ mockStubFetch.mockClear()
+ mockUpsertMachineByMachineId.mockResolvedValue({
+ machine: baseMachine,
+ priorLastSeenAt: "2026-08-08T00:00:00.000Z",
+ priorAvailableRuntimes: baseMachine.availableRuntimes,
+ priorStatus: "online",
+ })
+
+ await durable.webSocketMessage(machineWs() as any, driftFrame)
+
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/src/ws-do/src/ws-durable/machine-frames.ts b/src/ws-do/src/ws-durable/machine-frames.ts
new file mode 100644
index 000000000..05538b8dc
--- /dev/null
+++ b/src/ws-do/src/ws-durable/machine-frames.ts
@@ -0,0 +1,74 @@
+import { IDENTITY_KEY } from "./internal"
+import type { CommunityMachineIdentity, WsDurableContext } from "./internal"
+import { handleReadyFrame } from "./machine-ready"
+import {
+ handleAgentCommandAck,
+ handleAgentSessionFrame,
+ handleSessionErrorFrame,
+} from "./machine-restart"
+import type { MachineRestartHooks } from "./machine-restart"
+import {
+ handleActivityFrame,
+ handleAuditFrame,
+ handleTypingFrame,
+ handleTypingStopFrame,
+} from "./machine-telemetry"
+
+export async function handleCommunityMachineMessage(
+ context: WsDurableContext,
+ parsed: unknown,
+ hooks: MachineRestartHooks,
+): Promise<void> {
+ const identity = await context.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)
+ if (!identity) {
+ context.log.warn("community machine message with no cached identity")
+ return
+ }
+
+ // The router is intentionally first-match. Keep identity before every
+ // frame and preserve ack → session error → activity → typing → typing stop
+ // → agent session → audit → strict ready. A recognized frame is consumed
+ // even when its handler drops it for binding, persistence, or payload state.
+ if (await handleAgentCommandAck(
+ context,
+ parsed,
+ identity,
+ )) return
+ if (await handleSessionErrorFrame(
+ context,
+ parsed,
+ identity,
+ hooks,
+ )) return
+ if (await handleActivityFrame(
+ context,
+ parsed,
+ identity,
+ )) return
+ if (await handleTypingFrame(
+ context,
+ parsed,
+ identity,
+ )) return
+ if (await handleTypingStopFrame(
+ context,
+ parsed,
+ identity,
+ )) return
+ if (await handleAgentSessionFrame(
+ context,
+ parsed,
+ identity,
+ hooks,
+ )) return
+ if (await handleAuditFrame(
+ context,
+ parsed,
+ identity,
+ )) return
+ await handleReadyFrame(
+ context,
+ parsed,
+ identity,
+ )
+}
diff --git a/src/ws-do/src/ws-durable/machine-lifecycle.test.ts b/src/ws-do/src/ws-durable/machine-lifecycle.test.ts
new file mode 100644
index 000000000..c17e99a09
--- /dev/null
+++ b/src/ws-do/src/ws-durable/machine-lifecycle.test.ts
@@ -0,0 +1,482 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { createMockWebSocket } from "../__mocks__/cf"
+import {
+ CFResponse,
+ cleanupHarness,
+ createDO,
+ flushAsyncWork,
+ mockCheckAliveFetch,
+ mockCreateDb,
+ mockFindCredentialByHash,
+ mockGetBotBinding,
+ mockGetBotBindingWithOwner,
+ mockGetChannelForMember,
+ mockGetChannelType,
+ mockGetCoMemberUserIds,
+ mockGetDM,
+ mockGetFriendUserIds,
+ mockGetLatestTokenForUser,
+ mockGetMachineByDaemon,
+ mockGetMachineByIdForUser,
+ mockGetMachineTokenByToken,
+ mockGetPrivateChannelAudienceUserIds,
+ mockGetProfile,
+ mockGetRuntimeIdsByDaemon,
+ mockGetUserInternal,
+ mockGetValidSession,
+ mockGetValidSessionWithIdentity,
+ mockHashCredential,
+ mockInsertBotActivityEventAndPrune,
+ mockInsertBotAuditModelChanged,
+ mockInsertBotAuditNap,
+ mockInsertBotAuditProviderChanged,
+ mockInsertBotAuditSessionReset,
+ mockIsBotOnline,
+ mockIsChannelPrivate,
+ mockListBotsForMachine,
+ mockListChannelMemberUserIds,
+ mockListMembers,
+ mockListThreadParticipantUserIds,
+ mockMarkMachineOffline,
+ mockMarkMachineOnlineIfOffline,
+ mockReconcileBotActivityFromRunningAgents,
+ mockResolveScopeMemberUserIds,
+ mockStubFetch,
+ mockToSummary,
+ mockTouchBotRefreshContext,
+ mockTouchMachineHeartbeat,
+ mockUpdateProfile,
+ mockUpsertMachineByMachineId,
+ resetHarness
+} from "./test-harness"
+
+describe("WebSocketDurableObject", () => {
+ beforeEach(() => resetHarness())
+ afterEach(() => cleanupHarness())
+
+ describe("community-machine — webSocketClose presence lifecycle", () => {
+ // These tests cover the "graceful daemon quit → immediate offline" fix.
+ // See plans/community-machine-presence-fix.md § Server transitions.
+ it("flips status=offline via credential-scoped markMachineOffline and broadcasts on real transition", async () => {
+ const { durable, store, ctx } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ // Arm a placeholder alarm so we can check deleteAlarm ran.
+ await ctx.storage.setAlarm(Date.now() + 90_000)
+ mockMarkMachineOffline.mockResolvedValueOnce({
+ id: "cm_1",
+ userId: "u_1",
+ status: "offline",
+ lastSeenAt: "2026-07-06T00:00:00.000Z",
+ })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ await durable.webSocketClose(ws as any)
+
+ expect(mockMarkMachineOffline).toHaveBeenCalledTimes(1)
+ const [, args] = mockMarkMachineOffline.mock.calls[0]!
+ expect(args).toMatchObject({
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ // Broadcast fired via notifyUserDO → user DO's /broadcast endpoint.
+ expect(mockStubFetch).toHaveBeenCalled()
+ // Alarm was cleaned up and storage keys deleted.
+ expect(ctx.storage.deleteAlarm).toHaveBeenCalled()
+ expect(store.has("community-machine-identity")).toBe(false)
+ expect(store.has("community-machine-handle")).toBe(false)
+ })
+
+ it("null return (credential revoked or already offline) does NOT broadcast and leaves the alarm armed", async () => {
+ const { durable, store, ctx } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "revoked",
+ })
+ mockMarkMachineOffline.mockResolvedValueOnce(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ mockStubFetch.mockClear()
+ await durable.webSocketClose(ws as any)
+
+ expect(mockMarkMachineOffline).toHaveBeenCalledTimes(1)
+ // No broadcast fired — the guarded UPDATE returned zero rows.
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ // Alarm armed as the safety-net fallback (setAlarm was called; not deleted).
+ expect(ctx.storage.setAlarm).toHaveBeenCalled()
+ expect(ctx.storage.deleteAlarm).not.toHaveBeenCalled()
+ // Storage keys retained — a different DO instance may own the row now.
+ expect(store.has("community-machine-identity")).toBe(true)
+ })
+
+ it("missing IDENTITY_KEY (never fully accepted) is a clean no-op — no markMachineOffline, no alarm", async () => {
+ const { durable, store, ctx } = createDO()
+ // No identity in storage.
+ expect(store.has("community-machine-identity")).toBe(false)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ // Clear any setAlarm calls made during createDO setup.
+ ; (ctx.storage.setAlarm as any).mockClear?.()
+
+ await durable.webSocketClose(ws as any)
+
+ expect(mockMarkMachineOffline).not.toHaveBeenCalled()
+ // No alarm armed — with no identity there's nothing recoverable to do.
+ // HANDLE_KEY is written alongside IDENTITY_KEY, so if identity is gone
+ // the alarm has no state to act on either.
+ expect(ctx.storage.setAlarm).not.toHaveBeenCalled()
+ })
+ })
+
+ describe("community-machine — alarm presence + backfill", () => {
+ it("live-WS + status=offline row: markMachineOnlineIfOffline flips it back online and broadcasts (post-deploy backfill)", async () => {
+ const { durable, store, getWebSockets, ctx } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "abc",
+ })
+
+ // Attach a live authenticated community-machine WS.
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ getWebSockets.mockReturnValue([ws])
+
+ mockTouchMachineHeartbeat.mockResolvedValueOnce({
+ lastSeenAt: "now",
+ priorLastSeenAt: "earlier",
+ })
+ mockMarkMachineOnlineIfOffline.mockResolvedValueOnce({
+ id: "cm_1",
+ userId: "u_1",
+ status: "online",
+ lastSeenAt: "now",
+ })
+
+ mockStubFetch.mockClear()
+ await durable.alarm()
+
+ expect(mockTouchMachineHeartbeat).toHaveBeenCalledTimes(1)
+ expect(mockMarkMachineOnlineIfOffline).toHaveBeenCalledTimes(1)
+ // Broadcast fired for the offline→online transition.
+ expect(mockStubFetch).toHaveBeenCalled()
+ // Alarm rescheduled for the next heartbeat tick.
+ expect(ctx.storage.setAlarm).toHaveBeenCalled()
+ })
+
+ it("live-WS + status=online row (steady state): no broadcast fires (double-broadcast regression guard)", async () => {
+ const { durable, store, getWebSockets, ctx } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "abc",
+ })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ getWebSockets.mockReturnValue([ws])
+
+ mockTouchMachineHeartbeat.mockResolvedValueOnce({
+ lastSeenAt: "now",
+ priorLastSeenAt: "earlier",
+ })
+ // Guarded UPDATE returns zero rows — row is already online.
+ mockMarkMachineOnlineIfOffline.mockResolvedValueOnce(null)
+
+ mockStubFetch.mockClear()
+ await durable.alarm()
+
+ expect(mockTouchMachineHeartbeat).toHaveBeenCalledTimes(1)
+ // No broadcast — the guarded UPDATE returned zero rows.
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ // Alarm rescheduled.
+ expect(ctx.storage.setAlarm).toHaveBeenCalled()
+ })
+
+ it("no-live-WS + stale row: markMachineOffline flips + broadcasts + cleans HANDLE_KEY / IDENTITY_KEY", async () => {
+ const { durable, store, getWebSockets, ctx } = createDO()
+ // No live WS.
+ getWebSockets.mockReturnValue([])
+ store.set("community-machine-handle", { userId: "u_1", machineId: "cm_1" })
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "abc",
+ })
+ // Stale row — lastSeenAt is more than 120s (mocked threshold) ago.
+ mockGetMachineByIdForUser.mockResolvedValueOnce({
+ id: "cm_1",
+ userId: "u_1",
+ status: "online",
+ lastSeenAt: new Date(Date.now() - 200_000).toISOString(),
+ availableRuntimes: [],
+ })
+ mockMarkMachineOffline.mockResolvedValueOnce({
+ id: "cm_1",
+ userId: "u_1",
+ status: "offline",
+ lastSeenAt: "now",
+ })
+
+ mockStubFetch.mockClear()
+ await durable.alarm()
+
+ expect(mockMarkMachineOffline).toHaveBeenCalledTimes(1)
+ expect(mockStubFetch).toHaveBeenCalled()
+ expect(store.has("community-machine-handle")).toBe(false)
+ expect(store.has("community-machine-identity")).toBe(false)
+ // No further alarm reschedule after the terminal offline flip.
+ // (setAlarm may have been called on the earlier setup path; we assert
+ // deleteAlarm was NOT called since alarm() doesn't need to explicitly
+ // delete — it just doesn't reschedule.)
+ expect(ctx.storage.deleteAlarm).not.toHaveBeenCalled()
+ })
+
+ it("no-live-WS + stale row + no identity (mid-lifecycle wipe): still broadcasts offline using stored handle so UI sees the transition", async () => {
+ const { durable, store, getWebSockets, ctx } = createDO()
+ getWebSockets.mockReturnValue([])
+ // HANDLE_KEY is present (written at accept) but IDENTITY_KEY was
+ // wiped mid-lifecycle. The stale-flip branch can't run the
+ // credential-scoped UPDATE, but must still broadcast so the UI
+ // reflects the transition.
+ store.set("community-machine-handle", { userId: "u_1", machineId: "cm_1" })
+ expect(store.has("community-machine-identity")).toBe(false)
+
+ mockGetMachineByIdForUser.mockResolvedValueOnce({
+ id: "cm_1",
+ userId: "u_1",
+ status: "online",
+ lastSeenAt: new Date(Date.now() - 200_000).toISOString(),
+ availableRuntimes: [],
+ })
+
+ mockStubFetch.mockClear()
+ await durable.alarm()
+
+ // DB flip skipped (no identity to scope the credential guard).
+ expect(mockMarkMachineOffline).not.toHaveBeenCalled()
+ // But the UI broadcast MUST still fire — otherwise the machine
+ // chip stays green until reload.
+ expect(mockStubFetch).toHaveBeenCalled()
+ // Storage keys dropped — this DO's presence lifecycle is done.
+ expect(store.has("community-machine-handle")).toBe(false)
+ expect(ctx.storage.deleteAlarm).not.toHaveBeenCalled()
+ })
+
+ it("no-live-WS + fresh row: reschedules alarm to exact stale moment, no broadcast, no DB flip", async () => {
+ const { durable, store, getWebSockets, ctx } = createDO()
+ getWebSockets.mockReturnValue([])
+ store.set("community-machine-handle", { userId: "u_1", machineId: "cm_1" })
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "abc",
+ })
+ // Fresh row — lastSeenAt is 10s ago.
+ mockGetMachineByIdForUser.mockResolvedValueOnce({
+ id: "cm_1",
+ userId: "u_1",
+ status: "online",
+ lastSeenAt: new Date(Date.now() - 10_000).toISOString(),
+ availableRuntimes: [],
+ })
+
+ mockStubFetch.mockClear()
+ await durable.alarm()
+
+ expect(mockMarkMachineOffline).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ // Storage keys retained; alarm rescheduled precisely to the stale moment.
+ expect(store.has("community-machine-handle")).toBe(true)
+ expect(store.has("community-machine-identity")).toBe(true)
+ expect(ctx.storage.setAlarm).toHaveBeenCalled()
+ })
+ })
+
+ describe("C2b characterization — machine lifecycle", () => {
+ it("arms the exact offline retry when close-time D1 marking rejects", async () => {
+ vi.spyOn(Date, "now").mockReturnValue(3_000_000)
+ const { durable, store, storage } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "hash",
+ })
+ mockMarkMachineOffline.mockRejectedValueOnce(new Error("d1 unavailable"))
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ await expect(durable.webSocketClose(ws as any)).resolves.toBeUndefined()
+ expect(storage.setAlarm).toHaveBeenCalledWith(3_120_000)
+ })
+
+ it("does nothing when an alarm has no live socket and no stored handle", async () => {
+ const { durable, getWebSockets, storage } = createDO()
+ getWebSockets.mockReturnValue([])
+
+ await expect(durable.alarm()).resolves.toBeUndefined()
+
+ expect(mockGetMachineByIdForUser).not.toHaveBeenCalled()
+ expect(mockMarkMachineOffline).not.toHaveBeenCalled()
+ expect(storage.setAlarm).not.toHaveBeenCalled()
+ expect(storage.delete).not.toHaveBeenCalled()
+ })
+
+ it("cleans handle then identity when the stored machine row is missing", async () => {
+ const { durable, getWebSockets, store, storage } = createDO()
+ getWebSockets.mockReturnValue([])
+ store.set("community-machine-handle", { userId: "u_1", machineId: "cm_1" })
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "hash",
+ })
+ mockGetMachineByIdForUser.mockResolvedValueOnce(null)
+
+ await durable.alarm()
+
+ expect(storage.delete.mock.calls).toEqual([
+ ["community-machine-handle"],
+ ["community-machine-identity"],
+ ])
+ expect(storage.setAlarm).not.toHaveBeenCalled()
+ })
+
+ it("reschedules the exact heartbeat when live heartbeat touch rejects", async () => {
+ vi.spyOn(Date, "now").mockReturnValue(4_000_000)
+ const { durable, getWebSockets, storage } = createDO()
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ getWebSockets.mockReturnValue([ws])
+ mockTouchMachineHeartbeat.mockRejectedValueOnce(new Error("d1 unavailable"))
+
+ await expect(durable.alarm()).resolves.toBeUndefined()
+ expect(storage.setAlarm).toHaveBeenCalledWith(4_060_000)
+ })
+
+ it("reschedules the exact heartbeat when live online backfill rejects", async () => {
+ vi.spyOn(Date, "now").mockReturnValue(5_000_000)
+ const { durable, getWebSockets, store, storage } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "hash",
+ })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ getWebSockets.mockReturnValue([ws])
+ mockTouchMachineHeartbeat.mockResolvedValueOnce({ lastSeenAt: "now", priorLastSeenAt: "before" })
+ mockMarkMachineOnlineIfOffline.mockRejectedValueOnce(new Error("d1 unavailable"))
+
+ await expect(durable.alarm()).resolves.toBeUndefined()
+ expect(storage.setAlarm).toHaveBeenCalledWith(5_060_000)
+ })
+
+ it("cleans lifecycle storage when a stale offline flip rejects", async () => {
+ vi.spyOn(Date, "now").mockReturnValue(6_000_000)
+ const { durable, getWebSockets, store, storage } = createDO()
+ getWebSockets.mockReturnValue([])
+ store.set("community-machine-handle", { userId: "u_1", machineId: "cm_1" })
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "hash",
+ })
+ mockGetMachineByIdForUser.mockResolvedValueOnce({
+ id: "cm_1",
+ userId: "u_1",
+ status: "online",
+ lastSeenAt: new Date(5_800_000).toISOString(),
+ availableRuntimes: [],
+ })
+ mockMarkMachineOffline.mockRejectedValueOnce(new Error("d1 unavailable"))
+
+ await expect(durable.alarm()).resolves.toBeUndefined()
+ expect(storage.delete.mock.calls).toEqual([
+ ["community-machine-handle"],
+ ["community-machine-identity"],
+ ])
+ expect(storage.setAlarm).not.toHaveBeenCalled()
+ })
+
+ it("does not broadcast a stale null flip and still cleans lifecycle storage", async () => {
+ vi.spyOn(Date, "now").mockReturnValue(7_000_000)
+ const { durable, getWebSockets, store, storage } = createDO()
+ getWebSockets.mockReturnValue([])
+ store.set("community-machine-handle", { userId: "u_1", machineId: "cm_1" })
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "hash",
+ })
+ mockGetMachineByIdForUser.mockResolvedValueOnce({
+ id: "cm_1",
+ userId: "u_1",
+ status: "online",
+ lastSeenAt: new Date(6_800_000).toISOString(),
+ availableRuntimes: [],
+ })
+ mockMarkMachineOffline.mockResolvedValueOnce(null)
+ mockStubFetch.mockClear()
+
+ await durable.alarm()
+
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ expect(storage.delete.mock.calls).toEqual([
+ ["community-machine-handle"],
+ ["community-machine-identity"],
+ ])
+ })
+ })
+})
diff --git a/src/ws-do/src/ws-durable/machine-lifecycle.ts b/src/ws-do/src/ws-durable/machine-lifecycle.ts
new file mode 100644
index 000000000..5a2e4f020
--- /dev/null
+++ b/src/ws-do/src/ws-durable/machine-lifecycle.ts
@@ -0,0 +1,148 @@
+import {
+ COMMUNITY_MACHINE_HEARTBEAT_MS,
+ COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS,
+ WS_EVENTS,
+ createDb,
+ queries,
+} from "@alook/shared"
+import { HANDLE_KEY, IDENTITY_KEY } from "./internal"
+import type {
+ CommunityMachineConnectionState,
+ CommunityMachineHandle,
+ CommunityMachineIdentity,
+ ConnectionState,
+ WsDurableContext,
+} from "./internal"
+import { notifyUserDO } from "./presence-typing"
+
+export async function scheduleHeartbeatAlarm(context: WsDurableContext): Promise<void> {
+ const current = await context.ctx.storage.getAlarm()
+ const want = Date.now() + COMMUNITY_MACHINE_HEARTBEAT_MS
+ if (current == null || current > want) {
+ await context.ctx.storage.setAlarm(want)
+ }
+}
+
+export async function handleCommunityMachineClose(
+ context: WsDurableContext,
+ state: CommunityMachineConnectionState,
+): Promise<void> {
+ context.log.info("community machine websocket closed", { machineId: state.machineId, userId: state.userId })
+ const identity = await context.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)
+ if (!identity) return
+ try {
+ const db = createDb(context.env.DB)
+ const flipped = await queries.communityMachine.markMachineOffline(db, {
+ userId: identity.userId,
+ machineId: identity.machineId,
+ credentialHash: identity.credentialHash,
+ })
+ if (flipped) {
+ await notifyUserDO(context, identity.userId, {
+ type: WS_EVENTS.MACHINE_STATUS,
+ machineId: identity.machineId,
+ status: "offline",
+ lastSeenAt: flipped.lastSeenAt ?? new Date().toISOString(),
+ }).catch(() => { })
+ await context.ctx.storage.deleteAlarm()
+ await context.ctx.storage.delete(HANDLE_KEY)
+ await context.ctx.storage.delete(IDENTITY_KEY)
+ } else {
+ await context.ctx.storage.setAlarm(Date.now() + COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS)
+ }
+ } catch (err) {
+ context.log.warn("markMachineOffline failed on webSocketClose", { err: String(err) })
+ await context.ctx.storage.setAlarm(Date.now() + COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS)
+ }
+}
+
+export async function handleMachineAlarm(context: WsDurableContext): Promise<void> {
+ const sockets = context.ctx.getWebSockets()
+ const liveMachines: Array<{ userId: string; machineId: string }> = []
+ for (const ws of sockets) {
+ const s = ws.deserializeAttachment() as ConnectionState
+ if (s?.type === "community-machine" && s.authenticated) {
+ liveMachines.push({ userId: s.userId, machineId: s.machineId })
+ }
+ }
+
+ if (liveMachines.length > 0) {
+ const db = createDb(context.env.DB)
+ const identity = await context.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)
+ for (const m of liveMachines) {
+ try {
+ await queries.communityMachine.touchMachineHeartbeat(db, m.userId, m.machineId)
+ } catch { /* ok */ }
+ if (identity && identity.userId === m.userId && identity.machineId === m.machineId) {
+ try {
+ const backfilled = await queries.communityMachine.markMachineOnlineIfOffline(db, {
+ userId: identity.userId,
+ machineId: identity.machineId,
+ credentialHash: identity.credentialHash,
+ })
+ if (backfilled) {
+ await notifyUserDO(context, identity.userId, {
+ type: WS_EVENTS.MACHINE_STATUS,
+ machineId: identity.machineId,
+ status: "online",
+ lastSeenAt: backfilled.lastSeenAt ?? new Date().toISOString(),
+ }).catch(() => { })
+ }
+ } catch (err) {
+ context.log.warn("markMachineOnlineIfOffline (alarm live-WS) failed", { err: String(err) })
+ }
+ }
+ }
+ await context.ctx.storage.setAlarm(Date.now() + COMMUNITY_MACHINE_HEARTBEAT_MS)
+ return
+ }
+
+ const stored = await context.ctx.storage.get<CommunityMachineHandle>(HANDLE_KEY)
+ if (!stored) return
+ const identity = await context.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)
+ const db = createDb(context.env.DB)
+ const machine = await queries.communityMachine.getMachineByIdForUser(
+ db,
+ stored.userId,
+ stored.machineId
+ )
+ if (!machine) {
+ await context.ctx.storage.delete(HANDLE_KEY)
+ await context.ctx.storage.delete(IDENTITY_KEY)
+ return
+ }
+ const lastSeen = machine.lastSeenAt ? Date.parse(machine.lastSeenAt) : 0
+ const elapsed = Date.now() - lastSeen
+ if (elapsed >= COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS) {
+ if (identity) {
+ try {
+ const flipped = await queries.communityMachine.markMachineOffline(db, {
+ userId: identity.userId,
+ machineId: identity.machineId,
+ credentialHash: identity.credentialHash,
+ })
+ if (flipped) {
+ await notifyUserDO(context, stored.userId, {
+ type: WS_EVENTS.MACHINE_STATUS,
+ machineId: stored.machineId,
+ status: "offline",
+ lastSeenAt: flipped.lastSeenAt ?? new Date().toISOString(),
+ }).catch(() => { })
+ }
+ } catch (err) {
+ context.log.warn("markMachineOffline (alarm stale-flip) failed", { err: String(err) })
+ }
+ } else {
+ await notifyUserDO(context, stored.userId, {
+ type: WS_EVENTS.MACHINE_STATUS,
+ machineId: stored.machineId,
+ status: "offline",
+ lastSeenAt: machine.lastSeenAt ?? new Date().toISOString(),
+ }).catch(() => { })
+ }
+ await context.ctx.storage.delete(HANDLE_KEY)
+ await context.ctx.storage.delete(IDENTITY_KEY)
+ return
+ }
+ await context.ctx.storage.setAlarm(Date.now() + (COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS - elapsed))
+}
diff --git a/src/ws-do/src/ws-durable/machine-ready.ts b/src/ws-do/src/ws-durable/machine-ready.ts
new file mode 100644
index 000000000..752b79fc0
--- /dev/null
+++ b/src/ws-do/src/ws-durable/machine-ready.ts
@@ -0,0 +1,177 @@
+import {
+ createDb,
+ HostReadyMessageSchema,
+ queries,
+ WS_EVENTS,
+} from "@alook/shared"
+import type { CommunityMachineRuntime, CommunityMachineSummary } from "@alook/shared"
+import {
+ HANDLE_KEY,
+ IDENTITY_KEY,
+ RUNTIME_ERROR_KEY,
+} from "./internal"
+import type {
+ CommunityMachineHandle,
+ CommunityMachineIdentity,
+ WsDurableContext,
+} from "./internal"
+import { scheduleHeartbeatAlarm } from "./machine-lifecycle"
+import { broadcastToAudience, notifyUserDO } from "./presence-typing"
+
+/**
+ * Order-normalized runtime JSON includes status and lastError, so a health
+ * transition is observable even when id and version remain unchanged.
+ */
+function canonicalRuntimes(list: CommunityMachineRuntime[]): string {
+ const sorted = [...list].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
+ return JSON.stringify(
+ sorted.map((runtime) => ({
+ id: runtime.id,
+ ...(runtime.version !== undefined ? { version: runtime.version } : {}),
+ status: runtime.status ?? "healthy",
+ ...(runtime.lastError !== undefined ? { lastError: runtime.lastError } : {}),
+ }))
+ )
+}
+
+async function summaryWithOverlay(
+ context: WsDurableContext,
+ row: Parameters<typeof queries.communityMachine.toSummary>[0],
+): Promise<CommunityMachineSummary> {
+ // The runtime error is transient DO-local state, not a D1 field. Overlay it
+ // only at summary construction so persistence stays authoritative.
+ const base = queries.communityMachine.toSummary(row)
+ const overlay = await context.ctx.storage.get<{
+ requested: string
+ available: string[]
+ at: string
+ }>(RUNTIME_ERROR_KEY)
+ return overlay ? { ...base, lastRuntimeError: overlay } : base
+}
+
+/**
+ * Only strict flat ready frames reach persistence. A missing machine row
+ * stops before reconciliation, handle refresh, notification, or alarm work.
+ * Every write-side failure is classified and swallowed so the live socket
+ * remains available for the next heartbeat.
+ */
+export async function handleReadyFrame(
+ context: WsDurableContext,
+ parsed: unknown,
+ identity: CommunityMachineIdentity,
+): Promise<boolean> {
+ const readyParse = HostReadyMessageSchema.safeParse(parsed)
+ if (!readyParse.success) return false
+ const ready = readyParse.data
+ try {
+ const hostname = ready.hostname ?? ""
+ const platform = ready.platform ?? ""
+ const arch = ready.arch ?? ""
+ const daemonVersion = ready.daemonVersion ?? ""
+ const osRelease = ready.osRelease ?? ""
+ const availableRuntimes: CommunityMachineRuntime[] = ready.runtimeReport
+
+ const db = createDb(context.env.DB)
+ const result = await queries.communityMachine.upsertMachineByMachineId(
+ db,
+ identity.userId,
+ identity.machineId,
+ { hostname, platform, arch, daemonVersion, osRelease, availableRuntimes }
+ )
+ if (!result) {
+ context.log.warn("community machine row missing on ready", { machineId: identity.machineId })
+ return true
+ }
+ const { machine, priorAvailableRuntimes, priorStatus } = result
+
+ // Reconciliation is the coarse safety net for an activity frame lost
+ // during disconnect. It clears only stale system-owned activity pills;
+ // owner-authored custom statuses remain untouched in the query layer.
+ const activityChanges = await queries.communityMachine.reconcileBotActivityFromRunningAgents(
+ db,
+ machine.id,
+ ready.runningAgents
+ )
+ await Promise.allSettled(
+ activityChanges.map(({ botUserId, statusEmoji, statusText }) =>
+ broadcastToAudience(context, botUserId, {
+ type: WS_EVENTS.STATUS_UPDATE,
+ userId: botUserId,
+ statusEmoji,
+ statusText,
+ })
+ )
+ )
+
+ const summary = await summaryWithOverlay(context, machine)
+ // Accept writes the handle first; ready refreshes it idempotently in case
+ // the machine metadata or row identity changed during reconciliation.
+ await context.ctx.storage.put<CommunityMachineHandle>(HANDLE_KEY, {
+ userId: identity.userId,
+ machineId: machine.id,
+ })
+
+ // Activation owns machine.created. Ready emits status only for an actual
+ // offline → online transition, using the pre-upsert status returned by D1.
+ if (priorStatus !== "online") {
+ await notifyUserDO(context, identity.userId, {
+ type: WS_EVENTS.MACHINE_STATUS,
+ machineId: machine.id,
+ status: "online",
+ lastSeenAt: machine.lastSeenAt ?? new Date().toISOString(),
+ }).catch(() => { })
+ }
+
+ const priorCanonical = canonicalRuntimes(priorAvailableRuntimes ?? [])
+ const nextCanonical = canonicalRuntimes(availableRuntimes)
+ // Runtime status/lastError drift is machine metadata drift and must reach
+ // open clients even when the runtime set and versions are unchanged.
+ if (priorCanonical !== nextCanonical) {
+ await notifyUserDO(context, identity.userId, {
+ type: WS_EVENTS.MACHINE_UPDATED,
+ machine: summary,
+ }).catch(() => { })
+ }
+
+ await scheduleHeartbeatAlarm(context)
+ } catch (err) {
+ context.log.warn("ws_frame_dropped", {
+ category: "ws_frame_dropped",
+ frame_type: "ready",
+ phase: "write",
+ machineId: identity.machineId,
+ err: err instanceof Error ? err : new Error(String(err)),
+ })
+ }
+ return true
+}
+
+/**
+ * Wakes and force-close optimistically clear the transient runtime error. A
+ * stored overlay is deleted before the fresh summary is fanned out; missing
+ * identity or a missing row leaves the operation a safe no-op.
+ */
+export async function clearRuntimeErrorOverlay(context: WsDurableContext): Promise<void> {
+ const overlay = await context.ctx.storage.get(RUNTIME_ERROR_KEY)
+ if (overlay === undefined) return
+ await context.ctx.storage.delete(RUNTIME_ERROR_KEY)
+ const identity = await context.ctx.storage.get<CommunityMachineIdentity>(IDENTITY_KEY)
+ if (!identity) return
+ await fanOutMachineUpdated(context, identity.userId, identity.machineId).catch(() => { })
+}
+
+/** Compose a fresh D1 summary with the current DO-local overlay and notify its owner. */
+export async function fanOutMachineUpdated(
+ context: WsDurableContext,
+ userId: string,
+ machineId: string,
+): Promise<void> {
+ const db = createDb(context.env.DB)
+ const row = await queries.communityMachine.getMachineByIdForUser(db, userId, machineId)
+ if (!row) return
+ const summary = await summaryWithOverlay(context, row)
+ await notifyUserDO(context, userId, {
+ type: WS_EVENTS.MACHINE_UPDATED,
+ machine: summary,
+ })
+}
diff --git a/src/ws-do/src/ws-durable/machine-restart.test.ts b/src/ws-do/src/ws-durable/machine-restart.test.ts
new file mode 100644
index 000000000..54fdc3779
--- /dev/null
+++ b/src/ws-do/src/ws-durable/machine-restart.test.ts
@@ -0,0 +1,514 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { createMockWebSocket } from "../__mocks__/cf"
+import {
+ CFResponse,
+ cleanupHarness,
+ createDO,
+ flushAsyncWork,
+ mockCheckAliveFetch,
+ mockCreateDb,
+ mockFindCredentialByHash,
+ mockGetBotBinding,
+ mockGetBotBindingWithOwner,
+ mockGetChannelForMember,
+ mockGetChannelType,
+ mockGetCoMemberUserIds,
+ mockGetDM,
+ mockGetFriendUserIds,
+ mockGetLatestTokenForUser,
+ mockGetMachineByDaemon,
+ mockGetMachineByIdForUser,
+ mockGetMachineTokenByToken,
+ mockGetPrivateChannelAudienceUserIds,
+ mockGetProfile,
+ mockGetRuntimeIdsByDaemon,
+ mockGetUserInternal,
+ mockGetValidSession,
+ mockGetValidSessionWithIdentity,
+ mockHashCredential,
+ mockInsertBotActivityEventAndPrune,
+ mockInsertBotAuditModelChanged,
+ mockInsertBotAuditNap,
+ mockInsertBotAuditProviderChanged,
+ mockInsertBotAuditSessionReset,
+ mockIsBotOnline,
+ mockIsChannelPrivate,
+ mockListBotsForMachine,
+ mockListChannelMemberUserIds,
+ mockListMembers,
+ mockListThreadParticipantUserIds,
+ mockLogDebug,
+ mockLogWarn,
+ mockMarkMachineOffline,
+ mockMarkMachineOnlineIfOffline,
+ mockReconcileBotActivityFromRunningAgents,
+ mockResolveScopeMemberUserIds,
+ mockStubFetch,
+ mockToSummary,
+ mockTouchBotRefreshContext,
+ mockTouchMachineHeartbeat,
+ mockUpdateProfile,
+ mockUpsertMachineByMachineId,
+ resetHarness
+} from "./test-harness"
+
+describe("WebSocketDurableObject", () => {
+ beforeEach(() => resetHarness())
+ afterEach(() => cleanupHarness())
+
+ describe("community-machine — reset/nap completion re-home (agent_session landing)", () => {
+ beforeEach(() => {
+ mockInsertBotAuditSessionReset.mockReset()
+ mockInsertBotAuditNap.mockReset()
+ mockInsertBotAuditModelChanged.mockReset()
+ mockInsertBotAuditProviderChanged.mockReset()
+ mockTouchBotRefreshContext.mockReset()
+ mockGetBotBindingWithOwner.mockReset()
+ mockStubFetch.mockClear()
+ mockInsertBotAuditSessionReset.mockResolvedValue({ id: "bae_reset", createdAt: "2025-06-01T10:00:00.000Z" })
+ mockInsertBotAuditNap.mockResolvedValue({ id: "bae_nap", createdAt: "2025-06-01T11:00:00.000Z" })
+ mockInsertBotAuditModelChanged.mockResolvedValue({ id: "bae_model", createdAt: "2025-06-01T12:00:00.000Z" })
+ mockInsertBotAuditProviderChanged.mockResolvedValue({ id: "bae_provider", createdAt: "2025-06-01T13:00:00.000Z" })
+ mockTouchBotRefreshContext.mockResolvedValue(undefined)
+ mockGetBotBindingWithOwner.mockResolvedValue({
+ machineId: "cm_1",
+ runtime: "codex",
+ ownerUserId: "owner_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+ })
+
+ function machineWs() {
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
+ return ws
+ }
+
+ function seedIdentity(store: Map<string, unknown>) {
+ store.set("community-machine-identity", { userId: "u_1", machineId: "cm_1", credentialHash: "0".repeat(64) })
+ }
+
+ // record-iff-sent>0: pending is only written when a live community-machine
+ // socket accepts the forward. Seed one so /push and /push-*-switch tests
+ // exercise the completion landing (offline → sent=0 → no pending).
+ function onlineDaemon() {
+ const { durable, store, getWebSockets } = createDO()
+ seedIdentity(store)
+ const daemon = machineWs()
+ getWebSockets.mockReturnValue([daemon])
+ return { durable, store, daemon }
+ }
+
+ // Helper: push a frame through /push (records pending attribution), matching
+ // how the index worker forwards reset/nap frames to this DO.
+ async function pushFrame(durable: any, body: unknown) {
+ await durable.fetch(
+ new (globalThis.Request as any)("http://internal/push", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ )
+ }
+
+ async function pushSwitch(durable: any, kind: "provider" | "model", body: Record<string, unknown>) {
+ await durable.fetch(
+ new (globalThis.Request as any)(`http://internal/push-${kind}-switch`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ )
+ }
+
+ function auditBroadcast() {
+ return mockStubFetch.mock.calls
+ .map((c: any[]) => c[0] as Request)
+ .find((r: Request) => r.url.endsWith("/broadcast"))
+ }
+
+ it("single reset: agent_session writes session_reset audit + stamps awake in lockstep + broadcasts", async () => {
+ const { durable } = onlineDaemon()
+ // Dispatch: an agent:reset frame is forwarded → records launchId→single.
+ await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
+ // Completion: the reborn agent's agent_session lands.
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" }),
+ )
+
+ // Audit written server-side with the trigger derived from the endpoint.
+ expect(mockInsertBotAuditSessionReset).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ botId: "bot_1", launchId: "l_reset", trigger: "single" }),
+ )
+ expect(mockInsertBotAuditNap).not.toHaveBeenCalled()
+ // LOCKSTEP invariant: touch uses the audit row's own createdAt, not another clock.
+ expect(mockTouchBotRefreshContext).toHaveBeenCalledWith(expect.anything(), "bot_1", "2025-06-01T10:00:00.000Z")
+ // Broadcast to the owner carries the session_reset event.
+ const call = auditBroadcast()
+ expect(call).toBeDefined()
+ const body = JSON.parse(await (call!).clone().text()) as Record<string, unknown>
+ expect(body).toEqual({
+ type: "community:bot.audit_event",
+ botId: "bot_1",
+ id: "bae_reset",
+ kind: "session_reset",
+ payload: { trigger: "single" },
+ sessionId: null,
+ launchId: "l_reset",
+ createdAt: "2025-06-01T10:00:00.000Z",
+ })
+ })
+
+ it("two agent_session frames for the same launch write the reset audit ONCE (claim-first evict, no double record)", async () => {
+ const { durable } = onlineDaemon()
+ await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
+ // Two agent_session frames arrive back-to-back for the SAME launch (e.g. a
+ // runtime that announces its session twice). The pending trigger must be
+ // consumed by the first → the second finds nothing → only ONE audit row.
+ const frame = JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" })
+ await durable.webSocketMessage(machineWs() as any, frame)
+ await durable.webSocketMessage(machineWs() as any, frame)
+
+ expect(mockInsertBotAuditSessionReset).toHaveBeenCalledTimes(1)
+ })
+
+ it("batch reset: each agent's agent_session writes session_reset with trigger reset_all", async () => {
+ const { durable } = onlineDaemon()
+ // Dispatch: ONE machine:reset_all frame carrying two launches.
+ await pushFrame(durable, {
+ type: "machine:reset_all",
+ resets: [
+ { agentId: "bot_1", config: {}, launchId: "l_a" },
+ { agentId: "bot_2", config: {}, launchId: "l_b" },
+ ],
+ })
+ // Both agents reborn — two agent_session frames.
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_a", launchId: "l_a" }),
+ )
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_2", sessionId: "s_b", launchId: "l_b" }),
+ )
+
+ expect(mockInsertBotAuditSessionReset).toHaveBeenCalledTimes(2)
+ expect(mockInsertBotAuditSessionReset).toHaveBeenNthCalledWith(
+ 1,
+ expect.anything(),
+ expect.objectContaining({ botId: "bot_1", launchId: "l_a", trigger: "reset_all" }),
+ )
+ expect(mockInsertBotAuditSessionReset).toHaveBeenNthCalledWith(
+ 2,
+ expect.anything(),
+ expect.objectContaining({ botId: "bot_2", launchId: "l_b", trigger: "reset_all" }),
+ )
+ expect(mockTouchBotRefreshContext).toHaveBeenCalledTimes(2)
+ })
+
+ it("nap: agent_session writes nap audit (trigger nap) + stamps awake in lockstep + broadcasts", async () => {
+ const { durable } = onlineDaemon()
+ await pushFrame(durable, { type: "agent:nap", agentId: "bot_1", config: {}, launchId: "l_nap", handoff: "note" })
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_nap" }),
+ )
+
+ expect(mockInsertBotAuditNap).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ botId: "bot_1", launchId: "l_nap" }),
+ )
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).toHaveBeenCalledWith(expect.anything(), "bot_1", "2025-06-01T11:00:00.000Z")
+ const body = JSON.parse(await (auditBroadcast()!).clone().text()) as Record<string, unknown>
+ expect(body).toMatchObject({ kind: "nap", payload: { trigger: "nap" }, launchId: "l_nap" })
+ })
+
+ it("fire-once: a replayed agent_session for the same launch writes nothing the second time", async () => {
+ const { durable } = onlineDaemon()
+ await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
+ const frame = JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" })
+ await durable.webSocketMessage(machineWs() as any, frame)
+ await durable.webSocketMessage(machineWs() as any, frame) // replay
+
+ // Exactly one write despite two agent_session frames — the pending entry
+ // was consumed (deleted) on the first.
+ expect(mockInsertBotAuditSessionReset).toHaveBeenCalledTimes(1)
+ expect(mockTouchBotRefreshContext).toHaveBeenCalledTimes(1)
+ })
+
+ it("no pending launch: an ordinary agent_session (never a reset/nap) writes nothing", async () => {
+ const { durable, store } = createDO()
+ seedIdentity(store)
+ // No /push recorded this launch — a plain wake session.
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_plain" }),
+ )
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockInsertBotAuditNap).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
+ })
+
+ it("offline push (sent===0): records no pending — later agent_session writes nothing", async () => {
+ const { durable, store, getWebSockets } = createDO()
+ seedIdentity(store)
+ getWebSockets.mockReturnValue([])
+ await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_offline" })
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_offline" }),
+ )
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
+ })
+
+ // Cecilia #1270: landing must dispatch by pending.kind — provider stamps
+ // awake; model does not; payloads stay in their namespaces.
+ it("provider_switch: agent_session writes provider_changed {from,to} + stamps awake (not model_changed)", async () => {
+ const { durable } = onlineDaemon()
+ await pushSwitch(durable, "provider", {
+ agentId: "bot_1",
+ config: { runtime: "codex" },
+ launchId: "l_prov",
+ from: "claude",
+ to: "codex",
+ })
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_prov" }),
+ )
+
+ expect(mockInsertBotAuditProviderChanged).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ botId: "bot_1", launchId: "l_prov", from: "claude", to: "codex" }),
+ )
+ expect(mockInsertBotAuditModelChanged).not.toHaveBeenCalled()
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).toHaveBeenCalledWith(expect.anything(), "bot_1", "2025-06-01T13:00:00.000Z")
+ const body = JSON.parse(await (auditBroadcast()!).clone().text()) as Record<string, unknown>
+ expect(body).toMatchObject({
+ kind: "provider_changed",
+ payload: { from: "claude", to: "codex" },
+ launchId: "l_prov",
+ })
+ })
+
+ // Cecilia #1279: provider PATCH clears model as a binding side-effect, but
+ // landing must emit exactly one provider_changed — never a sibling model_changed.
+ it("provider_switch with cleared model in config → exactly one provider_changed, zero model_changed", async () => {
+ const { durable } = onlineDaemon()
+ await pushSwitch(durable, "provider", {
+ agentId: "bot_1",
+ // Mirrors route after provider switch: runtime flipped + model null→default.
+ config: { runtime: "codex", model: { kind: "default" } },
+ launchId: "l_prov_clear_model",
+ from: "claude",
+ to: "codex",
+ })
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({
+ type: "agent_session",
+ agentId: "bot_1",
+ sessionId: "s_new",
+ launchId: "l_prov_clear_model",
+ }),
+ )
+
+ expect(mockInsertBotAuditProviderChanged).toHaveBeenCalledTimes(1)
+ expect(mockInsertBotAuditProviderChanged).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ botId: "bot_1",
+ launchId: "l_prov_clear_model",
+ from: "claude",
+ to: "codex",
+ }),
+ )
+ expect(mockInsertBotAuditModelChanged).not.toHaveBeenCalled()
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ const broadcasts = mockStubFetch.mock.calls
+ .map((c: any[]) => c[0] as Request)
+ .filter((r: Request) => r.url.endsWith("/broadcast"))
+ expect(broadcasts).toHaveLength(1)
+ const body = JSON.parse(await broadcasts[0]!.clone().text()) as Record<string, unknown>
+ expect(body.kind).toBe("provider_changed")
+ expect(body.kind).not.toBe("model_changed")
+ })
+
+ it("model_switch: agent_session writes model_changed {from,to} and does NOT stamp awake", async () => {
+ const { durable } = onlineDaemon()
+ await pushSwitch(durable, "model", {
+ agentId: "bot_1",
+ config: { model: { kind: "named", name: "opus" } },
+ launchId: "l_model",
+ from: null,
+ to: "opus",
+ })
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_model" }),
+ )
+
+ expect(mockInsertBotAuditModelChanged).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ botId: "bot_1", launchId: "l_model", from: null, to: "opus" }),
+ )
+ expect(mockInsertBotAuditProviderChanged).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
+ const body = JSON.parse(await (auditBroadcast()!).clone().text()) as Record<string, unknown>
+ expect(body).toMatchObject({
+ kind: "model_changed",
+ payload: { from: null, to: "opus" },
+ launchId: "l_model",
+ })
+ })
+
+ it("cold-start fail branch B (agent_wake_ack error): evicts pending, no audit/awake, and a later replayed agent_session stays silent", async () => {
+ const { durable } = onlineDaemon()
+ await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
+ // Enroll fail / spawn threw → wake_ack error for this launch.
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_wake_ack", agentId: "bot_1", launchId: "l_reset", status: "error", error: { code: "spawn_threw", message: "boom" } }),
+ )
+ // If (impossibly) an agent_session arrives later, the entry is already gone
+ // → nothing written. This is the red-line-② positive proof.
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" }),
+ )
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
+ })
+
+ it("cold-start fail branch A (session.error runtime_not_available): evicts pending, no audit/awake", async () => {
+ const { durable } = onlineDaemon()
+ await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
+ // Runtime not installed → session.error carrying the launchId (Melisa's source half).
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "session.error", code: "runtime_not_available", agentId: "bot_1", launchId: "l_reset", payload: { requested: "codex", available: [] } }),
+ )
+ await durable.webSocketMessage(
+ machineWs() as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" }),
+ )
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
+ })
+ })
+
+ describe("C2c characterization — machine restart", () => {
+ beforeEach(() => {
+ mockGetBotBindingWithOwner.mockReset()
+ mockInsertBotAuditSessionReset.mockReset()
+ mockStubFetch.mockClear()
+ })
+
+ function setup() {
+ const result = createDO()
+ result.store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ return { ...result, ws }
+ }
+
+ it("consumes the pending claim before dropping a machine-binding mismatch", async () => {
+ const { durable, store, ws } = setup()
+ store.set("reset-pending:l_mismatch", { kind: "session_reset", trigger: "single" })
+ mockGetBotBindingWithOwner.mockResolvedValue({
+ machineId: "cm_other",
+ runtime: "codex",
+ ownerUserId: "owner_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_1", launchId: "l_mismatch" }),
+ )
+
+ expect(store.has("reset-pending:l_mismatch")).toBe(false)
+ expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
+ })
+
+ it("keeps claims consumed after binding and write failures", async () => {
+ const first = setup()
+ first.store.set("reset-pending:l_binding", { kind: "session_reset", trigger: "single" })
+ mockGetBotBindingWithOwner.mockRejectedValueOnce(new Error("binding failed"))
+
+ await first.durable.webSocketMessage(
+ first.ws as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_1", launchId: "l_binding" }),
+ )
+
+ const second = setup()
+ second.store.set("reset-pending:l_write", { kind: "session_reset", trigger: "single" })
+ mockGetBotBindingWithOwner.mockResolvedValueOnce({
+ machineId: "cm_1",
+ runtime: "codex",
+ ownerUserId: "owner_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+ mockInsertBotAuditSessionReset.mockRejectedValueOnce(new Error("write failed"))
+
+ await second.durable.webSocketMessage(
+ second.ws as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_2", launchId: "l_write" }),
+ )
+
+ expect(first.store.has("reset-pending:l_binding")).toBe(false)
+ expect(second.store.has("reset-pending:l_write")).toBe(false)
+ })
+
+ it("records only valid launch ids from malformed, unknown, and mixed reset frames in order", async () => {
+ const { durable, getWebSockets, storage } = setup()
+ const daemon = createMockWebSocket()
+ daemon.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ getWebSockets.mockReturnValue([daemon])
+ const push = (body: string) => durable.fetch(
+ new (globalThis.Request as any)("http://internal/push", { method: "POST", body }),
+ )
+
+ await push("{")
+ await push(JSON.stringify({ type: "unknown", launchId: "l_unknown" }))
+ storage.put.mockClear()
+ await push(JSON.stringify({
+ type: "machine:reset_all",
+ resets: [
+ { agentId: "bot_1", launchId: "l_1" },
+ null,
+ { agentId: "bot_2", launchId: "" },
+ { agentId: "bot_3", launchId: "l_2" },
+ { agentId: "bot_4", launchId: 4 },
+ ],
+ }))
+
+ expect(storage.put.mock.calls).toEqual([
+ ["reset-pending:l_1", { kind: "session_reset", trigger: "reset_all" }],
+ ["reset-pending:l_2", { kind: "session_reset", trigger: "reset_all" }],
+ ])
+ })
+ })
+})
diff --git a/src/ws-do/src/ws-durable/machine-restart.ts b/src/ws-do/src/ws-durable/machine-restart.ts
new file mode 100644
index 000000000..e744e1685
--- /dev/null
+++ b/src/ws-do/src/ws-durable/machine-restart.ts
@@ -0,0 +1,201 @@
+import {
+ AgentSessionMessageSchema,
+ createDb,
+ queries,
+ SessionErrorFrameSchema,
+ withD1Retry,
+ WS_EVENTS,
+} from "@alook/shared"
+import { handleFrameForBoundBot } from "./bound-bot-frame"
+import {
+ normalizeRestartAttribution,
+ restartPendingKey,
+ RUNTIME_ERROR_KEY,
+} from "./internal"
+import type {
+ CommunityMachineIdentity,
+ ResetTrigger,
+ RestartAttribution,
+ WsDurableContext,
+} from "./internal"
+
+export type MachineRestartHooks = Readonly<{
+ fanOutMachineUpdated: (userId: string, machineId: string) => Promise<void>
+ notifyUser: (userId: string, payload: unknown) => Promise<void>
+}>
+
+export async function handleAgentCommandAck(
+ context: WsDurableContext,
+ parsed: unknown,
+ identity: CommunityMachineIdentity,
+): Promise<boolean> {
+ if (
+ !parsed || typeof parsed !== "object" || !("type" in parsed) ||
+ typeof (parsed as { type: unknown }).type !== "string" ||
+ (
+ (parsed as { type: string }).type !== "agent_wake_ack" &&
+ (parsed as { type: string }).type !== "agent_stopped_ack"
+ )
+ ) return false
+
+ const ack = parsed as {
+ type: string
+ agentId?: string
+ launchId?: string
+ status?: string
+ error?: { code?: string; message?: string }
+ }
+ if (ack.status === "error") {
+ context.log.warn("agent command ack error", {
+ machineId: identity.machineId,
+ type: ack.type,
+ agentId: ack.agentId,
+ code: ack.error?.code,
+ message: ack.error?.message,
+ })
+ if (ack.type === "agent_wake_ack" && typeof ack.launchId === "string" && ack.launchId.length > 0) {
+ await evictPendingReset(context, ack.launchId)
+ }
+ } else if (ack.status === "ok") {
+ context.log.debug("agent command ack ok", {
+ machineId: identity.machineId,
+ type: ack.type,
+ agentId: ack.agentId,
+ })
+ }
+ return true
+}
+
+export async function handleSessionErrorFrame(
+ context: WsDurableContext,
+ parsed: unknown,
+ identity: CommunityMachineIdentity,
+ hooks: MachineRestartHooks,
+): Promise<boolean> {
+ const sessionErrorParse = SessionErrorFrameSchema.safeParse(parsed)
+ if (!sessionErrorParse.success || sessionErrorParse.data.code !== "runtime_not_available") return false
+
+ const payload = sessionErrorParse.data.payload ?? {}
+ const requested = typeof payload.requested === "string" ? payload.requested : ""
+ const availableRaw = Array.isArray(payload.available) ? payload.available : []
+ const available = availableRaw.filter((value): value is string => typeof value === "string")
+ const overlay = { requested, available, at: new Date().toISOString() }
+ await context.ctx.storage.put(RUNTIME_ERROR_KEY, overlay)
+ const launchId = sessionErrorParse.data.launchId
+ if (typeof launchId === "string" && launchId.length > 0) {
+ await evictPendingReset(context, launchId)
+ }
+ await hooks.fanOutMachineUpdated(identity.userId, identity.machineId).catch(() => { })
+ return true
+}
+
+export async function handleAgentSessionFrame(
+ context: WsDurableContext,
+ parsed: unknown,
+ identity: CommunityMachineIdentity,
+ hooks: MachineRestartHooks,
+): Promise<boolean> {
+ const sessionParse = AgentSessionMessageSchema.safeParse(parsed)
+ if (!sessionParse.success) return false
+
+ const { agentId, launchId } = sessionParse.data
+ const stored = await context.ctx.storage.get<ResetTrigger | RestartAttribution>(restartPendingKey(launchId))
+ if (!stored) return true
+ const attribution = normalizeRestartAttribution(stored)
+ await evictPendingReset(context, launchId)
+ const db = createDb(context.env.DB)
+ await handleFrameForBoundBot(context, {
+ frameType: "agent_session",
+ agentId,
+ machineId: identity.machineId,
+ writeCategory: "ws_frame_dropped_write",
+ resolveBinding: () => withD1Retry(
+ () => queries.communityBot.getBotBindingWithOwner(db, agentId),
+ { route: "ws-do:agent-session-binding" },
+ ),
+ isMatch: (binding) => binding.machineId === identity.machineId,
+ write: async (binding) => {
+ const inserted = attribution.kind === "nap"
+ ? await queries.communityBotAuditLog.insertBotAuditNap(db, { botId: agentId, launchId })
+ : attribution.kind === "session_reset"
+ ? await queries.communityBotAuditLog.insertBotAuditSessionReset(db, {
+ botId: agentId,
+ launchId,
+ trigger: attribution.trigger,
+ })
+ : attribution.kind === "model_switch"
+ ? await queries.communityBotAuditLog.insertBotAuditModelChanged(db, {
+ botId: agentId,
+ launchId,
+ from: attribution.from,
+ to: attribution.to,
+ })
+ : await queries.communityBotAuditLog.insertBotAuditProviderChanged(db, {
+ botId: agentId,
+ launchId,
+ from: attribution.from,
+ to: attribution.to,
+ })
+ if (!inserted) return
+ if (attribution.kind !== "model_switch") {
+ await queries.communityBot.touchBotRefreshContext(db, agentId, inserted.createdAt)
+ }
+ const payload = attribution.kind === "nap"
+ ? { trigger: "nap" }
+ : attribution.kind === "session_reset"
+ ? { trigger: attribution.trigger }
+ : { from: attribution.from, to: attribution.to }
+ await hooks.notifyUser(binding.ownerUserId, {
+ type: WS_EVENTS.BOT_AUDIT_EVENT,
+ botId: agentId,
+ id: inserted.id,
+ kind: attribution.kind === "provider_switch"
+ ? "provider_changed"
+ : attribution.kind === "model_switch"
+ ? "model_changed"
+ : attribution.kind,
+ payload,
+ sessionId: null,
+ launchId,
+ createdAt: inserted.createdAt,
+ }).catch(() => { })
+ },
+ })
+ return true
+}
+
+export async function recordPendingRestarts(
+ context: WsDurableContext,
+ body: string,
+): Promise<void> {
+ let frame: unknown
+ try {
+ frame = JSON.parse(body)
+ } catch {
+ return
+ }
+ if (!frame || typeof frame !== "object") return
+ const parsed = frame as { type?: unknown }
+ const put = async (launchId: unknown, attribution: RestartAttribution) => {
+ if (typeof launchId !== "string" || launchId.length === 0) return
+ await context.ctx.storage.put<RestartAttribution>(restartPendingKey(launchId), attribution)
+ }
+ if (parsed.type === "agent:reset") {
+ await put((parsed as { launchId?: unknown }).launchId, { kind: "session_reset", trigger: "single" })
+ } else if (parsed.type === "agent:nap") {
+ await put((parsed as { launchId?: unknown }).launchId, { kind: "nap" })
+ } else if (parsed.type === "machine:reset_all") {
+ const resets = (parsed as { resets?: unknown }).resets
+ if (Array.isArray(resets)) {
+ for (const reset of resets) {
+ if (reset && typeof reset === "object") {
+ await put((reset as { launchId?: unknown }).launchId, { kind: "session_reset", trigger: "reset_all" })
+ }
+ }
+ }
+ }
+}
+
+async function evictPendingReset(context: WsDurableContext, launchId: string): Promise<void> {
+ await context.ctx.storage.delete(restartPendingKey(launchId))
+}
diff --git a/src/ws-do/src/ws-durable/machine-telemetry.test.ts b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
new file mode 100644
index 000000000..b6a941215
--- /dev/null
+++ b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
@@ -0,0 +1,832 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { createMockWebSocket } from "../__mocks__/cf"
+import {
+ CFResponse,
+ cleanupHarness,
+ createDO,
+ flushAsyncWork,
+ mockCheckAliveFetch,
+ mockCreateDb,
+ mockFindCredentialByHash,
+ mockGetBotBinding,
+ mockGetBotBindingWithOwner,
+ mockGetChannelForMember,
+ mockGetChannelType,
+ mockGetCoMemberUserIds,
+ mockGetDM,
+ mockGetFriendUserIds,
+ mockGetLatestTokenForUser,
+ mockGetMachineByDaemon,
+ mockGetMachineByIdForUser,
+ mockGetMachineTokenByToken,
+ mockGetPrivateChannelAudienceUserIds,
+ mockGetProfile,
+ mockGetRuntimeIdsByDaemon,
+ mockGetUserInternal,
+ mockGetValidSession,
+ mockGetValidSessionWithIdentity,
+ mockHashCredential,
+ mockInsertBotActivityEventAndPrune,
+ mockInsertBotAuditModelChanged,
+ mockInsertBotAuditNap,
+ mockInsertBotAuditProviderChanged,
+ mockInsertBotAuditSessionReset,
+ mockIsBotOnline,
+ mockIsChannelPrivate,
+ mockListBotsForMachine,
+ mockListChannelMemberUserIds,
+ mockListMembers,
+ mockListThreadParticipantUserIds,
+ mockLogDebug,
+ mockLogWarn,
+ mockMarkMachineOffline,
+ mockMarkMachineOnlineIfOffline,
+ mockReconcileBotActivityFromRunningAgents,
+ mockResolveScopeMemberUserIds,
+ mockStubFetch,
+ mockToSummary,
+ mockTouchBotRefreshContext,
+ mockTouchMachineHeartbeat,
+ mockUpdateProfile,
+ mockUpsertMachineByMachineId,
+ resetHarness
+} from "./test-harness"
+
+describe("WebSocketDurableObject", () => {
+ beforeEach(() => resetHarness())
+ afterEach(() => cleanupHarness())
+
+ describe("community-machine — agent_activity frame", () => {
+ beforeEach(() => {
+ mockGetBotBinding.mockReset()
+ mockUpdateProfile.mockReset().mockResolvedValue({})
+ mockGetProfile.mockReset().mockResolvedValue(null)
+ mockStubFetch.mockClear()
+ })
+
+ it("writes the translated statusEmoji/statusText via updateProfile and fans out community:status.update when the frame's machine owns the bot", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })
+ mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" })
+ await durable.webSocketMessage(ws as any, frame)
+
+ // The (stubbed) `pickBotActivityPreset` returns a fixed pair for
+ // "running" in this test — the assertion pins that exact pair.
+ expect(mockUpdateProfile).toHaveBeenCalledWith(expect.anything(), "bot_1", {
+ statusEmoji: "⚡",
+ statusText: "Working on it",
+ })
+ const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
+ expect(call).toBeDefined()
+ const body = JSON.parse(await (call![0] as Request).clone().text()) as {
+ type: string
+ userId: string
+ statusEmoji: string
+ statusText: string
+ }
+ expect(body).toEqual({
+ type: "community:status.update",
+ userId: "bot_1",
+ statusEmoji: "⚡",
+ statusText: "Working on it",
+ })
+ })
+
+ it("drops a frame naming a bot bound to a different machine — no DB write, no fan-out", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_OTHER", runtime: "codex" })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockUpdateProfile).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("drops a frame for an unbound (unknown) bot — no DB write, no fan-out", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBinding.mockResolvedValue(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({ type: "agent_activity", agentId: "ghost_bot", state: "idle" })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockUpdateProfile).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("regression #3 — an owner-set custom status is NOT overwritten by a running frame (write-path guard); no DB write, no fan-out", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })
+ // Prior status is a custom (non-preset) pair the owner set.
+ mockGetProfile.mockResolvedValue({ statusEmoji: "🎨", statusText: "Painting" })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
+
+ const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" })
+ await durable.webSocketMessage(ws as any, frame)
+
+ // Guard skips the write entirely — custom status survives, even though the
+ // bot is working. This is what stops T6's heartbeat re-stomp every 5s.
+ expect(mockUpdateProfile).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("regression #3b — a BRAND-NEW bot (profile row exists but status unset: emoji=null, text=\"\") still gets its status written", async () => {
+ // `status_text` defaults to "" in the schema, so an unset status reads
+ // back as (null, "") not (null, null). The custom-status guard must treat
+ // that as "no status" (writable), NOT mistake "" for a custom status —
+ // otherwise new bots never get a pill (the reported regression).
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })
+ mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
+ mockGetProfile.mockResolvedValue({ statusEmoji: null, statusText: "" })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
+
+ const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockUpdateProfile).toHaveBeenCalledWith(expect.anything(), "bot_1", {
+ statusEmoji: "⚡",
+ statusText: "Working on it",
+ })
+ })
+
+ it("regression #4 — a known idle preset still flips to running (guard didn't over-reach)", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })
+ mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
+ // Prior is the idle PRESET (pipeline-owned) — must remain writable.
+ mockGetProfile.mockResolvedValue({ statusEmoji: "💤", statusText: "Idle" })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
+
+ const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockUpdateProfile).toHaveBeenCalledWith(expect.anything(), "bot_1", {
+ statusEmoji: "⚡",
+ statusText: "Working on it",
+ })
+ })
+
+ it("regression #4 — a known running preset still flips back to idle (guard didn't over-reach)", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_1", runtime: "codex" })
+ mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
+ // Prior is a running PRESET — an idle frame must be allowed to overwrite it.
+ mockGetProfile.mockResolvedValue({ statusEmoji: "⚡", statusText: "Working on it" })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
+
+ const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "idle" })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockUpdateProfile).toHaveBeenCalledWith(expect.anything(), "bot_1", {
+ statusEmoji: "💤",
+ statusText: "Idle",
+ })
+ })
+
+ it("drops the frame with phase='binding_check' when getBotBinding throws — socket stays open, no write", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBinding.mockRejectedValue(new Error("D1 down"))
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockUpdateProfile).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ // Socket didn't close — the DO doesn't touch ws.close() on any per-frame D1 error.
+ expect(ws.close as ReturnType<typeof vi.fn>).not.toHaveBeenCalled()
+ })
+ })
+
+ describe("community-machine — agent_typing / agent_typing_stop frames", () => {
+ beforeEach(() => {
+ mockGetBotBindingWithOwner.mockReset()
+ mockGetChannelForMember.mockReset()
+ mockGetChannelType.mockReset()
+ mockGetChannelType.mockResolvedValue("dm")
+ mockListChannelMemberUserIds.mockReset()
+ mockListChannelMemberUserIds.mockResolvedValue([])
+ mockStubFetch.mockClear()
+ })
+
+ it("agent_typing: fans out community:typing.start to the DM peer when machine owns the bot and DM is valid", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBindingWithOwner.mockResolvedValue({
+ machineId: "cm_1",
+ runtime: "codex",
+ ownerUserId: "u_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+ mockGetChannelForMember.mockResolvedValue({ id: "dm_1", serverId: null })
+ mockGetChannelType.mockResolvedValue("dm")
+ mockListChannelMemberUserIds.mockResolvedValue(["bot_1", "peer_1"])
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({
+ type: "agent_typing",
+ agentId: "bot_1",
+ channelId: "dm_1",
+ })
+ await durable.webSocketMessage(ws as any, frame)
+
+ const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
+ expect(call).toBeDefined()
+ const body = JSON.parse(await (call![0] as Request).clone().text()) as {
+ type: string
+ userId: string
+ channelId: string
+ name?: string
+ discriminator?: string
+ }
+ // Bot path carries name/discriminator from the binding (getBotBindingWithOwner's
+ // existing join) so the client renders the bot's name without a roster lookup.
+ expect(body).toEqual({
+ type: "community:typing.start",
+ userId: "bot_1",
+ channelId: "dm_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+ })
+
+ it("agent_typing: drops a frame naming a bot bound to a different machine — no fan-out", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBindingWithOwner.mockResolvedValue({
+ machineId: "cm_OTHER",
+ runtime: "codex",
+ ownerUserId: "u_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({
+ type: "agent_typing",
+ agentId: "bot_1",
+ channelId: "dm_1",
+ })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockGetChannelForMember).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("agent_typing: drops a frame for a bot that is not a DM participant — no fan-out", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBindingWithOwner.mockResolvedValue({
+ machineId: "cm_1",
+ runtime: "codex",
+ ownerUserId: "u_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+ // Bot isn't a member of the channel → getChannelForMember returns null,
+ // so fanOutTyping bails before resolving recipients.
+ mockGetChannelForMember.mockResolvedValue(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({
+ type: "agent_typing",
+ agentId: "bot_1",
+ channelId: "dm_1",
+ })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("agent_typing_stop: fans out community:typing.stop to the DM peer, excludes sender", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBindingWithOwner.mockResolvedValue({
+ machineId: "cm_1",
+ runtime: "codex",
+ ownerUserId: "u_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+ mockGetChannelForMember.mockResolvedValue({ id: "dm_1", serverId: null })
+ mockGetChannelType.mockResolvedValue("dm")
+ mockListChannelMemberUserIds.mockResolvedValue(["bot_1", "peer_1"])
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({
+ type: "agent_typing_stop",
+ agentId: "bot_1",
+ channelId: "dm_1",
+ })
+ await durable.webSocketMessage(ws as any, frame)
+
+ const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
+ expect(call).toBeDefined()
+ const body = JSON.parse(await (call![0] as Request).clone().text()) as {
+ type: string
+ userId: string
+ channelId: string
+ }
+ expect(body).toEqual({
+ type: "community:typing.stop",
+ userId: "bot_1",
+ channelId: "dm_1",
+ })
+ // Sender exclusion: only the peer (peer_1) is targeted — a single
+ // /broadcast call, addressed via the peer's user DO.
+ expect(mockStubFetch.mock.calls.filter((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))).toHaveLength(1)
+ })
+ })
+
+ describe("community-machine — bot_audit_event frame", () => {
+ beforeEach(() => {
+ mockGetBotBindingWithOwner.mockReset()
+ mockInsertBotActivityEventAndPrune.mockReset()
+ mockStubFetch.mockClear()
+ })
+
+ it("inserts + prunes atomically and notifies the OWNER only when the machine owns the bot", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBindingWithOwner.mockResolvedValue({
+ machineId: "cm_1",
+ runtime: "codex",
+ ownerUserId: "owner_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+ mockInsertBotActivityEventAndPrune.mockResolvedValue({
+ id: "bae_abc",
+ createdAt: "2025-01-01T00:00:00.000Z",
+ })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({
+ type: "bot_audit_event",
+ agentId: "bot_1",
+ sessionId: "s_1",
+ launchId: "l_1",
+ event: { kind: "tool_call", payload: { name: "Read" } },
+ })
+ await durable.webSocketMessage(ws as any, frame)
+
+ // Insert was called with server-derived payload (not trust-the-daemon).
+ expect(mockInsertBotActivityEventAndPrune).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ botId: "bot_1",
+ sessionId: "s_1",
+ launchId: "l_1",
+ kind: "tool_call",
+ payload: JSON.stringify({ name: "Read" }),
+ }),
+ )
+ // Owner is notified via notifyUserDO — request goes to `user:owner_1`
+ // and the payload carries the full audit event including createdAt
+ // stamped server-side.
+ const call = mockStubFetch.mock.calls.find((c: any[]) => (c[0] as Request).url.endsWith("/broadcast"))
+ expect(call).toBeDefined()
+ const body = JSON.parse(await (call![0] as Request).clone().text()) as {
+ type: string
+ botId: string
+ id: string
+ kind: string
+ payload: unknown
+ createdAt: string
+ }
+ expect(body).toEqual({
+ type: "community:bot.audit_event",
+ botId: "bot_1",
+ id: "bae_abc",
+ kind: "tool_call",
+ payload: { name: "Read" },
+ sessionId: "s_1",
+ launchId: "l_1",
+ createdAt: "2025-01-01T00:00:00.000Z",
+ })
+ })
+
+ it("drops a frame naming a bot bound to a different machine — no insert, no fan-out", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBindingWithOwner.mockResolvedValue({
+ machineId: "cm_OTHER",
+ runtime: "codex",
+ ownerUserId: "owner_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({
+ type: "bot_audit_event",
+ agentId: "bot_1",
+ event: { kind: "cli_invocation", payload: { subcommand: "send" } },
+ })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockInsertBotActivityEventAndPrune).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("drops a frame for a soft-deleted/unknown bot — no insert, no fan-out", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBindingWithOwner.mockResolvedValue(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({
+ type: "bot_audit_event",
+ agentId: "ghost_bot",
+ event: { kind: "thinking", payload: { text: "hmm", truncated: false, chars: 3 } },
+ })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockInsertBotActivityEventAndPrune).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("does not fan out when the INSERT returns null (empty batch result)", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBindingWithOwner.mockResolvedValue({
+ machineId: "cm_1",
+ runtime: "codex",
+ ownerUserId: "owner_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+ // Simulate the D1 batch returning no rows for the primary statement.
+ mockInsertBotActivityEventAndPrune.mockResolvedValue(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({
+ type: "bot_audit_event",
+ agentId: "bot_1",
+ event: { kind: "tool_call", payload: { name: "Read" } },
+ })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("drops the frame with phase='write' when the insert throws — socket stays open, no fan-out", async () => {
+ // This is the ws_frame_dropped_write category — the audit-loss SLO
+ // signal. The DO must NOT close the socket, and no owner fan-out
+ // should be emitted (the row was never persisted).
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBindingWithOwner.mockResolvedValue({
+ machineId: "cm_1",
+ runtime: "codex",
+ ownerUserId: "owner_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+ mockInsertBotActivityEventAndPrune.mockRejectedValue(new Error("D1 insert failed"))
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ const frame = JSON.stringify({
+ type: "bot_audit_event",
+ agentId: "bot_1",
+ event: { kind: "tool_call", payload: { name: "Read" } },
+ })
+ await durable.webSocketMessage(ws as any, frame)
+
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ expect(ws.close as ReturnType<typeof vi.fn>).not.toHaveBeenCalled()
+ })
+ })
+
+ describe("C2c characterization — machine telemetry", () => {
+ beforeEach(() => {
+ mockGetBotBinding.mockReset()
+ mockGetBotBindingWithOwner.mockReset()
+ mockGetChannelForMember.mockReset()
+ mockGetProfile.mockReset().mockResolvedValue(null)
+ mockUpdateProfile.mockReset().mockResolvedValue({})
+ mockInsertBotAuditNap.mockReset()
+ mockInsertBotActivityEventAndPrune.mockReset()
+ mockTouchBotRefreshContext.mockReset().mockResolvedValue(undefined)
+ mockStubFetch.mockClear()
+ })
+
+ function setup() {
+ const result = createDO()
+ result.store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ return { ...result, ws }
+ }
+
+ const binding = {
+ machineId: "cm_1",
+ runtime: "codex",
+ ownerUserId: "owner_1",
+ name: "Bot",
+ discriminator: "0007",
+ }
+
+ it("does not rewrite or fan out an unchanged running activity preset", async () => {
+ const { durable, ws } = setup()
+ mockGetBotBinding.mockResolvedValue(binding)
+ mockGetProfile.mockResolvedValue({ statusEmoji: "⚡", statusText: "Working on it" })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" }),
+ )
+
+ expect(mockUpdateProfile).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("classifies activity write failures as plain write drops", async () => {
+ const { durable, ws } = setup()
+ mockGetBotBinding.mockResolvedValue(binding)
+ mockGetProfile.mockRejectedValue(new Error("D1 unavailable"))
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "agent_activity", agentId: "bot_1", state: "running" }),
+ )
+
+ expect(mockLogWarn).toHaveBeenCalledWith(
+ "ws_frame_dropped",
+ expect.objectContaining({
+ category: "ws_frame_dropped",
+ frame_type: "agent_activity",
+ phase: "write",
+ }),
+ )
+ })
+
+ it("classifies typing binding failures before the write phase", async () => {
+ const { durable, ws } = setup()
+ mockGetBotBindingWithOwner.mockRejectedValue(new Error("D1 unavailable"))
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "agent_typing", agentId: "bot_1", channelId: "dm_1" }),
+ )
+
+ expect(mockLogWarn).toHaveBeenCalledWith(
+ "ws_frame_dropped",
+ expect.objectContaining({
+ category: "ws_frame_dropped",
+ frame_type: "agent_typing",
+ phase: "binding_check",
+ }),
+ )
+ })
+
+ it("classifies typing fan-out failures as plain write drops", async () => {
+ const { durable, ws } = setup()
+ mockGetBotBindingWithOwner.mockResolvedValue(binding)
+ mockGetChannelForMember.mockRejectedValue(new Error("D1 unavailable"))
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "agent_typing", agentId: "bot_1", channelId: "dm_1" }),
+ )
+
+ expect(mockLogWarn).toHaveBeenCalledWith(
+ "ws_frame_dropped",
+ expect.objectContaining({
+ category: "ws_frame_dropped",
+ frame_type: "agent_typing",
+ phase: "write",
+ }),
+ )
+ })
+
+ it("keeps audit binding failures outside the audit-write SLO category", async () => {
+ const { durable, ws } = setup()
+ mockGetBotBindingWithOwner.mockRejectedValue(new Error("D1 unavailable"))
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({
+ type: "bot_audit_event",
+ agentId: "bot_1",
+ event: { kind: "tool_call", payload: { name: "Read" } },
+ }),
+ )
+
+ expect(mockLogWarn).toHaveBeenCalledWith(
+ "ws_frame_dropped",
+ expect.objectContaining({
+ category: "ws_frame_dropped",
+ frame_type: "bot_audit_event",
+ phase: "binding_check",
+ }),
+ )
+ })
+
+ it("skips awake and owner notification when an agent-session audit insert returns null", async () => {
+ const { durable, store, ws } = setup()
+ store.set("reset-pending:l_nap", { kind: "nap" })
+ mockGetBotBindingWithOwner.mockResolvedValue(binding)
+ mockInsertBotAuditNap.mockResolvedValue(null)
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_1", launchId: "l_nap" }),
+ )
+
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/src/ws-do/src/ws-durable/machine-telemetry.ts b/src/ws-do/src/ws-durable/machine-telemetry.ts
new file mode 100644
index 000000000..63f06f76f
--- /dev/null
+++ b/src/ws-do/src/ws-durable/machine-telemetry.ts
@@ -0,0 +1,241 @@
+import {
+ AgentActivityMessageSchema,
+ AgentTypingMessageSchema,
+ AgentTypingStopMessageSchema,
+ createDb,
+ HostBotAuditEventFrameSchema,
+ isBotActivityStatus,
+ pickBotActivityPreset,
+ queries,
+ RUNNING_PRESETS,
+ withD1Retry,
+ WS_EVENTS,
+} from "@alook/shared"
+import { handleFrameForBoundBot } from "./bound-bot-frame"
+import type { CommunityMachineIdentity, WsDurableContext } from "./internal"
+import {
+ broadcastToAudience,
+ fanOutTyping,
+ fanOutTypingStop,
+ notifyUserDO,
+} from "./presence-typing"
+
+/**
+ * Telemetry handlers are deliberately independent first-match branches. Each
+ * returns false only when its schema does not recognize the frame; once a
+ * schema matches, binding mismatches and write failures consume the frame.
+ * This keeps later schemas from observing a frame already owned by an earlier
+ * protocol branch and preserves the original monolith's drop behavior.
+ */
+
+/**
+ * Daemon activity is translated into the same status fields humans use, so
+ * downstream consumers never branch on whether the user is a bot. Running
+ * chooses one persisted preset per episode; repeated running frames reuse it.
+ * The reporting machine must own the bot before any profile write occurs.
+ * Empty status pairs remain writable, while a non-preset pair is treated as
+ * a custom owner status. The resulting update uses the common presence
+ * audience rather than a bot-specific delivery path.
+ */
+export async function handleActivityFrame(
+ context: WsDurableContext,
+ parsed: unknown,
+ identity: CommunityMachineIdentity,
+): Promise<boolean> {
+ const activityParse = AgentActivityMessageSchema.safeParse(parsed)
+ if (!activityParse.success) return false
+
+ const { agentId, state } = activityParse.data
+ const db = createDb(context.env.DB)
+ await handleFrameForBoundBot(context, {
+ frameType: "agent_activity",
+ agentId,
+ machineId: identity.machineId,
+ resolveBinding: () => queries.communityBot.getBotBinding(db, agentId),
+ isMatch: (binding) => binding.machineId === identity.machineId,
+ write: async () => {
+ const prior = await withD1Retry(
+ () => queries.communityUserProfile.getProfile(db, agentId),
+ { route: "ws-do:agent-activity-profile-read" },
+ )
+ const priorEmoji = prior?.statusEmoji ?? null
+ // `status_text` defaults to "". Normalize it to null so an unset status
+ // is writable and does not look like an owner-authored custom status.
+ const priorText = prior?.statusText ? prior.statusText : null
+ // This path owns only known activity pills. Any other persisted pair is
+ // owner-authored and must survive activity heartbeats unchanged.
+ if (
+ (priorEmoji !== null || priorText !== null) &&
+ !isBotActivityStatus(priorEmoji, priorText)
+ ) return
+ const priorIsRunning =
+ priorEmoji !== null &&
+ RUNNING_PRESETS.some((preset) => preset.emoji === priorEmoji && preset.text === priorText)
+ // Reuse an existing running preset instead of rerolling on every
+ // derived turn_end → idle → wake → running transition.
+ const preset =
+ state === "running" && priorIsRunning
+ ? { emoji: priorEmoji as string, text: priorText as string }
+ : pickBotActivityPreset(state, Math.random())
+ if (preset.emoji === priorEmoji && preset.text === priorText) return
+ await withD1Retry(
+ () => queries.communityUserProfile.updateProfile(db, agentId, {
+ statusEmoji: preset.emoji,
+ statusText: preset.text,
+ }),
+ { route: "ws-do:agent-activity-profile" },
+ )
+ await broadcastToAudience(context, agentId, {
+ type: WS_EVENTS.STATUS_UPDATE,
+ userId: agentId,
+ statusEmoji: preset.emoji,
+ statusText: preset.text,
+ })
+ },
+ })
+ return true
+}
+
+/**
+ * Daemon typing bypasses the client-inbound eight-second dedup gate. The
+ * daemon already meters its heartbeat and the client owns stale-indicator
+ * expiry; applying both gates here would make the typing pill flicker.
+ * Channel membership and reach are resolved inside the shared typing fan-out,
+ * keeping DM pairs, thread participants, and server/roster audiences aligned
+ * with human typing frames.
+ */
+export async function handleTypingFrame(
+ context: WsDurableContext,
+ parsed: unknown,
+ identity: CommunityMachineIdentity,
+): Promise<boolean> {
+ const typingParse = AgentTypingMessageSchema.safeParse(parsed)
+ if (!typingParse.success) return false
+
+ const { agentId, channelId } = typingParse.data
+ const db = createDb(context.env.DB)
+ await handleFrameForBoundBot(context, {
+ frameType: "agent_typing",
+ agentId,
+ machineId: identity.machineId,
+ resolveBinding: () => withD1Retry(
+ () => queries.communityBot.getBotBindingWithOwner(db, agentId),
+ { route: "ws-do:agent-typing-binding" },
+ ),
+ isMatch: (binding) => binding.machineId === identity.machineId,
+ write: async (binding) => {
+ // Membership is enforced by `fanOutTyping`; the binding already carries
+ // the bot display identity, avoiding another roster query per heartbeat.
+ const event = JSON.stringify({
+ type: WS_EVENTS.TYPING_START,
+ channelId,
+ userId: agentId,
+ name: binding.name,
+ discriminator: binding.discriminator,
+ })
+ await fanOutTyping(context, agentId, channelId, event)
+ },
+ })
+ return true
+}
+
+/**
+ * A stop frame uses the same binding check and reach resolver as a start but
+ * never traverses typing dedup. Stops must always land or the pill remains
+ * until client-side expiry.
+ */
+export async function handleTypingStopFrame(
+ context: WsDurableContext,
+ parsed: unknown,
+ identity: CommunityMachineIdentity,
+): Promise<boolean> {
+ const typingStopParse = AgentTypingStopMessageSchema.safeParse(parsed)
+ if (!typingStopParse.success) return false
+
+ const { agentId, channelId } = typingStopParse.data
+ const db = createDb(context.env.DB)
+ await handleFrameForBoundBot(context, {
+ frameType: "agent_typing_stop",
+ agentId,
+ machineId: identity.machineId,
+ resolveBinding: () => withD1Retry(
+ () => queries.communityBot.getBotBindingWithOwner(db, agentId),
+ { route: "ws-do:agent-typing-stop-binding" },
+ ),
+ isMatch: (binding) => binding.machineId === identity.machineId,
+ write: () => fanOutTypingStop(context, agentId, channelId),
+ })
+ return true
+}
+
+/**
+ * Audit payload serialization happens before the shared bound-bot scaffold.
+ * Serialization failures are not persistence loss and remain outside the
+ * `ws_frame_dropped_write` SLO; binding failures do too. Only the insert path
+ * uses the audit-write category, and successful rows notify the owner alone.
+ * Insert and rolling prune stay atomic in the query layer. The server-stamped
+ * row id and creation time are authoritative; daemon timestamps never enter
+ * the persisted or outbound event. A null insert produces no notification.
+ * This path must never use the general presence audience because per-bot
+ * activity is private to the owner.
+ * The stored payload remains a JSON string for the audit query while the
+ * outbound payload retains the parsed object shape. sessionId and launchId
+ * preserve null-vs-omitted normalization from the strict frame schema.
+ */
+export async function handleAuditFrame(
+ context: WsDurableContext,
+ parsed: unknown,
+ identity: CommunityMachineIdentity,
+): Promise<boolean> {
+ const auditParse = HostBotAuditEventFrameSchema.safeParse(parsed)
+ if (!auditParse.success) return false
+
+ const frame = auditParse.data
+ let payload: string
+ try {
+ payload = JSON.stringify(frame.event.payload)
+ } catch (err) {
+ context.log.warn("ws_frame_dropped", {
+ category: "ws_frame_dropped",
+ frame_type: "bot_audit_event",
+ phase: "serialize",
+ agentId: frame.agentId,
+ machineId: identity.machineId,
+ err: err instanceof Error ? err : new Error(String(err)),
+ })
+ return true
+ }
+ const db = createDb(context.env.DB)
+ await handleFrameForBoundBot(context, {
+ frameType: "bot_audit_event",
+ agentId: frame.agentId,
+ machineId: identity.machineId,
+ writeCategory: "ws_frame_dropped_write",
+ resolveBinding: () => withD1Retry(
+ () => queries.communityBot.getBotBindingWithOwner(db, frame.agentId),
+ { route: "ws-do:bot-audit-binding" },
+ ),
+ isMatch: (binding) => binding.machineId === identity.machineId,
+ write: async (binding) => {
+ const inserted = await queries.communityBotAuditLog.insertBotActivityEventAndPrune(db, {
+ botId: frame.agentId,
+ sessionId: frame.sessionId ?? null,
+ launchId: frame.launchId ?? null,
+ kind: frame.event.kind,
+ payload,
+ })
+ if (!inserted) return
+ await notifyUserDO(context, binding.ownerUserId, {
+ type: WS_EVENTS.BOT_AUDIT_EVENT,
+ botId: frame.agentId,
+ id: inserted.id,
+ kind: frame.event.kind,
+ payload: frame.event.payload,
+ sessionId: frame.sessionId ?? null,
+ launchId: frame.launchId ?? null,
+ createdAt: inserted.createdAt,
+ }).catch(() => { })
+ },
+ })
+ return true
+}
diff --git a/src/ws-do/src/ws-durable/presence-typing.test.ts b/src/ws-do/src/ws-durable/presence-typing.test.ts
new file mode 100644
index 000000000..a23a74fe3
--- /dev/null
+++ b/src/ws-do/src/ws-durable/presence-typing.test.ts
@@ -0,0 +1,772 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { readFileSync } from "node:fs"
+import { createMockWebSocket } from "../__mocks__/cf"
+import {
+ CFResponse,
+ cleanupHarness,
+ createDO,
+ flushAsyncWork,
+ mockCheckAliveFetch,
+ mockCreateDb,
+ mockFindCredentialByHash,
+ mockGetBotBinding,
+ mockGetBotBindingWithOwner,
+ mockGetChannelForMember,
+ mockGetChannelType,
+ mockGetCoMemberUserIds,
+ mockGetDM,
+ mockGetFriendUserIds,
+ mockGetLatestTokenForUser,
+ mockGetMachineByDaemon,
+ mockGetMachineByIdForUser,
+ mockGetMachineTokenByToken,
+ mockGetPrivateChannelAudienceUserIds,
+ mockGetProfile,
+ mockGetRuntimeIdsByDaemon,
+ mockGetUserInternal,
+ mockGetValidSession,
+ mockGetValidSessionWithIdentity,
+ mockHashCredential,
+ mockInsertBotActivityEventAndPrune,
+ mockInsertBotAuditModelChanged,
+ mockInsertBotAuditNap,
+ mockInsertBotAuditProviderChanged,
+ mockInsertBotAuditSessionReset,
+ mockIsBotOnline,
+ mockIsChannelPrivate,
+ mockListBotsForMachine,
+ mockListChannelMemberUserIds,
+ mockListMembers,
+ mockListThreadParticipantUserIds,
+ mockMarkMachineOffline,
+ mockMarkMachineOnlineIfOffline,
+ mockReconcileBotActivityFromRunningAgents,
+ mockResolveScopeMemberUserIds,
+ mockResolveChannelRecipientUserIds,
+ mockStubFetch,
+ mockToSummary,
+ mockTouchBotRefreshContext,
+ mockTouchMachineHeartbeat,
+ mockUpdateProfile,
+ mockUpsertMachineByMachineId,
+ mockWithD1Retry,
+ resetHarness
+} from "./test-harness"
+
+describe("WebSocketDurableObject", () => {
+ beforeEach(() => resetHarness())
+ afterEach(() => cleanupHarness())
+
+
+ describe("fetch — broadcast", () => {
+ it("sends message to all authenticated connections", async () => {
+ const { durable, ctx } = createDO()
+
+ // Set up two WebSockets: one authenticated, one not
+ const wsAuth = createMockWebSocket()
+ wsAuth.serializeAttachment({ type: "user", userId: "u1", authenticated: true })
+ const wsUnauth = createMockWebSocket()
+ wsUnauth.serializeAttachment({ type: "user", userId: "", authenticated: false })
+ ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsAuth, wsUnauth])
+
+ const req = new Request("http://internal/broadcast", {
+ method: "POST",
+ body: JSON.stringify({ type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" }),
+ })
+
+ const res = await durable.fetch(req)
+
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 1 })
+ expect(wsAuth.send).toHaveBeenCalledWith(
+ JSON.stringify({ type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" })
+ )
+ expect(wsUnauth.send).not.toHaveBeenCalled()
+ })
+
+ it("returns sent: 0 when no connections exist", async () => {
+ const { durable, ctx } = createDO()
+ ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([])
+
+ const req = new Request("http://internal/broadcast", {
+ method: "POST",
+ body: '{"type":"test"}',
+ })
+
+ const res = await durable.fetch(req)
+
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ sent: 0 })
+ })
+
+ it("skips connections that throw on send (already closed)", async () => {
+ const { durable, ctx } = createDO()
+
+ const wsOpen = createMockWebSocket(WebSocket.OPEN)
+ wsOpen.serializeAttachment({ type: "user", userId: "u1", authenticated: true })
+ const wsClosed = createMockWebSocket(WebSocket.CLOSED)
+ wsClosed.serializeAttachment({ type: "user", userId: "u1", authenticated: true })
+ wsClosed.send.mockImplementation(() => { throw new Error("Connection closed") })
+ ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsOpen, wsClosed])
+
+ const req = new Request("http://internal/broadcast", {
+ method: "POST",
+ body: '{"type":"test"}',
+ })
+
+ const res = await durable.fetch(req)
+
+ expect(wsOpen.send).toHaveBeenCalled()
+ expect(wsClosed.send).toHaveBeenCalled()
+ expect(await res.json()).toEqual({ sent: 1 })
+ })
+ })
+
+
+ describe("fetch — /check-alive characterization", () => {
+ it("reports alive only when an authenticated daemon socket is attached", async () => {
+ const { durable, ctx } = createDO()
+ const daemon = createMockWebSocket()
+ daemon.serializeAttachment({ type: "daemon", daemonId: "daemon-1", userId: "user-1", authenticated: true })
+ const user = createMockWebSocket()
+ user.serializeAttachment({ type: "user", userId: "user-1", authenticated: true })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([user, daemon])
+
+ const response = await durable.fetch(new Request("http://internal/check-alive"))
+
+ expect(await response.json()).toEqual({ alive: true })
+ })
+
+ it("reports not alive for unauthenticated daemon and authenticated non-daemon attachments", async () => {
+ const { durable, ctx } = createDO()
+ const daemon = createMockWebSocket()
+ daemon.serializeAttachment({ type: "daemon", daemonId: "daemon-1", userId: "user-1", authenticated: false })
+ const machine = createMockWebSocket()
+ machine.serializeAttachment({ type: "community-machine", machineId: "machine-1", userId: "user-1", authenticated: true })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([daemon, machine])
+
+ const response = await durable.fetch(new Request("http://internal/check-alive"))
+
+ expect(await response.json()).toEqual({ alive: false })
+ })
+ })
+
+
+ describe("fetch — /check-user-online (bot-aware, keyed by ?userId=)", () => {
+ // This DO instance is keyed by `user:<id>` (idFromName) but can't read
+ // its own name back off `ctx` on this worker's pinned compatibility_date
+ // — see plans/community-account-debt-fixes.md Fix 3 — so every caller
+ // passes `?userId=` explicitly and the handler branches on it.
+ it("answers via isBotOnline for a bot id, bypassing the live-socket check entirely", async () => {
+ const { durable, ctx } = createDO()
+ mockGetUserInternal.mockResolvedValue({ isBot: true } as any)
+ mockIsBotOnline.mockResolvedValue(true)
+ ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([])
+
+ const res = await durable.fetch(new Request("http://internal/check-user-online?userId=bot-1"))
+
+ expect(await res.json()).toEqual({ online: true })
+ expect(mockGetUserInternal).toHaveBeenCalledWith({}, "bot-1")
+ expect(mockIsBotOnline).toHaveBeenCalledWith({}, "bot-1")
+ })
+
+ it("answers false for a bot id with no bound machine or an offline one", async () => {
+ const { durable } = createDO()
+ mockGetUserInternal.mockResolvedValue({ isBot: true } as any)
+ mockIsBotOnline.mockResolvedValue(false)
+
+ const res = await durable.fetch(new Request("http://internal/check-user-online?userId=bot-1"))
+
+ expect(await res.json()).toEqual({ online: false })
+ })
+
+ it("falls back to the live-socket check for a human id (regression: query-param change must not break humans)", async () => {
+ const { durable, ctx } = createDO()
+ mockGetUserInternal.mockResolvedValue({ isBot: false } as any)
+ const wsAuth = createMockWebSocket()
+ wsAuth.serializeAttachment({ type: "user", userId: "human-1", authenticated: true })
+ ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsAuth])
+
+ const res = await durable.fetch(new Request("http://internal/check-user-online?userId=human-1"))
+
+ expect(await res.json()).toEqual({ online: true })
+ expect(mockIsBotOnline).not.toHaveBeenCalled()
+ })
+
+ it("falls back to the live-socket check when userId is missing entirely", async () => {
+ const { durable, ctx } = createDO()
+ const wsAuth = createMockWebSocket()
+ wsAuth.serializeAttachment({ type: "user", userId: "u1", authenticated: true })
+ ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsAuth])
+
+ const res = await durable.fetch(new Request("http://internal/check-user-online"))
+
+ expect(await res.json()).toEqual({ online: true })
+ expect(mockGetUserInternal).not.toHaveBeenCalled()
+ })
+
+ it("degrades to { online: false, stale: true } when D1 throws on the bot-online lookup", async () => {
+ // Fail-closed via `readOrStale`: getUserInternal (or isBotOnline)
+ // throwing on retry-exhaust must NOT surface as a 500 — the caller
+ // reads `{ online: false, stale: true }` and moves on.
+ const { durable } = createDO()
+ mockGetUserInternal.mockRejectedValue(new Error("D1 down"))
+
+ const res = await durable.fetch(new Request("http://internal/check-user-online?userId=bot-1"))
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ online: false, stale: true })
+ })
+ })
+
+
+ describe("presence audience — co-members ∪ friends (deduped)", () => {
+ // Presence fan-out must reach friends who share no server, not just
+ // co-members — that's the whole point of a friends list. Exercised
+ // directly against the private helper/methods (bypassing the
+ // fire-and-forget `.catch(() => {})` call sites in the auth flow) so
+ // these assertions aren't racing an un-awaited promise.
+ type PresenceInternals = {
+ getPresenceAudience(userId: string): Promise<string[]>
+ broadcastPresence(userId: string, online: boolean): Promise<void>
+ sendPresenceSnapshot(ws: WebSocket, userId: string): Promise<void>
+ }
+
+ it("getPresenceAudience merges co-members and friends without duplicates", async () => {
+ const { durable } = createDO()
+ mockGetCoMemberUserIds.mockResolvedValue(["member-a", "shared-b"])
+ mockGetFriendUserIds.mockResolvedValue(["shared-b", "friend-c"])
+
+ const audience = await (durable as unknown as PresenceInternals).getPresenceAudience("user-1")
+
+ expect(new Set(audience)).toEqual(new Set(["member-a", "shared-b", "friend-c"]))
+ expect(audience).toHaveLength(3)
+ expect(mockGetCoMemberUserIds).toHaveBeenCalledWith({}, "user-1")
+ expect(mockGetFriendUserIds).toHaveBeenCalledWith({}, "user-1")
+ })
+
+ it("getPresenceAudience returns [] when the user has no co-members and no friends", async () => {
+ const { durable } = createDO()
+ mockGetCoMemberUserIds.mockResolvedValue([])
+ mockGetFriendUserIds.mockResolvedValue([])
+
+ const audience = await (durable as unknown as PresenceInternals).getPresenceAudience("user-1")
+
+ expect(audience).toEqual([])
+ })
+
+ it("broadcastPresence fans out to a friend who shares no server", async () => {
+ const { durable, env } = createDO()
+ mockGetCoMemberUserIds.mockResolvedValue([])
+ mockGetFriendUserIds.mockResolvedValue(["friend-c"])
+ mockStubFetch.mockClear()
+
+ await (durable as unknown as PresenceInternals).broadcastPresence("user-1", true)
+
+ expect(env.WS_DO.idFromName).toHaveBeenCalledWith("user:friend-c")
+ expect(mockStubFetch).toHaveBeenCalledTimes(1)
+ const [req] = mockStubFetch.mock.calls[0] as [Request]
+ expect(req.url).toBe("http://internal/broadcast")
+ })
+
+ it("broadcastPresence no-ops (no fetches) when co-members and friends are both empty", async () => {
+ const { durable } = createDO()
+ mockGetCoMemberUserIds.mockResolvedValue([])
+ mockGetFriendUserIds.mockResolvedValue([])
+ mockStubFetch.mockClear()
+
+ await (durable as unknown as PresenceInternals).broadcastPresence("user-1", true)
+
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("sendPresenceSnapshot reports an online friend who shares no server", async () => {
+ const { durable } = createDO()
+ mockGetCoMemberUserIds.mockResolvedValue([])
+ mockGetFriendUserIds.mockResolvedValue(["friend-c"])
+ mockStubFetch.mockResolvedValue(
+ new (globalThis.Response as any)(JSON.stringify({ online: true })),
+ )
+ const ws = createMockWebSocket()
+
+ await (durable as unknown as PresenceInternals).sendPresenceSnapshot(ws as any, "user-1")
+
+ expect(ws.send).toHaveBeenCalledWith(
+ JSON.stringify({ type: "community:presence.update", userId: "friend-c", online: true }),
+ )
+ })
+
+ it("authentication snapshot sends only fulfilled non-stale online audience entries", async () => {
+ const { durable, env } = createDO()
+ mockGetValidSessionWithIdentity.mockResolvedValue({ userId: "user-1", name: "User", discriminator: "0001" })
+ mockGetCoMemberUserIds.mockResolvedValue(["online", "offline", "stale", "rejected"])
+ ;(env.WS_DO.idFromName as ReturnType<typeof vi.fn>).mockImplementation((name: string) => name)
+ ;(env.WS_DO.get as ReturnType<typeof vi.fn>).mockImplementation((id: string) => ({
+ fetch: vi.fn(async (request: Request) => {
+ if (request.method === "POST") {
+ return new (globalThis.Response as any)(JSON.stringify({ sent: 1 }))
+ }
+ if (id === "user:online") {
+ return new (globalThis.Response as any)(JSON.stringify({ online: true }))
+ }
+ if (id === "user:offline") {
+ return new (globalThis.Response as any)(JSON.stringify({ online: false }))
+ }
+ if (id === "user:stale") {
+ return new (globalThis.Response as any)(JSON.stringify({ online: false, stale: true }))
+ }
+ throw new Error("unreachable user DO")
+ }),
+ }))
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))
+ await flushAsyncWork()
+
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))
+ expect(ws.send).toHaveBeenCalledWith(
+ JSON.stringify({ type: "community:presence.update", userId: "online", online: true }),
+ )
+ expect(ws.send).toHaveBeenCalledTimes(2)
+ })
+
+ // Regression (post-Fix-3 hotfix): a fresh bot has no server membership,
+ // so co-members alone can be empty for it even while its bound machine
+ // is genuinely online. The fix lives one layer down, in
+ // `getFriendUserIds` itself (see `community-friendship.test.ts`) — the
+ // owner↔own-bot implicit friendship it already returns for `listFriends`
+ // /`areFriends` now also flows through here, so `getPresenceAudience`
+ // needs no bot-specific branch at all; it just trusts whatever
+ // `getFriendUserIds` (mocked as `mockGetFriendUserIds` above) says.
+ })
+
+
+ describe("notifyUserDO — bot fan-out on community:machine.status (Fix 3)", () => {
+ // `notifyUserDO` is private; every `community:machine.status` emission in
+ // this file funnels through it (the single choke point the plan calls
+ // for), so exercising it directly here covers all 5 call sites without
+ // duplicating their individual setup.
+ type NotifyInternals = { notifyUserDO(userId: string, payload: unknown): Promise<void> }
+
+ /** Collects `{ url, body }` for every `mockStubFetch` call so far. */
+ async function capturedRequests(): Promise<Array<{ url: string; body: string }>> {
+ return Promise.all(
+ mockStubFetch.mock.calls.map(async ([req]) => ({
+ url: (req as Request).url,
+ body: await (req as Request).clone().text(),
+ }))
+ )
+ }
+
+ it("fans out community:presence.update(online: true) to every bot bound to the machine, beyond the owner notify", async () => {
+ const { durable, env } = createDO()
+ mockListBotsForMachine.mockResolvedValue([
+ { id: "bot-1", name: "Bot One", discriminator: "0001", description: "" },
+ { id: "bot-2", name: "Bot Two", discriminator: "0002", description: "" },
+ ])
+ mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
+ mockGetFriendUserIds.mockResolvedValue([])
+ mockStubFetch.mockClear()
+
+ await (durable as unknown as NotifyInternals).notifyUserDO("owner-1", {
+ type: "community:machine.status",
+ machineId: "m1",
+ status: "online",
+ lastSeenAt: "2026-01-01T00:00:00.000Z",
+ })
+
+ expect(mockListBotsForMachine).toHaveBeenCalledWith({}, "m1")
+ expect(env.WS_DO.idFromName).toHaveBeenCalledWith("user:owner-1")
+ expect(env.WS_DO.idFromName).toHaveBeenCalledWith("user:viewer-1")
+
+ const requests = await capturedRequests()
+ // 1 owner notify (raw payload) + 1 broadcastPresence fetch per bot to the shared viewer.
+ expect(requests).toHaveLength(3)
+ expect(requests.filter((r) => r.body.includes('"userId":"bot-1"') && r.body.includes('"online":true'))).toHaveLength(1)
+ expect(requests.filter((r) => r.body.includes('"userId":"bot-2"') && r.body.includes('"online":true'))).toHaveLength(1)
+ })
+
+ it("broadcasts online: false for every bound bot on a machine-offline transition", async () => {
+ const { durable } = createDO()
+ mockListBotsForMachine.mockResolvedValue([
+ { id: "bot-1", name: "Bot One", discriminator: "0001", description: "" },
+ ])
+ mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
+ mockGetFriendUserIds.mockResolvedValue([])
+ mockStubFetch.mockClear()
+
+ await (durable as unknown as NotifyInternals).notifyUserDO("owner-1", {
+ type: "community:machine.status",
+ machineId: "m1",
+ status: "offline",
+ lastSeenAt: "2026-01-01T00:00:00.000Z",
+ })
+
+ const requests = await capturedRequests()
+ expect(requests.some((r) => r.body.includes('"userId":"bot-1"') && r.body.includes('"online":false'))).toBe(true)
+ })
+
+ it("a machine bound to zero bots triggers no extra broadcast beyond the owner notify", async () => {
+ const { durable } = createDO()
+ mockListBotsForMachine.mockResolvedValue([])
+ mockStubFetch.mockClear()
+
+ await (durable as unknown as NotifyInternals).notifyUserDO("owner-1", {
+ type: "community:machine.status",
+ machineId: "m1",
+ status: "online",
+ lastSeenAt: "2026-01-01T00:00:00.000Z",
+ })
+
+ expect(mockStubFetch).toHaveBeenCalledTimes(1) // owner notify only
+ })
+
+ it("does not call listBotsForMachine for a payload that isn't a community:machine.status transition", async () => {
+ const { durable } = createDO()
+ mockStubFetch.mockClear()
+
+ await (durable as unknown as NotifyInternals).notifyUserDO("owner-1", {
+ type: "community:machine.updated",
+ machine: { id: "m1" },
+ })
+
+ expect(mockListBotsForMachine).not.toHaveBeenCalled()
+ expect(mockStubFetch).toHaveBeenCalledTimes(1) // owner notify only
+ })
+
+ it("does not throw and skips the bot fan-out on a malformed/non-object payload", async () => {
+ const { durable } = createDO()
+ await expect(
+ (durable as unknown as NotifyInternals).notifyUserDO("owner-1", "not-an-object")
+ ).resolves.toBeUndefined()
+ expect(mockListBotsForMachine).not.toHaveBeenCalled()
+ })
+
+ it("resolves cleanly when the owner-notify stub fetch rejects — the whole method is under try/catch, callers never see the throw", async () => {
+ // Regression guard: the owner-notify `userStub.fetch(...)` used to
+ // sit OUTSIDE the method's try/catch. A stub-fetch throw would
+ // propagate through every caller's `.catch(() => {})` and skip the
+ // bot fan-out entirely, contradicting the comment that claims the
+ // failure would "at least be visible."
+ const { durable } = createDO()
+ mockStubFetch.mockClear()
+ // First call is the owner notify — reject it. Subsequent calls
+ // (bot fan-out per-audience-member) should still fire.
+ mockStubFetch.mockRejectedValueOnce(new Error("stub unreachable"))
+ mockListBotsForMachine.mockResolvedValue([
+ { id: "bot-1", name: "Bot One", discriminator: "0001", description: "" },
+ ])
+ mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])
+ mockGetFriendUserIds.mockResolvedValue([])
+
+ await expect(
+ (durable as unknown as NotifyInternals).notifyUserDO("owner-1", {
+ type: "community:machine.status",
+ machineId: "m1",
+ status: "online",
+ lastSeenAt: "2026-01-01T00:00:00.000Z",
+ })
+ ).resolves.toBeUndefined()
+
+ // Owner notify was attempted (and failed) — bot fan-out still ran.
+ expect(mockListBotsForMachine).toHaveBeenCalledWith({}, "m1")
+ // Owner notify + at least one broadcastPresence fetch to viewer-1.
+ expect(mockStubFetch.mock.calls.length).toBeGreaterThanOrEqual(2)
+ })
+ })
+
+
+ describe("webSocketMessage — community:typing.start authz (fanOutTyping)", () => {
+ // fanOutTyping runs fire-and-forget (`.catch()`, not awaited) inside
+ // webSocketMessage, so `await durable.webSocketMessage(...)` alone
+ // doesn't guarantee its internal DB-then-broadcast chain has settled.
+ // Flush a macrotask so all pending microtasks (getDM/getChannelForMember
+ // → listMembers → Promise.all(fetch)) drain before asserting.
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0))
+
+ it("does nothing when a typing frame has no channelId", async () => {
+ const { durable } = createDO()
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start" }),
+ )
+ await flush()
+
+ expect(mockGetChannelForMember).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("deduplicates the same user and scope inside eight seconds and accepts the boundary", async () => {
+ const { durable } = createDO()
+ mockGetChannelForMember.mockResolvedValue({ id: "channel-1", serverId: "server-1" })
+ mockResolveScopeMemberUserIds.mockResolvedValue(["sender-1", "recipient-1"])
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })
+ const now = vi.spyOn(Date, "now")
+ try {
+ now.mockReturnValue(10_000)
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "channel-1" }),
+ )
+ await flushAsyncWork()
+ now.mockReturnValue(17_999)
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "channel-1" }),
+ )
+ await flushAsyncWork()
+ now.mockReturnValue(18_000)
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "channel-1" }),
+ )
+ await flushAsyncWork()
+
+ expect(mockStubFetch).toHaveBeenCalledTimes(2)
+ } finally {
+ now.mockRestore()
+ }
+ })
+
+ it("prunes only all-stale typing scopes after the map grows beyond two hundred", async () => {
+ const { durable } = createDO()
+ mockGetChannelForMember.mockResolvedValue(null)
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })
+ let timestamp = 100_000
+ const now = vi.spyOn(Date, "now").mockImplementation(() => timestamp)
+ try {
+ for (let index = 0; index < 200; index++) {
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: `stale-${index}` }),
+ )
+ }
+ timestamp = 140_001
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "current" }),
+ )
+
+ const typingDedup = (durable as unknown as {
+ typingDedup: Map<string, Map<string, number>>
+ }).typingDedup
+ expect([...typingDedup.keys()]).toEqual(["current"])
+ expect(typingDedup.get("current")?.get("sender-1")).toBe(140_001)
+ } finally {
+ now.mockRestore()
+ }
+ })
+
+ it("does not fan out or broadcast when sender is not a member of the target channel", async () => {
+ const { durable, env } = createDO()
+ mockGetChannelForMember.mockResolvedValueOnce(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "chan-private" }),
+ )
+ await flush()
+
+ expect(mockGetChannelForMember).toHaveBeenCalledWith(expect.anything(), "chan-private", "attacker")
+ expect(mockResolveChannelRecipientUserIds).not.toHaveBeenCalled()
+ expect(mockListMembers).not.toHaveBeenCalled()
+ expect((env.WS_DO as any).get).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("fans out to other server members when sender IS a channel member", async () => {
+ const { durable, env } = createDO()
+ mockGetChannelForMember.mockResolvedValueOnce({ id: "chan-1", serverId: "server-1" })
+ // Recipient resolution now goes through the shared member resolver — a
+ // public channel resolves to every server member (sender included).
+ mockResolveScopeMemberUserIds.mockResolvedValueOnce(["member-1", "member-2", "sender-1"])
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "chan-1" }),
+ )
+ await flush()
+
+ expect(mockGetChannelForMember).toHaveBeenCalledWith(expect.anything(), "chan-1", "sender-1")
+ expect(mockResolveScopeMemberUserIds).toHaveBeenCalledWith(expect.anything(), {
+ scope: "channel",
+ scopeId: "chan-1",
+ })
+ expect(mockResolveChannelRecipientUserIds).toHaveBeenCalledWith(expect.anything(), "chan-1")
+ // Sender is excluded from recipients — only the other 2 members get a broadcast POST.
+ expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:member-1")
+ expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:member-2")
+ expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:sender-1")
+ expect(mockStubFetch).toHaveBeenCalledTimes(2)
+ })
+
+ it("private channel: fans out to the channel audience, not all server members", async () => {
+ const { durable, env } = createDO()
+ mockGetChannelForMember.mockResolvedValueOnce({ id: "chan-p", serverId: "server-1" })
+ // The resolver applies the public/private split internally — a private
+ // channel resolves to its audience (creator + added member + admin).
+ mockResolveScopeMemberUserIds.mockResolvedValueOnce(["sender-1", "member-1"])
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "chan-p" }),
+ )
+ await flush()
+
+ expect(mockResolveScopeMemberUserIds).toHaveBeenCalledWith(expect.anything(), {
+ scope: "channel",
+ scopeId: "chan-p",
+ })
+ expect(mockResolveChannelRecipientUserIds).toHaveBeenCalledWith(expect.anything(), "chan-p")
+ expect(mockListMembers).not.toHaveBeenCalled()
+ // Only the non-sender audience member gets a broadcast POST.
+ expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:member-1")
+ expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:sender-1")
+ expect(mockStubFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it("thread: typing fans out to PARTICIPANTS, not the channel audience", async () => {
+ const { durable, env } = createDO()
+ mockGetChannelForMember.mockResolvedValueOnce({ id: "t-1", serverId: "server-1" })
+ mockGetChannelType.mockResolvedValueOnce("thread")
+ mockListThreadParticipantUserIds.mockResolvedValueOnce(["sender-1", "part-1"])
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "t-1" }),
+ )
+ await flush()
+
+ expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith(expect.anything(), "t-1")
+ // Thread typing must NOT fall back to the channel-audience resolver.
+ expect(mockResolveScopeMemberUserIds).not.toHaveBeenCalled()
+ expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:part-1")
+ expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:sender-1")
+ expect(mockStubFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it("does not fan out when sender is not a participant of the target DM", async () => {
+ const { durable, env } = createDO()
+ // A DM is a type=dm channel now; a non-member sender can't see it, so
+ // getChannelForMember returns null and fanOutTyping bails.
+ mockGetChannelForMember.mockResolvedValueOnce(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "dm-1" }),
+ )
+ await flush()
+
+ expect(mockGetChannelForMember).toHaveBeenCalledWith(expect.anything(), "dm-1", "attacker")
+ expect((env.WS_DO as any).get).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("fans out to the other participant when sender IS a DM participant", async () => {
+ const { durable, env } = createDO()
+ mockGetChannelForMember.mockResolvedValueOnce({ id: "dm-1", serverId: null })
+ mockGetChannelType.mockResolvedValueOnce("dm")
+ mockListChannelMemberUserIds.mockResolvedValueOnce(["alice", "bob"])
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "dm-1" }),
+ )
+ await flush()
+
+ expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:bob")
+ expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:alice")
+ expect(mockStubFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it("keeps membership retry separate while recipient retry re-runs the complete shared resolver", async () => {
+ const { durable } = createDO()
+ mockGetChannelForMember.mockResolvedValue({ id: "chan-1", serverId: "server-1" })
+ mockResolveChannelRecipientUserIds
+ .mockRejectedValueOnce(new Error("SQLITE_BUSY"))
+ .mockResolvedValueOnce(["sender-1", "peer-1"])
+ mockWithD1Retry.mockImplementation(async (fn, opts) => {
+ if ((opts as { route?: string }).route !== "ws-do:agent-typing-recipients") return fn()
+ try { return await fn() } catch { return fn() }
+ })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "chan-1" }),
+ )
+ await flushAsyncWork()
+
+ expect(mockGetChannelForMember).toHaveBeenCalledTimes(1)
+ expect(mockResolveChannelRecipientUserIds).toHaveBeenCalledTimes(2)
+ expect(mockWithD1Retry.mock.calls.map((call) => (call[1] as { route?: string }).route)).toEqual([
+ "ws-do:agent-typing-membership",
+ "ws-do:agent-typing-recipients",
+ ])
+ const request = mockStubFetch.mock.calls[0]![0] as Request
+ expect(JSON.parse(await request.text())).toEqual({
+ type: "community:typing.start",
+ channelId: "chan-1",
+ userId: "sender-1",
+ })
+ })
+
+ it("keeps typing delivery concurrency bounded by the class-owned batch size of forty", async () => {
+ const { durable, env } = createDO()
+ mockGetChannelForMember.mockResolvedValue({ id: "chan-1", serverId: "server-1" })
+ mockResolveChannelRecipientUserIds.mockResolvedValue(
+ Array.from({ length: 81 }, (_, index) => `recipient-${index}`),
+ )
+ let active = 0
+ let maximum = 0
+ const fetch = vi.fn(async () => {
+ active += 1
+ maximum = Math.max(maximum, active)
+ await Promise.resolve()
+ active -= 1
+ return new Response(JSON.stringify({ sent: 1 }))
+ })
+ ;(env.WS_DO.get as ReturnType<typeof vi.fn>).mockReturnValue({ fetch })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "community:typing.start", channelId: "chan-1" }),
+ )
+ await flushAsyncWork()
+
+ expect(fetch).toHaveBeenCalledTimes(81)
+ expect(maximum).toBe(40)
+ })
+
+ it("contains no local reach classifier after delegating to shared", () => {
+ const source = readFileSync(new URL("./presence-typing.ts", import.meta.url), "utf8")
+ expect(source).not.toMatch(/\bchannelReach\b|\bisStoredChannelType\b|switch\s*\(\s*reach\s*\)/)
+ })
+ })
+})
diff --git a/src/ws-do/src/ws-durable/presence-typing.ts b/src/ws-do/src/ws-durable/presence-typing.ts
new file mode 100644
index 000000000..4a6bb1d85
--- /dev/null
+++ b/src/ws-do/src/ws-durable/presence-typing.ts
@@ -0,0 +1,264 @@
+import {
+ createDb,
+ queries,
+ withD1Retry,
+ WS_EVENTS,
+} from "@alook/shared"
+import type { UserConnectionState, WsDurableContext } from "./internal"
+
+export function handleClientTypingStart(
+ context: WsDurableContext,
+ state: UserConnectionState,
+ parsed: unknown,
+): boolean {
+ const msg = parsed as { type: string }
+ if (msg.type !== WS_EVENTS.TYPING_START) return false
+ const typingMsg = parsed as {
+ type: string
+ channelId?: string
+ }
+ const scopeKey = typingMsg.channelId
+ if (!scopeKey) return true
+
+ const now = Date.now()
+ let scopeMap = context.typingDedup.get(scopeKey)
+ if (!scopeMap) {
+ scopeMap = new Map()
+ context.typingDedup.set(scopeKey, scopeMap)
+ }
+ const lastTs = scopeMap.get(state.userId) || 0
+ if (now - lastTs < context.typingDedupMs) return true
+ scopeMap.set(state.userId, now)
+
+ if (context.typingDedup.size > 200) {
+ for (const [key, map] of context.typingDedup) {
+ let allStale = true
+ for (const ts of map.values()) {
+ if (now - ts < context.typingDedupMs * 4) {
+ allStale = false
+ break
+ }
+ }
+ if (allStale) context.typingDedup.delete(key)
+ }
+ }
+
+ const event = JSON.stringify({
+ type: WS_EVENTS.TYPING_START,
+ channelId: typingMsg.channelId,
+ userId: state.userId,
+ name: state.name,
+ discriminator: state.discriminator,
+ })
+
+ fanOutTyping(context, state.userId, typingMsg.channelId, event).catch((err) => {
+ context.log.warn("community:typing.start fan-out failed", { err: String(err) })
+ })
+ return true
+}
+
+export async function notifyUserDO(
+ context: WsDurableContext,
+ userId: string,
+ payload: unknown,
+): Promise<void> {
+ try {
+ const userDoId = context.env.WS_DO.idFromName("user:" + userId)
+ const userStub = context.env.WS_DO.get(userDoId)
+ try {
+ await userStub.fetch(new Request("http://internal/broadcast", {
+ method: "POST",
+ body: JSON.stringify(payload),
+ }))
+ } catch (err) {
+ context.log.error("notifyUserDO: owner notify failed", { err: String(err), userId })
+ }
+
+ try {
+ const status = machineStatusPayload(payload)
+ if (!status) return
+ const db = createDb(context.env.DB)
+ const bots = await queries.communityBot.listBotsForMachine(db, status.machineId)
+ if (bots.length === 0) return
+ await Promise.allSettled(
+ bots.map((bot) => broadcastPresence(context, bot.id, status.online))
+ )
+ } catch (err) {
+ context.log.error("notifyUserDO: bot presence fan-out failed", { err: String(err), userId })
+ }
+ } catch (err) {
+ context.log.error("notifyUserDO: unexpected failure", { err: String(err), userId })
+ }
+}
+
+function machineStatusPayload(payload: unknown): { machineId: string; online: boolean } | null {
+ if (typeof payload !== "object" || payload === null) return null
+ const p = payload as { type?: unknown; machineId?: unknown; status?: unknown }
+ if (p.type !== WS_EVENTS.MACHINE_STATUS) return null
+ if (typeof p.machineId !== "string") return null
+ if (p.status !== "online" && p.status !== "offline") return null
+ return { machineId: p.machineId, online: p.status === "online" }
+}
+
+export async function fanOutTyping(
+ context: WsDurableContext,
+ senderUserId: string,
+ channelId?: string,
+ event?: string,
+): Promise<void> {
+ if (!event || !channelId) return
+ const db = createDb(context.env.DB)
+ let recipientUserIds: string[] = []
+
+ const membership = await withD1Retry(
+ () => queries.communityChannel.getChannelForMember(db, channelId, senderUserId),
+ { route: "ws-do:agent-typing-membership" },
+ )
+ if (!membership) {
+ context.log.warn("fanOutTyping: sender not a channel member", { senderUserId, channelId })
+ return
+ }
+ recipientUserIds = await withD1Retry(
+ () => queries.communityMembersResolver.resolveChannelRecipientUserIds(db, channelId),
+ { route: "ws-do:agent-typing-recipients" },
+ )
+ recipientUserIds = recipientUserIds.filter((id) => id !== senderUserId)
+ if (recipientUserIds.length === 0) return
+
+ for (let i = 0; i < recipientUserIds.length; i += context.subrequestBatchSize) {
+ const batch = recipientUserIds.slice(i, i + context.subrequestBatchSize)
+ await Promise.all(
+ batch.map((userId) => {
+ const doId = context.env.WS_DO.idFromName("user:" + userId)
+ const stub = context.env.WS_DO.get(doId)
+ return stub.fetch(new Request("http://internal/broadcast", {
+ method: "POST",
+ body: event,
+ })).catch(() => { })
+ })
+ )
+ }
+}
+
+export async function fanOutTypingStop(
+ context: WsDurableContext,
+ senderUserId: string,
+ channelId: string,
+): Promise<void> {
+ const db = createDb(context.env.DB)
+ const membership = await withD1Retry(
+ () => queries.communityChannel.getChannelForMember(db, channelId, senderUserId),
+ { route: "ws-do:agent-typing-stop-membership" },
+ )
+ if (!membership) {
+ context.log.warn("fanOutTypingStop: sender not a channel member", { senderUserId, channelId })
+ return
+ }
+ let recipientUserIds = await withD1Retry(
+ () => queries.communityMembersResolver.resolveChannelRecipientUserIds(db, channelId),
+ { route: "ws-do:agent-typing-stop-recipients" },
+ )
+ recipientUserIds = recipientUserIds.filter((id) => id !== senderUserId)
+ if (recipientUserIds.length === 0) return
+ const body = JSON.stringify({
+ type: WS_EVENTS.TYPING_STOP,
+ channelId,
+ userId: senderUserId,
+ })
+ for (let i = 0; i < recipientUserIds.length; i += context.subrequestBatchSize) {
+ const batch = recipientUserIds.slice(i, i + context.subrequestBatchSize)
+ await Promise.all(
+ batch.map((userId) => {
+ const doId = context.env.WS_DO.idFromName("user:" + userId)
+ const stub = context.env.WS_DO.get(doId)
+ return stub.fetch(new Request("http://internal/broadcast", {
+ method: "POST",
+ body,
+ })).catch(() => { })
+ })
+ )
+ }
+}
+
+export async function broadcastPresence(
+ context: WsDurableContext,
+ userId: string,
+ online: boolean,
+): Promise<void> {
+ await broadcastToAudience(context, userId, { type: WS_EVENTS.PRESENCE_UPDATE, userId, online })
+}
+
+export async function broadcastToAudience(
+ context: WsDurableContext,
+ userId: string,
+ payload: unknown,
+): Promise<void> {
+ const audience = await getPresenceAudience(context, userId)
+ if (audience.length === 0) return
+ const body = JSON.stringify(payload)
+ for (let i = 0; i < audience.length; i += context.subrequestBatchSize) {
+ const batch = audience.slice(i, i + context.subrequestBatchSize)
+ await Promise.allSettled(
+ batch.map((memberId) => {
+ const doId = context.env.WS_DO.idFromName("user:" + memberId)
+ const stub = context.env.WS_DO.get(doId)
+ return stub.fetch(new Request("http://internal/broadcast", {
+ method: "POST",
+ body,
+ }))
+ })
+ )
+ }
+}
+
+async function getCoMembers(context: WsDurableContext, userId: string): Promise<string[]> {
+ const db = createDb(context.env.DB)
+ return queries.communityMember.getCoMemberUserIds(db, userId)
+}
+
+async function getFriendIds(context: WsDurableContext, userId: string): Promise<string[]> {
+ const db = createDb(context.env.DB)
+ return queries.communityFriendship.getFriendUserIds(db, userId)
+}
+
+export async function getPresenceAudience(
+ context: WsDurableContext,
+ userId: string,
+): Promise<string[]> {
+ const [coMembers, friends] = await Promise.all([
+ getCoMembers(context, userId),
+ getFriendIds(context, userId),
+ ])
+ return [...new Set([...coMembers, ...friends])]
+}
+
+export async function sendPresenceSnapshot(
+ context: WsDurableContext,
+ ws: WebSocket,
+ userId: string,
+): Promise<void> {
+ const audience = await getPresenceAudience(context, userId)
+ if (audience.length === 0) return
+ const onlineIds: string[] = []
+ for (let i = 0; i < audience.length; i += context.subrequestBatchSize) {
+ const batch = audience.slice(i, i + context.subrequestBatchSize)
+ const checks = await Promise.allSettled(
+ batch.map(async (memberId) => {
+ const doId = context.env.WS_DO.idFromName("user:" + memberId)
+ const stub = context.env.WS_DO.get(doId)
+ const resp = await stub.fetch(
+ new Request(`http://internal/check-user-online?userId=${encodeURIComponent(memberId)}`)
+ )
+ const data = await resp.json() as { online: boolean; stale?: boolean }
+ if (data.stale) return null
+ return data.online ? memberId : null
+ })
+ )
+ for (const r of checks) {
+ if (r.status === "fulfilled" && r.value) onlineIds.push(r.value)
+ }
+ }
+ for (const id of onlineIds) {
+ ws.send(JSON.stringify({ type: WS_EVENTS.PRESENCE_UPDATE, userId: id, online: true }))
+ }
+}
diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.ts
new file mode 100644
index 000000000..41c6cd68f
--- /dev/null
+++ b/src/ws-do/src/ws-durable/test-harness.ts
@@ -0,0 +1,485 @@
+import { vi } from "vitest"
+import { createMockCtx, createMockWebSocket } from "../__mocks__/cf"
+
+const loggerMocks = vi.hoisted(() => ({
+ mockLogDebug: vi.fn(),
+ mockLogInfo: vi.fn(),
+ mockLogWarn: vi.fn(),
+ mockLogError: vi.fn(),
+}))
+export const mockLogDebug = loggerMocks.mockLogDebug
+const mockLogInfo = loggerMocks.mockLogInfo
+export const mockLogWarn = loggerMocks.mockLogWarn
+const mockLogError = loggerMocks.mockLogError
+
+// --- Cloudflare Workers globals that don't exist in Node ---
+
+// Replace the global Response with one that allows status 101 and a webSocket property
+export class CFResponse {
+ status: number
+ webSocket: unknown
+ private _body: BodyInit | null
+ private _headers: Headers
+
+ constructor(body: BodyInit | null = null, init: ResponseInit & { webSocket?: unknown } = {}) {
+ this._body = body
+ this._headers = new Headers(init.headers)
+ this.status = init.status ?? 200
+ this.webSocket = (init as { webSocket?: unknown }).webSocket
+ }
+
+ async text(): Promise<string> {
+ if (this._body == null) return ""
+ if (typeof this._body === "string") return this._body
+ return ""
+ }
+
+ async json(): Promise<unknown> {
+ return JSON.parse(await this.text())
+ }
+
+ get headers() { return this._headers }
+}
+
+globalThis.Response = CFResponse as unknown as typeof Response
+
+// WebSocketPair — creates a paired (client, server) mock
+globalThis.WebSocketPair = class {
+ 0: ReturnType<typeof createMockWebSocket>
+ 1: ReturnType<typeof createMockWebSocket>
+ constructor() {
+ this[0] = createMockWebSocket()
+ this[1] = createMockWebSocket()
+ }
+} as unknown as typeof WebSocketPair
+
+// WebSocketRequestResponsePair — used for the ping/pong auto-response
+globalThis.WebSocketRequestResponsePair = class {
+ constructor(public request: string, public response: string) { }
+} as unknown as typeof WebSocketRequestResponsePair
+
+// --- Module mocks ---
+
+// Mock cloudflare:workers DurableObject base class
+vi.mock("cloudflare:workers", () => ({
+ DurableObject: class {
+ ctx: unknown
+ env: unknown
+ constructor(ctx: unknown, env: unknown) {
+ this.ctx = ctx
+ this.env = env
+ }
+ },
+}))
+
+// Mock @alook/shared
+export const mockGetValidSession = vi.fn<(db: unknown, token: string) => Promise<string | null>>()
+export const mockGetValidSessionWithIdentity = vi.fn<(db: unknown, token: string) => Promise<{ userId: string; name: string; discriminator: string } | null>>()
+export const mockGetMachineTokenByToken = vi.fn()
+export const mockGetLatestTokenForUser = vi.fn()
+export const mockGetRuntimeIdsByDaemon = vi.fn()
+export const mockGetMachineByDaemon = vi.fn().mockResolvedValue({ daemonId: "my-daemon", workspaceId: "sp_ws1" })
+export const mockCreateDb = vi.fn().mockReturnValue({})
+export const mockHashCredential = vi.fn(async (bearer: string) => `hash:${bearer}`)
+export const mockFindCredentialByHash = vi.fn()
+export const mockGetMachineByIdForUser = vi.fn()
+export const mockUpsertMachineByMachineId = vi.fn()
+export const mockTouchMachineHeartbeat = vi.fn()
+export const mockMarkMachineOffline = vi.fn()
+export const mockMarkMachineOnlineIfOffline = vi.fn()
+export const mockGetCoMemberUserIds = vi.fn<(db: unknown, userId: string) => Promise<string[]>>().mockResolvedValue([])
+export const mockGetFriendUserIds = vi.fn<(db: unknown, userId: string) => Promise<string[]>>().mockResolvedValue([])
+export const mockGetChannelForMember = vi.fn()
+export const mockListChannelMemberUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])
+export const mockIsChannelPrivate = vi.fn<(db: unknown, channelId: string) => Promise<boolean>>().mockResolvedValue(false)
+export const mockGetPrivateChannelAudienceUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])
+export const mockResolveScopeMemberUserIds = vi.fn<(db: unknown, opts: { scope: string; scopeId: string }) => Promise<string[]>>().mockResolvedValue([])
+// Default: non-thread channel → typing uses the shared resolver path.
+export const mockGetChannelType = vi.fn<(db: unknown, channelId: string) => Promise<string | null>>().mockResolvedValue("text")
+export const mockListThreadParticipantUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])
+async function resolveChannelRecipientUserIdsMock(db: unknown, channelId: string): Promise<string[]> {
+ const type = await mockGetChannelType(db, channelId)
+ if (type === "thread") return mockListThreadParticipantUserIds(db, channelId)
+ if (type === "dm") return mockListChannelMemberUserIds(db, channelId)
+ return mockResolveScopeMemberUserIds(db, { scope: "channel", scopeId: channelId })
+}
+export const mockResolveChannelRecipientUserIds = vi.fn(resolveChannelRecipientUserIdsMock)
+export const mockWithD1Retry = vi.fn(async <T>(fn: () => Promise<T>, _opts?: unknown): Promise<T> => fn())
+export const mockGetDM = vi.fn()
+export const mockListMembers = vi.fn()
+export const mockListBotsForMachine = vi.fn<(db: unknown, machineId: string) => Promise<Array<{ id: string; name: string; discriminator: string; description: string }>>>().mockResolvedValue([])
+export const mockIsBotOnline = vi.fn<(db: unknown, botUserId: string) => Promise<boolean>>().mockResolvedValue(false)
+export const mockGetBotBinding = vi.fn<(db: unknown, botId: string) => Promise<{ machineId: string; runtime: string } | null>>().mockResolvedValue(null)
+export const mockGetBotBindingWithOwner = vi.fn<(db: unknown, botId: string) => Promise<{ machineId: string; runtime: string; ownerUserId: string; name: string; discriminator: string } | null>>().mockResolvedValue(null)
+export const mockInsertBotActivityEventAndPrune = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
+export const mockInsertBotAuditSessionReset = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
+export const mockInsertBotAuditNap = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
+export const mockInsertBotAuditModelChanged = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
+export const mockInsertBotAuditProviderChanged = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
+export const mockTouchBotRefreshContext = vi.fn<(db: unknown, botId: string, now: string) => Promise<void>>().mockResolvedValue(undefined)
+export const mockUpdateProfile = vi
+ .fn<(db: unknown, userId: string, data: { statusEmoji?: string | null; statusText?: string | null }) => Promise<unknown>>()
+ .mockResolvedValue({})
+export const mockGetProfile = vi
+ .fn<(db: unknown, userId: string) => Promise<{ statusEmoji: string | null; statusText: string | null } | null>>()
+ .mockResolvedValue(null)
+export const mockReconcileBotActivityFromRunningAgents = vi
+ .fn<(db: unknown, machineId: string, runningAgentIds: string[]) => Promise<Array<{ botUserId: string; statusEmoji: string; statusText: string }>>>()
+ .mockResolvedValue([])
+export const mockGetUserInternal = vi.fn<(db: unknown, id: string) => Promise<{ isBot: boolean; ownerUserId: string | null } | null>>().mockResolvedValue(null)
+// mockToSummary now returns row.status verbatim — status is the source of
+// truth on the column, not a derivation from lastSeenAt. See
+// plans/community-machine-presence-fix.md.
+export const mockToSummary = vi.fn((row: any) => ({
+ id: row.id,
+ hostname: row.hostname ?? "",
+ displayName: row.displayName ?? row.hostname ?? "",
+ platform: row.platform ?? "",
+ arch: row.arch ?? "",
+ osRelease: row.osRelease ?? "",
+ daemonVersion: row.daemonVersion ?? "",
+ lastSeenAt: row.lastSeenAt ?? null,
+ status: (row.status as "online" | "offline") ?? "offline",
+ availableRuntimes: row.availableRuntimes ?? [],
+ createdAt: row.createdAt ?? "",
+ updatedAt: row.updatedAt ?? "",
+}))
+
+vi.mock("@alook/shared", () => {
+ const noopLogger = {
+ debug: mockLogDebug,
+ info: mockLogInfo,
+ warn: mockLogWarn,
+ error: mockLogError,
+ child: () => noopLogger,
+ }
+ // Bare-minimum safeParse stubs — the DO only calls `.safeParse(msg)` and
+ // reads `.success` / `.data`. Enough to route the test frames correctly
+ // without pulling in zod (which isn't a direct dep of @alook/ws-do).
+ const SessionErrorFrameSchema = {
+ safeParse(v: unknown) {
+ const m = v as { type?: unknown; code?: unknown; agentId?: unknown; launchId?: unknown; payload?: unknown }
+ if (m?.type !== "session.error" || m?.code !== "runtime_not_available") {
+ return { success: false } as const
+ }
+ return {
+ success: true as const,
+ data: {
+ type: "session.error" as const,
+ code: "runtime_not_available" as const,
+ agentId: typeof m.agentId === "string" ? (m.agentId as string) : undefined,
+ // launchId rides the frame now (Melisa's source half) — the DO uses
+ // it to evict pending reset/nap attribution on cold-start branch A.
+ launchId: typeof m.launchId === "string" ? (m.launchId as string) : undefined,
+ payload: (m.payload as Record<string, unknown> | undefined) ?? undefined,
+ },
+ }
+ },
+ }
+ // Mirror the shared HostReadyMessageSchema: the daemon's ready frame must be
+ // FLAT (fields at top level), not wrapped in a `ready` key. A wrapped frame
+ // is rejected — regression guard against the wire-shape mismatch we hit
+ // when the daemon sent `{type:"ready", ready:{...}}` while the DO expected
+ // flat top-level fields.
+ const HostReadyMessageSchema = {
+ safeParse(v: unknown) {
+ const m = v as { type?: unknown; runtimeReport?: unknown; runningAgents?: unknown }
+ if (m?.type !== "ready") return { success: false } as const
+ if (!Array.isArray(m?.runtimeReport)) return { success: false } as const
+ const data: Record<string, unknown> = {
+ type: "ready",
+ runtimeReport: m.runtimeReport,
+ runningAgents: Array.isArray(m.runningAgents) ? m.runningAgents : [],
+ }
+ for (const k of ["hostname", "platform", "arch", "osRelease", "daemonVersion"]) {
+ const val = (m as Record<string, unknown>)[k]
+ if (typeof val === "string") data[k] = val
+ }
+ return { success: true as const, data }
+ },
+ }
+ const AgentActivityMessageSchema = {
+ safeParse(v: unknown) {
+ const m = v as { type?: unknown; agentId?: unknown; state?: unknown }
+ if (m?.type !== "agent_activity") return { success: false } as const
+ if (typeof m.agentId !== "string") return { success: false } as const
+ if (!["idle", "starting", "running", "stopping"].includes(m.state as string)) return { success: false } as const
+ return { success: true as const, data: { type: "agent_activity" as const, agentId: m.agentId, state: m.state } }
+ },
+ }
+ const AgentTypingMessageSchema = {
+ safeParse(v: unknown) {
+ const m = v as { type?: unknown; agentId?: unknown; channelId?: unknown }
+ if (m?.type !== "agent_typing") return { success: false } as const
+ if (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const
+ if (typeof m.channelId !== "string" || m.channelId.length === 0) return { success: false } as const
+ return {
+ success: true as const,
+ data: { type: "agent_typing" as const, agentId: m.agentId, channelId: m.channelId },
+ }
+ },
+ }
+ const AgentTypingStopMessageSchema = {
+ safeParse(v: unknown) {
+ const m = v as { type?: unknown; agentId?: unknown; channelId?: unknown }
+ if (m?.type !== "agent_typing_stop") return { success: false } as const
+ if (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const
+ if (typeof m.channelId !== "string" || m.channelId.length === 0) return { success: false } as const
+ return {
+ success: true as const,
+ data: { type: "agent_typing_stop" as const, agentId: m.agentId, channelId: m.channelId },
+ }
+ },
+ }
+ const AgentSessionMessageSchema = {
+ safeParse(v: unknown) {
+ const m = v as { type?: unknown; agentId?: unknown; sessionId?: unknown; launchId?: unknown }
+ if (m?.type !== "agent_session") return { success: false } as const
+ if (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const
+ if (typeof m.sessionId !== "string" || m.sessionId.length === 0) return { success: false } as const
+ if (typeof m.launchId !== "string" || m.launchId.length === 0) return { success: false } as const
+ return {
+ success: true as const,
+ data: {
+ type: "agent_session" as const,
+ agentId: m.agentId,
+ sessionId: m.sessionId,
+ launchId: m.launchId,
+ },
+ }
+ },
+ }
+ const HostBotAuditEventFrameSchema = {
+ safeParse(v: unknown) {
+ const m = v as { type?: unknown; agentId?: unknown; sessionId?: unknown; launchId?: unknown; event?: unknown }
+ if (m?.type !== "bot_audit_event") return { success: false } as const
+ if (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const
+ const ev = m.event as { kind?: unknown; payload?: unknown }
+ if (!ev || typeof ev !== "object") return { success: false } as const
+ const kind = ev.kind
+ const payload = ev.payload as Record<string, unknown> | undefined
+ if (!payload || typeof payload !== "object") return { success: false } as const
+ let ok = false
+ if (kind === "cli_invocation") ok = typeof payload.subcommand === "string"
+ else if (kind === "tool_call") ok = typeof payload.name === "string"
+ else if (kind === "thinking")
+ ok = typeof payload.text === "string" && typeof payload.truncated === "boolean" && typeof payload.chars === "number"
+ if (!ok) return { success: false } as const
+ return {
+ success: true as const,
+ data: {
+ type: "bot_audit_event" as const,
+ agentId: m.agentId,
+ sessionId: typeof m.sessionId === "string" ? m.sessionId : m.sessionId === null ? null : undefined,
+ launchId: typeof m.launchId === "string" ? m.launchId : m.launchId === null ? null : undefined,
+ event: { kind, payload },
+ },
+ }
+ },
+ }
+ return {
+ // Real WS event-type strings the DO reads at runtime (#5 T2 — ws-do
+ // broadcasts now use WS_EVENTS.* instead of raw literals). Values match
+ // @alook/shared so the event assertions still hold.
+ WS_EVENTS: {
+ TYPING_START: "community:typing.start",
+ TYPING_STOP: "community:typing.stop",
+ MACHINE_STATUS: "community:machine.status",
+ MACHINE_UPDATED: "community:machine.updated",
+ STATUS_UPDATE: "community:status.update",
+ BOT_AUDIT_EVENT: "community:bot.audit_event",
+ PRESENCE_UPDATE: "community:presence.update",
+ },
+ createDb: (d1: unknown) => mockCreateDb(d1),
+ createLogger: () => noopLogger,
+ withD1Retry: <T>(fn: () => Promise<T>, opts?: unknown): Promise<T> =>
+ mockWithD1Retry(fn, opts) as Promise<T>,
+ // Minimal `readOrStale` shim — bypasses the classifier so tests can
+ // inject arbitrary Error shapes at the query-fn boundary and observe
+ // fail-closed semantics. Real production behavior (retry then fallback)
+ // is covered by the shared `resilience.test.ts` suite.
+ readOrStale: async <T>(
+ fn: () => Promise<T>,
+ fallback: T,
+ _opts?: unknown,
+ ): Promise<{ value: T; stale: boolean }> => {
+ try { return { value: await fn(), stale: false } }
+ catch { return { value: fallback, stale: true } }
+ },
+ COMMUNITY_MACHINE_HEARTBEAT_MS: 60_000,
+ COMMUNITY_MACHINE_OFFLINE_THRESHOLD_MS: 120_000,
+ SessionErrorFrameSchema,
+ HostReadyMessageSchema,
+ AgentActivityMessageSchema,
+ AgentTypingMessageSchema,
+ AgentTypingStopMessageSchema,
+ AgentSessionMessageSchema,
+ HostBotAuditEventFrameSchema,
+ // Deterministic preset picker so the assertion can pin exact
+ // `statusEmoji`/`statusText` values regardless of the injected `seed`.
+ pickBotActivityPreset: (state: string) => {
+ if (state === "running") return { emoji: "⚡", text: "Working on it" }
+ if (state === "starting") return { emoji: "🌀", text: "Waking up" }
+ if (state === "stopping") return { emoji: "🌙", text: "Wrapping up" }
+ return { emoji: "💤", text: "Idle" }
+ },
+ RUNNING_PRESETS: [
+ { emoji: "⚡", text: "Working on it" },
+ { emoji: "🛠️", text: "Cooking" },
+ { emoji: "🧠", text: "Thinking hard" },
+ { emoji: "🔧", text: "Tinkering" },
+ { emoji: "🚀", text: "On it" },
+ { emoji: "🔥", text: "In the zone" },
+ ],
+ // Real impl of the write-path/reconciler guard — mirrors the shared module
+ // over the presets emitted above (idle/starting/stopping + running pool).
+ isBotActivityStatus: (emoji: string | null, text: string | null) => {
+ if (emoji === null && text === null) return false
+ const pairs = [
+ { emoji: "💤", text: "Idle" },
+ { emoji: "🌀", text: "Waking up" },
+ { emoji: "🌙", text: "Wrapping up" },
+ { emoji: "⚡", text: "Working on it" },
+ { emoji: "🛠️", text: "Cooking" },
+ { emoji: "🧠", text: "Thinking hard" },
+ { emoji: "🔧", text: "Tinkering" },
+ { emoji: "🚀", text: "On it" },
+ { emoji: "🔥", text: "In the zone" },
+ ]
+ return pairs.some((p) => p.emoji === emoji && p.text === text)
+ },
+ queries: {
+ session: {
+ getValidSession: (db: unknown, token: string) => mockGetValidSession(db, token),
+ getValidSessionWithIdentity: (db: unknown, token: string) => mockGetValidSessionWithIdentity(db, token),
+ },
+ machineToken: {
+ getMachineTokenByToken: (...a: any[]) => mockGetMachineTokenByToken(...a),
+ getLatestTokenForUser: (...a: any[]) => mockGetLatestTokenForUser(...a),
+ },
+ runtime: { getRuntimeIdsByDaemon: (...a: any[]) => mockGetRuntimeIdsByDaemon(...a) },
+ machine: { getMachineByDaemon: (...a: any[]) => mockGetMachineByDaemon(...a) },
+ communityMachine: {
+ hashCredential: (bearer: string) => mockHashCredential(bearer),
+ findCredentialByHash: (...a: any[]) => mockFindCredentialByHash(...a),
+ getMachineByIdForUser: (...a: any[]) => mockGetMachineByIdForUser(...a),
+ upsertMachineByMachineId: (...a: any[]) => mockUpsertMachineByMachineId(...a),
+ touchMachineHeartbeat: (...a: any[]) => mockTouchMachineHeartbeat(...a),
+ markMachineOffline: (...a: any[]) => mockMarkMachineOffline(...a),
+ markMachineOnlineIfOffline: (...a: any[]) => mockMarkMachineOnlineIfOffline(...a),
+ toSummary: (row: any) => mockToSummary(row),
+ isBotOnline: (...a: [unknown, string]) => mockIsBotOnline(...a),
+ reconcileBotActivityFromRunningAgents: (...a: any[]) =>
+ mockReconcileBotActivityFromRunningAgents(...(a as [unknown, string, string[]])),
+ },
+ communityUserProfile: {
+ updateProfile: (...a: any[]) =>
+ mockUpdateProfile(...(a as [unknown, string, { statusEmoji?: string | null; statusText?: string | null }])),
+ getProfile: (...a: any[]) => mockGetProfile(...(a as [unknown, string])),
+ },
+ communityMember: {
+ getCoMemberUserIds: (...a: [unknown, string]) => mockGetCoMemberUserIds(...a),
+ listMembers: (...a: any[]) => mockListMembers(...a),
+ },
+ communityFriendship: {
+ getFriendUserIds: (...a: [unknown, string]) => mockGetFriendUserIds(...a),
+ },
+ communityChannel: {
+ getChannelForMember: (...a: any[]) => mockGetChannelForMember(...a),
+ getChannelType: (...a: any[]) => mockGetChannelType(...a),
+ listChannelMemberUserIds: (...a: any[]) => mockListChannelMemberUserIds(...a),
+ isChannelPrivate: (...a: any[]) => mockIsChannelPrivate(...a),
+ getPrivateChannelAudienceUserIds: (...a: any[]) => mockGetPrivateChannelAudienceUserIds(...a),
+ },
+ communityMembersResolver: {
+ resolveScopeMemberUserIds: (...a: any[]) => mockResolveScopeMemberUserIds(...a),
+ resolveChannelRecipientUserIds: (...a: [unknown, string]) =>
+ mockResolveChannelRecipientUserIds(...a),
+ },
+ communityThread: {
+ listThreadParticipantUserIds: (...a: any[]) => mockListThreadParticipantUserIds(...a),
+ },
+ communityDm: {
+ getDM: (...a: any[]) => mockGetDM(...a),
+ },
+ communityBot: {
+ listBotsForMachine: (...a: [unknown, string]) => mockListBotsForMachine(...a),
+ getBotBinding: (...a: [unknown, string]) => mockGetBotBinding(...a),
+ getBotBindingWithOwner: (...a: [unknown, string]) => mockGetBotBindingWithOwner(...a),
+ touchBotRefreshContext: (...a: [unknown, string, string]) => mockTouchBotRefreshContext(...a),
+ },
+ communityBotAuditLog: {
+ insertBotActivityEventAndPrune: (...a: any[]) => mockInsertBotActivityEventAndPrune(...a),
+ insertBotAuditSessionReset: (...a: any[]) => mockInsertBotAuditSessionReset(...a),
+ insertBotAuditNap: (...a: any[]) => mockInsertBotAuditNap(...a),
+ insertBotAuditModelChanged: (...a: any[]) => mockInsertBotAuditModelChanged(...a),
+ insertBotAuditProviderChanged: (...a: any[]) => mockInsertBotAuditProviderChanged(...a),
+ },
+ user: {
+ getUserInternal: (...a: [unknown, string]) => mockGetUserInternal(...a),
+ },
+ },
+ }
+})
+
+// Import after mocks
+const { WebSocketDurableObject } = await import("../ws-durable")
+
+export const mockStubFetch = vi.fn().mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ sent: 1 })))
+export const mockCheckAliveFetch = vi.fn().mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ alive: true })))
+
+export function createDO() {
+ const { ctx, getWebSockets, storage, store } = createMockCtx()
+ const stubGet = vi.fn().mockReturnValue({ fetch: mockStubFetch })
+ const env = {
+ DB: {} as D1Database,
+ WS_DO: {
+ idFromName: vi.fn().mockReturnValue("mock-do-id"),
+ get: stubGet,
+ } as unknown as DurableObjectNamespace,
+ RATE_LIMIT_DO: {} as DurableObjectNamespace,
+ }
+ const durable = new WebSocketDurableObject(ctx, env)
+ return { durable, ctx, getWebSockets, env, stubGet, storage, store }
+}
+
+export const flushAsyncWork = async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ await new Promise((resolve) => setTimeout(resolve, 0))
+}
+export function resetHarness() {
+ vi.clearAllMocks()
+ // `clearAllMocks` doesn't undo a `mockResolvedValue` set by a prior test —
+ // re-pin these two to their empty default so presence-audience tests
+ // don't leak state into unrelated auth-flow tests.
+ mockGetCoMemberUserIds.mockResolvedValue([])
+ mockGetFriendUserIds.mockResolvedValue([])
+ mockListBotsForMachine.mockResolvedValue([])
+ mockIsBotOnline.mockResolvedValue(false)
+ mockGetUserInternal.mockResolvedValue(null)
+ mockIsChannelPrivate.mockResolvedValue(false)
+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue([])
+ // Non-thread default so typing uses the shared resolver path; the
+ // thread-typing test overrides this.
+ mockGetChannelType.mockResolvedValue("text")
+ mockListThreadParticipantUserIds.mockResolvedValue([])
+ mockListChannelMemberUserIds.mockResolvedValue([])
+ mockResolveScopeMemberUserIds.mockResolvedValue([])
+ mockResolveChannelRecipientUserIds.mockImplementation(resolveChannelRecipientUserIdsMock)
+ mockWithD1Retry.mockImplementation(async <T>(fn: () => Promise<T>, _opts?: unknown): Promise<T> => fn())
+ mockGetBotBinding.mockResolvedValue(null)
+ mockUpdateProfile.mockResolvedValue({})
+ mockGetProfile.mockResolvedValue(null)
+ mockReconcileBotActivityFromRunningAgents.mockResolvedValue([])
+ // Daemon-auth binds the token to a machine row for daemonId+workspace;
+ // default to a present row so auth-flow success tests pass. Tests that
+ // exercise a missing machine override this.
+ mockGetMachineByDaemon.mockResolvedValue({ daemonId: "my-daemon", workspaceId: "sp_ws1" })
+
+}
+
+export function cleanupHarness() {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+}
diff --git a/src/ws-do/src/ws-durable/user-auth.test.ts b/src/ws-do/src/ws-durable/user-auth.test.ts
new file mode 100644
index 000000000..a312115a5
--- /dev/null
+++ b/src/ws-do/src/ws-durable/user-auth.test.ts
@@ -0,0 +1,489 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { createMockWebSocket } from "../__mocks__/cf"
+import {
+ CFResponse,
+ cleanupHarness,
+ createDO,
+ flushAsyncWork,
+ mockCheckAliveFetch,
+ mockCreateDb,
+ mockFindCredentialByHash,
+ mockGetBotBinding,
+ mockGetBotBindingWithOwner,
+ mockGetChannelForMember,
+ mockGetChannelType,
+ mockGetCoMemberUserIds,
+ mockGetDM,
+ mockGetFriendUserIds,
+ mockGetLatestTokenForUser,
+ mockGetMachineByDaemon,
+ mockGetMachineByIdForUser,
+ mockGetMachineTokenByToken,
+ mockGetPrivateChannelAudienceUserIds,
+ mockGetProfile,
+ mockGetRuntimeIdsByDaemon,
+ mockGetUserInternal,
+ mockGetValidSession,
+ mockGetValidSessionWithIdentity,
+ mockHashCredential,
+ mockInsertBotActivityEventAndPrune,
+ mockInsertBotAuditModelChanged,
+ mockInsertBotAuditNap,
+ mockInsertBotAuditProviderChanged,
+ mockInsertBotAuditSessionReset,
+ mockIsBotOnline,
+ mockIsChannelPrivate,
+ mockListBotsForMachine,
+ mockListChannelMemberUserIds,
+ mockListMembers,
+ mockListThreadParticipantUserIds,
+ mockMarkMachineOffline,
+ mockMarkMachineOnlineIfOffline,
+ mockReconcileBotActivityFromRunningAgents,
+ mockResolveScopeMemberUserIds,
+ mockStubFetch,
+ mockToSummary,
+ mockTouchBotRefreshContext,
+ mockTouchMachineHeartbeat,
+ mockUpdateProfile,
+ mockUpsertMachineByMachineId,
+ resetHarness
+} from "./test-harness"
+
+describe("WebSocketDurableObject", () => {
+ beforeEach(() => resetHarness())
+ afterEach(() => cleanupHarness())
+
+
+ describe("fetch — WebSocket upgrade", () => {
+ it("returns 101 for valid WebSocket upgrade", async () => {
+ const { durable } = createDO()
+ const req = new Request("http://internal/?userId=u1", {
+ headers: { Upgrade: "websocket" },
+ })
+
+ const res = await durable.fetch(req)
+
+ expect(res.status).toBe(101)
+ expect((res as unknown as CFResponse).webSocket).toBeDefined()
+ })
+
+ it("returns 426 for non-WebSocket request", async () => {
+ const { durable } = createDO()
+ const req = new Request("http://internal/")
+
+ const res = await durable.fetch(req)
+
+ expect(res.status).toBe(426)
+ })
+
+ it("attaches an unauthenticated ConnectionState on upgrade", async () => {
+ const { durable, ctx } = createDO()
+ const req = new Request("http://internal/?userId=u1", {
+ headers: { Upgrade: "websocket" },
+ })
+
+ await durable.fetch(req)
+
+ const acceptCall = (ctx.acceptWebSocket as ReturnType<typeof vi.fn>).mock.calls[0]
+ const serverWs = acceptCall[0]
+ expect(serverWs.deserializeAttachment()).toEqual({ type: "user", userId: "", authenticated: false })
+ })
+ })
+
+
+ describe("webSocketMessage — auth flow", () => {
+ it("authenticates with valid token and sends auth.ok", async () => {
+ const { durable } = createDO()
+ mockGetValidSessionWithIdentity.mockResolvedValue({ userId: "user-42", name: "Ana", discriminator: "0012" })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))
+
+ expect(mockGetValidSessionWithIdentity).toHaveBeenCalledWith({}, "valid-token")
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))
+ expect(ws.deserializeAttachment()).toEqual({ type: "user", userId: "user-42", authenticated: true, name: "Ana", discriminator: "0012" })
+ })
+
+ it("first authenticated user connection broadcasts online presence and starts a snapshot", async () => {
+ const { durable } = createDO()
+ mockGetValidSessionWithIdentity.mockResolvedValue({ userId: "user-42", name: "Ana", discriminator: "0012" })
+ mockGetCoMemberUserIds.mockResolvedValue(["friend-1"])
+ mockStubFetch.mockImplementation(async (request: Request) =>
+ new (globalThis.Response as any)(
+ request.url.includes("/check-user-online")
+ ? JSON.stringify({ online: false })
+ : JSON.stringify({ sent: 1 }),
+ ),
+ )
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))
+ await flushAsyncWork()
+
+ const requests = mockStubFetch.mock.calls.map(([request]) => request as Request)
+ expect(requests.some((request) => request.method === "POST" && request.url.endsWith("/broadcast"))).toBe(true)
+ expect(requests.some((request) => request.method === "GET" && request.url.includes("/check-user-online"))).toBe(true)
+ })
+
+ it("second authenticated user connection does not duplicate the online presence transition", async () => {
+ const { durable, ctx } = createDO()
+ mockGetValidSessionWithIdentity.mockResolvedValue({ userId: "user-42", name: "Ana", discriminator: "0012" })
+ mockGetCoMemberUserIds.mockResolvedValue(["friend-1"])
+ mockStubFetch.mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ online: false })))
+ const existing = createMockWebSocket()
+ existing.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([existing])
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))
+ await flushAsyncWork()
+
+ const requests = mockStubFetch.mock.calls.map(([request]) => request as Request)
+ expect(requests.some((request) => request.method === "POST" && request.url.endsWith("/broadcast"))).toBe(false)
+ expect(requests.some((request) => request.method === "GET" && request.url.includes("/check-user-online"))).toBe(true)
+ })
+
+ it("closes with 1008 on invalid token", async () => {
+ const { durable } = createDO()
+ mockGetValidSessionWithIdentity.mockResolvedValue(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "bad" }))
+
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
+ expect(ws.send).not.toHaveBeenCalled()
+ })
+
+ it("closes with 1008 when auth message has no token", async () => {
+ const { durable } = createDO()
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth" }))
+
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
+ expect(ws.send).not.toHaveBeenCalled()
+ expect(mockGetValidSession).not.toHaveBeenCalled()
+ })
+
+ it("closes with 1008 when auth message has empty string token", async () => {
+ const { durable } = createDO()
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "" }))
+
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
+ expect(ws.send).not.toHaveBeenCalled()
+ expect(mockGetValidSession).not.toHaveBeenCalled()
+ })
+
+ it("closes unauthenticated connection sending non-auth message", async () => {
+ const { durable } = createDO()
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "some-event" }))
+
+ expect(ws.close).toHaveBeenCalledWith(1008, "Not authenticated")
+ })
+
+ it("closes with 1008 when session token is expired (getValidSession returns null)", async () => {
+ const { durable } = createDO()
+ mockGetValidSessionWithIdentity.mockResolvedValue(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "expired-token" }))
+
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
+ expect(ws.send).not.toHaveBeenCalled()
+ expect(ws.deserializeAttachment()).toEqual({ type: "user", userId: "", authenticated: false })
+ })
+
+ it("closes on invalid JSON", async () => {
+ const { durable } = createDO()
+
+ const ws = createMockWebSocket()
+
+ await durable.webSocketMessage(ws as any, "not-json")
+
+ expect(ws.close).toHaveBeenCalledWith(1008, "Invalid JSON")
+ })
+
+ it("ignores binary messages", async () => {
+ const { durable } = createDO()
+
+ const ws = createMockWebSocket()
+
+ await durable.webSocketMessage(ws as any, new ArrayBuffer(4))
+
+ expect(ws.close).not.toHaveBeenCalled()
+ expect(ws.send).not.toHaveBeenCalled()
+ })
+ })
+
+
+ describe("webSocketMessage — daemon auth flow", () => {
+ it("rejects daemon with pending token (not yet activated)", async () => {
+ const { durable } = createDO()
+ mockGetMachineTokenByToken.mockResolvedValue({
+ id: "mt_1", userId: "u1", status: "pending", workspaceId: null,
+ })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "daemon", daemonId: "", userId: "", authenticated: false })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "auth", machineToken: "al_pending123", daemonId: "my-daemon" }),
+ )
+
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
+ expect(mockGetRuntimeIdsByDaemon).not.toHaveBeenCalled()
+ })
+
+ it("authenticates daemon with active token (no runtime check in auth)", async () => {
+ const { durable } = createDO()
+ mockGetMachineTokenByToken.mockResolvedValue({
+ id: "mt_1", userId: "u1", status: "active", workspaceId: "sp_ws1",
+ })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "auth", machineToken: "al_active123", daemonId: "my-daemon" }),
+ )
+
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))
+ // Runtime presence is no longer part of auth — it must not gate the WS
+ // connection (tasks route by workspaceId; runtimes may be mid-register).
+ expect(mockGetRuntimeIdsByDaemon).not.toHaveBeenCalled()
+ })
+
+ it("authenticates daemon with active token even when it has no runtimes yet", async () => {
+ const { durable } = createDO()
+ mockGetMachineTokenByToken.mockResolvedValue({
+ id: "mt_1", userId: "u1", status: "active", workspaceId: "sp_ws1",
+ })
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "auth", machineToken: "al_noruntimes", daemonId: "my-daemon" }),
+ )
+
+ // No-runtime is a valid state (not an auth failure) — auth.ok, no reject.
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))
+ expect(ws.send).not.toHaveBeenCalledWith(JSON.stringify({ type: "error", code: "AUTH_REJECTED" }))
+ })
+
+ it("sends AUTH_REJECTED then closes on definitely-invalid token", async () => {
+ const { durable } = createDO()
+ mockGetMachineTokenByToken.mockResolvedValue(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "auth", machineToken: "al_dead", daemonId: "my-daemon" }),
+ )
+
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "error", code: "AUTH_REJECTED" }))
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
+ })
+
+ it("closes WITHOUT AUTH_REJECTED on transient D1 failure (daemon must retry)", async () => {
+ const { durable } = createDO()
+ mockGetMachineTokenByToken.mockRejectedValue(new Error("D1 unavailable"))
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "auth", machineToken: "al_blip", daemonId: "my-daemon" }),
+ )
+
+ expect(ws.send).not.toHaveBeenCalledWith(JSON.stringify({ type: "error", code: "AUTH_REJECTED" }))
+ expect(ws.close).toHaveBeenCalledWith(1011, "Auth temporarily unavailable")
+ })
+
+ it("rejects daemon with unknown token", async () => {
+ const { durable } = createDO()
+ mockGetMachineTokenByToken.mockResolvedValue(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "auth", machineToken: "al_unknown", daemonId: "my-daemon" }),
+ )
+
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
+ })
+
+ it("rejects daemon with non-al_ prefixed token", async () => {
+ const { durable } = createDO()
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "daemon", daemonId: "", authenticated: false })
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({ type: "auth", machineToken: "bad_prefix", daemonId: "my-daemon" }),
+ )
+
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
+ expect(mockGetMachineTokenByToken).not.toHaveBeenCalled()
+ })
+ })
+
+
+ describe("webSocketMessage — check_daemon_status (cross-DO)", () => {
+ it("returns runtime.status online when daemon DO reports alive", async () => {
+ const { durable, env } = createDO()
+ mockGetLatestTokenForUser.mockResolvedValue({ hostname: "MyMachine.local" })
+
+ const aliveStub = { fetch: vi.fn().mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ alive: true }))) }
+ ; (env.WS_DO as any).get = vi.fn().mockReturnValue(aliveStub)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
+
+ expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("daemon:MyMachine.local")
+ expect(ws.send).toHaveBeenCalledWith(
+ JSON.stringify({ type: "runtime.status", status: "online", daemonId: "MyMachine.local" }),
+ )
+ })
+
+ it("does not respond when daemon DO reports not alive", async () => {
+ const { durable, env } = createDO()
+ mockGetLatestTokenForUser.mockResolvedValue({ hostname: "MyMachine.local" })
+
+ const deadStub = { fetch: vi.fn().mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ alive: false }))) }
+ ; (env.WS_DO as any).get = vi.fn().mockReturnValue(deadStub)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
+
+ expect(ws.send).not.toHaveBeenCalled()
+ })
+
+ it("does not respond when no token/hostname found", async () => {
+ const { durable } = createDO()
+ mockGetLatestTokenForUser.mockResolvedValue(null)
+
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
+
+ expect(ws.send).not.toHaveBeenCalled()
+ })
+
+ it("does not respond when the daemon durable object fetch rejects", async () => {
+ const { durable, env } = createDO()
+ mockGetLatestTokenForUser.mockResolvedValue({ hostname: "MyMachine.local" })
+ ;(env.WS_DO as any).get = vi.fn().mockReturnValue({
+ fetch: vi.fn().mockRejectedValue(new Error("daemon DO unavailable")),
+ })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
+
+ expect(ws.send).not.toHaveBeenCalled()
+ expect(ws.close).not.toHaveBeenCalled()
+ })
+ })
+
+
+ describe("webSocketError", () => {
+ it("closes with 1011", async () => {
+ const { durable } = createDO()
+
+ const ws = createMockWebSocket()
+
+ await durable.webSocketError(ws as any, new Error("boom"))
+
+ expect(ws.close).toHaveBeenCalledWith(1011, "Internal error")
+ })
+ })
+
+
+ describe("webSocketClose — user and daemon characterization", () => {
+ it("keeps user presence online while another authenticated tab remains", async () => {
+ const { durable, ctx } = createDO()
+ const closing = createMockWebSocket()
+ closing.serializeAttachment({ type: "user", userId: "user-1", authenticated: true })
+ const other = createMockWebSocket()
+ other.serializeAttachment({ type: "user", userId: "user-1", authenticated: true })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([closing, other])
+
+ await durable.webSocketClose(closing as any)
+ await flushAsyncWork()
+
+ expect(mockGetCoMemberUserIds).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("broadcasts offline presence when the last authenticated user tab closes", async () => {
+ const { durable, ctx } = createDO()
+ mockGetCoMemberUserIds.mockResolvedValue(["friend-1"])
+ mockStubFetch.mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ sent: 1 })))
+ const closing = createMockWebSocket()
+ closing.serializeAttachment({ type: "user", userId: "user-1", authenticated: true })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([closing])
+
+ await durable.webSocketClose(closing as any)
+ await flushAsyncWork()
+
+ const [request] = mockStubFetch.mock.calls[0] as [Request]
+ expect(await request.clone().json()).toEqual({
+ type: "community:presence.update",
+ userId: "user-1",
+ online: false,
+ })
+ })
+
+ it("reports daemon offline and swallows a rejected owner notification", async () => {
+ const { durable } = createDO()
+ mockStubFetch.mockRejectedValue(new Error("owner DO unavailable"))
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "daemon", daemonId: "daemon-1", userId: "user-1", authenticated: true })
+
+ await expect(durable.webSocketClose(ws as any)).resolves.toBeUndefined()
+ await flushAsyncWork()
+
+ expect(mockStubFetch).toHaveBeenCalledTimes(1)
+ const [request] = mockStubFetch.mock.calls[0] as [Request]
+ expect(await request.clone().json()).toEqual({
+ type: "runtime.status",
+ status: "offline",
+ daemonId: "daemon-1",
+ })
+ })
+ })
+})
diff --git a/src/ws-do/src/ws-durable/user-auth.ts b/src/ws-do/src/ws-durable/user-auth.ts
new file mode 100644
index 000000000..dac8329ca
--- /dev/null
+++ b/src/ws-do/src/ws-durable/user-auth.ts
@@ -0,0 +1,276 @@
+import { createDb, queries, readOrStale } from "@alook/shared"
+import type {
+ CommunityMachineConnectionState,
+ ConnectionState,
+ WsDurableContext,
+} from "./internal"
+import {
+ broadcastPresence,
+ handleClientTypingStart,
+ notifyUserDO,
+ sendPresenceSnapshot,
+} from "./presence-typing"
+
+export async function handleUserFetch(
+ context: WsDurableContext,
+ request: Request,
+ url: URL,
+): Promise<Response | null> {
+ if (url.pathname === "/broadcast" && request.method === "POST") {
+ const body = await request.text()
+ const sent = broadcast(context, body)
+ return new Response(JSON.stringify({ sent }), {
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+
+ if (url.pathname === "/check-alive") {
+ const hasAuthDaemon = context.ctx.getWebSockets().some(ws => {
+ const s = ws.deserializeAttachment() as ConnectionState
+ return s?.type === "daemon" && s.authenticated
+ })
+ return new Response(JSON.stringify({ alive: hasAuthDaemon }), {
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+
+ if (url.pathname === "/check-user-online") {
+ const targetUserId = url.searchParams.get("userId")
+ const hasAuthUser = context.ctx.getWebSockets().some(ws => {
+ const s = ws.deserializeAttachment() as ConnectionState
+ return s?.type === "user" && s.authenticated
+ })
+ if (hasAuthUser) {
+ return new Response(JSON.stringify({ online: true }), {
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+ if (targetUserId) {
+ const db = createDb(context.env.DB)
+ const { value, stale } = await readOrStale<{ isBotResolved: boolean; online: boolean }>(
+ async () => {
+ const target = await queries.user.getUserInternal(db, targetUserId)
+ if (target?.isBot) {
+ const online = await queries.communityMachine.isBotOnline(db, targetUserId)
+ return { isBotResolved: true, online }
+ }
+ return { isBotResolved: false, online: false }
+ },
+ { isBotResolved: false, online: false },
+ { route: "ws-do/check-user-online" },
+ )
+ if (stale) {
+ return new Response(JSON.stringify({ online: false, stale: true }), {
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+ if (value.isBotResolved) {
+ return new Response(JSON.stringify({ online: value.online }), {
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+ }
+ return new Response(JSON.stringify({ online: false }), {
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+
+ return null
+}
+
+export function acceptUserWebSocket(context: WsDurableContext): Response {
+ const pair = new WebSocketPair()
+ const [client, server] = Object.values(pair)
+
+ context.ctx.acceptWebSocket(server)
+
+ server.serializeAttachment({ type: "user", userId: "", authenticated: false } as ConnectionState)
+
+ context.ctx.setWebSocketAutoResponse(
+ new WebSocketRequestResponsePair("ping", "pong")
+ )
+
+ return new Response(null, { status: 101, webSocket: client })
+}
+
+export async function handleWebSocketMessage(
+ context: WsDurableContext,
+ ws: WebSocket,
+ message: string | ArrayBuffer,
+ handleCommunityMachineMessage: (parsed: unknown) => Promise<void>,
+): Promise<void> {
+ if (typeof message !== "string") return
+
+ let parsed: unknown
+ try { parsed = JSON.parse(message) } catch { ws.close(1008, "Invalid JSON"); return }
+
+ const state = ws.deserializeAttachment() as ConnectionState
+
+ if (state?.type === "community-machine") {
+ await handleCommunityMachineMessage(parsed)
+ return
+ }
+
+ const msg = parsed as { type: string; token?: string; machineToken?: string; daemonId?: string }
+
+ if (msg.type === "auth") {
+ if (msg.machineToken && msg.daemonId) {
+ const authResult = await validateMachineToken(context, msg.machineToken, msg.daemonId)
+ if (authResult.kind === "invalid") {
+ context.log.warn("daemon websocket auth rejected", { daemonId: msg.daemonId })
+ try { ws.send(JSON.stringify({ type: "error", code: "AUTH_REJECTED" })) } catch { }
+ ws.close(1008, "Unauthorized")
+ return
+ }
+ if (authResult.kind === "transient") {
+ context.log.warn("daemon websocket auth transient failure", { daemonId: msg.daemonId })
+ ws.close(1011, "Auth temporarily unavailable")
+ return
+ }
+ ws.serializeAttachment({ type: "daemon", daemonId: msg.daemonId, userId: authResult.userId, authenticated: true } as ConnectionState)
+ context.log.info("daemon websocket authenticated", { daemonId: msg.daemonId })
+ ws.send(JSON.stringify({ type: "auth.ok" }))
+
+ notifyUserDO(context, authResult.userId, { type: "runtime.status", status: "online", daemonId: msg.daemonId }).catch(() => { })
+ return
+ }
+
+ if (!msg.token) {
+ ws.close(1008, "Unauthorized")
+ return
+ }
+ const identity = await validateToken(context, msg.token)
+ if (!identity) {
+ context.log.warn("websocket auth failed")
+ ws.close(1008, "Unauthorized")
+ return
+ }
+ const { userId, name, discriminator } = identity
+ const wasOnline = countAuthenticatedUserConnections(context, userId) > 0
+ ws.serializeAttachment({ type: "user", userId, authenticated: true, name, discriminator } as ConnectionState)
+ context.log.info("websocket authenticated", { userId })
+ ws.send(JSON.stringify({ type: "auth.ok" }))
+ if (!wasOnline) {
+ broadcastPresence(context, userId, true).catch(() => { })
+ }
+ sendPresenceSnapshot(context, ws, userId).catch(() => { })
+ return
+ }
+
+ if (!state.authenticated) {
+ ws.close(1008, "Not authenticated")
+ return
+ }
+
+ if (msg.type === "check_daemon_status" && state.type === "user") {
+ const daemonId = await getDaemonIdForUser(context, state.userId)
+ if (daemonId) {
+ try {
+ const daemonDoId = context.env.WS_DO.idFromName("daemon:" + daemonId)
+ const daemonStub = context.env.WS_DO.get(daemonDoId)
+ const resp = await daemonStub.fetch(new Request("http://internal/check-alive"))
+ const { alive } = await resp.json() as { alive: boolean }
+ if (alive) {
+ ws.send(JSON.stringify({ type: "runtime.status", status: "online", daemonId }))
+ }
+ } catch {
+ context.log.debug("check_daemon_status: failed to reach daemon DO", { daemonId })
+ }
+ }
+ return
+ }
+
+ if (state.type === "user" && handleClientTypingStart(context, state, parsed)) return
+}
+
+export async function handleWebSocketClose(
+ context: WsDurableContext,
+ ws: WebSocket,
+ handleCommunityMachineClose: (state: CommunityMachineConnectionState) => Promise<void>,
+): Promise<void> {
+ const state = ws.deserializeAttachment() as ConnectionState
+ if (state?.type === "daemon" && state.authenticated) {
+ context.log.info("daemon websocket closed", { daemonId: state.daemonId })
+ notifyUserDO(context, state.userId, { type: "runtime.status", status: "offline", daemonId: state.daemonId }).catch(() => { })
+ }
+ if (state?.type === "user" && state.authenticated) {
+ const remaining = countAuthenticatedUserConnections(context, state.userId) - 1
+ if (remaining <= 0) {
+ broadcastPresence(context, state.userId, false).catch(() => { })
+ }
+ }
+ if (state?.type === "community-machine" && state.authenticated) {
+ await handleCommunityMachineClose(state)
+ }
+}
+
+export async function handleWebSocketError(
+ context: WsDurableContext,
+ ws: WebSocket,
+ error: unknown,
+): Promise<void> {
+ context.log.error("websocket error", { err: error instanceof Error ? error : String(error) })
+ try { ws.close(1011, "Internal error") } catch { }
+}
+
+function broadcast(context: WsDurableContext, message: string): number {
+ let sent = 0
+ for (const ws of context.ctx.getWebSockets()) {
+ const state = ws.deserializeAttachment() as ConnectionState
+ if (state.authenticated) {
+ try {
+ ws.send(message)
+ sent++
+ } catch { }
+ }
+ }
+ return sent
+}
+
+function countAuthenticatedUserConnections(context: WsDurableContext, userId: string): number {
+ let count = 0
+ for (const ws of context.ctx.getWebSockets()) {
+ const state = ws.deserializeAttachment() as ConnectionState
+ if (state?.type === "user" && state.authenticated && state.userId === userId) {
+ count++
+ }
+ }
+ return count
+}
+
+async function getDaemonIdForUser(context: WsDurableContext, userId: string): Promise<string | null> {
+ const db = createDb(context.env.DB)
+ const token = await queries.machineToken.getLatestTokenForUser(db, userId)
+ return token?.hostname || null
+}
+
+async function validateToken(
+ context: WsDurableContext,
+ token: string,
+): Promise<{ userId: string; name: string; discriminator: string } | null> {
+ const db = createDb(context.env.DB)
+ return queries.session.getValidSessionWithIdentity(db, token)
+}
+
+async function validateMachineToken(
+ context: WsDurableContext,
+ token: string,
+ daemonId: string,
+): Promise<
+ | { kind: "valid"; userId: string }
+ | { kind: "invalid" }
+ | { kind: "transient" }
+> {
+ if (!token.startsWith("al_")) return { kind: "invalid" }
+ try {
+ const db = createDb(context.env.DB)
+ const mt = await queries.machineToken.getMachineTokenByToken(db, token)
+ if (!mt || mt.status !== "active" || !mt.workspaceId) return { kind: "invalid" }
+ const machine = await queries.machine.getMachineByDaemon(db, daemonId, mt.workspaceId)
+ if (!machine) return { kind: "invalid" }
+ return { kind: "valid", userId: mt.userId }
+ } catch (err) {
+ context.log.warn("daemon websocket auth lookup threw", { err: String(err) })
+ return { kind: "transient" }
+ }
+}