Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(community): stamp sender name on typing events to kill 'Unknown member'
Claudette#9873e9feb408c1a1
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex 9e22fa0d1..18946b913 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -91,6 +91,14 @@ export type CommunityTypingStart = {type: "community:typing.start"channelId: stringuserId: string+ // Sender's display name + discriminator, stamped server-side at fan-out from+ // already-known identity (connection state for humans, bot binding for bots)+ // — never a per-event DB lookup. Optional so an older client ignores it and+ // falls back to roster resolution; present, it lets the client render the+ // name without depending on whether the typer is in the loaded roster page+ // (the "Unknown member is typing" bug when they aren't).+ name?: string+ discriminator?: string}/**@@ -103,6 +111,8 @@ export type CommunityTypingStop = {type: "community:typing.stop"channelId: stringuserId: string+ name?: string+ discriminator?: string}// ── Child channel events (threads + forum posts) ─────────────────────────────diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex a15a19541..c60d4ba7a 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -219,12 +219,17 @@ export async function getBotBinding(export async function getBotBindingWithOwner(db: Database,botId: string-): Promise<{ machineId: string; runtime: string; ownerUserId: string } | null> {+): Promise<{ machineId: string; runtime: string; ownerUserId: string; name: string; discriminator: string } | null> {const rows = await db.select({machineId: communityBotBinding.machineId,runtime: communityBotBinding.runtime,ownerUserId: user.ownerUserId,+ // Bot's display identity — carried on typing fan-out so the client+ // renders the name without a roster lookup. Free: this join already+ // reads the `user` row.+ name: user.name,+ discriminator: user.discriminator,}).from(user).innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))@@ -238,7 +243,7 @@ export async function getBotBindingWithOwner(.limit(1);const r = rows[0];if (!r || !r.ownerUserId) return null;- return { machineId: r.machineId, runtime: r.runtime, ownerUserId: r.ownerUserId };+ return { machineId: r.machineId, runtime: r.runtime, ownerUserId: r.ownerUserId, name: r.name, discriminator: r.discriminator };}/**diff --git a/src/shared/src/db/queries/session.ts b/src/shared/src/db/queries/session.tsindex 1c2fa959e..e79f4e4fc 100644--- a/src/shared/src/db/queries/session.ts+++ b/src/shared/src/db/queries/session.ts@@ -1,5 +1,5 @@import { eq, and, gt } from "drizzle-orm";-import { session } from "../schema";+import { session, user } from "../schema";import type { Database } from "../index";export async function getValidSession(db: Database, token: string) {@@ -15,3 +15,32 @@ export async function getValidSession(db: Database, token: string) {if (rows.length === 0) return null;return rows[0].userId;}++/**+ * Like `getValidSession`, but also returns the user's display `name` ++ * `discriminator` (one join to `user`). Used by the WS-auth handshake so the+ * connection state can carry the name and typing fan-out stamps it into the+ * event WITHOUT a per-event DB lookup (see the "Unknown member is typing" fix).+ * Runs once per WS connection at auth, not on the hot typing path.+ */+export async function getValidSessionWithIdentity(+ db: Database,+ token: string+): Promise<{ userId: string; name: string; discriminator: string } | null> {+ const rows = await db+ .select({+ userId: session.userId,+ name: user.name,+ discriminator: user.discriminator,+ })+ .from(session)+ .innerJoin(user, eq(user.id, session.userId))+ .where(+ and(+ eq(session.token, token),+ gt(session.expiresAt, new Date().toISOString())+ )+ );+ if (rows.length === 0) return null;+ return rows[0];+}diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.tsindex 9828af3aa..7cbb984b4 100644--- a/src/ws-do/src/ws-durable.test.ts+++ b/src/ws-do/src/ws-durable.test.ts@@ -63,6 +63,7 @@ vi.mock("cloudflare:workers", () => ({// Mock @alook/sharedconst 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()@@ -90,7 +91,7 @@ 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 } | 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 mockUpdateProfile = vi.fn<(db: unknown, userId: string, data: { statusEmoji?: string | null; statusText?: string | null }) => Promise<unknown>>()@@ -292,7 +293,10 @@ vi.mock("@alook/shared", () => {return pairs.some((p) => p.emoji === emoji && p.text === text)},queries: {- session: { getValidSession: (db: unknown, token: string) => mockGetValidSession(db, token) },+ 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),@@ -573,21 +577,21 @@ describe("WebSocketDurableObject", () => {describe("webSocketMessage — auth flow", () => {it("authenticates with valid token and sends auth.ok", async () => {const { durable } = createDO()- mockGetValidSession.mockResolvedValue("user-42")+ 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(mockGetValidSession).toHaveBeenCalledWith({}, "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 })+ 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()- mockGetValidSession.mockResolvedValue(null)+ mockGetValidSessionWithIdentity.mockResolvedValue(null)const ws = createMockWebSocket()ws.serializeAttachment({ type: "user", userId: "", authenticated: false })@@ -637,7 +641,7 @@ describe("WebSocketDurableObject", () => {it("closes with 1008 when session token is expired (getValidSession returns null)", async () => {const { durable } = createDO()- mockGetValidSession.mockResolvedValue(null)+ mockGetValidSessionWithIdentity.mockResolvedValue(null)const ws = createMockWebSocket()ws.serializeAttachment({ type: "user", userId: "", authenticated: false })@@ -1515,6 +1519,8 @@ describe("WebSocketDurableObject", () => {machineId: "cm_1",runtime: "codex",ownerUserId: "u_1",+ name: "Bot",+ discriminator: "0007",})mockGetChannelForMember.mockResolvedValue({ id: "dm_1", serverId: null })mockGetChannelType.mockResolvedValue("dm")@@ -1541,11 +1547,17 @@ describe("WebSocketDurableObject", () => {type: stringuserId: stringchannelId: 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",})})@@ -1560,6 +1572,8 @@ describe("WebSocketDurableObject", () => {machineId: "cm_OTHER",runtime: "codex",ownerUserId: "u_1",+ name: "Bot",+ discriminator: "0007",})const ws = createMockWebSocket()@@ -1592,6 +1606,8 @@ describe("WebSocketDurableObject", () => {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.@@ -1626,6 +1642,8 @@ describe("WebSocketDurableObject", () => {machineId: "cm_1",runtime: "codex",ownerUserId: "u_1",+ name: "Bot",+ discriminator: "0007",})mockGetChannelForMember.mockResolvedValue({ id: "dm_1", serverId: null })mockGetChannelType.mockResolvedValue("dm")@@ -1682,6 +1700,8 @@ describe("WebSocketDurableObject", () => {machineId: "cm_1",runtime: "codex",ownerUserId: "owner_1",+ name: "Bot",+ discriminator: "0007",})mockInsertBotActivityEventAndPrune.mockResolvedValue({id: "bae_abc",@@ -1752,6 +1772,8 @@ describe("WebSocketDurableObject", () => {machineId: "cm_OTHER",runtime: "codex",ownerUserId: "owner_1",+ name: "Bot",+ discriminator: "0007",})const ws = createMockWebSocket()@@ -1812,6 +1834,8 @@ describe("WebSocketDurableObject", () => {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)@@ -1848,6 +1872,8 @@ describe("WebSocketDurableObject", () => {machineId: "cm_1",runtime: "codex",ownerUserId: "owner_1",+ name: "Bot",+ discriminator: "0007",})mockInsertBotActivityEventAndPrune.mockRejectedValue(new Error("D1 insert failed"))diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.tsindex 68979ccc9..614896c57 100644--- a/src/ws-do/src/ws-durable.ts+++ b/src/ws-do/src/ws-durable.ts@@ -41,7 +41,7 @@ function canonicalRuntimes(list: CommunityMachineRuntime[]): string {const log = createLogger({ service: "ws-do" })type ConnectionState =- | { type: "user"; userId: string; authenticated: boolean }+ | { type: "user"; userId: string; authenticated: boolean; name?: string; discriminator?: string }| { type: "daemon"; daemonId: string; userId: string; authenticated: boolean }| {type: "community-machine"@@ -371,14 +371,15 @@ export class WebSocketDurableObject extends DurableObject<Env> {ws.close(1008, "Unauthorized")return}- const userId = await this.validateToken(msg.token)- if (!userId) {+ const identity = await this.validateToken(msg.token)+ if (!identity) {log.warn("websocket auth failed")ws.close(1008, "Unauthorized")return}+ const { userId, name, discriminator } = identityconst wasOnline = this.countAuthenticatedUserConnections(userId) > 0- ws.serializeAttachment({ type: "user", userId, authenticated: true } as ConnectionState)+ 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) {@@ -451,10 +452,16 @@ export class WebSocketDurableObject extends DurableObject<Env> {// 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: "community:typing.start",channelId: typingMsg.channelId,userId: state.userId,+ name: state.name,+ discriminator: state.discriminator,})// Resolve recipients and broadcast@@ -850,13 +857,17 @@ export class WebSocketDurableObject extends DurableObject<Env> {machineId: identity.machineId,resolveBinding: () => queries.communityBot.getBotBindingWithOwner(db, agentId),isMatch: (binding) => binding.machineId === identity.machineId,- write: async () => {+ write: async (binding) => {// Channel membership is enforced inside `fanOutTyping` — no need to- // pre-query here at 5s cadence.+ // 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: "community:typing.start",channelId,userId: agentId,+ name: binding.name,+ discriminator: binding.discriminator,})await this.fanOutTyping(agentId, channelId, event)},@@ -1192,9 +1203,14 @@ export class WebSocketDurableObject extends DurableObject<Env> {return token?.hostname || null}- private async validateToken(token: string): Promise<string | null> {+ private async validateToken(+ token: string,+ ): Promise<{ userId: string; name: string; discriminator: string } | null> {const db = createDb(this.env.DB)- return queries.session.getValidSession(db, token)+ // 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)}/**