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
feat(community): agent global handles, gated busy-steering, presence + account-debt fixes
Gusa25c7793a50a
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.tsindex bcaf90850..fcd6cd860 100644--- a/src/daemon/src/daemon/createDaemon.test.ts+++ b/src/daemon/src/daemon/createDaemon.test.ts@@ -188,7 +188,7 @@ describe("createDaemon — logging", () => {sockets[0].emit("message",- JSON.stringify({ type: "bot:added", botId: "bot_1", name: "Bot One" }),+ JSON.stringify({ type: "bot:added", botId: "bot_1", name: "Bot One", discriminator: "4821" }),);// bot:added is logged directly on the root logger (createDaemon's own tag).expect(logger.calls.debug.some(([, m]) => m === "bot:added")).toBe(true);@@ -216,6 +216,90 @@ describe("createDaemon — logging", () => {await daemon.stop();});+ it("baseContextFor builds config.agentHandle from the botsById cache's name+discriminator, and bot:updated refreshes it", async () => {+ global.fetch = vi.fn(async (url: string | URL) => {+ const href = String(url);+ if (href.includes("/enroll-agent")) {+ return new Response(JSON.stringify({ runnerKey: "rk_1" }), { status: 200 });+ }+ return new Response(JSON.stringify({ bots: [] }), { status: 200 });+ }) as unknown as typeof fetch;++ const seenConfigs: Array<{ agentName?: string; agentHandle?: string }> = [];+ const driver: Driver = {+ ...fullFakeDriver("codex"),+ buildSystemPrompt: (config: { agentName?: string; agentHandle?: string }) => {+ seenConfigs.push(config);+ return "";+ },+ } as unknown as Driver;++ const sockets: FakeSocket[] = [];+ const daemon = await createDaemon({+ machineKey: "cmk_handle",+ serverUrl: "http://localhost:9999",+ serverWsUrl: "ws://x",+ webSocketFactory: factory(sockets) as any,+ runtimeReport: [{ id: "codex" }],+ driverFor: () => driver,+ capabilities: [],+ });+ sockets[0].emit("open");+ // Let cold-start warmup's async fetch (bots: []) settle first — it+ // `botsById.clear()`s on resolve, which would otherwise wipe out the+ // bot:added entry below if it lands first.+ await new Promise((r) => setTimeout(r, 20));++ sockets[0].emit(+ "message",+ JSON.stringify({ type: "bot:added", botId: "bot_1", name: "Bot One", discriminator: "4821" }),+ );+ sockets[0].emit(+ "message",+ JSON.stringify({+ type: "agent:wake",+ agentId: "bot_1",+ config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: "l1",+ unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 1 },+ }),+ );+ await new Promise((r) => setTimeout(r, 20));++ expect(seenConfigs).toContainEqual(+ expect.objectContaining({ agentName: "Bot One", agentHandle: "@Bot One#4821" }),+ );++ // A second bot, added then immediately corrected via bot:updated BEFORE+ // its first spawn — proves bot:updated's discriminator/name land in the+ // cache the next spawn reads from (not just bot:added's).+ sockets[0].emit(+ "message",+ JSON.stringify({ type: "bot:added", botId: "bot_2", name: "Wrong Name", discriminator: "0000" }),+ );+ sockets[0].emit(+ "message",+ JSON.stringify({ type: "bot:updated", botId: "bot_2", name: "Bot Two", discriminator: "1111" }),+ );+ sockets[0].emit(+ "message",+ JSON.stringify({+ type: "agent:wake",+ agentId: "bot_2",+ config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: "l2",+ unreadNotice: { kind: "unread_notice", channel: "/demo/general", latestSeq: 2 },+ }),+ );+ await new Promise((r) => setTimeout(r, 20));++ expect(seenConfigs).toContainEqual(+ expect.objectContaining({ agentName: "Bot Two", agentHandle: "@Bot Two#1111" }),+ );++ await daemon.stop();+ });+it("logs cold-start warmup success with the bot count", async () => {global.fetch = vi.fn(async () => new Response(JSON.stringify({ bots: [{ id: "b1", name: "n" }] }), { status: 200 })) as unknown as typeof fetch;diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex 2f1e029e8..53cba1399 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -33,6 +33,7 @@ import { createLogger, type Logger } from "../logger.js";import type { Driver, LaunchContext } from "../types.js";import type { RuntimeConfig } from "../runtimeConfig.js";import type { UnreadNotice, HostCommand } from "../server/contract.js";+import { formatHandle } from "@alook/shared/lib/discriminator";// Cold-start warmup backoff schedule (ms).const WARMUP_BACKOFF_MS = [250, 500, 1000, 2000, 4000] as const;@@ -137,10 +138,10 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa//// Note: `cmk_`-rotation-implies-re-pair is documented as an assumption;// runtime code doesn't handle rotation.- const botsById = new Map<string, { name: string; description?: string }>();+ const botsById = new Map<string, { name: string; discriminator: string; description?: string }>();async function listMyBotsHttp(): Promise<- Array<{ id: string; name: string; description?: string }>+ Array<{ id: string; name: string; discriminator: string; description?: string }>> {const res = await fetch(`${opts.serverUrl}/api/community/daemon/bots`, {method: "GET",@@ -148,7 +149,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa});if (!res.ok) throw new Error(`listMyBots ${res.status}`);const json = (await res.json()) as {- bots?: Array<{ id: string; name: string; description?: string }>;+ bots?: Array<{ id: string; name: string; discriminator: string; description?: string }>;};return json.bots ?? [];}@@ -162,7 +163,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa// Server snapshot wins — reconcile the cache.botsById.clear();for (const b of bots) {- botsById.set(b.id, { name: b.name, description: b.description });+ botsById.set(b.id, { name: b.name, discriminator: b.discriminator, description: b.description });}log.info("cold-start bot-cache warmup succeeded", { bots: bots.length, attempt });return;@@ -251,12 +252,12 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDafunction handleBotFrame(cmd: HostCommand): void {switch (cmd.type) {case "bot:added":- botsById.set(cmd.botId, { name: cmd.name, description: cmd.description });+ botsById.set(cmd.botId, { name: cmd.name, discriminator: cmd.discriminator, description: cmd.description });log.debug("bot:added", { botId: cmd.botId, name: cmd.name });break;case "bot:updated": {const prev = botsById.get(cmd.botId);- botsById.set(cmd.botId, { name: cmd.name, description: cmd.description });+ botsById.set(cmd.botId, { name: cmd.name, discriminator: cmd.discriminator, description: cmd.description });// If a subprocess is running for this bot AND name/description changed,// stop it so the next wake trigger spawns a fresh subprocess with the// new system prompt. Rename is effective on next spawn, not mid-flight.@@ -319,6 +320,9 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaagentCliPath: resolvedCliPath ?? opts.agentCliPath,config: {...(botMeta?.name ? { agentName: botMeta.name } : {}),+ ...(botMeta?.name && botMeta?.discriminator+ ? { agentHandle: `@${formatHandle(botMeta.name, botMeta.discriminator)}` }+ : {}),...(botMeta?.description ? { description: botMeta.description } : {}),} as LaunchContext["config"],} as Omit<LaunchContext, "prompt" | "standingPrompt"> & { config?: LaunchContext["config"] };@@ -354,7 +358,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDatry {const bots = await listMyBotsHttp();for (const b of bots) {- botsById.set(b.id, { name: b.name, description: b.description });+ botsById.set(b.id, { name: b.name, discriminator: b.discriminator, description: b.description });}} catch {// Fall through — still treat as unknown below.diff --git a/src/daemon/src/drivers/codex.ts b/src/daemon/src/drivers/codex.tsindex 361cb5865..d7279bc56 100644--- a/src/daemon/src/drivers/codex.ts+++ b/src/daemon/src/drivers/codex.ts@@ -1,10 +1,14 @@/**- * Codex driver — persistent, JSON-RPC app-server, DIRECT steering.+ * Codex driver — persistent, JSON-RPC app-server, GATED steering.*- * Codex runs as `app-server --listen stdio://` and speaks JSON-RPC 2.0. Unlike- * Claude, it tolerates injection at any time, so busy delivery is `direct`:- * a busy message becomes a `turn/steer` RPC against the active turn, while an- * idle message becomes a fresh `turn/start`.+ * Codex runs as `app-server --listen stdio://` and speaks JSON-RPC 2.0. Like+ * Claude, a `turn/steer` sent while a tool call / compaction / review is in+ * flight can race the app-server's own turn-state handling, so busy delivery+ * is `gated` — held until a safe boundary by the manager-level mechanism in+ * `manager/managerPolicy.ts` (see plans/wire-gated-busy-steering-daemon.md). A+ * busy message becomes a `turn/steer` RPC against the active turn, while an+ * idle message becomes a fresh `turn/start` — the encoding itself is+ * unaffected by gating, only WHEN the manager calls it.** Handshake (queued on spawn): `initialize` → then `thread/start` (or* `thread/resume` with the prior threadId). The thread id is the session id.@@ -42,7 +46,7 @@ export function classifyCodexResumeError(export class CodexDriver implements Driver {readonly id = "codex";- readonly lifecycle = { kind: "persistent", stdin: "direct", inFlightWake: "steer" } as const;+ readonly lifecycle = { kind: "persistent", stdin: "gated", inFlightWake: "queue" } as const;readonly session = { recovery: "resume_or_fresh" } as const;readonly model = {detectedModelsVerifiedAs: "launchable",@@ -50,7 +54,7 @@ export class CodexDriver implements Driver {} as const;readonly supportsStdinNotification = true;- readonly busyDeliveryMode = "direct" as const;+ readonly busyDeliveryMode = "gated" as const;readonly supportsNativeStandingPrompt = true;private readonly eventNormalizer = new CodexEventNormalizer();@@ -61,11 +65,6 @@ export class CodexDriver implements Driver {return ++this.requestId;}- /** Safe to inject a busy (steering) message right now? */- get canSteerBusy(): boolean {- return this.eventNormalizer.canSteerBusy;- }-/** Resolved Codex home root (CODEX_HOME or ~/.codex). Null until spawned. */get codexHome(): string | null {return this.codexHomeRoot;diff --git a/src/daemon/src/drivers/codexEventNormalizer.test.ts b/src/daemon/src/drivers/codexEventNormalizer.test.tsnew file mode 100644index 000000000..552efea35--- /dev/null+++ b/src/daemon/src/drivers/codexEventNormalizer.test.ts@@ -0,0 +1,69 @@+/**+ * Tests for `CodexEventNormalizer` — in particular the tool_call/tool_output+ * symmetry fix from plans/wire-gated-busy-steering-daemon.md (§9c): before+ * this fix, `handleItemCompleted` had no case for `fileChange`, `webSearch`,+ * or `collabAgentToolCall`, so `outstandingToolUses` (tracked by the manager+ * via these `ParsedEvent`s) would permanently increment on the first such+ * item of a turn and never come back down.+ */+import { describe, it, expect } from "vitest";+import { CodexEventNormalizer } from "./codexEventNormalizer";++function notify(method: string, params: unknown): string {+ return JSON.stringify({ jsonrpc: "2.0", method, params });+}++describe("CodexEventNormalizer — tool_call/tool_output symmetry", () => {+ it("fileChange: item/started then item/completed emits tool_call then tool_output", () => {+ const n = new CodexEventNormalizer();+ const started = n.normalizeLine(notify("item/started", { item: { type: "fileChange" } }));+ expect(started).toEqual([{ kind: "tool_call", name: "file_change", input: { type: "fileChange" } }]);++ const completed = n.normalizeLine(notify("item/completed", { item: { type: "fileChange" } }));+ expect(completed).toEqual([{ kind: "tool_output", name: "file_change" }]);+ });++ it("webSearch: item/started then item/completed emits tool_call then tool_output", () => {+ const n = new CodexEventNormalizer();+ const started = n.normalizeLine(notify("item/started", { item: { type: "webSearch" } }));+ expect(started).toEqual([{ kind: "tool_call", name: "web_search", input: { type: "webSearch" } }]);++ const completed = n.normalizeLine(notify("item/completed", { item: { type: "webSearch" } }));+ expect(completed).toEqual([{ kind: "tool_output", name: "web_search" }]);+ });++ it("collabAgentToolCall: item/started then item/completed emits tool_call then tool_output", () => {+ const n = new CodexEventNormalizer();+ const started = n.normalizeLine(notify("item/started", { item: { type: "collabAgentToolCall" } }));+ expect(started).toEqual([{ kind: "tool_call", name: "collab_tool_call", input: { type: "collabAgentToolCall" } }]);++ const completed = n.normalizeLine(notify("item/completed", { item: { type: "collabAgentToolCall" } }));+ expect(completed).toEqual([{ kind: "tool_output", name: "collab_tool_call" }]);+ });++ it("commandExecution: item/started then item/completed still pairs correctly (regression — 9b removed markProgress from this handler)", () => {+ const n = new CodexEventNormalizer();+ const started = n.normalizeLine(notify("item/started", { item: { type: "commandExecution" } }));+ expect(started).toEqual([{ kind: "tool_call", name: "shell", input: { type: "commandExecution" } }]);++ const completed = n.normalizeLine(notify("item/completed", { item: { type: "commandExecution" } }));+ expect(completed).toEqual([{ kind: "tool_output", name: "shell" }]);+ });++ it("mcpToolCall: item/started then item/completed still pairs correctly (regression — 9b removed markProgress from this handler)", () => {+ const n = new CodexEventNormalizer();+ const started = n.normalizeLine(notify("item/started", { item: { type: "mcpToolCall", name: "search" } }));+ expect(started).toEqual([+ { kind: "tool_call", name: "mcp_search", input: { type: "mcpToolCall", name: "search" } },+ ]);++ const completed = n.normalizeLine(notify("item/completed", { item: { type: "mcpToolCall", name: "search" } }));+ expect(completed).toEqual([{ kind: "tool_output", name: "mcp_search" }]);+ });++ it("does not expose canSteerBusy or a turnState field (dead/redundant driver-level gate must not silently reappear)", () => {+ const n = new CodexEventNormalizer();+ expect((n as unknown as { canSteerBusy?: unknown }).canSteerBusy).toBeUndefined();+ expect((n as unknown as { turnState?: unknown }).turnState).toBeUndefined();+ });+});diff --git a/src/daemon/src/drivers/codexEventNormalizer.ts b/src/daemon/src/drivers/codexEventNormalizer.tsindex 521a8e663..2e7e8c996 100644--- a/src/daemon/src/drivers/codexEventNormalizer.ts+++ b/src/daemon/src/drivers/codexEventNormalizer.ts@@ -13,22 +13,14 @@*/import type { ParsedEvent } from "../types.js";import { mapCodexTelemetry } from "./codexTelemetrySidecar.js";-import { RuntimeTurnState } from "../runtime/turnState.js";export class CodexEventNormalizer {private threadId: string | null = null;- /** Tracks turn/tool boundaries so the driver can answer `canSteerBusy`. */- readonly turnState = new RuntimeTurnState();get currentSessionId(): string | null {return this.threadId;}- /** Safe to inject a busy (steering) message right now? */- get canSteerBusy(): boolean {- return this.turnState.canSteerBusy;- }-adoptThreadId(threadId: string | null): void {this.threadId = threadId;}@@ -63,16 +55,13 @@ export class CodexEventNormalizer {return this.threadId ? [{ kind: "session_init", sessionId: this.threadId }] : [];case "turn/started":- this.turnState.markTurnStarted(params?.turnId ?? this.threadId ?? undefined);return [{ kind: "thinking", text: "" }];case "item/reasoning/textDelta":case "item/reasoning/summaryTextDelta":- this.turnState.markProgress();return [{ kind: "thinking", text: params?.delta ?? "" }];case "item/agentMessage/delta":- this.turnState.markProgress();return [{ kind: "text", text: params?.delta ?? "" }];case "item/started":@@ -83,7 +72,6 @@ export class CodexEventNormalizer {// A raw response item is a liveness signal (no user-visible content).case "rawResponseItem/completed":- this.turnState.markProgress();return [{ kind: "internal_progress", source: "codex_raw_item", itemType: "rawResponseItem" }];// Non-fatal diagnostics surfaced by Codex.@@ -96,7 +84,6 @@ export class CodexEventNormalizer {];case "turn/completed":- this.turnState.markTurnCompleted();if (params?.status === "failed") return [{ kind: "error", message: "Codex turn failed" }];if (params?.status === "interrupted") {return [{ kind: "error", message: "Codex turn interrupted" }, { kind: "turn_end", sessionId: this.threadId ?? undefined }];@@ -117,10 +104,6 @@ export class CodexEventNormalizer {private handleItemStarted(params: any): ParsedEvent[] {const t = params?.item?.type ?? params?.type;- // A started tool item closes the steering gate until it completes.- if (t === "commandExecution" || t === "fileChange" || t === "mcpToolCall" || t === "webSearch" || t === "collabAgentToolCall") {- this.turnState.markToolBoundary();- }switch (t) {case "commandExecution":return [{ kind: "tool_call", name: "shell", input: params?.item }];@@ -143,10 +126,6 @@ export class CodexEventNormalizer {private handleItemCompleted(params: any): ParsedEvent[] {const t = params?.item?.type ?? params?.type;- // A completed tool item is a boundary that reopens steering.- if (t === "commandExecution" || t === "mcpToolCall") {- this.turnState.markProgress();- }switch (t) {case "commandExecution":return [{ kind: "tool_output", name: "shell" }];@@ -154,8 +133,14 @@ export class CodexEventNormalizer {return [{ kind: "compaction_finished" }];case "exitedReviewMode":return [{ kind: "review_finished" }];+ case "fileChange":+ return [{ kind: "tool_output", name: "file_change" }];case "mcpToolCall":return [{ kind: "tool_output", name: `mcp_${params?.item?.name ?? "tool"}` }];+ case "webSearch":+ return [{ kind: "tool_output", name: "web_search" }];+ case "collabAgentToolCall":+ return [{ kind: "tool_output", name: "collab_tool_call" }];case "agentMessage":return [{ kind: "text", text: params?.item?.text ?? "" }];case "reasoning":diff --git a/src/daemon/src/drivers/systemPrompt.test.ts b/src/daemon/src/drivers/systemPrompt.test.tsindex fedee3324..4ae95309e 100644--- a/src/daemon/src/drivers/systemPrompt.test.ts+++ b/src/daemon/src/drivers/systemPrompt.test.ts@@ -35,28 +35,37 @@ describe("buildCliSystemPrompt", () => {});it("injects agentName and agentHandle into the prompt only when set", () => {+ // Discriminator deliberately avoids "4821" — the messaging section's own+ // illustrative example (`@gustavo#4821`) is fixed doc prose, unrelated to+ // `config.agentHandle`, and would collide with a `not.toContain` check+ // below if reused here.const withIdentity = buildCliSystemPrompt(- { ...baseConfig, agentName: "Nova", agentHandle: "nova" },+ { ...baseConfig, agentName: "Nova", agentHandle: "@nova#7392" },{ lifecycleKind: "persistent" },);expect(withIdentity).toContain("Nova");- expect(withIdentity).toContain("nova");+ // Assert on the contract (config.agentHandle's exact value round-trips+ // verbatim), not on the surrounding prose — see this file's philosophy+ // note above.+ expect(withIdentity).toContain("@nova#7392");const without = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });expect(without).not.toContain("Nova");+ expect(without).not.toContain("#7392");});- it("includes a Role section with config.description's exact text only when it's set", () => {+ it("includes a Role subsection (nested under Identity) with config.description's exact text only when it's set", () => {const withRole = buildCliSystemPrompt({ ...baseConfig, description: "You are the onboarding assistant." },{ lifecycleKind: "persistent" },);expect(withRole).toContain("You are the onboarding assistant.");- expect(withRole).toContain("## Role");+ expect(withRole).toContain("### Role");+ expect(withRole).toContain("## Identity");const withoutRole = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });expect(withoutRole).not.toContain("You are the onboarding assistant.");- expect(withoutRole).not.toContain("## Role");+ expect(withoutRole).not.toContain("### Role");});it("never parameterizes the CLI/product identity away (Alook is the product, not a configurable host)", () => {diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.tsindex 260ec1c4f..5394c1cc8 100644--- a/src/daemon/src/drivers/systemPrompt.ts+++ b/src/daemon/src/drivers/systemPrompt.ts@@ -3,7 +3,10 @@** Every CLI driver's `buildSystemPrompt` funnels through here. The prompt is* assembled from a fixed sequence of sections:- * 1. Identity line+ * 1. Identity (intro line + name + handle explanation + Role, from+ * `config.description` when set — all merged into one section so an+ * agent's "who am I" reads as a single block up front instead of being+ * split between a bare intro line and a Role section at the very end)* 2. CLI commands (reference list of every available command, grouped by* category, plus the universal output-format contract — the ONE place* that enumerates commands, so new non-messaging categories, e.g. tasks@@ -18,7 +21,6 @@* 7. Channel awareness* 8. Workspace & memory* 9. Message notifications (auto-generated from `lifecycleKind`)- * 10. Role (from `config.description`, when set)** Alook is the product — there's no other host to be neutral toward, so the* CLI name (`alook`) and platform label (`Alook`) are hardcoded, not@@ -50,6 +52,42 @@ export interface SystemPromptOpts {/* Section builders *//* ------------------------------------------------------------------ */+/**+ * Intro line + name + handle explanation + Role (from `config.description`),+ * merged into one "who am I" section. Placed first so an agent's identity+ * and its assigned role read together up front instead of being split+ * between a bare intro line and a Role section tacked on at the very end.+ */+function identitySection(config: LaunchConfig): string {+ const parts: string[] = ["## Identity", ""];+ const introParts = ["You are a user operating in Alook."];+ if (config.agentName) introParts.push(`Your name is ${config.agentName}.`);+ parts.push(introParts.join(" "));++ if (config.agentHandle) {+ parts.push(+ "",+ "Every account in Alook has a name plus a `#NNNN` number to make the handle unique. " ++ `Your handle is \`${config.agentHandle}\`. ` ++ "Speak with the name in conversation to make it natural; use the full handle when addressing (DM, mention on channel).",+ );+ }++ if (config.description) {+ parts.push(+ "",+ "### Role",+ "",+ config.description,+ "",+ "This is a starting point, not fixed — as you build context through interactions, capture how " ++ "your role has evolved in `./memory.md` (the Role text above isn't something you can edit directly).",+ );+ }++ return parts.join("\n");+}+/*** Reference list of every command `alook` exposes, grouped by category, plus* the universal output-format contract every command shares. This is the ONE@@ -101,11 +139,11 @@ function messagingSection(): string {"","Channels and messages are addressed with path-style refs:","",- "| Shape | Meaning |",+ "| Channel Ref | Meaning |","|---|---|","| `/<server>/<channel>` | A channel in a server |","| `/<server>/<channel>/#N` | Thread rooted at message #N |",- "| `/.dm/<peer>` | A DM with another user/agent |",+ "| `/.dm/<peer>` | A DM with another user/agent (peer = handle, `name#0042`) |","| `/.dm/<peer>#N` | Message #N in a DM |","| `/.dm/<peer>/#N` | Thread in a DM |","",@@ -117,13 +155,13 @@ function messagingSection(): string {`When you call \`${CLI} inbox pull\`, you receive messages as JSON objects:`,"","```json",- '{"seq": "#3", "channel": "/demo/general", "sender": "@gustavo", "content": {"text": "hello"}, "time": "2026-06-01T12:00:00Z"}',+ '{"seq": "#3", "channel": "/demo/general", "sender": "@gustavo#4821", "content": {"text": "hello"}, "time": "2026-06-01T12:00:00Z"}',"```","","Fields:","- `seq` — per-channel sequence number (`#N`). Identifies a message within its channel.","- `channel` — the path ref of the channel/DM. Reuse as `--target` when replying.",- "- `sender` — `@handle` of who sent it.",+ "- `sender` — handle (`@name#0042`) of who sent it.","- `content.text` — the message body.","- `time` — ISO-8601 timestamp.",].join("\n");@@ -266,12 +304,8 @@ function messageNotificationSection(lifecycleKind: SystemPromptOpts["lifecycleKi* and notification handling. The only per-driver input is `lifecycleKind`.*/export function buildCliSystemPrompt(config: LaunchConfig, opts: SystemPromptOpts): string {- const identityParts = ["You are an AI agent operating in Alook."];- if (config.agentName) identityParts.push(`Your name is ${config.agentName}.`);- if (config.agentHandle) identityParts.push(`Your handle is \`${config.agentHandle}\` (others use this to @mention you).`);-const sections: string[] = [- identityParts.join(" "),+ identitySection(config),cliCommandsSection(),messagingSection(),criticalRulesSection(),@@ -282,14 +316,5 @@ export function buildCliSystemPrompt(config: LaunchConfig, opts: SystemPromptOptmessageNotificationSection(opts.lifecycleKind),];- if (config.description) {- sections.push(- "## Role\n" +- config.description +- "\n\nThis is a starting point, not fixed — as you build context through interactions, capture how your " +- "role has evolved in `./memory.md` (the Role text above isn't something you can edit directly).",- );- }-return sections.filter((s) => s && s.length > 0).join("\n\n");}diff --git a/src/daemon/src/manager/managerCapabilityContract.test.ts b/src/daemon/src/manager/managerCapabilityContract.test.tsindex 50daedf3f..65fa69337 100644--- a/src/daemon/src/manager/managerCapabilityContract.test.ts+++ b/src/daemon/src/manager/managerCapabilityContract.test.ts@@ -9,7 +9,7 @@* `sessionFactory`, bypassing real process/SDK spawning) to assert the* orchestration contract each profile is supposed to get.*- * Why this exists: `PiDriver` and `CodexDriver` both declare+ * Why this exists: `PiDriver` and `KimiDriver` both declare* `{kind: "persistent", stdin: "direct", inFlightWake: "steer"}` +* `busyDeliveryMode: "direct"`. A real production bug shipped because* `SdkManagedSession.start()` (Pi's session adapter) used to await the@@ -21,13 +21,16 @@* That fix lives in `sdkManagedSession.ts`/`pi.ts` and is regression-tested* in `sdkManagedSession.test.ts` — but that only protects Pi. This file* protects the *manager's* half of the contract for EVERY driver sharing- * that capability profile today (Pi, Codex) and any future one, without+ * that capability profile today (Pi and Kimi declare direct/steer; Codex+ * joins Claude in the gated/queue bucket — see+ * plans/wire-gated-busy-steering-daemon.md) and any future one, without* needing driver-specific test plumbing.*/import { describe, it, expect } from "vitest";import { AgentProcessManager, type ManagedSession, type SessionFactory } from "./managerRuntime.js";import { listRuntimeIds, getDriver } from "../drivers/index.js";import type { Driver, LaunchContext } from "../types.js";+import type { Logger } from "../logger.js";interface CapabilityProfile {lifecycleKind: "persistent" | "per_turn";@@ -120,7 +123,28 @@ function fakeSession(): FakeSession {return s;}-function makeManager(driver: Driver, session: FakeSession) {+/** Stub logger — records calls per level for assertions (copied from+ * `managerRuntime.test.ts`; kept local so these two test files don't need to+ * import from each other). */+function stubLogger(): Logger & { calls: Record<"debug" | "info" | "warn" | "error", Array<[string, unknown[]]>> } {+ const calls: Record<"debug" | "info" | "warn" | "error", Array<[string, unknown[]]>> = {+ debug: [],+ info: [],+ warn: [],+ error: [],+ };+ const logger = {+ calls,+ debug: (m: string, ...d: unknown[]) => calls.debug.push([m, d]),+ info: (m: string, ...d: unknown[]) => calls.info.push([m, d]),+ warn: (m: string, ...d: unknown[]) => calls.warn.push([m, d]),+ error: (m: string, ...d: unknown[]) => calls.error.push([m, d]),+ child: () => logger,+ };+ return logger;+}++function makeManager(driver: Driver, session: FakeSession, logger?: Logger) {const factory: SessionFactory = () => session;const mgr = new AgentProcessManager({driverFor: () => driver,@@ -131,6 +155,7 @@ function makeManager(driver: Driver, session: FakeSession) {config: {} as LaunchContext["config"],}),sessionFactory: factory,+ logger,});mgr.register("a1");return mgr;@@ -194,45 +219,92 @@ describe("AgentProcessManager capability contract — persistent/gated/queue runconst label = bucket.driverIds.join(", ");/**- * KNOWN GAP — not the bug this plan set out to fix, but found while- * writing a contract test that assumed `lifecycle.stdin: "gated"` /- * `inFlightWake: "queue"` changed the manager's delivery timing the way- * Claude's own doc comment implies ("held until a safe boundary — see- * runtime/apmStateMachine and runtime/turnState"). It doesn't:- * `managerPolicy.ts::onWake`'s "running" branch only checks- * `lifecycleKind === "persistent" && supportsStdinNotification` — it- * never reads `inFlightWake` or `busyDeliveryMode` — so a gated driver's- * mid-turn wake is sent exactly as immediately as a direct/steer one.- * `ChildProcessRuntimeSession.send()` also writes to stdin unconditionally,- * regardless of mode. `apmStateMachine.ts`/`turnState.ts` exist in this- * package (exported from `index.ts`) but have ZERO call sites in- * `managerRuntime.ts`/`runtimeSession.ts` — they're a real, tested reducer- * that's wired up in the OTHER daemon implementation- * (`src/cli/daemon/session-runner.ts` branches on `busyMode === "gated"`- * and drives `apmStateMachine`/`turnState` for real) but were never- * connected here. This test asserts what ACTUALLY happens today (not- * what the naming implies) precisely so it breaks loudly — instead of- * silently drifting further — if/when gating is either wired up for- * real or intentionally dropped from the type model.+ * FIXED (see plans/wire-gated-busy-steering-daemon.md) — a mid-turn wake+ * on a gated driver is HELD, not sent immediately. `managerPolicy.ts`'s+ * `onWake` running branch now checks `busyDeliveryMode === "gated" &&+ * turnActive` and emits `gated_hold` instead of draining the inbox. The+ * message flows to stdin only once a safe boundary is reached — here, a+ * `tool_call`→`tool_output` pair closing the last outstanding tool use —+ * and only once a `session_init` runtime event has landed (`hasSession`+ * is a `reduceApmGatedFlushReadiness` prerequisite). This test drives+ * that whole path through the public `AgentProcessManager` + a fake+ * session (not just the pure reducer), proving the executor's+ * `runtime_signal` forwarding AND the `gated_hold` logging path (via an+ * injected logger spy) both work end to end.*/- it(`[${label}] TODAY sends a mid-turn wake immediately (mode:"busy"), identically to a direct/steer runtime — "gated" delivery is declared but not wired up in this package's ManagedSession path`, async () => {+ it(`[${label}] holds a mid-turn wake until a safe boundary (session_init, then tool_call/tool_output) instead of sending immediately`, async () => {const session = fakeSession();- const mgr = makeManager(bucket.sample, session);+ const logger = stubLogger();+ const mgr = makeManager(bucket.sample, session, logger);mgr.deliver("a1", { seq: 1, text: "first" });session.startResolver?.();await Promise.resolve();+ session.fire("runtime_event", { kind: "session_init", sessionId: "sess_1" });mgr.deliver("a1", { seq: 2, text: "mid-turn wake" });+ // Held, not sent — and a gated_hold was logged for the mid-turn wake.+ expect(session.sendCalls).toEqual([]);+ expect(+ logger.calls.info.some(+ ([m, d]) => m === "gated busy message held" && (d[0] as any).reason === "mid_turn_wake",+ ),+ ).toBe(true);++ // A tool_call/tool_output pair is the next safe boundary — the+ // single outstanding tool closes, readiness passes, the held message+ // flushes as mode:"busy".+ session.fire("runtime_event", { kind: "tool_call", name: "shell", input: {} });+ session.fire("runtime_event", { kind: "tool_output", name: "shell" });+expect(session.sendCalls).toEqual([{ text: "mid-turn wake", mode: "busy" }]);});}});+describe("AgentProcessManager capability contract — Codex fileChange tool_call/tool_output fix (§9c)", () => {+ /**+ * Proves 9c's fix end to end, not just its `ParsedEvent` shape (that part+ * is covered by `codexEventNormalizer.test.ts`): before the fix,+ * `handleItemCompleted` had no `fileChange` case, so a `fileChange`+ * `tool_call` would open `outstandingToolUses` and it would never close —+ * permanently blocking mid-turn flushes for the rest of that turn. Uses+ * the real `CodexDriver` capability profile via the same fake-session+ * harness as the gated/queue bucket tests above.+ */+ it("a fileChange tool_call immediately followed by its tool_output closes outstandingToolUses back to 0 and unblocks a held message", async () => {+ const codexDriver = getDriver("codex");+ const session = fakeSession();+ const mgr = makeManager(codexDriver, session);++ mgr.deliver("a1", { seq: 1, text: "first" });+ session.startResolver?.();+ await Promise.resolve();+ session.fire("runtime_event", { kind: "session_init", sessionId: "sess_1" });++ mgr.deliver("a1", { seq: 2, text: "mid-turn wake" });+ expect(session.sendCalls).toEqual([]); // held — gated mid-turn wake++ session.fire("runtime_event", { kind: "tool_call", name: "file_change", input: {} });+ session.fire("runtime_event", { kind: "tool_output", name: "file_change" });++ expect(session.sendCalls).toEqual([{ text: "mid-turn wake", mode: "busy" }]);+ });+});+describe("AgentProcessManager capability contract — bucket sanity", () => {it("the registered drivers still contain at least one direct/steer profile and one gated/queue profile (catches an accidental capability drift silently disabling the contracts above)", () => {expect(directSteerBuckets.length).toBeGreaterThan(0);expect(gatedQueueBuckets.length).toBeGreaterThan(0);});-});\ No newline at end of file++ it("the gated/queue bucket contains BOTH claude and codex, sharing one identical profile (see plans/wire-gated-busy-steering-daemon.md §9a) — catches a future capability drift between the two silently splitting the bucket", () => {+ expect(gatedQueueBuckets).toHaveLength(1);+ expect(gatedQueueBuckets[0]!.driverIds.slice().sort()).toEqual(["claude", "codex"]);+ });++ it("the direct/steer bucket contains exactly pi and kimi — codex moved to gated/queue, NOT just pi alone", () => {+ expect(directSteerBuckets.flatMap((b) => b.driverIds).sort()).toEqual(["kimi", "pi"]);+ });+});diff --git a/src/daemon/src/manager/managerPolicy.test.ts b/src/daemon/src/manager/managerPolicy.test.tsindex 535d2d280..58e2b47eb 100644--- a/src/daemon/src/manager/managerPolicy.test.ts+++ b/src/daemon/src/manager/managerPolicy.test.ts@@ -6,11 +6,17 @@ import {type AgentRuntimeCaps,} from "./managerPolicy";-const PERSISTENT_STEERABLE: AgentRuntimeCaps = {+const PERSISTENT_GATED: AgentRuntimeCaps = {lifecycleKind: "persistent",supportsStdinNotification: true,busyDeliveryMode: "gated",};+/** Matches Pi/Kimi — NOT Codex, which this plan moves to "gated". */+const PERSISTENT_DIRECT: AgentRuntimeCaps = {+ lifecycleKind: "persistent",+ supportsStdinNotification: true,+ busyDeliveryMode: "direct",+};const PER_TURN: AgentRuntimeCaps = {lifecycleKind: "per_turn",supportsStdinNotification: false,@@ -24,7 +30,7 @@ function register(state: ManagerState, agentId: string, caps: AgentRuntimeCaps):describe("reduceManager — single-flight spawn", () => {it("first wake from idle spawns; second wake while starting does NOT spawn again", () => {let s = createInitialManagerState();- s = register(s, "a", PERSISTENT_STEERABLE);+ s = register(s, "a", PERSISTENT_GATED);const r1 = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 });expect(r1.effects).toEqual([{ type: "spawn", agentId: "a", prompt: "m1", resumeSessionId: null }]);@@ -45,21 +51,183 @@ describe("reduceManager — single-flight spawn", () => {});describe("reduceManager — steering a running persistent agent", () => {- it("wake while running+turnActive steers as busy", () => {+ it("gated: wake while running+turnActive is HELD, not steered — message stays in inbox", () => {let s = createInitialManagerState();- s = register(s, "a", PERSISTENT_STEERABLE);+ s = register(s, "a", PERSISTENT_GATED);+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state; // running, turnActive++ const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 3 });+ expect(r.effects).toEqual([+ { type: "gated_hold", agentId: "a", reason: "mid_turn_wake", blockedReason: "idle", recentEvents: [] },+ ]);+ // Held, not dropped.+ expect(r.state.agents.a.inbox.map((m) => m.text)).toEqual(["m2"]);+ });++ it("direct (Pi/Kimi profile): wake while running+turnActive still steers as busy immediately — regression guard, gating must not affect non-gated drivers", () => {+ let s = createInitialManagerState();+ s = register(s, "a", PERSISTENT_DIRECT);s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state; // running, turnActiveconst r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 3 });expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "m2", mode: "busy" }]);+ // Never held for a direct driver.+ expect(r.effects.some((e) => e.type === "gated_hold")).toBe(false);+ });++ it("gated: wake while running but turnActive=false steers as idle immediately — unchanged from today", () => {+ let s = createInitialManagerState();+ s = register(s, "a", PERSISTENT_GATED);+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;+ s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 3 }).state; // running, turnActive=false, idle++ const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 4 });+ expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "m2", mode: "idle" }]);+ });+});++describe("reduceManager — none-driver (per-turn) mid-turn wake — regression", () => {+ it("wake while running (per-turn, mid-turn) stays queued for the next spawn; no send", () => {+ let s = createInitialManagerState();+ s = register(s, "a", PER_TURN);+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state; // running, turnActive++ const r = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m2" }, nowMs: 3 });+ expect(r.effects).toEqual([]);+ expect(r.state.agents.a.inbox.map((m) => m.text)).toEqual(["m2"]);+ });+});++describe("reduceManager — onRuntimeSignal (gated tool/compaction/review boundaries)", () => {+ /** Register + wake + spawn + session_init — a running, turnActive, gated agent with a known session. */+ function gatedRunningWithSession(): ManagerState {+ let s = createInitialManagerState();+ s = register(s, "a", PERSISTENT_GATED);+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;+ s = reduceManager(s, { type: "session", agentId: "a", sessionId: "sess_1" }).state;+ return s;+ }++ /** Same, but WITHOUT a session_init — for the missing_session test. */+ function gatedRunningNoSession(): ManagerState {+ let s = createInitialManagerState();+ s = register(s, "a", PERSISTENT_GATED);+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;+ return s;+ }++ it("tool_call then tool_output (single outstanding tool) flushes a held message as busy, draining the inbox", () => {+ let s = gatedRunningWithSession();+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 3 }).state; // held (gated_hold)++ s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_call", nowMs: 4 }).state;+ const r = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_output", nowMs: 5 });++ expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "held", mode: "busy" }]);+ expect(r.state.agents.a.inbox).toEqual([]);+ });++ it("tool_call/tool_output boundary WITHOUT a prior session_init is held with blockedReason: missing_session", () => {+ let s = gatedRunningNoSession();+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 3 }).state;++ s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_call", nowMs: 4 }).state;+ const r = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_output", nowMs: 5 });++ expect(r.effects).toEqual([+ { type: "gated_hold", agentId: "a", reason: "tool_batch_complete", blockedReason: "missing_session", recentEvents: expect.any(Array) },+ ]);+ expect(r.state.agents.a.inbox.map((m) => m.text)).toEqual(["held"]);+ });++ it("two nested tool_calls, only one tool_output closes (outstandingToolUses stays > 0) — flush is attempted but blocked with outstanding_tool_uses, not missing_session", () => {+ let s = gatedRunningWithSession();+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 3 }).state;++ s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_call", nowMs: 4 }).state;+ s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_call", nowMs: 5 }).state; // outstandingToolUses = 2+ const r = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_output", nowMs: 6 }); // -> 1, still > 0++ expect(r.effects).toEqual([+ { type: "gated_hold", agentId: "a", reason: "tool_batch_complete", blockedReason: "outstanding_tool_uses", recentEvents: expect.any(Array) },+ ]);+ expect(r.state.agents.a.apm.outstandingToolUses).toBe(1);+ });++ it("compaction_started then compaction_finished flushes a held message on compaction_finished", () => {+ let s = gatedRunningWithSession();+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 3 }).state;++ s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "compaction_started", nowMs: 4 }).state;+ expect(s.agents.a.apm.compacting).toBe(true);+ const r = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "compaction_finished", nowMs: 5 });++ expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "held", mode: "busy" }]);+ });++ it("review_started then review_finished flushes a held message on review_finished", () => {+ let s = gatedRunningWithSession();+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 3 }).state;++ s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "review_started", nowMs: 4 }).state;+ expect(s.agents.a.apm.reviewing).toBe(true);+ const r = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "review_finished", nowMs: 5 });++ expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "held", mode: "busy" }]);+ });++ it("an error disables tool-boundary flushing until the next turn_end — a later tool_output boundary is held with blockedReason: tool_boundary_flush_disabled, not missing_session", () => {+ let s = gatedRunningWithSession();+ s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "error", nowMs: 3 }).state;+ expect(s.agents.a.apm.toolBoundaryFlushDisabled).toBe(true);++ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 4 }).state;+ s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_call", nowMs: 5 }).state;+ const r = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_output", nowMs: 6 });++ expect(r.effects).toEqual([+ { type: "gated_hold", agentId: "a", reason: "tool_batch_complete", blockedReason: "tool_boundary_flush_disabled", recentEvents: expect.any(Array) },+ ]);+ });++ it("turn_end while a message is still held flushes it as mode:idle — unchanged, independent of hasSession/phase", () => {+ let s = gatedRunningNoSession(); // no session_init at all+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 3 }).state;++ const r = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 4 });+ expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "held", mode: "idle" }]);+ });++ it("turn_end resets the gated phase — a stale compacting flag from the PRIOR turn does not block a flush in the NEXT turn", () => {+ let s = gatedRunningWithSession();++ // Turn 1: enter compacting, never finish it.+ s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "compaction_started", nowMs: 3 }).state;+ expect(s.agents.a.apm.compacting).toBe(true);+ s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 4 }).state;++ // Turn 2: session_id persists across turn_end; re-spawn for the new turn.+ s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 5 }).state;+ s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "held" }, nowMs: 6 }).state;+ s = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_call", nowMs: 7 }).state;+ const r = reduceManager(s, { type: "runtime_signal", agentId: "a", kind: "tool_output", nowMs: 8 });++ // If `compacting` had leaked across turn_end, this would be blocked with+ // blockedReason: "compacting" instead of flushing.+ expect(r.effects).toEqual([{ type: "send", agentId: "a", text: "held", mode: "busy" }]);});});describe("reduceManager — turn_end behavior", () => {it("persistent with queued messages delivers them as a fresh idle turn", () => {let s = createInitialManagerState();- s = register(s, "a", PERSISTENT_STEERABLE);+ s = register(s, "a", PERSISTENT_GATED);s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;// queue while running but pretend not steered: directly push via wake after turn?@@ -73,7 +241,7 @@ describe("reduceManager — turn_end behavior", () => {it("persistent with empty inbox goes idle and starts the idle clock", () => {let s = createInitialManagerState();- s = register(s, "a", PERSISTENT_STEERABLE);+ s = register(s, "a", PERSISTENT_GATED);s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 1 }).state;s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 2 }).state;@@ -141,7 +309,7 @@ describe("reduceManager — tick: stall + idle hibernation", () => {it("stops a persistent agent that sat idle past the idle timeout (sessionId preserved)", () => {let s = createInitialManagerState(100_000, 100); // idleTimeoutMs = 100- s = register(s, "a", PERSISTENT_STEERABLE);+ s = register(s, "a", PERSISTENT_GATED);s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;s = reduceManager(s, { type: "session", agentId: "a", sessionId: "sess-1" }).state;@@ -154,7 +322,7 @@ describe("reduceManager — tick: stall + idle hibernation", () => {it("idle timeout of 0 disables hibernation", () => {let s = createInitialManagerState(100_000, 0);- s = register(s, "a", PERSISTENT_STEERABLE);+ s = register(s, "a", PERSISTENT_GATED);s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;s = reduceManager(s, { type: "spawned", agentId: "a", nowMs: 0 }).state;s = reduceManager(s, { type: "turn_end", agentId: "a", nowMs: 0 }).state;diff --git a/src/daemon/src/manager/managerPolicy.ts b/src/daemon/src/manager/managerPolicy.tsindex 337916146..61a431122 100644--- a/src/daemon/src/manager/managerPolicy.ts+++ b/src/daemon/src/manager/managerPolicy.ts@@ -19,10 +19,21 @@* threshold, terminate it for restart.** Per-runtime delivery nuance (gated steering, etc.) is delegated to the- * existing `apmStateMachine` / `RuntimeTurnState` reducers; this layer is the- * higher-level lifecycle/queue orchestrator above them.+ * existing `apmStateMachine` reducers (read-only; see `onRuntimeSignal` below)+ * — this layer is the higher-level lifecycle/queue orchestrator above them.+ * See plans/wire-gated-busy-steering-daemon.md for how gating is wired up.*/import type { BusyDeliveryMode, DriverLifecycle } from "../types.js";+import {+ type ApmGatedSteeringState,+ createInitialApmGatedSteeringState,+ reduceApmGatedToolUse,+ reduceApmGatedCompaction,+ reduceApmGatedReview,+ reduceApmGatedError,+ reduceApmGatedFlushReadiness,+ reduceApmGatedRecentEvent,+} from "../runtime/apmStateMachine.js";export type AgentStatus = "idle" | "starting" | "running" | "stopping";@@ -51,6 +62,13 @@ export interface AgentState {lastProgressAt: number;/** ms timestamp since which the agent has been idle (running, no turn, empty inbox); null if not idle. */idleSince: number | null;+ /**+ * Coarse gated-steering phase (tool/compaction/review boundaries). Only+ * meaningfully consulted when `caps.busyDeliveryMode === "gated"`; kept on+ * every agent (harmless/unused otherwise) so the reducer set never needs a+ * null-check.+ */+ apm: ApmGatedSteeringState;}export interface ManagerState {@@ -77,13 +95,26 @@ export type ManagerEvent =| { type: "progress"; agentId: string; nowMs: number }| { type: "turn_end"; agentId: string; nowMs: number }| { type: "exit"; agentId: string }- | { type: "tick"; nowMs: number };+ | { type: "tick"; nowMs: number }+ /**+ * Generic passthrough of a `ParsedEvent`'s `kind` string, forwarded for+ * EVERY runtime event (not just the ones the reducer acts on) so the+ * gated-steering diagnostics ring buffer (`reduceApmGatedRecentEvent`) sees+ * a complete history. See `onRuntimeSignal`.+ */+ | { type: "runtime_signal"; agentId: string; kind: string; nowMs: number };export type ManagerEffect =| { type: "spawn"; agentId: string; prompt: string; resumeSessionId: string | null }| { type: "send"; agentId: string; text: string; mode: "busy" | "idle" }| { type: "stop"; agentId: string; reason: string }- | { type: "terminate_stalled"; agentId: string };+ | { type: "terminate_stalled"; agentId: string }+ /**+ * Pure observability: a gated agent has a non-empty inbox but nothing was+ * actually sent — either a mid-turn wake was held, or a boundary flush+ * attempt was still blocked. Never emitted for `direct`/`none` drivers.+ */+ | { type: "gated_hold"; agentId: string; reason: string; blockedReason: string | null; recentEvents: string[] };/** Default thresholds (ms). */export const DEFAULT_STALE_THRESHOLD_MS = 120_000;@@ -139,6 +170,9 @@ export function reduceManager(state: ManagerState, event: ManagerEvent): ReduceRcase "tick":return onTick(state, event.nowMs);++ case "runtime_signal":+ return onRuntimeSignal(state, event.agentId, event.kind);}}@@ -171,6 +205,22 @@ function onWake(state: ManagerState, agentId: string, message: AgentMsg): Reduceif (agent.status === "running") {// Persistent + can take stdin ⇒ steer/deliver into the live process.if (agent.caps.lifecycleKind === "persistent" && agent.caps.supportsStdinNotification) {+ // Gated + mid-turn: a raw stdin write right now could collide with an+ // in-flight tool call / signed thinking block / compaction / review.+ // The message is already enqueued above — hold instead of draining it;+ // `onRuntimeSignal` flushes it at the next safe boundary.+ const isGatedMidTurn = agent.caps.busyDeliveryMode === "gated" && agent.turnActive;+ if (isGatedMidTurn) {+ return commit(state, agent, [+ {+ type: "gated_hold",+ agentId,+ reason: "mid_turn_wake",+ blockedReason: agent.apm.phase,+ recentEvents: agent.apm.recentEvents,+ },+ ]);+ }const text = drainInboxToPrompt(agent);const mode = agent.turnActive ? "busy" : "idle";return commit(state, agent, [{ type: "send", agentId, text, mode }]);@@ -189,6 +239,10 @@ function onTurnEnd(state: ManagerState, agentId: string, nowMs: number): ReduceRconst agent = clone(existing);agent.turnActive = false;agent.lastProgressAt = nowMs;+ // Fresh turn ⇒ fresh gated phase; prevents a stale compacting/reviewing/+ // outstandingToolUses flag from one turn silently blocking a flush in the+ // next turn.+ agent.apm = createInitialApmGatedSteeringState();// Per-turn runtimes exit on their own; the process will emit "exit".if (agent.caps.lifecycleKind === "per_turn") {@@ -207,6 +261,95 @@ function onTurnEnd(state: ManagerState, agentId: string, nowMs: number): ReduceRreturn commit(state, agent, []);}+/**+ * Handles one forwarded `ParsedEvent.kind` for gated-steering phase tracking+ * and boundary flush attempts. Only meaningfully acts when the agent is+ * `running`, `turnActive`, and declares `busyDeliveryMode: "gated"` —+ * otherwise it's a no-op (still records `recentEvents` for diagnostics via+ * `reduceApmGatedRecentEvent`, cheap and harmless).+ *+ * Pinned execution order per branch (deliberately different from+ * `session-runner.ts`, which calls `reduceApmGatedRecentEvent` first — here+ * it runs last so the ring buffer reflects the phase actually reached, not+ * the incoming phase):+ * 1. Run the kind-specific reducer and assign its `nextState`.+ * 2. Run `reduceApmGatedRecentEvent` and assign its `nextState` again.+ * 3. If the branch calls for it, attempt a flush via+ * `reduceApmGatedFlushReadiness`, reading the now-fully-updated `apm`.+ */+function onRuntimeSignal(state: ManagerState, agentId: string, kind: string): ReduceResult {+ const existing = state.agents[agentId];+ if (!existing) return { state, effects: [] };+ const agent = clone(existing);++ const isGatedActive =+ agent.status === "running" && agent.turnActive && agent.caps.busyDeliveryMode === "gated";+ if (!isGatedActive) {+ // Still record the event for diagnostics — cheap and harmless even when+ // not gated (the ring buffer is unused unless busyDeliveryMode is gated).+ agent.apm = reduceApmGatedRecentEvent(agent.apm, { event: kind }).nextState;+ return commit(state, agent, []);+ }++ let attemptFlushReason: string | null = null;+ switch (kind) {+ case "tool_call":+ agent.apm = reduceApmGatedToolUse(agent.apm, { kind }).nextState;+ break;+ case "tool_output":+ agent.apm = reduceApmGatedToolUse(agent.apm, { kind }).nextState;+ attemptFlushReason = "tool_batch_complete";+ break;+ case "compaction_started":+ case "compaction_finished":+ agent.apm = reduceApmGatedCompaction(agent.apm, { kind }).nextState;+ if (kind === "compaction_finished") attemptFlushReason = "compaction_finished";+ break;+ case "review_started":+ case "review_finished":+ agent.apm = reduceApmGatedReview(agent.apm, { kind }).nextState;+ if (kind === "review_finished") attemptFlushReason = "review_finished";+ break;+ case "error":+ agent.apm = reduceApmGatedError(agent.apm, { disableToolBoundaryFlush: true }).nextState;+ break;+ default:+ // "text" / "thinking" / "internal_progress" / "runtime_diagnostic" /+ // "telemetry" / "session_init" / "turn_end" — no phase change here;+ // "turn_end" is already handled by onTurnEnd via its own event.+ break;+ }++ agent.apm = reduceApmGatedRecentEvent(agent.apm, { event: kind }).nextState;++ if (attemptFlushReason === null) return commit(state, agent, []);+ // Attempting a flush on every tool_output is intentional (not just when+ // the last outstanding tool just closed): it lets `reduceApmGatedFlushReadiness`+ // be the single source of truth for "is it safe", and surfaces a+ // `gated_hold` for "one of several nested tool calls just closed" too.+ if (agent.inbox.length === 0) return commit(state, agent, []);++ const readiness = reduceApmGatedFlushReadiness(agent.apm, {+ isGated: true,+ hasSession: agent.sessionId != null,+ inboxLength: agent.inbox.length,+ reason: attemptFlushReason,+ });+ if (readiness.shouldNotify) {+ const text = drainInboxToPrompt(agent);+ return commit(state, agent, [{ type: "send", agentId, text, mode: "busy" }]);+ }+ return commit(state, agent, [+ {+ type: "gated_hold",+ agentId,+ reason: attemptFlushReason,+ blockedReason: readiness.blockedReason,+ recentEvents: agent.apm.recentEvents,+ },+ ]);+}+function onExit(state: ManagerState, agentId: string): ReduceResult {const existing = state.agents[agentId];if (!existing) return { state, effects: [] };@@ -277,6 +420,7 @@ function freshAgent(agentId: string, caps: AgentRuntimeCaps): AgentState {turnActive: false,lastProgressAt: 0,idleSince: null,+ apm: createInitialApmGatedSteeringState(),};}@@ -295,7 +439,12 @@ function drainInboxToPrompt(agent: AgentState): string {}function clone(a: AgentState): AgentState {- return { ...a, inbox: [...a.inbox], caps: { ...a.caps } };+ return {+ ...a,+ inbox: [...a.inbox],+ caps: { ...a.caps },+ apm: { ...a.apm, recentEvents: [...a.apm.recentEvents] },+ };}function commit(state: ManagerState, agent: AgentState, effects: ManagerEffect[]): ReduceResult {diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.tsindex 0bb8ad35a..1500c8dd7 100644--- a/src/daemon/src/manager/managerRuntime.ts+++ b/src/daemon/src/manager/managerRuntime.ts@@ -303,6 +303,16 @@ export class AgentProcessManager {this.logSessionEnded(effect.agentId, effect.type === "stop" ? "stopped" : "terminate_stalled");break;}+ case "gated_hold":+ // Pure observability — no behavioral effect. Emitted whenever a+ // gated agent has a non-empty inbox but nothing was actually sent.+ this.log.info("gated busy message held", {+ agentId: effect.agentId,+ reason: effect.reason,+ blockedReason: effect.blockedReason,+ recentEvents: effect.recentEvents,+ });+ break;}}@@ -484,6 +494,10 @@ export class AgentProcessManager {}// Any event is progress for stall detection.this.dispatch({ type: "progress", agentId, nowMs: this.now() });+ // Forward every parsed event's kind for gated-steering phase tracking+ // (tool/compaction/review boundaries). No-ops in the reducer for kinds+ // it doesn't care about, aside from the diagnostics ring buffer.+ this.dispatch({ type: "runtime_signal", agentId, kind: ev.kind, nowMs: this.now() });if (ev.kind === "turn_end") {this.logSessionEnded(agentId, "turn_end");this.dispatch({ type: "turn_end", agentId, nowMs: this.now() });diff --git a/src/daemon/src/server/contract.test.ts b/src/daemon/src/server/contract.test.tsindex 015b2d14a..d240dd4b7 100644--- a/src/daemon/src/server/contract.test.ts+++ b/src/daemon/src/server/contract.test.ts@@ -33,8 +33,24 @@ describe("parseRef", () => {expect(parseRef("/demo/general/#5")).toEqual({ server: "demo", channel: "general", threadRootSeq: 5 });});it("parses a DM ref", () => {+ // No "#" in the segment — legacy/no-discriminator id form, round-trips+ // through the parser unchanged. Resolution (not parsing) is what changes+ // once the server requires a `name#0042` handle for DM refs.expect(parseRef("/.dm/gustavo")).toEqual({ server: DM_SERVER, channel: "gustavo" });});+ it("parses a DM ref that's a bare name#0042 handle (no seq stripped)", () => {+ expect(parseRef("/.dm/gusye#1231")).toEqual({ server: DM_SERVER, channel: "gusye#1231" });+ });+ it("parses a pinned message on a handle peer (/.dm/name#0042#N)", () => {+ expect(parseRef("/.dm/gusye#1231#42")).toEqual({ server: DM_SERVER, channel: "gusye#1231", seq: 42 });+ });+ it("parses a thread on a handle peer (/.dm/name#0042/#N)", () => {+ expect(parseRef("/.dm/gusye#1231/#42")).toEqual({+ server: DM_SERVER,+ channel: "gusye#1231",+ threadRootSeq: 42,+ });+ });it("rejects refs not starting with '/'", () => {expect(() => parseRef("demo/general")).toThrow(/must start with/);});diff --git a/src/daemon/src/server/mockServer.dm.test.ts b/src/daemon/src/server/mockServer.dm.test.tsnew file mode 100644index 000000000..9d5d7d1d9--- /dev/null+++ b/src/daemon/src/server/mockServer.dm.test.ts@@ -0,0 +1,56 @@+import { describe, it, expect } from "vitest";+import { MockServer } from "./mockServer";+import { computeDiscriminator } from "@alook/shared/lib/discriminator";++/**+ * `MockServer` resolves DM peers by a different scheme than production+ * `resolve-ref.ts` — this file proves both `createAgent` (deterministic+ * `computeDiscriminator`) and seeded `members` produce `@name#0042` handles+ * that `membersOf`/`post`/`send` round-trip through the `/.dm/<handle>`+ * ref format.+ */+describe("MockServer — DM handle resolution", () => {+ it("membersOf resolves a /.dm/name#0042 ref built from createAgent's handle", async () => {+ const s = new MockServer();+ const { user } = await s.createUser({ name: "u" });+ const { agent } = await s.createAgent({ userId: user.id, name: "cindy", runtime: "mock" });++ const discriminator = computeDiscriminator(agent.id);+ const dmRef = `/.dm/cindy#${discriminator}`;++ expect(s.membersOf(dmRef)).toEqual([agent.id]);+ });++ it("a post/send round-trip through a DM ref built from the handle format works end-to-end", async () => {+ const s = new MockServer();+ const { user } = await s.createUser({ name: "u" });+ const { agent } = await s.createAgent({ userId: user.id, name: "cindy", runtime: "mock" });+ const discriminator = computeDiscriminator(agent.id);+ const dmRef = `/.dm/cindy#${discriminator}`;++ s.post({ channel: dmRef, sender: "@gustavo#4821", text: "hello" });+ const { messages } = await s.inboxPull({ agentId: agent.id, max: 50 });+ expect(messages).toHaveLength(1);+ expect(messages[0]!.sender).toBe("@gustavo#4821");+ expect(messages[0]!.channel).toBe(dmRef);++ await s.ack({ agentId: agent.id, cursors: [{ channel: dmRef, seq: 1 }] });+ const res = await s.send({ agentId: agent.id, channel: dmRef, content: { text: "hi back" } });+ expect(res.state).toBe("sent");+ if (res.state === "sent") {+ expect(res.message.sender).toBe(`@cindy#${discriminator}`);+ }+ });++ it("seeded members resolve via their explicit discriminator, defaulting to computeDiscriminator(id) when omitted", async () => {+ const s = new MockServer({+ servers: [],+ members: [+ { id: "agent_a", name: "alex", discriminator: "1111" },+ { id: "agent_b", name: "sam" },+ ],+ });+ expect(s.membersOf("/.dm/alex#1111")).toEqual(["agent_a"]);+ expect(s.membersOf(`/.dm/sam#${computeDiscriminator("agent_b")}`)).toEqual(["agent_b"]);+ });+});diff --git a/src/daemon/src/server/mockServer.ts b/src/daemon/src/server/mockServer.tsindex 9f74b07b7..389eab969 100644--- a/src/daemon/src/server/mockServer.ts+++ b/src/daemon/src/server/mockServer.ts@@ -6,9 +6,9 @@* network. The CLI (in test mode) and example harnesses talk to it exactly as* they would the real server, exercising the contract end to end.*- * Addressing is by `ChannelRef` path strings (`/server/channel`, `/.dm/peer`);- * messages are located by channel + seq. The agent-facing `Message` is flat:- * `{ seq:"#N", channel, sender:"@handle", content:{text}, time }`.+ * Addressing is by `ChannelRef` path strings (`/server/channel`,+ * `/.dm/name#0042`); messages are located by channel + seq. The agent-facing+ * `Message` is flat: `{ seq:"#N", channel, sender:"@name#0042", content:{text}, time }`.** Data/admin/enrollment-only (minimal-wake-queue-unread-notice plan §6) —* this class deliberately carries NO control-plane state or dispatch logic.@@ -51,6 +51,7 @@ import { DM_SERVER, parseRef, formatSeq } from "./contract.js";import * as crypto from "crypto";import type { RuntimeConfig } from "../runtimeConfig.js";import { makeRuntimeConfig } from "../runtimeConfig.js";+import { computeDiscriminator, formatHandle } from "@alook/shared/lib/discriminator";/** Internal stored row — richer than the flat agent-facing Message. */interface StoredMessage {@@ -64,8 +65,14 @@ interface StoredMessage {interface SeedMember {id: string;- /** Handle without "@", e.g. "gustavo". */+ /** Handle without "@" or "#0042", e.g. "gustavo". */name: string;+ /**+ * 4-digit tag pairing with `name` for the global handle (`name#0042`).+ * Defaults to `computeDiscriminator(id)` — this is a fresh test fixture,+ * not legacy data that needed a random backfill.+ */+ discriminator?: string;}export interface MockServerSeed {@@ -90,7 +97,7 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {private readonly channels = new Map<string, Channel>();/** serverId → set of agentIds participating. */private readonly membership = new Map<string, Set<string>>();- /** agentId → handle ("@name") for sender stamping. */+ /** agentId → global handle ("@name#0042") for sender stamping. */private readonly agentHandles = new Map<string, string>();/*** agentId → RuntimeConfig, as set by `createAgent`. Admin-surface storage@@ -196,10 +203,17 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {}private applySeed(seed: MockServerSeed): void {- for (const m of seed.members ?? []) this.agentHandles.set(m.id, `@${m.name}`);+ for (const m of seed.members ?? []) {+ const discriminator = m.discriminator ?? computeDiscriminator(m.id);+ this.agentHandles.set(m.id, `@${formatHandle(m.name, discriminator)}`);+ }for (const a of seed.members ?? []) {if (!this.agentConfigs.has(a.id)) {- this.agentConfigs.set(a.id, makeRuntimeConfig({ runtime: "mock", agentName: a.name, agentHandle: `@${a.name}` }));+ const discriminator = a.discriminator ?? computeDiscriminator(a.id);+ this.agentConfigs.set(+ a.id,+ makeRuntimeConfig({ runtime: "mock", agentName: a.name, agentHandle: `@${formatHandle(a.name, discriminator)}` }),+ );}}for (const s of seed.servers) {@@ -250,7 +264,7 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {/* ----- test/seed helpers (not part of ServerApi) ----- */- /** Inject a message as if `senderHandle` (e.g. "@gustavo") posted it. */+ /** Inject a message as if `senderHandle` (e.g. "@gustavo#4821") posted it. */post(input: { channel: ChannelRef; sender: string; text: string; mention?: boolean }): Message {return toAgentMessage(this.append(input.channel, input.sender.startsWith("@") ? input.sender : `@${input.sender}`, input.text, input.mention),@@ -466,14 +480,18 @@ export class MockServer implements ServerApi, AdminApi, EnrollmentApi {}): Promise<{ agent: Agent }> {// Agent is the user's asset — created independent of any server.const agent: Agent = { id: this.mkId("agent"), name: req.name, userId: req.userId };- this.agentHandles.set(agent.id, `@${req.name}`);+ // Fresh test fixture — no legacy backfill to worry about, so the+ // discriminator is deterministically derived from the freshly minted id.+ const discriminator = computeDiscriminator(agent.id);+ const handle = `@${formatHandle(req.name, discriminator)}`;+ this.agentHandles.set(agent.id, handle);if (req.machineKey) this.agentMachineKey.set(agent.id, req.machineKey);// The agent's identity (name + instruction) lives in its RuntimeConfig — the// same config downlinked via agent:wake — so the daemon gets it from the// server, not by inventing it.this.agentConfigs.set(agent.id,- makeRuntimeConfig({ runtime: req.runtime ?? "mock", agentName: req.name, agentHandle: `@${req.name}`, instruction: req.instruction }),+ makeRuntimeConfig({ runtime: req.runtime ?? "mock", agentName: req.name, agentHandle: handle, instruction: req.instruction }),);return { agent };}diff --git a/src/daemon/src/types.ts b/src/daemon/src/types.tsindex ce47d4d2d..aee94ca19 100644--- a/src/daemon/src/types.ts+++ b/src/daemon/src/types.ts@@ -174,7 +174,12 @@ export interface LaunchConfig {runtimeContext?: RuntimeContext;/** Agent display name (e.g. "Cindy"). */agentName?: string;- /** Agent @mention handle (e.g. "@cindy"). */+ /**+ * Agent's global @mention handle, `@name#0042` (e.g. "@cindy#4821"). Every+ * account in Alook — human or agent — has a name plus a 4-digit+ * discriminator; this is the `@`-prefixed pair, unique even when names+ * collide.+ */agentHandle?: string;}diff --git a/src/shared/package.json b/src/shared/package.jsonindex 5d3ac1c87..f6541a560 100644--- a/src/shared/package.json+++ b/src/shared/package.json@@ -7,7 +7,8 @@"./crypto": "./src/utils/crypto.ts","./browser": "./src/browser/index.ts","./community-cli-contract": "./src/community-cli-contract.ts",- "./runtime-config": "./src/runtime-config.ts"+ "./runtime-config": "./src/runtime-config.ts",+ "./lib/discriminator": "./src/lib/discriminator.ts"},"scripts": {"knip": "knip",@@ -27,4 +28,4 @@"typescript": "^6.0.3","vitest": "^4.1.9"}-}+}\ No newline at end of filediff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 355eaefd4..4d1a2393d 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -104,7 +104,11 @@ export const DM_SERVER = ".dm";* /<server>/<channel> a channel* /<server>/<channel>#N the N-th message (seq) in that channel* /<server>/<channel>/#N the thread rooted at message #N- * /.dm/<peer> a DM (DM is the standalone `.dm` server)+ * /.dm/<peer> a DM (DM is the standalone `.dm` server);+ * <peer> is the peer's global handle+ * (`name#0042`, e.g. `/.dm/gusye#1231`),+ * NOT a raw user id — see `parseRef`'s+ * `.dm`-specific branch below.* /.dm/<peer>#N , /.dm/<peer>/#N a DM message / DM thread** A message is located by **channel + seq** (`<channelRef>#N`) — there is no id.@@ -118,7 +122,7 @@ export type ChannelRef = string;*/export type Target =| { server: ServerId; kind: "channel"; channel: ChannelId | string }- | { server: typeof DM_SERVER; kind: "dm"; peer: AgentId | UserId | string }+ | { server: typeof DM_SERVER; kind: "dm"; peer: AgentId | UserId | string /** global handle (`name#0042`) on the wire; resolved server-side to a real id */ }| {server: ServerId | typeof DM_SERVER;kind: "thread";@@ -136,8 +140,8 @@ export type Target =* The flat, agent-facing message. This is exactly what the agent sees (one JSON* object per line, JSONL). Deliberately minimal:* - `seq` — "#N", the per-channel sequence (locate via channel + seq).- * - `channel` — the path ref, e.g. "/demo-workspace/general" or "/.dm/gustavo".- * - `sender` — "@handle" (no id, no human/agent/system type).+ * - `channel` — the path ref, e.g. "/demo-workspace/general" or "/.dm/gustavo#4821".+ * - `sender` — "@handle" (`name#0042`, no id, no human/agent/system type).* - `content` — `{ text }` today; an object (not a bare string) so future* content kinds (attachments, embeds, …) can be added without* breaking the shape.@@ -155,7 +159,7 @@ export interface Message {seq: string;/** Path ref of the containing channel/DM. */channel: ChannelRef;- /** Sender handle, e.g. "@gustavo". */+ /** Sender global handle (`name#0042`), e.g. "@gustavo#4821". */sender: string;content: MessageContent;/** ISO-8601. */@@ -376,12 +380,16 @@ export type HostCommand =type: "bot:added";botId: AgentId;name: string;+ /** 4-digit tag (`computeDiscriminator`) — pairs with `name` for the bot's global handle. */+ discriminator: string;description?: string;}| {type: "bot:updated";botId: AgentId;name: string;+ /** 4-digit tag (`computeDiscriminator`) — pairs with `name` for the bot's global handle. */+ discriminator: string;description?: string;}| {@@ -630,7 +638,12 @@ export interface ParsedRef {* /<server>/<channel> → { server, channel }* /<server>/<channel>#N → { server, channel, seq:N }* /<server>/<channel>/#N → { server, channel, threadRootSeq:N }- * /.dm/<peer>[...] → DM (server = ".dm", channel = peer)+ * /.dm/<peer>[...] → DM (server = ".dm", channel = peer, a+ * `name#0042` handle) — see the `.dm`-specific+ * branch below, which differs from the+ * generic channel-ref `#`-split (a handle's+ * `#0042` suffix must NOT be mistaken for a+ * pinned-message seq).*/export function parseRef(ref: ChannelRef): ParsedRef {if (!ref.startsWith("/")) throw new Error(`ref must start with "/": ${ref}`);@@ -647,8 +660,28 @@ export function parseRef(ref: ChannelRef): ParsedRef {threadRootSeq = parseSeq(parts[parts.length - 1]);return { server, channel: parts[1], threadRootSeq };}- // Message form: /server/channel#N (channel segment carries the #N).const chSeg = parts[1];++ // DM-specific branch: a DM peer segment is a `name#0042` handle, not a bare+ // channel name — the generic "first #" split below would mis-parse+ // `gusye#1231` as peer="gusye", seq=1231. Find the LAST "#" instead: if+ // there's exactly one "#" in the segment and the tail is exactly 4 digits,+ // the WHOLE segment is the handle (the common case). Otherwise (2+ "#"s,+ // or a non-4-digit tail) the text after the last "#" is a seq/thread root,+ // matching `gusye#1231#42` (pin) / `gusye#1231/#42` (thread, handled by the+ // thread-form branch above) — see plan §1 for the accepted `a#b` ambiguity.+ if (server === DM_SERVER) {+ const lastHash = chSeg.lastIndexOf("#");+ if (lastHash < 0) return { server, channel: chSeg };+ const firstHash = chSeg.indexOf("#");+ const tail = chSeg.slice(lastHash + 1);+ const isBareHandle = firstHash === lastHash && /^\d{4}$/.test(tail);+ if (isBareHandle) return { server, channel: chSeg };+ seq = parseSeq(tail);+ return { server, channel: chSeg.slice(0, lastHash), seq };+ }++ // Message form: /server/channel#N (channel segment carries the #N).const hashIdx = chSeg.indexOf("#");if (hashIdx >= 0) {seq = parseSeq(chSeg.slice(hashIdx));diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex a65e9f25b..3bdaba928 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -211,6 +211,9 @@ export type CommunityMemberJoin = {id: stringuserId: stringname: string+ // 4-digit discriminator (`"0042"`) — optional so older/mock payloads+ // that predate the column keep type-checking.+ discriminator?: stringavatar?: stringrole: stringjoinedAt: string@@ -399,6 +402,8 @@ export type BotAddedFrame = {type: "bot:added"botId: stringname: string+ /** 4-digit tag (`computeDiscriminator`) — pairs with `name` for the bot's global handle. */+ discriminator: stringdescription?: string}@@ -406,6 +411,8 @@ export type BotUpdatedFrame = {type: "bot:updated"botId: stringname: string+ /** 4-digit tag (`computeDiscriminator`) — pairs with `name` for the bot's global handle. */+ discriminator: stringdescription?: string}diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.tsindex 6f67896ad..345132abc 100644--- a/src/shared/src/community/wake-dispatch.ts+++ b/src/shared/src/community/wake-dispatch.ts@@ -1,6 +1,7 @@import { nanoid } from "nanoid";import type { HostCommand, UnreadNotice } from "../community-cli-contract";import { makeRuntimeConfig } from "../runtime-config";+import { formatHandle } from "../lib/discriminator";import * as message from "../db/queries/community/message";import * as bot from "../db/queries/community/bot";import * as member from "../db/queries/community/member";@@ -145,7 +146,7 @@ export async function buildUnreadWakeCommand(const config = makeRuntimeConfig({runtime: botCtx.runtime,agentName: botCtx.name,- agentHandle: `@${botCtx.name}`,+ agentHandle: `@${formatHandle(botCtx.name, botCtx.discriminator)}`,});const command: HostCommand = {type: "agent:wake",diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.tsindex f82d50326..6b9a7a038 100644--- a/src/shared/src/db/queries/community/agent-inbox.ts+++ b/src/shared/src/db/queries/community/agent-inbox.ts@@ -22,6 +22,7 @@ import {import { user } from "../../schema";import type { Database } from "../../index";import { formatRef, formatSeq, DM_SERVER, type Message, type Seq, type ChannelRef } from "../../../community-cli-contract";+import { formatHandle } from "../../../lib/discriminator";type RawAgentMessage = {id: string;@@ -85,6 +86,25 @@ async function resolveScopeRefs(const channelById = new Map(channels.map((c) => [c.id, c]));const dmById = new Map(dms.map((d) => [d.id, d]));+ // DM peer ids → the OTHER party of each dm relative to viewerId — resolved+ // to name+discriminator so the DM ref is a handle (`/.dm/<peer#0042>`), not+ // a raw user id. Batched alongside the author-id fetch below (a separate+ // Promise.all slot, not a second round-trip per dm).+ const dmPeerIds = [+ ...new Set(+ dms+ .map((dm) => (dm.user1Id === viewerId ? dm.user2Id : dm.user1Id))+ .filter((x): x is string => !!x)+ ),+ ];+ const dmPeerUsers = dmPeerIds.length+ ? await db+ .select({ id: user.id, name: user.name, discriminator: user.discriminator })+ .from(user)+ .where(inArray(user.id, dmPeerIds))+ : [];+ const dmPeerById = new Map(dmPeerUsers.map((u) => [u.id, u]));+const parentChannelIds = [...new Set(channels.map((c) => c.parentChannelId).filter((x): x is string => !!x)),];@@ -130,7 +150,9 @@ async function resolveScopeRefs(}for (const dm of dms) {const peerId = dm.user1Id === viewerId ? dm.user2Id : dm.user1Id;- out.set(`dm:${dm.id}`, { ref: formatRef({ server: DM_SERVER, channel: peerId || "unknown" }), isThread: false });+ const peer = peerId ? dmPeerById.get(peerId) : undefined;+ const peerSegment = peer ? formatHandle(peer.name, peer.discriminator) : peerId || "unknown";+ out.set(`dm:${dm.id}`, { ref: formatRef({ server: DM_SERVER, channel: peerSegment }), isThread: false });}return out;}@@ -157,20 +179,21 @@ export async function toAgentMessages(const [refs, users] = await Promise.all([resolveScopeRefs(db, rows, viewerId),db- .select({ id: user.id, name: user.name })+ .select({ id: user.id, name: user.name, discriminator: user.discriminator }).from(user).where(inArray(user.id, [...new Set(rows.map((r) => r.authorId))])),]);- const userNameById = new Map(users.map((u) => [u.id, u.name]));+ const userById = new Map(users.map((u) => [u.id, u]));return rows.map((r) => {const scope = refs.get(scopeRefKey(r));const channel = scope?.ref ?? `/unknown/${scopeRefKey(r)}`;- const senderName = userNameById.get(r.authorId) ?? r.authorId;+ const author = userById.get(r.authorId);+ const sender = author ? formatHandle(author.name, author.discriminator) : r.authorId;return {seq: formatSeq(r.seq),channel,- sender: `@${senderName}`,+ sender: `@${sender}`,content: { text: r.content },time: r.createdAt,};@@ -243,7 +266,18 @@ export async function resolveUnreadNoticeChannel(if (!dm) return null;const peerId = dm.user1Id === botUserId ? dm.user2Id : dm.user1Id;if (!peerId) return null;- return formatRef({ server: DM_SERVER, channel: peerId });+ const peerRows = await db+ .select({ name: user.name, discriminator: user.discriminator })+ .from(user)+ .where(eq(user.id, peerId))+ .limit(1);+ const peer = peerRows[0];+ // A wake command's notice channel must NEVER be a placeholder (see this+ // function's doc comment) — a peer that no longer resolves to a+ // name+discriminator is `notice_channel_unresolvable`, same as any other+ // missing-scope case, not a bare-peerId ref the agent can't act on.+ if (!peer) return null;+ return formatRef({ server: DM_SERVER, channel: formatHandle(peer.name, peer.discriminator) });}return null;@@ -402,19 +436,25 @@ export async function getInboxSnapshotForAgent(db: Database, botUserId: string):const senderIds = [...new Set(rows.map((r) => r.latestSenderId).filter(Boolean))];const users = senderIds.length- ? await db.select({ id: user.id, name: user.name }).from(user).where(inArray(user.id, senderIds))+ ? await db+ .select({ id: user.id, name: user.name, discriminator: user.discriminator })+ .from(user)+ .where(inArray(user.id, senderIds)): [];- const nameById = new Map(users.map((u) => [u.id, u.name]));-- return rows.map((r) => ({- channelId: r.channelId,- dmConversationId: r.dmConversationId,- pendingCount: r.pendingCount,- firstPendingSeq: r.firstPendingSeq,- latestSeq: r.latestSeq,- latestSender: `@${nameById.get(r.latestSenderId) ?? r.latestSenderId}`,- hasMention: r.mentionCount > 0,- }));+ const userById = new Map(users.map((u) => [u.id, u]));++ return rows.map((r) => {+ const sender = userById.get(r.latestSenderId);+ return {+ channelId: r.channelId,+ dmConversationId: r.dmConversationId,+ pendingCount: r.pendingCount,+ firstPendingSeq: r.firstPendingSeq,+ latestSeq: r.latestSeq,+ latestSender: `@${sender ? formatHandle(sender.name, sender.discriminator) : r.latestSenderId}`,+ hasMention: r.mentionCount > 0,+ };+ });}/**diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex 812347110..94dc6482b 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -35,7 +35,7 @@ import {import { communityMachine } from "../../community-machine-schema";import type { Database } from "../../index";import { communityBotSyntheticEmail } from "../../../constants";-import { computeDiscriminator } from "../../../lib/discriminator";+import { withUniqueDiscriminator } from "../user";import { nanoid } from "nanoid";// ─── Types ──────────────────────────────────────────────────────────────────@@ -257,13 +257,14 @@ export type BotWakeContext =| { state: "bot_missing" }| { state: "bot_deleted" }| { state: "bot_unbound" }- | { state: "ready"; botUserId: string; name: string; machineId: string; runtime: string };+ | { state: "ready"; botUserId: string; name: string; discriminator: string; machineId: string; runtime: string };export async function getBotWakeContext(db: Database, botUserId: string): Promise<BotWakeContext> {const rows = await db.select({id: user.id,name: user.name,+ discriminator: user.discriminator,isBot: user.isBot,deletedAt: user.deletedAt,machineId: communityBotBinding.machineId,@@ -277,14 +278,21 @@ export async function getBotWakeContext(db: Database, botUserId: string): Promisif (!r || !r.isBot) return { state: "bot_missing" };if (r.deletedAt) return { state: "bot_deleted" };if (!r.machineId || !r.runtime) return { state: "bot_unbound" };- return { state: "ready", botUserId: r.id, name: r.name, machineId: r.machineId, runtime: r.runtime };+ return {+ state: "ready",+ botUserId: r.id,+ name: r.name,+ discriminator: r.discriminator,+ machineId: r.machineId,+ runtime: r.runtime,+ };}/** Bots bound to this machine — daemon cold-start warmup uses this. */export async function listBotsForMachine(db: Database,machineId: string-): Promise<Array<{ id: string; name: string; description: string }>> {+): Promise<Array<{ id: string; name: string; discriminator: string; description: string }>> {// Guard against orphaned bots: if a future flow soft-deletes an owner user// without cascading their bots, don't hand them to the daemon for warmup.const owner = aliasedTable(user, "owner");@@ -292,6 +300,7 @@ export async function listBotsForMachine(.select({id: user.id,name: user.name,+ discriminator: user.discriminator,description: communityUserProfile.aboutMe,}).from(user)@@ -312,6 +321,7 @@ export async function listBotsForMachine(return rows.map((r) => ({id: r.id,name: r.name,+ discriminator: r.discriminator,description: r.description ?? "",}));}@@ -376,51 +386,62 @@ export type CreateBotInput = {* 2. INSERT `community_bot_binding` (machineId + runtime).* 3. INSERT `community_user_profile` (aboutMe = description).*- * Batched so all commit or none. Returns the bot row.+ * Batched so all commit or none. `withUniqueDiscriminator` wraps the WHOLE+ * batch (not just statement 1) — a discriminator collision retries all three+ * statements together so the binding/profile rows always land alongside the+ * user row that actually won the discriminator. Returns the bot row.*/export async function createBot(db: Database,data: CreateBotInput-): Promise<{ botId: string; name: string; description: string; image: string | null }> {+): Promise<{ botId: string; name: string; discriminator: string; description: string; image: string | null }> {const botId = nanoid();const email = communityBotSyntheticEmail(botId);const nowIso = new Date().toISOString();const description = data.description ?? "";- // Three-statement batch. D1 rolls back all on any error.- const stmt1 = db.insert(user).values({- id: botId,- name: data.name,- email,- emailVerified: true,- image: data.image ?? null,- isBot: true,- ownerUserId: data.ownerId,- discriminator: computeDiscriminator(botId),- createdAt: nowIso,- updatedAt: nowIso,- });- const stmt2 = db.insert(communityBotBinding).values({- userId: botId,- machineId: data.machineId,- runtime: data.runtime,- createdAt: nowIso,- });- // Match updateBot's upsert semantics — reincarnation paths (nanoid collision- // aside, future flows that recycle a botId) shouldn't roll the batch back on- // a profile PK conflict.- const stmt3 = db- .insert(communityUserProfile)- .values({ userId: botId, aboutMe: description })- .onConflictDoUpdate({- target: communityUserProfile.userId,- set: { aboutMe: description },- });- await db.batch([stmt1, stmt2, stmt3] as any);+ const discriminator = await withUniqueDiscriminator(+ db,+ { id: botId, name: data.name },+ async (discriminator) => {+ // Three-statement batch. D1 rolls back all on any error.+ const stmt1 = db.insert(user).values({+ id: botId,+ name: data.name,+ email,+ emailVerified: true,+ image: data.image ?? null,+ isBot: true,+ ownerUserId: data.ownerId,+ discriminator,+ createdAt: nowIso,+ updatedAt: nowIso,+ });+ const stmt2 = db.insert(communityBotBinding).values({+ userId: botId,+ machineId: data.machineId,+ runtime: data.runtime,+ createdAt: nowIso,+ });+ // Match updateBot's upsert semantics — reincarnation paths (nanoid collision+ // aside, future flows that recycle a botId) shouldn't roll the batch back on+ // a profile PK conflict.+ const stmt3 = db+ .insert(communityUserProfile)+ .values({ userId: botId, aboutMe: description })+ .onConflictDoUpdate({+ target: communityUserProfile.userId,+ set: { aboutMe: description },+ });+ await db.batch([stmt1, stmt2, stmt3] as any);+ return discriminator;+ }+ );return {botId,name: data.name,+ discriminator,description,image: data.image ?? null,};@@ -436,7 +457,7 @@ export async function updateBot(botId: string,ownerId: string,data: { name?: string; description?: string; image?: string | null }-): Promise<{ botId: string; name: string; description: string; image: string | null } | null> {+): Promise<{ botId: string; name: string; discriminator: string; description: string; image: string | null } | null> {const set: { name?: string; image?: string | null; updatedAt: string } = {updatedAt: new Date().toISOString(),};@@ -447,7 +468,7 @@ export async function updateBot(// concurrent softDeleteBot can't slip in between and leave a fresh description// on a tombstoned bot. The upsert INSERT branch is safe (createBot writes the// profile row); it only fires for legacy rows that pre-date the profile write.- let rows: Array<{ id: string; name: string; image: string | null }>;+ let rows: Array<{ id: string; name: string; discriminator: string; image: string | null }>;if (data.description !== undefined) {const s1 = db.update(user)@@ -460,7 +481,7 @@ export async function updateBot(isNull(user.deletedAt)))- .returning({ id: user.id, name: user.name, image: user.image });+ .returning({ id: user.id, name: user.name, discriminator: user.discriminator, image: user.image });const s2 = db.insert(communityUserProfile).values({ userId: botId, aboutMe: data.description })@@ -482,7 +503,7 @@ export async function updateBot(isNull(user.deletedAt)))- .returning({ id: user.id, name: user.name, image: user.image });+ .returning({ id: user.id, name: user.name, discriminator: user.discriminator, image: user.image });}if (rows.length === 0) return null;@@ -500,6 +521,7 @@ export async function updateBot(return {botId: rows[0]!.id,name: rows[0]!.name,+ discriminator: rows[0]!.discriminator,description,image: rows[0]!.image,};diff --git a/src/shared/src/db/queries/community/friendship.ts b/src/shared/src/db/queries/community/friendship.tsindex 63d87a0c2..92e115043 100644--- a/src/shared/src/db/queries/community/friendship.ts+++ b/src/shared/src/db/queries/community/friendship.ts@@ -314,28 +314,54 @@ export async function listFriends(db: Database, userId: string) {}/**- * Ids-only variant of `listFriends` — no `user` join, no own-bot rows. Used- * on hot paths that only need "who is this user's friend" (WS presence- * fan-out, presence bulk-check route) and would rather not pay for name/- * email/image columns they're going to throw away.+ * Ids-only variant of `listFriends` — no name/email/image columns. Used on+ * hot paths that only need "who is this user's friend" (WS presence+ * fan-out via `ws-durable.ts`'s `getPresenceAudience`, and the+ * `/friends/presence` bulk-check route).+ *+ * DOES include the owner↔own-bot implicit friendship (same rule as+ * `areFriends`/`listFriends` — no real `communityFriendship` row exists for+ * the pair, but they act like friends everywhere), because both real+ * callers are presence checks and a bot's presence is meaningless without+ * its owner in the audience. An earlier revision deliberately excluded+ * these rows here (to match `listFriends`' "no join" cost-saving, not+ * realizing that trimmed the whole reason a bot's owner needs to be in this+ * list) — that's what caused a bot's owner to never learn about its own+ * presence, see plans/community-account-debt-fixes.md Fix 3 hotfix.*/export async function getFriendUserIds(db: Database, userId: string): Promise<string[]> {- const rows = await db- .select({- requesterId: communityFriendship.requesterId,- addresseeId: communityFriendship.addresseeId,- })- .from(communityFriendship)- .where(- and(- eq(communityFriendship.status, "accepted"),- or(- eq(communityFriendship.requesterId, userId),- eq(communityFriendship.addresseeId, userId),+ const [rows, selfBotRows] = await Promise.all([+ db+ .select({+ requesterId: communityFriendship.requesterId,+ addresseeId: communityFriendship.addresseeId,+ })+ .from(communityFriendship)+ .where(+ and(+ eq(communityFriendship.status, "accepted"),+ or(+ eq(communityFriendship.requesterId, userId),+ eq(communityFriendship.addresseeId, userId),+ ),),),- );- return rows.map((r) => (r.requesterId === userId ? r.addresseeId : r.requesterId));+ db+ .select({ id: user.id, ownerUserId: user.ownerUserId })+ .from(user)+ .where(+ and(+ eq(user.isBot, true),+ or(eq(user.id, userId), eq(user.ownerUserId, userId)),+ isNull(user.deletedAt)+ )+ ),+ ]);+ const friendIds = rows.map((r) => (r.requesterId === userId ? r.addresseeId : r.requesterId));+ const selfBotIds = selfBotRows+ .map((r) => (r.id === userId ? r.ownerUserId : r.id))+ .filter((id): id is string => !!id);+ return [...new Set([...friendIds, ...selfBotIds])];}/**diff --git a/src/shared/src/db/queries/community/invite.ts b/src/shared/src/db/queries/community/invite.tsindex 001752268..6b4a9d2bc 100644--- a/src/shared/src/db/queries/community/invite.ts+++ b/src/shared/src/db/queries/community/invite.ts@@ -96,7 +96,7 @@ export async function useInvite(// Join the joined-user row so WS listeners can render name/avatar without// waiting for the next /members refetch.const userRows = await db- .select({ name: user.name, image: user.image })+ .select({ name: user.name, image: user.image, discriminator: user.discriminator }).from(user).where(eq(user.id, userId));const userRow = userRows[0];@@ -107,6 +107,7 @@ export async function useInvite(...insertedMember,userName: userRow?.name ?? "",userImage: userRow?.image ?? null,+ discriminator: userRow?.discriminator ?? null,},};}diff --git a/src/shared/src/db/queries/community/machine.ts b/src/shared/src/db/queries/community/machine.tsindex 05dafa5e7..847c97def 100644--- a/src/shared/src/db/queries/community/machine.ts+++ b/src/shared/src/db/queries/community/machine.ts@@ -5,6 +5,7 @@ import {communityMachine,communityMachineCredential,communityAgentRunnerKey,+ communityBotBinding,} from "../../community-machine-schema";import { user } from "../../schema";import type { Database } from "../../index";@@ -240,18 +241,31 @@ export interface MachineRow {* Upsert-by-machine-id — the runtime path used by every `ready` frame and* every /activate reconnect. First-pair /activate calls `insertMachineRow`* instead (below) so the machine.id is minted by the insert.+ *+ * `markOnline` (default true) gates the `status: "online"` / `lastSeenAt`+ * write. The WS `ready`-frame handler is the only caller that actually KNOWS+ * there's a live socket, so it uses the default. /activate reconnect calls+ * this with `markOnline: false` — HTTP activation happens before the+ * daemon's WS connects, so flipping status here would make the row already+ * "online" by the time the real `ready` frame lands, and the DO's+ * `priorStatus !== 'online'` broadcast guard (which gates the bot-presence+ * fan-out, see `ws-durable.ts` `notifyUserDO`) would silently skip the+ * notification. Leaving status untouched here mirrors `insertMachineRow`,+ * which already withholds `lastSeenAt` for the same reason on first pair.*/export async function upsertMachineByMachineId(db: Database,userId: string,machineId: string,- meta: MachineMetadataInput+ meta: MachineMetadataInput,+ opts: { markOnline?: boolean } = {}): Promise<{machine: MachineRow;priorLastSeenAt: string | null;priorAvailableRuntimes: CommunityMachineRuntime[];priorStatus: "online" | "offline";} | null> {+ const markOnline = opts.markOnline ?? true;const existing = await db.select().from(communityMachine)@@ -281,11 +295,7 @@ export async function upsertMachineByMachineId(meta.availableRuntimes !== undefined? meta.availableRuntimes: prior.availableRuntimes,- // The daemon just sent a `ready` frame — we KNOW there is a live WS,- // so flip status to online unconditionally. The DO gates its- // `community:machine.status online` broadcast on `priorStatus !== 'online'`.- status: "online",- lastSeenAt: nowIso,+ ...(markOnline ? { status: "online" as const, lastSeenAt: nowIso } : {}),updatedAt: nowIso,}).where(eq(communityMachine.id, prior.id))@@ -437,7 +447,13 @@ export async function activateMachineCredential(try {let machine: MachineRow;if (tok.machineId) {- const existing = await upsertMachineByMachineId(db, tok.userId, tok.machineId, meta);+ // `markOnline: false` — this runs before the daemon's WS connects, so+ // the real `ready` frame (not this HTTP call) must be the one that+ // flips status and fires the online/bot-presence broadcast. See+ // `upsertMachineByMachineId`'s doc comment.+ const existing = await upsertMachineByMachineId(db, tok.userId, tok.machineId, meta, {+ markOnline: false,+ });if (!existing) {// Machine was deleted between mint and activate. Don't roll the// token back to `pending` — that would loop the daemon forever and@@ -880,6 +896,27 @@ export async function markMachineOffline(return rows.length ? (rows[0] as MachineRow) : null;}+/**+ * Read-path counterpart to `listBotsForMachine` (`bot.ts`) — given a bot's+ * `user.id`, answer whether it's currently online by following its+ * `communityBotBinding` to the bound machine's `status` column. A bot has no+ * WebSocket of its own (see `ws-durable.ts`'s `/check-user-online`), so+ * `status` on the bound machine IS the bot's presence, unlike a human where+ * presence is a live-socket check.+ */+export async function isBotOnline(db: Database, botUserId: string): Promise<boolean> {+ const rows = await db+ .select({ status: communityMachine.status })+ .from(communityBotBinding)+ .innerJoin(communityMachine, eq(communityMachine.id, communityBotBinding.machineId))+ .innerJoin(user, eq(user.id, communityBotBinding.userId))+ // Mirrors `listBotsForMachine`'s soft-delete guard: a tombstoned bot must+ // never read back as online, even if its machine binding row is still live.+ .where(and(eq(communityBotBinding.userId, botUserId), isNull(user.deletedAt)))+ .limit(1);+ return rows.length > 0 && rows[0]!.status === "online";+}+/*** Safety-net used by the DO's alarm live-WS branch. If we observe a live* community-machine socket for a machine whose row is stale-offline (e.g.diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.tsindex 360139b42..ec4e1415a 100644--- a/src/shared/src/db/queries/community/member.ts+++ b/src/shared/src/db/queries/community/member.ts@@ -43,7 +43,8 @@ export async function updateRole(db: Database, memberId: string, role: string) {export async function listMembers(db: Database, serverId: string) {// deletedAt filter — a bot (or a soft-deleted human) is hidden from every// member list. History surfaces still hydrate cached name/avatar via- // `getUsersByIds` without excludeDeleted, so tombstone rendering still works.+ // `getUsersByIds` (which never filters `deletedAt`), so tombstone rendering+ // still works.// Return type MUST NOT include isBot/ownerUserId — the route response// projection is responsible for owner-scoped `isBot` gating.return db@@ -59,6 +60,7 @@ export async function listMembers(db: Database, serverId: string) {userImage: user.image,userIsBot: user.isBot,userOwnerUserId: user.ownerUserId,+ discriminator: user.discriminator,}).from(communityServerMember).innerJoin(user, eq(communityServerMember.userId, user.id))@@ -146,6 +148,7 @@ export async function listMembersPaginated(userImage: string | null;userIsBot: boolean;userOwnerUserId: string | null;+ discriminator: string | null;}>;hasMore: boolean;cursor: { joinedAt: string; id: string } | undefined;@@ -184,6 +187,7 @@ export async function listMembersPaginated(userImage: user.image,userIsBot: user.isBot,userOwnerUserId: user.ownerUserId,+ discriminator: user.discriminator,}).from(communityServerMember).innerJoin(user, eq(communityServerMember.userId, user.id))@@ -231,6 +235,7 @@ export async function searchMembers(userName: user.name,userEmail: user.email,userImage: user.image,+ discriminator: user.discriminator,}).from(communityServerMember).innerJoin(user, eq(communityServerMember.userId, user.id))diff --git a/src/shared/src/db/queries/user.ts b/src/shared/src/db/queries/user.tsindex 76007b481..796d2e2eb 100644--- a/src/shared/src/db/queries/user.ts+++ b/src/shared/src/db/queries/user.ts@@ -4,6 +4,10 @@ import { user } from "../schema";import type { Database } from "../index";import { escapeLikePattern } from "../../utils/sql-like";import { computeDiscriminator } from "../../lib/discriminator";+import { isUniqueConstraintError } from "../../utils/db-errors";++/** Bounded retry ceiling for `withUniqueDiscriminator`/`probeAvailableDiscriminator` salting. */+const MAX_DISCRIMINATOR_ATTEMPTS = 5;// ─── Column projections ──────────────────────────────────────────────────────//@@ -55,48 +59,53 @@ export type InternalUserFields = {export type InternalUser = PublicUser & InternalUserFields;-// ─── Caller audit (as of 2026-07-06) ────────────────────────────────────────-//-// `excludeDeleted` defaults to `false` for backward compatibility — flipping-// the default would silently break admin, session, and history-hydration-// paths. Every current caller is enumerated below with its decision:-//-// getUser:-// - api/me → false (own row, keep)-// - api/community/dm (target lookup) → true (listing surface)-// - api/community/users/[id]/block/profile → true (public surface)-// - api/community/friends/request → true (must not friend deleted users)-// - api/community/channels/.../posts (create) → false (self hydration)-// - services/email-dispatch, calendar, payload → false (identity lookup)+// ─── Public vs. self lookups (as of 2026-07-09) ─────────────────────────────//-// getUsersByIds:-// - channel threads/posts creator hydration → false (history, tombstone renders)+// Every lookup below is one of exactly two kinds, and the function name is+// now the only contract — there is no boolean flag left for a caller to+// forget to pass://-// getUserByEmail:-// - (Better-Auth adapter path, indirect) → false+// - "Public" lookups (`getUserPublic`, `getUserByNameCaseInsensitive`,+// `getUserByNameAndDiscriminator`, `searchUsersByName`) always exclude+// soft-deleted rows. Used to resolve *someone else's* identity from a+// public-facing surface (profile, block, search, friend-request-by-+// username, DM-ref resolution) — a tombstoned account must never appear+// live on any of these.+// - "Self" lookups (`getUserSelf`, `getUsersByIds`, `getUserByEmail`) never+// filter `deletedAt`. Used for the caller's own row, or for hydrating+// already-known ids/emails from an internal/identity/history context+// (own profile, own post/DM creation, Better-Auth adapter, email+// dispatch, calendar, task payload building, tombstone rendering in+// channel history) — none of these are "is this account still live"+// checks, so there is nothing to filter.//-// getUserByNameCaseInsensitive / searchUsersByName:-// - api/community/friends/request (username) → true (send to live users only)-// - api/community/users/search → true (user picker surface)-//-// The call-sites above are updated to pass `{ excludeDeleted: true }` where-// the plan requires filtering deleted users. All others rely on the default.+// This previously lived behind a shared `excludeDeleted?: boolean` option+// with a `false` default. Two real call sites (`users/[userId]/profile`,+// `users/[userId]/block`) silently relied on that default and rendered a+// soft-deleted account as if it were live; `users/search` had the same bug+// via `searchUsersByName`. Splitting into named functions with no option+// closes that hole structurally instead of asking every future caller to+// remember a flag.-function withDeletedFilter(condition: unknown, excludeDeleted: boolean) {- if (!excludeDeleted) return condition as any;- return and(condition as any, isNull(user.deletedAt));+export async function getUserPublic(+ db: Database,+ id: string+): Promise<PublicUser | null> {+ const rows = await db+ .select(publicUserColumns)+ .from(user)+ .where(and(eq(user.id, id), isNull(user.deletedAt)));+ return (rows[0] as PublicUser | undefined) ?? null;}-export async function getUser(+export async function getUserSelf(db: Database,- id: string,- opts?: { excludeDeleted?: boolean }+ id: string): Promise<PublicUser | null> {- const excludeDeleted = opts?.excludeDeleted === true;const rows = await db.select(publicUserColumns).from(user)- .where(withDeletedFilter(eq(user.id, id), excludeDeleted));+ .where(eq(user.id, id));return (rows[0] as PublicUser | undefined) ?? null;}@@ -111,57 +120,54 @@ export async function getUserInternal(return (rows[0] as InternalUser | undefined) ?? null;}+/** Self/internal — history + tombstone rendering (channel threads/posts creator hydration). */export async function getUsersByIds(db: Database,- ids: string[],- opts?: { excludeDeleted?: boolean }+ ids: string[]): Promise<PublicUser[]> {if (ids.length === 0) return [];- const excludeDeleted = opts?.excludeDeleted === true;return db.select(publicUserColumns).from(user)- .where(withDeletedFilter(inArray(user.id, ids), excludeDeleted)) as Promise<PublicUser[]>;+ .where(inArray(user.id, ids)) as Promise<PublicUser[]>;}+/** Self/internal — Better-Auth adapter path. */export async function getUserByEmail(db: Database,- email: string,- opts?: { excludeDeleted?: boolean }+ email: string): Promise<PublicUser | null> {- const excludeDeleted = opts?.excludeDeleted === true;const rows = await db.select(publicUserColumns).from(user)- .where(withDeletedFilter(eq(user.email, email), excludeDeleted));+ .where(eq(user.email, email));return (rows[0] as PublicUser | undefined) ?? null;}+/** Public — bare-name fallback path (e.g. friend-request-by-username with no `#tag`). */export async function getUserByNameCaseInsensitive(db: Database,- name: string,- opts?: { excludeDeleted?: boolean }+ name: string): Promise<PublicUser | null> {- const excludeDeleted = opts?.excludeDeleted === true;const rows = await db.select(publicUserColumns).from(user)- .where(withDeletedFilter(like(user.name, name), excludeDeleted));+ .where(and(like(user.name, name), isNull(user.deletedAt)));return (rows[0] as PublicUser | undefined) ?? null;}+/** Public — user picker / add-friend search surface. Always excludes deleted rows. */export async function searchUsersByName(db: Database,name: string,opts?: {excludeUserId?: string;limit?: number;- excludeDeleted?: boolean;/** When set, filter to an exact name + discriminator match (`name#0042`). */discriminator?: string;}): Promise<PublicUser[]> {- const conditions: any[] = [];+ const conditions: any[] = [isNull(user.deletedAt)];if (opts?.discriminator !== undefined) {// Exact match — used by the `name#0042` add-friend search path.conditions.push(eq(user.name, name));@@ -173,9 +179,6 @@ export async function searchUsersByName(if (opts?.excludeUserId) {conditions.push(ne(user.id, opts.excludeUserId));}- if (opts?.excludeDeleted) {- conditions.push(isNull(user.deletedAt));- }return db.select(publicUserColumns).from(user)@@ -183,6 +186,93 @@ export async function searchUsersByName(.limit(opts?.limit ?? 20) as Promise<PublicUser[]>;}+/**+ * Exact `name#0042` lookup — case-insensitive on `name` (matching+ * `getUserByNameCaseInsensitive`'s existing behavior so a caller switching+ * from bare-name to `name#tag` lookup doesn't regress case handling), exact+ * match on `discriminator`. Used by DM-ref resolution and mention/friend+ * disambiguation, where the pair must resolve to exactly one user. Public —+ * always excludes deleted rows.+ */+export async function getUserByNameAndDiscriminator(+ db: Database,+ name: string,+ discriminator: string+): Promise<PublicUser | null> {+ const rows = await db+ .select(publicUserColumns)+ .from(user)+ .where(+ and(like(user.name, name), eq(user.discriminator, discriminator), isNull(user.deletedAt))+ )+ .limit(1);+ return (rows[0] as PublicUser | undefined) ?? null;+}++/**+ * Wrap an insert that writes `computeDiscriminator(id)` so a collision+ * against the partial unique index (`idx_user_name_discriminator`, migration+ * 0055) self-heals instead of failing the caller's whole request. Calls+ * `insertFn(discriminator)`; on `isUniqueConstraintError` retries with+ * `computeDiscriminator(id + ":" + attempt)` and a FRESH `insertFn` call+ * (the caller's `insertFn` closure re-reads the salted discriminator each+ * time — see `createUser`/`createBot`), bounded to+ * `MAX_DISCRIMINATOR_ATTEMPTS`. Throws past the bound rather than looping+ * forever — a persistent failure past a handful of attempts is almost+ * certainly not actually a discriminator collision.+ */+export async function withUniqueDiscriminator<T>(+ _db: Database,+ input: { id: string; name: string },+ insertFn: (discriminator: string) => Promise<T>+): Promise<T> {+ let lastErr: unknown;+ for (let attempt = 0; attempt < MAX_DISCRIMINATOR_ATTEMPTS; attempt++) {+ const discriminator =+ attempt === 0+ ? computeDiscriminator(input.id)+ : computeDiscriminator(`${input.id}:${attempt}`);+ try {+ return await insertFn(discriminator);+ } catch (err) {+ if (!isUniqueConstraintError(err)) throw err;+ lastErr = err;+ }+ }+ throw lastErr;+}++/**+ * Best-effort SELECT-based pre-check for callers that can't wrap their own+ * insert (Better Auth's `user.create.before` hook — the adapter inserts+ * AFTER the hook returns, so there's no insert call here to retry). Returns+ * an available discriminator, salting past a live `(name, discriminator)`+ * collision the same way `withUniqueDiscriminator` does. This is weaker than+ * `withUniqueDiscriminator`: a concurrent signup of the exact same name at+ * the exact same instant can still race past this check. The partial unique+ * index is the actual backstop for that residual window — a double-loss+ * fails Better Auth's insert, the signup surfaces a generic error, and the+ * user's retry mints a fresh id/discriminator pair. Self-healing, not+ * silently broken; not full parity with the insert-wrapped paths.+ */+export async function probeAvailableDiscriminator(+ db: Database,+ input: { id: string; name: string }+): Promise<string> {+ for (let attempt = 0; attempt < MAX_DISCRIMINATOR_ATTEMPTS; attempt++) {+ const discriminator =+ attempt === 0+ ? computeDiscriminator(input.id)+ : computeDiscriminator(`${input.id}:${attempt}`);+ const existing = await getUserByNameAndDiscriminator(db, input.name, discriminator);+ if (!existing) return discriminator;+ }+ // Ceiling exhausted — hand back the last candidate anyway; the partial+ // unique index (not this function) is what makes a true double-collision+ // impossible to persist.+ return computeDiscriminator(`${input.id}:${MAX_DISCRIMINATOR_ATTEMPTS - 1}`);+}+export async function createUser(db: Database,data: { name: string; email: string }@@ -191,16 +281,18 @@ export async function createUser(// Generate the id up-front so the discriminator (an FNV-1a hash of the id)// can be written in the same INSERT — no separate UPDATE round-trip.const id = nanoid();- const rows = await db- .insert(user)- .values({- id,- name: data.name,- email: data.email,- discriminator: computeDiscriminator(id),- })- .returning(publicUserColumns);- return rows[0] as PublicUser;+ return withUniqueDiscriminator(db, { id, name: data.name }, async (discriminator) => {+ const rows = await db+ .insert(user)+ .values({+ id,+ name: data.name,+ email: data.email,+ discriminator,+ })+ .returning(publicUserColumns);+ return rows[0] as PublicUser;+ });}/** omit a field to leave it unchanged; pass image: null to explicitly clear it. */diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.tsindex c62de46cc..9780df254 100644--- a/src/shared/src/db/schema.ts+++ b/src/shared/src/db/schema.ts@@ -6,6 +6,7 @@ import {unique,primaryKey,foreignKey,+ type AnySQLiteColumn,} from "drizzle-orm/sqlite-core";import { sql } from "drizzle-orm";import { nanoid } from "nanoid";@@ -15,10 +16,14 @@ import { TASK_TYPES } from "../constants";// Better Auth tables// ----------------------------------------------------------------------------// NOTE: `ownerUserId` FK is `ON DELETE NO ACTION` (the DB will refuse to delete-// an owner while they still have bot rows). Any future user-delete path MUST-// call `assertNoLiveBots` (see `queries/community/bot.ts`) to fail early with-// a clear error before hitting the FK.+// `ownerUserId` is a real, already-applied self-referencing FK — see+// `src/web/migrations/0050_community_bots.sql` (`ownerUserId TEXT REFERENCES+// user(id)`, no `ON DELETE` clause, so SQLite/D1 default to `NO ACTION`: the+// DB refuses to delete an owner while they still have bot rows pointing at+// them). `.references()` below is a type-level sync with that DDL, not a new+// constraint — do not generate a migration for it. Any future user-delete+// path should still call `assertNoLiveBots` (see `queries/community/bot.ts`)+// to fail early with a clear error before hitting the FK.export const user = sqliteTable("user",{@@ -30,7 +35,7 @@ export const user = sqliteTable(createdAt: text("createdAt").notNull().$defaultFn(() => new Date().toISOString()),updatedAt: text("updatedAt").notNull().$defaultFn(() => new Date().toISOString()),isBot: integer("isBot", { mode: "boolean" }).notNull().default(false),- ownerUserId: text("ownerUserId"),+ ownerUserId: text("ownerUserId").references((): AnySQLiteColumn => user.id, { onDelete: "no action" }),deletedAt: text("deletedAt"),discriminator: text("discriminator").notNull().default("0000"),},diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 40dc09845..5ca2dac32 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -459,7 +459,7 @@ export { parseIcs } from "./lib/ics-parser";export type { MeetingInfo } from "./lib/ics-parser";export { buildMimeMessage, extractAttachmentMeta, filterDownloadableAttachments } from "./lib/mime";export type { MimeAttachment, BuildMimeOptions, InboundAttachmentMeta } from "./lib/mime";-export { computeDiscriminator, parseNameAndTag } from "./lib/discriminator";+export { computeDiscriminator, parseNameAndTag, formatHandle } from "./lib/discriminator";export {addRepeatInterval,computeNextScheduledAt,diff --git a/src/shared/src/lib/discriminator.ts b/src/shared/src/lib/discriminator.tsindex 29a06f13c..e72bbd3f7 100644--- a/src/shared/src/lib/discriminator.ts+++ b/src/shared/src/lib/discriminator.ts@@ -43,3 +43,13 @@ export function parseNameAndTag(if (!name) return null;return { name, discriminator };}++/**+ * Build the canonical global-handle string, `name#0042`. The ONE place this+ * string is assembled — every call site (system prompt, `agentHandle`,+ * message wire `sender`/`latestSender`, DM refs) goes through this instead of+ * hand-rolling the template literal, so the format can't drift.+ */+export function formatHandle(name: string, discriminator: string): string {+ return `${name}#${discriminator}`;+}diff --git a/src/shared/src/runtime-config.ts b/src/shared/src/runtime-config.tsindex 8b2f9a93d..33529b7cd 100644--- a/src/shared/src/runtime-config.ts+++ b/src/shared/src/runtime-config.ts@@ -63,7 +63,12 @@ export interface RuntimeConfig {* invent these; it fills the LaunchContext from them.*/agentName?: string;- /** The agent's @mention handle (e.g. "@cindy"). */+ /**+ * The agent's global @mention handle, `@name#0042` (e.g. "@cindy#4821").+ * Every account in Alook — human or agent — has a name plus a 4-digit+ * discriminator; this is the `@`-prefixed pair, unique even when names+ * collide.+ */agentHandle?: string;/** The agent's standing instruction / role (becomes the standing prompt). */instruction?: string;diff --git a/src/shared/src/utils/community-mentions.ts b/src/shared/src/utils/community-mentions.tsindex d2826909e..b64efaa4f 100644--- a/src/shared/src/utils/community-mentions.ts+++ b/src/shared/src/utils/community-mentions.ts@@ -10,11 +10,20 @@* Identifier characters are `[A-Za-z0-9_]`, so a name ending or starting in* those plus the next-char rule covers normal punctuation, spaces, and* newlines as boundaries. Names containing whitespace are supported.+ *+ * When a candidate carries a `discriminator`, an exact `@Name#0042` match is+ * tried FIRST at each `@` site (so a channel with two "Alex"es can be+ * disambiguated), falling back to the existing longest-bare-name match when+ * no `#0042` suffix is present or it doesn't match anyone.*/+import { formatHandle } from "../lib/discriminator";+export interface MentionCandidate {userId: string;name: string;+ /** 4-digit tag (`computeDiscriminator`). Enables exact `@Name#0042` matching. */+ discriminator?: string;}/**@@ -49,7 +58,18 @@ export function extractMentionedUserIds(if (!byName.has(key)) byName.set(key, c);}const sorted = [...byName.values()].sort((a, b) => b.name.length - a.name.length);- if (sorted.length === 0) return [];++ // Exact `@Name#0042` handles, tried FIRST at each `@` site — longest-handle+ // first (mirrors the bare-name ordering). Built from ALL candidates (not+ // the de-duped-by-name map above) since a handle is already unambiguous+ // per-candidate; de-duping by name would arbitrarily drop one of the two+ // "Alex"es a handle exists specifically to disambiguate.+ const handled = candidates+ .filter((c): c is MentionCandidate & { discriminator: string } => !!c.name && !!c.discriminator)+ .map((c) => ({ candidate: c, handle: formatHandle(c.name, c.discriminator).toLowerCase() }))+ .sort((a, b) => b.handle.length - a.handle.length);++ if (sorted.length === 0 && handled.length === 0) return [];const lower = content.toLowerCase();const found = new Set<string>();@@ -64,18 +84,31 @@ export function extractMentionedUserIds(continue;}let matched: MentionCandidate | undefined;- for (const cand of sorted) {- const nameLen = cand.name.length;- const slice = lower.slice(at + 1, at + 1 + nameLen);- if (slice !== cand.name.toLowerCase()) continue;- const after = content[at + 1 + nameLen];+ let matchedLen = 0;+ for (const { candidate, handle } of handled) {+ const slice = lower.slice(at + 1, at + 1 + handle.length);+ if (slice !== handle) continue;+ const after = content[at + 1 + handle.length];if (!isBoundaryChar(after)) continue;- matched = cand;+ matched = candidate;+ matchedLen = handle.length;break;}+ if (!matched) {+ for (const cand of sorted) {+ const nameLen = cand.name.length;+ const slice = lower.slice(at + 1, at + 1 + nameLen);+ if (slice !== cand.name.toLowerCase()) continue;+ const after = content[at + 1 + nameLen];+ if (!isBoundaryChar(after)) continue;+ matched = cand;+ matchedLen = nameLen;+ break;+ }+ }if (matched) {found.add(matched.userId);- i = at + 1 + matched.name.length;+ i = at + 1 + matchedLen;} else {i = at + 1;}diff --git a/src/shared/test/community-cli-contract.test.ts b/src/shared/test/community-cli-contract.test.tsindex df626e5d9..302901b52 100644--- a/src/shared/test/community-cli-contract.test.ts+++ b/src/shared/test/community-cli-contract.test.ts@@ -19,11 +19,38 @@ describe("parseRef", () => {});it('parses "/.dm/user_123" as a DM ref (server === DM_SERVER)', () => {+ // Legacy/no-discriminator id form: no "#" in the segment, so it round-trips+ // through the PARSER unchanged — see Design §1. Resolution (not parsing) is+ // what changes once `resolve-ref.ts` requires a `name#0042` handle; this+ // parser-level case documents that the shape itself still parses fine.const parsed = parseRef("/.dm/user_123");expect(parsed).toEqual({ server: DM_SERVER, channel: "user_123" });expect(parsed.server).toBe(".dm");});+ it('parses "/.dm/gusye#1231" as a bare handle (no seq stripped)', () => {+ expect(parseRef("/.dm/gusye#1231")).toEqual({ server: DM_SERVER, channel: "gusye#1231" });+ });++ it('parses "/.dm/gusye#1231#42" as a pinned message on a handle peer', () => {+ expect(parseRef("/.dm/gusye#1231#42")).toEqual({ server: DM_SERVER, channel: "gusye#1231", seq: 42 });+ });++ it('parses "/.dm/gusye#1231/#42" as a thread rooted on a handle peer', () => {+ expect(parseRef("/.dm/gusye#1231/#42")).toEqual({+ server: DM_SERVER,+ channel: "gusye#1231",+ threadRootSeq: 42,+ });+ });++ it('parses "/.dm/a#b#0042" (name itself contains "#") with the documented ambiguity: peer="a#b", seq=42, NOT peer="a#b#0042"', () => {+ // Known, accepted footgun from the Breaking Changes section — asserting+ // it here means a future change to this behavior is a deliberate diff,+ // not a silent regression.+ expect(parseRef("/.dm/a#b#0042")).toEqual({ server: DM_SERVER, channel: "a#b", seq: 42 });+ });+it("throws when the ref doesn't start with /", () => {expect(() => parseRef("studio/general")).toThrow();});diff --git a/src/shared/test/community/wake-dispatch-build.test.ts b/src/shared/test/community/wake-dispatch-build.test.tsindex c364fbbfd..c8c629b3d 100644--- a/src/shared/test/community/wake-dispatch-build.test.ts+++ b/src/shared/test/community/wake-dispatch-build.test.ts@@ -42,6 +42,7 @@ const BOT_READY = {state: "ready" as const,botUserId: "bot_1",name: "zoe",+ discriminator: "0042",machineId: "machine_1",runtime: "claude",};@@ -82,7 +83,7 @@ describe("buildUnreadWakeCommand", () => {});expect(typeof result.command.launchId).toBe("string");expect(result.command.launchId.length).toBeGreaterThan(0);- expect(result.command).toMatchObject({ config: { runtime: "claude" } });+ expect(result.command).toMatchObject({ config: { runtime: "claude", agentHandle: "@zoe#0042" } });// Every downstream query is scoped with the SAME messageId/botUserId/scope.expect(mockGetWakeMessageScopeById).toHaveBeenCalledWith(fakeDb, "msg_1");@@ -93,9 +94,13 @@ describe("buildUnreadWakeCommand", () => {});it("ready: resolves a DM scope when the message has no channelId", async () => {+ // "/.dm/@gustavo" was never actually valid production output — prod never+ // puts "@" in a ref segment. `resolveUnreadNoticeChannel` now produces a+ // bare `name#0042` handle segment (mocked here, but shaped like the real+ // thing) since DM refs address peers by handle, not raw user id.seedHappyPath({message: { channelId: null, dmConversationId: "dm_1" },- channel: "/.dm/@gustavo",+ channel: "/.dm/gustavo#0042",});const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });@@ -104,7 +109,7 @@ describe("buildUnreadWakeCommand", () => {if (result.state !== "ready") throw new Error("expected ready");expect(result.command.unreadNotice).toEqual({kind: "unread_notice",- channel: "/.dm/@gustavo",+ channel: "/.dm/gustavo#0042",latestSeq: 7,});expect(mockCanBotReadWakeScope).toHaveBeenCalledWith(fakeDb, "bot_1", { dmConversationId: "dm_1" });diff --git a/src/shared/test/community/wake-dispatch-one.test.ts b/src/shared/test/community/wake-dispatch-one.test.tsindex 3e11dda4b..871c7075a 100644--- a/src/shared/test/community/wake-dispatch-one.test.ts+++ b/src/shared/test/community/wake-dispatch-one.test.ts@@ -42,6 +42,7 @@ const BOT_READY = {state: "ready" as const,botUserId: "bot_1",name: "zoe",+ discriminator: "0042",machineId: "machine_1",runtime: "claude",};diff --git a/src/shared/test/queries/community-agent-inbox.test.ts b/src/shared/test/queries/community-agent-inbox.test.tsindex 8c12282a3..014ace84e 100644--- a/src/shared/test/queries/community-agent-inbox.test.ts+++ b/src/shared/test/queries/community-agent-inbox.test.ts@@ -69,17 +69,18 @@ describe("toAgentMessages", () => {// 1. resolveScopeRefs' `channels` query (channelIds=[ch_1])// 2. toAgentMessages' own author-name query (outer Promise.all's 2nd slot)// 3. resolveScopeRefs' `servers` query (serverIds=[srv_1]; parentChannelIds/- // parentMessageIds/dmIds are all empty here, so those selects are skipped)+ // parentMessageIds/dmIds are all empty here, so those selects — including+ // the DM-peer lookup — are skipped)const db = createSequentialDb([[{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],- [{ id: "u_1", name: "Alice" }],+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],[{ id: "srv_1", name: "studio" }],]);const [msg] = await agentInbox.toAgentMessages(db, [rawMsg()], "viewer_1");expect(msg).toEqual({seq: formatSeq(1),channel: formatRef({ server: "studio", channel: "general" }),- sender: "@Alice",+ sender: "@Alice#1234",content: { text: "hello" },time: "2026-07-01T00:00:00.000Z",});@@ -104,20 +105,24 @@ describe("toAgentMessages", () => {expect(msg!.channel).toBe(formatRef({ server: "studio", channel: "general", threadRootSeq: 7 }));});- it("hydrates a DM message, addressing the OTHER party relative to viewerId", async () => {+ it("hydrates a DM message, addressing the OTHER party (as a name#0042 handle) relative to viewerId", async () => {// Call order: 1. dms query (channels query skipped, channelIds empty),- // 2. author names (parentChannels/servers/parentMessages all skipped —- // no channel scopes at all).+ // 2. author names (outer Promise.all's 2nd slot — evaluated synchronously+ // right after resolveScopeRefs' own internal await yields), 3. the DM-peer+ // name+discriminator lookup (resolveScopeRefs, after its first internal+ // Promise.all resolves — parentChannels/servers/parentMessages stay+ // skipped, no channel scopes at all).const db = createSequentialDb([[{ id: "dm_1", user1Id: "viewer_1", user2Id: "peer_1" }],- [{ id: "u_1", name: "Alice" }],+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],+ [{ id: "peer_1", name: "Bob", discriminator: "9999" }],]);const [msg] = await agentInbox.toAgentMessages(db,[rawMsg({ channelId: null, dmConversationId: "dm_1" })],"viewer_1");- expect(msg!.channel).toBe(formatRef({ server: DM_SERVER, channel: "peer_1" }));+ expect(msg!.channel).toBe(formatRef({ server: DM_SERVER, channel: "Bob#9999" }));});it("falls back to /unknown/<key> when the scope can't be resolved (e.g. deleted channel)", async () => {@@ -145,11 +150,11 @@ describe("toAgentMessage", () => {it("returns the single hydrated message (convenience wrapper)", async () => {const db = createSequentialDb([[{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],- [{ id: "u_1", name: "Alice" }],+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],[{ id: "srv_1", name: "studio" }],]);const msg = await agentInbox.toAgentMessage(db, rawMsg(), "viewer_1");- expect(msg.sender).toBe("@Alice");+ expect(msg.sender).toBe("@Alice#1234");});});@@ -218,6 +223,33 @@ describe("getLatestUnreadMessageForAgent", () => {});});+describe("resolveUnreadNoticeChannel", () => {+ it("DM scope: produces a handle-based ref (/.dm/name#0042), not a raw peerId", async () => {+ // Call order: 1. the dm-conversation row, 2. the peer's name+discriminator.+ const db = createSequentialDb([+ [{ id: "dm_1", user1Id: "bot_1", user2Id: "peer_1" }],+ [{ name: "Bob", discriminator: "9999" }],+ ]);+ const result = await agentInbox.resolveUnreadNoticeChannel(db, { dmConversationId: "dm_1" }, "bot_1");+ expect(result).toBe(formatRef({ server: DM_SERVER, channel: "Bob#9999" }));+ });++ it("DM scope: null when the dm conversation itself doesn't resolve", async () => {+ const db = createSequentialDb([[]]);+ const result = await agentInbox.resolveUnreadNoticeChannel(db, { dmConversationId: "dm_gone" }, "bot_1");+ expect(result).toBeNull();+ });++ it("DM scope: null (never a bare-peerId placeholder) when the peer no longer resolves to a name+discriminator", async () => {+ const db = createSequentialDb([+ [{ id: "dm_1", user1Id: "bot_1", user2Id: "peer_1" }],+ [], // peer row missing (e.g. hard-deleted)+ ]);+ const result = await agentInbox.resolveUnreadNoticeChannel(db, { dmConversationId: "dm_1" }, "bot_1");+ expect(result).toBeNull();+ });+});+describe("getInboxSnapshotForAgent", () => {it("returns [] and skips the user-name lookup when there's no pending unread", async () => {const db = createSequentialDb([[]]);@@ -249,8 +281,8 @@ describe("getInboxSnapshotForAgent", () => {},],[- { id: "u_1", name: "Alice" },- { id: "u_2", name: "Bob" },+ { id: "u_1", name: "Alice", discriminator: "1234" },+ { id: "u_2", name: "Bob", discriminator: "5678" },],]);const result = await agentInbox.getInboxSnapshotForAgent(db, "bot_1");@@ -261,7 +293,7 @@ describe("getInboxSnapshotForAgent", () => {pendingCount: 3,firstPendingSeq: 5,latestSeq: 7,- latestSender: "@Alice",+ latestSender: "@Alice#1234",hasMention: true,},{@@ -270,7 +302,7 @@ describe("getInboxSnapshotForAgent", () => {pendingCount: 1,firstPendingSeq: 9,latestSeq: 9,- latestSender: "@Bob",+ latestSender: "@Bob#5678",hasMention: false,},]);@@ -319,17 +351,20 @@ describe("toInboxRows", () => {},];// Call order: 1. channels query (channelIds=[thread_1]), 2. dms query- // (dmIds=[dm_1]), 3. parentChannels, 4. servers, 5. parentMessages.+ // (dmIds=[dm_1]), 3. DM-peer name+discriminator lookup (dmPeerIds=[peer_1],+ // awaited right after the first internal Promise.all resolves — NOT part+ // of that Promise.all itself), 4. parentChannels, 5. servers, 6. parentMessages.const db = createSequentialDb([[{ id: "thread_1", name: "thread-x", serverId: "srv_1", parentChannelId: "ch_parent", parentMessageId: "m_root" }],[{ id: "dm_1", user1Id: "viewer_1", user2Id: "peer_1" }],+ [{ id: "peer_1", name: "Bob", discriminator: "9999" }],[{ id: "ch_parent", name: "general" }],[{ id: "srv_1", name: "studio" }],[{ id: "m_root", seq: 3 }],]);const result = await agentInbox.toInboxRows(db, rows, "viewer_1");expect(result[0]).toMatchObject({- channel: formatRef({ server: DM_SERVER, channel: "peer_1" }),+ channel: formatRef({ server: DM_SERVER, channel: "Bob#9999" }),flags: ["dm", "mention"],});expect(result[1]).toMatchObject({diff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.tsindex 96e6abb5c..03b683d84 100644--- a/src/shared/test/queries/community-bot.test.ts+++ b/src/shared/test/queries/community-bot.test.ts@@ -87,6 +87,72 @@ describe("createBot", () => {expect(botUser.discriminator).toMatch(/^\d{4}$/)expect(db.batch).toHaveBeenCalledOnce()})++ it("on a discriminator collision, retries the WHOLE 3-statement batch with a salted discriminator", async () => {+ // Every statement in the batch (`user`, `communityBotBinding`,+ // `communityUserProfile`) gets rebuilt per attempt, so all three of an+ // attempt's `.values(...)` payloads must carry the SAME (salted)+ // discriminator that attempt used — not just the user row.+ const userValues: Array<{ id: string; discriminator: string }> = []+ const uniqueErr = Object.assign(new Error("UNIQUE constraint failed: user.name, user.discriminator"), {+ code: "SQLITE_CONSTRAINT_UNIQUE",+ })+ const batch = vi.fn().mockRejectedValueOnce(uniqueErr).mockResolvedValueOnce([])+ const db = {+ insert: vi.fn(() => ({+ values: vi.fn((values: unknown) => {+ userValues.push(values as { id: string; discriminator: string })+ return {+ onConflictDoUpdate: vi.fn(() => ({ __stmt: "profile" })),+ }+ }),+ })),+ batch,+ }++ const result = await q.createBot(db as never, {+ ownerId: "owner_1",+ name: "helper",+ description: "does things",+ machineId: "machine_1",+ runtime: "codex",+ })++ // 2 attempts × 3 statements (user, binding, profile) each pushing values.+ expect(userValues).toHaveLength(6)+ expect(batch).toHaveBeenCalledTimes(2)++ const botId = result.botId+ const firstAttemptDiscriminator = userValues[0]!.discriminator+ const secondAttemptDiscriminator = userValues[3]!.discriminator+ expect(firstAttemptDiscriminator).toBe(computeDiscriminator(botId))+ expect(secondAttemptDiscriminator).toBe(computeDiscriminator(`${botId}:1`))+ expect(secondAttemptDiscriminator).not.toBe(firstAttemptDiscriminator)++ // The winning (second) attempt's discriminator is what's returned.+ expect(result.discriminator).toBe(secondAttemptDiscriminator)+ })++ it("rethrows a non-unique-constraint db.batch failure without retrying", async () => {+ const otherErr = new Error("D1_ERROR: disk I/O error")+ const db = {+ insert: vi.fn(() => ({+ values: vi.fn(() => ({ onConflictDoUpdate: vi.fn(() => ({ __stmt: "profile" })) })),+ })),+ batch: vi.fn().mockRejectedValue(otherErr),+ }++ await expect(+ q.createBot(db as never, {+ ownerId: "owner_1",+ name: "helper",+ description: "does things",+ machineId: "machine_1",+ runtime: "codex",+ }),+ ).rejects.toBe(otherErr)+ expect(db.batch).toHaveBeenCalledOnce()+ })})describe("bot limits", () => {diff --git a/src/shared/test/queries/community-friendship.test.ts b/src/shared/test/queries/community-friendship.test.tsindex b4b005772..19fe53fcd 100644--- a/src/shared/test/queries/community-friendship.test.ts+++ b/src/shared/test/queries/community-friendship.test.ts@@ -1,53 +1,113 @@import { describe, it, expect, vi } from "vitest";import * as q from "../../src/db/queries/community/friendship";+import { user } from "../../src/db/schema";-function createSelectMock(rows: unknown[]) {- const chain: any = {};- chain.select = vi.fn(() => chain);- chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve(rows));- return chain;+/**+ * `getFriendUserIds` now issues two parallel selects — the real+ * `communityFriendship` rows, and the owner↔own-bot implicit-friendship rows+ * off the `user` table (see the function's doc comment). Route each mock+ * `.from(table)` to its own canned rows so the two queries don't bleed into+ * each other.+ */+function createDb(opts: { friendshipRows?: unknown[]; selfBotRows?: unknown[] } = {}) {+ const friendshipRows = opts.friendshipRows ?? [];+ const selfBotRows = opts.selfBotRows ?? [];+ const selectCalls: unknown[] = [];+ const whereCalls: unknown[] = [];+ const db: any = {+ select: vi.fn((cols: unknown) => {+ selectCalls.push(cols);+ const chain: any = {};+ chain.from = vi.fn((table: unknown) => {+ chain.where = vi.fn((cond: unknown) => {+ whereCalls.push(cond);+ return Promise.resolve(table === user ? selfBotRows : friendshipRows);+ });+ return chain;+ });+ return chain;+ }),+ };+ db.__selectCalls = selectCalls;+ db.__whereCalls = whereCalls;+ return db;}describe("getFriendUserIds", () => {it("returns the other side's id when the caller is the requester", async () => {- const db = createSelectMock([- { requesterId: "u_me", addresseeId: "u_friend1" },- ]);+ const db = createDb({ friendshipRows: [{ requesterId: "u_me", addresseeId: "u_friend1" }] });const result = await q.getFriendUserIds(db, "u_me");expect(result).toEqual(["u_friend1"]);});it("returns the other side's id when the caller is the addressee", async () => {- const db = createSelectMock([- { requesterId: "u_friend2", addresseeId: "u_me" },- ]);+ const db = createDb({ friendshipRows: [{ requesterId: "u_friend2", addresseeId: "u_me" }] });const result = await q.getFriendUserIds(db, "u_me");expect(result).toEqual(["u_friend2"]);});it("resolves the correct side independently per row when both directions are mixed", async () => {- const db = createSelectMock([- { requesterId: "u_me", addresseeId: "u_friend1" },- { requesterId: "u_friend2", addresseeId: "u_me" },- ]);+ const db = createDb({+ friendshipRows: [+ { requesterId: "u_me", addresseeId: "u_friend1" },+ { requesterId: "u_friend2", addresseeId: "u_me" },+ ],+ });const result = await q.getFriendUserIds(db, "u_me");expect(result.sort()).toEqual(["u_friend1", "u_friend2"]);});- it("returns [] when the user has no accepted friendships", async () => {- const db = createSelectMock([]);+ it("returns [] when the user has no accepted friendships and owns/is no bot", async () => {+ const db = createDb();const result = await q.getFriendUserIds(db, "u_me");expect(result).toEqual([]);});- it("only queries rows filtered by status=accepted (pending/blocked excluded at the query layer)", async () => {- // The mock DB can't express SQL predicates, but we can pin that the- // query issues exactly one `where` — the status/direction filter — so a- // future edit can't silently add a second unfiltered fetch-and-merge.- const db = createSelectMock([]);+ it("issues exactly one `where` per sub-query (real friendships + self-bot), no extra unfiltered fetch", async () => {+ const db = createDb();await q.getFriendUserIds(db, "u_me");- expect(db.where).toHaveBeenCalledTimes(1);- expect(db.select).toHaveBeenCalledTimes(1);+ expect(db.__whereCalls).toHaveLength(2);+ expect(db.select).toHaveBeenCalledTimes(2);+ });++ // Owner↔own-bot implicit friendship — see `areFriends`/`listFriends`: no+ // real `communityFriendship` row exists for the pair, but `getFriendUserIds`+ // must surface it too, since its only two real callers (WS presence+ // fan-out, `/friends/presence` bulk-check) both need a bot's presence to+ // reach its owner and vice versa.+ it("includes the owner when called with a bot's own id", async () => {+ const db = createDb({ selfBotRows: [{ id: "bot-1", ownerUserId: "owner-1" }] });+ const result = await q.getFriendUserIds(db, "bot-1");+ expect(result).toEqual(["owner-1"]);+ });++ it("includes every owned bot when called with the owner's id", async () => {+ const db = createDb({+ selfBotRows: [+ { id: "bot-1", ownerUserId: "owner-1" },+ { id: "bot-2", ownerUserId: "owner-1" },+ ],+ });+ const result = await q.getFriendUserIds(db, "owner-1");+ expect(result.sort()).toEqual(["bot-1", "bot-2"]);+ });++ it("merges real friends and self-bot links without duplicates", async () => {+ const db = createDb({+ friendshipRows: [{ requesterId: "owner-1", addresseeId: "friend-x" }],+ selfBotRows: [{ id: "bot-1", ownerUserId: "owner-1" }],+ });+ const result = await q.getFriendUserIds(db, "owner-1");+ expect(new Set(result)).toEqual(new Set(["friend-x", "bot-1"]));+ expect(result).toHaveLength(2);+ });++ it("dedupes when a bot is somehow also a real accepted-friendship row", async () => {+ const db = createDb({+ friendshipRows: [{ requesterId: "owner-1", addresseeId: "bot-1" }],+ selfBotRows: [{ id: "bot-1", ownerUserId: "owner-1" }],+ });+ const result = await q.getFriendUserIds(db, "owner-1");+ expect(result).toEqual(["bot-1"]);});});diff --git a/src/shared/test/queries/community-machine.test.ts b/src/shared/test/queries/community-machine.test.tsindex de3d15150..26823cc3b 100644--- a/src/shared/test/queries/community-machine.test.ts+++ b/src/shared/test/queries/community-machine.test.ts@@ -214,6 +214,43 @@ describe("claimPairingToken", () => {});});+describe("isBotOnline", () => {+ function makeJoinChain(rows: unknown[]) {+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.innerJoin = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ chain.limit = vi.fn(() => Promise.resolve(rows));+ return chain;+ }++ it("returns true when the bound machine is online", async () => {+ const chain = makeJoinChain([{ status: "online" }]);+ expect(await q.isBotOnline(chain, "bot_1")).toBe(true);+ });++ it("returns false when the bound machine is offline", async () => {+ const chain = makeJoinChain([{ status: "offline" }]);+ expect(await q.isBotOnline(chain, "bot_1")).toBe(false);+ });++ it("returns false when the bot has no machine binding", async () => {+ const chain = makeJoinChain([]);+ expect(await q.isBotOnline(chain, "bot_1")).toBe(false);+ });++ it("joins the user table so a soft-deleted bot's row is excluded (mirrors listBotsForMachine's guard)", async () => {+ // A real DB would filter the join itself; this mock always returns the+ // row, so the assertion is structural — the query must join `user` at+ // all, not just `communityBotBinding`/`communityMachine`, so a+ // `deletedAt` filter has somewhere to apply.+ const chain = makeJoinChain([{ status: "online" }]);+ await q.isBotOnline(chain, "bot_1");+ expect(chain.innerJoin).toHaveBeenCalledTimes(2);+ });+});+describe("findActiveToken", () => {it("returns null when no row matches", async () => {const chain: any = {};@@ -475,6 +512,38 @@ describe("upsertMachineByMachineId", () => {const res = await q.upsertMachineByMachineId(chain, "u_1", "cm_1", {});expect(res?.priorStatus).toBe("online");});++ it("leaves status/lastSeenAt untouched when markOnline=false (HTTP /activate reconnect)", async () => {+ // /activate runs before the daemon's WS connects — it must not flip+ // status itself, or the later `ready`-frame's `priorStatus !== 'online'`+ // guard would wrongly see 'online' and skip the broadcast (incl. bot+ // presence fan-out). Only the real ready-frame call (default+ // markOnline=true) may set status.+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ chain.limit = vi.fn(() => Promise.resolve([priorRow]));+ chain.update = vi.fn(() => chain);+ chain.set = vi.fn(() => chain);+ chain.returning = vi.fn(() => Promise.resolve([priorRow]));+ const res = await q.upsertMachineByMachineId(+ chain,+ "u_1",+ "cm_1",+ { hostname: "host2" },+ { markOnline: false }+ );+ expect(chain.set).toHaveBeenCalledWith(+ expect.not.objectContaining({ status: expect.anything() })+ );+ const setArg = chain.set.mock.calls[0][0];+ expect(setArg).not.toHaveProperty("status");+ expect(setArg).not.toHaveProperty("lastSeenAt");+ // priorStatus still reflects the pre-upsert row (offline), unaffected+ // by markOnline — it's purely about what gets WRITTEN.+ expect(res?.priorStatus).toBe("offline");+ });});// ---------------------------------------------------------------------------@@ -709,6 +778,15 @@ describe("activateMachineCredential — success paths", () => {// Update was called at least twice — once for machine, once for revoking// prior credentials.expect(chain.update).toHaveBeenCalled();+ // Reconnect activation must not flip status/lastSeenAt itself — that's+ // reserved for the real WS `ready` frame (see upsertMachineByMachineId's+ // markOnline doc comment). Find the machine-row `.set()` call (the one+ // touching `hostname`) and assert it carries no status.+ const machineSetCall = chain.set.mock.calls.find(+ (args: any[]) => args[0] && "hostname" in args[0]+ );+ expect(machineSetCall?.[0]).not.toHaveProperty("status");+ expect(machineSetCall?.[0]).not.toHaveProperty("lastSeenAt");});it("leaves the token revoked (not rolled back) when the reconnect target machine is missing", async () => {diff --git a/src/shared/test/queries/community-member.test.ts b/src/shared/test/queries/community-member.test.tsindex abbe3ff96..2374acb59 100644--- a/src/shared/test/queries/community-member.test.ts+++ b/src/shared/test/queries/community-member.test.ts@@ -81,6 +81,7 @@ function buildMember(i: number) {userName: `User ${i}`,userEmail: `u${i}@x.com`,userImage: null,+ discriminator: String(i).padStart(4, "0"),};}@@ -164,6 +165,12 @@ describe("listMembersPaginated", () => {await memberQueries.listMembersPaginated(db, "srv_1", {});expect(db.limit).toHaveBeenCalledWith(DEFAULT_MEMBERS_PAGE_SIZE + 1);});++ it("rows carry the user's discriminator", async () => {+ const db = createSelectMock([buildMember(1), buildMember(2)]);+ const result = await memberQueries.listMembersPaginated(db, "srv_1", { limit: 5 });+ expect(result.members.map((r) => r.discriminator)).toEqual(["0001", "0002"]);+ });});describe("searchMembers", () => {@@ -244,6 +251,15 @@ describe("searchMembers", () => {const res = await memberQueries.searchMembers(db, "srv_1", "Ali");expect(res.map((r) => r.id)).toEqual(["m1", "m2"]);});++ it("rows carry the user's discriminator", async () => {+ const db = createSearchMock([+ { id: "m1", userName: "Alex", discriminator: "0001" },+ { id: "m2", userName: "Alex", discriminator: "0002" },+ ]);+ const res = await memberQueries.searchMembers(db, "srv_1", "Alex");+ expect(res.map((r) => r.discriminator)).toEqual(["0001", "0002"]);+ });});describe("getMemberById", () => {diff --git a/src/shared/test/queries/user.test.ts b/src/shared/test/queries/user.test.tsindex 8c1e62799..3a5e6cc05 100644--- a/src/shared/test/queries/user.test.ts+++ b/src/shared/test/queries/user.test.ts@@ -13,16 +13,68 @@ function createSelectMock(rows: any[]) {return chain;}+/** Like `createSelectMock`, but `.where(...)` returns a chainable (for the `.limit(1)` callers, e.g. `getUserByNameAndDiscriminator`). */+function createSelectLimitMock(rows: any[]) {+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ chain.limit = vi.fn(() => Promise.resolve(rows));+ return chain;+}++/**+ * Drizzle's built SQL condition objects are self-referencing (a column's+ * `.table` points back at the table, which lists every other column again —+ * including ones the condition never touches), so `JSON.stringify` throws,+ * and a naive walk would false-positive on any column purely because it's a+ * sibling on the same table. Walk the object graph by hand, tracking+ * visited nodes and skipping `.table` back-references, looking for a+ * drizzle column/field whose `name` is `columnName` — reachable only via an+ * actual queryChunks entry the condition builder produced.+ */+function conditionReferencesColumn(node: unknown, columnName: string, seen = new Set<unknown>()): boolean {+ if (node === null || typeof node !== "object") return false;+ if (seen.has(node)) return false;+ seen.add(node);+ if ((node as { name?: unknown }).name === columnName) return true;+ for (const [key, value] of Object.entries(node as Record<string, unknown>)) {+ if (key === "table") continue;+ if (Array.isArray(value)) {+ if (value.some((v) => conditionReferencesColumn(v, columnName, seen))) return true;+ } else if (conditionReferencesColumn(value, columnName, seen)) {+ return true;+ }+ }+ return false;+}+describe("user exports", () => {- it("exports getUser", () => { expect(typeof userQueries.getUser).toBe("function"); });+ it("exports getUserPublic", () => { expect(typeof userQueries.getUserPublic).toBe("function"); });+ it("exports getUserSelf", () => { expect(typeof userQueries.getUserSelf).toBe("function"); });it("exports getUserByEmail", () => { expect(typeof userQueries.getUserByEmail).toBe("function"); });it("exports createUser", () => { expect(typeof userQueries.createUser).toBe("function"); });it("exports updateUser", () => { expect(typeof userQueries.updateUser).toBe("function"); });});-describe("getUser", () => {- it("returns null when not found", async () => { expect(await userQueries.getUser(createSelectMock([]), "x")).toBeNull(); });- it("returns user", async () => { const u = { id: "u_1" }; expect(await userQueries.getUser(createSelectMock([u]), "u_1")).toEqual(u); });+describe("getUserPublic", () => {+ it("returns null when not found", async () => { expect(await userQueries.getUserPublic(createSelectMock([]), "x")).toBeNull(); });+ it("returns user", async () => { const u = { id: "u_1" }; expect(await userQueries.getUserPublic(createSelectMock([u]), "u_1")).toEqual(u); });+ it("filters on deletedAt unconditionally — no option can disable it", async () => {+ const chain = createSelectMock([{ id: "u_1" }]);+ await userQueries.getUserPublic(chain, "u_1");+ expect(conditionReferencesColumn(chain.where.mock.calls[0][0], "deletedAt")).toBe(true);+ });+});++describe("getUserSelf", () => {+ it("returns null when not found", async () => { expect(await userQueries.getUserSelf(createSelectMock([]), "x")).toBeNull(); });+ it("returns user", async () => { const u = { id: "u_1" }; expect(await userQueries.getUserSelf(createSelectMock([u]), "u_1")).toEqual(u); });+ it("never filters on deletedAt — self lookups see soft-deleted rows too", async () => {+ const chain = createSelectMock([{ id: "u_1" }]);+ await userQueries.getUserSelf(chain, "u_1");+ expect(conditionReferencesColumn(chain.where.mock.calls[0][0], "deletedAt")).toBe(false);+ });});describe("getUserByEmail", () => {@@ -55,6 +107,144 @@ describe("createUser", () => {});});+describe("getUserByNameAndDiscriminator", () => {+ it("returns the exact match case-insensitively on name", async () => {+ const u = { id: "u_1", name: "Alice", discriminator: "1234" };+ const chain = createSelectLimitMock([u]);+ const result = await userQueries.getUserByNameAndDiscriminator(chain, "alice", "1234");+ expect(result).toEqual(u);+ });++ it("returns null on no match", async () => {+ const chain = createSelectLimitMock([]);+ const result = await userQueries.getUserByNameAndDiscriminator(chain, "nobody", "0000");+ expect(result).toBeNull();+ });++ it("filters on deletedAt unconditionally — public lookup, no option to disable it", async () => {+ const chain = createSelectLimitMock([{ id: "u_1" }]);+ await userQueries.getUserByNameAndDiscriminator(chain, "alice", "1234");+ expect(conditionReferencesColumn(chain.where.mock.calls[0][0], "deletedAt")).toBe(true);+ });+});++describe("getUserByNameCaseInsensitive", () => {+ it("returns the match case-insensitively on name", async () => {+ const u = { id: "u_1", name: "Alice" };+ const chain = createSelectMock([u]);+ const result = await userQueries.getUserByNameCaseInsensitive(chain, "alice");+ expect(result).toEqual(u);+ });++ it("returns null on no match", async () => {+ const result = await userQueries.getUserByNameCaseInsensitive(createSelectMock([]), "nobody");+ expect(result).toBeNull();+ });++ it("filters on deletedAt unconditionally — public lookup, no option to disable it", async () => {+ const chain = createSelectMock([{ id: "u_1" }]);+ await userQueries.getUserByNameCaseInsensitive(chain, "alice");+ expect(conditionReferencesColumn(chain.where.mock.calls[0][0], "deletedAt")).toBe(true);+ });+});++describe("searchUsersByName", () => {+ it("always filters out soft-deleted rows — isNull(deletedAt) is unconditional, not opt-in", async () => {+ const chain = createSelectLimitMock([{ id: "u_1", name: "Alice" }]);+ await userQueries.searchUsersByName(chain, "ali");+ const whereArg = chain.where.mock.calls[0][0];+ // drizzle's `and(...)` keeps every condition as a queryChunks entry —+ // there is no code path left that can build a call without the+ // deletedAt filter, unlike the old `opts?.excludeDeleted` flag.+ expect(conditionReferencesColumn(whereArg, "deletedAt")).toBe(true);+ });++ it("returns matches for a bare-name substring search", async () => {+ const u = { id: "u_1", name: "Alice" };+ const result = await userQueries.searchUsersByName(createSelectLimitMock([u]), "ali");+ expect(result).toEqual([u]);+ });++ it("exact (name, discriminator) match when discriminator is provided", async () => {+ const chain = createSelectLimitMock([{ id: "u_1", name: "Alice", discriminator: "1234" }]);+ await userQueries.searchUsersByName(chain, "Alice", { discriminator: "1234" });+ expect(chain.limit).toHaveBeenCalledWith(20);+ });++ it("excludeUserId narrows the query without changing the result shape", async () => {+ const u = { id: "u_2", name: "Bob" };+ const result = await userQueries.searchUsersByName(createSelectLimitMock([u]), "bob", {+ excludeUserId: "u_1",+ });+ expect(result).toEqual([u]);+ });++ it("respects a custom limit", async () => {+ const chain = createSelectLimitMock([]);+ await userQueries.searchUsersByName(chain, "x", { limit: 5 });+ expect(chain.limit).toHaveBeenCalledWith(5);+ });+});++describe("withUniqueDiscriminator", () => {+ it("happy path — never retries when insertFn succeeds on the first (unsalted) attempt", async () => {+ const insertFn = vi.fn(async (discriminator: string) => ({ discriminator }));+ const result = await userQueries.withUniqueDiscriminator(+ {} as any,+ { id: "u_fixed", name: "Alice" },+ insertFn,+ );+ expect(insertFn).toHaveBeenCalledTimes(1);+ expect(insertFn).toHaveBeenCalledWith(computeDiscriminator("u_fixed"));+ expect(result).toEqual({ discriminator: computeDiscriminator("u_fixed") });+ });++ it("retries with a salted discriminator on isUniqueConstraintError, then succeeds", async () => {+ const uniqueErr = Object.assign(new Error("UNIQUE constraint failed"), { code: "SQLITE_CONSTRAINT_UNIQUE" });+ const insertFn = vi+ .fn<(discriminator: string) => Promise<{ discriminator: string }>>()+ .mockRejectedValueOnce(uniqueErr)+ .mockImplementationOnce(async (discriminator: string) => ({ discriminator }));++ const result = await userQueries.withUniqueDiscriminator(+ {} as any,+ { id: "u_collide", name: "Alice" },+ insertFn,+ );++ expect(insertFn).toHaveBeenCalledTimes(2);+ expect(insertFn).toHaveBeenNthCalledWith(1, computeDiscriminator("u_collide"));+ expect(insertFn).toHaveBeenNthCalledWith(2, computeDiscriminator("u_collide:1"));+ expect(result).toEqual({ discriminator: computeDiscriminator("u_collide:1") });+ });++ it("throws past the bounded attempt ceiling instead of looping forever", async () => {+ const uniqueErr = Object.assign(new Error("UNIQUE constraint failed"), { code: "SQLITE_CONSTRAINT_UNIQUE" });+ const insertFn = vi.fn(async () => {+ throw uniqueErr;+ });++ await expect(+ userQueries.withUniqueDiscriminator({} as any, { id: "u_always_collides", name: "Alice" }, insertFn),+ ).rejects.toBe(uniqueErr);+ // Bounded — doesn't retry forever.+ expect(insertFn.mock.calls.length).toBeGreaterThan(0);+ expect(insertFn.mock.calls.length).toBeLessThan(20);+ });++ it("rethrows immediately on a non-unique-constraint error (no retry)", async () => {+ const otherErr = new Error("D1_ERROR: something else broke");+ const insertFn = vi.fn(async () => {+ throw otherErr;+ });++ await expect(+ userQueries.withUniqueDiscriminator({} as any, { id: "u_x", name: "Alice" }, insertFn),+ ).rejects.toBe(otherErr);+ expect(insertFn).toHaveBeenCalledTimes(1);+ });+});+describe("updateUser", () => {function createUpdateMock(rows: any[]) {const chain: any = {};diff --git a/src/shared/test/utils/community-mentions.test.ts b/src/shared/test/utils/community-mentions.test.tsindex 01a4815cb..1af5b75ee 100644--- a/src/shared/test/utils/community-mentions.test.ts+++ b/src/shared/test/utils/community-mentions.test.ts@@ -65,3 +65,44 @@ describe("extractMentionedUserIds", () => {expect(got).toEqual(["u2", "u1"]);});});++describe("extractMentionedUserIds — @Name#0042 disambiguation", () => {+ const DUP_ROSTER = [+ { userId: "u_alex_1", name: "Alex", discriminator: "0001" },+ { userId: "u_alex_2", name: "Alex", discriminator: "0002" },+ { userId: "u_bob", name: "Bob", discriminator: "9999" },+ ];++ it("disambiguates two same-named members via the #0042 handle", () => {+ expect(extractMentionedUserIds("hey @Alex#0001", DUP_ROSTER)).toEqual(["u_alex_1"]);+ expect(extractMentionedUserIds("hey @Alex#0002", DUP_ROSTER)).toEqual(["u_alex_2"]);+ });++ it("handle matching is case-insensitive on the name part", () => {+ expect(extractMentionedUserIds("hey @ALEX#0002", DUP_ROSTER)).toEqual(["u_alex_2"]);+ });++ it("matches both duplicates in one message when both handles are used", () => {+ const got = extractMentionedUserIds("@Alex#0001 and @Alex#0002 discuss", DUP_ROSTER);+ expect(got).toEqual(["u_alex_1", "u_alex_2"]);+ });++ it("falls back to bare-name (first occurrence) when no #0042 suffix is present", () => {+ expect(extractMentionedUserIds("hey @Alex, you there?", DUP_ROSTER)).toEqual(["u_alex_1"]);+ });++ it("falls back to bare-name when the discriminator suffix doesn't match anyone", () => {+ expect(extractMentionedUserIds("hey @Alex#9999", DUP_ROSTER)).toEqual(["u_alex_1"]);+ });++ it("a longer digit run after # doesn't match the handle, falls back to bare-name", () => {+ // "#00013" isn't the "#0001" handle (boundary char after would need to be+ // non-identifier) — falls through to the bare "@Alex" bare-name match,+ // since "#" itself is already a non-identifier boundary character.+ expect(extractMentionedUserIds("hey @Alex#00013", DUP_ROSTER)).toEqual(["u_alex_1"]);+ });++ it("handle match still respects word-boundary punctuation immediately after", () => {+ expect(extractMentionedUserIds("cc @Bob#9999, ok?", DUP_ROSTER)).toEqual(["u_bob"]);+ });+});diff --git a/src/web/migrations/0055_user_discriminator_unique.sql b/src/web/migrations/0055_user_discriminator_unique.sqlnew file mode 100644index 000000000..8b73b5367--- /dev/null+++ b/src/web/migrations/0055_user_discriminator_unique.sql@@ -0,0 +1,10 @@+-- The `(name, discriminator)` pair is now load-bearing for routing: DM refs+-- (`/.dm/name#0042`) and mentions (`@Name#0042`) resolve a handle to exactly+-- one user, so it must be unique among live users. Partial index (excludes+-- soft-deleted rows) so a deleted user's old handle can be reissued.+-- `name COLLATE NOCASE` matches the case-insensitive `like(user.name, ...)`+-- lookups in queries/user.ts (getUserByNameAndDiscriminator etc.) — without+-- it, "Alice#0042" and "alice#0042" could both exist as live rows (the+-- byte-for-byte-unique index wouldn't reject the second insert), and a+-- case-insensitive handle lookup would then match two rows nondeterministically.+CREATE UNIQUE INDEX idx_user_name_discriminator ON user(name COLLATE NOCASE, discriminator) WHERE deletedAt IS NULL;diff --git a/src/web/src/app/api/community/agent/ack/route.test.ts b/src/web/src/app/api/community/agent/ack/route.test.tsindex d898052fa..42279f372 100644--- a/src/web/src/app/api/community/agent/ack/route.test.ts+++ b/src/web/src/app/api/community/agent/ack/route.test.ts@@ -8,6 +8,7 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))const mockFindActiveAgentRunnerKeyByBearer = vi.fn()const mockGetUserInternal = vi.fn()+const mockGetUserByNameAndDiscriminator = vi.fn()const mockGetBotBinding = vi.fn()const mockResolveServerByNameForMember = vi.fn()const mockResolveChannelByNameForMember = vi.fn()@@ -24,7 +25,10 @@ vi.mock("@alook/shared", async () => {queries: {...actual.queries,communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },- user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },+ user: {+ getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),+ getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),+ },communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },communityFriendship: { isBlocked: (...a: unknown[]) => mockIsBlocked(...a) },communityServer: { resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a) },@@ -119,6 +123,7 @@ describe("POST /api/community/agent/ack", () => {})it("200 { ok: true } advances the cursor for every scope in the request, channel and DM alike", async () => {+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null }))@@ -131,7 +136,7 @@ describe("POST /api/community/agent/ack", () => {{cursors: [{ channel: "/studio/general", seq: 3 },- { channel: "/.dm/peer_1", seq: 1 },+ { channel: "/.dm/peer#0001", seq: 1 },],},{ Authorization: "Bearer crk_abc" }@@ -143,4 +148,12 @@ describe("POST /api/community/agent/ack", () => {expect(mockBumpReadCursor).toHaveBeenNthCalledWith(1, expect.anything(), "bot_1", { channelId: "ch_1" }, 3)expect(mockBumpReadCursor).toHaveBeenNthCalledWith(2, expect.anything(), "bot_1", { dmConversationId: "dm_1" }, 1)})++ it("400 invalid DM handle when a cursor's channel segment has no #0042 tag", async () => {+ const res = await POST(+ req({ cursors: [{ channel: "/.dm/peer_1", seq: 1 }] }, { Authorization: "Bearer crk_abc" })+ )+ expect(res.status).toBe(400)+ expect(mockBumpReadCursor).not.toHaveBeenCalled()+ })})diff --git a/src/web/src/app/api/community/agent/resolve/route.test.ts b/src/web/src/app/api/community/agent/resolve/route.test.tsindex bc02bc627..9f573f95c 100644--- a/src/web/src/app/api/community/agent/resolve/route.test.ts+++ b/src/web/src/app/api/community/agent/resolve/route.test.ts@@ -8,6 +8,7 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))const mockFindActiveAgentRunnerKeyByBearer = vi.fn()const mockGetUserInternal = vi.fn()+const mockGetUserByNameAndDiscriminator = vi.fn()const mockGetBotBinding = vi.fn()const mockResolveServerByNameForMember = vi.fn()const mockResolveChannelByNameForMember = vi.fn()@@ -25,7 +26,10 @@ vi.mock("@alook/shared", async () => {queries: {...actual.queries,communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },- user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },+ user: {+ getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),+ getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),+ },communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },communityFriendship: { isBlocked: (...a: unknown[]) => mockIsBlocked(...a) },communityServer: { resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a) },@@ -119,6 +123,7 @@ describe("POST /api/community/agent/resolve", () => {})it("200 happy path over a DM ref, gated by requireDMParticipant", async () => {+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null }))@@ -127,8 +132,13 @@ describe("POST /api/community/agent/resolve", () => {mockGetDM.mockResolvedValue({ id: "dm_1", user1Id: "bot_1", user2Id: "peer_1", lastMessageAt: null, createdAt: "t" })mockIsBlocked.mockResolvedValue(false)mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_dm_1", seq: 2, content: "hey" })- const res = await POST(req({ channel: "/.dm/peer_1", seq: 2 }, { Authorization: "Bearer crk_abc" }))+ const res = await POST(req({ channel: "/.dm/peer#0001", seq: 2 }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith(expect.anything(), { dmConversationId: "dm_1" }, 2)})++ it("400 invalid DM handle when the channel segment has no #0042 tag", async () => {+ const res = await POST(req({ channel: "/.dm/peer_1", seq: 2 }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(400)+ })})diff --git a/src/web/src/app/api/community/agent/send/route.test.ts b/src/web/src/app/api/community/agent/send/route.test.tsindex 7fc68cc4d..29047537c 100644--- a/src/web/src/app/api/community/agent/send/route.test.ts+++ b/src/web/src/app/api/community/agent/send/route.test.ts@@ -8,6 +8,7 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))const mockFindActiveAgentRunnerKeyByBearer = vi.fn()const mockGetUserInternal = vi.fn()+const mockGetUserByNameAndDiscriminator = vi.fn()const mockGetBotBinding = vi.fn()const mockResolveServerByNameForMember = vi.fn()const mockResolveChannelByNameForMember = vi.fn()@@ -28,7 +29,10 @@ vi.mock("@alook/shared", async () => {queries: {...actual.queries,communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },- user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },+ user: {+ getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),+ getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),+ },communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },communityFriendship: {isBlocked: (...a: unknown[]) => mockIsBlocked(...a),@@ -189,6 +193,7 @@ describe("POST /api/community/agent/send", () => {})it("200 happy path for a DM send, auto-creating the DM row via createDmIfMissing", async () => {+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null }))@@ -197,7 +202,7 @@ describe("POST /api/community/agent/send", () => {mockGetDM.mockResolvedValue({ id: "dm_new", user1Id: "bot_1", user2Id: "peer_1", lastMessageAt: null, createdAt: "t" })mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_dm", seq: 1, content: "hey" } })const res = await POST(- req({ channel: "/.dm/peer_1", content: { text: "hey" } }, { Authorization: "Bearer crk_abc" })+ req({ channel: "/.dm/peer#0001", content: { text: "hey" } }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)expect(mockCreateCommunityMessage).toHaveBeenCalledWith(@@ -206,15 +211,24 @@ describe("POST /api/community/agent/send", () => {})it("403 blocked propagates from guardDmOpen when trying to auto-create a DM with a blocking peer", async () => {+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null }))mockIsBlocked.mockResolvedValue(true)const res = await POST(- req({ channel: "/.dm/peer_1", content: { text: "hey" } }, { Authorization: "Bearer crk_abc" })+ req({ channel: "/.dm/peer#0001", content: { text: "hey" } }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(403)expect(mockCreateOrGetDM).not.toHaveBeenCalled()expect(mockCreateCommunityMessage).not.toHaveBeenCalled()})++ it("400 invalid DM handle when the channel segment has no #0042 tag", async () => {+ const res = await POST(+ req({ channel: "/.dm/peer_1", content: { text: "hey" } }, { Authorization: "Bearer crk_abc" })+ )+ expect(res.status).toBe(400)+ expect(mockCreateCommunityMessage).not.toHaveBeenCalled()+ })})diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.tsindex 25e610149..90bc1c340 100644--- a/src/web/src/app/api/community/bots/[id]/route.ts+++ b/src/web/src/app/api/community/bots/[id]/route.ts@@ -42,6 +42,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {type: "bot:updated",botId: id,name: updated.name,+ discriminator: updated.discriminator,description: updated.description || undefined,})}diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.tsindex e3bfb800e..bfa601436 100644--- a/src/web/src/app/api/community/bots/route.ts+++ b/src/web/src/app/api/community/bots/route.ts@@ -84,6 +84,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {type: "bot:added",botId: created.botId,name: created.name,+ discriminator: created.discriminator,description: created.description || undefined,})diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.ts b/src/web/src/app/api/community/channels/[id]/posts/route.tsindex 511d0a92c..6e913394c 100644--- a/src/web/src/app/api/community/channels/[id]/posts/route.ts+++ b/src/web/src/app/api/community/channels/[id]/posts/route.ts@@ -141,7 +141,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {})// Resolve author info for response- const creator = await queries.user.getUser(db, ctx.userId)+ const creator = await queries.user.getUserSelf(db, ctx.userId)const authorName = creator ? creator.name : ""const authorAvatar = creator?.image ?? avatarInitial(authorName)diff --git a/src/web/src/app/api/community/daemon/bots/route.ts b/src/web/src/app/api/community/daemon/bots/route.tsindex e72289195..20228282e 100644--- a/src/web/src/app/api/community/daemon/bots/route.ts+++ b/src/web/src/app/api/community/daemon/bots/route.ts@@ -8,9 +8,10 @@ import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"** Returns the bots bound to THIS machine (scope is machineId, not userId —* a user may own bots across multiple machines, but each daemon only cares- * about its own). Response shape is minimal — `id`, `name`, `description` —- * for the daemon's `botsById` cache and system-prompt assembly. No avatar- * (display-only, server does that).+ * about its own). Response shape is minimal — `id`, `name`, `discriminator`,+ * `description` — for the daemon's `botsById` cache and system-prompt+ * assembly (`name`+`discriminator` pair into the bot's global handle). No+ * avatar (display-only, server does that).*/export const GET = withCommunityDaemonAuth(async (_req, ctx) => {const db = getDb(ctx.env.DB)diff --git a/src/web/src/app/api/community/friends/request/route.test.ts b/src/web/src/app/api/community/friends/request/route.test.tsindex 2c2bd9174..fd53fbcb5 100644--- a/src/web/src/app/api/community/friends/request/route.test.ts+++ b/src/web/src/app/api/community/friends/request/route.test.ts@@ -3,6 +3,8 @@ import { NextRequest } from "next/server"const getUser = vi.fn()const getUserInternal = vi.fn()+const getUserByNameAndDiscriminator = vi.fn()+const getUserByNameCaseInsensitive = vi.fn()const isBlocked = vi.fn()const sendRequest = vi.fn()const broadcastToUser = vi.fn()@@ -17,7 +19,8 @@ vi.mock("@alook/shared", async () => {user: {getUser: (...a: unknown[]) => getUser(...a),getUserInternal: (...a: unknown[]) => getUserInternal(...a),- getUserByNameCaseInsensitive: vi.fn(),+ getUserByNameAndDiscriminator: (...a: unknown[]) => getUserByNameAndDiscriminator(...a),+ getUserByNameCaseInsensitive: (...a: unknown[]) => getUserByNameCaseInsensitive(...a),},communityFriendship: {sendRequest: (...a: unknown[]) => sendRequest(...a),@@ -164,9 +167,9 @@ describe("POST /api/community/friends/request", () => {// hack manually concatenated `err.cause.message` — this test guards that// the helper preserves that behaviour.const wrapped = new Error("failed query: insert into community_friendship")- ;(wrapped as { cause?: unknown }).cause = new Error(- "UNIQUE constraint failed: community_friendship.requester_id",- )+ ; (wrapped as { cause?: unknown }).cause = new Error(+ "UNIQUE constraint failed: community_friendship.requester_id",+ )sendRequest.mockRejectedValue(wrapped)const res = await POST(postReq({ userId: "u2" }), {} as never)expect(res.status).toBe(409)@@ -176,7 +179,7 @@ describe("POST /api/community/friends/request", () => {// Only reachable through the helper — the old substring hack would have// rethrown this because "UNIQUE" is not in the message.const codeErr = new Error("constraint violation")- ;(codeErr as { code?: string }).code = "SQLITE_CONSTRAINT_UNIQUE"+ ; (codeErr as { code?: string }).code = "SQLITE_CONSTRAINT_UNIQUE"sendRequest.mockRejectedValue(codeErr)const res = await POST(postReq({ userId: "u2" }), {} as never)expect(res.status).toBe(409)@@ -202,4 +205,54 @@ describe("POST /api/community/friends/request", () => {expect(res.status).toBe(403)expect(sendRequest).not.toHaveBeenCalled()})++ describe("username resolution (name#0042 exact match, else case-insensitive bare-name fallback)", () => {+ it("resolves a name#0042 handle via getUserByNameAndDiscriminator, skipping the bare-name fallback", async () => {+ getUserByNameAndDiscriminator.mockResolvedValue({ id: "u2" })+ sendRequest.mockResolvedValue({+ kind: "created",+ friendship: { id: "f1", requesterId: "u1", addresseeId: "u2", status: "pending" },+ })++ const res = await POST(postReq({ username: "Alex#0002" }), {} as never)++ expect(res.status).toBe(201)+ expect(getUserByNameAndDiscriminator).toHaveBeenCalledWith({}, "Alex", "0002")+ expect(getUserByNameCaseInsensitive).not.toHaveBeenCalled()+ expect(sendRequest).toHaveBeenCalledWith({}, { requesterId: "u1", addresseeId: "u2" })+ })++ it("404s when the name#0042 handle doesn't resolve to anyone (no bare-name fallback on a well-formed handle)", async () => {+ getUserByNameAndDiscriminator.mockResolvedValue(null)++ const res = await POST(postReq({ username: "Alex#0002" }), {} as never)++ expect(res.status).toBe(404)+ expect(getUserByNameCaseInsensitive).not.toHaveBeenCalled()+ expect(sendRequest).not.toHaveBeenCalled()+ })++ it("falls back to case-insensitive bare-name match when no #dddd suffix is present", async () => {+ getUserByNameCaseInsensitive.mockResolvedValue({ id: "u2" })+ sendRequest.mockResolvedValue({+ kind: "created",+ friendship: { id: "f1", requesterId: "u1", addresseeId: "u2", status: "pending" },+ })++ const res = await POST(postReq({ username: "alex" }), {} as never)++ expect(res.status).toBe(201)+ expect(getUserByNameAndDiscriminator).not.toHaveBeenCalled()+ expect(getUserByNameCaseInsensitive).toHaveBeenCalledWith({}, "alex")+ })++ it("404s when the bare-name fallback finds no one", async () => {+ getUserByNameCaseInsensitive.mockResolvedValue(null)++ const res = await POST(postReq({ username: "nobody" }), {} as never)++ expect(res.status).toBe(404)+ expect(sendRequest).not.toHaveBeenCalled()+ })+ })})diff --git a/src/web/src/app/api/community/friends/request/route.ts b/src/web/src/app/api/community/friends/request/route.tsindex bc730ddc8..d031ad168 100644--- a/src/web/src/app/api/community/friends/request/route.ts+++ b/src/web/src/app/api/community/friends/request/route.ts@@ -1,5 +1,5 @@import { NextRequest } from "next/server"-import { queries, WS_EVENTS, isUniqueConstraintError } from "@alook/shared"+import { queries, WS_EVENTS, isUniqueConstraintError, parseNameAndTag } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"@@ -19,11 +19,13 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {let targetUserId = body.userIdif (!targetUserId && body.username) {- const targetUser = await queries.user.getUserByNameCaseInsensitive(- db,- body.username,- { excludeDeleted: true },- )+ // `name#0042` exact match first — same-name users can't get friended by+ // mistake once a discriminator is given. Falls back to the existing+ // case-insensitive bare-name match when no `#dddd` suffix is present.+ const handle = parseNameAndTag(body.username)+ const targetUser = handle+ ? await queries.user.getUserByNameAndDiscriminator(db, handle.name, handle.discriminator)+ : await queries.user.getUserByNameCaseInsensitive(db, body.username)if (!targetUser) return writeError("user not found", 404)targetUserId = targetUser.id}diff --git a/src/web/src/app/api/community/invites/[token]/join/route.test.ts b/src/web/src/app/api/community/invites/[token]/join/route.test.tsindex 600c53349..0e8afe231 100644--- a/src/web/src/app/api/community/invites/[token]/join/route.test.ts+++ b/src/web/src/app/api/community/invites/[token]/join/route.test.ts@@ -94,6 +94,26 @@ describe("POST /api/community/invites/[token]/join", () => {expect(event.member.joinedAt).toBe("2026-07-03T00:00:00.000Z")})+ it("includes the user's discriminator on the emitted member.join event", async () => {+ mockUseInvite.mockResolvedValue({+ invite: { id: "inv_1", serverId: "srv_1" },+ member: {+ id: "mem_1",+ userId: "u_caller",+ role: "member",+ nickname: null,+ joinedAt: "2026-07-03T00:00:00.000Z",+ userName: "Alice",+ userImage: null,+ discriminator: "0042",+ },+ })++ await callPOST("tok_abc")+ const [, event] = mockFanOut.mock.calls[0]!+ expect(event.member.discriminator).toBe("0042")+ })+it("prefers nickname over userName when set", async () => {mockUseInvite.mockResolvedValue({invite: { id: "inv_1", serverId: "srv_1" },@@ -133,9 +153,9 @@ describe("POST /api/community/invites/[token]/join", () => {// message only. isUniqueConstraintError walks the cause chain; this// regression test guards that behaviour.const wrapped = new Error("failed query: insert into community_member")- ;(wrapped as { cause?: unknown }).cause = new Error(- "UNIQUE constraint failed: community_member.user_id",- )+ ; (wrapped as { cause?: unknown }).cause = new Error(+ "UNIQUE constraint failed: community_member.user_id",+ )mockUseInvite.mockRejectedValue(wrapped)const res = await callPOST("tok_abc")expect(res.status).toBe(400)@@ -145,7 +165,7 @@ describe("POST /api/community/invites/[token]/join", () => {it("returns 400 when the driver reports SQLITE_CONSTRAINT_UNIQUE via .code", async () => {// Only reachable via the helper — the old substring hack would rethrow.const codeErr = new Error("constraint violation")- ;(codeErr as { code?: string }).code = "SQLITE_CONSTRAINT_UNIQUE"+ ; (codeErr as { code?: string }).code = "SQLITE_CONSTRAINT_UNIQUE"mockUseInvite.mockRejectedValue(codeErr)const res = await callPOST("tok_abc")expect(res.status).toBe(400)diff --git a/src/web/src/app/api/community/invites/[token]/join/route.ts b/src/web/src/app/api/community/invites/[token]/join/route.tsindex 39e98963f..b6903a236 100644--- a/src/web/src/app/api/community/invites/[token]/join/route.ts+++ b/src/web/src/app/api/community/invites/[token]/join/route.ts@@ -41,6 +41,7 @@ export const POST = withAuth(async (_req, ctx) => {id: result.member.id,userId: result.member.userId,name: result.member.nickname ?? result.member.userName,+ discriminator: result.member.discriminator ?? undefined,avatar: result.member.userImage ?? undefined,role: result.member.role ?? ROLES.MEMBER,joinedAt: result.member.joinedAt,diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.ts b/src/web/src/app/api/community/servers/[id]/bots/route.tsindex ee1c958e3..dc9505bc4 100644--- a/src/web/src/app/api/community/servers/[id]/bots/route.ts+++ b/src/web/src/app/api/community/servers/[id]/bots/route.ts@@ -61,7 +61,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {targetId: botId,changes: JSON.stringify({ botId, serverId, kind: "owner_added" }),})- const bot = await queries.user.getUser(db, botId)+ const bot = await queries.user.getUserSelf(db, botId)const joinEvent: CommunityMemberJoin = {type: WS_EVENTS.MEMBER_JOIN,serverId,diff --git a/src/web/src/app/api/community/servers/[id]/members/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/route.test.tsindex 4c15520ef..8681819dd 100644--- a/src/web/src/app/api/community/servers/[id]/members/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/members/route.test.ts@@ -59,6 +59,7 @@ function buildRow(i: number) {userName: `User ${i}`,userEmail: `u${i}@x.com`,userImage: null,+ discriminator: String(i).padStart(4, "0"),}}@@ -162,6 +163,16 @@ describe("GET /api/community/servers/[id]/members — cursor envelope", () => {expect(body.limit).toBe(DEFAULT_MEMBERS_PAGE_SIZE)})+ it("includes each member's discriminator in the response", async () => {+ const rows = [buildRow(1), buildRow(2)]+ mockListMembersPaginated.mockResolvedValue({ members: rows, hasMore: false, cursor: undefined })+ mockCountMembers.mockResolvedValue(2)++ const res = await GET(getReq(), ctx)+ const body = await res.json() as { members: Array<{ discriminator?: string }> }+ expect(body.members.map((m) => m.discriminator)).toEqual(["0001", "0002"])+ })+it("returns 403 for non-members (permission check ahead of the query)", async () => {mockGetMember.mockResolvedValue(null)const res = await GET(getReq(), ctx)diff --git a/src/web/src/app/api/community/servers/[id]/members/route.ts b/src/web/src/app/api/community/servers/[id]/members/route.tsindex 785f257d7..684c0ae2e 100644--- a/src/web/src/app/api/community/servers/[id]/members/route.ts+++ b/src/web/src/app/api/community/servers/[id]/members/route.ts@@ -51,6 +51,7 @@ export const GET = withAuth(async (req, ctx) => {id: r.id,userId: r.userId,name: display,+ discriminator: r.discriminator ?? undefined,avatar: r.userImage ?? avatarInitial(display),status: (r.userId === ctx.userId ? "online" : "offline") as "online" | "offline",sub: "",diff --git a/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/search/route.test.tsindex 982e1d4f6..d28a989b4 100644--- a/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts@@ -58,6 +58,7 @@ function buildRow(i: number, name: string) {userName: name,userEmail: `${name.toLowerCase()}@x.com`,userImage: null,+ discriminator: String(i).padStart(4, "0"),}}@@ -76,6 +77,13 @@ describe("GET /api/community/servers/[id]/members/search", () => {expect(body.limit).toBe(MAX_MEMBERS_PAGE_SIZE)})+ it("includes each member's discriminator in the response", async () => {+ mockSearchMembers.mockResolvedValue([buildRow(1, "Alex"), buildRow(2, "Alex")])+ const res = await GET(getReq("?q=Alex"), ctx)+ const body = await res.json() as { members: Array<{ discriminator?: string }> }+ expect(body.members.map((m) => m.discriminator)).toEqual(["0001", "0002"])+ })+it("rejects empty q with 400", async () => {const res = await GET(getReq(""), ctx)expect(res.status).toBe(400)diff --git a/src/web/src/app/api/community/servers/[id]/members/search/route.ts b/src/web/src/app/api/community/servers/[id]/members/search/route.tsindex 4fb0d212f..a97f02c35 100644--- a/src/web/src/app/api/community/servers/[id]/members/search/route.ts+++ b/src/web/src/app/api/community/servers/[id]/members/search/route.ts@@ -31,6 +31,7 @@ export const GET = withAuth(async (req, ctx) => {id: r.id,userId: r.userId,name: display,+ discriminator: r.discriminator ?? undefined,avatar: r.userImage ?? avatarInitial(display),status: (r.userId === ctx.userId ? "online" : "offline") as "online" | "offline",sub: "",diff --git a/src/web/src/app/api/community/users/[userId]/block/route.test.ts b/src/web/src/app/api/community/users/[userId]/block/route.test.tsindex 04226c112..23931d54f 100644--- a/src/web/src/app/api/community/users/[userId]/block/route.test.ts+++ b/src/web/src/app/api/community/users/[userId]/block/route.test.ts@@ -12,7 +12,7 @@ vi.mock("@alook/shared", async () => {return {...actual,queries: {- user: { getUser: (...a: unknown[]) => getUser(...a) },+ user: { getUserPublic: (...a: unknown[]) => getUser(...a) },communityFriendship: { block: (...a: unknown[]) => block(...a) },},}diff --git a/src/web/src/app/api/community/users/[userId]/block/route.ts b/src/web/src/app/api/community/users/[userId]/block/route.tsindex 3e95c825e..c9ce3be8a 100644--- a/src/web/src/app/api/community/users/[userId]/block/route.ts+++ b/src/web/src/app/api/community/users/[userId]/block/route.ts@@ -11,7 +11,7 @@ export const POST = withAuth(async (_req, ctx) => {if (!targetId) return writeError("userId is required", 400)if (targetId === ctx.userId) return writeError("cannot block yourself", 400)- const target = await queries.user.getUser(db, targetId)+ const target = await queries.user.getUserPublic(db, targetId)if (!target) return writeError("user not found", 404)const result = await queries.communityFriendship.block(db, {diff --git a/src/web/src/app/api/community/users/[userId]/profile/route.test.ts b/src/web/src/app/api/community/users/[userId]/profile/route.test.tsindex d2b88f0e2..48eb9d3eb 100644--- a/src/web/src/app/api/community/users/[userId]/profile/route.test.ts+++ b/src/web/src/app/api/community/users/[userId]/profile/route.test.ts@@ -16,7 +16,7 @@ vi.mock("@alook/shared", async () => {return {...actual,queries: {- user: { getUser: (...a: unknown[]) => mockGetUser(...a) },+ user: { getUserPublic: (...a: unknown[]) => mockGetUser(...a) },communityUserProfile: { getProfile: (...a: unknown[]) => mockGetProfile(...a) },communityMember: {listMemberServerIds: (...a: unknown[]) => mockListMemberServerIds(...a),@@ -81,4 +81,12 @@ describe("GET /api/community/users/[userId]/profile", () => {mutualServers: 1,})})++ it("404s when the target doesn't exist or is soft-deleted — getUserPublic excludes deleted rows unconditionally", async () => {+ mockGetUser.mockResolvedValue(null)+ const res = await GET(req(), ctx())+ expect(res.status).toBe(404)+ const body = await res.json() as Record<string, unknown>+ expect(body.error).toBe("user not found")+ })})diff --git a/src/web/src/app/api/community/users/[userId]/profile/route.ts b/src/web/src/app/api/community/users/[userId]/profile/route.tsindex 4fa192293..a1c759572 100644--- a/src/web/src/app/api/community/users/[userId]/profile/route.ts+++ b/src/web/src/app/api/community/users/[userId]/profile/route.ts@@ -10,7 +10,7 @@ export const GET = withAuth(async (_req, ctx) => {const db = getDb(ctx.env.DB)// Get target user basic info- const targetUser = await queries.user.getUser(db, id)+ const targetUser = await queries.user.getUserPublic(db, id)if (!targetUser) return writeError("user not found", 404)// Get profile datadiff --git a/src/web/src/app/api/community/users/me/profile/route.test.ts b/src/web/src/app/api/community/users/me/profile/route.test.tsindex cfc27d1e1..9d431f5da 100644--- a/src/web/src/app/api/community/users/me/profile/route.test.ts+++ b/src/web/src/app/api/community/users/me/profile/route.test.ts@@ -22,7 +22,7 @@ vi.mock("@alook/shared", async () => {updateProfile: (...a: unknown[]) => updateProfile(...a),},user: {- getUser: (...a: unknown[]) => getUser(...a),+ getUserSelf: (...a: unknown[]) => getUser(...a),updateUser: (...a: unknown[]) => updateUser(...a),},},diff --git a/src/web/src/app/api/community/users/me/profile/route.ts b/src/web/src/app/api/community/users/me/profile/route.tsindex 395ac5d99..47046491f 100644--- a/src/web/src/app/api/community/users/me/profile/route.ts+++ b/src/web/src/app/api/community/users/me/profile/route.ts@@ -13,7 +13,7 @@ export const GET = withAuth(async (_req, ctx) => {const db = getDb(ctx.env.DB)const [profile, viewer] = await Promise.all([queries.communityUserProfile.getProfile(db, ctx.userId),- queries.user.getUser(db, ctx.userId),+ queries.user.getUserSelf(db, ctx.userId),])return writeJSON({aboutMe: profile?.aboutMe ?? "",diff --git a/src/web/src/app/api/daemon/tasks/poll/route.test.ts b/src/web/src/app/api/daemon/tasks/poll/route.test.tsindex 0fe555bf2..e70258469 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.test.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.test.ts@@ -61,7 +61,7 @@ vi.mock("@alook/shared", async () => {getConversationsByIds: (...args: unknown[]) => mockGetConversationsByIds(...args),},user: {- getUser: (...args: unknown[]) => mockGetUser(...args),+ getUserSelf: (...args: unknown[]) => mockGetUser(...args),},emailAccount: {getEmailAccountsByAgents: (...args: unknown[]) => mockGetAllEmailAccountsForWorkspace(...args),diff --git a/src/web/src/app/api/email/notify/route.test.ts b/src/web/src/app/api/email/notify/route.test.tsindex e84464713..9744a7140 100644--- a/src/web/src/app/api/email/notify/route.test.ts+++ b/src/web/src/app/api/email/notify/route.test.ts@@ -45,7 +45,7 @@ vi.mock("@alook/shared", async () => {createMapping: (...args: unknown[]) => mockCreateMapping(...args),},user: {- getUser: (...args: unknown[]) => mockGetUser(...args),+ getUserSelf: (...args: unknown[]) => mockGetUser(...args),},},};diff --git a/src/web/src/app/api/me/route.test.ts b/src/web/src/app/api/me/route.test.tsindex ceed84e33..b6d687cd3 100644--- a/src/web/src/app/api/me/route.test.ts+++ b/src/web/src/app/api/me/route.test.ts@@ -12,7 +12,7 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));vi.mock("@alook/shared", () => ({createDb: vi.fn(() => ({})),queries: {- user: { getUser: (...args: unknown[]) => mockGetUser(...args) },+ user: { getUserSelf: (...args: unknown[]) => mockGetUser(...args) },},}));diff --git a/src/web/src/app/api/me/route.ts b/src/web/src/app/api/me/route.tsindex 5f09d52f1..8744c8e48 100644--- a/src/web/src/app/api/me/route.ts+++ b/src/web/src/app/api/me/route.ts@@ -7,7 +7,7 @@ import { userToResponse } from "@/lib/api/responses";export const GET = withAuth(async (_req, ctx) => {const db = getDb(ctx.env.DB)- const user = await queries.user.getUser(db, ctx.userId);+ const user = await queries.user.getUserSelf(db, ctx.userId);if (!user) {return writeError("user not found", 404);}diff --git a/src/web/src/app/community/community-shell.tsx b/src/web/src/app/community/community-shell.tsxindex 8feae582a..000c83bb0 100644--- a/src/web/src/app/community/community-shell.tsx+++ b/src/web/src/app/community/community-shell.tsx@@ -10,7 +10,6 @@ import {type CurrentUser,} from "@/contexts/community/current-user"import { useCommunityWs } from "@/hooks/community/use-community-ws"-import { useBotPresenceBridge } from "@/hooks/community/use-bot-presence"/*** Client wrapper that provides the QueryClient, CurrentUser, and the@@ -57,11 +56,6 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {// flag stuck at false for the viewer's own reactions.useCommunityWs({ viewerUserId: currentUser.id })- // Seed own-bot presence into the WS presence store. Runs once for the whole- // community subtree so every consumer reads bot presence through the same- // `useOnlineUserIds()` API as human presence — no per-page overlay code.- useBotPresenceBridge()-// Hydrate `aboutMe` — the community identity holds email/name/avatar from// the session, but the free-text "about me" lives on the community profile// row. Fetch it once so the settings dialog opens pre-filled.@@ -74,7 +68,7 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {discriminator: data.discriminator,})),)- .catch(() => {})+ .catch(() => { })}, [setCurrentUser])return <>{children}</>diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.tsindex d3d694338..b0d0661d8 100644--- a/src/web/src/components/community/_types.ts+++ b/src/web/src/components/community/_types.ts@@ -141,6 +141,9 @@ export type Member = {id: stringuserId: stringname: string+ // 4-digit discriminator (`"0042"`). Optional so mock/older payloads that+ // predate the column keep type-checking; live payloads always include it.+ discriminator?: stringavatar: stringstatus: Presencesub: string@@ -237,4 +240,7 @@ export type UnreadServer = {}// Shared callback signature for opening a user's profile card at a click point.-export type OpenProfile = (name: string, e: React.MouseEvent) => void+// `discriminator` is only ever passed for a mention pill that carried a+// disambiguating `#0042` tag (see message-markdown.tsx) — it lets the lookup+// pick the exact same-named member/friend instead of the first name match.+export type OpenProfile = (name: string, e: React.MouseEvent, discriminator?: string) => voiddiff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsxindex 16231102c..37c6d4c1b 100644--- a/src/web/src/components/community/bots/bot-list.tsx+++ b/src/web/src/components/community/bots/bot-list.tsx@@ -1,7 +1,8 @@"use client"-import { useState } from "react"-import { ChevronLeft, Bot as BotIcon, MoreVertical, Plus } from "lucide-react"+import { useEffect, useMemo, useRef, useState } from "react"+import { useRouter, useSearchParams } from "next/navigation"+import { ChevronLeft, Bot as BotIcon, Monitor, MoreVertical, Plus } from "lucide-react"import { toast } from "sonner"import { Button } from "@/components/ui/button"import { Card } from "@/components/ui/card"@@ -25,6 +26,7 @@ import { AgentAvatar } from "@/components/avatar"import { ProviderLogo } from "@/components/provider-logo"import { useMachines } from "@/hooks/community/use-machines"import { useBots, useDeleteBot, type BotSummary } from "@/hooks/community/use-bots"+import { useCreateOrGetDm } from "@/hooks/community/mutations"import { useOnlineUserIds } from "@/stores/community/ws"import { CreateBotDialog } from "./create-bot-dialog"import { EditBotDialog } from "./edit-bot-dialog"@@ -38,17 +40,30 @@ import { EditBotDialog } from "./edit-bot-dialog"* empty state so users don't learn two idioms.*/export function BotList({ onBack }: { onBack?: () => void } = {}) {+ const router = useRouter()+ const searchParams = useSearchParams()const { bots, isLoading } = useBots()const { machines } = useMachines()- // Presence read: single API for humans + bots. The community-shell bridge- // hydrates own-bot ids into the same set, so a bot row's "online" pill- // uses the same signal every other surface (DM sidebar, friend list,- // mention popover) reads from — no code-path divergence.+ // Presence read: single API for humans + bots, server-pushed identically+ // (see plans/community-account-debt-fixes.md Fix 3 — the owner is always+ // part of its own bots' presence audience, even for a bot not yet in any+ // shared server, so this pill uses the same signal every other surface+ // (DM sidebar, friend list, mention popover) reads from — no divergence).const onlineUserIds = useOnlineUserIds()const [createOpen, setCreateOpen] = useState(false)const [editing, setEditing] = useState<BotSummary | null>(null)const [confirmDelete, setConfirmDelete] = useState<BotSummary | null>(null)const del = useDeleteBot()+ const createOrGetDm = useCreateOrGetDm()++ const chatWithBot = async (bot: BotSummary) => {+ try {+ const data = await createOrGetDm.mutateAsync({ userId: bot.id })+ router.push(`/community/me/${data.conversation.id}`)+ } catch {+ toast.error("Failed to open chat")+ }+ }const machineName = (id: string): string => {const m = machines.find((x) => x.id === id)@@ -56,6 +71,44 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {return m.displayName?.trim() || m.hostname?.trim() || "Unnamed machine"}+ // Group bots by their bound machine, ordered to match the Machines page+ // (any bot whose machine no longer resolves — deleted/unbound — sorts+ // into a trailing "Unknown machine" group instead of disappearing).+ const groups = useMemo(() => {+ const byMachine = new Map<string, BotSummary[]>()+ for (const bot of bots) {+ const list = byMachine.get(bot.machineId)+ if (list) list.push(bot)+ else byMachine.set(bot.machineId, [bot])+ }+ const orderedIds = [+ ...machines.map((m) => m.id).filter((id) => byMachine.has(id)),+ ...[...byMachine.keys()].filter((id) => !machines.some((m) => m.id === id)),+ ]+ return orderedIds.map((machineId) => ({+ machineId,+ machine: machines.find((m) => m.id === machineId) ?? null,+ bots: byMachine.get(machineId)!,+ }))+ }, [bots, machines])++ // Deep-link from the machine-delete dialog's "Manage bots" action+ // (`?machineId=`) — scroll to that group and flash a highlight so the+ // user immediately sees which bots block the delete.+ const targetMachineId = searchParams.get("machineId")+ const [highlightId, setHighlightId] = useState<string | null>(null)+ const groupRefs = useRef<Record<string, HTMLDivElement | null>>({})+ const scrolledForRef = useRef<string | null>(null)+ useEffect(() => {+ if (!targetMachineId || bots.length === 0) return+ if (scrolledForRef.current === targetMachineId) return+ scrolledForRef.current = targetMachineId+ groupRefs.current[targetMachineId]?.scrollIntoView({ behavior: "smooth", block: "start" })+ setHighlightId(targetMachineId)+ const t = setTimeout(() => setHighlightId(null), 2000)+ return () => clearTimeout(t)+ }, [targetMachineId, bots.length])+const backBar = onBack ? (<header className="flex h-12 shrink-0 items-center gap-2 border-b border-border/40 px-6"><Button@@ -123,69 +176,100 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {</Button></header>- <div className="flex flex-col gap-3">- {bots.map((bot) => {- const online = onlineUserIds.has(bot.id)+ <div className="flex flex-col gap-6">+ {groups.map(({ machineId, machine, bots: machineBots }) => {+ const machineOnline = machine?.status === "online"return (- <Card key={bot.id} className="flex flex-col gap-3 p-4">- <div className="flex items-start justify-between gap-3">- <div className="flex min-w-0 items-start gap-3">- <AgentAvatar name={bot.name} avatarUrl={bot.image} size={40} />- <div className="flex min-w-0 flex-col gap-1">- <div className="flex items-center gap-2">- <span className="truncate text-[15px] font-medium text-foreground">- {bot.name}- </span>- <span- className={[- "inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-1 text-[11px] font-medium",- online- ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"- : "bg-muted text-muted-foreground",- ].join(" ")}- >- <span- className={[- "inline-block size-1.5 rounded-full",- online ? "bg-emerald-500" : "bg-muted-foreground/40",- ].join(" ")}- />- {online ? "Online" : "Offline"}- </span>- </div>- <span className="flex items-center gap-1.5 truncate text-xs text-muted-foreground">- <ProviderLogo provider={bot.runtime} className="size-3.5 shrink-0" />- <span className="truncate">- {bot.runtime} · {machineName(bot.machineId)}- </span>- </span>- </div>- </div>- <DropdownMenu>- <DropdownMenuTrigger- render={- <button- aria-label="Bot actions"- className="grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"- >- <MoreVertical className="size-4" />- </button>- }- />- <DropdownMenuContent align="end">- <DropdownMenuItem onClick={() => setEditing(bot)}>- Edit- </DropdownMenuItem>- <DropdownMenuItem- variant="destructive"- onClick={() => setConfirmDelete(bot)}- >- Delete- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ <div+ key={machineId}+ ref={(el) => {+ groupRefs.current[machineId] = el+ }}+ className={[+ "flex flex-col gap-3 rounded-lg p-1 transition-colors duration-500",+ highlightId === machineId ? "bg-primary/5 ring-2 ring-primary/40" : "",+ ].join(" ")}+ >+ <div className="flex items-center gap-2 px-1">+ <Monitor className="size-3.5 text-muted-foreground" />+ <span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">+ {machineName(machineId)}+ </span>+ <span+ className={[+ "inline-block size-1.5 rounded-full",+ machineOnline ? "bg-emerald-500" : "bg-muted-foreground/40",+ ].join(" ")}+ />+ </div>+ <div className="flex flex-col gap-3">+ {machineBots.map((bot) => {+ const online = onlineUserIds.has(bot.id)+ return (+ <Card key={bot.id} className="flex flex-col gap-3 p-4">+ <div className="flex items-start justify-between gap-3">+ <div className="flex min-w-0 items-start gap-3">+ <AgentAvatar name={bot.name} avatarUrl={bot.image} size={40} />+ <div className="flex min-w-0 flex-col gap-1">+ <div className="flex items-center gap-2">+ <span className="truncate text-[15px] font-medium text-foreground">+ {bot.name}+ </span>+ <span+ className={[+ "inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-1 text-[11px] font-medium",+ online+ ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"+ : "bg-muted text-muted-foreground",+ ].join(" ")}+ >+ <span+ className={[+ "inline-block size-1.5 rounded-full",+ online ? "bg-emerald-500" : "bg-muted-foreground/40",+ ].join(" ")}+ />+ {online ? "Online" : "Offline"}+ </span>+ </div>+ <span className="flex items-center gap-1.5 truncate text-xs text-muted-foreground">+ <ProviderLogo provider={bot.runtime} className="size-3.5 shrink-0" />+ <span className="truncate">{bot.runtime}</span>+ </span>+ </div>+ </div>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ aria-label="Bot actions"+ className="grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"+ >+ <MoreVertical className="size-4" />+ </button>+ }+ />+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => chatWithBot(bot)}>+ Chat+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => setEditing(bot)}>+ Edit+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="destructive"+ onClick={() => setConfirmDelete(bot)}+ >+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </Card>+ )+ })}</div>- </Card>+ </div>)})}</div>diff --git a/src/web/src/components/community/inline-marks.tsx b/src/web/src/components/community/inline-marks.tsxindex 3b8b1f15f..09efc7829 100644--- a/src/web/src/components/community/inline-marks.tsx+++ b/src/web/src/components/community/inline-marks.tsx@@ -22,18 +22,31 @@ export function Spoiler({ children }: { children?: React.ReactNode }) {)}-// @mention pill. `everyone` styles @everyone/@here distinctly.-export function MentionPill({ children, everyone }: { children?: React.ReactNode; everyone?: boolean }) {- return (- <span- className={[- "rounded-[4px] px-1 font-medium",- everyone ? "bg-primary/15 text-primary" : "bg-accent text-foreground",- ].join(" ")}- >- {children}- </span>- )+// @mention pill. `everyone` styles @everyone/@here distinctly. `onClick` is+// only wired for resolvable member mentions — @everyone/@here have no+// profile to open, so message-markdown.tsx never passes it for those.+export function MentionPill({+ children,+ everyone,+ onClick,+}: {+ children?: React.ReactNode+ everyone?: boolean+ onClick?: (e: React.MouseEvent) => void+}) {+ const className = [+ "rounded-[4px] px-1 font-medium",+ everyone ? "bg-primary/15 text-primary" : "bg-accent text-foreground",+ onClick ? "cursor-pointer hover:underline" : "",+ ].join(" ")+ if (onClick) {+ return (+ <button type="button" onClick={onClick} className={className}>+ {children}+ </button>+ )+ }+ return <span className={className}>{children}</span>}// #channel pill — leading hash icon, strips a literal "#" from the label.diff --git a/src/web/src/components/community/machines/machine-list.tsx b/src/web/src/components/community/machines/machine-list.tsxindex b41a6fea8..e1658e1ed 100644--- a/src/web/src/components/community/machines/machine-list.tsx+++ b/src/web/src/components/community/machines/machine-list.tsx@@ -1,6 +1,7 @@"use client"import { useCallback, useEffect, useState } from "react"+import { useRouter } from "next/navigation"import { toast } from "sonner"import { ChevronLeft, Monitor } from "lucide-react"import { useQueryClient } from "@tanstack/react-query"@@ -20,12 +21,15 @@ import { apiFetch } from "@/lib/api/client"import { MachineCard } from "./machine-card"import { PairMachineSheet, type PairMachineSheetMode } from "./pair-machine-sheet"import { useMachines, type MachinesResponse } from "@/hooks/community/use-machines"+import { useBots } from "@/hooks/community/use-bots"import { useCommunityStore, usePendingMachineTokenId } from "@/stores/community"import { communityKeys } from "@/lib/query-keys"export function MachineList({ onBack }: { onBack?: () => void } = {}) {+ const router = useRouter()const queryClient = useQueryClient()const { machines, isLoading: machinesLoading } = useMachines()+ const { bots } = useBots()const pendingMachineTokenId = usePendingMachineTokenId()const [pairOpen, setPairOpen] = useState(false)const [pairMode, setPairMode] = useState<PairMachineSheetMode>({ kind: "pair" })@@ -81,6 +85,10 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {const id = confirmDelete.idsetConfirmDelete(null)try {+ // Never sends `cascade: true` — deleting a machine with live bots on+ // it is blocked (see the dialog below, which swaps the destructive+ // action out for "Manage bots" whenever `botsToDelete` is non-empty).+ // This call only fires for a machine we already know has zero bots.await apiFetch(`/api/community/machines/${id}`, { method: "DELETE" })// Optimistically drop the row from the machines cache. WS// `machine.removed` fans out and reconciles, but the same-tab actor@@ -90,8 +98,17 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {(prev) =>prev ? { ...prev, machines: prev.machines.filter((m) => m.id !== id) } : prev,)- } catch {- toast.error("Couldn't delete the machine")+ } catch (err) {+ // MACHINE_HAS_BOTS can still happen here despite the client-side+ // guard above — e.g. a bot was created on this machine from another+ // tab between opening the dialog and confirming.+ const message =+ err instanceof Error && err.message === "MACHINE_HAS_BOTS"+ ? "This machine now has bots on it — delete or move them first"+ : err instanceof Error && err.message+ ? err.message+ : "Couldn't delete the machine"+ toast.error(message)}}, [confirmDelete, queryClient])@@ -100,6 +117,10 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {useCommunityStore.getState().setPendingMachineTokenId(tokenId)}, [])+ const botsToDelete = confirmDelete+ ? bots.filter((b) => b.machineId === confirmDelete.id)+ : []+const backBar = onBack ? (<header className="flex h-12 shrink-0 items-center gap-2 border-b border-border/40 px-6"><Button variant="ghost" size="icon-sm" onClick={onBack} className="text-muted-foreground hover:text-foreground" aria-label="Back">@@ -190,20 +211,57 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {<AlertDialogContent><AlertDialogHeader><AlertDialogTitle>- Delete {confirmDelete?.hostname || "machine"}?+ {botsToDelete.length > 0+ ? `Can't delete ${confirmDelete?.hostname || "machine"}`+ : `Delete ${confirmDelete?.hostname || "machine"}?`}</AlertDialogTitle><AlertDialogDescription>- The daemon will be disconnected immediately and the pairing key revoked.+ {botsToDelete.length > 0 ? (+ <>+ This machine still has{" "}+ {botsToDelete.length === 1+ ? `a bot ("${botsToDelete[0].name}")`+ : `${botsToDelete.length} bots (${botsToDelete+ .map((b) => b.name)+ .join(", ")})`}{" "}+ bound to it. Delete {botsToDelete.length === 1 ? "it " : "them "} from the+ Bots page first — machines can't be deleted while they still have+ bots on them.+ </>+ ) : (+ "The daemon will be disconnected immediately and the pairing key revoked."+ )}</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction- onClick={onConfirmDelete}- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"- >- Delete- </AlertDialogAction>+ {botsToDelete.length > 0 ? (+ <>+ <AlertDialogCancel>Close</AlertDialogCancel>+ <AlertDialogAction+ onClick={() => {+ const machineId = confirmDelete?.id+ setConfirmDelete(null)+ router.push(+ machineId+ ? `/community/me/bots?machineId=${machineId}`+ : "/community/me/bots"+ )+ }}+ >+ Manage bots+ </AlertDialogAction>+ </>+ ) : (+ <>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ onClick={onConfirmDelete}+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ >+ Delete+ </AlertDialogAction>+ </>+ )}</AlertDialogFooter></AlertDialogContent></AlertDialog>diff --git a/src/web/src/components/community/machines/machine-runtimes.test.ts b/src/web/src/components/community/machines/machine-runtimes.test.tsindex a85abcfad..f85465118 100644--- a/src/web/src/components/community/machines/machine-runtimes.test.ts+++ b/src/web/src/components/community/machines/machine-runtimes.test.ts@@ -104,6 +104,19 @@ describe("MachineRuntimes", () => {expect(triggerRender.props["aria-label"]).toBe("codex unavailable")})+ it("sorts unhealthy runtimes after healthy ones, preserving relative order within each group", () => {+ const tree = MachineRuntimes({+ runtimes: [+ { id: "codex", status: "unhealthy" as const },+ { id: "claude" },+ { id: "pi", status: "unhealthy" as const },+ { id: "gemini" },+ ],+ })+ const chips = collectChips(tree)+ expect(chips.map((c) => c.key)).toEqual([".$claude", ".$gemini", ".$codex", ".$pi"])+ })+it("unhealthy without lastError falls back to a generic 'Unavailable — check daemon logs' tooltip", () => {const tree = MachineRuntimes({runtimes: [{ id: "codex", status: "unhealthy" as const }],diff --git a/src/web/src/components/community/machines/machine-runtimes.tsx b/src/web/src/components/community/machines/machine-runtimes.tsxindex 7bbcf4377..8e1e7e5f0 100644--- a/src/web/src/components/community/machines/machine-runtimes.tsx+++ b/src/web/src/components/community/machines/machine-runtimes.tsx@@ -14,9 +14,14 @@ export function MachineRuntimes({ runtimes }: { runtimes: CommunityMachineRuntim// still be missing this field. Do not throw; render nothing.const list = runtimes ?? []if (list.length === 0) return null+ // Available (healthy) chips first, unhealthy ones trail — `toSorted` keeps+ // relative order stable within each group instead of reshuffling ids.+ const sorted = list.toSorted((a, b) =>+ Number(a.status === "unhealthy") - Number(b.status === "unhealthy")+ )return (<div className="flex flex-wrap items-center gap-2">- {list.map((r) => (+ {sorted.map((r) => (<RuntimeChip key={r.id} runtime={r} />))}</div>diff --git a/src/web/src/components/community/message-body.tsx b/src/web/src/components/community/message-body.tsxindex 59111abc1..56286d881 100644--- a/src/web/src/components/community/message-body.tsx+++ b/src/web/src/components/community/message-body.tsx@@ -1,3 +1,4 @@+import { useMemo } from "react"import { Streamdown } from "streamdown"import { mermaid, cjk, math } from "@/lib/streamdown-plugins"import {@@ -6,9 +7,10 @@ import {extractInviteTokens,MD_ALLOWED_TAGS,MD_LITERAL_TAGS,- MD_COMPONENTS,+ buildMdComponents,} from "./message-markdown"import { CommunityInviteCard } from "./community-invite-card"+import type { OpenProfile } from "./_types"// Message body renderer. Standard markdown (bold/italic/strike/code/codeblock/quote)// is rendered natively by streamdown (GFM, matching agent-chat). The shared@@ -21,8 +23,9 @@ import { CommunityInviteCard } from "./community-invite-card"// URL stays as a plain auto-linked <a> in the message body, and a rich join// card renders BELOW it. Both surfaces coexist so users can still copy/share// the raw link even when the card is present.-export function MessageBody({ text }: { text: string }) {+export function MessageBody({ text, onOpenProfile }: { text: string; onOpenProfile?: OpenProfile }) {const inviteTokens = extractInviteTokens(text)+ const components = useMemo(() => buildMdComponents(onOpenProfile), [onOpenProfile])return (<div className="markdown text-[15px] leading-snug"><Streamdown@@ -35,7 +38,7 @@ export function MessageBody({ text }: { text: string }) {}}allowedTags={MD_ALLOWED_TAGS}literalTagContent={MD_LITERAL_TAGS}- components={MD_COMPONENTS}+ components={components}>{preprocessMarkdown(escapeHtml(text))}</Streamdown>diff --git a/src/web/src/components/community/message-markdown.test.ts b/src/web/src/components/community/message-markdown.test.tsindex 5fdf098f3..7980ba457 100644--- a/src/web/src/components/community/message-markdown.test.ts+++ b/src/web/src/components/community/message-markdown.test.ts@@ -1,5 +1,18 @@-import { describe, it, expect } from "vitest"-import { escapeHtml, preprocessMarkdown, extractInviteTokens } from "./message-markdown"+import { describe, it, expect, vi } from "vitest"+import {+ escapeHtml,+ preprocessMarkdown,+ extractInviteTokens,+ mentionNameFromText,+ buildMdComponents,+ MD_COMPONENTS,+} from "./message-markdown"++// `components.mention(...)` returns a plain React element (JSX under the+// hood) — inspecting `.props` here reaches into the MentionPill it wraps+// without a jsdom/testing-library render pass (this repo runs vitest under+// node, see the other describe blocks in this file).+type MentionElement = { props: { onClick?: (e: unknown) => void } }describe("escapeHtml", () => {it("neutralizes < and &, keeps > for blockquotes", () => {@@ -17,6 +30,14 @@ describe("preprocessMarkdown", () => {expect(preprocessMarkdown("hi @Lindsay")).toBe("hi <mention>@Lindsay</mention>")})+ it("wraps a full @name#0042 handle as a single mention token, hiding the discriminator from display but keeping it as a data-tag", () => {+ expect(preprocessMarkdown("hi @Gus#0042")).toBe('hi <mention data-tag="0042">@Gus</mention>')+ })++ it("doesn't truncate a 5+ digit run into a false-positive handle", () => {+ expect(preprocessMarkdown("hi @Gus#00423")).toBe("hi <mention>@Gus</mention>#00423")+ })+it("flags @everyone / @here", () => {expect(preprocessMarkdown("cc @everyone")).toBe('cc <mention data-everyone="1">@everyone</mention>')expect(preprocessMarkdown("@here ping")).toBe('<mention data-everyone="1">@here</mention> ping')@@ -62,6 +83,63 @@ describe("preprocessMarkdown", () => {})})+describe("mentionNameFromText", () => {+ it("strips the leading @", () => {+ expect(mentionNameFromText("@Gus")).toBe("Gus")+ })++ it("strips a trailing #0042 discriminator", () => {+ expect(mentionNameFromText("@Gus#0042")).toBe("Gus")+ })++ it("leaves a 5+ digit trailing run alone (not a valid discriminator)", () => {+ expect(mentionNameFromText("@Gus#00423")).toBe("Gus#00423")+ })++ it("leaves @everyone / @here as-is (no discriminator to strip)", () => {+ expect(mentionNameFromText("@everyone")).toBe("everyone")+ expect(mentionNameFromText("@here")).toBe("here")+ })+})++describe("buildMdComponents — mention pill onClick wiring", () => {+ it("wires onClick to call onOpenProfile with the name (no @, no #dddd) and no discriminator when the tag wasn't stashed", () => {+ const onOpenProfile = vi.fn()+ const components = buildMdComponents(onOpenProfile)+ const el = components.mention({ children: "@Gus#0042" }) as unknown as MentionElement+ const fakeEvent = {} as never+ el.props.onClick?.(fakeEvent)+ expect(onOpenProfile).toHaveBeenCalledWith("Gus", fakeEvent, undefined)+ })++ it("forwards the stashed data-tag discriminator so same-named members can be disambiguated", () => {+ const onOpenProfile = vi.fn()+ const components = buildMdComponents(onOpenProfile)+ const el = components.mention({ children: "@Gus", "data-tag": "0042" }) as unknown as MentionElement+ const fakeEvent = {} as never+ el.props.onClick?.(fakeEvent)+ expect(onOpenProfile).toHaveBeenCalledWith("Gus", fakeEvent, "0042")+ })++ it("does not wire onClick for @everyone / @here", () => {+ const onOpenProfile = vi.fn()+ const components = buildMdComponents(onOpenProfile)+ const el = components.mention({ children: "@everyone", "data-everyone": "1" }) as unknown as MentionElement+ expect(el.props.onClick).toBeUndefined()+ })++ it("has no onClick when no onOpenProfile callback is given", () => {+ const components = buildMdComponents(undefined)+ const el = components.mention({ children: "@Gus" }) as unknown as MentionElement+ expect(el.props.onClick).toBeUndefined()+ })++ it("MD_COMPONENTS.mention (the static, no-callback default) has no onClick", () => {+ const el = MD_COMPONENTS.mention({ children: "@Gus" }) as unknown as MentionElement+ expect(el.props.onClick).toBeUndefined()+ })+})+describe("extractInviteTokens", () => {it("extracts a bare-path token", () => {expect(extractInviteTokens("join /community/invite/abc123XYZ")).toEqual(["abc123XYZ"])diff --git a/src/web/src/components/community/message-markdown.tsx b/src/web/src/components/community/message-markdown.tsxindex dcae5d18a..7cceae907 100644--- a/src/web/src/components/community/message-markdown.tsx+++ b/src/web/src/components/community/message-markdown.tsx@@ -55,23 +55,42 @@ export function preprocessMarkdown(text: string): string {// Insert one so a `> ` that immediately follows text still renders as a quote..replace(/([^\n])\n(> )/g, "$1\n\n$2").replace(/\|\|([\s\S]+?)\|\|/g, (_m, c) => `<spoiler>${c}</spoiler>`)- // single mention pass so @everyone/@here aren't re-matched inside the tag just inserted- .replace(/@[\w-]+/g, (m) =>- m === "@everyone" || m === "@here"- ? `<mention data-everyone="1">${m}</mention>`- : `<mention>${m}</mention>`,- )+ // single mention pass so @everyone/@here aren't re-matched inside the tag just inserted.+ // Optional `#0042` discriminator suffix (global handle format) — the+ // `(?!\d)` lookahead stops a 5+-digit run from being truncated into a+ // false-positive handle (e.g. `@Gus#00423` wraps only `@Gus`). The+ // discriminator is consumed here (so it never leaks as unstyled trailing+ // text) and stashed in a `data-tag` attribute, but dropped from the tag's+ // visible *content* — humans only ever see `@name`. Carrying it as a data+ // attribute (rather than discarding it outright) lets a click handler+ // resolve the exact same-named member instead of the first name match+ // (see `buildMdComponents`/`shell-frame.tsx`'s `openProfile`).+ .replace(/@[\w-]+(?:#\d{4}(?!\d))?/g, (m) => {+ if (m === "@everyone" || m === "@here") return `<mention data-everyone="1">${m}</mention>`+ const tagMatch = /#(\d{4})$/.exec(m)+ const bare = m.replace(/#\d{4}$/, "")+ return tagMatch ? `<mention data-tag="${tagMatch[1]}">${bare}</mention>` : `<mention>${bare}</mention>`+ }).replace(/(^|\s)#([\w-]+)/g, (_m, pre, name) => `${pre}<channel>#${name}</channel>`)return out.replace(new RegExp(`${S0}(\\d+)${S1}`, "g"), (_m, i) => stash[Number(i)])}export const MD_ALLOWED_TAGS = {spoiler: [],- mention: ["data-everyone"],+ mention: ["data-everyone", "data-tag"],channel: [],}export const MD_LITERAL_TAGS = ["spoiler", "mention", "channel"]+// A mention pill's rendered text is always `@name` (see `preprocessMarkdown`,+// which already drops the `#0042` discriminator) — this strips the leading+// `@` and, defensively, any trailing `#dddd` that slips through another path,+// so the result matches `Member.name`/`Msg.authorName` for the profile-card+// lookup in shell-frame.tsx's `openProfile`. Exported for tests.+export function mentionNameFromText(text: string): string {+ return text.replace(/^@/, "").replace(/#\d{4}$/, "")+}+export const MD_COMPONENTS = {spoiler: ({ children }: { children?: React.ReactNode }) => <Spoiler>{children}</Spoiler>,mention: ({ children, ...rest }: Record<string, unknown> & { children?: React.ReactNode }) => (@@ -79,3 +98,29 @@ export const MD_COMPONENTS = {),channel: ({ children }: { children?: React.ReactNode }) => <ChannelPill>{children}</ChannelPill>,} as Record<string, React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>>++// Same as `MD_COMPONENTS`, but the `mention` pill opens the profile card on+// click (skipped for @everyone/@here — there's no user behind those). Built+// per-render (memoized by the caller) rather than statically, since it+// closes over `onOpenProfile`.+export function buildMdComponents(+ onOpenProfile?: (name: string, e: React.MouseEvent, discriminator?: string) => void,+): Record<string, React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>> {+ return {+ ...MD_COMPONENTS,+ mention: ({ children, ...rest }: Record<string, unknown> & { children?: React.ReactNode }) => {+ const everyone = rest["data-everyone"] === "1"+ const name = mentionNameFromText(String(children ?? ""))+ const tag = rest["data-tag"]+ const discriminator = typeof tag === "string" ? tag : undefined+ return (+ <MentionPill+ everyone={everyone}+ onClick={!everyone && onOpenProfile ? (e) => onOpenProfile(name, e, discriminator) : undefined}+ >+ {children}+ </MentionPill>+ )+ },+ }+}diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsxindex 1a8c135bf..20437b552 100644--- a/src/web/src/components/community/message.tsx+++ b/src/web/src/components/community/message.tsx@@ -134,7 +134,7 @@ export function Message({</div>)}{m.content && (- <MessageBody text={m.content} />+ <MessageBody text={m.content} onOpenProfile={onOpenProfile} />)}{m.attachments && (diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsxindex b538d0919..6488d8d1f 100644--- a/src/web/src/components/community/shell-frame.tsx+++ b/src/web/src/components/community/shell-frame.tsx@@ -2,8 +2,10 @@import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"import { useRouter } from "next/navigation"+import { useQueryClient } from "@tanstack/react-query"import { toast } from "sonner"-import { apiFetch } from "@/lib/api/client"+import { communityKeys } from "@/lib/query-keys"+import { userProfileQueryFn, PROFILE_STALE_TIME_MS } from "@/hooks/community/use-user-profile"import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/components/ui/resizable"import { AppSurface } from "@/components/ui/app-surface"import { Dialog, DialogContent } from "@/components/ui/dialog"@@ -78,6 +80,7 @@ export function ShellFrame({}) {const router = useRouter()const bp = useBreakpoint()+ const queryClient = useQueryClient()const currentUser = useCurrentUser()const setCurrentUser = useSetCurrentUser()@@ -272,7 +275,7 @@ export function ShellFrame({// enriches with the profile API. Registered with the community store so// pages can trigger this from anywhere via `useCommunityStore.uiHandlers`.const openProfile = useCallback(- (name: string, e: React.MouseEvent) => {+ (name: string, e: React.MouseEvent, discriminator?: string) => {const isSelf = name === currentUser.nameif (isSelf) {const data: Profile = {@@ -287,7 +290,14 @@ export function ShellFrame({setProfile({ data, x: e.clientX, y: e.clientY })return}- const member = (members ?? []).find((m) => m.name === name)+ // A `#0042`-tagged mention pill disambiguates an exact same-named+ // member/friend; without a tag (author-name/avatar clicks, plain+ // `@name` mentions), fall back to the first name match as before.+ const member = (discriminator+ ? (members ?? []).find((m) => m.name === name && m.discriminator === discriminator)+ ?? (friends ?? []).find((f) => f.name === name && f.discriminator === discriminator)+ : undefined)+ ?? (members ?? []).find((m) => m.name === name)?? (friends ?? []).find((f) => f.name === name)const role: string = member && "role" in member ? (member as { role: string }).role : "member"const about: string = member && "sub" in member && (member as { sub: string }).sub ? (member as { sub: string }).sub : ""@@ -304,26 +314,34 @@ export function ShellFrame({setProfile({ data, x: e.clientX, y: e.clientY })const userId = member && "userId" in member ? (member as { userId: string }).userId : member?.idif (userId) {- apiFetch<{ aboutMe?: string; mutualServers?: number; discriminator?: string }>(`/api/community/users/${userId}/profile`)+ // Cached under `communityKeys.profile(userId)` — a re-click on the+ // same person within `PROFILE_STALE_TIME_MS` resolves from memory+ // instead of re-hitting the network (see plans/profile-card-memory-cache.md).+ queryClient+ .fetchQuery({+ queryKey: communityKeys.profile(userId),+ queryFn: userProfileQueryFn(userId),+ staleTime: PROFILE_STALE_TIME_MS,+ }).then((p) => {setProfile((prev) =>prev? {- ...prev,- data: {- ...prev.data,- about: p.aboutMe ?? prev.data.about,- mutual: p.mutualServers ?? 0,- discriminator: p.discriminator ?? prev.data.discriminator,- },- }+ ...prev,+ data: {+ ...prev.data,+ about: p.aboutMe ?? prev.data.about,+ mutual: p.mutualServers ?? 0,+ discriminator: p.discriminator ?? prev.data.discriminator,+ },+ }: prev,)})- .catch(() => {})+ .catch(() => { })}},- [currentUser, members, friends],+ [currentUser, members, friends, queryClient],)const previewImage = useCallback((url: string) => setPreview(url), [])diff --git a/src/web/src/components/community/thread-opener.tsx b/src/web/src/components/community/thread-opener.tsxindex 6f0fc65ad..007b5f10b 100644--- a/src/web/src/components/community/thread-opener.tsx+++ b/src/web/src/components/community/thread-opener.tsx@@ -80,7 +80,7 @@ export function ThreadOpener({</span></div>- {msg.content && <MessageBody text={msg.content} />}+ {msg.content && <MessageBody text={msg.content} onOpenProfile={onOpenProfile} />}{msg.attachments && msg.attachments.length > 0 && (<div className="mt-2 flex flex-col gap-2">diff --git a/src/web/src/hooks/community/use-bot-presence.ts b/src/web/src/hooks/community/use-bot-presence.tsdeleted file mode 100644index cc4c0c6c7..000000000--- a/src/web/src/hooks/community/use-bot-presence.ts+++ /dev/null@@ -1,50 +0,0 @@-"use client"--import { useEffect, useMemo } from "react"-import { useBots } from "@/hooks/community/use-bots"-import { useMachines } from "@/hooks/community/use-machines"-import { useCommunityWsStore } from "@/stores/community/ws"--/**- * Bridge: derive own-bot presence from `useMachines()` + `useBots()` and seed- * it into the community WS store's `onlineBotUserIds` set.- *- * Why a store bridge instead of per-consumer overlay: bots pass as users at- * every user-facing surface. Every consumer (DM sidebar, friends page, mention- * popover, profile card, member list) already reads presence via- * `useOnlineUserIds()`. Making bot presence flow through the same store means- * those consumers need zero code changes — the union hook returns- * human-online ∪ bot-online transparently.- *- * The only reason human vs bot presence exists as two writes is that the- * underlying signals are different:- * - human user: tab open → user WS DO holds a connection → `presence.update`.- * - own bot: daemon on the bound machine is connected → `machine.status`.- * We can't collapse those into one signal, but we CAN collapse the read path.- *- * Mount this hook once at the top of the community subtree (see the- * `me/layout.tsx` bridge point) — subsequent renders just seed / no-op.- */-export function useBotPresenceBridge(): void {- const { bots } = useBots()- const { machines } = useMachines()- const hydrateBotPresence = useCommunityWsStore((s) => s.hydrateBotPresence)-- const onlineBotIds = useMemo(() => {- // Fast-path: no bots → empty. Avoid iterating machines when there's nothing- // to correlate.- if (bots.length === 0) return [] as string[]- const onlineMachineIds = new Set(- machines.filter((m) => m.status === "online").map((m) => m.id),- )- const out: string[] = []- for (const b of bots) {- if (onlineMachineIds.has(b.machineId)) out.push(b.id)- }- return out- }, [bots, machines])-- useEffect(() => {- hydrateBotPresence(onlineBotIds)- }, [onlineBotIds, hydrateBotPresence])-}diff --git a/src/web/src/hooks/community/use-server-members.test.ts b/src/web/src/hooks/community/use-server-members.test.tsindex 19362be67..43cfb3246 100644--- a/src/web/src/hooks/community/use-server-members.test.ts+++ b/src/web/src/hooks/community/use-server-members.test.ts@@ -78,6 +78,16 @@ describe("applyJoinEvent", () => {const next = applyJoinEvent(prev, joinEvent("a"), false)expect(next).toBe(prev)})++ it("carries the discriminator from the event onto the produced Member", () => {+ const prev = [m("a")]+ const event: CommunityMemberJoin = {+ ...joinEvent("c"),+ member: { ...joinEvent("c").member, discriminator: "0042" },+ }+ const next = applyJoinEvent(prev, event, false)+ expect(next.find((x) => x.id === "c")?.discriminator).toBe("0042")+ })})describe("applyLeaveEvent", () => {diff --git a/src/web/src/hooks/community/use-server-members.ts b/src/web/src/hooks/community/use-server-members.tsindex ccf90c233..44ee69ba4 100644--- a/src/web/src/hooks/community/use-server-members.ts+++ b/src/web/src/hooks/community/use-server-members.ts@@ -46,6 +46,7 @@ export function applyJoinEvent(id: event.member.id,userId: event.member.userId,name: event.member.name,+ discriminator: event.member.discriminator,avatar: event.member.avatar ?? avatarInitial(event.member.name),status: "online",sub: "",@@ -88,12 +89,12 @@ type SearchEnvelope = {// apiFetch without going through React.export const membersPageQueryFn =(serverId: string) =>- async ({ pageParam }: { pageParam: string | null | undefined }): Promise<MembersEnvelope> => {- const params = new URLSearchParams()- if (pageParam) params.set("cursor", pageParam)- const url = `/api/community/servers/${serverId}/members${params.toString() ? `?${params}` : ""}`- return apiFetch<MembersEnvelope>(url)- }+ async ({ pageParam }: { pageParam: string | null | undefined }): Promise<MembersEnvelope> => {+ const params = new URLSearchParams()+ if (pageParam) params.set("cursor", pageParam)+ const url = `/api/community/servers/${serverId}/members${params.toString() ? `?${params}` : ""}`+ return apiFetch<MembersEnvelope>(url)+ }// ── Cache mutation helpers (also used by the WS handler in Step 3) ──────────@@ -241,7 +242,7 @@ export function dispatchMemberOverlayEvent(ev: MemberOverlayEvent): void {export function subscribeMemberOverlayEvents(listener: (ev: MemberOverlayEvent) => void,): () => void {- if (!memberOverlayBus) return () => {}+ if (!memberOverlayBus) return () => { }const handler = (e: Event) => {const detail = (e as CustomEvent<MemberOverlayEvent>).detailif (detail) listener(detail)diff --git a/src/web/src/hooks/community/use-user-profile.test.ts b/src/web/src/hooks/community/use-user-profile.test.tsindex 920c1d88c..446ef3437 100644--- a/src/web/src/hooks/community/use-user-profile.test.ts+++ b/src/web/src/hooks/community/use-user-profile.test.ts@@ -1,6 +1,7 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { QueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"+import { PROFILE_STALE_TIME_MS } from "./use-user-profile"const apiFetchMock = vi.fn()vi.mock("@/lib/api/client", () => ({@@ -45,4 +46,57 @@ describe("useUserProfile / userProfileQueryFn", () => {await qc.invalidateQueries({ queryKey: communityKeys.all })expect(qc.getQueryState(key)?.isInvalidated).toBe(true)})++ it("exports a positive PROFILE_STALE_TIME_MS", () => {+ expect(PROFILE_STALE_TIME_MS).toBeGreaterThan(0)+ })++ it("a re-fetch for the same userId within the stale window resolves from cache, no second network call", async () => {+ apiFetchMock.mockResolvedValueOnce({+ id: "u_1",+ name: "Alice",+ image: null,+ aboutMe: "hi",+ bannerColor: null,+ mutualServers: 3,+ })+ const { userProfileQueryFn } = await import("./use-user-profile")+ const qc = new QueryClient()+ const key = communityKeys.profile("u_1")++ const first = await qc.fetchQuery({ queryKey: key, queryFn: userProfileQueryFn("u_1"), staleTime: PROFILE_STALE_TIME_MS })+ const second = await qc.fetchQuery({ queryKey: key, queryFn: userProfileQueryFn("u_1"), staleTime: PROFILE_STALE_TIME_MS })++ expect(apiFetchMock).toHaveBeenCalledTimes(1)+ expect(second).toEqual(first)+ })++ it("a re-fetch past the stale window hits the network again", async () => {+ apiFetchMock.mockResolvedValueOnce({+ id: "u_1",+ name: "Alice",+ image: null,+ aboutMe: "hi",+ bannerColor: null,+ mutualServers: 3,+ })+ apiFetchMock.mockResolvedValueOnce({+ id: "u_1",+ name: "Alice",+ image: null,+ aboutMe: "updated",+ bannerColor: null,+ mutualServers: 4,+ })+ const { userProfileQueryFn } = await import("./use-user-profile")+ const qc = new QueryClient()+ const key = communityKeys.profile("u_1")+ const shortStale = 1++ await qc.fetchQuery({ queryKey: key, queryFn: userProfileQueryFn("u_1"), staleTime: shortStale })+ await new Promise((r) => setTimeout(r, 5))+ await qc.fetchQuery({ queryKey: key, queryFn: userProfileQueryFn("u_1"), staleTime: shortStale })++ expect(apiFetchMock).toHaveBeenCalledTimes(2)+ })})diff --git a/src/web/src/hooks/community/use-user-profile.ts b/src/web/src/hooks/community/use-user-profile.tsindex ed3916a1f..dfd897cbf 100644--- a/src/web/src/hooks/community/use-user-profile.ts+++ b/src/web/src/hooks/community/use-user-profile.ts@@ -12,6 +12,7 @@ import { apiFetch } from "@/lib/api/client"export type UserProfile = {id: stringname: string+ discriminator: stringimage: string | nullaboutMe: stringbannerColor: string | null@@ -20,3 +21,10 @@ export type UserProfile = {export const userProfileQueryFn = (userId: string) => () =>apiFetch<UserProfile>(`/api/community/users/${userId}/profile`)++// How long a fetched profile card is considered fresh before a re-click+// triggers a background refetch (`queryClient.fetchQuery`'s `staleTime`).+// aboutMe/mutual-server-count change rarely enough that re-fetching on+// every click (the pre-cache behavior) was pure waste — see+// shell-frame.tsx's `openProfile`.+export const PROFILE_STALE_TIME_MS = 5 * 60 * 1000diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.tsindex b777efd87..f746a4b74 100644--- a/src/web/src/lib/auth.test.ts+++ b/src/web/src/lib/auth.test.ts@@ -10,7 +10,27 @@ vi.mock("better-auth/plugins", () => ({bearer: vi.fn(() => ({ __plugin: "bearer" })),}))-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));+// `probeAvailableDiscriminator` (called from the `user.create.before` hook)+// does a real `getUserByNameAndDiscriminator` SELECT against `getDb(env.DB)`+// — stub `getDb` to return a minimal drizzle-chain fake instead of `{}` so+// hook tests don't need a real `Database`. Each `.select(...).from(...)+// .where(...).limit(1)` call resolves to the next queued response (FIFO);+// defaults to "no collision" (empty rows) so every existing hook test keeps+// getting `computeDiscriminator(id)` verbatim on the first attempt, same as+// before this hook started probing the DB.+let selectResponses: unknown[][] = []+function queueSelectResponse(rows: unknown[]) {+ selectResponses.push(rows)+}+function makeFakeDb() {+ const chain = {+ from: () => chain,+ where: () => chain,+ limit: async () => selectResponses.shift() ?? [],+ }+ return { select: () => chain }+}+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => makeFakeDb()) }));vi.mock("@alook/shared", async (importOriginal) => {const actual = await importOriginal<typeof import("@alook/shared")>()@@ -324,7 +344,10 @@ describe("createAuth databaseHooks — user.create.after", () => {})describe("createAuth databaseHooks — user.create.before", () => {- beforeEach(() => vi.clearAllMocks())+ beforeEach(() => {+ vi.clearAllMocks()+ selectResponses = []+ })it("coalesces empty name to email prefix", async () => {const createAuth = await loadCreateAuth()@@ -379,4 +402,22 @@ describe("createAuth databaseHooks — user.create.before", () => {expect(a.data.discriminator).toBe(computeDiscriminator("u_fixed_id"))expect(a.data.discriminator).not.toBe("0000")})++ it("salts past a pre-existing (name, discriminator) collision via probeAvailableDiscriminator", async () => {+ const createAuth = await loadCreateAuth()+ const opts = (createAuth(makeEnv({ NODE_ENV: "production" }) as never) as { __options: AuthOptions }).__options+ const beforeHook = opts.databaseHooks!.user!.create!.before!+ const { computeDiscriminator } = await import("@alook/shared")+ const unsalted = computeDiscriminator("u_collide")+ // First probe (unsalted discriminator) reports a live collision; the+ // salted retry's probe reports the coast is clear.+ queueSelectResponse([{ id: "existing_user" }])+ queueSelectResponse([])++ const result = await beforeHook({ id: "u_collide", name: "dana", email: "[email protected]" })++ expect(result.data.discriminator).not.toBe(unsalted)+ expect(result.data.discriminator).toBe(computeDiscriminator("u_collide:1"))+ expect(result.data.discriminator).toMatch(/^\d{4}$/)+ })})diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.tsindex 033761b53..7f68f1e74 100644--- a/src/web/src/lib/auth.ts+++ b/src/web/src/lib/auth.ts@@ -7,7 +7,6 @@ import {resolveMode,queries,COMMUNITY_BOT_EMAIL_DOMAIN,- computeDiscriminator,RATE_LIMITS,} from "@alook/shared"import { getDb } from "@/lib/db"@@ -107,9 +106,15 @@ export function createAuth(env: Env) {// of the id) in the same INSERT — the schema default of "0000"// otherwise sticks and a backfill has to catch it.const id = (user as { id?: string }).id ?? nanoid()- const discriminator = computeDiscriminator(id)const trimmed = (user.name ?? "").trim()const name = trimmed || user.email?.split("@")[0]?.trim() || user.name+ // Better Auth's adapter inserts AFTER this hook returns — there's no+ // insert call here to wrap in a catch/retry like `withUniqueDiscriminator`+ // does. `probeAvailableDiscriminator` is a best-effort SELECT pre-check+ // instead (see its doc comment for the accepted residual race window;+ // the partial unique index is the actual backstop).+ const db = getDb(env.DB)+ const discriminator = await queries.user.probeAvailableDiscriminator(db, { id, name: name ?? "" })return { data: { ...user, id, name, discriminator } }},after: async (user, ctx) => {diff --git a/src/web/src/lib/community/mention-extension.test.ts b/src/web/src/lib/community/mention-extension.test.tsindex 79042809a..3b42831f8 100644--- a/src/web/src/lib/community/mention-extension.test.ts+++ b/src/web/src/lib/community/mention-extension.test.ts@@ -9,10 +9,11 @@ import {type MentionPopupState,} from "./mention-extension"-const member = (id: string, name: string): Member => ({+const member = (id: string, name: string, discriminator?: string): Member => ({id,userId: id,name,+ discriminator,avatar: name[0],status: "online",sub: name,@@ -112,6 +113,35 @@ describe("rankMentionItems", () => {const memberIds = items.filter((i) => i.kind === "member").map((i) => i.id)expect(memberIds).toEqual(["m_al", "m_mal"])})++ it("appends #0042 to the label when two ranked members share a name", () => {+ const dupes = [+ member("u1", "Alex", "0001"),+ member("u2", "Alex", "0002"),+ member("u3", "Bob", "0003"),+ ]+ const items = rankMentionItems(dupes, "channel", "al")+ const labels = items.filter((i) => i.kind === "member").map((i) => i.label)+ expect(labels.sort()).toEqual(["Alex#0001", "Alex#0002"])+ })++ it("leaves a unique name's label bare even when other names collide", () => {+ const mixed = [+ member("u1", "Alex", "0001"),+ member("u2", "Alex", "0002"),+ member("u3", "Bob", "0003"),+ ]+ const items = rankMentionItems(mixed, "channel", "")+ const bob = items.find((i) => i.kind === "member" && i.id === "u3")+ expect(bob?.label).toBe("Bob")+ })++ it("leaves the label bare when a colliding member has no discriminator", () => {+ const noDisc = [member("u1", "Alex"), member("u2", "Alex", "0002")]+ const items = rankMentionItems(noDisc, "channel", "")+ const labels = items.filter((i) => i.kind === "member").map((i) => i.label)+ expect(labels.sort()).toEqual(["Alex", "Alex#0002"])+ })})// Reach into the extension the same way the composer does — read@@ -128,6 +158,62 @@ function getItemsCallback(return items}+// Same access pattern as `getItemsCallback` above — reach into the configured+// `renderText`/`renderHTML` options rather than the tag's declared defaults.+type RenderNodeProps = {+ options?: { HTMLAttributes?: Record<string, unknown> }+ node: { attrs: { label?: string | null; id?: string | null } }+}++function getRenderFns(ext: ReturnType<typeof buildCommunityMentionExtension>): {+ renderText: (props: RenderNodeProps) => string+ renderHTML: (props: RenderNodeProps) => unknown+} {+ const config = (ext as unknown as {+ config: { addOptions?: () => { renderText?: unknown; renderHTML?: unknown } }+ }).config+ const opts =+ config.addOptions?.() ??+ (ext as unknown as { options?: { renderText?: unknown; renderHTML?: unknown } }).options+ const renderText = opts?.renderText as ((props: RenderNodeProps) => string) | undefined+ const renderHTML = opts?.renderHTML as ((props: RenderNodeProps) => unknown) | undefined+ if (!renderText || !renderHTML) throw new Error("renderText/renderHTML not found")+ return { renderText, renderHTML }+}++describe("buildCommunityMentionExtension — renderText/renderHTML", () => {+ const build = () =>+ buildCommunityMentionExtension({+ membersRef: { current: [] as Member[] },+ contextRef: { current: "channel" as MentionContext },+ popupRef: { current: EMPTY_MENTION_STATE as MentionPopupState },+ setPopup: () => { },+ })++ it("renderText keeps the full disambiguated label — the server needs #0042 to resolve exactly", () => {+ const { renderText } = getRenderFns(build())+ expect(renderText({ node: { attrs: { label: "Alex#0002", id: "m1" } } })).toBe("@Alex#0002")+ })++ it("renderHTML strips the discriminator — the in-editor chip never shows the number", () => {+ const { renderHTML } = getRenderFns(build())+ const spec = renderHTML({ options: { HTMLAttributes: {} }, node: { attrs: { label: "Alex#0002", id: "m1" } } })+ expect(spec).toEqual(["span", {}, "@Alex"])+ })++ it("renderHTML leaves a bare (non-colliding) label untouched", () => {+ const { renderHTML } = getRenderFns(build())+ const spec = renderHTML({ options: { HTMLAttributes: {} }, node: { attrs: { label: "Bob", id: "m2" } } })+ expect(spec).toEqual(["span", {}, "@Bob"])+ })++ it("renderHTML falls back to id when label is missing", () => {+ const { renderHTML } = getRenderFns(build())+ const spec = renderHTML({ options: { HTMLAttributes: {} }, node: { attrs: { label: null, id: "m3" } } })+ expect(spec).toEqual(["span", {}, "@m3"])+ })+})+describe("buildCommunityMentionExtension — suggestion.items callback", () => {it("fires onSearchMembersRef.current with the current query on each items() call", () => {const membersRef = { current: [] as Member[] }@@ -139,7 +225,7 @@ describe("buildCommunityMentionExtension — suggestion.items callback", () => {membersRef,contextRef,popupRef,- setPopup: () => {},+ setPopup: () => { },onSearchMembersRef,queryRef,})@@ -161,7 +247,7 @@ describe("buildCommunityMentionExtension — suggestion.items callback", () => {membersRef,contextRef,popupRef,- setPopup: () => {},+ setPopup: () => { },queryRef,})const items = getItemsCallback(ext)@@ -181,7 +267,7 @@ describe("buildCommunityMentionExtension — suggestion.items callback", () => {membersRef,contextRef,popupRef,- setPopup: () => {},+ setPopup: () => { },})const items = getItemsCallback(ext)expect(items({ query: "anything" })).toEqual([])@@ -197,7 +283,7 @@ describe("buildCommunityMentionExtension — suggestion.items callback", () => {membersRef,contextRef,popupRef,- setPopup: () => {},+ setPopup: () => { },})const items = getItemsCallback(ext)// Live refs — mutate the roster after the extension is built. items()diff --git a/src/web/src/lib/community/mention-extension.ts b/src/web/src/lib/community/mention-extension.tsindex 4a18bc0d0..c022ca9d3 100644--- a/src/web/src/lib/community/mention-extension.ts+++ b/src/web/src/lib/community/mention-extension.ts@@ -4,20 +4,32 @@ import type { Member } from "@/components/community/_types"export type MentionContext = "channel" | "thread" | "dm"+type MemberMentionItem = {+ kind: "member"+ id: string+ label: string+ avatar: string+ status: "online" | "offline"+}+export type MentionItem =| { kind: MentionType; id: MentionType; label: MentionType }- | {- kind: "member"- id: string- label: string- avatar: string- status: "online" | "offline"- }+ | MemberMentionItemconst VIRTUAL_ITEMS: MentionItem[] = MENTION_TYPES.map((t) => ({ kind: t, id: t, label: t }))const MENTION_LIMIT = 8+// The disambiguated label (`Alex#0002`, set by `rankMentionItems` below) is+// what gets serialized into the message text via `renderText` — the backend+// needs it to resolve the exact user instead of falling back to a first-match+// guess. Humans should never see the number though, so the in-editor chip+// (`renderHTML`) and the rendered pill (message-markdown.tsx) both strip it+// for display only.+function mentionDisplayLabel(label: string): string {+ return label.replace(/#\d{4}$/, "")+}+// Pure ranker — exported for tests. Items are everyone/here followed by// members, ranked prefix-first then substring. Returns an empty list for DMs:// a 1:1 conversation has no roster to disambiguate against, and the backend@@ -33,11 +45,11 @@ export function rankMentionItems(const q = query.toLowerCase()const virtual = VIRTUAL_ITEMS.filter((v) => !q || v.label.startsWith(q))- const sw: MentionItem[] = []- const inc: MentionItem[] = []+ const sw: MemberMentionItem[] = []+ const inc: MemberMentionItem[] = []for (const m of members) {const name = m.name.toLowerCase()- const item: MentionItem = {+ const item: MemberMentionItem = {kind: "member",id: m.id,label: m.name,@@ -48,7 +60,28 @@ export function rankMentionItems(else if (name.includes(q)) inc.push(item)}- return [...virtual, ...sw, ...inc].slice(0, MENTION_LIMIT)+ // Disambiguate same-name members within the ranked window: append the+ // `#0042` discriminator to the label (which is also what gets inserted+ // into the message, via `renderText`) so picking either one resolves to+ // the exact user server-side instead of the backend's first-match+ // fallback. Unique names stay plain — no visual noise for the common+ // case.+ const ranked = [...sw, ...inc]+ const nameCounts = new Map<string, number>()+ for (const item of ranked) {+ const key = item.label.toLowerCase()+ nameCounts.set(key, (nameCounts.get(key) ?? 0) + 1)+ }+ const membersByLabel = new Map(members.map((m) => [m.id, m]))+ const disambiguated = ranked.map((item) => {+ const key = item.label.toLowerCase()+ if ((nameCounts.get(key) ?? 0) < 2) return item+ const discriminator = membersByLabel.get(item.id)?.discriminator+ if (!discriminator) return item+ return { ...item, label: `${item.label}#${discriminator}` }+ })++ return [...virtual, ...disambiguated].slice(0, MENTION_LIMIT)}// Popup state. `rect` is `clientRect()` from @tiptap/suggestion — it's the@@ -107,6 +140,8 @@ export function buildCommunityMentionExtension(opts: {return Mention.configure({HTMLAttributes: { class: "mention-highlight" },renderText: ({ node }) => `@${node.attrs.label ?? node.attrs.id}`,+ renderHTML: ({ options, node }) =>+ ["span", options.HTMLAttributes, `@${mentionDisplayLabel(node.attrs.label ?? node.attrs.id ?? "")}`],suggestion: {char: "@",items: ({ query }: { query: string }) => {diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex 4f13a9f05..8e7900d6a 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -179,3 +179,54 @@ describe("createCommunityMessage — audit relocation (plan §10)", () => {})})})++describe("createCommunityMessage — @Name#0042 mention disambiguation", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockCreateMessage.mockResolvedValue({ id: "msg_1" })+ mockFanOutToChannel.mockResolvedValue(undefined)+ mockFanOutToDM.mockResolvedValue(undefined)+ mockBroadcastToUser.mockResolvedValue(undefined)+ mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: false, deletedAt: null })+ mockListMembers.mockResolvedValue([+ { userId: "author_1", userName: "Author", discriminator: "1111" },+ { userId: "alex_1", userName: "Alex", discriminator: "0001" },+ { userId: "alex_2", userName: "Alex", discriminator: "0002" },+ ])+ })++ it("disambiguates two same-named members via the @Name#0042 handle in the message body", async () => {+ mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Alex#0002, over here" }))++ await createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },+ body: { content: "hey @Alex#0002, over here" },+ })++ expect(mockListMembers).toHaveBeenCalledWith({}, "srv_1")+ expect(mockCreateMentions).toHaveBeenCalledWith({}, {+ messageId: "msg_1",+ userIds: ["alex_2"],+ kind: "mention",+ })+ })++ it("passes each member's discriminator through as a mention candidate", async () => {+ mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Alex#0001" }))++ await createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },+ body: { content: "hey @Alex#0001" },+ })++ expect(mockCreateMentions).toHaveBeenCalledWith({}, {+ messageId: "msg_1",+ userIds: ["alex_1"],+ kind: "mention",+ })+ })+})diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex c7541f9a8..9a788b760 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -218,7 +218,7 @@ export async function createCommunityMessage(params: {if (row.content) {const candidates = members.filter((m) => m.userId !== authorId && m.userName)- .map((m) => ({ userId: m.userId, name: m.userName as string }))+ .map((m) => ({ userId: m.userId, name: m.userName as string, discriminator: m.discriminator }))for (const id of extractMentionedUserIds(row.content, candidates)) {mentionTargets.add(id)}diff --git a/src/web/src/lib/community/resolve-ref.test.ts b/src/web/src/lib/community/resolve-ref.test.tsindex e713fc225..7c97d5842 100644--- a/src/web/src/lib/community/resolve-ref.test.ts+++ b/src/web/src/lib/community/resolve-ref.test.ts@@ -1,6 +1,7 @@import { describe, it, expect, vi, beforeEach } from "vitest"const mockGetUserInternal = vi.fn()+const mockGetUserByNameAndDiscriminator = vi.fn()const mockAreFriends = vi.fn()const mockIsBlocked = vi.fn()const mockCreateOrGetDM = vi.fn()@@ -18,7 +19,10 @@ vi.mock("@alook/shared", async () => {...actual,isUniqueConstraintError: (...a: unknown[]) => mockIsUniqueConstraintError(...a),queries: {- user: { getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a) },+ user: {+ getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),+ getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),+ },communityFriendship: {areFriends: (...a: unknown[]) => mockAreFriends(...a),isBlocked: (...a: unknown[]) => mockIsBlocked(...a),@@ -62,47 +66,56 @@ describe("resolveTargetForMember", () => {expect((res as { message: string }).message).toMatch(/must not pin/)})- describe("DM refs (/.dm/<peer>)", () => {+ describe("DM refs (/.dm/<peer#0042>)", () => {it("404 DM threads are not supported", async () => {- const res = await resolveTargetForMember(db, "u_1", "/.dm/peer_1/#3")+ const res = await resolveTargetForMember(db, "u_1", "/.dm/peer#0001/#3")expect(res).toEqual({ error: 404, message: "DM threads are not supported" })})- it("404 user not found when peer is missing or soft-deleted", async () => {- mockGetUserInternal.mockResolvedValue(null)+ it("400 invalid DM handle when the segment has no #0042 tag", async () => {const res = await resolveTargetForMember(db, "u_1", "/.dm/peer_1")+ expect(res).toEqual({ error: 400, message: "invalid DM handle, expected name#0042" })+ expect(mockGetUserByNameAndDiscriminator).not.toHaveBeenCalled()+ })++ it("404 user not found when peer is missing or soft-deleted", async () => {+ mockGetUserByNameAndDiscriminator.mockResolvedValue(null)+ const res = await resolveTargetForMember(db, "u_1", "/.dm/peer#0001")expect(res).toEqual({ error: 404, message: "user not found" })+ expect(mockGetUserByNameAndDiscriminator).toHaveBeenCalledWith(db, "peer", "0001")})it("without createDmIfMissing: 404 dm not found when no existing DM row", async () => {- mockGetUserInternal.mockResolvedValue({ id: "peer_1", deletedAt: null })+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })mockGetDMBetween.mockResolvedValue(null)- const res = await resolveTargetForMember(db, "u_1", "/.dm/peer_1")+ const res = await resolveTargetForMember(db, "u_1", "/.dm/peer#0001")expect(res).toEqual({ error: 404, message: "dm not found" })expect(mockCreateOrGetDM).not.toHaveBeenCalled()})it("without createDmIfMissing: resolves an existing DM without calling guardDmOpen", async () => {- mockGetUserInternal.mockResolvedValue({ id: "peer_1", deletedAt: null })+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })mockGetDMBetween.mockResolvedValue({ id: "dm_1" })- const res = await resolveTargetForMember(db, "u_1", "/.dm/peer_1")+ const res = await resolveTargetForMember(db, "u_1", "/.dm/peer#0001")expect(res).toEqual({ kind: "dm", dmConversationId: "dm_1", otherUserId: "peer_1" })expect(mockIsBlocked).not.toHaveBeenCalled()})it("with createDmIfMissing: blocked by guardDmOpen surfaces the guard's status/error", async () => {+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })mockGetUserInternal.mockResolvedValue({ id: "peer_1", deletedAt: null })mockIsBlocked.mockResolvedValue(true)- const res = await resolveTargetForMember(db, "u_1", "/.dm/peer_1", { createDmIfMissing: true })+ const res = await resolveTargetForMember(db, "u_1", "/.dm/peer#0001", { createDmIfMissing: true })expect(res).toEqual({ error: 403, message: "blocked" })expect(mockCreateOrGetDM).not.toHaveBeenCalled()})it("with createDmIfMissing: creates/gets the DM when guard passes", async () => {+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })mockGetUserInternal.mockResolvedValue({ id: "peer_1", deletedAt: null })mockIsBlocked.mockResolvedValue(false)mockCreateOrGetDM.mockResolvedValue({ id: "dm_new" })- const res = await resolveTargetForMember(db, "u_1", "/.dm/peer_1", { createDmIfMissing: true })+ const res = await resolveTargetForMember(db, "u_1", "/.dm/peer#0001", { createDmIfMissing: true })expect(res).toEqual({ kind: "dm", dmConversationId: "dm_new", otherUserId: "peer_1" })expect(mockCreateOrGetDM).toHaveBeenCalledWith(db, { userId1: "u_1", userId2: "peer_1" })})diff --git a/src/web/src/lib/community/resolve-ref.ts b/src/web/src/lib/community/resolve-ref.tsindex 29e4d6fca..b8259765f 100644--- a/src/web/src/lib/community/resolve-ref.ts+++ b/src/web/src/lib/community/resolve-ref.ts@@ -1,5 +1,5 @@import { NextResponse } from "next/server"-import { queries, parseRef, DM_SERVER } from "@alook/shared"+import { queries, parseRef, DM_SERVER, parseNameAndTag } from "@alook/shared"import type { Database } from "@alook/shared"import { isUniqueConstraintError } from "@alook/shared"import { guardDmOpen } from "./dm-guard"@@ -20,7 +20,7 @@ export interface ResolveTargetOpts {/*** Resolve a CLI path ref (`ChannelRef`, e.g. `/studio/general`,- * `/studio/general/#42`, `/.dm/user_123`) to a concrete channel/DM id,+ * `/studio/general/#42`, `/.dm/gusye#1231`) to a concrete channel/DM id,* scoped to `userId`'s memberships. Threads flatten to `{ kind: "channel",* channelId: <thread's own id> }` (debt #10 — threads ARE channels); the* caller (the `send` route) is responsible for reconstructing the full@@ -62,11 +62,15 @@ export async function resolveTargetForMember(return { error: 404, message: "DM threads are not supported" }}- const peerId = parsed.channel- const peer = await queries.user.getUserInternal(db, peerId)- if (!peer || peer.deletedAt !== null) {+ const handle = parseNameAndTag(parsed.channel)+ if (!handle) {+ return { error: 400, message: "invalid DM handle, expected name#0042" }+ }+ const peer = await queries.user.getUserByNameAndDiscriminator(db, handle.name, handle.discriminator)+ if (!peer) {return { error: 404, message: "user not found" }}+ const peerId = peer.idif (opts?.createDmIfMissing) {const guard = await guardDmOpen(db, userId, peerId, { callerKind: opts.callerKind })diff --git a/src/web/src/lib/services/calendar.test.ts b/src/web/src/lib/services/calendar.test.tsindex 209dcfc35..2f831e129 100644--- a/src/web/src/lib/services/calendar.test.ts+++ b/src/web/src/lib/services/calendar.test.ts@@ -27,7 +27,7 @@ vi.mock("@alook/shared", async () => {...actual,queries: {agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },- user: { getUser: (...args: unknown[]) => mockGetUser(...args) },+ user: { getUserSelf: (...args: unknown[]) => mockGetUser(...args) },conversation: {createConversation: (...args: unknown[]) => mockCreateConv(...args),},diff --git a/src/web/src/lib/services/calendar.ts b/src/web/src/lib/services/calendar.tsindex a2ffd25e9..fea79c98c 100644--- a/src/web/src/lib/services/calendar.ts+++ b/src/web/src/lib/services/calendar.ts@@ -85,7 +85,7 @@ export async function promoteDueCalendarEventsForWorkspace(});if (!ownerCache.has(agent.ownerId)) {- const u = await queries.user.getUser(db, agent.ownerId);+ const u = await queries.user.getUserSelf(db, agent.ownerId);ownerCache.set(agent.ownerId, u ? { name: u.name, email: u.email } : null);}const ownerInfo = ownerCache.get(agent.ownerId)!;diff --git a/src/web/src/lib/services/email-dispatch.ts b/src/web/src/lib/services/email-dispatch.tsindex 17e1dd009..29c661006 100644--- a/src/web/src/lib/services/email-dispatch.ts+++ b/src/web/src/lib/services/email-dispatch.ts@@ -53,7 +53,7 @@ export async function dispatchEmailToAgent(if (conv) {conversationType = conv.typeif (conv.type === TASK_TYPES.USER_DM_MESSAGE && conv.userId) {- const u = await queries.user.getUser(db, conv.userId)+ const u = await queries.user.getUserSelf(db, conv.userId)if (u) dmUser = { name: u.name, email: u.email }}}diff --git a/src/web/src/lib/services/task-payload-builder.test.ts b/src/web/src/lib/services/task-payload-builder.test.tsindex c7bda6f5d..26ba08e6c 100644--- a/src/web/src/lib/services/task-payload-builder.test.ts+++ b/src/web/src/lib/services/task-payload-builder.test.ts@@ -26,7 +26,7 @@ vi.mock("@alook/shared", async () => {getMemberByUserAndWorkspace: (...args: unknown[]) => mockGetMemberByUserAndWorkspace(...args),},user: {- getUser: (...args: unknown[]) => mockGetUser(...args),+ getUserSelf: (...args: unknown[]) => mockGetUser(...args),},conversation: {getConversation: (...args: unknown[]) => mockGetConversation(...args),diff --git a/src/web/src/lib/services/task-payload-builder.ts b/src/web/src/lib/services/task-payload-builder.tsindex 0f776934b..1362fe131 100644--- a/src/web/src/lib/services/task-payload-builder.ts+++ b/src/web/src/lib/services/task-payload-builder.ts@@ -85,7 +85,7 @@ export class TaskPayloadBuilder {const u = await cached(cacheKeys.user(agent.ownerId),1800,- () => queries.user.getUser(this.db, agent.ownerId!),+ () => queries.user.getUserSelf(this.db, agent.ownerId!),);userCache.set(agent.ownerId, u ? { name: u.name, email: u.email } : null);}@@ -101,7 +101,7 @@ export class TaskPayloadBuilder {const u = await cached(cacheKeys.user(convo.userId),1800,- () => queries.user.getUser(this.db, convo!.userId!),+ () => queries.user.getUserSelf(this.db, convo!.userId!),);userCache.set(convo.userId, u ? { name: u.name, email: u.email } : null);}diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.tsindex eb34fe412..cd52eba6c 100644--- a/src/web/src/stores/community/index.ts+++ b/src/web/src/stores/community/index.ts@@ -68,7 +68,7 @@ type CommunitySubscription = {type CommunityUiHandlers = {previewImage?: (url: string) => void- openProfile?: (name: string, e: React.MouseEvent) => void+ openProfile?: (name: string, e: React.MouseEvent, discriminator?: string) => voidgoBackMobile?: () => void}@@ -218,7 +218,8 @@ export const useCurrentChannelMeta = () =>*/const stableUiHandlers: CommunityUiHandlers = {previewImage: (url) => useCommunityStore.getState().uiHandlers.previewImage?.(url),- openProfile: (name, e) => useCommunityStore.getState().uiHandlers.openProfile?.(name, e),+ openProfile: (name, e, discriminator) =>+ useCommunityStore.getState().uiHandlers.openProfile?.(name, e, discriminator),goBackMobile: () => useCommunityStore.getState().uiHandlers.goBackMobile?.(),}export const useUiHandlers = () => stableUiHandlersdiff --git a/src/web/src/stores/community/ws.ts b/src/web/src/stores/community/ws.tsindex 8e28a40b0..075d6c6b7 100644--- a/src/web/src/stores/community/ws.ts+++ b/src/web/src/stores/community/ws.ts@@ -28,24 +28,20 @@ export const SEEN_MESSAGE_MAX = 500export const SEEN_MESSAGE_TRIM_TO = 400export type CommunityWsStoreState = {- /** Human users online right now. Fed by `community:presence.update` WS. */- onlineUserIds: Set<string>/**- * Owner's own bots that are online right now. A bot is "online" iff its- * bound machine's daemon is connected. Fed by `use-bot-presence.ts` which- * derives from `useMachines()` + `useBots()` and reconciles on `machine.status`- * WS events. Stored separately so the two data streams don't collide.+ * Everyone online right now — human or bot. The server pushes+ * `community:presence.update` identically for both (see+ * plans/community-account-debt-fixes.md Fix 3: a bot's bound-machine+ * connect/disconnect fans out through the same audience-based pipeline as+ * a human WS connect/disconnect), so there's a single stream to store.*/- onlineBotUserIds: Set<string>+ onlineUserIds: Set<string>seenMessageIds: Set<string>setPresence: (userId: string, online: boolean) => void/** Atomic bulk seed — one notification for N users. Use on server switch. */hydratePresence: (userIds: readonly string[]) => voidresetPresence: () => void- /** Atomic bulk seed of bot presence. Content-equality guarded like `hydratePresence`. */- hydrateBotPresence: (botUserIds: readonly string[]) => void- resetBotPresence: () => voidhasSeenMessage: (id: string) => booleanmarkSeenMessage: (id: string) => voidreset: () => void@@ -53,10 +49,9 @@ export type CommunityWsStoreState = {const initialState = (): Pick<CommunityWsStoreState,- "onlineUserIds" | "onlineBotUserIds" | "seenMessageIds"+ "onlineUserIds" | "seenMessageIds"> => ({onlineUserIds: new Set(),- onlineBotUserIds: new Set(),seenMessageIds: new Set(),})@@ -86,22 +81,6 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => (set({ onlineUserIds: new Set() })},- hydrateBotPresence: (botUserIds) => {- const current = get().onlineBotUserIds- if (- current.size === botUserIds.length &&- botUserIds.every((id) => current.has(id))- ) {- return- }- set({ onlineBotUserIds: new Set(botUserIds) })- },-- resetBotPresence: () => {- if (get().onlineBotUserIds.size === 0) return- set({ onlineBotUserIds: new Set() })- },-hasSeenMessage: (id) => get().seenMessageIds.has(id),markSeenMessage: (id) => {@@ -123,24 +102,12 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => (// ── Selectors ────────────────────────────────────────────────────────────────-import { useMemo } from "react"-/**- * Presence unions users + own-bots — every consumer that asks "is X online?"- * gets the right answer regardless of whether X is a human friend or an- * owner's own bot.- *- * Returned Set is memoized on the two slice identities, so consumers used as- * effect deps don't retrigger unless a real presence change happened.+ * Every consumer that asks "is X online?" reads this — the server already+ * pushes bot presence into the same `onlineUserIds` stream as human+ * presence (see the store-level comment above), so this is a direct+ * passthrough, not a union of two sources.*/export const useOnlineUserIds = (): ReadonlySet<string> => {- const users = useCommunityWsStore((s) => s.onlineUserIds)- const bots = useCommunityWsStore((s) => s.onlineBotUserIds)- return useMemo(() => {- if (bots.size === 0) return users- if (users.size === 0) return bots- const merged = new Set<string>(users)- for (const id of bots) merged.add(id)- return merged- }, [users, bots])+ return useCommunityWsStore((s) => s.onlineUserIds)}diff --git a/src/web/src/test/e2e/community-bot-owner-fk.test.ts b/src/web/src/test/e2e/community-bot-owner-fk.test.tsnew file mode 100644index 000000000..36301200a--- /dev/null+++ b/src/web/src/test/e2e/community-bot-owner-fk.test.ts@@ -0,0 +1,64 @@+import { describe, it, expect, afterAll } from "vitest"+import { sql, sqlRun, sqlQuery } from "@alook/test-utils"++/**+ * Real-DB verification for `plans/community-account-debt-fixes.md` Fix 1.+ *+ * `src/web/migrations/0050_community_bots.sql` added `ownerUserId TEXT+ * REFERENCES user(id)` with no explicit `ON DELETE` clause (defaults to+ * `NO ACTION`, i.e. the DB refuses the delete). Cloudflare D1 enforces+ * foreign keys for every transaction, equivalent to `PRAGMA foreign_keys =+ * ON`. This test connects directly to the local D1 sqlite file (bypassing+ * the D1/miniflare query wrapper), so it must opt into that pragma itself —+ * SQLite's own default for a raw connection is OFF — to accurately predict+ * production D1 behavior rather than silently testing against a+ * non-enforcing connection.+ */++const ownerId = "e2e_fk_owner_1"+const botId = "e2e_fk_bot_1"++afterAll(() => {+ // Idempotent cleanup regardless of which assertion ran last.+ sqlRun(`DELETE FROM user WHERE id IN (?, ?)`, botId, ownerId)+})++describe("user.ownerUserId FK (community bot ownership)", () => {+ it("refuses to delete an owner while they still own a live bot", () => {+ sql("PRAGMA foreign_keys = ON")+ sqlRun(`DELETE FROM user WHERE id IN (?, ?)`, botId, ownerId)++ sqlRun(+ `INSERT INTO user (id, email, name) VALUES (?, ?, ?)`,+ ownerId,+ `${ownerId}@example.com`,+ "FK Test Owner",+ )+ sqlRun(+ `INSERT INTO user (id, email, name, isBot, ownerUserId) VALUES (?, ?, ?, 1, ?)`,+ botId,+ `${botId}@example.com`,+ "FK Test Bot",+ ownerId,+ )++ expect(() => sqlRun(`DELETE FROM user WHERE id = ?`, ownerId)).toThrow(+ /FOREIGN KEY constraint failed/i,+ )++ // Owner row must still be there — the failed DELETE must not have+ // partially applied.+ const rows = sqlQuery<{ id: string }>(`SELECT id FROM user WHERE id = ?`, ownerId)+ expect(rows).toHaveLength(1)+ })++ it("allows deleting the owner once the bot is gone", () => {+ sql("PRAGMA foreign_keys = ON")+ // Delete the bot first — clears the FK's referencing row.+ sqlRun(`DELETE FROM user WHERE id = ?`, botId)+ expect(() => sqlRun(`DELETE FROM user WHERE id = ?`, ownerId)).not.toThrow()++ const rows = sqlQuery<{ id: string }>(`SELECT id FROM user WHERE id = ?`, ownerId)+ expect(rows).toHaveLength(0)+ })+})diff --git a/src/ws-do/src/index.test.ts b/src/ws-do/src/index.test.tsindex 6f6be5971..f681dafc6 100644--- a/src/ws-do/src/index.test.ts+++ b/src/ws-do/src/index.test.ts@@ -110,6 +110,22 @@ describe("ws-do router", () => {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",@@ -193,6 +209,8 @@ describe("ws-do router", () => {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/index.ts b/src/ws-do/src/index.tsindex 735260654..330120322 100644--- a/src/ws-do/src/index.ts+++ b/src/ws-do/src/index.ts@@ -101,7 +101,9 @@ export default {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"))+ return stub.fetch(+ new Request(`http://internal/check-user-online?userId=${encodeURIComponent(id)}`)+ )}))const online: string[] = []@@ -122,7 +124,9 @@ export default {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"))+ return stub.fetch(+ new Request(`http://internal/check-user-online?userId=${encodeURIComponent(uid)}`)+ )}// POST /community-machine/by-id/<machineId>/push — push a bot eventdiff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.tsindex aa43268e2..eb33fb7d0 100644--- a/src/ws-do/src/ws-durable.test.ts+++ b/src/ws-do/src/ws-durable.test.ts@@ -44,7 +44,7 @@ globalThis.WebSocketPair = class {// WebSocketRequestResponsePair — used for the ping/pong auto-responseglobalThis.WebSocketRequestResponsePair = class {- constructor(public request: string, public response: string) {}+ constructor(public request: string, public response: string) { }} as unknown as typeof WebSocketRequestResponsePair// --- Module mocks ---@@ -79,6 +79,9 @@ const mockGetFriendUserIds = vi.fn<(db: unknown, userId: string) => Promise<striconst mockGetChannelForMember = vi.fn()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 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.@@ -99,10 +102,10 @@ const mockToSummary = vi.fn((row: any) => ({vi.mock("@alook/shared", () => {const noopLogger = {- debug: () => {},- info: () => {},- warn: () => {},- error: () => {},+ debug: () => { },+ info: () => { },+ warn: () => { },+ error: () => { },child: () => noopLogger,}// Bare-minimum safeParse stubs — the DO only calls `.safeParse(msg)` and@@ -170,6 +173,7 @@ vi.mock("@alook/shared", () => {markMachineOffline: (...a: any[]) => mockMarkMachineOffline(...a),markMachineOnlineIfOffline: (...a: any[]) => mockMarkMachineOnlineIfOffline(...a),toSummary: (row: any) => mockToSummary(row),+ isBotOnline: (...a: [unknown, string]) => mockIsBotOnline(...a),},communityMember: {getCoMemberUserIds: (...a: [unknown, string]) => mockGetCoMemberUserIds(...a),@@ -184,6 +188,12 @@ vi.mock("@alook/shared", () => {communityDm: {getDM: (...a: any[]) => mockGetDM(...a),},+ communityBot: {+ listBotsForMachine: (...a: [unknown, string]) => mockListBotsForMachine(...a),+ },+ user: {+ getUserInternal: (...a: [unknown, string]) => mockGetUserInternal(...a),+ },},}})@@ -217,6 +227,9 @@ describe("WebSocketDurableObject", () => {// don't leak state into unrelated auth-flow tests.mockGetCoMemberUserIds.mockResolvedValue([])mockGetFriendUserIds.mockResolvedValue([])+ mockListBotsForMachine.mockResolvedValue([])+ mockIsBotOnline.mockResolvedValue(false)+ mockGetUserInternal.mockResolvedValue(null)})describe("fetch — WebSocket upgrade", () => {@@ -264,7 +277,7 @@ describe("WebSocketDurableObject", () => {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])+ ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsAuth, wsUnauth])const req = new Request("http://internal/broadcast", {method: "POST",@@ -283,7 +296,7 @@ describe("WebSocketDurableObject", () => {it("returns sent: 0 when no connections exist", async () => {const { durable, ctx } = createDO()- ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([])+ ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([])const req = new Request("http://internal/broadcast", {method: "POST",@@ -304,7 +317,7 @@ describe("WebSocketDurableObject", () => {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])+ ; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsOpen, wsClosed])const req = new Request("http://internal/broadcast", {method: "POST",@@ -319,6 +332,60 @@ describe("WebSocketDurableObject", () => {})})+ 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()+ })+ })+describe("webSocketMessage — auth flow", () => {it("authenticates with valid token and sends auth.ok", async () => {const { durable } = createDO()@@ -495,6 +562,117 @@ describe("WebSocketDurableObject", () => {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()+ })})describe("webSocketMessage — daemon auth flow", () => {@@ -591,7 +769,7 @@ describe("WebSocketDurableObject", () => {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)+ ; (env.WS_DO as any).get = vi.fn().mockReturnValue(aliveStub)const ws = createMockWebSocket()ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })@@ -609,7 +787,7 @@ describe("WebSocketDurableObject", () => {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)+ ; (env.WS_DO as any).get = vi.fn().mockReturnValue(deadStub)const ws = createMockWebSocket()ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })@@ -929,8 +1107,8 @@ describe("WebSocketDurableObject", () => {authenticated: true,})- // Clear any setAlarm calls made during createDO setup.- ;(ctx.storage.setAlarm as any).mockClear?.()+ // Clear any setAlarm calls made during createDO setup.+ ; (ctx.storage.setAlarm as any).mockClear?.()await durable.webSocketClose(ws as any)diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.tsindex a4cfb0fa8..b5deaa83b 100644--- a/src/ws-do/src/ws-durable.ts+++ b/src/ws-do/src/ws-durable.ts@@ -34,11 +34,11 @@ type ConnectionState =| { type: "user"; userId: string; authenticated: boolean }| { type: "daemon"; daemonId: string; userId: string; authenticated: boolean }| {- type: "community-machine"- machineId: string- userId: string- authenticated: boolean- }+ type: "community-machine"+ machineId: string+ userId: string+ authenticated: boolean+ }/*** Persisted identity for the community-machine connection. Written once at@@ -93,6 +93,24 @@ export class WebSocketDurableObject extends DurableObject<Env> {}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.+ const targetUserId = url.searchParams.get("userId")+ if (targetUserId) {+ const db = createDb(this.env.DB)+ const target = await queries.user.getUserInternal(db, targetUserId)+ if (target?.isBot) {+ const online = await queries.communityMachine.isBotOnline(db, targetUserId)+ return new Response(JSON.stringify({ online }), {+ headers: { "Content-Type": "application/json" },+ })+ }+ }const hasAuthUser = this.ctx.getWebSockets().some(ws => {const s = ws.deserializeAttachment() as ConnectionStatereturn s?.type === "user" && s.authenticated@@ -128,7 +146,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {// the next inbound frame.const body = await request.text()const sent = this.forwardToCommunityMachine(body)- await this.clearRuntimeErrorOverlay().catch(() => {})+ await this.clearRuntimeErrorOverlay().catch(() => { })return new Response(JSON.stringify({ sent }), {headers: { "Content-Type": "application/json" },})@@ -245,7 +263,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {// 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(() => {})+ await this.fanOutMachineUpdated(identity.userId, identity.machineId).catch(() => { })}return closed}@@ -292,7 +310,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {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(() => {})+ this.notifyUserDO(authResult.userId, { type: "runtime.status", status: "online", daemonId: msg.daemonId }).catch(() => { })return}@@ -311,10 +329,10 @@ export class WebSocketDurableObject extends DurableObject<Env> {log.info("websocket authenticated", { userId })ws.send(JSON.stringify({ type: "auth.ok" }))if (!wasOnline) {- this.broadcastPresence(userId, true).catch(() => {})+ this.broadcastPresence(userId, true).catch(() => { })}// Send presence snapshot of online co-members + friends- this.sendPresenceSnapshot(ws, userId).catch(() => {})+ this.sendPresenceSnapshot(ws, userId).catch(() => { })return}@@ -402,12 +420,12 @@ export class WebSocketDurableObject extends DurableObject<Env> {const state = ws.deserializeAttachment() as ConnectionStateif (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(() => {})+ 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) - 1if (remaining <= 0) {- this.broadcastPresence(state.userId, false).catch(() => {})+ this.broadcastPresence(state.userId, false).catch(() => { })}}if (state?.type === "community-machine" && state.authenticated) {@@ -441,7 +459,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {machineId: identity.machineId,status: "offline",lastSeenAt: flipped.lastSeenAt ?? new Date().toISOString(),- }).catch(() => {})+ }).catch(() => { })await this.ctx.storage.deleteAlarm()await this.ctx.storage.delete(HANDLE_KEY)await this.ctx.storage.delete(IDENTITY_KEY)@@ -493,7 +511,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {machineId: identity.machineId,status: "online",lastSeenAt: backfilled.lastSeenAt ?? new Date().toISOString(),- }).catch(() => {})+ }).catch(() => { })}} catch (err) {log.warn("markMachineOnlineIfOffline (alarm live-WS) failed", { err: String(err) })@@ -541,7 +559,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {machineId: stored.machineId,status: "offline",lastSeenAt: flipped.lastSeenAt ?? new Date().toISOString(),- }).catch(() => {})+ }).catch(() => { })}} catch (err) {log.warn("markMachineOffline (alarm stale-flip) failed", { err: String(err) })@@ -557,7 +575,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {machineId: stored.machineId,status: "offline",lastSeenAt: machine.lastSeenAt ?? new Date().toISOString(),- }).catch(() => {})+ }).catch(() => { })}// In either branch, this DO's presence lifecycle is done. Drop storage// so a future connection on the same DO name starts clean.@@ -632,7 +650,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {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)- await this.fanOutMachineUpdated(identity.userId, identity.machineId).catch(() => {})+ await this.fanOutMachineUpdated(identity.userId, identity.machineId).catch(() => { })return}@@ -689,7 +707,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {machineId: machine.id,status: "online",lastSeenAt: machine.lastSeenAt ?? new Date().toISOString(),- }).catch(() => {})+ }).catch(() => { })}// Runtime-drift diff. Canonicalized form now includes status/lastError@@ -701,7 +719,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {await this.notifyUserDO(identity.userId, {type: "community:machine.updated",machine: summary,- }).catch(() => {})+ }).catch(() => { })}await this.scheduleHeartbeatAlarm()@@ -751,7 +769,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {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(() => {})+ await this.fanOutMachineUpdated(identity.userId, identity.machineId).catch(() => { })}/**@@ -772,7 +790,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {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 {}+ try { ws.close(1011, "Internal error") } catch { }}private broadcast(message: string): number {@@ -783,7 +801,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {try {ws.send(message)sent++- } catch {}+ } catch { }}}return sent@@ -796,6 +814,43 @@ export class WebSocketDurableObject extends DurableObject<Env> {method: "POST",body: JSON.stringify(payload),}))++ // 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.+ //+ // 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 here vanishes with zero trace. Own try/catch + log so+ // a real failure (bad query, DO unreachable, etc.) is at least visible+ // instead of silently degrading to "you have to refresh to see your bot+ // come online."+ 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 })+ }+ }++ /** 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 !== "community: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> {@@ -881,7 +936,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {return stub.fetch(new Request("http://internal/broadcast", {method: "POST",body: event,- })).catch(() => {})+ })).catch(() => { })}))}@@ -931,10 +986,14 @@ export class WebSocketDurableObject extends DurableObject<Env> {/*** Who should learn about `userId`'s online/offline flips: server- * co-members AND accepted friends. Friends are the common case that a- * co-members-only audience misses entirely — two people can be friends- * without ever sharing a server, which is the whole point of a friends- * list. Deduped so a friend who's also a co-member gets one fetch, not two.+ * co-members AND accepted friends — where "friends" (`getFriendUserIds`)+ * already includes the owner↔own-bot implicit friendship (see+ * `queries/community/friendship.ts`), so a fresh bot with zero servers+ * still reaches its owner with no `isBot` branch needed here. Friends are+ * also the common case that a co-members-only audience misses entirely —+ * two people can be friends without ever sharing a server, which is the+ * whole point of a friends list. Deduped so a friend who's also a+ * co-member gets one fetch, not two.*/private async getPresenceAudience(userId: string): Promise<string[]> {const [coMembers, friends] = await Promise.all([@@ -954,7 +1013,9 @@ export class WebSocketDurableObject extends DurableObject<Env> {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"))+ const resp = await stub.fetch(+ new Request(`http://internal/check-user-online?userId=${encodeURIComponent(memberId)}`)+ )const { online } = await resp.json() as { online: boolean }return online ? memberId : null})