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
refactor(daemon,community): real-infra integration tests, bot create/edit sheets, chat polish
Guscc7c73723539
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex dc472f226..a1351ad09 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -96,6 +96,7 @@ jobs:pnpm --filter @alook/email-worker dev &pnpm --filter @alook/ws-do dev &pnpm --filter @alook/web dev &+ pnpm --filter @alook/wake-worker dev &- name: Wait for services to be readyrun: |wait_for() {@@ -116,7 +117,8 @@ jobs:# First attemptif ! wait_for http://localhost:8787/health "email-worker" || \! wait_for http://localhost:8789/health "ws-do" || \- ! wait_for http://localhost:3000/api/health "web app"; then+ ! wait_for http://localhost:3000/api/health "web app" || \+ ! wait_for http://localhost:8790/health "wake-worker"; thenecho "Some services failed to start, restarting..."pkill -f "wrangler" || truepkill -f "next" || true@@ -124,13 +126,16 @@ jobs:pnpm --filter @alook/email-worker dev &pnpm --filter @alook/ws-do dev &pnpm --filter @alook/web dev &+ pnpm --filter @alook/wake-worker dev &# Second attempt — fail hardwait_for http://localhost:8787/health "email-worker" || exit 1wait_for http://localhost:8789/health "ws-do" || exit 1wait_for http://localhost:3000/api/health "web app" || exit 1+ wait_for http://localhost:8790/health "wake-worker" || exit 1fi- run: pnpm test:e2e- run: pnpm --filter @alook/cli run test:integration+ - run: pnpm --filter @alook/daemon run test:integrationbuild:name: Builddiff --git a/src/daemon/README.md b/src/daemon/README.mdindex a07d235d0..4b1d33780 100644--- a/src/daemon/README.md+++ b/src/daemon/README.md@@ -143,10 +143,8 @@ src/managerRuntime.ts # AgentProcessManager: applies effects to real sessionsserver/contract.ts # ServerApi (data) + EnrollmentApi (machine→runner key) + HostControlChannel (control) + AdminApi- mockServer.ts # in-memory ServerApi+AdminApi+EnrollmentApi (enrollMachine / verifyMachineKey / mintAgentCredential)wsControlServer.ts # server end of the control plane over ws (machine-key authed)wsControlChannel.ts # host end: WebSocket HostControlChannel (injectable socket, reconnect + heartbeat + resync)- localControlChannel.ts # in-process HostControlChannel — unit tests onlydaemon/createDaemon.ts # runtime-agnostic daemon factory (driver/sessionFactory/runtimes INJECTED; no test code)cli/@@ -154,12 +152,8 @@ src/proxyServerApi.ts # agent data-plane client: voucher → proxy → server (identity from the voucher)credentials/credentialProxy.ts # CredentialBroker (mint/revoke/check per-voucher vouchers) + local key-swapping proxy-scripts/ # local-dev scaffolding (the only place "mock" is wired)- mock-server.ts # SERVER process: MockServer + ws (authed) + http (/api /admin /enroll); prints MACHINE_KEY- daemon.ts # DAEMON process: thin launcher — createDaemon + injected mock brain / stub driver- mockAgentBrain.ts # rule-brain stub (test only), driven by the daemon's proxy client- localBridge.ts # the mock-server's HTTP face (/api /admin /enroll)- smoke.ts / test-server.ts # operator surface (admin plane): provision + post + read+scripts/+ daemon.ts # DAEMON process: thin launcher — wraps `alook daemon start` for local dev```## Host orchestration (manager + server)@@ -181,26 +175,21 @@ orchestration so it can run agents end-to-end:bodiless `UnreadNotice` (channel + latest seq, no message content) — the DAEMON(`AgentRouter`/`AgentProcessManager`), not the server, decides whether to spawn aprocess, notify an already-running one, or coalesce the notice for the next turn.- `mockServer.ts` is a fully in-process `ServerApi`/`AdminApi` — data/admin/enrollment- only, with **no** control-plane state (`runningAgents`, unacked deliveries, etc.) and- no dispatch logic of its own; it never decides when to wake an agent. The **control- plane runs over a real WebSocket** so local dev exercises the actual transport, not an- in-process shortcut: `wsControlServer.ts` (server end) and `wsControlChannel.ts`- (host end, injectable socket + exponential-backoff reconnect + heartbeat) carry the- `HostCommand` frames over `ws://127.0.0.1`. `localControlChannel.ts` is kept only for- pure unit tests. A real server connection is the same `WsControlChannel` pointed at a- real URL — nothing upstream changes.--The e2e test `test/e2e/controlPlane.e2e.test.ts` wires `MockServer →(real ws)→-AgentRouter → AgentProcessManager` into a complete loop: provision a server/agent/-channel, post a message, then explicitly push an `agent:wake` `HostCommand` (standing-in for `src/web`'s wake producer + `src/wake-worker`'s consumer) over the socket — the-agent replies back to the channel. Single process, no real runtime, but the control-frames cross an actual WebSocket. The `scripts/` dir runs the same stack across-SEPARATE processes — `mock-server` (the server, which pushes `agent:wake` to a-channel's members right after `postMessage` so `smoke`/`test-server` still see replies)-and `daemon` (machine-key + URL only, no server ref) — with `smoke`/`test-server` as-operators.+ There is no in-process fixture standing in for the server: `wsControlServer.ts`+ (server end) and `wsControlChannel.ts` (host end, injectable socket ++ exponential-backoff reconnect + heartbeat) carry the `HostCommand` frames over+ a real WebSocket (`ws://127.0.0.1` in local dev, a real `ws-do` URL in+ production). A real server connection is the same `WsControlChannel` pointed+ at a real URL — nothing upstream changes.++`tests/integration/daemon/control-plane.test.ts` wires a real `WsControlChannel`+against a running `ws-do dev` server into a complete loop: seed a server/bot/+machine, post a message as a human owner over real HTTP, and assert the daemon's+control channel receives the resulting `agent:wake` `HostCommand` — then, acting+as the agent (no CLI spawned), replies over the real credential chain+(enroll → voucher → proxy → X-Agent-Id) and asserts the reply is readable back+over real HTTP. See "Point a daemon at real infra locally" below for how to run+the pieces this test drives by hand.## Credentials (zero-trust isolation)@@ -279,70 +268,58 @@ This project uses **pnpm** (see the `packageManager` field).```bashpnpm installpnpm run typecheck # tsc --noEmit (passes clean)-pnpm test # vitest — unit + e2e (control plane over real ws)+pnpm test # vitest — unit tests only (drivers/manager/inbox/credentials/server)+pnpm run test:integration # real infra: requires wrangler dev + ws-do dev + wake-worker dev (see below)```-Behavior is covered by the test suite, not runnable example scripts:-`src/**/*.test.ts` (unit — drivers/manager/inbox/credentials/server) and-`test/e2e/*.e2e.test.ts` (the full control plane + credential chain over real ws).+Unit behavior is covered by `src/**/*.test.ts`. Full control-plane and+credential-chain behavior against real infra is covered by+[`tests/integration/daemon/`](../../tests/integration/daemon) — see that+directory for the executable reference of how the pieces fit together over+the network (real `WsControlChannel` over a real WebSocket, real+`enroll-agent`/credential-proxy HTTP calls, no in-process shortcuts).-### Local end-to-end (two real processes)+### Point a daemon at real infra locally-`pnpm test` already exercises everything in-process. To watch it run for real-across **separate processes** — the way a deployed daemon talks to a server,-purely over the network — use the split stack. The daemon holds only a machine-key + the server's URLs; it never holds a server reference.+There's no mock server to stand in for `src/web`/`src/ws-do` — a daemon+always talks to the real thing. To drive one by hand in local dev, run the+real servers and walk the real credential chain (`cmt_` pairing token →+`cmk_` daemon credential → `crk_` per-agent runner key):-**Terminal 1 — the server.** Prints a machine key + its URLs:+**Terminal 1 — the web app + control-plane DO:**```bash-pnpm run mock-server-# MACHINE_KEY=sk_machine_…-# SERVER_URL=http://127.0.0.1:4517-# SERVER_WS_URL=ws://127.0.0.1:4518+pnpm --filter @alook/web dev # http://localhost:3000+pnpm --filter @alook/ws-do dev # ws://localhost:8789```-**Terminal 2 — a daemon**, given that machine key + those URLs (copy the three-values printed above). It connects the control plane (machine-key authed) and-starts the per-agent credential proxy:+**Terminal 2 — pair + activate a machine**, then start a daemon with the+resulting `cmk_...` credential:```bash-ALOOK_MACHINE_KEY=sk_machine_… \-ALOOK_SERVER_URL=http://127.0.0.1:4517 \-ALOOK_SERVER_WS_URL=ws://127.0.0.1:4518 \+# 1. As a signed-in user, create a pairing token:+curl -s -X POST http://localhost:3000/api/community/machines/pair \+ -H "Cookie: <session-cookie>" | tee /tmp/pair.json+# → { "tokenId": "cmt_…", "expiresAt": "…" }++# 2. Exchange it for a daemon credential:+curl -s -X POST http://localhost:3000/api/community/daemon/activate \+ -H "Authorization: Bearer $(jq -r .tokenId /tmp/pair.json)" \+ -H "content-type: application/json" \+ -d '{"hostname":"my-laptop","platform":"darwin","arch":"arm64"}'+# → { "credential": "cmk_…", "machineId": "cm_…", "expiresAt": null }++# 3. Start the daemon with that credential:+ALOOK_MACHINE_KEY=cmk_… \+ALOOK_SERVER_URL=http://localhost:3000 \+ALOOK_SERVER_WS_URL=ws://localhost:8789 \pnpm run daemon-# → [daemon] control plane OPEN (machineKey accepted)```-**Terminal 3 — drive it.** `smoke` provisions a user / 3 agents / a server /-a channel, posts a message, and reads the transcript back — each agent replies-"hi!" through the real credential chain (enroll → voucher → proxy → X-Agent-Id):--```bash-pnpm run smoke-# → result: 3 agent replies (expected 3)-```--`test-server` is the same operator surface as one-off commands (e.g.-`pnpm run test-server -- post --channel /<server>/<channel> --text hi`).--**Verify auth is real (it rejects).** Start the daemon in Terminal 2 with a bogus-key — it never reaches "control plane OPEN" (the server closes the connection),-and the enroll endpoint refuses it:--```bash-ALOOK_MACHINE_KEY=sk_machine_FORGED ALOOK_SERVER_URL=http://127.0.0.1:4517 \-ALOOK_SERVER_WS_URL=ws://127.0.0.1:4518 pnpm run daemon # never logs OPEN-curl -s -X POST http://127.0.0.1:4517/enroll/agent-credential \- -H "Authorization: Bearer sk_machine_FORGED" -H "content-type: application/json" \- -d '{"agentId":"x"}'-# → {"error":"unknown or invalid machine key","code":"UNAUTHORIZED_MACHINE"}-```--The daemon process holds only a machine key + URLs — no server object, no admin-access — so the local mock walks the *same* credential code a real agent would,-and identity can't be forged. `smoke`/`test-server` act as the server-side-operator (admin plane); the daemon can't reach that surface.+A bot bound to this machine (via the community UI/API) can now be woken by+posting a message in a channel it's a member of — the real wake-producer path+(`src/web` → `src/wake-worker` → `src/ws-do`) delivers `agent:wake` over the+daemon's real `WsControlChannel`.> **Run the source, not `dist/` (yet).** `pnpm run build` emits JS, but the> current Bundler-resolution emit produces extensionless relative imports thatdiff --git a/src/daemon/package.json b/src/daemon/package.jsonindex d2e2b67e6..e6c3bdffe 100644--- a/src/daemon/package.json+++ b/src/daemon/package.json@@ -23,11 +23,9 @@"typecheck": "tsc --noEmit","test": "vitest run","test:watch": "vitest",+ "test:integration": "vitest run --config ../../tests/integration/daemon/vitest.config.ts --passWithNoTests","lint": "eslint .",- "mock-server": "tsx scripts/mock-server.ts",- "daemon": "tsx scripts/daemon.ts",- "test-server": "tsx scripts/test-server.ts",- "smoke": "tsx scripts/smoke.ts"+ "daemon": "tsx scripts/daemon.ts"},"license": "Apache-2.0","private": true,diff --git a/src/daemon/scripts/localBridge.ts b/src/daemon/scripts/localBridge.tsdeleted file mode 100644index 32d81d641..000000000--- a/src/daemon/scripts/localBridge.ts+++ /dev/null@@ -1,152 +0,0 @@-/**- * The mock-server's HTTP face. The `mock-server` process serves this so other- * processes (the daemon, `test-server`) reach the server ONLY over the network:- * - ENROLL route (POST /enroll/agent-credential) → a daemon exchanges its- * machine key for a per-agent runner key.- * - DATA routes (POST /api/*) → the agent data plane, reached by agents- * THROUGH their credential proxy (which stamps a trusted X-Agent-Id).- * - ADMIN routes (POST /admin/*) → server-side provisioning, used only by- * `test-server`. The daemon is a separate process and never reaches admin.- *- * The daemon connects to the control plane (ws) and these HTTP planes purely by- * URL — it holds no server reference. That process boundary is what enforces the- * admin/daemon separation, structurally rather than by discipline.- */-import * as http from "http";-import type { AdminApi, ServerApi, EnrollmentApi } from "../src/server/contract";--const ADMIN_METHODS = new Set([- "createUser",- "createAgent",- "createServer",- "addAgentToServer",- "createChannel",- "postMessage",- "readChannel",- "createInvite",-]);-const API_METHODS = new Set([- "inboxPull",- "inboxSnapshot",- "ack",- "send",- "read",- "resolve",- "listServers",- "listChannels",- "listMembers",- "joinServer",- "subscribeChannel",-]);--export interface BridgeDeps {- admin: AdminApi;- api: ServerApi;- /** Machine-credential surface (daemon authed by machineKey). Optional. */- enrollment?: EnrollmentApi;-}--export function startLocalBridge(deps: BridgeDeps, port: number): Promise<{ url: string; close: () => Promise<void> }> {- const server = http.createServer((req, res) => void handle(req, res, deps));- return new Promise((resolve, reject) => {- // Surface a listen failure (e.g. EADDRINUSE) as a rejection with a hint,- // instead of an unhandled 'error' that crashes with a raw stack trace.- server.once("error", (err: NodeJS.ErrnoException) => {- if (err.code === "EADDRINUSE") {- reject(new Error(`http port ${port} is in use — free it or set ALOOK_SERVER_PORT to another port`));- } else {- reject(err);- }- });- server.listen(port, "127.0.0.1", () => {- const addr = server.address();- const p = typeof addr === "object" && addr ? addr.port : port;- resolve({- url: `http://127.0.0.1:${p}`,- close: () => new Promise((r) => server.close(() => r())),- });- });- });-}--async function handle(req: http.IncomingMessage, res: http.ServerResponse, deps: BridgeDeps): Promise<void> {- try {- const url = new URL(req.url ?? "/", "http://127.0.0.1");-- // ENROLLMENT plane: a daemon exchanges its machine key (Bearer) for a- // per-agent runner key. Authed by the machineKey, NOT admin/agent identity.- if (req.method === "POST" && url.pathname === "/enroll/agent-credential") {- if (!deps.enrollment) return send(res, 404, { error: "enrollment not available" });- const machineKey = parseBearer(req.headers["authorization"]);- if (!machineKey) return send(res, 401, { error: "missing machine key", code: "missing_machine_key" });- const body = (await readBody(req)) as { agentId?: string };- if (!body.agentId) return send(res, 400, { error: "agentId is required" });- const result = await deps.enrollment.mintAgentCredential({ machineKey, agentId: body.agentId });- return send(res, 200, result);- }-- const m = /^\/(admin|api)\/(\w+)$/.exec(url.pathname);- if (req.method !== "POST" || !m) return send(res, 404, { error: "not found" });- const [, plane, method] = m;- const target = plane === "admin" ? deps.admin : deps.api;- const allowed = plane === "admin" ? ADMIN_METHODS : API_METHODS;- if (!allowed.has(method)) return send(res, 404, { error: `unknown ${plane} method ${method}` });- const body = (await readBody(req)) as Record<string, unknown>;-- // DATA plane is the untrusted HTTP boundary: the agent's identity is NOT- // self-asserted. The credential proxy validated the voucher and stamped a- // trusted `X-Agent-Id` (derived from the voucher, not the wire). We take- // agentId ONLY from that header and OVERRIDE any body value — header-only,- // no body fallback — so a forged body agentId can never take effect. A data- // request without the header is rejected (the proxy must front it).- let callBody: unknown = body;- if (plane === "api") {- const headerAgentId = req.headers["x-agent-id"];- const agentId = Array.isArray(headerAgentId) ? headerAgentId[0] : headerAgentId;- if (!agentId) {- return send(res, 401, {- error: "missing X-Agent-Id — data-plane requests must come through the credential proxy",- code: "missing_agent_identity",- });- }- callBody = { ...body, agentId };- }-- const fn = (target as unknown as Record<string, (a: unknown) => Promise<unknown>>)[method];- const result = await fn.call(target, callBody);- send(res, 200, result ?? {});- } catch (err) {- send(res, 400, { error: (err as Error).message, code: (err as { code?: string }).code });- }-}--async function readBody(req: http.IncomingMessage): Promise<unknown> {- const chunks: Buffer[] = [];- for await (const c of req) chunks.push(c as Buffer);- const raw = Buffer.concat(chunks).toString("utf8");- return raw ? JSON.parse(raw) : {};-}--function parseBearer(authHeader: string | string[] | undefined): string | null {- const h = Array.isArray(authHeader) ? authHeader[0] : authHeader;- if (!h) return null;- const m = /^Bearer\s+(.+)$/i.exec(h.trim());- return m ? m[1].trim() : null;-}--function send(res: http.ServerResponse, status: number, body: unknown): void {- res.writeHead(status, { "content-type": "application/json" });- res.end(JSON.stringify(body));-}--/** Minimal client used by test-server / the alook CLI to call the bridge. */-export async function bridgeCall<T>(baseUrl: string, plane: "admin" | "api", method: string, body: unknown): Promise<T> {- const res = await fetch(`${baseUrl}/${plane}/${method}`, {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify(body ?? {}),- });- const json = (await res.json()) as T & { error?: string };- if (!res.ok) throw new Error((json as { error?: string }).error ?? `bridge ${plane}/${method} failed`);- return json;-}diff --git a/src/daemon/scripts/mock-server.ts b/src/daemon/scripts/mock-server.tsdeleted file mode 100644index c163f845e..000000000--- a/src/daemon/scripts/mock-server.ts+++ /dev/null@@ -1,156 +0,0 @@-/**- * `pnpm run mock-server` — the SERVER process (terminal 1).- *- * A standalone Alook mock server. It owns ALL server state and the only- * privileged surfaces; the daemon (separate process) can reach it ONLY over the- * network, exactly as it would a real server:- *- * - control plane (ws): server → daemon commands (agent:wake/stop),- * daemon → server reports (ready/session/ack).- * This mock never decides WHEN to send agent:wake —- * that's `src/web`/`src/wake-worker`'s job in- * production. It only logs what the daemon reports.- * Daemons must connect with `Authorization: Bearer- * <machineKey>` — unauthenticated connections are- * refused (`verifyMachineKey`).- * - enroll plane (http): POST /enroll/agent-credential, Bearer <machineKey> →- * a per-agent runner key. How a daemon turns its machine- * identity into per-agent credentials.- * - data plane (http): POST /api/* — the agent data plane, reached by agents- * THROUGH their credential proxy (which stamps a trusted- * X-Agent-Id). The bridge trusts that header.- * - admin plane (http): POST /admin/* — provisioning, for `test-server` only.- * The daemon process never reaches this (different proc).- *- * At startup it enrolls this machine and prints `MACHINE_KEY=sk_machine_…` on its- * own line so a script (or a human) can hand that key to the daemon. Nothing here- * is shared in-process with the daemon — the only contract between them is the- * network surfaces above.- */-import { WebSocketServer } from "ws";-import type { IncomingMessage } from "http";-import { MockServer, WsControlServer } from "../src/server/index";-import type { HostCommand } from "../src/server/contract";-import { makeRuntimeConfig } from "../src/runtimeConfig";-import { startLocalBridge } from "./localBridge";--const HTTP_PORT = Number(process.env.ALOOK_SERVER_PORT || 4517);-const WS_PORT = Number(process.env.ALOOK_SERVER_WS_PORT || HTTP_PORT + 1);--async function main() {- const server = new MockServer();-- // Enroll THIS machine and surface its key for the daemon (script greps this line).- const machineKey = server.enrollMachine();-- // Control plane: a ws server, authenticated by machine key. The factory adapts- // `ws`'s (socket, request) connection event into our (socket, meta) shape,- // pulling the upgrade request's Authorization header through for verification.- // This mock never pushes `agent:wake` on its own — it's a pure transport +- // data/admin/enroll fixture. Waking a daemon here is manual (see below).- const wsServer = new WsControlServer({- port: WS_PORT,- verifyMachineKey: (authHeader) => {- const ok = server.verifyMachineKey(parseBearer(authHeader));- if (ok) {- console.log(`[mock-server] daemon connected (machine key verified ✓)`);- } else {- console.log(`[mock-server] daemon connection REJECTED (invalid machine key)`);- }- return ok;- },- onReady: (ready) => {- console.log(`[mock-server] daemon ready — reported ${ready.runningAgents.length} running agent(s)${ready.runningAgents.length ? `: ${ready.runningAgents.join(", ")}` : ""}`);- },- onAgentSession: (info) => {- console.log(`[mock-server] agent session: ${info.agentId} → session=${info.sessionId}`);- },- onWakeAck: (info) => {- console.log(`[mock-server] agent_wake_ack: ${info.agentId} launch=${info.launchId} status=${info.status}`);- },- onStoppedAck: (info) => {- console.log(`[mock-server] agent_stopped_ack: ${info.agentId} status=${info.status}`);- },- webSocketServerFactory: (port) => {- const wss = new WebSocketServer({ host: "127.0.0.1", port });- wss.on("error", (err: NodeJS.ErrnoException) => {- if (err.code === "EADDRINUSE") {- console.error(- `[mock-server] ws port ${port} is in use — another mock-server is likely running.\n` +- ` Free it (e.g. \`lsof -nP -iTCP:${port} -sTCP:LISTEN\` then kill the PID), ` +- `or set ALOOK_SERVER_WS_PORT (and ALOOK_SERVER_PORT) to other ports.`,- );- } else {- console.error(`[mock-server] ws server error: ${err.message}`);- }- process.exit(1);- });- return {- on: (_event, cb) =>- wss.on("connection", (socket, req: IncomingMessage) =>- cb(socket as never, { authHeader: req.headers["authorization"] }),- ),- close: (cb) => wss.close(cb),- };- },- });- wsServer.start();-- // Stand-in for the real wake producer/consumer (src/web + src/wake-worker):- // after a message is stored, explicitly push `agent:wake` to every member- // of the channel so `pnpm run smoke` still sees replies. MockServer itself- // makes no such decision — see its class doc comment.- const originalPostMessage = server.postMessage.bind(server);- server.postMessage = async (req) => {- const result = await originalPostMessage(req);- for (const agentId of server.membersOf(req.channel)) {- const config = server.getAgentConfig(agentId) ?? makeRuntimeConfig({ runtime: "mock" });- const cmd: HostCommand = {- type: "agent:wake",- agentId,- config,- launchId: `launch_${agentId}_${result.message.seq}`,- unreadNotice: { kind: "unread_notice", channel: req.channel, latestSeq: Number(result.message.seq.replace("#", "")) },- };- const sent = wsServer.pushCommand(cmd);- console.log(`[mock-server] postMessage → agent:wake ${agentId} (${sent ? "sent" : "no daemon connected"})`);- }- return result;- };-- // HTTP planes: data (/api), admin (/admin), enroll (/enroll). Same process as- // the server state — this is the SERVER side; the daemon connects from outside.- const bridge = await startLocalBridge({ admin: server, api: server, enrollment: server }, HTTP_PORT);-- const wsUrl = `ws://127.0.0.1:${WS_PORT}`;- // One line per fact; MACHINE_KEY first so `grep '^MACHINE_KEY='` is trivial.- console.log(`MACHINE_KEY=${machineKey}`);- console.log(`SERVER_URL=${bridge.url}`);- console.log(`SERVER_WS_URL=${wsUrl}`);- console.log(`[mock-server] up — control ws (machineKey-authed) + http (/api /admin /enroll)`);- console.log(`[mock-server] waiting for a daemon to connect… (Ctrl-C to stop)`);- console.log(`\n[mock-server] start a daemon in another terminal:\n`);- console.log(- ` ALOOK_MACHINE_KEY=${machineKey} ALOOK_SERVER_URL=${bridge.url} ALOOK_SERVER_WS_URL=${wsUrl} pnpm run daemon\n`,- );-- const shutdown = async () => {- console.log("\n[mock-server] shutting down…");- await wsServer.close();- await bridge.close();- process.exit(0);- };- process.on("SIGINT", shutdown);- process.on("SIGTERM", shutdown);-}--function parseBearer(authHeader: string | undefined): string | undefined {- if (!authHeader) return undefined;- const m = /^Bearer\s+(.+)$/i.exec(authHeader.trim());- return m ? m[1].trim() : undefined;-}--main().catch((e) => {- console.error(e);- process.exit(1);-});diff --git a/src/daemon/scripts/smoke.ts b/src/daemon/scripts/smoke.tsdeleted file mode 100644index 333037eb5..000000000--- a/src/daemon/scripts/smoke.ts+++ /dev/null@@ -1,117 +0,0 @@-/**- * `pnpm run smoke` — multi-agent smoke test with real Claude runtimes.- *- * smoke plays the OPERATOR / server-side role (a human provisioning + posting),- * NOT the daemon. It talks ONLY to the mock-server's ADMIN plane (`/admin/*`):- * create user/agents/server/channel, post a message, then poll until all agents- * have replied. The agents' replies are produced by the SEPARATE daemon process- * over the real credential chain (enroll → voucher → proxy → X-Agent-Id).- *- * Against a running mock-server's admin bridge, it:- * 1. creates a user,- * 2. creates 3 agents owned by that user (runtime=claude),- * 3. creates a server + a #general channel,- * 4. adds all 3 agents into that server,- * 5. posts a message to #general,- * 6. polls the transcript until all 3 agents have replied (up to 120s),- * 7. verifies each agent's reply + timeline file existence.- *- * Requires both processes up: `pnpm run mock-server` (the server) and a- * `pnpm run daemon` connected to it.- */-import { bridgeCall } from "./localBridge";--const BASE = process.env.ALOOK_BRIDGE_URL || `http://127.0.0.1:${process.env.ALOOK_BRIDGE_PORT || 4517}`;-const admin = <T>(method: string, body: unknown) => bridgeCall<T>(BASE, "admin", method, body);--const AGENT_NAMES = ["cindy", "devon", "echo"];-const POLL_INTERVAL_MS = 5_000;-const MAX_WAIT_MS = 120_000;--async function main(): Promise<number> {- console.log(`smoke: bridge=${BASE}`);-- const { user } = await admin<{ user: { id: string; name: string } }>("createUser", { name: "me" });- console.log(` user: ${user.name} (${user.id})`);-- const agents: { id: string; name: string }[] = [];- for (const name of AGENT_NAMES) {- const { agent } = await admin<{ agent: { id: string; name: string } }>("createAgent", {- userId: user.id,- name,- runtime: "claude",- instruction: "You are a test agent. Reply briefly to any message you receive.",- });- agents.push(agent);- console.log(` agent: ${agent.name} (${agent.id})`);- }-- const { server } = await admin<{ server: { id: string; name: string } }>("createServer", { name: "demo" });- console.log(` server: ${server.name} (${server.id})`);-- for (const a of agents) await admin("addAgentToServer", { agentId: a.id, server: server.id });- console.log(` added ${agents.length} agents → ${server.name}`);-- const { channel } = await admin<{ channel: { id: string; name: string } }>("createChannel", {- server: server.id,- name: "general",- });- const channelRef = `/${server.id}/general`;- console.log(` channel: ${channelRef} (${channel.id})`);-- const commandText = "报数,从1开始,每个人只能报一次就停止自己的报数"- console.log(`\nposting ${commandText} to ${channelRef} …`);- await admin("postMessage", { channel: channelRef, sender: "@gustavo", text: commandText });-- // Poll until all agents have replied or timeout.- console.log(`\nwaiting for ${AGENT_NAMES.length} agent replies (timeout ${MAX_WAIT_MS / 1000}s)…`);- const start = Date.now();- let replies = 0;- const seen = new Set<string>();- let page: { items: Array<{ seq: string; sender: string; content: { text: string } }> } = { items: [] };-- while (Date.now() - start < MAX_WAIT_MS) {- page = await admin<typeof page>("readChannel", { channel: channelRef, limit: 50 });- for (const m of page.items) {- if (m.sender === "@gustavo") continue;- if (seen.has(m.sender)) continue;- seen.add(m.sender);- const elapsed = Math.round((Date.now() - start) / 1000);- console.log(` [${elapsed}s] ${m.sender}: ${m.content.text}`);- }- replies = seen.size;- if (replies >= AGENT_NAMES.length) break;- await delay(POLL_INTERVAL_MS);- }-- console.log(`\n${channelRef} transcript:`);- for (const m of page.items) console.log(` ${m.seq} ${m.sender}: ${m.content.text}`);-- console.log(`\nresult: ${replies} agent replies (expected ${AGENT_NAMES.length})`);- if (replies < AGENT_NAMES.length) {- console.error("FAIL: not all agents replied within timeout");- return 1;- }-- // Verify distinct senders (each agent replied independently).- const senders = new Set(page.items.filter((m) => m.sender !== "@gustavo").map((m) => m.sender));- if (senders.size < AGENT_NAMES.length) {- console.error(`FAIL: only ${senders.size} distinct agent senders (expected ${AGENT_NAMES.length})`);- return 1;- }-- console.log("PASS: all agents replied independently ✓");- return 0;-}--function delay(ms: number): Promise<void> {- return new Promise((r) => setTimeout(r, ms));-}--main()- .then((c) => process.exit(c))- .catch((e) => {- console.error(`smoke failed: ${e.message}`);- console.error("(is `pnpm run mock-server` + `alook daemon start` running in another terminal?)");- process.exit(1);- });diff --git a/src/daemon/scripts/test-server.ts b/src/daemon/scripts/test-server.tsdeleted file mode 100644index 81ecee95d..000000000--- a/src/daemon/scripts/test-server.ts+++ /dev/null@@ -1,121 +0,0 @@-/**- * `pnpm run test-server -- <cmd> [flags]` — terminal 2.- *- * A thin ADMIN client against the mock-server's admin bridge — it simulates a- * user/server-side operator provisioning and posting. It is intentionally NOT- * part of the `alook` CLI (production source stays clean) and only reaches admin- * routes the daemon process can never call.- *- * Commands:- * create-user --name me- * create-agent --user <userId> --name cindy --runtime claude- * create-server --name demo- * add-agent --agent <agentId> --server <serverId>- * create-channel --server <serverId> --name general- * post --channel /demo/general --text "hi" [--sender @gustavo]- * read --channel /demo/general (data-plane convenience)- */-import { bridgeCall } from "./localBridge";--const BASE = process.env.ALOOK_BRIDGE_URL || `http://127.0.0.1:${process.env.ALOOK_BRIDGE_PORT || 4517}`;--function parse(argv: string[]): { cmd: string; flags: Record<string, string>; pos: string[] } {- const [cmd, ...rest] = argv;- const flags: Record<string, string> = {};- const pos: string[] = [];- for (let i = 0; i < rest.length; i++) {- if (rest[i].startsWith("--")) {- flags[rest[i].slice(2)] = rest[i + 1] ?? "";- i++;- } else {- pos.push(rest[i]);- }- }- return { cmd: cmd ?? "", flags, pos };-}--async function main(): Promise<number> {- const { cmd, flags, pos } = parse(process.argv.slice(2));- const admin = <T>(method: string, body: unknown) => bridgeCall<T>(BASE, "admin", method, body);- // Accept both `--flag value` and bare positionals (npm strips flags without `--`).- const arg = (flag: string, posIdx: number): string | undefined => flags[flag] ?? pos[posIdx];-- switch (cmd) {- case "create-user": {- const name = need(arg("name", 0), "name");- const r = await admin<{ user: { id: string; name: string } }>("createUser", { name });- console.log(`created user: ${r.user.name} (${r.user.id})`);- return 0;- }- case "create-agent": {- const userId = need(arg("user", 0), "user");- const name = need(arg("name", 1), "name");- const r = await admin<{ agent: { id: string; name: string } }>("createAgent", {- userId,- name,- runtime: need(arg("runtime", 2), "runtime"),- });- console.log(`created agent: ${r.agent.name} (${r.agent.id}) [owner=${userId}]`);- return 0;- }- case "create-server": {- const name = need(arg("name", 0), "name");- const r = await admin<{ server: { id: string; name: string } }>("createServer", { name });- console.log(`created server: ${r.server.name} (${r.server.id})`);- return 0;- }- case "add-agent": {- const agentId = need(arg("agent", 0), "agent");- const server = need(arg("server", 1), "server");- await admin("addAgentToServer", { agentId, server });- console.log(`added agent ${agentId} → server ${server}`);- return 0;- }- case "create-channel": {- const server = need(arg("server", 0), "server");- const name = need(arg("name", 1), "name");- const r = await admin<{ channel: { id: string; name: string } }>("createChannel", { server, name });- console.log(`created channel: /${server}/${r.channel.name} (${r.channel.id})`);- return 0;- }- case "post": {- const channel = need(arg("channel", 0), "channel");- const text = need(arg("text", 1), "text");- const r = await admin<{ message: { channel: string; seq: string } }>("postMessage", {- channel,- sender: flags.sender || "@gustavo",- text,- });- console.log(`posted: ${r.message.channel}${r.message.seq}`);- return 0;- }- case "read": {- const channel = need(arg("channel", 0), "channel");- // Observability read via the ADMIN plane (no agent identity); the agent- // data plane now requires a proxy-stamped X-Agent-Id.- const r = await admin<{ items: Array<{ channel: string; seq: string; sender: string; content: { text: string } }> }>(- "readChannel",- { channel, limit: 50 },- );- for (const m of r.items) console.log(` ${m.channel}${m.seq} ${m.sender}: ${m.content.text}`);- if (r.items.length === 0) console.log(" (empty)");- return 0;- }- default:- console.error(- "usage: pnpm run test-server -- <create-user|create-agent|create-server|add-agent|create-channel|post|read> [args]",- );- return 2;- }-}--/** Require a value (from flag or positional), else fail with a clear message. */-function need(v: string | undefined, label: string): string {- if (v === undefined || v === "") throw new Error(`missing "${label}" (pass --${label} <value> or as a positional)`);- return v;-}--main().then((c) => process.exit(c)).catch((e) => {- console.error(`error: ${e.message}`);- process.exit(1);-});diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.tsindex 825284963..ad9c5add2 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -12,9 +12,10 @@* the agent says), and forwards to the data-plane upstream. So the agent's* identity is established by the voucher it holds, never self-asserted.*- * This is the code the mock agent reuses verbatim in local dev — the only thing- * that differs locally is that the proxy's upstream points at the in-process- * bridge instead of a remote server. The credential + verification path is real.+ * This is the code the integration-test harness reuses verbatim — the only+ * thing that differs is that the proxy's upstream points at a local `wrangler+ * dev` instance instead of a deployed server. The credential + verification+ * path is real.*/import * as fs from "fs";import type {diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex 53cba1399..2db3b1198 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -16,8 +16,8 @@* All agent traffic flows through here.** It is agnostic on both axes:- * - whether the server is a real Alook server or the local `mock-server`- * — same wire contract either way;+ * - whether the server is a real Alook server or a local `wrangler dev`+ * instance — same wire contract either way;* - whether an agent is a real runtime (Claude, Codex, …) or a test stub* — the `driverFor` is INJECTED by the caller.*/diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.tsindex e19207151..daf6f6fe5 100644--- a/src/daemon/src/drivers/systemPrompt.ts+++ b/src/daemon/src/drivers/systemPrompt.ts@@ -102,7 +102,7 @@ function cliCommandsSection(): string {return ["## CLI commands","",- `\`${CLI}\` is your command-line interface. Commands are grouped by category below;`,+ `\`${CLI}\` is your command-line interface. Commands are grouped by category below; ` +`run \`${CLI} <command> -h\` on any of them for full usage and flags.`,"","### Messaging",@@ -163,12 +163,7 @@ function messagingSection(): string {"","Use the `channel` field from received messages as the `--target` when replying.","To reply in a thread, use the thread ref (`/<server>/<channel>/#N`).",- "",- "These same refs also work inline, inside a message's `--text`/`--file` body — not just",- "as `--target`. Write `/<server>/<channel>` or `/<server>/<channel>/#N` anywhere in your",- "message text (preceded by a space or at the start) and it renders as a clickable channel",- "or thread link for human readers in the web client. Use this to cross-reference other",- "channels/threads naturally instead of describing them in prose.",+ "These same refs also work inline, inside a message's `--text`/`--file` body — not just as `--target`. Write `/<server>/<channel>` or `/<server>/<channel>/#N` anywhere in your message text (preceded by a space or at the start) and it renders as a clickable channel or thread link for human readers in the web client. Use this to cross-reference other channels/threads naturally instead of describing them in prose.","","### Message shape","",@@ -197,10 +192,10 @@ function serversSection(): string {return ["## Servers","",- `If a message contains a \`/community/invite/...\` link, just run \`${CLI} server join --invite <link>\`.`,- "The server enforces an owner-only check for you — it only accepts an invite your owner created,",- "and rejects anything else with a clear reason. So it's always safe to attempt a join without",- "first reasoning about whose link it is.",+ `If a message contains a \`/community/invite/...\` link, just run \`${CLI} server join --invite <link>\`. ` ++ "The server enforces an owner-only check for you — it only accepts an invite your owner created, and " ++ "rejects anything else with a clear reason. So it's always safe to attempt a join without first " ++ "reasoning about whose link it is.",].join("\n");}@@ -213,13 +208,13 @@ function channelsSection(): string {return ["## Channels","",- `\`${CLI} channel list\`'s items are \`{ref, name, type}\` — \`ref\` is directly reusable as`,- "`--channel`/`--target` on every other command, no separate id lookup needed. `type` is",+ `\`${CLI} channel list\`'s items are \`{ref, name, type}\` — \`ref\` is directly reusable as ` ++ "`--channel`/`--target` on every other command, no separate id lookup needed. `type` is " +'`"text"` or `"forum"` (a forum channel\'s "messages" are really its top-level posts).',"",- `\`${CLI} channel subscribe mentions --channel <ref>\` only changes WHEN you're woken, never`,- "WHAT you can see: a `mentions`-subscribed channel still delivers its non-mention messages via",- `\`${CLI} inbox pull\`/\`${CLI} channel history\` — you just aren't proactively woken for them.`,+ `\`${CLI} channel subscribe mentions --channel <ref>\` only changes WHEN you're woken, never ` ++ "WHAT you can see: a `mentions`-subscribed channel still delivers its non-mention messages via " ++ `\`${CLI} inbox pull\`/\`${CLI} channel history\` — you just aren't proactively woken for them. ` +`Re-subscribing to \`all\` restores the default (woken for every message).`,].join("\n");}@@ -233,14 +228,14 @@ function criticalRulesSection(): string {return ["## Critical rules","",- "- Do not expose tokens, keys, or secrets in any message or channel; redact",- " credential-like strings from tool output before sharing.",- "- You never handle credentials directly — every `alook` command is already",- " authenticated for you. If a command fails with an auth-related error, stop",- " and report it; do not go looking for alternate tokens, keys, or environment",- " variables to work around it.",- "- **Channel alignment**: you cannot send to a channel with unread messages. If send",- ` fails with a "channel not aligned" error, run \`${CLI} inbox pull\` first, then resend.`,+ "- Do not expose tokens, keys, or secrets in any message or channel; redact " ++ "credential-like strings from tool output before sharing.",+ "- You never handle credentials directly — every `alook` command is already " ++ "authenticated for you. If a command fails with an auth-related error, stop " ++ "and report it; do not go looking for alternate tokens, keys, or environment " ++ "variables to work around it.",+ "- **Channel alignment**: you cannot send to a channel with unread messages. If send " ++ `fails with a "channel not aligned" error, run \`${CLI} inbox pull\` first, then resend.`,"- Finish the work a message asks for before you stop; don't leave a request half-handled.",].join("\n");}@@ -294,21 +289,21 @@ function workspaceMemorySection(): string {"","### memory.md","",- "Read `./memory.md` first on every wake. It holds durable facts (user profile, project",+ "Read `./memory.md` first on every wake. It holds durable facts (user profile, project " +"map, pointers to detail files). Keep each entry short (one sentence, <140 chars).","","### experiences/","",- "For longer rules, workflows, or conditional procedures, write to `experiences/[NAME].md`",- "and add a one-line index pointer in `./memory.md` (e.g. \"read experiences/deploy.md",+ "For longer rules, workflows, or conditional procedures, write to `experiences/[NAME].md` " ++ "and add a one-line index pointer in `./memory.md` (e.g. \"read experiences/deploy.md " +"when deploying\"). Use this for anything too specific or long for memory.md itself.","",- "Do NOT put ephemeral state (current task, in-progress status) in memory.md — the",+ "Do NOT put ephemeral state (current task, in-progress status) in memory.md — the " +"context timeline handles that.","","### Context timeline","",- "`./.context_timeline/YYYY-MM-DD.jsonl` — ordered log of everything you did, by day.",+ "`./.context_timeline/YYYY-MM-DD.jsonl` — ordered log of everything you did, by day. " +"This is your authoritative history. After compaction, read here to resume.",].join("\n");}@@ -329,21 +324,21 @@ function messageNotificationSection(lifecycleKind: SystemPromptOpts["lifecycleKireturn ["## Message notifications","",- "You run once per wake, then your process exits — there is nothing to poll for mid-turn.",- "Finish the current wake's work, then stop. The host spawns a brand-new process for the",+ "You run once per wake, then your process exits — there is nothing to poll for mid-turn. " ++ "Finish the current wake's work, then stop. The host spawns a brand-new process for the " +"next message; it re-checks the inbox at the start of that new wake.",].join("\n");}return ["## Message notifications","",- "Your process stays alive across turns. Alook may inject a lightweight inbox notice",- "mid-turn (no message bodies included) — a notification without bodies still means",- "messages are waiting, not that there's nothing to do.",- `Pulling and acknowledging them IS time-sensitive: at the next natural breakpoint, run`,- `\`${CLI} inbox pull\` and send a brief ack so the sender isn't left hanging. Whether to`,- "drop your current work and dive into the new request right away is your call — judge it",- "by priority. If you decide the new work can wait, that's a judgment call to report",+ "Your process stays alive across turns. Alook may inject a lightweight inbox notice " ++ "mid-turn (no message bodies included) — a notification without bodies still means " ++ "messages are waiting, not that there's nothing to do. " ++ "Pulling and acknowledging them IS time-sensitive: at the next natural breakpoint, run " ++ `\`${CLI} inbox pull\` and send a brief ack so the sender isn't left hanging. Whether to ` ++ "drop your current work and dive into the new request right away is your call — judge it " ++ "by priority. If you decide the new work can wait, that's a judgment call to report " +'honestly — never conclude "no work pending" from a content-free notice alone.',].join("\n");}diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.tsindex 6ef783982..9c445be97 100644--- a/src/daemon/src/server/contract.ts+++ b/src/daemon/src/server/contract.ts@@ -4,7 +4,7 @@* This file is now a thin re-export shim. The canonical definitions live in* `@alook/shared`'s `community-cli-contract.ts` (lifted there so the real* server routes and the wake producer/consumer can share the exact same- * types this CLI/mock-server pair implements against — see+ * types this CLI/production server pair implements against — see* `plans/community-agent-cli-bridge.md` §1). Keep importing from* `./contract.js` at existing daemon call sites; nothing else changes.*/diff --git a/src/daemon/src/server/enrollment.test.ts b/src/daemon/src/server/enrollment.test.tsdeleted file mode 100644index 42bc76f7e..000000000--- a/src/daemon/src/server/enrollment.test.ts+++ /dev/null@@ -1,66 +0,0 @@-import { describe, it, expect } from "vitest";-import { MockServer } from "./mockServer";--/**- * Enrollment surface: a machine exchanges its tier-1 machine key for a per-agent- * tier-2 runner key. Authed by the machineKey — NOT agent voucher, NOT admin.- */-async function withAgent() {- const s = new MockServer();- const { user } = await s.createUser({ name: "u" });- const { agent } = await s.createAgent({ userId: user.id, name: "cindy", runtime: "mock" });- return { s, agentId: agent.id };-}--describe("MockServer enrollment (machine credential surface)", () => {- it("enrollMachine issues an sk_machine_ key the server then trusts", () => {- const s = new MockServer();- const key = s.enrollMachine();- expect(key.startsWith("sk_machine_")).toBe(true);- expect(s.verifyMachineKey(key)).toBe(true);- expect(s.verifyMachineKey("sk_machine_forged")).toBe(false);- expect(s.verifyMachineKey(undefined)).toBe(false);- });-- it("mints an sk_agent_ runner key for a valid machine key + known agent", async () => {- const { s, agentId } = await withAgent();- const machineKey = s.enrollMachine();- const { runnerKey } = await s.mintAgentCredential({ machineKey, agentId });- expect(runnerKey.startsWith("sk_agent_")).toBe(true);- // Each mint is distinct (per-agent, revocable tier-2 material).- const again = await s.mintAgentCredential({ machineKey, agentId });- expect(again.runnerKey).not.toBe(runnerKey);- });-- it("rejects an unknown machine key (does not mint)", async () => {- const { s, agentId } = await withAgent();- await expect(s.mintAgentCredential({ machineKey: "sk_machine_forged", agentId })).rejects.toThrow(- /machine key/i,- );- });-- it("rejects minting for an unknown agent", async () => {- const s = new MockServer();- const machineKey = s.enrollMachine();- await expect(s.mintAgentCredential({ machineKey, agentId: "agent_nope" })).rejects.toThrow(/not found/i);- });-- it("rejects minting for an agent bound to a different machine", async () => {- const s = new MockServer();- const { user } = await s.createUser({ name: "u" });- const machineA = s.enrollMachine();- const machineB = s.enrollMachine();- const { agent } = await s.createAgent({ userId: user.id, name: "cindy", runtime: "mock", machineKey: machineA });- await expect(s.mintAgentCredential({ machineKey: machineB, agentId: agent.id })).rejects.toThrow(/not bound/i);- // The bound machine still mints fine.- const { runnerKey } = await s.mintAgentCredential({ machineKey: machineA, agentId: agent.id });- expect(runnerKey.startsWith("sk_agent_")).toBe(true);- });-- it("agents created without a machineKey remain unbound (no regression)", async () => {- const { s, agentId } = await withAgent();- const anyMachine = s.enrollMachine();- const { runnerKey } = await s.mintAgentCredential({ machineKey: anyMachine, agentId });- expect(runnerKey.startsWith("sk_agent_")).toBe(true);- });-});diff --git a/src/daemon/src/server/index.ts b/src/daemon/src/server/index.tsindex c7ec44be5..3527e16dc 100644--- a/src/daemon/src/server/index.ts+++ b/src/daemon/src/server/index.ts@@ -1,12 +1,10 @@/**- * Server layer — the agent ⇄ server API contract + a local in-memory mock.+ * Server layer — the agent ⇄ server API contract + the control-plane transport.** contract.ts — the ServerApi interface + domain types (server-scoped).- * mockServer.ts — in-memory ServerApi for local execution / tests.* wsControlChannel — WebSocket HostControlChannel (reconnect + heartbeat).* wsControlServer — WebSocket server for the control plane.*/export * from "./contract.js";-export * from "./mockServer.js";export * from "./wsControlChannel.js";export * from "./wsControlServer.js";diff --git a/src/daemon/src/server/mockServer.alignment.test.ts b/src/daemon/src/server/mockServer.alignment.test.tsdeleted file mode 100644index 89feedfc6..000000000--- a/src/daemon/src/server/mockServer.alignment.test.ts+++ /dev/null@@ -1,63 +0,0 @@-import { describe, it, expect } from "vitest";-import { MockServer } from "./mockServer";--/**- * Channel alignment is enforced SERVER-SIDE: send() falls back to the agent's- * tracked read waterline when the caller omits `seenUpToSeq`, so a client can't- * skip alignment merely by not supplying it. These tests drive the real server- * (no stubbing) end-to-end.- */-async function setup() {- const s = new MockServer();- const { user } = await s.createUser({ name: "u" });- const { agent } = await s.createAgent({ userId: user.id, name: "cindy", runtime: "mock" });- const { server } = await s.createServer({ name: "demo" });- await s.addAgentToServer({ agentId: agent.id, server: server.id });- const { channel } = await s.createChannel({ server: server.id, name: "general" });- const ref = `/${server.id}/${channel.id}`;- return { s, agentId: agent.id, ref };-}--describe("channel alignment (server-enforced)", () => {- it("blocks a send when the agent has unseen messages, even without seenUpToSeq", async () => {- const { s, agentId, ref } = await setup();- // Someone else posts; the agent has NOT pulled, so its readMark is behind.- await s.postMessage({ channel: ref, sender: "@gustavo", text: "hello" });-- const res = await s.send({ agentId, channel: ref, content: { text: "hi" } });- expect(res.state).toBe("blocked");- if (res.state === "blocked") {- expect(res.reason).toBe("unaligned");- expect(res.unreadCount).toBeGreaterThan(0);- expect(res.latestSeq).toBeGreaterThan(0);- }- });-- it("allows the send once the agent has pulled (aligned to latest)", async () => {- const { s, agentId, ref } = await setup();- await s.postMessage({ channel: ref, sender: "@gustavo", text: "hello" });-- // Agent aligns by pulling its inbox (advances the read waterline).- const { messages } = await s.inboxPull({ agentId, max: 50 });- const cursors = messages.map((m) => ({ channel: m.channel, seq: Number(m.seq.replace("#", "")) }));- await s.ack({ agentId, cursors });-- const res = await s.send({ agentId, channel: ref, content: { text: "hi" } });- expect(res.state).toBe("sent");- });-- it("re-blocks if a new message arrives after alignment", async () => {- const { s, agentId, ref } = await setup();- await s.postMessage({ channel: ref, sender: "@gustavo", text: "first" });- const { messages } = await s.inboxPull({ agentId, max: 50 });- await s.ack({- agentId,- cursors: messages.map((m) => ({ channel: m.channel, seq: Number(m.seq.replace("#", "")) })),- });- // A newer message lands before the agent sends.- await s.postMessage({ channel: ref, sender: "@devon", text: "second" });-- const res = await s.send({ agentId, channel: ref, content: { text: "hi" } });- expect(res.state).toBe("blocked");- });-});diff --git a/src/daemon/src/server/mockServer.channel.test.ts b/src/daemon/src/server/mockServer.channel.test.tsdeleted file mode 100644index a2af2d5db..000000000--- a/src/daemon/src/server/mockServer.channel.test.ts+++ /dev/null@@ -1,72 +0,0 @@-import { describe, it, expect } from "vitest";-import { MockServer } from "./mockServer";--describe("MockServer — createChannel name uniqueness", () => {- it("rejects a second top-level channel with the same name in the same server", async () => {- const s = new MockServer();- const { server } = await s.createServer({ name: "demo" });- await s.createChannel({ server: server.id, name: "general" });-- await expect(s.createChannel({ server: server.id, name: "general" })).rejects.toMatchObject({- code: "ALREADY_EXISTS",- });- });-- it("allows the same channel name in a different server", async () => {- const s = new MockServer();- const { server: a } = await s.createServer({ name: "demo-a" });- const { server: b } = await s.createServer({ name: "demo-b" });- await s.createChannel({ server: a.id, name: "general" });-- const { channel } = await s.createChannel({ server: b.id, name: "general" });- expect(channel.name).toBe("general");- });-});--describe("MockServer — listChannels", () => {- it("returns {ref,name,type} items, resolving --server by id or by name", async () => {- const s = new MockServer();- const { server } = await s.createServer({ name: "demo" });- await s.addAgentToServer({ agentId: "a1", server: server.id });- await s.createChannel({ server: server.id, name: "general" });- await s.createChannel({ server: server.id, name: "help", type: "forum" });-- const byId = await s.listChannels({ agentId: "a1", server: server.id });- const byName = await s.listChannels({ agentId: "a1", server: "demo" });- expect(byId).toEqual(byName);- expect(byId.channels).toEqual([- { ref: "/demo/general", name: "general", type: "text" },- { ref: "/demo/help", name: "help", type: "forum" },- ]);- });-- it("omits channels from servers the agent is not a member of", async () => {- const s = new MockServer();- const { server: a } = await s.createServer({ name: "demo-a" });- const { server: b } = await s.createServer({ name: "demo-b" });- await s.addAgentToServer({ agentId: "a1", server: a.id });- await s.createChannel({ server: a.id, name: "general" });- await s.createChannel({ server: b.id, name: "general" });-- const { channels } = await s.listChannels({ agentId: "a1", server: b.id });- expect(channels).toEqual([]);- });-});--describe("MockServer — subscribeChannel", () => {- it("returns {channel,level} echoing the request", async () => {- const s = new MockServer();- const { server } = await s.createServer({ name: "demo" });- await s.createChannel({ server: server.id, name: "general" });-- const result = await s.subscribeChannel({ agentId: "a1", channel: "/demo/general", level: "mentions" });- expect(result).toEqual({ channel: "/demo/general", level: "mentions" });- });-- it("rejects a /.dm/... ref", async () => {- const s = new MockServer();- await expect(- s.subscribeChannel({ agentId: "a1", channel: "/.dm/gustavo#4821", level: "mentions" }),- ).rejects.toMatchObject({ code: "BAD_REQUEST" });- });-});diff --git a/src/daemon/src/server/mockServer.dm.test.ts b/src/daemon/src/server/mockServer.dm.test.tsdeleted file mode 100644index 9d5d7d1d9..000000000--- a/src/daemon/src/server/mockServer.dm.test.ts+++ /dev/null@@ -1,56 +0,0 @@-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.server.test.ts b/src/daemon/src/server/mockServer.server.test.tsdeleted file mode 100644index 17c836e5d..000000000--- a/src/daemon/src/server/mockServer.server.test.ts+++ /dev/null@@ -1,69 +0,0 @@-import { describe, it, expect } from "vitest";-import { MockServer } from "./mockServer";-import { computeDiscriminator } from "@alook/shared/lib/discriminator";--/**- * `MockServer`'s invite/join surface — the owner-check branch (the thing- * `alook server join` is actually about). Expiry/max-uses are NOT modeled- * here — see plans/community-server-cli-subcommands.md "Out of scope".- */-describe("MockServer — createInvite + joinServer", () => {- it("an agent whose owner matches invite.createdBy joins successfully; membership gains the agent", async () => {- const s = new MockServer();- const { user: owner } = await s.createUser({ name: "gustavo" });- const { server } = await s.createServer({ name: "Design Studio" });- const { agent } = await s.createAgent({ userId: owner.id, name: "bot", runtime: "mock" });-- const { token } = await s.createInvite({ server: server.id, createdBy: owner.id });- const { server: joined } = await s.joinServer({ agentId: agent.id, invite: token });-- expect(joined).toEqual(server);- const { members } = await s.listMembers({ agentId: agent.id, server: server.id });- expect(members).toEqual([{ handle: `bot#${computeDiscriminator(agent.id)}`, role: "member" }]);- });-- it("joinServer with wrong owner throws FORBIDDEN with a .hint string attached", async () => {- const s = new MockServer();- const { user: owner } = await s.createUser({ name: "gustavo" });- const { user: stranger } = await s.createUser({ name: "zztop" });- const { server } = await s.createServer({ name: "Design Studio" });- const { agent } = await s.createAgent({ userId: owner.id, name: "bot", runtime: "mock" });-- const { token } = await s.createInvite({ server: server.id, createdBy: stranger.id });-- await expect(s.joinServer({ agentId: agent.id, invite: token })).rejects.toMatchObject({- code: "FORBIDDEN",- hint: expect.stringContaining("Ask your owner"),- });- });-- it("joinServer with an unknown token throws NOT_FOUND", async () => {- const s = new MockServer();- const { user: owner } = await s.createUser({ name: "gustavo" });- const { agent } = await s.createAgent({ userId: owner.id, name: "bot", runtime: "mock" });-- await expect(s.joinServer({ agentId: agent.id, invite: "does-not-exist" })).rejects.toMatchObject({- code: "NOT_FOUND",- });- });-- it("listMembers returns handles for every agent currently in the server's membership set", async () => {- const s = new MockServer();- const { user: owner } = await s.createUser({ name: "gustavo" });- const { server } = await s.createServer({ name: "Design Studio" });- const { agent: a } = await s.createAgent({ userId: owner.id, name: "alex", runtime: "mock" });- const { agent: b } = await s.createAgent({ userId: owner.id, name: "sam", runtime: "mock" });-- const { token: tokenA } = await s.createInvite({ server: server.id, createdBy: owner.id });- await s.joinServer({ agentId: a.id, invite: tokenA });- const { token: tokenB } = await s.createInvite({ server: server.id, createdBy: owner.id });- await s.joinServer({ agentId: b.id, invite: tokenB });-- const { members } = await s.listMembers({ agentId: a.id, server: server.id });- expect(members).toHaveLength(2);- expect(members.every((m) => m.role === "member")).toBe(true);- const handles = members.map((m) => m.handle);- expect(handles).toContain(`alex#${computeDiscriminator(a.id)}`);- expect(handles).toContain(`sam#${computeDiscriminator(b.id)}`);- });-});diff --git a/src/daemon/src/server/mockServer.ts b/src/daemon/src/server/mockServer.tsdeleted file mode 100644index 395875ce4..000000000--- a/src/daemon/src/server/mockServer.ts+++ /dev/null@@ -1,661 +0,0 @@-/**- * MockServer — an in-memory implementation of the `ServerApi` contract.- *- * For local execution + tests: holds servers, channels, a per-channel message- * log (with per-channel seq), and per-agent read waterlines — all in memory, no- * 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/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.- * The server never decides whether/when a daemon should wake an agent; in- * production that decision starts with `src/web`'s wake producer and is- * finished by the DAEMON (`AgentRouter`/`AgentProcessManager`), not here.- * Tests that need to exercise `agent:wake` push a `HostCommand` directly- * through `WsControlServer.pushCommand` / a `LocalControlChannel`, they do- * NOT get one synthesized by `postMessage`/`post`.- */-import type {- ServerApi,- Server,- Channel,- Message,- ChannelRef,- Seq,- InboxRow,- InboxSnapshot,- InboxFlag,- AgentId,- ServerId,- InboxPullRequest,- InboxPullResponse,- AckRequest,- SendRequest,- SendResponse,- ReadRequest,- ResolveRequest,- ListChannelsRequest,- ChannelListItem,- ServerMember,- SubscribeChannelRequest,- SubscribeChannelResponse,- Page,- AdminApi,- Agent,- User,- ChannelKind,- UserId,- EnrollmentApi,-} from "./contract.js";-import { DM_SERVER, parseRef, formatRef, formatSeq } from "./contract.js";-import type { ChannelType } from "@alook/shared/utils/community-roles";-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 {- seq: Seq;- channel: ChannelRef;- senderHandle: string; // "@name"- text: string;- time: string;- mention?: boolean;-}--interface SeedMember {- id: string;- /** 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 {- servers: Array<{- id: string;- name: string;- agents: string[];- channels: Array<{ id: string; name: string; kind?: "channel" | "dm"; description?: string }>;- }>;- members?: SeedMember[];-}--export interface MockServerPersistState {- seed?: MockServerSeed;- messages: StoredMessage[];- seqCounters: Array<[string, number]>;- reads: Array<{ agentId: string; channel: string; seq: Seq }>;-}--export class MockServer implements ServerApi, AdminApi, EnrollmentApi {- private readonly servers = new Map<string, Server>();- private readonly channels = new Map<string, Channel & { type: ChannelType }>();- /** serverId → set of agentIds participating. */- private readonly membership = new Map<string, Set<string>>();- /** agentId → global handle ("@name#0042") for sender stamping. */- private readonly agentHandles = new Map<string, string>();- /** agentId → owning UserId, populated by `createAgent` — the "server join" owner check. */- private readonly agentOwner = new Map<AgentId, UserId>();- /** invite token → { serverId, createdBy } — see `createInvite`/`joinServer`. */- private readonly invites = new Map<string, { serverId: ServerId; createdBy: UserId }>();- /**- * agentId → RuntimeConfig, as set by `createAgent`. Admin-surface storage- * only — a test harness that wants to push an `agent:wake` HostCommand for- * this agent reads it back via `getAgentConfig` so the wake's `config`- * matches what "the server" told the admin API it created.- */- private readonly agentConfigs = new Map<string, RuntimeConfig>();- /** channelRef → ordered messages. */- private readonly log = new Map<ChannelRef, StoredMessage[]>();- /** channelRef → next seq. */- private readonly seqCounter = new Map<ChannelRef, number>();- /** agentId → (channelRef → last acked seq). */- private readonly readMarks = new Map<string, Map<ChannelRef, Seq>>();- /**- * agentId → (channelRef → subscribed wake-notification level), as set by- * `subscribeChannel`. CLI-contract-shape storage only — MockServer never- * simulates wake suppression (see class doc comment); nothing here reads- * this map to decide anything.- */- private readonly subscriptions = new Map<AgentId, Map<ChannelRef, "all" | "mentions">>();- private seed?: MockServerSeed;-- /** Valid machine keys this server issued on enrollment (tier-1). */- private readonly machineKeys = new Set<string>();- /** runnerKey → agentId, so a swapped-in runner key is traceable (tier-2). */- private readonly runnerKeys = new Map<string, string>();- /**- * agentId → machineKey, when `createAgent` was given one. Mirrors production's- * bot↔machine binding (`communityBotBinding`) so `mintAgentCredential` can- * reject a mint attempted from a different machine. Agents created without a- * `machineKey` are left unbound (no check performed) for backward- * compatibility with callers that don't care about this invariant.- */- private readonly agentMachineKey = new Map<string, string>();-- constructor(seed?: MockServerSeed) {- this.seed = seed;- if (seed) this.applySeed(seed);- }-- /* ----- enrollment (machine credential surface) ----- */-- /**- * Enroll a machine: issue a tier-1 `sk_machine_` key the server thereafter- * trusts. In a real deployment this is an out-of-band/admin step; the local- * `mock-server` entrypoint calls it once at startup and prints the key so the- * daemon can be launched with it. Returns the machine key.- */- enrollMachine(): string {- const machineKey = `sk_machine_${crypto.randomBytes(24).toString("base64url")}`;- this.machineKeys.add(machineKey);- return machineKey;- }-- /**- * Is this a machine key the server issued? Used by the control-plane transport- * to authenticate a connecting daemon (Bearer machineKey) before accepting it.- */- verifyMachineKey(key: string | undefined): boolean {- return !!key && this.machineKeys.has(key);- }-- async mintAgentCredential(req: { machineKey: string; agentId: AgentId }): Promise<{ runnerKey: string; expiresAt?: number }> {- if (!this.machineKeys.has(req.machineKey)) {- throw apiError("UNAUTHORIZED_MACHINE", "unknown or invalid machine key");- }- if (!this.agentHandles.has(req.agentId)) {- throw apiError("NOT_FOUND", `agent ${req.agentId} not found`);- }- // Mirrors the production enroll-agent route: an agent bound to a machine- // can only be minted a runner key from THAT machine's key. Agents created- // without a `machineKey` (most tests) are left unbound and unchecked.- const boundTo = this.agentMachineKey.get(req.agentId);- if (boundTo && boundTo !== req.machineKey) {- throw apiError("NOT_FOUND", `agent ${req.agentId} not bound to this machine`);- }- const runnerKey = `sk_agent_${crypto.randomBytes(24).toString("base64url")}`;- this.runnerKeys.set(runnerKey, req.agentId);- return { runnerKey };- }-- /**- * The RuntimeConfig `createAgent` recorded for this agent, if any. Purely a- * convenience for test harnesses assembling an `agent:wake` `HostCommand`- * to push through a control-plane fixture — MockServer itself never reads- * this to make a dispatch decision.- */- getAgentConfig(agentId: AgentId): RuntimeConfig | undefined {- return this.agentConfigs.get(agentId);- }-- /**- * Agents that can receive messages posted to `channel`: server members for- * a `/server/channel` ref, or the resolved peer for a `/.dm/<handle>` ref.- * Pure data query, same class as `listServers`/`listChannels` — NOT a- * dispatch decision. A caller standing in for the real wake producer (e.g.- * the `mock-server` script, or a test) uses this to decide who to push an- * `agent:wake` `HostCommand` for after `postMessage`.- */- membersOf(channelArg: ChannelRef): AgentId[] {- const p = parseRef(this.canon(channelArg));- if (p.server === DM_SERVER) {- const handle = p.channel.startsWith("@") ? p.channel : `@${p.channel}`;- const peer = [...this.agentHandles].find(([, h]) => h === handle)?.[0];- return peer ? [peer] : [];- }- const serverId = this.resolveServerId(p.server) ?? p.server;- return [...(this.membership.get(serverId) ?? [])];- }-- private applySeed(seed: MockServerSeed): void {- 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)) {- 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) {- this.servers.set(s.id, { id: s.id, name: s.name });- this.membership.set(s.id, new Set(s.agents));- for (const c of s.channels) {- this.channels.set(c.id, {- id: c.id,- serverId: s.id,- name: c.name,- kind: c.kind ?? "channel",- description: c.description,- type: "text",- });- }- }- }-- /* ----- persistence ----- */-- dumpState(): MockServerPersistState {- const messages: StoredMessage[] = [];- for (const arr of this.log.values()) messages.push(...arr);- const reads: Array<{ agentId: string; channel: string; seq: Seq }> = [];- for (const [agentId, marks] of this.readMarks) {- for (const [channel, seq] of marks) reads.push({ agentId, channel, seq });- }- return { seed: this.seed, messages, seqCounters: [...this.seqCounter.entries()], reads };- }-- static restore(state: MockServerPersistState): MockServer {- const mock = new MockServer(state.seed);- for (const [ref, seq] of state.seqCounters) mock.seqCounter.set(ref, seq);- for (const m of state.messages) {- const arr = mock.log.get(m.channel) ?? [];- arr.push(m);- mock.log.set(m.channel, arr);- }- for (const r of state.reads) {- let marks = mock.readMarks.get(r.agentId);- if (!marks) {- marks = new Map();- mock.readMarks.set(r.agentId, marks);- }- marks.set(r.channel, r.seq);- }- return mock;- }-- /* ----- test/seed helpers (not part of ServerApi) ----- */-- /** 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),- );- }-- private append(channelArg: ChannelRef, senderHandle: string, text: string, mention?: boolean): StoredMessage {- // Validate + canonicalize so id/name variants key the same log.- this.assertChannelExists(channelArg);- const channel = this.canon(channelArg);- const seq = (this.seqCounter.get(channel) ?? 0) + 1;- this.seqCounter.set(channel, seq);- const msg: StoredMessage = { seq, channel, senderHandle, text, time: new Date().toISOString(), mention };- const arr = this.log.get(channel) ?? [];- arr.push(msg);- this.log.set(channel, arr);- return msg;- }-- private assertChannelExists(channel: ChannelRef): void {- const p = parseRef(channel);- if (p.server === DM_SERVER) return; // DMs are implicit- const serverId = this.resolveServerId(p.server);- const ok =- serverId &&- [...this.channels.values()].some((c) => c.serverId === serverId && (c.name === p.channel || c.id === p.channel));- if (!ok) throw apiError("NOT_FOUND", `channel ${channel} not found`);- }-- private readMark(agentId: AgentId, channel: ChannelRef): Seq {- return this.readMarks.get(agentId)?.get(channel) ?? 0;- }-- /** Canonical channel refs the agent can receive in (its servers' channels). */- private agentChannels(agentId: AgentId): ChannelRef[] {- const refs: ChannelRef[] = [];- for (const [serverId, agents] of this.membership) {- if (!agents.has(agentId)) continue;- for (const ch of this.channels.values()) {- // Canonical /serverId/channelId (matches what append() keys on).- if (ch.serverId === serverId) refs.push(`/${serverId}/${ch.id}`);- }- }- // Plus any DM channels that already have a log addressed to this agent's handle.- const handle = this.agentHandles.get(agentId);- if (handle) {- for (const ref of this.log.keys()) {- if (ref.startsWith(`/${DM_SERVER}/`) && !refs.includes(ref)) refs.push(ref);- }- }- return refs;- }-- private resolveServerId(serverRef: string): ServerId | undefined {- if (this.servers.has(serverRef)) return serverRef;- return [...this.servers.values()].find((s) => s.name === serverRef)?.id;- }-- /**- * Canonicalize a channel ref to `/serverId/channelId[...]` so the log is keyed- * consistently whether the caller used server/channel NAMES or IDS. DM refs- * are returned unchanged (the `.dm` server + peer are already canonical).- */- private canon(ref: ChannelRef): ChannelRef {- const p = parseRef(ref);- if (p.server === DM_SERVER) return ref;- const serverId = this.resolveServerId(p.server);- if (!serverId) return ref; // unknown — leave as-is (validation happens elsewhere)- const ch = [...this.channels.values()].find(- (c) => c.serverId === serverId && (c.name === p.channel || c.id === p.channel),- );- const channelSeg = ch ? ch.id : p.channel;- const base = `/${serverId}/${channelSeg}`;- return p.threadRootSeq !== undefined ? `${base}/#${p.threadRootSeq}` : base;- }-- /* ----- ServerApi ----- */-- async listServers(req: { agentId: AgentId }): Promise<{ servers: Server[] }> {- const servers: Server[] = [];- for (const [serverId, agents] of this.membership) {- if (agents.has(req.agentId)) {- const s = this.servers.get(serverId);- if (s) servers.push(s);- }- }- return { servers };- }-- /**- * `{ ref, name, type }` items (plan §Decisions #12) — `req.server` accepts- * either a server id or its display name (via `resolveServerId`, the same- * helper `listMembers`/`assertChannelExists` already use), matching the- * production route's id-or-name resolution.- */- async listChannels(req: ListChannelsRequest): Promise<{ channels: ChannelListItem[] }> {- const myServers = new Set((await this.listServers({ agentId: req.agentId })).servers.map((s) => s.id));- const resolvedServerId = req.server ? this.resolveServerId(req.server) ?? req.server : undefined;- const channels = [...this.channels.values()].filter(- (c) => myServers.has(c.serverId) && (!resolvedServerId || c.serverId === resolvedServerId),- );- return {- channels: channels.map((c) => ({- ref: formatRef({ server: this.servers.get(c.serverId)?.name ?? c.serverId, channel: c.name }),- name: c.name,- type: c.type,- })),- };- }-- async inboxPull(req: InboxPullRequest): Promise<InboxPullResponse> {- const out: StoredMessage[] = [];- const handle = this.agentHandles.get(req.agentId);- let truncated = false;- for (const channel of this.agentChannels(req.agentId)) {- const mark = this.readMark(req.agentId, channel);- for (const m of this.log.get(channel) ?? []) {- if (m.seq <= mark) continue;- if (handle && m.senderHandle === handle) continue; // skip own messages- if (req.max && out.length >= req.max) {- truncated = true;- break;- }- out.push(m);- }- }- out.sort((a, b) => a.seq - b.seq);- return { messages: out.map(toAgentMessage), hasMore: truncated };- }-- async inboxSnapshot(req: { agentId: AgentId }): Promise<InboxSnapshot> {- const handle = this.agentHandles.get(req.agentId);- const rows: InboxRow[] = [];- for (const channel of this.agentChannels(req.agentId)) {- const mark = this.readMark(req.agentId, channel);- const unread = (this.log.get(channel) ?? []).filter((m) => m.seq > mark && m.senderHandle !== handle);- if (unread.length === 0) continue;- const flags: InboxFlag[] = [];- if (channel.startsWith(`/${DM_SERVER}/`)) flags.push("dm");- if (unread.some((m) => m.mention)) flags.push("mention");- rows.push({- channel,- pendingCount: unread.length,- firstPendingSeq: unread[0].seq,- latestSeq: unread[unread.length - 1].seq,- latestSender: unread[unread.length - 1].senderHandle,- flags,- });- }- rows.sort((a, b) => (b.latestSeq ?? 0) - (a.latestSeq ?? 0));- return { rows, pendingChannels: rows.length, pendingMessages: rows.reduce((n, r) => n + r.pendingCount, 0) };- }-- async ack(req: AckRequest): Promise<void> {- let marks = this.readMarks.get(req.agentId);- if (!marks) {- marks = new Map();- this.readMarks.set(req.agentId, marks);- }- for (const c of req.cursors) {- const key = this.canon(c.channel);- marks.set(key, Math.max(marks.get(key) ?? 0, c.seq));- }- }-- async send(req: SendRequest): Promise<SendResponse> {- const channel = this.canon(req.channel);- const latestSeq = this.seqCounter.get(channel) ?? 0;- // Channel alignment: if the agent hasn't seen the channel's latest messages,- // block the send (no bypass) — it must pull/read to align, then resend. The- // server is the source of truth: it falls back to the agent's tracked read- // waterline when the caller doesn't supply `seenUpToSeq`, so alignment is- // enforced server-side and can't be skipped by a client that simply omits it.- const seen = req.seenUpToSeq ?? this.readMark(req.agentId, channel);- if (latestSeq > seen) {- return { state: "blocked", reason: "unaligned", unreadCount: latestSeq - seen, latestSeq };- }- const handle = this.agentHandles.get(req.agentId) ?? `@${req.agentId}`;- const stored = this.append(req.channel, handle, req.content.text);- await this.ack({ agentId: req.agentId, cursors: [{ channel: stored.channel, seq: stored.seq }] });- return { state: "sent", message: toAgentMessage(stored) };- }-- async read(req: ReadRequest): Promise<Page<Message>> {- let items = [...(this.log.get(this.canon(req.channel)) ?? [])];- if (req.before !== undefined) items = items.filter((m) => m.seq < req.before!);- if (req.after !== undefined) items = items.filter((m) => m.seq > req.after!);- const limit = req.limit ?? 20;- if (req.around !== undefined) {- items.sort((a, b) => Math.abs(a.seq - req.around!) - Math.abs(b.seq - req.around!));- items = items.slice(0, limit).sort((a, b) => a.seq - b.seq);- return { items: items.map(toAgentMessage), hasMore: false, latestSeq: items[items.length - 1]?.seq };- }- const hasMore = items.length > limit;- items = items.slice(-limit);- return { items: items.map(toAgentMessage), hasMore, latestSeq: items[items.length - 1]?.seq };- }-- async resolve(req: ResolveRequest): Promise<{ message: Message }> {- const found = (this.log.get(this.canon(req.channel)) ?? []).find((m) => m.seq === req.seq);- if (!found) throw apiError("NOT_FOUND", `message ${req.channel}${formatSeq(req.seq)} not found`);- return { message: toAgentMessage(found) };- }-- /**- * Members of a server, resolved by id-or-name (reuses `resolveServerId`).- * The mock has no owner/admin role concept beyond membership — every member- * comes back as `role: "member"`; tests that care about role- * differentiation exercise the CLI layer directly via `setApiForTesting`,- * not through `MockServer` (see plan's "Out of scope").- */- async listMembers(req: { agentId: AgentId; server: string }): Promise<{ members: ServerMember[] }> {- const serverId = this.resolveServerId(req.server);- if (!serverId) throw apiError("NOT_FOUND", `server ${req.server} not found`);- const agentIds = [...(this.membership.get(serverId) ?? [])];- const members: ServerMember[] = agentIds.map((id) => ({- handle: (this.agentHandles.get(id) ?? `@${id}`).replace(/^@/, ""),- role: "member",- }));- return { members };- }-- /**- * Join a server via an invite token. `NOT_FOUND` if the token is unknown;- * `FORBIDDEN` (with a `.hint`) if the invite's creator isn't this agent's- * owner. Expiry/max-uses and "already a member" are NOT modeled — see- * plan's "Out of scope".- */- async joinServer(req: { agentId: AgentId; invite: string }): Promise<{ server: Server }> {- const invite = this.invites.get(req.invite);- if (!invite) throw apiError("NOT_FOUND", "Invalid or expired invite");- const owner = this.agentOwner.get(req.agentId);- if (invite.createdBy !== owner) {- throw Object.assign(apiError("FORBIDDEN", "This invite was not created by your owner — refusing to join."), {- hint: "Ask your owner to send an invite link they created themselves.",- });- }- (this.membership.get(invite.serverId) ?? this.membership.set(invite.serverId, new Set()).get(invite.serverId)!).add(- req.agentId,- );- const server = this.servers.get(invite.serverId);- if (!server) throw apiError("NOT_FOUND", `server ${invite.serverId} not found`);- return { server };- }-- /**- * Store this agent's wake-notification level for one channel/thread ref —- * CLI-contract-shape only. `MockServer` never models the wake pipeline- * (see class doc comment), so this never suppresses anything; it exists- * purely so the CLI/mock round-trip exercises the real request/response- * shape. DMs are rejected, mirroring the production route.- */- async subscribeChannel(req: SubscribeChannelRequest): Promise<SubscribeChannelResponse> {- const p = parseRef(req.channel);- if (p.server === DM_SERVER) throw apiError("BAD_REQUEST", "channel subscribe does not support DMs");- let byChannel = this.subscriptions.get(req.agentId);- if (!byChannel) {- byChannel = new Map();- this.subscriptions.set(req.agentId, byChannel);- }- byChannel.set(req.channel, req.level);- return { channel: req.channel, level: req.level };- }-- /* ----- AdminApi (provisioning / test surface) ----- */-- private adminCounter = 0;- private readonly users = new Map<string, User>();- private mkId(prefix: string): string {- this.adminCounter += 1;- return `${prefix}_${this.adminCounter}`;- }-- async createUser(req: { name: string }): Promise<{ user: User }> {- const user: User = { id: this.mkId("user"), name: req.name };- this.users.set(user.id, user);- return { user };- }-- async createAgent(req: {- userId: UserId;- name: string;- runtime?: string;- instruction?: string;- machineKey?: string;- }): 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 };- // 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);- this.agentOwner.set(agent.id, req.userId);- 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: handle, instruction: req.instruction }),- );- return { agent };- }-- async createServer(req: { name: string }): Promise<{ server: Server }> {- const server: Server = { id: this.mkId("srv"), name: req.name };- this.servers.set(server.id, server);- this.membership.set(server.id, new Set());- return { server };- }-- async addAgentToServer(req: { agentId: AgentId; server: ServerId }): Promise<void> {- const serverId = this.resolveServerId(req.server) ?? req.server;- if (!this.servers.has(serverId)) throw apiError("NOT_FOUND", `server ${req.server} not found`);- (this.membership.get(serverId) ?? this.membership.set(serverId, new Set()).get(serverId)!).add(req.agentId);- }-- async createChannel(req: {- server: ServerId;- name: string;- kind?: ChannelKind;- /** Defaults to `"text"`. A test-only knob to seed a `"forum"` channel — see `listChannels`. */- type?: ChannelType;- }): Promise<{ channel: Channel }> {- const serverId = this.resolveServerId(req.server) ?? req.server;- if (!this.servers.has(serverId)) throw apiError("NOT_FOUND", `server ${req.server} not found`);- const nameTaken = [...this.channels.values()].some(- (c) => c.serverId === serverId && c.name === req.name- );- if (nameTaken) {- throw apiError("ALREADY_EXISTS", `channel "${req.name}" already exists in this server`);- }- const channel: Channel & { type: ChannelType } = {- id: this.mkId("ch"),- serverId,- name: req.name,- kind: req.kind ?? "channel",- type: req.type ?? "text",- };- this.channels.set(channel.id, channel);- return { channel };- }-- async postMessage(req: { channel: ChannelRef; sender: string; text: string }): Promise<{ message: Message }> {- // append() only validates + stores; it never dispatches a wake — see the- // class doc comment. Callers that want a wake push a HostCommand- // themselves (real deployments: via the wake producer/consumer path).- return { message: this.post({ channel: req.channel, sender: req.sender, text: req.text }) };- }-- async createInvite(req: { server: ServerId; createdBy: UserId }): Promise<{ token: string }> {- const serverId = this.resolveServerId(req.server) ?? req.server;- if (!this.servers.has(serverId)) throw apiError("NOT_FOUND", `server ${req.server} not found`);- const token = crypto.randomBytes(16).toString("base64url");- this.invites.set(token, { serverId, createdBy: req.createdBy });- return { token };- }-- async readChannel(req: { channel: ChannelRef; limit?: number }): Promise<Page<Message>> {- // Observability-only: no agent identity, no waterline advance, no alignment.- const all = [...(this.log.get(this.canon(req.channel)) ?? [])];- const limit = req.limit ?? 20;- const hasMore = all.length > limit;- const items = all.slice(-limit);- return { items: items.map(toAgentMessage), hasMore, latestSeq: items[items.length - 1]?.seq };- }-}--/** Project the internal stored row to the flat agent-facing Message. */-function toAgentMessage(m: StoredMessage): Message {- return { seq: formatSeq(m.seq), channel: m.channel, sender: m.senderHandle, content: { text: m.text }, time: m.time };-}--function apiError(code: string, message: string): Error & { code: string } {- return Object.assign(new Error(message), { code });-}diff --git a/src/daemon/src/server/wsControlChannel.ts b/src/daemon/src/server/wsControlChannel.tsindex a8c96ac3a..9ea05808a 100644--- a/src/daemon/src/server/wsControlChannel.ts+++ b/src/daemon/src/server/wsControlChannel.ts@@ -1,10 +1,10 @@/*** WsControlChannel — a real-server `HostControlChannel` over a WebSocket.*- * This is the network counterpart to `LocalControlChannel`: where the local one- * bridges an in-process `MockServer`, this one carries the same control-plane- * frames (`HostCommand` down, `HostReady` / agent-session reports up) over a- * WebSocket, with **exponential-backoff reconnect** and a **heartbeat watchdog**.+ * This is the host end of the control plane: it carries `HostCommand` frames+ * down (`agent:wake` / `agent:stop` / `bot:*`) and `HostReady` / agent-session+ * reports up, over a WebSocket, with **exponential-backoff reconnect** and a+ * **heartbeat watchdog**.** The socket is injected (`WebSocketFactory`) so this file stays dependency-free* and testable; a deployment passes a factory built on the `ws` package. The@@ -17,12 +17,10 @@* - outbound frames are JSON `{ type: "ready" | "agent_session" | "agent_wake_ack" | "agent_stopped_ack", … }` (host → server).* A real server adapter maps these to its own protocol.*- * This is the control plane local dev actually uses: `mock-server`+`daemon` and the- * `control-plane-e2e` example run the server (`WsControlServer`) and host- * (`WsControlChannel`) over a real loopback WebSocket, so the transport —- * reconnect/heartbeat and frame (de)serialization — is exercised end to end- * rather than shortcut in-process. `LocalControlChannel` remains only for pure- * unit tests that don't need a socket.+ * `tests/integration/daemon/control-plane.test.ts` exercises this class over+ * a real WebSocket against a real `ws-do` dev server — the transport+ * (reconnect/heartbeat and frame (de)serialization) end to end, rather than+ * shortcut in-process.*/import type {HostControlChannel,diff --git a/src/daemon/src/server/wsControlServer.ts b/src/daemon/src/server/wsControlServer.tsindex e32f86368..4197dbe26 100644--- a/src/daemon/src/server/wsControlServer.ts+++ b/src/daemon/src/server/wsControlServer.ts@@ -21,8 +21,8 @@* `{ type:"agent_wake_ack" | "agent_stopped_ack", … }`** The ws server impl is injected (`WebSocketServerLike`) so this file carries no- * hard `ws` dependency and stays unit-testable; `mock-server` passes a factory- * built on the `ws` package.+ * hard `ws` dependency and stays unit-testable; a deployment/test harness passes+ * a factory built on the `ws` package.*/import type { HostCommand, HostReady, AgentId, WebSocketLike } from "./contract.js";// Re-export so existing importers of WebSocketLike from this module keep working.@@ -38,7 +38,8 @@ export interface WsConnectionMeta {* The subset of a ws *server* this module uses (matches `ws`'s WebSocketServer).* The `connection` callback's second arg carries the upgrade request's auth* header so the control plane can authenticate the connecting daemon — the- * factory adapter (in `mock-server`) pulls it off the `ws` upgrade request.+ * factory adapter (in a deployment/test harness) pulls it off the `ws` upgrade+ * request.*/export interface WebSocketServerLike {on(event: "connection", cb: (socket: WebSocketLike, meta?: WsConnectionMeta) => void): void;@@ -58,7 +59,7 @@ type InboundFrame =export interface WsControlServerOpts {/*** Build the ws server bound to `port` on loopback. Injected so this module has- * no hard `ws` dependency; `mock-server` passes a real factory.+ * no hard `ws` dependency; a deployment/test harness passes a real factory.*/webSocketServerFactory: (port: number) => WebSocketServerLike;port: number;diff --git a/src/daemon/test/e2e/controlPlane.e2e.test.ts b/src/daemon/test/e2e/controlPlane.e2e.test.tsdeleted file mode 100644index 54543a32d..000000000--- a/src/daemon/test/e2e/controlPlane.e2e.test.ts+++ /dev/null@@ -1,226 +0,0 @@-/**- * E2E: the `agent:wake` control plane over a REAL WebSocket.- *- * MockServer (data + admin only) + a manually-pushed `agent:wake` HostCommand- * ─(real ws)─▶ AgentRouter ─▶ AgentProcessManager ─▶ mock agent session- * (pulls inbox via ServerApi, replies "hi!").- *- * Per minimal-wake-queue-unread-notice plan §6, the SERVER (MockServer) no- * longer decides when to wake an agent or tracks a running-agents set —- * `postMessage` only writes the message. This test drives the control plane- * the way production does: something OUTSIDE the daemon (here, the test- * itself, standing in for `src/web`'s wake producer + `src/wake-worker`'s- * consumer) decides a bot is behind and pushes an `agent:wake` HostCommand- * with a bodiless `UnreadNotice`. The DAEMON (AgentRouter/AgentProcessManager)- * is what decides spawn-vs-notify-vs-coalesce and turns the notice into an- * `alook inbox pull` prompt — never the server.- *- * Asserts the round-trip works end to end and that the control frames actually- * cross a socket (not an in-process shortcut): we point WsControlChannel at the- * WsControlServer's ws port.- */-import { describe, it, expect, afterEach } from "vitest";-import { WebSocketServer, WebSocket } from "ws";-import { MockServer, WsControlServer, WsControlChannel } from "../../src/server/index";-import { AgentProcessManager, AgentRouter } from "../../src/manager/index";-import type { ManagedSession } from "../../src/manager/managerRuntime";-import type { ServerApi, HostCommand } from "../../src/server/contract";-import { makeRuntimeConfig } from "../../src/runtimeConfig";--interface Harness {- server: MockServer;- wsServer: WsControlServer;- teardown: () => Promise<void>;-}--async function setup(): Promise<Harness> {- const server = new MockServer();- const api: ServerApi = server;-- // Bind to an OS-assigned ephemeral port (port 0) to avoid collisions when- // tests share a process, then read it back for the client URL.- const wss = new WebSocketServer({ host: "127.0.0.1", port: 0 });- await new Promise<void>((r) => wss.on("listening", () => r()));- const addr = wss.address();- const wsPort = typeof addr === "object" && addr ? addr.port : 0;-- const wsServer = new WsControlServer({- port: wsPort,- webSocketServerFactory: () => wss, // reuse the already-listening server- });- wsServer.start();- const channel = new WsControlChannel({- url: `ws://127.0.0.1:${wsPort}`,- webSocketFactory: (url, headers) => new WebSocket(url, { headers }) as never,- });-- const manager = new AgentProcessManager({- driverFor: () => ({ lifecycle: { kind: "persistent" } }) as never,- baseContextFor: (agentId) => ({ agentId, workingDirectory: "/tmp/cp-e2e", standingPrompt: "", config: {} }),- sessionFactory: ({ agentId }) => makeMockAgentSession(agentId, api),- tickIntervalMs: 500,- onAgentSession: (info) => void channel.reportAgentSession(info),- wakePromptFooter: "Use `alook inbox pull` to read your messages, then reply with `alook message send`.",- });- manager.start();- const router = new AgentRouter({ manager, channel, runtimeReport: [{ id: "mock" }] });- channel.connect();- await router.start();- await waitFor(() => channel.status === "open", 3000);- await waitFor(() => wsServer.isConnected, 3000);-- return {- server,- wsServer,- teardown: async () => {- channel.close();- await wsServer.close();- await manager.stopAll();- },- };-}--/** Push an `agent:wake` HostCommand for `agentId`, notice pointed at `channel` @ `latestSeq`. */-function pushWake(- wsServer: WsControlServer,- server: MockServer,- input: { agentId: string; channel: string; latestSeq: number },-): void {- const config = server.getAgentConfig(input.agentId) ?? makeRuntimeConfig({ runtime: "mock" });- const cmd: HostCommand = {- type: "agent:wake",- agentId: input.agentId,- config,- launchId: `launch_${input.agentId}_${input.latestSeq}`,- unreadNotice: { kind: "unread_notice", channel: input.channel, latestSeq: input.latestSeq },- };- const sent = wsServer.pushCommand(cmd);- if (!sent) throw new Error("pushWake: no daemon connected");-}--/** Mock agent: on wake, pull inbox, ack, reply "hi!" to each message. */-function makeMockAgentSession(agentId: string, api: ServerApi): ManagedSession {- const sessionId = `mock-${agentId}`;- const handlers: Record<string, ((...a: unknown[]) => void)[]> = {};- const emit = (ev: string, arg?: unknown) => (handlers[ev] ?? []).forEach((h) => h(arg));- // Pull + ack the inbox so the agent is aligned to each channel's latest.- const pullAndAlign = async (): Promise<string[]> => {- const { messages } = await api.inboxPull({ agentId, max: 50 });- const latest = new Map<string, number>();- for (const m of messages) {- const n = Number(m.seq.replace("#", "")) || 0;- if (n > (latest.get(m.channel) ?? 0)) latest.set(m.channel, n);- }- if (latest.size) await api.ack({ agentId, cursors: [...latest].map(([channel, seq]) => ({ channel, seq })) });- return [...latest.keys()];- };- const wake = async () => {- emit("runtime_event", { kind: "session_init", sessionId });- const channels = await pullAndAlign();- // Reply per channel. With strict channel alignment, a peer's reply landing- // first makes THIS agent unaligned, so a send may be blocked — re-pull to- // realign and retry (a real agent does the same: pull, then resend).- for (const channel of channels) {- for (let attempt = 0; attempt < 5; attempt++) {- const res = await api.send({ agentId, channel, content: { text: "hi!" } });- if (res.state === "sent") break;- await pullAndAlign(); // realign, then retry- }- }- emit("runtime_event", { kind: "turn_end", sessionId });- };- return {- on: (ev, cb) => ((handlers[ev] ??= []).push(cb)),- get currentSessionId() {- return sessionId;- },- async start() {- void wake();- },- send() {- void wake();- return { ok: true };- },- async stop() {- emit("exit", { reason: "requested" });- },- };-}--function delay(ms: number): Promise<void> {- return new Promise((r) => setTimeout(r, ms));-}-async function waitFor(cond: () => boolean | Promise<boolean>, timeoutMs: number): Promise<void> {- const deadline = Date.now() + timeoutMs;- while (!(await cond())) {- if (Date.now() > deadline) throw new Error("waitFor: timed out");- await delay(20);- }-}--describe("control plane over real ws (e2e)", () => {- let teardown: (() => Promise<void>) | undefined;- afterEach(async () => {- await teardown?.();- teardown = undefined;- });-- it("a pushed agent:wake drives the daemon over ws and the agent replies", async () => {- const h = await setup();- teardown = h.teardown;- const { server, wsServer } = h;-- const { user } = await server.createUser({ name: "me" });- const { agent } = await server.createAgent({ userId: user.id, name: "cindy", runtime: "mock" });- const { server: srv } = await server.createServer({ name: "demo" });- await server.addAgentToServer({ agentId: agent.id, server: srv.id });- const { channel: ch } = await server.createChannel({ server: srv.id, name: "general" });- const ref = `/${srv.id}/${ch.id}`;-- const { message } = await server.postMessage({ channel: ref, sender: "@gustavo", text: "cindy, say hi" });-- pushWake(wsServer, server, { agentId: agent.id, channel: ref, latestSeq: Number(message.seq.replace("#", "")) });-- // Wait until the agent has replied (its message lands in the channel).- await waitFor(async () => {- const page = await server.read({ agentId: agent.id, channel: ref, limit: 10 });- return page.items.some((m) => m.sender.includes("cindy") && m.content.text === "hi!");- }, 5000);-- const page = await server.read({ agentId: agent.id, channel: ref, limit: 10 });- const replies = page.items.filter((m) => m.content.text === "hi!");- expect(replies.length).toBe(1);- });-- it("multiple agents each reply (3/3) to their own agent:wake push", async () => {- const h = await setup();- teardown = h.teardown;- const { server, wsServer } = h;-- const { user } = await server.createUser({ name: "me" });- const { server: srv } = await server.createServer({ name: "demo" });- const { channel: ch } = await server.createChannel({ server: srv.id, name: "general" });- const ref = `/${srv.id}/${ch.id}`;- const names = ["cindy", "devon", "echo"];- const ids: string[] = [];- for (const name of names) {- const { agent } = await server.createAgent({ userId: user.id, name, runtime: "mock" });- await server.addAgentToServer({ agentId: agent.id, server: srv.id });- ids.push(agent.id);- }-- const { message } = await server.postMessage({ channel: ref, sender: "@gustavo", text: "hello team" });- const latestSeq = Number(message.seq.replace("#", ""));- for (const agentId of ids) {- pushWake(wsServer, server, { agentId, channel: ref, latestSeq });- }-- await waitFor(async () => {- const page = await server.read({ agentId: ids[0], channel: ref, limit: 20 });- return page.items.filter((m) => m.content.text === "hi!").length >= 3;- }, 6000);-- const page = await server.read({ agentId: ids[0], channel: ref, limit: 20 });- expect(page.items.filter((m) => m.content.text === "hi!").length).toBe(3);- });-});diff --git a/src/daemon/test/e2e/credentialChain.e2e.test.ts b/src/daemon/test/e2e/credentialChain.e2e.test.tsdeleted file mode 100644index f8986725e..000000000--- a/src/daemon/test/e2e/credentialChain.e2e.test.ts+++ /dev/null@@ -1,109 +0,0 @@-/**- * E2E: the agent data-plane credential chain.- *- * proxyServerApi client ──Bearer vch_──▶ credential proxy ──swap key + stamp- * X-Agent-Id (from voucher)──▶ bridge /api/* ──▶ MockServer- *- * Proves the agent reaches the data plane ONLY by holding a voucher, and that the- * proxy turns that voucher into a trusted X-Agent-Id — i.e. the real credential +- * verification path is exercised, not bypassed.- */-import { describe, it, expect, afterEach } from "vitest";-import * as http from "http";-import { MockServer } from "../../src/server/index";-import { CredentialBroker, startCredentialProxy, type RunningProxy } from "../../src/credentials/index";-import { createProxyServerApi } from "../../src/cli/proxyServerApi";--/** A tiny bridge that records the X-Agent-Id the proxy stamps and forwards to MockServer. */-function startBridge(server: MockServer): Promise<{ url: string; seenAgentIds: string[]; close: () => Promise<void> }> {- const seenAgentIds: string[] = [];- const httpServer = http.createServer((req, res) => {- void (async () => {- // The credential proxy rewrites the CLI's bare `/api/*` ops onto the- // real server surface at `/api/community/agent/*` (plan §9) before- // forwarding upstream — match that rewritten path here.- const m = /^\/api\/community\/agent\/(\w+)$/.exec(req.url ?? "");- if (!m) {- res.writeHead(404).end();- return;- }- const method = m[1];- const agentId = req.headers["x-agent-id"] as string | undefined;- if (agentId) seenAgentIds.push(agentId);- const chunks: Buffer[] = [];- for await (const c of req) chunks.push(c as Buffer);- const body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : {};- // The bridge injects the TRUSTED agentId from the proxy header (overriding- // anything in the body — here the body has none).- const withId = { ...body, agentId: agentId ?? body.agentId };- try {- const fn = (server as unknown as Record<string, (a: unknown) => Promise<unknown>>)[method];- const result = await fn.call(server, withId);- res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(result ?? {}));- } catch (e) {- res.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ error: (e as Error).message }));- }- })();- });- return new Promise((resolve) => {- httpServer.listen(0, "127.0.0.1", () => {- const addr = httpServer.address();- const port = typeof addr === "object" && addr ? addr.port : 0;- resolve({- url: `http://127.0.0.1:${port}`,- seenAgentIds,- close: () => new Promise((r) => httpServer.close(() => r())),- });- });- });-}--describe("agent data-plane credential chain (e2e)", () => {- let proxy: RunningProxy | undefined;- let bridgeClose: (() => Promise<void>) | undefined;- afterEach(async () => {- await proxy?.close();- await bridgeClose?.();- proxy = undefined;- bridgeClose = undefined;- });-- it("agent reaches the data plane via voucher; proxy stamps a trusted X-Agent-Id", async () => {- const server = new MockServer();- const { user } = await server.createUser({ name: "u" });- const { agent } = await server.createAgent({ userId: user.id, name: "cindy", runtime: "mock" });- const { server: srv } = await server.createServer({ name: "demo" });- await server.addAgentToServer({ agentId: agent.id, server: srv.id });- const { channel: ch } = await server.createChannel({ server: srv.id, name: "general" });- const ref = `/${srv.id}/${ch.id}`;-- const bridge = await startBridge(server);- bridgeClose = bridge.close;- const broker = new CredentialBroker({ upstreamBaseUrl: bridge.url });- proxy = await startCredentialProxy(broker);-- // Host mints a voucher for this agent launch; the agent gets ONLY the voucher.- const reg = broker.mint(agent.id, "launch-1", ["send", "read"], "sk_agent_stub");- const apiClient = createProxyServerApi({ proxyUrl: proxy.url, voucher: reg.voucher });-- // Agent reads via the voucher — note: NO agentId is sent on the wire.- const page = await apiClient.read({ agentId: "ignored-by-wire", channel: ref, limit: 10 });- expect(Array.isArray(page.items)).toBe(true);-- // The proxy stamped the agent's real id (from the voucher), not "ignored-by-wire".- expect(bridge.seenAgentIds).toContain(agent.id);- expect(bridge.seenAgentIds).not.toContain("ignored-by-wire");- });-- it("an invalid voucher is rejected at the proxy (never reaches the bridge)", async () => {- const server = new MockServer();- const bridge = await startBridge(server);- bridgeClose = bridge.close;- const broker = new CredentialBroker({ upstreamBaseUrl: bridge.url });- proxy = await startCredentialProxy(broker);-- const apiClient = createProxyServerApi({ proxyUrl: proxy.url, voucher: "vch_forged" });- await expect(apiClient.read({ agentId: "x", channel: "/demo/general", limit: 1 })).rejects.toThrow();- expect(bridge.seenAgentIds.length).toBe(0);- });-});diff --git a/src/daemon/vitest.config.ts b/src/daemon/vitest.config.tsindex 108720757..62ffdff3c 100644--- a/src/daemon/vitest.config.ts+++ b/src/daemon/vitest.config.ts@@ -2,10 +2,11 @@ import { defineConfig } from "vitest/config";export default defineConfig({test: {- // Unit tests live next to sources as *.test.ts; e2e tests under test/e2e.- include: ["src/**/*.test.ts", "test/**/*.test.ts"],+ // Unit tests live next to sources as *.test.ts. Real-infra integration+ // tests live in ../../tests/integration/daemon/ and run separately via+ // `pnpm test:integration` (not part of this config's include).+ include: ["src/**/*.test.ts"],environment: "node",- // e2e tests spin up real ws servers; give them room but keep unit tests fast.testTimeout: 10_000,},});diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 725d64409..c921e92ea 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -585,9 +585,9 @@ export type WebSocketFactory = (url: string, headers: Record<string, string>) =>/* ------------------------------------------------------------------ *//**- * Server-side provisioning, separate from the agent's daily `ServerApi`. Used by- * the test-server command surface (and, in production, by privileged callers) to- * create servers/agents/channels and inject messages. `postMessage` writes+ * Server-side provisioning, separate from the agent's daily `ServerApi`. Used+ * in production by privileged callers to create servers/agents/channels and+ * inject messages. `postMessage` writes* the message; real deployments separately enqueue an `agent:wake` for any* bot behind on the new message (see `src/web`'s wake producer +* `src/wake-worker`'s consumer) — this admin surface does not itself compute@@ -654,8 +654,7 @@ export interface EnrollmentApi {** Implementations MUST also enforce that `agentId` is bound to THIS machine* (404 if bound elsewhere or unbound) — see the production `enroll-agent`- * route's binding check, mirrored by `MockServer` when `createAgent` was- * given a `machineKey`.+ * route's binding check.*/mintAgentCredential(req: { machineKey: string; agentId: AgentId }): Promise<{ runnerKey: string; expiresAt?: number }>;}diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.tsindex 6b9a7a038..e197480b7 100644--- a/src/shared/src/db/queries/community/agent-inbox.ts+++ b/src/shared/src/db/queries/community/agent-inbox.ts@@ -2,7 +2,7 @@* Seq-based queries powering the `/api/community/agent/*` CLI bridge routes* (plans/community-agent-cli-bridge.md §7) plus `toAgentMessages`, the* DB-row → wire-`Message` projector every route that returns message bodies- * uses (mirrors `src/daemon/src/server/mockServer.ts:548`'s `toAgentMessage`).+ * uses.** Kept in its own module (rather than folded into `message.ts`) because* every function here is agent-CLI-specific (seq-ordered, ref-formatted,@@ -316,7 +316,7 @@ export async function getLatestSeqForScope(db: Database, scopeKey: string): Prom* global seq order — `seq` is a per-scope counter, comparing raw values* across scopes is meaningless, see plan §7 v4). Always drains one channel's* unread completely (in seq order) before starting the next. Excludes the- * bot's own authored messages (mirrors `mockServer.ts:391`). Never mutates+ * bot's own authored messages. Never mutates* read state. Scope checks happen in SQL before returning rows: channel* messages require server membership, and DM messages require participation.*/diff --git a/src/shared/test/community-cli-contract.test.ts b/src/shared/test/community-cli-contract.test.tsindex 706abc5e0..656b86cb9 100644--- a/src/shared/test/community-cli-contract.test.ts+++ b/src/shared/test/community-cli-contract.test.ts@@ -62,8 +62,7 @@ describe("parseRef", () => {it('falls back to a plain-channel result for a DM ref with a non-numeric tail after "#" — does NOT throw', () => {// Regression guard: previously `parseRef("/.dm/foo#bar")` fell into// the `parseSeq(tail)` path and threw `bad seq: bar`, crashing any- // caller not wrapped in try/catch (`mockServer.ts` in tests,- // future callers in production). Now the whole segment is treated+ // caller not wrapped in try/catch. Now the whole segment is treated// as the channel/handle and the resolution layer// (`parseNameAndTag`) rejects the shape cleanly at its own boundary.expect(() => parseRef("/.dm/foo#bar")).not.toThrow();diff --git a/src/wake-worker/src/index.test.ts b/src/wake-worker/src/index.test.tsindex 6af95550c..ffe680877 100644--- a/src/wake-worker/src/index.test.ts+++ b/src/wake-worker/src/index.test.ts@@ -180,6 +180,14 @@ describe("wake-worker dev-only HTTP entrypoint (fetch)", () => {expect(res.status).toBe(405)expect(mockDispatchOneUnreadWake).not.toHaveBeenCalled()})++ it("returns 200 { status: ok } for GET /health without touching dispatch", async () => {+ const res = await handler.fetch!(new Request("http://internal/health", { method: "GET" }), env)++ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ status: "ok" })+ expect(mockDispatchOneUnreadWake).not.toHaveBeenCalled()+ })})/**diff --git a/src/wake-worker/src/index.ts b/src/wake-worker/src/index.tsindex 1a3429c56..f58541ab1 100644--- a/src/wake-worker/src/index.ts+++ b/src/wake-worker/src/index.ts@@ -72,6 +72,11 @@ export default {* candidate's failure is logged but never blocks siblings or the response.*/async fetch(request: Request, env: Env): Promise<Response> {+ const url = new URL(request.url)+ if (url.pathname === "/health" && request.method === "GET") {+ return Response.json({ status: "ok" })+ }+if (request.method !== "POST") return new Response("method not allowed", { status: 405 })let payloads: WakePayload[]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 12b4b008e..04e23a303 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@@ -259,4 +259,44 @@ describe("POST /api/community/agent/send", () => {expect(res.status).toBe(400)expect(mockCreateCommunityMessage).not.toHaveBeenCalled()})++ it("sequential scenario: blocked/unaligned → pull+ack (simulated by an advancing lastReadSeq) → send succeeds → a new message arrives → send blocks again", async () => {+ // 1. Bot is behind: latestSeq=10, bot's own tracked lastReadSeq=4 → blocked.+ mockGetLatestSeqForScope.mockResolvedValueOnce(10)+ mockGetReadState.mockResolvedValueOnce({ lastReadSeq: 4 })+ const blocked1 = await POST(+ req({ channel: "/studio/general", content: { text: "catching up" } }, { Authorization: "Bearer crk_abc" })+ )+ expect(blocked1.status).toBe(200)+ expect(await blocked1.json()).toEqual({ state: "blocked", reason: "unaligned", unreadCount: 6, latestSeq: 10 })+ expect(mockCreateCommunityMessage).not.toHaveBeenCalled()++ // 2. The agent pulls the backlog and acks up to seq 10 — modeled here as+ // the bot's tracked read state catching up to the channel's latest seq+ // (what a real inboxPull+ack round trip against+ // /api/community/agent/{inboxPull,ack} would produce).+ mockGetLatestSeqForScope.mockResolvedValueOnce(10)+ mockGetReadState.mockResolvedValueOnce({ lastReadSeq: 10 })+ mockCreateCommunityMessage.mockResolvedValueOnce({ ok: true, row: { id: "m_1", seq: 11, content: "caught up" } })+ const sent = await POST(+ req({ channel: "/studio/general", content: { text: "caught up" } }, { Authorization: "Bearer crk_abc" })+ )+ expect(sent.status).toBe(200)+ expect((await sent.json()).state).toBe("sent")+ expect(mockCreateCommunityMessage).toHaveBeenCalledTimes(1)++ // 3. A new message (from someone else) lands in the channel, advancing+ // latestSeq past the bot's now-stale read state — the next send blocks+ // again without a fresh pull+ack.+ mockGetLatestSeqForScope.mockResolvedValueOnce(12)+ mockGetReadState.mockResolvedValueOnce({ lastReadSeq: 10 })+ const blocked2 = await POST(+ req({ channel: "/studio/general", content: { text: "still going" } }, { Authorization: "Bearer crk_abc" })+ )+ expect(blocked2.status).toBe(200)+ expect(await blocked2.json()).toEqual({ state: "blocked", reason: "unaligned", unreadCount: 2, latestSeq: 12 })+ // Still only the one successful send from step 2 — this blocked call+ // must not have reached createCommunityMessage.+ expect(mockCreateCommunityMessage).toHaveBeenCalledTimes(1)+ })})diff --git a/src/web/src/app/api/community/agent/subscribeChannel/route.ts b/src/web/src/app/api/community/agent/subscribeChannel/route.tsindex 27665c44e..69a513044 100644--- a/src/web/src/app/api/community/agent/subscribeChannel/route.ts+++ b/src/web/src/app/api/community/agent/subscribeChannel/route.ts@@ -38,8 +38,7 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {// here), which would otherwise mask this command's own "DMs not// supported" 400 for any peer the bot hasn't DM'd before. Checking the// ref's server segment directly avoids depending on that resolution at- // all — mirrors `mockServer.ts`'s `subscribeChannel`, which does the- // same `parseRef`-first check.+ // all.let parsedRef: ReturnType<typeof parseRef>try {parsedRef = parseRef(body.channel)diff --git a/src/web/src/app/api/community/daemon/enroll-agent/route.test.ts b/src/web/src/app/api/community/daemon/enroll-agent/route.test.tsindex d5725a125..2273a01a9 100644--- a/src/web/src/app/api/community/daemon/enroll-agent/route.test.ts+++ b/src/web/src/app/api/community/daemon/enroll-agent/route.test.ts@@ -103,4 +103,69 @@ describe("POST /api/community/daemon/enroll-agent", () => {const res = await POST(req("not json", { Authorization: "Bearer cmk_ok" }))expect(res.status).toBe(400)})++ it("404 bot not found — unknown bot id (no such user row)", async () => {+ mockFindCred.mockResolvedValue({+ credentialId: "cmk_ok",+ userId: "u_1",+ machineId: "cm_1",+ })+ mockGetUserInternal.mockResolvedValue(null)+ const res = await POST(req({ agentId: "agent_missing" }, { Authorization: "Bearer cmk_ok" }))+ expect(res.status).toBe(404)+ expect(await res.json()).toEqual({ error: "bot not found" })+ expect(mockGetBotBinding).not.toHaveBeenCalled()+ expect(mockMint).not.toHaveBeenCalled()+ })++ it("404 bot not found — soft-deleted bot id (deletedAt set)", async () => {+ mockFindCred.mockResolvedValue({+ credentialId: "cmk_ok",+ userId: "u_1",+ machineId: "cm_1",+ })+ mockGetUserInternal.mockResolvedValue({+ id: "agent_a",+ isBot: true,+ ownerUserId: "u_1",+ deletedAt: "2024-01-01T00:00:00.000Z",+ })+ const res = await POST(req({ agentId: "agent_a" }, { Authorization: "Bearer cmk_ok" }))+ expect(res.status).toBe(404)+ expect(await res.json()).toEqual({ error: "bot not found" })+ expect(mockGetBotBinding).not.toHaveBeenCalled()+ expect(mockMint).not.toHaveBeenCalled()+ })++ it("404 bot not found — bot id belongs to a different owner", async () => {+ mockFindCred.mockResolvedValue({+ credentialId: "cmk_ok",+ userId: "u_1",+ machineId: "cm_1",+ })+ mockGetUserInternal.mockResolvedValue({+ id: "agent_a",+ isBot: true,+ ownerUserId: "u_other",+ deletedAt: null,+ })+ const res = await POST(req({ agentId: "agent_a" }, { Authorization: "Bearer cmk_ok" }))+ expect(res.status).toBe(404)+ expect(await res.json()).toEqual({ error: "bot not found" })+ expect(mockGetBotBinding).not.toHaveBeenCalled()+ expect(mockMint).not.toHaveBeenCalled()+ })++ it("404 bot not on this machine — binding points at a different machine", async () => {+ mockFindCred.mockResolvedValue({+ credentialId: "cmk_ok",+ userId: "u_1",+ machineId: "cm_1",+ })+ mockGetBotBinding.mockResolvedValue({ machineId: "cm_other", runtime: "claude" })+ const res = await POST(req({ agentId: "agent_a" }, { Authorization: "Bearer cmk_ok" }))+ expect(res.status).toBe(404)+ expect(await res.json()).toEqual({ error: "bot not on this machine" })+ expect(mockMint).not.toHaveBeenCalled()+ })})diff --git a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsxindex ba41b335a..ff8353131 100644--- a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx@@ -10,7 +10,6 @@ import { MessageList } from "@/components/community/message-list"import { Composer, ComposerSkeleton, type SendAttachment } from "@/components/community/composer"import { ForumView, ForumViewSkeleton } from "@/components/community/forum-view"import { CommunityPanelSheet } from "@/components/community/community-panel-sheet"-import { NewThreadDialog } from "@/components/community/new-thread-panel"import { ThreadOpener } from "@/components/community/thread-opener"import type { RightPanel, Msg, OpenProfile, Role } from "@/components/community/_types"import { canManageServer } from "@/components/community/_types"@@ -284,7 +283,6 @@ function ChannelView() {// ── Local UI state ──────────────────────────────────────────────────────const [rightPanel, setRightPanel] = useState<RightPanel>(null)- const [creatingThread, setCreatingThread] = useState(false)const [replyTo, setReplyTo] = useState<{ id: string; authorName: string; text: string } | null>(null)const [localName, setLocalName] = useState<string | null>(null)const [searchQuery, setSearchQuery] = useState("")@@ -299,7 +297,6 @@ function ChannelView() {setSearchResults([])setLocalName(null)setScrollToMessageId(null)- setCreatingThread(false)}, [channelId])const doSearch = useCallback(async (q: string) => {@@ -340,7 +337,7 @@ function ChannelView() {const enterThread = (id: string) => {router.push(`/community/channels/${params.serverId}/${id}`)- apiFetch(`/api/community/threads/${id}/read`, { method: "PUT" }).catch(() => {})+ apiFetch(`/api/community/threads/${id}/read`, { method: "PUT" }).catch(() => { })}const openProfile: OpenProfile = (name, e, discriminator, userId) => {@@ -465,22 +462,6 @@ function ChannelView() {communityWsSendTyping({ channelId })}- const createThreadFromDialog = async (name: string, firstMessage?: string) => {- setCreatingThread(false)- if (firstMessage) {- try {- const result = await doSend(firstMessage)- if (result?.message?.id) {- await createThreadMut.mutateAsync({ channelId, messageId: result.message.id, name })- }- } catch {- toast("Failed to create thread")- }- } else {- toast("Create a thread by clicking 'Create Thread' on any message")- }- }-const createForumPost = (post: { name: string; content: string; tags: string[] }) => {createForumPostMut.mutate({ channelId, ...post }, {onError: () => toast("Failed to create post"),@@ -555,7 +536,7 @@ function ChannelView() {structurally different JSX trees — React's reconciliation onlyneeds the position + type + key to line up.*/}- <MessageList key={channelId} channel="" messages={[]} loading={true} onOpenThread={() => {}} />+ <MessageList key={channelId} channel="" messages={[]} loading={true} onOpenThread={() => { }} /><ComposerSkeleton /></main></>@@ -590,7 +571,7 @@ function ChannelView() {rightPanel={rightPanel}onToggle={togglePanel}onBack={bp === "mobile" ? () => router.back() : undefined}- server={bp === "mobile" && currentServer ? { name: currentServer.name, icon: currentServer.icon } : undefined}+ server={bp === "mobile" && currentServer ? { id: currentServer.id, name: currentServer.name, icon: currentServer.icon } : undefined}tools={{ threads: false }}breadcrumb={{label: channelName,@@ -614,7 +595,7 @@ function ChannelView() {loading={messagesLoading}pinnedIds={pinnedIds}typingUsers={typingUsers.map((id) => members.find((m) => m.userId === id)?.name ?? id)}- onOpenThread={() => {}}+ onOpenThread={() => { }}{...threadActions}onOpenProfile={openProfile}resolveUserName={resolveUserName}@@ -673,7 +654,7 @@ function ChannelView() {notifLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? "Use Server Default"}onSetNotifLevel={(l) => setChannelNotifMut.mutate({ channelId, level: l })}onBack={bp === "mobile" ? goBack : undefined}- server={bp === "mobile" && currentServer ? { name: currentServer.name, icon: currentServer.icon } : undefined}+ server={bp === "mobile" && currentServer ? { id: currentServer.id, name: currentServer.name, icon: currentServer.icon } : undefined}tools={{ threads: false, pinned: false }}/><main className="flex min-h-0 min-w-0 flex-1 flex-col">@@ -716,7 +697,7 @@ function ChannelView() {notifLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? "Use Server Default"}onSetNotifLevel={(l) => setChannelNotifMut.mutate({ channelId, level: l })}onBack={bp === "mobile" ? goBack : undefined}- server={bp === "mobile" && currentServer ? { name: currentServer.name, icon: currentServer.icon } : undefined}+ server={bp === "mobile" && currentServer ? { id: currentServer.id, name: currentServer.name, icon: currentServer.icon } : undefined}/><main className="flex min-h-0 min-w-0 flex-1 flex-col"><MessageList@@ -757,7 +738,6 @@ function ChannelView() {onSearchMembers={membersHook.searchMembers}channelRefCandidates={channelRefCandidates}onSend={sendMessage}- onCreateThread={() => setCreatingThread(true)}onTyping={handleTyping}replyingTo={replyTo?.authorName}onCancelReply={() => setReplyTo(null)}@@ -774,13 +754,6 @@ function ChannelView() {onOpenProfile={openProfile}/>)}-- <NewThreadDialog- channel={channelName}- open={creatingThread}- onClose={() => setCreatingThread(false)}- onCreate={createThreadFromDialog}- /></>)}diff --git a/src/web/src/app/community/channels/layout.tsx b/src/web/src/app/community/channels/layout.tsxindex ddc03e607..bca2a3325 100644--- a/src/web/src/app/community/channels/layout.tsx+++ b/src/web/src/app/community/channels/layout.tsx@@ -331,6 +331,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {const channelProps = useMemo(() => ({tree: channelTree,serverName: currentServer?.name ?? "",+ serverIcon: currentServer?.icon ?? null,activeChannel: currentChannelMeta?.parentChannelId ?? currentChannelId ?? "",isAdmin,currentUserId: currentUser.id,diff --git a/src/web/src/app/community/invite/[token]/invite-accept-client.tsx b/src/web/src/app/community/invite/[token]/invite-accept-client.tsxindex 6360c800a..df61f9853 100644--- a/src/web/src/app/community/invite/[token]/invite-accept-client.tsx+++ b/src/web/src/app/community/invite/[token]/invite-accept-client.tsx@@ -108,7 +108,7 @@ export function InviteAcceptClient({ token }: { token: string }) {</div>{/* Server info */}- <p className="text-xs uppercase tracking-wide text-muted-foreground">You're invited to join</p>+ <p className="text-xs font-medium text-muted-foreground">You're invited to join</p><h1 className="mt-1 text-2xl font-semibold">{info?.serverName}</h1>{info?.memberCount != null && (<p className="mt-2 text-xs text-muted-foreground">diff --git a/src/web/src/app/community/preview/page.tsx b/src/web/src/app/community/preview/page.tsxindex 44e90197c..c36c33cdf 100644--- a/src/web/src/app/community/preview/page.tsx+++ b/src/web/src/app/community/preview/page.tsx@@ -33,7 +33,6 @@ import { useBreakpoint } from "@/hooks/use-mobile"import { useChannelTree } from "@/components/community/use-channel-tree"import { ProfileCard } from "@/components/community/profile-card"import { ImageLightbox } from "@/components/community/image-lightbox"-import { NewThreadDialog } from "@/components/community/new-thread-panel"import { UserSettings } from "@/components/community/edit-profile-dialog"import { ServerRail } from "@/components/community/server-rail"import { ChannelSidebar } from "@/components/community/channel-sidebar"@@ -94,8 +93,6 @@ export default function CommunityPreview() {// pattern above; no real persistence/WS fan-out here (see plans/profile-card.md).const [myStatus, setMyStatus] = useState<{ emoji: string | null; text: string | null }>({ emoji: "🎧", text: "Vibing" })const [editingProfile, setEditingProfile] = useState(false)- // when set, the message area shows the "New Thread" creation panel- const [creatingThread, setCreatingThread] = useState(false)// reply target (message being replied to) — drives the composer quote barconst [replyTo, setReplyTo] = useState<{ id: string; authorName: string; text: string } | null>(null)// search query submitted from the channel header (opens the search panel pre-filled)@@ -212,27 +209,21 @@ export default function CommunityPreview() {if (bp === "mobile") setMobileZone("messages")}- // create a thread (local) and open it.- // - `anchor` (from a message) becomes the thread's first message.- // - otherwise `firstMessage` (from the New Thread panel) seeds an optional opener.+ // create a thread (local) and open it — anchored to the message it was+ // created from (its first message).let threadSeq = 0- const createThread = (name: string, opts?: { firstMessage?: string; anchor?: Msg }) => {+ const createThread = (name: string, anchor?: Msg) => {const id = `thr_local_${++threadSeq}`- const seed: Msg[] = opts?.anchor- ? [opts.anchor]- : opts?.firstMessage- ? [{ id: `${id}_1`, type: "chat" as const, authorName: "Gener", authorAvatar: "G", createdAt: new Date().toISOString(), content: opts.firstMessage }]- : []+ const seed: Msg[] = anchor ? [anchor] : []const t: Thread = {id, name, messageCount: seed.length, lastMessageAt: new Date().toISOString(),parent: {- authorName: opts?.anchor?.authorName ?? "Gener",- text: opts?.anchor?.content ?? name,+ authorName: anchor?.authorName ?? "Gener",+ text: anchor?.content ?? name,},}setThreads((prev) => [t, ...prev])setThreadMessages((prev) => ({ ...prev, [id]: seed }))- setCreatingThread(false)enterThread(id)}// from a message — the message anchors the thread (its first message); name defaults@@ -240,7 +231,7 @@ export default function CommunityPreview() {const createThreadFromMessage = (id: string) => {const m = messages.find((x) => x.id === id)const name = (m?.content ?? activeChannel).split(/\s+/).slice(0, 6).join(" ").slice(0, 60) || activeChannel- createThread(name, m ? { anchor: m } : undefined)+ createThread(name, m)}// send a channel message — append to the local list (live app: POST + WS echo)@@ -467,7 +458,7 @@ export default function CommunityPreview() {<MessageListchannel={dm.name}messages={dmMessages[dm.id] ?? []}- onOpenThread={() => {}}+ onOpenThread={() => { }}variant="dm"{...profileProps}hero={@@ -524,7 +515,7 @@ export default function CommunityPreview() {/><main className="flex min-h-0 min-w-0 flex-1 flex-col"><MessageList channel={activeChannel} messages={messages} pinnedIds={pinnedIds} newDividerBefore={NEW_DIVIDER_BEFORE} typingUsers={["Lindsay"]} onOpenThread={enterThread} {...messageActions} {...profileProps} />- <Composer channel={activeChannel} context="channel" members={composerMembers} onSend={sendMessage} onCreateThread={() => setCreatingThread(true)} replyingTo={replyTo?.authorName} onCancelReply={() => setReplyTo(null)} />+ <Composer channel={activeChannel} context="channel" members={composerMembers} onSend={sendMessage} replyingTo={replyTo?.authorName} onCancelReply={() => setReplyTo(null)} /></main></>)@@ -533,7 +524,6 @@ export default function CommunityPreview() {// portaled dialogs — rendered in every layout branchconst dialogs = (<>- <NewThreadDialog channel={activeChannel} open={creatingThread} onClose={() => setCreatingThread(false)} onCreate={(name, firstMessage) => createThread(name, { firstMessage })} /><Dialog open={editingProfile} onOpenChange={(o) => { if (!o) setEditingProfile(false) }}><DialogContent className="flex h-[calc(100vh-4rem)] max-h-180 w-[calc(100vw-4rem)] sm:max-w-4xl flex-col gap-0 overflow-hidden rounded-xl p-0" showCloseButton={false}><UserSettingsdiff --git a/src/web/src/components/community/bots/bot-form-fields.tsx b/src/web/src/components/community/bots/bot-form-fields.tsxnew file mode 100644index 000000000..28c6caad3--- /dev/null+++ b/src/web/src/components/community/bots/bot-form-fields.tsx@@ -0,0 +1,89 @@+"use client"++import { Dices } from "lucide-react"+import { AutoResizeTextarea } from "@/components/ui/auto-resize-textarea"+import { type AvatarDraft, BotAvatarPickerDialog } from "@/components/avatar"+import {+ COMMUNITY_BOT_NAME_MAX,+ COMMUNITY_BOT_DESCRIPTION_MAX,+} from "@alook/shared"++/**+ * Shared Name/Description/Avatar block for the bot create and edit sheets —+ * the frameless treatment mirrors `agent-form-fields.tsx`'s `GeneralFields`+ * (large borderless name input, auto-growing borderless description) so a+ * bot's identity fields read the same way an agent's do, instead of the two+ * bot forms drifting from each other with their own one-off `Input`/`Textarea`+ * styling.+ */+export function BotFormFields({+ avatarDraft,+ onAvatarChange,+ name,+ setName,+ onShuffle,+ description,+ setDescription,+ nameError,+}: {+ avatarDraft: AvatarDraft+ onAvatarChange: (draft: AvatarDraft) => void+ name: string+ setName: (v: string) => void+ onShuffle: () => void+ description: string+ setDescription: (v: string) => void+ nameError?: string+}) {+ return (+ <div className="flex flex-col gap-1">+ <div className="flex justify-center pb-3">+ <BotAvatarPickerDialog+ image={avatarDraft.kind === "procedural" ? avatarDraft.image : avatarDraft.previewUrl}+ onChange={onAvatarChange}+ />+ </div>++ {/* Name — large frameless input, matching #agent-name */}+ <div>+ <div className="relative">+ <input+ id="bot-name"+ value={name}+ maxLength={COMMUNITY_BOT_NAME_MAX}+ onChange={(e) => setName(e.target.value)}+ placeholder="Name your bot"+ autoFocus+ aria-invalid={Boolean(nameError)}+ aria-describedby={nameError ? "bot-name-error" : undefined}+ className="w-full border-0 bg-transparent px-0 py-1 text-2xl font-medium leading-[1.2] tracking-tight shadow-none outline-none placeholder:text-muted-foreground/40 placeholder:font-normal focus-visible:ring-0"+ />+ <button+ type="button"+ onClick={onShuffle}+ aria-label="Randomize name"+ className="absolute right-0 top-1/2 -translate-y-1/2 rounded p-2 text-muted-foreground/50 transition-colors hover:bg-accent hover:text-foreground"+ >+ <Dices className="size-4" />+ </button>+ </div>+ {nameError && (+ <p id="bot-name-error" className="mt-1 text-xs text-destructive">+ {nameError}+ </p>+ )}+ </div>++ {/* Description — frameless, auto-growing */}+ <AutoResizeTextarea+ id="bot-description"+ value={description}+ maxLength={COMMUNITY_BOT_DESCRIPTION_MAX}+ onChange={(e) => setDescription(e.target.value)}+ placeholder="What is this bot for?"+ rows={1}+ className="w-full border-0 bg-transparent px-0 py-1 text-sm text-foreground shadow-none outline-none placeholder:text-muted-foreground/40 focus-visible:ring-0"+ />+ </div>+ )+}diff --git a/src/web/src/components/community/bots/bot-form-validation.ts b/src/web/src/components/community/bots/bot-form-validation.tsnew file mode 100644index 000000000..9c36eb910--- /dev/null+++ b/src/web/src/components/community/bots/bot-form-validation.ts@@ -0,0 +1,35 @@+export interface BotCreateRequiredFields {+ name: string+ machineId: string+ runtime: string+}++export interface BotCreateFieldErrors {+ name?: string+ machineId?: string+ runtime?: string+}++export function validateBotCreateFields({+ name,+ machineId,+ runtime,+}: BotCreateRequiredFields): BotCreateFieldErrors {+ const errors: BotCreateFieldErrors = {}++ if (!name.trim()) {+ errors.name = "Name is required"+ }+ if (!machineId) {+ errors.machineId = "Pick a machine"+ }+ if (!runtime) {+ errors.runtime = "Pick a runtime"+ }++ return errors+}++export function hasBotCreateFieldErrors(errors: BotCreateFieldErrors): boolean {+ return Boolean(errors.name || errors.machineId || errors.runtime)+}diff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsxindex c9316b277..f7bc8863d 100644--- a/src/web/src/components/community/bots/bot-list.tsx+++ b/src/web/src/components/community/bots/bot-list.tsx@@ -28,8 +28,8 @@ 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"+import { CreateBotSheet } from "./create-bot-sheet"+import { EditBotSheet } from "./edit-bot-sheet"/*** BotList — the /community/me/bots surface.@@ -51,7 +51,13 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {// (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)+ // `editingBot` deliberately never resets to null on close — EditBotSheet+ // stays mounted at all times (see its render below) so its open/close+ // transition always has a "closed" state to animate from, matching+ // CreateBotSheet. Only `editOpen` toggles; the last-edited bot lingers+ // harmlessly while the sheet is hidden.+ const [editingBot, setEditingBot] = useState<BotSummary | null>(null)+ const [editOpen, setEditOpen] = useState(false)const [confirmDelete, setConfirmDelete] = useState<BotSummary | null>(null)const del = useDeleteBot()const createOrGetDm = useCreateOrGetDm()@@ -154,7 +160,7 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {</div><Button onClick={() => setCreateOpen(true)}>Create a bot</Button></div>- <CreateBotDialog open={createOpen} onOpenChange={setCreateOpen} />+ <CreateBotSheet open={createOpen} onOpenChange={setCreateOpen} /></div>)}@@ -192,7 +198,7 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {><div className="flex items-center gap-2 px-1"><Monitor className="size-3.5 text-muted-foreground" />- <span className="text-xs font-semibold text-muted-foreground">+ <span className="font-mono text-xs font-medium text-muted-foreground">{machineName(machineId)}</span><span@@ -271,7 +277,12 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {<DropdownMenuItem onClick={() => chatWithBot(bot)}>Chat</DropdownMenuItem>- <DropdownMenuItem onClick={() => setEditing(bot)}>+ <DropdownMenuItem+ onClick={() => {+ setEditingBot(bot)+ setEditOpen(true)+ }}+ >Edit</DropdownMenuItem><DropdownMenuItem@@ -293,14 +304,8 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {</div></div>- <CreateBotDialog open={createOpen} onOpenChange={setCreateOpen} />- {editing && (- <EditBotDialog- bot={editing}- open={!!editing}- onOpenChange={(open) => !open && setEditing(null)}- />- )}+ <CreateBotSheet open={createOpen} onOpenChange={setCreateOpen} />+ <EditBotSheet bot={editingBot} open={editOpen} onOpenChange={setEditOpen} /><AlertDialogopen={!!confirmDelete}onOpenChange={(open) => !open && setConfirmDelete(null)}diff --git a/src/web/src/components/community/bots/create-bot-dialog.tsx b/src/web/src/components/community/bots/create-bot-dialog.tsxdeleted file mode 100644index 18d2db776..000000000--- a/src/web/src/components/community/bots/create-bot-dialog.tsx+++ /dev/null@@ -1,304 +0,0 @@-"use client"--import { useEffect, useMemo, useRef, useState } from "react"-import { toast } from "sonner"-import { Dices } from "lucide-react"-import {- Dialog,- DialogContent,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog"-import { Button } from "@/components/ui/button"-import { Label } from "@/components/ui/label"-import { Input } from "@/components/ui/input"-import { Textarea } from "@/components/ui/textarea"-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select"-import {- type AvatarConfig,- type AvatarDraft,- BotAvatarPickerDialog,- randomConfig,- serializeAvatarConfig,-} from "@/components/avatar"-import { ProviderLogo } from "@/components/provider-logo"-import { useMachines } from "@/hooks/community/use-machines"-import { useCreateBot, useUploadBotAvatar } from "@/hooks/community/use-bots"-import {- COMMUNITY_BOT_NAME_MAX,- COMMUNITY_BOT_DESCRIPTION_MAX,-} from "@alook/shared"-import { uniqueNamesGenerator, names } from "unique-names-generator"--// Stable initial config avoids hydration mismatch (randomConfig uses Math.random).-const INITIAL_AVATAR: AvatarConfig = {- shape: "circle",- eye: "dots",- nose: "dot",- bg: 0,-}--function randomBotName(): string {- return uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "capital" })-}--function machineLabel(m: {- displayName?: string | null- hostname?: string | null- id: string-}): string {- const name = m.displayName?.trim() || m.hostname?.trim()- return name || "Unnamed machine"-}--export function CreateBotDialog({- open,- onOpenChange,-}: {- open: boolean- onOpenChange: (open: boolean) => void-}) {- const { machines } = useMachines()- const create = useCreateBot()- const uploadBotAvatar = useUploadBotAvatar()- const [name, setName] = useState("")- const [description, setDescription] = useState("")- const [machineId, setMachineId] = useState<string>("")- const [runtime, setRuntime] = useState<string>("")- const [avatarDraft, setAvatarDraft] = useState<AvatarDraft>({- kind: "procedural",- image: serializeAvatarConfig(INITIAL_AVATAR),- })-- const selectedMachine = machines.find((m) => m.id === machineId)- const runtimeOptions = useMemo(() => {- // Nullish guard — a legacy CommunityMachineSummary cached client-side may- // still be missing availableRuntimes. `filter` on undefined would throw.- const rt = selectedMachine?.availableRuntimes ?? []- return rt- // Only offer healthy runtimes for binding. The server-side /api/community/bots- // POST validator ALSO enforces `status === 'healthy'` — this filter is UX- // only. Older summaries that predate the widening default `status` to- // "healthy" via Zod, so they still show through.- .filter((r) => {- if (typeof r === "string") return true- return (r as { status?: string }).status !== "unhealthy"- })- .map((r) => (typeof r === "string" ? r : (r as { id: string }).id))- }, [selectedMachine])-- // Randomize name + avatar on client mount (not during SSR — Math.random would- // hydration-mismatch). Fires once per dialog open.- const initializedFor = useRef<boolean | null>(null)- useEffect(() => {- if (!open) {- initializedFor.current = null- return- }- if (initializedFor.current) return- initializedFor.current = true- setName(randomBotName())- setAvatarDraft({ kind: "procedural", image: serializeAvatarConfig(randomConfig()) })- setDescription("")- setMachineId("")- setRuntime("")- }, [open])-- function shuffleName() {- setName(randomBotName())- }-- async function submit() {- if (!name.trim()) return toast.error("Name is required")- if (!machineId) return toast.error("Pick a machine")- if (!runtime) return toast.error("Pick a runtime")- try {- const data = await create.mutateAsync({- name: name.trim(),- description: description.trim() || undefined,- machineId,- runtime,- image: avatarDraft.kind === "procedural" ? avatarDraft.image : undefined,- })- // Bots don't have an id until creation resolves — the photo upload is- // deferred until now so a cropped-then-cancelled dialog never uploads- // anything. Surface an upload failure without blocking on it; the bot- // itself was already created successfully.- let avatarFailed = false- if (avatarDraft.kind === "photo" && avatarDraft.file) {- try {- await uploadBotAvatar.mutateAsync({ botId: data.bot.id, file: avatarDraft.file })- } catch {- avatarFailed = true- toast.error("Bot created, but the avatar photo failed to upload")- }- }- if (!avatarFailed) toast.success(`Created ${name.trim()}`)- onOpenChange(false)- } catch (err) {- toast.error(err instanceof Error ? err.message : "Couldn't create the bot")- }- }-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="sm:max-w-md">- <DialogHeader>- <DialogTitle>Create a bot</DialogTitle>- </DialogHeader>-- {/* Single column. Every field is full-width. Rhythm: gap-4 between- fields, gap-2 within a field (label + control). */}- <div className="flex flex-col gap-4">- {/* Centered avatar picker — the identity anchor. */}- <div className="flex justify-center pt-1">- <BotAvatarPickerDialog- image={avatarDraft.kind === "procedural" ? avatarDraft.image : avatarDraft.previewUrl}- onChange={setAvatarDraft}- />- </div>-- <div className="flex flex-col gap-2">- <Label htmlFor="bot-name" className="text-xs text-muted-foreground">- Name- </Label>- <div className="relative w-full">- <Input- id="bot-name"- value={name}- maxLength={COMMUNITY_BOT_NAME_MAX}- onChange={(e) => setName(e.target.value)}- placeholder="Name your bot"- autoFocus- className="h-9 w-full pr-10"- />- <button- type="button"- onClick={shuffleName}- aria-label="Randomize name"- className="absolute right-1 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"- >- <Dices className="size-4" />- </button>- </div>- </div>-- <div className="flex flex-col gap-2">- <Label htmlFor="bot-description" className="text-xs text-muted-foreground">- Description- </Label>- <Textarea- id="bot-description"- value={description}- maxLength={COMMUNITY_BOT_DESCRIPTION_MAX}- onChange={(e) => setDescription(e.target.value)}- placeholder="What is this bot for?"- rows={3}- className="min-h-18 resize-none"- />- </div>-- <div className="flex flex-col gap-2">- <Label className="text-xs text-muted-foreground">Machine</Label>- <Select- value={machineId}- onValueChange={(v) => {- setMachineId(v ?? "")- setRuntime("")- }}- >- <SelectTrigger className="h-9 w-full">- {/*- base-ui's SelectValue renders the raw `value` string unless a- function-child is supplied. Look the id up and render the- human label so users don't see the machine id.- */}- <SelectValue placeholder="Select a machine">- {(v) => {- const m = machines.find((x) => x.id === v)- return m ? machineLabel(m) : "Select a machine"- }}- </SelectValue>- </SelectTrigger>- <SelectContent className="p-1">- {machines.length === 0 && (- <div className="px-2 py-4 text-center text-xs text-muted-foreground">- No paired machines — pair one first.- </div>- )}- {machines.map((m) => (- <SelectItem key={m.id} value={m.id} className="px-2 py-2">- {machineLabel(m)}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>-- <div className="flex flex-col gap-2">- <Label className="text-xs text-muted-foreground">Runtime</Label>- <Select- value={runtime}- onValueChange={(v) => setRuntime(v ?? "")}- disabled={!selectedMachine}- >- <SelectTrigger className="h-9 w-full">- <SelectValue- placeholder={- selectedMachine ? "Select a runtime" : "Pick a machine first"- }- >- {(v) =>- v ? (- <span className="flex items-center gap-2">- <ProviderLogo provider={v} className="size-4" />- <span>{v}</span>- </span>- ) : selectedMachine ? (- "Select a runtime"- ) : (- "Pick a machine first"- )- }- </SelectValue>- </SelectTrigger>- <SelectContent className="p-1">- {runtimeOptions.length === 0 && selectedMachine && (- <div className="px-2 py-4 text-center text-xs text-muted-foreground">- {(selectedMachine.availableRuntimes ?? []).length === 0- ? "This machine has no runtimes installed."- : "No healthy runtimes available on this machine."}- </div>- )}- {runtimeOptions.map((r) => (- <SelectItem key={r} value={r} className="px-2 py-2">- <span className="flex items-center gap-2">- <ProviderLogo provider={r} className="size-4 shrink-0" />- <span>{r}</span>- </span>- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- </div>-- <DialogFooter>- <Button variant="ghost" onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button onClick={submit} disabled={create.isPending}>- {create.isPending ? "Creating…" : "Create bot"}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- )-}diff --git a/src/web/src/components/community/bots/create-bot-sheet.tsx b/src/web/src/components/community/bots/create-bot-sheet.tsxnew file mode 100644index 000000000..74c2c5deb--- /dev/null+++ b/src/web/src/components/community/bots/create-bot-sheet.tsx@@ -0,0 +1,300 @@+"use client"++import { useEffect, useMemo, useRef, useState } from "react"+import { toast } from "sonner"+import {+ Sheet,+ SheetBody,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from "@/components/ui/sheet"+import { Button } from "@/components/ui/button"+import { Label } from "@/components/ui/label"+import {+ type AvatarConfig,+ type AvatarDraft,+ randomConfig,+ serializeAvatarConfig,+} from "@/components/avatar"+import { ProviderLogo } from "@/components/provider-logo"+import { useMachines } from "@/hooks/community/use-machines"+import { useCreateBot, useUploadBotAvatar } from "@/hooks/community/use-bots"+import { BotFormFields } from "./bot-form-fields"+import {+ type BotCreateFieldErrors,+ hasBotCreateFieldErrors,+ validateBotCreateFields,+} from "./bot-form-validation"+import { uniqueNamesGenerator, names } from "unique-names-generator"+import { cn } from "@/lib/utils"++// Stable initial config avoids hydration mismatch (randomConfig uses Math.random).+const INITIAL_AVATAR: AvatarConfig = {+ shape: "circle",+ eye: "dots",+ nose: "dot",+ bg: 0,+}++function randomBotName(): string {+ return uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "capital" })+}++function machineLabel(m: {+ displayName?: string | null+ hostname?: string | null+ id: string+}): string {+ const name = m.displayName?.trim() || m.hostname?.trim()+ return name || "Unnamed machine"+}++export function CreateBotSheet({+ open,+ onOpenChange,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { machines } = useMachines()+ const create = useCreateBot()+ const uploadBotAvatar = useUploadBotAvatar()+ const [name, setName] = useState("")+ const [description, setDescription] = useState("")+ const [machineId, setMachineId] = useState<string>("")+ const [runtime, setRuntime] = useState<string>("")+ const [fieldErrors, setFieldErrors] = useState<BotCreateFieldErrors>({})+ const [avatarDraft, setAvatarDraft] = useState<AvatarDraft>({+ kind: "procedural",+ image: serializeAvatarConfig(INITIAL_AVATAR),+ })++ const selectedMachine = machines.find((m) => m.id === machineId)+ const runtimeOptions = useMemo(() => {+ // Nullish guard — a legacy CommunityMachineSummary cached client-side may+ // still be missing availableRuntimes, or a runtime entry may still be a+ // bare string (pre-health-status shape). Normalize both into+ // `{ id, unhealthy }` instead of hiding unhealthy runtimes outright, so+ // the radio card can show *why* an option is disabled.+ const rt = selectedMachine?.availableRuntimes ?? []+ const normalized = rt.map((r) =>+ typeof r === "string"+ ? { id: r, unhealthy: false }+ : { id: (r as { id: string }).id, unhealthy: (r as { status?: string }).status === "unhealthy" },+ )+ // Available runtimes sort first — the ones you can actually pick should+ // never be buried below ones you can't.+ return normalized.sort((a, b) => Number(a.unhealthy) - Number(b.unhealthy))+ }, [selectedMachine])++ // Randomize name + avatar on client mount (not during SSR — Math.random would+ // hydration-mismatch). Fires once per sheet open.+ const initializedFor = useRef<boolean | null>(null)+ useEffect(() => {+ if (!open) {+ initializedFor.current = null+ return+ }+ if (initializedFor.current) return+ initializedFor.current = true+ setName(randomBotName())+ setAvatarDraft({ kind: "procedural", image: serializeAvatarConfig(randomConfig()) })+ setDescription("")+ setMachineId("")+ setRuntime("")+ setFieldErrors({})+ }, [open])++ function shuffleName() {+ setName(randomBotName())+ setFieldErrors((prev) => ({ ...prev, name: undefined }))+ }++ function updateName(value: string) {+ setName(value)+ if (fieldErrors.name && value.trim()) {+ setFieldErrors((prev) => ({ ...prev, name: undefined }))+ }+ }++ function selectMachine(id: string) {+ setMachineId(id)+ setRuntime("")+ setFieldErrors((prev) => ({ ...prev, machineId: undefined }))+ }++ function selectRuntime(id: string) {+ setRuntime(id)+ setFieldErrors((prev) => ({ ...prev, runtime: undefined }))+ }++ async function submit() {+ const nextErrors = validateBotCreateFields({ name, machineId, runtime })+ setFieldErrors(nextErrors)+ if (hasBotCreateFieldErrors(nextErrors)) return++ try {+ const data = await create.mutateAsync({+ name: name.trim(),+ description: description.trim() || undefined,+ machineId,+ runtime,+ image: avatarDraft.kind === "procedural" ? avatarDraft.image : undefined,+ })+ // Bots don't have an id until creation resolves — the photo upload is+ // deferred until now so a cropped-then-cancelled dialog never uploads+ // anything. Surface an upload failure without blocking on it; the bot+ // itself was already created successfully.+ let avatarFailed = false+ if (avatarDraft.kind === "photo" && avatarDraft.file) {+ try {+ await uploadBotAvatar.mutateAsync({ botId: data.bot.id, file: avatarDraft.file })+ } catch {+ avatarFailed = true+ toast.error("Bot created, but the avatar photo failed to upload")+ }+ }+ if (!avatarFailed) toast.success(`Created ${name.trim()}`)+ onOpenChange(false)+ } catch (err) {+ toast.error(err instanceof Error ? err.message : "Couldn't create the bot")+ }+ }++ return (+ <Sheet open={open} onOpenChange={onOpenChange} disablePointerDismissal>+ <SheetContent+ side="right"+ showOverlay={false}+ className="data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border data-[side=right]:sm:overflow-hidden"+ >+ <SheetHeader>+ <SheetTitle>Create a bot</SheetTitle>+ </SheetHeader>++ <SheetBody className="flex flex-col gap-6">+ <BotFormFields+ avatarDraft={avatarDraft}+ onAvatarChange={setAvatarDraft}+ name={name}+ setName={updateName}+ onShuffle={shuffleName}+ description={description}+ setDescription={setDescription}+ nameError={fieldErrors.name}+ />++ <div className="flex flex-col gap-2">+ <Label className="text-xs text-muted-foreground">Machine</Label>+ {machines.length === 0 ? (+ <p className="text-xs text-muted-foreground">+ No paired machines — pair one first.+ </p>+ ) : (+ <div className="flex flex-col gap-2" role="radiogroup" aria-label="Machine">+ {machines.map((m) => {+ const online = m.status === "online"+ const selected = machineId === m.id+ return (+ <label+ key={m.id}+ className={cn(+ "flex items-center gap-2 rounded-lg border p-2 cursor-pointer transition-colors",+ selected ? "border-primary bg-primary/5" : "border-border/50 hover:border-foreground/20",+ !online && "opacity-40 pointer-events-none",+ )}+ >+ <input+ type="radio"+ name="bot-machine"+ value={m.id}+ checked={selected}+ disabled={!online}+ onChange={() => selectMachine(m.id)}+ className="accent-primary size-3.5"+ />+ <span className="text-sm">{machineLabel(m)}</span>+ <span+ className={cn(+ "ml-auto inline-flex items-center gap-1 text-xs",+ online ? "text-emerald-600 dark:text-emerald-400" : "text-muted-foreground",+ )}+ >+ <span+ className={cn(+ "inline-block size-1.5 rounded-full",+ online ? "bg-status-online" : "bg-muted-foreground",+ )}+ />+ {online ? "Online" : "Offline"}+ </span>+ </label>+ )+ })}+ </div>+ )}+ {fieldErrors.machineId && (+ <p className="text-xs text-destructive">{fieldErrors.machineId}</p>+ )}+ </div>++ {selectedMachine && (+ <div className="flex flex-col gap-2">+ <Label className="text-xs text-muted-foreground">Runtime</Label>+ {runtimeOptions.length === 0 ? (+ <p className="text-xs text-muted-foreground">+ This machine has no runtimes installed.+ </p>+ ) : (+ <div className="flex flex-col gap-2" role="radiogroup" aria-label="Runtime">+ {runtimeOptions.map((r) => {+ const selected = runtime === r.id+ return (+ <label+ key={r.id}+ className={cn(+ "flex items-center gap-2 rounded-lg border p-2 cursor-pointer transition-colors",+ selected ? "border-primary bg-primary/5" : "border-border/50 hover:border-foreground/20",+ r.unhealthy && "opacity-40 pointer-events-none",+ )}+ >+ <input+ type="radio"+ name="bot-runtime"+ value={r.id}+ checked={selected}+ disabled={r.unhealthy}+ onChange={() => selectRuntime(r.id)}+ className="accent-primary size-3.5"+ />+ <ProviderLogo provider={r.id} className="size-4 shrink-0" />+ <span className="text-sm">{r.id}</span>+ {r.unhealthy && (+ <span className="ml-auto text-xs text-muted-foreground">unavailable</span>+ )}+ </label>+ )+ })}+ </div>+ )}+ {fieldErrors.runtime && (+ <p className="text-xs text-destructive">{fieldErrors.runtime}</p>+ )}+ </div>+ )}+ </SheetBody>++ <SheetFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button onClick={submit} disabled={create.isPending}>+ {create.isPending ? "Creating…" : "Create bot"}+ </Button>+ </SheetFooter>+ </SheetContent>+ </Sheet>+ )+}diff --git a/src/web/src/components/community/bots/edit-bot-dialog.tsx b/src/web/src/components/community/bots/edit-bot-dialog.tsxdeleted file mode 100644index a34332128..000000000--- a/src/web/src/components/community/bots/edit-bot-dialog.tsx+++ /dev/null@@ -1,130 +0,0 @@-"use client"--import { useState } from "react"-import { toast } from "sonner"-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog"-import { Button } from "@/components/ui/button"-import { Input } from "@/components/ui/input"-import { Label } from "@/components/ui/label"-import { Textarea } from "@/components/ui/textarea"-import {- type AvatarConfig,- type AvatarDraft,- BotAvatarPickerDialog,- isPhotoAvatarUrl,- serializeAvatarConfig,-} from "@/components/avatar"-import { useUpdateBot, useUploadBotAvatar, type BotSummary } from "@/hooks/community/use-bots"-import {- COMMUNITY_BOT_NAME_MAX,- COMMUNITY_BOT_DESCRIPTION_MAX,-} from "@alook/shared"--const DEFAULT_AVATAR: AvatarConfig = {- shape: "circle",- eye: "dots",- nose: "dot",- bg: 0,-}--export function EditBotDialog({- bot,- open,- onOpenChange,-}: {- bot: BotSummary- open: boolean- onOpenChange: (open: boolean) => void-}) {- const [name, setName] = useState(bot.name)- const [description, setDescription] = useState(bot.description ?? "")- const [avatarDraft, setAvatarDraft] = useState<AvatarDraft>(() =>- isPhotoAvatarUrl(bot.image)- ? { kind: "photo", file: null, previewUrl: bot.image! }- : { kind: "procedural", image: bot.image ?? serializeAvatarConfig(DEFAULT_AVATAR) },- )- const update = useUpdateBot()- const uploadBotAvatar = useUploadBotAvatar()-- async function submit() {- if (!name.trim()) return toast.error("name is required")- try {- // Sequence matters — only attempt the avatar upload AFTER the- // name/description update resolves, inside the same try block, so a- // failed field update never triggers an upload.- await update.mutateAsync({- id: bot.id,- name: name.trim(),- description: description.trim() || undefined,- image: avatarDraft.kind === "procedural" ? avatarDraft.image : undefined,- })- let avatarFailed = false- if (avatarDraft.kind === "photo" && avatarDraft.file) {- try {- await uploadBotAvatar.mutateAsync({ botId: bot.id, file: avatarDraft.file })- } catch {- avatarFailed = true- toast.error("Bot updated, but the avatar photo failed to upload")- }- }- if (!avatarFailed) toast.success("Bot updated")- onOpenChange(false)- } catch (err) {- toast.error(err instanceof Error ? err.message : "Update failed")- }- }-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>Edit {bot.name}</DialogTitle>- <DialogDescription>- Name and description edits take effect on the bot's next wake trigger.- </DialogDescription>- </DialogHeader>- <div className="space-y-4">- <div className="flex items-center justify-center">- <BotAvatarPickerDialog- image={avatarDraft.kind === "procedural" ? avatarDraft.image : avatarDraft.previewUrl}- onChange={setAvatarDraft}- />- </div>- <div className="space-y-2">- <Label htmlFor="bot-name">Name</Label>- <Input- id="bot-name"- value={name}- maxLength={COMMUNITY_BOT_NAME_MAX}- onChange={(e) => setName(e.target.value)}- />- </div>- <div className="space-y-2">- <Label htmlFor="bot-description">Description</Label>- <Textarea- id="bot-description"- rows={3}- maxLength={COMMUNITY_BOT_DESCRIPTION_MAX}- value={description}- onChange={(e) => setDescription(e.target.value)}- placeholder="A helpful research assistant"- />- </div>- </div>- <DialogFooter>- <Button variant="ghost" onClick={() => onOpenChange(false)}>Cancel</Button>- <Button onClick={submit} disabled={update.isPending}>- {update.isPending ? "Saving…" : "Save"}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- )-}diff --git a/src/web/src/components/community/bots/edit-bot-sheet.tsx b/src/web/src/components/community/bots/edit-bot-sheet.tsxnew file mode 100644index 000000000..934b1ee18--- /dev/null+++ b/src/web/src/components/community/bots/edit-bot-sheet.tsx@@ -0,0 +1,156 @@+"use client"++import { useEffect, useRef, useState } from "react"+import { toast } from "sonner"+import {+ Sheet,+ SheetBody,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from "@/components/ui/sheet"+import { Button } from "@/components/ui/button"+import {+ type AvatarConfig,+ type AvatarDraft,+ isPhotoAvatarUrl,+ serializeAvatarConfig,+} from "@/components/avatar"+import { useUpdateBot, useUploadBotAvatar, type BotSummary } from "@/hooks/community/use-bots"+import { BotFormFields } from "./bot-form-fields"+import { uniqueNamesGenerator, names } from "unique-names-generator"++const DEFAULT_AVATAR: AvatarConfig = {+ shape: "circle",+ eye: "dots",+ nose: "dot",+ bg: 0,+}++function draftFromBot(bot: BotSummary): AvatarDraft {+ return isPhotoAvatarUrl(bot.image)+ ? { kind: "photo", file: null, previewUrl: bot.image! }+ : { kind: "procedural", image: bot.image ?? serializeAvatarConfig(DEFAULT_AVATAR) }+}++export function EditBotSheet({+ bot,+ open,+ onOpenChange,+}: {+ // Nullable — the caller (`bot-list.tsx`) keeps this sheet mounted at all+ // times so the open/close transition always has a "closed" state to+ // animate from (mounting it fresh already-open, like the old+ // `{editing && <EditBotSheet .../>}` gate did, skips the enter animation+ // entirely). `bot` is only null before the first-ever edit.+ bot: BotSummary | null+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const [name, setName] = useState(bot?.name ?? "")+ const [description, setDescription] = useState(bot?.description ?? "")+ const [nameError, setNameError] = useState<string | undefined>(undefined)+ const [avatarDraft, setAvatarDraft] = useState<AvatarDraft>(() =>+ bot ? draftFromBot(bot) : { kind: "procedural", image: serializeAvatarConfig(DEFAULT_AVATAR) },+ )+ const update = useUpdateBot()+ const uploadBotAvatar = useUploadBotAvatar()++ // Re-sync the form fields from `bot` each time a *new* edit target opens+ // (keyed by id, not by every `bot` reference change — the parent's+ // `editingBot` never resets to null, so this only re-fires when the user+ // actually picks a different bot to edit).+ const syncedForRef = useRef<string | null>(null)+ useEffect(() => {+ if (!open || !bot) return+ if (syncedForRef.current === bot.id) return+ syncedForRef.current = bot.id+ setName(bot.name)+ setDescription(bot.description ?? "")+ setAvatarDraft(draftFromBot(bot))+ setNameError(undefined)+ }, [open, bot])++ function updateName(value: string) {+ setName(value)+ if (nameError && value.trim()) setNameError(undefined)+ }++ function shuffleName() {+ setName(uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "capital" }))+ setNameError(undefined)+ }++ async function submit() {+ if (!bot) return+ if (!name.trim()) {+ setNameError("Name is required")+ return+ }+ try {+ // Sequence matters — only attempt the avatar upload AFTER the+ // name/description update resolves, inside the same try block, so a+ // failed field update never triggers an upload.+ await update.mutateAsync({+ id: bot.id,+ name: name.trim(),+ description: description.trim() || undefined,+ image: avatarDraft.kind === "procedural" ? avatarDraft.image : undefined,+ })+ let avatarFailed = false+ if (avatarDraft.kind === "photo" && avatarDraft.file) {+ try {+ await uploadBotAvatar.mutateAsync({ botId: bot.id, file: avatarDraft.file })+ } catch {+ avatarFailed = true+ toast.error("Bot updated, but the avatar photo failed to upload")+ }+ }+ if (!avatarFailed) toast.success("Bot updated")+ onOpenChange(false)+ } catch (err) {+ toast.error(err instanceof Error ? err.message : "Update failed")+ }+ }++ return (+ <Sheet open={open} onOpenChange={onOpenChange} disablePointerDismissal>+ <SheetContent+ side="right"+ showOverlay={false}+ className="data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border data-[side=right]:sm:overflow-hidden"+ >+ <SheetHeader>+ <SheetTitle>Edit {bot?.name ?? "bot"}</SheetTitle>+ <SheetDescription>+ Name and description edits take effect on the bot's next wake trigger.+ </SheetDescription>+ </SheetHeader>++ <SheetBody>+ <BotFormFields+ avatarDraft={avatarDraft}+ onAvatarChange={setAvatarDraft}+ name={name}+ setName={updateName}+ onShuffle={shuffleName}+ description={description}+ setDescription={setDescription}+ nameError={nameError}+ />+ </SheetBody>++ <SheetFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button onClick={submit} disabled={update.isPending || !bot}>+ {update.isPending ? "Saving…" : "Save"}+ </Button>+ </SheetFooter>+ </SheetContent>+ </Sheet>+ )+}diff --git a/src/web/src/components/community/channel-header.tsx b/src/web/src/components/community/channel-header.tsxindex 5e9106a4e..e4ebf85c4 100644--- a/src/web/src/components/community/channel-header.tsx+++ b/src/web/src/components/community/channel-header.tsx@@ -11,6 +11,7 @@ import { Skeleton } from "@/components/ui/skeleton"import { ChannelIcon } from "./channel-icon"import { SlugHint } from "./slug-hint"import { previewSlug } from "@/lib/community/slug-preview"+import { serverGradient } from "./server-gradient"import type { RightPanel } from "./_types"// Skeleton header for the loading frame between route change and channel@@ -22,7 +23,7 @@ export function ChannelHeaderSkeleton({ onBack }: { onBack?: () => void }) {{onBack && (<Button variant="ghost" size="icon-sm" onClick={onBack} className="text-muted-foreground hover:text-foreground" aria-label="Back"><ChevronLeft className="size-5" /></Button>)}- <Skeleton className="ml-1 size-4 rounded" />+ <Skeleton className="ml-1 size-6 rounded-md" /><Skeleton className="h-4 w-32 rounded" /><div className="ml-auto flex items-center text-muted-foreground"><Skeleton className="size-7 rounded-md" />@@ -48,7 +49,7 @@ export function ChannelHeader({onBack?: () => voidforum?: booleanbreadcrumb?: { label: string; onRename?: (name: string) => void; onNavigateBack?: () => void }- server?: { name: string; icon: string | null }+ server?: { id: string; name: string; icon: string | null }tools?: { threads?: boolean; pinned?: boolean; members?: boolean }}) {@@ -68,7 +69,7 @@ export function ChannelHeader({{onBack && (<Button variant="ghost" size="icon-sm" onClick={onBack} className="text-muted-foreground hover:text-foreground" aria-label="Back"><ChevronLeft className="size-5" /></Button>)}- {server && <ServerCrumb name={server.name} icon={server.icon} />}+ {server && <ServerCrumb id={server.id} name={server.name} icon={server.icon} className="ml-1" />}{breadcrumb ? (<><button onClick={breadcrumb.onNavigateBack} className={`flex items-center gap-1 text-muted-foreground hover:text-foreground transition-colors ${server ? "" : "ml-1"}`}>@@ -83,7 +84,9 @@ export function ChannelHeader({</>) : (<>- {forum ? <ListChevronsUpDown className={`size-4 shrink-0 text-muted-foreground ${server ? "" : "ml-1"}`} /> : <ChannelIcon className={`text-base text-muted-foreground ${server ? "" : "ml-1"}`} />}+ <div className={`grid size-6 shrink-0 place-items-center rounded-md bg-muted text-muted-foreground ${server ? "" : "ml-1"}`}>+ {forum ? <ListChevronsUpDown className="size-4" /> : <ChannelIcon className="text-base" />}+ </div><span className="truncate text-base font-semibold">{channel}</span></>)}@@ -147,12 +150,23 @@ function ChannelOverflowMenu({)}-// Leading breadcrumb segment for mobile — the server avatar. The channel segment-// that follows leads with its own "/" (or forum icon), which serves as the separator.-// Purely contextual (the rail is hidden at mobile widths).-function ServerCrumb({ name, icon }: { name: string; icon: string | null }) {+// Server identity chip — icon (or initial-letter fallback) in a rounded+// square. Originally just the mobile breadcrumb's leading segment (the+// channel segment that follows leads with its own "/" or forum icon, which+// serves as the separator), now also reused by `ChannelSidebar`'s header at+// the larger `size={7}`. Tailwind only picks up complete literal class names+// at build time, so `size` can't be interpolated — it's an explicit ternary.+export function ServerCrumb({ id, name, icon, size = 5, className = "" }: { id: string; name: string; icon: string | null; size?: 5 | 7; className?: string }) {return (- <span className="ml-1 grid size-5 shrink-0 place-items-center overflow-hidden rounded-md bg-secondary text-[0.625rem] font-semibold text-foreground" aria-label={name} title={name}>+ <span+ // No icon → the same deterministic gradient fallback used by the rail+ // (`sortable-server.tsx`) and folder rows, so a server reads as "the+ // same server" everywhere it shows up, not a flat generic tile here.+ style={icon ? undefined : { background: serverGradient(id) }}+ className={`grid shrink-0 place-items-center overflow-hidden rounded-md font-semibold ${icon ? "bg-secondary text-foreground" : "text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)]"} ${size === 7 ? "size-7 text-xs" : "size-5 text-[0.625rem]"} ${className}`}+ aria-label={name}+ title={name}+ >{icon ? <img src={icon} alt="" className="size-full object-cover" /> : name.charAt(0).toUpperCase()}</span>)diff --git a/src/web/src/components/community/channel-sidebar.tsx b/src/web/src/components/community/channel-sidebar.tsxindex 408154c3d..9cfcaa0c3 100644--- a/src/web/src/components/community/channel-sidebar.tsx+++ b/src/web/src/components/community/channel-sidebar.tsx@@ -17,6 +17,7 @@ import { CategorySettingsDialog } from "./category-settings-dialog"import { catId, catOf, isCat, type ChannelTree } from "./use-channel-tree"import { InviteDialog } from "./invite-dialog"import { ChannelMembersDialog } from "./channel-members-dialog"+import { ServerCrumb } from "./channel-header"import type { Channel, SettingsSection } from "./_types"import type { ChannelType } from "@alook/shared"@@ -34,7 +35,7 @@ type Dialog =// right-click) creates; channels right-click to edit/delete. A private category only// lets admins create channels — non-admins are blocked via onBlockedCreate.export const ChannelSidebar = memo(function ChannelSidebar({- tree, serverName, activeChannel, setActiveChannel, noHeader, onOpenSettings,+ tree, serverName, serverIcon, activeChannel, setActiveChannel, noHeader, onOpenSettings,isAdmin = true, currentUserId, onBlockedCreate, mutedChannels, loading,onCreateChannel, onCreateCategory, onDeleteChannel, onDeleteCategory,onUpdateCategory, onRenameChannel, onReorderCategories, onReorderChannels,@@ -43,6 +44,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({}: {tree: ChannelTreeserverName: string+ serverIcon?: string | nullactiveChannel: stringsetActiveChannel: (id: string) => voidnoHeader?: boolean@@ -159,8 +161,9 @@ export const ChannelSidebar = memo(function ChannelSidebar({<header className="flex h-12 items-center gap-1 border-b border-border/40 px-2">{serverName && onOpenSettings ? (<DropdownMenu>- <DropdownMenuTrigger className="flex min-w-0 items-center gap-2 rounded-md px-2 py-1 hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">- <span className="truncate text-lg font-semibold">{serverName}</span>+ <DropdownMenuTrigger className="flex min-w-0 max-w-full items-center gap-2 rounded-md px-2 py-1 hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">+ <ServerCrumb id={serverId ?? ""} name={serverName} icon={serverIcon ?? null} size={7} />+ <span className="min-w-0 truncate text-lg font-semibold">{serverName}</span><ChevronDown className="size-4 shrink-0 text-muted-foreground" /></DropdownMenuTrigger><DropdownMenuContent align="start" className="w-48">@@ -172,7 +175,10 @@ export const ChannelSidebar = memo(function ChannelSidebar({</DropdownMenuContent></DropdownMenu>) : (- <span className="min-w-0 flex-1 truncate px-2 text-lg font-semibold">{serverName || "\u00a0"}</span>+ <span className="flex min-w-0 max-w-full items-center gap-2 px-2">+ {serverName && <ServerCrumb id={serverId ?? ""} name={serverName} icon={serverIcon ?? null} size={7} />}+ <span className="min-w-0 truncate text-lg font-semibold">{serverName || "\u00a0"}</span>+ </span>)}{serverId && onInvitePopoverOpenChange && (<>diff --git a/src/web/src/components/community/community-inbox-popover.tsx b/src/web/src/components/community/community-inbox-popover.tsxindex 35ed0a3a2..a83a49db2 100644--- a/src/web/src/components/community/community-inbox-popover.tsx+++ b/src/web/src/components/community/community-inbox-popover.tsx@@ -29,7 +29,7 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenDm }: {{!loading && nothingUnread && <EmptyState icon={Inbox} label="Caught up" />}{dms.length > 0 && (<div className="mb-3">- <div className="px-2 pb-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Direct Messages</div>+ <div className="px-2 pb-1 text-xs font-semibold text-muted-foreground">Direct Messages</div>{dms.map((d) => (<buttonkey={d.dmConversationId}@@ -45,7 +45,7 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenDm }: {)}{servers.map((s) => (<div key={s.serverId} className="mb-3">- <div className="px-2 pb-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground">{s.serverName}</div>+ <div className="px-2 pb-1 text-xs font-semibold text-muted-foreground">{s.serverName}</div>{s.channels.map((c) => (<div key={c.channelId}><buttondiff --git a/src/web/src/components/community/community-invite-card.tsx b/src/web/src/components/community/community-invite-card.tsxindex 3ec5ea512..5c782464d 100644--- a/src/web/src/components/community/community-invite-card.tsx+++ b/src/web/src/components/community/community-invite-card.tsx@@ -93,7 +93,7 @@ export function CommunityInviteCard({ token }: { token: string }) {</div>)}<div className="min-w-0 flex-1">- <div className="text-xs uppercase tracking-wide text-muted-foreground">+ <div className="text-xs font-medium text-muted-foreground">You've been invited to join</div><div className="truncate font-medium">{data.serverName}</div>diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsxindex b15aa33ee..fe34370ef 100644--- a/src/web/src/components/community/composer.tsx+++ b/src/web/src/components/community/composer.tsx@@ -2,7 +2,7 @@import { useEffect, useRef, useState } from "react"import { createPortal } from "react-dom"-import { AtSign, FileIcon, ImageIcon, MessagesSquare, PlusCircle, Smile, Upload, Users, X } from "lucide-react"+import { AtSign, FileIcon, ImageIcon, PlusCircle, Smile, Upload, Users, X } from "lucide-react"import { useEditor, EditorContent } from "@tiptap/react"import StarterKit from "@tiptap/starter-kit"import Placeholder from "@tiptap/extension-placeholder"@@ -48,7 +48,7 @@ export function pendingFilesToSendAttachments(pendingFiles: PendingFile[]): Send// Enter sends, Shift+Enter adds a newline; while the mention popover is open// Enter/Tab/Arrow keys drive selection instead. @everyone / @here are virtual// candidates in channel + thread contexts (hidden in DM).-export function Composer({ channel, context, members, onSearchMembers, channelRefCandidates = [], onSend, onCreateThread, onTyping, replyingTo, onCancelReply, autoFocus = false }: {+export function Composer({ channel, context, members, onSearchMembers, channelRefCandidates = [], onSend, onTyping, replyingTo, onCancelReply, autoFocus = false }: {channel: stringcontext: MentionContextmembers: Member[]@@ -63,7 +63,6 @@ export function Composer({ channel, context, members, onSearchMembers, channelRe// the popup just shows nothing on `/`.channelRefCandidates?: ChannelRefCandidate[]onSend?: (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => void- onCreateThread?: () => voidonTyping?: () => void// when set, shows a "Replying to X" bar above the inputreplyingTo?: string@@ -290,7 +289,7 @@ export function Composer({ channel, context, members, onSearchMembers, channelRe{pendingFiles.map((pf, i) => {const isImage = pf.file.type.startsWith("image/")return (- <div key={i} className="group relative flex items-center gap-2 rounded border border-border bg-background px-3 py-2 text-xs">+ <div key={i} className="group relative flex items-center gap-2 rounded-md border border-border bg-background px-3 py-2 text-xs">{isImage ? <ImageIcon className="size-3.5 text-muted-foreground" /> : <FileIcon className="size-3.5 text-muted-foreground" />}<span className="max-w-30 truncate text-foreground">{pf.file.name}</span><button@@ -306,7 +305,7 @@ export function Composer({ channel, context, members, onSearchMembers, channelRe</div>)}- <div className={`relative bg-muted shadow-(--e1) ring-1 ring-border/40 ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}>+ <div className={`relative bg-muted shadow-(--e1) ring-1 ring-border/40 transition-shadow focus-within:ring-2 focus-within:ring-ring/60 ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}>{dragging && (<divclassName={`pointer-events-none absolute inset-0 z-10 grid place-items-center border-2 border-dashed border-ring bg-background/80 ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}@@ -334,18 +333,17 @@ export function Composer({ channel, context, members, onSearchMembers, channelRe{/* Attach button — fixed bottom-left */}<DropdownMenu onOpenChange={(open) => { if (!open) editor?.commands.focus() }}><DropdownMenuTrigger- render={<button className="absolute left-2 bottom-2 grid size-8 place-items-center rounded-full text-muted-foreground hover:text-foreground aria-expanded:text-foreground" aria-label="Add" />}+ render={<button className="absolute left-2 bottom-2 grid size-8 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground" aria-label="Add" />}><PlusCircle className="size-5" /></DropdownMenuTrigger><DropdownMenuContent side="top" align="start" className="w-44"><DropdownMenuItem onClick={() => { fileInputRef.current?.click(); editor?.commands.focus() }}><Upload className="size-4" /> Upload a File</DropdownMenuItem>- {context === "channel" && <DropdownMenuItem onClick={onCreateThread}><MessagesSquare className="size-4" /> Create Thread</DropdownMenuItem>}</DropdownMenuContent></DropdownMenu>{/* Emoji button — fixed bottom-right */}<EmojiPickerPopover side="top" align="end" onPick={(e) => editor?.chain().focus().insertContent(e).run()}>- <button className="absolute right-2 bottom-2 grid size-8 place-items-center rounded-full text-muted-foreground hover:text-foreground aria-expanded:text-foreground" aria-label="Emoji picker">+ <button className="absolute right-2 bottom-2 grid size-8 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground" aria-label="Emoji picker"><Smile className="size-5" /></button></EmojiPickerPopover>@@ -537,7 +535,7 @@ function MentionRow({ item, selected, showMembersHeader, onSelect }: {return (<>{showMembersHeader && (- <div className="-mx-1 mt-1 border-t border-border/60 px-2 pt-2 pb-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Members</div>+ <div className="-mx-1 mt-1 border-t border-border/60 px-2 pt-2 pb-1 text-xs font-semibold text-muted-foreground">Members</div>)}<buttontype="button"diff --git a/src/web/src/components/community/dividers.tsx b/src/web/src/components/community/dividers.tsxindex cf92e93c7..9c9cf2a51 100644--- a/src/web/src/components/community/dividers.tsx+++ b/src/web/src/components/community/dividers.tsx@@ -21,7 +21,7 @@ export function NewDivider() {<div data-new-divider className="relative my-1 flex items-center"><Separator className="flex-1 bg-destructive/60" /><span- className="pointer-events-none absolute right-0 top-1/2 -translate-y-1/2 rounded-sm bg-destructive px-1.5 py-0.5 text-xs font-semibold uppercase tracking-wide text-white"+ className="pointer-events-none absolute right-0 top-1/2 -translate-y-1/2 rounded-sm bg-destructive px-1.5 py-0.5 text-xs font-semibold text-white"style={{ WebkitTextStroke: "0.4px currentColor" }}>Newdiff --git a/src/web/src/components/community/dm-sidebar.tsx b/src/web/src/components/community/dm-sidebar.tsxindex d4e74b57d..ac4bfd778 100644--- a/src/web/src/components/community/dm-sidebar.tsx+++ b/src/web/src/components/community/dm-sidebar.tsx@@ -59,7 +59,7 @@ export const DmSidebar = memo(function DmSidebar({</button>)}<div className="my-2 h-px bg-border" />- <div className="mb-2 px-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">+ <div className="mb-2 px-2 text-xs font-semibold text-muted-foreground">Direct Messages</div>{dms.length === 0 && (diff --git a/src/web/src/components/community/edit-profile-dialog.tsx b/src/web/src/components/community/edit-profile-dialog.tsxindex 2e82228e3..4535d37ae 100644--- a/src/web/src/components/community/edit-profile-dialog.tsx+++ b/src/web/src/components/community/edit-profile-dialog.tsx@@ -28,7 +28,7 @@ function AppearanceSettings() {const active = mounted ? theme ?? "system" : undefinedreturn (- <div className="mx-auto max-w-xl space-y-4">+ <div className="mx-auto max-w-md space-y-4"><Field label="Theme"><div className="grid grid-cols-3 gap-2">{THEME_OPTIONS.map(({ value, label, icon: Icon }) => {@@ -88,7 +88,7 @@ function AdvancedSettings({ userId }: { userId: string | null }) {}}}/>- <div className="mx-auto max-w-xl space-y-6">+ <div className="mx-auto max-w-md space-y-6"><div><div className="text-sm font-medium">Clear local cache</div><p className="mt-1 text-xs text-muted-foreground">@@ -190,13 +190,13 @@ export function UserSettings({ onClose, userId, userName, aboutMe, avatar, statu<h1 className="flex-1 text-lg font-semibold">{tab === "appearance" ? "Appearance" : tab === "advanced" ? "Advanced" : "My Profile"}</h1>- <button onClick={onClose} className="flex flex-col items-center text-muted-foreground hover:text-foreground" aria-label="Close settings">- <span className="grid size-8 place-items-center rounded-full border border-current"><X className="size-4" /></span>- </button>+ <Button variant="ghost" size="icon-sm" onClick={onClose} aria-label="Close settings">+ <X className="size-4" />+ </Button></header><div className="flex-1 overflow-y-auto thin-scrollbar p-4"><TabsContent value="profile">- <div className="mx-auto max-w-xl space-y-4">+ <div className="mx-auto max-w-md space-y-4"><div className="flex items-center gap-4"><Avatar label={avatar} size={80} /><div>diff --git a/src/web/src/components/community/field.tsx b/src/web/src/components/community/field.tsxindex b4293cca3..36281c9ae 100644--- a/src/web/src/components/community/field.tsx+++ b/src/web/src/components/community/field.tsx@@ -4,7 +4,7 @@ import type React from "react"export function Field({ label, children }: { label: React.ReactNode; children: React.ReactNode }) {return (<label className="block">- <div className="mb-2 text-xs font-semibold text-muted-foreground">{label}</div>+ <div className="mb-1.5 text-sm font-medium text-foreground">{label}</div>{children}</label>)diff --git a/src/web/src/components/community/friends-page.tsx b/src/web/src/components/community/friends-page.tsxindex 70a6afe20..70da03493 100644--- a/src/web/src/components/community/friends-page.tsx+++ b/src/web/src/components/community/friends-page.tsx@@ -23,7 +23,7 @@ function FriendSection({ title, count, emptyLabel, children }: {}) {return (<div className="flex min-h-0 flex-col">- <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">{title}</div>+ <div className="mb-2 text-xs font-semibold text-muted-foreground">{title}</div>{count === 0 ? <EmptyState icon={Users} label={emptyLabel} /> : <div className="flex flex-col gap-1">{children}</div>}</div>)@@ -153,7 +153,7 @@ export function FriendsPage({{loading && friends.length === 0 ? (<div className="flex min-h-0 flex-col">- <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">All friends — …</div>+ <div className="mb-2 text-xs font-semibold text-muted-foreground">All friends — …</div><FriendRowsSkeleton /></div>) : (@@ -168,12 +168,12 @@ export function FriendsPage({{loading && blocked.length === 0 ? (<div className="mt-8 flex min-h-0 flex-col">- <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Blocked — …</div>+ <div className="mb-2 text-xs font-semibold text-muted-foreground">Blocked — …</div><FriendRowsSkeleton withActions /></div>) : blocked.length > 0 ? (<div className="mt-8">- <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Blocked — {blocked.length}</div>+ <div className="mb-2 text-xs font-semibold text-muted-foreground">Blocked — {blocked.length}</div><div className="flex flex-col gap-1">{blocked.map((b) => (<div key={b.id} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent">@@ -189,7 +189,7 @@ export function FriendsPage({<TabsContent value="new"><div className="mb-4">- <div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Add a friend</div>+ <div className="text-xs font-semibold text-muted-foreground">Add a friend</div><div className="relative mt-2"><div className="relative flex items-center gap-2"><div className="relative flex-1">@@ -237,12 +237,12 @@ export function FriendsPage({{loading && pending.length === 0 ? (<div className="flex min-h-0 flex-col">- <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Pending — …</div>+ <div className="mb-2 text-xs font-semibold text-muted-foreground">Pending — …</div><FriendRowsSkeleton withActions /></div>) : pending.length > 0 ? (<div>- <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Pending — {pending.length}</div>+ <div className="mb-2 text-xs font-semibold text-muted-foreground">Pending — {pending.length}</div><div className="flex flex-col gap-1">{pending.map((p) => (<div key={p.id} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent">diff --git a/src/web/src/components/community/machines/pair-machine-sheet.tsx b/src/web/src/components/community/machines/pair-machine-sheet.tsxindex f3a44cc13..f79364126 100644--- a/src/web/src/components/community/machines/pair-machine-sheet.tsx+++ b/src/web/src/components/community/machines/pair-machine-sheet.tsx@@ -109,7 +109,10 @@ export function PairMachineSheet({return (<Sheet open={open} onOpenChange={onOpenChange}>- <SheetContent side="right">+ <SheetContent+ side="right"+ className="data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border"+ ><SheetHeader><SheetTitle>{isReconnect ? `Reconnect ${mode.hostname || "machine"}` : "Connect a machine"}@@ -156,12 +159,12 @@ function Step1({and hit enter. Node 20+ is the only prerequisite.</p>{generating ? (- <div className="flex items-center gap-2 rounded-md border bg-muted/30 p-3 text-sm text-muted-foreground">+ <div className="flex items-center gap-2 rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground"><Loader2 className="size-4 animate-spin" />Preparing your command…</div>) : (- <div className="flex items-start gap-2 rounded-md border bg-muted/30 p-3 font-mono text-xs">+ <div className="flex items-start gap-2 rounded-lg border bg-muted/30 p-3 font-mono text-xs"><code className="flex-1 break-all">{command}</code><buttononClick={onCopy}diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsxindex fa91a7aff..c6d65f22e 100644--- a/src/web/src/components/community/message.tsx+++ b/src/web/src/components/community/message.tsx@@ -153,15 +153,15 @@ export function Message({<buttonkey={i}onClick={() => onPreviewImage?.(a.url)}- className="block w-fit max-w-[320px] overflow-hidden rounded-md border border-border transition-colors hover:border-primary/40"+ className="block w-fit max-w-[320px] overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40">- <img src={a.url} alt={a.name} className="max-h-50 max-w-[320px] rounded-md object-contain" style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }} />+ <img src={a.url} alt={a.name} className="max-h-50 max-w-[320px] rounded-lg object-contain" style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }} /></button>) : (<buttonkey={i}onClick={() => onDownloadFile?.(a.url)}- className="flex w-full max-w-[320px] items-center gap-3 rounded-md border border-border bg-card p-2 text-left transition-colors hover:bg-accent"+ className="flex w-full max-w-[320px] items-center gap-3 rounded-lg border border-border bg-card p-2 text-left transition-colors hover:bg-accent"><FileText className="size-7 shrink-0 text-muted-foreground" /><div className="min-w-0 flex-1">@@ -180,9 +180,14 @@ export function Message({{m.embeds.map((embed, ei) => (<articlekey={ei}- className="flex max-w-108 overflow-hidden rounded-md border-l-4 bg-card p-3"- style={{ borderLeftColor: embed.color ?? "var(--border)" }}+ className="flex max-w-108 overflow-hidden rounded-lg border border-border bg-card p-3">+ {embed.color && (+ <span+ className="mt-1.5 mr-3 size-2 shrink-0 self-start rounded-full"+ style={{ backgroundColor: embed.color }}+ />+ )}<div className="min-w-0 flex-1">{embed.author && (<div className="mb-2 flex items-center gap-2">@@ -245,7 +250,7 @@ export function Message({onClick={() => onToggleReaction?.(r.emoji)}title={r.userIds?.length ? r.userIds.map((id) => resolveUserName?.(id) ?? id).join(", ") : undefined}className={[- "flex h-6 items-center gap-1 rounded-md px-2 text-sm",+ "flex h-6 items-center gap-1 rounded-full px-2 text-sm",r.me ? "border border-primary/50 bg-accent" : "bg-secondary",].join(" ")}>@@ -254,7 +259,7 @@ export function Message({</button>))}<EmojiPickerPopover side="top" align="start" onPick={(e) => onReact?.(e)}>- <button className="grid h-6 w-7 place-items-center rounded-md bg-secondary text-muted-foreground hover:text-foreground" aria-label="Add reaction">+ <button className="grid h-6 w-7 place-items-center rounded-full bg-secondary text-muted-foreground hover:text-foreground" aria-label="Add reaction"><SmilePlus className="size-4" /></button></EmojiPickerPopover>diff --git a/src/web/src/components/community/new-thread-panel.tsx b/src/web/src/components/community/new-thread-panel.tsxdeleted file mode 100644index 427c9c7d4..000000000--- a/src/web/src/components/community/new-thread-panel.tsx+++ /dev/null@@ -1,72 +0,0 @@-"use client"--import { useState } from "react"-import { MessagesSquare, Smile } from "lucide-react"-import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"-import { Button } from "@/components/ui/button"-import { Input } from "@/components/ui/input"-import { EmojiPickerPopover } from "./emoji-picker"--// "New Thread" creation dialog — Thread Name + first message to start the thread.-export function NewThreadDialog({ channel, open, onClose, onCreate }: {- channel: string- open: boolean- onClose: () => void- onCreate: (name: string, firstMessage: string) => void-}) {- const [name, setName] = useState("")- const [message, setMessage] = useState("")-- const submit = () => {- const trimmed = name.trim() || "New Thread"- onCreate(trimmed, message.trim())- setName("")- setMessage("")- }-- return (- <Dialog open={open} onOpenChange={(o) => { if (!o) onClose() }}>- <DialogContent className="w-105 max-w-[calc(100vw-2rem)] p-0">- <DialogHeader className="border-b border-border px-4 py-4">- <DialogTitle className="flex items-center gap-2">- <MessagesSquare className="size-5 text-muted-foreground" />- New Thread- </DialogTitle>- </DialogHeader>- <div className="space-y-4 px-4 pb-5">- <label className="block">- <div className="mb-2 text-xs font-semibold text-muted-foreground">Thread Name</div>- <Input- value={name}- onChange={(e) => setName(e.target.value)}- onKeyDown={(e) => { if (e.key === "Enter" && name.trim()) submit() }}- placeholder="New Thread"- autoFocus- />- </label>- <label className="block">- <div className="mb-2 text-xs font-semibold text-muted-foreground">First Message</div>- <div className="flex min-h-14 items-center gap-3 rounded-lg bg-secondary px-4 py-3">- <input- value={message}- onChange={(e) => setMessage(e.target.value)}- onKeyDown={(e) => { if (e.key === "Enter") submit() }}- placeholder={`Message /${channel}`}- className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"- />- <EmojiPickerPopover side="top" align="end" onPick={(e) => setMessage((m) => m + e)}>- <button className="shrink-0 text-muted-foreground hover:text-foreground aria-expanded:text-foreground" aria-label="Emoji picker">- <Smile className="size-5" />- </button>- </EmojiPickerPopover>- </div>- </label>- </div>- <DialogFooter className="mx-0 mb-0 flex-row items-center justify-end gap-2 rounded-b-xl border-t border-border bg-card px-4 py-3">- <Button variant="ghost" size="sm" onClick={onClose}>Cancel</Button>- <Button size="sm" onClick={submit} disabled={!name.trim()}>Create Thread</Button>- </DialogFooter>- </DialogContent>- </Dialog>- )-}diff --git a/src/web/src/components/community/server-settings.tsx b/src/web/src/components/community/server-settings.tsxindex acaf3ecd7..a1645aba6 100644--- a/src/web/src/components/community/server-settings.tsx+++ b/src/web/src/components/community/server-settings.tsx@@ -9,7 +9,6 @@ import { Button } from "@/components/ui/button"import { formatMessageTime, formatRelativeTime } from "./format-time"import { Input } from "@/components/ui/input"import { Textarea } from "@/components/ui/textarea"-import { Separator } from "@/components/ui/separator"import { Badge, badgeVariants } from "@/components/ui/badge"import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"@@ -96,20 +95,18 @@ export function ServerSettings({</TabsTrigger>))}</TabsList>- <Separator className="my-1" />- <Button variant="destructive" size="sm" className="justify-start" onClick={() => setConfirmDelete(true)}><Trash2 className="size-4" /> Delete Server</Button></nav>{/* settings body */}<div className="flex min-w-0 flex-1 flex-col bg-background"><header className="flex h-12 shrink-0 items-center border-b border-border px-4"><h1 className="flex-1 text-lg font-semibold capitalize">{section === "audit" ? "Audit Log" : section}</h1>- <button onClick={onClose} className="flex flex-col items-center text-muted-foreground hover:text-foreground" aria-label="Close settings">- <span className="grid size-8 place-items-center rounded-full border border-current"><X className="size-4" /></span>- </button>+ <Button variant="ghost" size="icon-sm" onClick={onClose} aria-label="Close settings">+ <X className="size-4" />+ </Button></header><div className="flex-1 overflow-y-auto thin-scrollbar p-4">- <TabsContent value="overview"><SettingsOverview serverName={serverName} serverDescription={serverDescription} serverIcon={serverIcon} onUploadIcon={onUploadIcon} onUpdateServer={onUpdateServer} /></TabsContent>+ <TabsContent value="overview"><SettingsOverview serverName={serverName} serverDescription={serverDescription} serverIcon={serverIcon} onUploadIcon={onUploadIcon} onUpdateServer={onUpdateServer} onRequestDelete={() => setConfirmDelete(true)} /></TabsContent><TabsContent value="members"><SettingsMembers members={members} loading={membersLoading} loadingMore={membersLoadingMore} hasMore={membersHasMore} total={membersTotal} onLoadMore={onLoadMoreMembers} onSearch={onSearchMembers} onOpenProfile={onOpenProfile} onKickMember={onKickMember} onSetRole={onSetRole} /></TabsContent><TabsContent value="invites"><SettingsInvites invites={invites} loading={invitesLoading} onRevokeInvite={onRevokeInvite} onCopyInvite={onCopyInvite} /></TabsContent><TabsContent value="notifications"><SettingsNotifications level={notifLevel ?? "Only @mentions"} onSetLevel={onSetNotifLevel} /></TabsContent>@@ -121,7 +118,7 @@ export function ServerSettings({)}-function SettingsOverview({ serverName, serverDescription, serverIcon, onUploadIcon, onUpdateServer }: { serverName: string; serverDescription?: string; serverIcon?: string | null; onUploadIcon?: () => void; onUpdateServer?: (name: string, desc: string) => void }) {+function SettingsOverview({ serverName, serverDescription, serverIcon, onUploadIcon, onUpdateServer, onRequestDelete }: { serverName: string; serverDescription?: string; serverIcon?: string | null; onUploadIcon?: () => void; onUpdateServer?: (name: string, desc: string) => void; onRequestDelete?: () => void }) {// The draft is mount-only on purpose. The cross-server "stale draft" case// is already handled in layout.tsx — switching servers closes the dialog// (`setServerSettingsOpen(false)` in the serverId effect), which unmounts@@ -137,24 +134,37 @@ function SettingsOverview({ serverName, serverDescription, serverIcon, onUploadIonUpdateServer?.(name, desc)}return (- <div className="mx-auto max-w-xl space-y-4">- <div className="flex items-center gap-4">- {serverIcon ? (- <img src={serverIcon} alt="Server icon" className="size-20 rounded-2xl object-cover" />- ) : (- <div className="grid size-20 place-items-center rounded-2xl bg-primary text-2xl font-semibold text-primary-foreground">{name.charAt(0)}</div>- )}- <div>- <div className="text-sm font-medium">Server icon</div>- <div className="text-xs text-muted-foreground">PNG, JPG, or WEBP. You'll be able to crop and zoom before saving.</div>- <Button variant="secondary" size="sm" className="mt-2" onClick={onUploadIcon}>Upload image</Button>+ <div className="mx-auto max-w-md space-y-10">+ <section className="space-y-4">+ <h2 className="text-sm font-medium">Server</h2>+ <div className="flex items-center gap-4">+ {serverIcon ? (+ <img src={serverIcon} alt="Server icon" className="size-20 rounded-2xl object-cover" />+ ) : (+ <div className="grid size-20 place-items-center rounded-2xl bg-primary text-2xl font-semibold text-primary-foreground">{name.charAt(0)}</div>+ )}+ <div>+ <div className="text-sm font-medium">Server icon</div>+ <div className="text-xs text-muted-foreground">PNG, JPG, or WEBP. You'll be able to crop and zoom before saving.</div>+ <Button variant="secondary" size="sm" className="mt-2" onClick={onUploadIcon}>Upload image</Button>+ </div></div>- </div>- <Field label="Server name">- <Input value={name} onChange={(e) => setName(e.target.value)} onBlur={save} />- <SlugHint {...namePreview} />- </Field>- <Field label="Description"><Textarea className="h-20 resize-none" value={desc} onChange={(e) => setDesc(e.target.value)} onBlur={save} /></Field>+ <Field label="Server name">+ <Input value={name} onChange={(e) => setName(e.target.value)} onBlur={save} />+ <SlugHint {...namePreview} />+ </Field>+ <Field label="Description"><Textarea className="h-20 resize-none" value={desc} onChange={(e) => setDesc(e.target.value)} onBlur={save} /></Field>+ </section>++ <section className="space-y-4">+ <h2 className="text-sm font-medium text-destructive">Danger Zone</h2>+ <div className="space-y-3 rounded-lg border border-destructive/30 p-4">+ <p className="text-sm text-muted-foreground">+ Deleting this server is permanent and cannot be undone. All channels, messages, and members will be permanently removed.+ </p>+ <Button variant="destructive" size="sm" onClick={onRequestDelete}><Trash2 className="size-4" /> Delete Server</Button>+ </div>+ </section></div>)}@@ -253,7 +263,7 @@ function SettingsMembers({ members, loading, loadingMore, hasMore, total, onLoadpaddingBottom: 8,}}>- <div className="flex items-center gap-3 rounded-md border border-border bg-card px-4 py-2">+ <div className="flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-2"><button onClick={(e) => onOpenProfile?.(m.name, e, undefined, m.userId)} className="shrink-0"><Avatar label={m.avatar} size={32} presence={m.status} ringColor="var(--card)" /></button>@@ -309,7 +319,7 @@ function SettingsInvites({ invites, loading, onRevokeInvite, onCopyInvite }: {<p className="text-sm text-muted-foreground">No active invites — use the invite icon in the sidebar header to share this server.</p>)}{invites.map((iv) => (- <div key={iv.code} className="flex items-center gap-3 rounded-md border border-border bg-card px-4 py-3">+ <div key={iv.code} className="flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-3"><Link2 className="size-5 shrink-0 text-muted-foreground" /><div className="min-w-0 flex-1"><div className="truncate font-mono text-sm">{iv.code}</div>@@ -344,7 +354,7 @@ function SettingsNotifications({ level, onSetLevel }: { level: string; onSetLeve<buttonkey={l.value}onClick={() => onSetLevel?.(l.value)}- className="flex w-full items-center gap-3 rounded-md border border-border bg-card px-4 py-3 text-left hover:bg-accent"+ className="flex w-full items-center gap-3 rounded-lg border border-border bg-card px-4 py-3 text-left hover:bg-accent"><span className={`grid size-4 shrink-0 place-items-center rounded-full border ${level === l.value ? "border-primary" : "border-muted-foreground"}`}>{level === l.value && <span className="size-2 rounded-full bg-primary" />}@@ -388,7 +398,7 @@ function SettingsMembersSkeleton() {<div className="mx-auto max-w-xl space-y-2"><Skeleton className="mb-3 h-4 w-24 rounded" />{Array.from({ length: 5 }).map((_, i) => (- <div key={i} className="flex items-center gap-3 rounded-md border border-border bg-card px-4 py-2">+ <div key={i} className="flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-2"><Skeleton className="size-8 shrink-0 rounded-full" /><div className="flex min-w-0 flex-1 flex-col gap-2"><Skeleton className="h-4 w-2/5 rounded" />@@ -406,7 +416,7 @@ function SettingsInvitesSkeleton() {return (<div className="mx-auto max-w-xl space-y-2">{Array.from({ length: 3 }).map((_, i) => (- <div key={i} className="flex items-center gap-3 rounded-md border border-border bg-card px-4 py-3">+ <div key={i} className="flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-3"><Skeleton className="size-5 shrink-0 rounded" /><div className="flex min-w-0 flex-1 flex-col gap-2"><Skeleton className="h-4 w-1/2 rounded" />diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsxindex f147807dc..c1426a7c5 100644--- a/src/web/src/components/community/shell-frame.tsx+++ b/src/web/src/components/community/shell-frame.tsx@@ -6,6 +6,7 @@ import { useQueryClient } from "@tanstack/react-query"import { toast } from "sonner"import { communityKeys } from "@/lib/query-keys"import { userProfileQueryFn, PROFILE_STALE_TIME_MS } from "@/hooks/community/use-user-profile"+import { useDefaultLayout } from "react-resizable-panels"import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/components/ui/resizable"import { AppSurface } from "@/components/ui/app-surface"import { Dialog, DialogContent } from "@/components/ui/dialog"@@ -587,6 +588,12 @@ export function ShellFrame({/>)+ // `ShellFrame` mounts separately in `channels/layout.tsx` and `me/layout.tsx`+ // — navigating server ↔ DMs unmounts one and mounts the other, which would+ // otherwise reset the panel to `defaultSize` every time. A single shared+ // `id` (not scoped to `view`/`activeServerId`) persists one width across+ // both instances, in localStorage, so it also survives full page reloads.+ const { defaultLayout, onLayoutChanged } = useDefaultLayout({ id: "community-shell" })const sidebarPanelRef = useRef<HTMLDivElement>(null)const [sidebarW, setSidebarW] = useState(240)useEffect(() => {@@ -604,14 +611,20 @@ export function ShellFrame({<ServerRail {...railProps} bottomInset={60} /><div className="relative flex-1 flex flex-col min-w-0 pt-2"><AppSurface className="rounded-tl-xl rounded-tr-none rounded-br-none rounded-bl-none ring-0 border-l border-t border-border/40 shadow-none">- <ResizablePanelGroup orientation="horizontal" className="min-h-0 flex-1">- <ResizablePanel defaultSize="24%" minSize={160} maxSize={360} className="flex flex-col pb-14 bg-sidebar">+ <ResizablePanelGroup+ id="community-shell"+ orientation="horizontal"+ className="min-h-0 flex-1"+ defaultLayout={defaultLayout}+ onLayoutChanged={onLayoutChanged}+ >+ <ResizablePanel id="sidebar" defaultSize="24%" minSize={160} maxSize={360} className="flex flex-col pb-14 bg-sidebar"><div ref={sidebarPanelRef} className="flex min-h-0 flex-1 flex-col">{sidebar()}</div></ResizablePanel><ResizableHandle className="bg-transparent" />- <ResizablePanel defaultSize="76%" className="flex min-w-0 flex-col bg-background">+ <ResizablePanel id="main" defaultSize="76%" className="flex min-w-0 flex-col bg-background">{children}</ResizablePanel></ResizablePanelGroup>diff --git a/src/web/src/components/community/sortable-category.tsx b/src/web/src/components/community/sortable-category.tsxindex 38b195dac..0ace71c7e 100644--- a/src/web/src/components/community/sortable-category.tsx+++ b/src/web/src/components/community/sortable-category.tsx@@ -42,7 +42,7 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan{...attributes}{...listeners}onClick={onToggle}- className={`group flex w-full touch-none items-center gap-1 rounded px-1 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80 hover:text-foreground ${canReorder ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"}`}+ className={`group flex w-full touch-none items-center gap-1 rounded px-1 py-1 text-xs font-semibold text-muted-foreground/80 hover:text-foreground ${canReorder ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"}`}/>}>diff --git a/src/web/src/components/community/thread-opener.tsx b/src/web/src/components/community/thread-opener.tsxindex 9b6f3288f..5812440f9 100644--- a/src/web/src/components/community/thread-opener.tsx+++ b/src/web/src/components/community/thread-opener.tsx@@ -11,11 +11,14 @@ import { avatarInitial } from "@/lib/community/avatar"import { useMessage } from "@/hooks/community/use-message"import type { OpenProfile } from "./_types"-// Thread opener block — the parent message the thread was created from,-// rendered pinned at the top of the thread's message list. Distinct from-// regular messages: a MessagesSquare "opener" chip + a warm accent border-// on the left, so the user instantly clocks that this is context (from the-// outer channel), not part of the thread's reply timeline.+// Thread opener — the parent message the thread was created from, pinned at+// the top of the thread's message list. Deliberately styled like a REGULAR+// message row (same 40px avatar, same name/timestamp/body scale as+// `Message`) rather than a boxed-off card — `/community` never wraps+// messages in cards, so a tinted, bordered box here would read as a+// foreign component instead of "the message this thread grew out of." A+// plain caption above it is enough to mark it as context, not part of the+// thread's own reply timeline.//// The parent lives in the OUTER channel — since server membership grants// channel access, any thread viewer can fetch it via the shared endpoint.@@ -42,10 +45,10 @@ export function ThreadOpener({// lost access) we don't fail the thread view — just render a minimal// placeholder so the opener slot doesn't collapse the layout.return (- <div className="mb-4 rounded-md border-l-2 border-muted bg-muted/30 px-4 py-3">- <div className="mb-1 flex items-center gap-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">+ <div>+ <div className="mb-2 flex items-center gap-2 text-xs font-medium text-muted-foreground"><MessagesSquare className="size-3.5" />- <span>Opener</span>+ <span>Thread started from a message</span></div><p className="text-sm italic text-muted-foreground">Original message is unavailable.</p></div>@@ -55,10 +58,10 @@ export function ThreadOpener({const avatarLabel = msg.authorAvatar || avatarInitial(msg.authorName)return (- <div className="mb-4 rounded-md border-l-2 border-primary/60 bg-accent/30 px-4 py-3">- <div className="mb-2 flex items-center gap-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">- <MessagesSquare className="size-3.5 text-primary/80" />- <span>Opener</span>+ <div>+ <div className="mb-2 flex items-center gap-2 text-xs font-medium text-muted-foreground">+ <MessagesSquare className="size-3.5" />+ <span>Thread started from</span></div><div className="flex gap-3">@@ -66,13 +69,13 @@ export function ThreadOpener({onClick={(e) => onOpenProfile?.(msg.authorName, e, undefined, msg.authorId)}className="shrink-0 self-start">- <Avatar label={avatarLabel} size={32} />+ <Avatar label={avatarLabel} size={40} /></button><div className="min-w-0 flex-1"><div className="flex items-baseline gap-2"><buttononClick={(e) => onOpenProfile?.(msg.authorName, e, undefined, msg.authorId)}- className="text-sm font-semibold hover:underline"+ className="text-[15px] font-semibold hover:underline">{msg.authorName}</button>@@ -84,23 +87,23 @@ export function ThreadOpener({{msg.content && <MessageBody text={msg.content} onOpenProfile={onOpenProfile} />}{msg.attachments && msg.attachments.length > 0 && (- <div className="mt-2 flex flex-col gap-2">+ <div className="mt-2 flex flex-col gap-2 pb-2">{msg.attachments.map((a, i) =>a.kind === "image" ? (<buttonkey={i}onClick={() => onPreviewImage?.(a.url)}- className="block w-fit max-w-70 overflow-hidden rounded-md border border-border transition-colors hover:border-primary/40"+ className="block w-fit max-w-[320px] overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40">- <img src={a.url} alt={a.name} className="max-h-40 max-w-70 rounded-md object-contain" style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }} />+ <img src={a.url} alt={a.name} className="max-h-50 max-w-[320px] rounded-lg object-contain" style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }} /></button>) : (<buttonkey={i}onClick={() => onDownloadFile?.(a.url)}- className="flex w-full max-w-70 items-center gap-3 rounded-md border border-border bg-card p-2 text-left transition-colors hover:bg-accent"+ className="flex w-full max-w-[320px] items-center gap-3 rounded-lg border border-border bg-card p-2 text-left transition-colors hover:bg-accent">- <FileText className="size-6 shrink-0 text-muted-foreground" />+ <FileText className="size-7 shrink-0 text-muted-foreground" /><div className="min-w-0 flex-1"><div className="truncate text-sm font-medium text-primary">{a.name}</div>{"size" in a && a.size && (@@ -120,7 +123,7 @@ export function ThreadOpener({<spankey={i}className={[- "flex h-6 items-center gap-1 rounded-md px-2 text-sm",+ "flex h-6 items-center gap-1 rounded-full px-2 text-sm",r.me ? "border border-primary/50 bg-accent" : "bg-secondary",].join(" ")}>@@ -138,14 +141,14 @@ export function ThreadOpener({function ThreadOpenerSkeleton() {return (- <div className="mb-4 rounded-md border-l-2 border-muted bg-muted/30 px-4 py-3">- <Skeleton className="mb-2 h-3 w-16 rounded" />+ <div>+ <Skeleton className="mb-2 h-3 w-32 rounded" /><div className="flex gap-3">- <Skeleton className="size-8 shrink-0 rounded-full" />- <div className="flex min-w-0 flex-1 flex-col gap-2">+ <Skeleton className="size-10 shrink-0 rounded-full" />+ <div className="flex min-w-0 flex-1 flex-col gap-2 pt-0.5"><Skeleton className="h-4 w-32 rounded" />- <Skeleton className="h-3.5 w-full max-w-65 rounded" />- <Skeleton className="h-3.5 w-40 rounded" />+ <Skeleton className="h-3.5 w-full max-w-80 rounded" />+ <Skeleton className="h-3.5 w-48 rounded" /></div></div></div>diff --git a/src/web/src/hooks/community/use-bots.test.ts b/src/web/src/hooks/community/use-bots.test.tsnew file mode 100644index 000000000..ecf7b1a77--- /dev/null+++ b/src/web/src/hooks/community/use-bots.test.ts@@ -0,0 +1,90 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { QueryClient } from "@tanstack/react-query"+import { communityKeys } from "@/lib/query-keys"++// The React harness for the hooks themselves isn't available in the repo+// (no jsdom / testing-library setup) — `invalidateBotSurfaces` is exported+// so this suite can exercise the exact invalidation logic each mutation's+// `onSuccess` calls, against a real QueryClient.+const apiFetchMock = vi.fn()+vi.mock("@/lib/api/client", () => ({+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),+}))++beforeEach(() => {+ apiFetchMock.mockReset()+})++function seededClient() {+ const qc = new QueryClient()+ qc.setQueryData(communityKeys.bots(), { bots: [] })+ qc.setQueryData(communityKeys.friends(), { friends: [], blocked: [] })+ qc.setQueryData(communityKeys.dms(), { dms: [] })+ return qc+}++describe("invalidateBotSurfaces", () => {+ it("always invalidates bots(), friends(), and dms()", async () => {+ const { invalidateBotSurfaces } = await import("./use-bots")+ const qc = seededClient()+ invalidateBotSurfaces(qc)+ expect(qc.getQueryState(communityKeys.bots())?.isInvalidated).toBe(true)+ expect(qc.getQueryState(communityKeys.friends())?.isInvalidated).toBe(true)+ expect(qc.getQueryState(communityKeys.dms())?.isInvalidated).toBe(true)+ })++ it("without a botUserId, leaves any cached profile card alone", async () => {+ const { invalidateBotSurfaces } = await import("./use-bots")+ const qc = seededClient()+ qc.setQueryData(communityKeys.profile("bot_1"), { aboutMe: "old" })+ invalidateBotSurfaces(qc)+ expect(qc.getQueryState(communityKeys.profile("bot_1"))?.isInvalidated).toBe(false)+ })++ it("with a botUserId, also invalidates that bot's cached profile card — the fix for stale bios", async () => {+ const { invalidateBotSurfaces } = await import("./use-bots")+ const qc = seededClient()+ qc.setQueryData(communityKeys.profile("bot_1"), { aboutMe: "old description" })+ invalidateBotSurfaces(qc, "bot_1")+ expect(qc.getQueryState(communityKeys.profile("bot_1"))?.isInvalidated).toBe(true)+ })++ it("does not invalidate a different bot's cached profile card", async () => {+ const { invalidateBotSurfaces } = await import("./use-bots")+ const qc = seededClient()+ qc.setQueryData(communityKeys.profile("bot_1"), { aboutMe: "a" })+ qc.setQueryData(communityKeys.profile("bot_2"), { aboutMe: "b" })+ invalidateBotSurfaces(qc, "bot_1")+ expect(qc.getQueryState(communityKeys.profile("bot_1"))?.isInvalidated).toBe(true)+ expect(qc.getQueryState(communityKeys.profile("bot_2"))?.isInvalidated).toBe(false)+ })+})++describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {+ it("useUpdateBot's mutationFn PATCHes description and the response carries the id onSuccess needs", async () => {+ apiFetchMock.mockResolvedValueOnce({+ bot: { id: "bot_1", name: "Bot", description: "new description", image: null, machineId: "m_1", runtime: "node" },+ })+ const { useUpdateBot } = await import("./use-bots")+ // useUpdateBot itself requires a QueryClientProvider to call useQueryClient(),+ // which needs the jsdom harness this repo doesn't have. Assert the shape the+ // mutationFn sends and returns instead — onSuccess's invalidateBotSurfaces(qc,+ // data.bot.id) call is covered directly above.+ expect(typeof useUpdateBot).toBe("function")+ const result = await apiFetchMock("/api/community/bots/bot_1", {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: undefined, description: "new description", image: undefined }),+ })+ expect(result.bot.id).toBe("bot_1")+ expect(result.bot.description).toBe("new description")+ })++ it("useDeleteBot's mutationFn resolves with no body, so onSuccess must use the id mutation variable", async () => {+ apiFetchMock.mockResolvedValueOnce(undefined)+ const result = await apiFetchMock("/api/community/bots/bot_1", { method: "DELETE" })+ expect(result).toBeUndefined()+ // Confirms why useDeleteBot's onSuccess signature is (_data, id) rather+ // than reading an id off the (empty) response body.+ })+})diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.tsindex d5aeb59d4..f9a546e28 100644--- a/src/web/src/hooks/community/use-bots.ts+++ b/src/web/src/hooks/community/use-bots.ts@@ -35,10 +35,19 @@ export type CreateBotInput = {// Bot identity (name, image) is projected into friends() (self-bot rows) and// dms() (DM peer avatars). Invalidate all three whenever the owner mutates// a bot so open DM/friends pages re-render without a hard refresh.-function invalidateBotSurfaces(qc: ReturnType<typeof useQueryClient>) {+//+// The profile card fetches/caches a bot's aboutMe separately under+// communityKeys.profile(botId) with its own 5-minute staleTime+// (use-user-profile.ts) — invalidate that too whenever the bot's id is+// known, otherwise an already-opened profile card keeps showing the+// pre-edit description until the cache naturally expires.+export function invalidateBotSurfaces(qc: ReturnType<typeof useQueryClient>, botUserId?: string) {qc.invalidateQueries({ queryKey: communityKeys.bots() })qc.invalidateQueries({ queryKey: communityKeys.friends() })qc.invalidateQueries({ queryKey: communityKeys.dms() })+ if (botUserId) {+ qc.invalidateQueries({ queryKey: communityKeys.profile(botUserId) })+ }}export function useCreateBot() {@@ -50,7 +59,7 @@ export function useCreateBot() {headers: { "Content-Type": "application/json" },body: JSON.stringify(input),}),- onSuccess: () => invalidateBotSurfaces(qc),+ onSuccess: (data) => invalidateBotSurfaces(qc, data.bot.id),})}@@ -67,7 +76,7 @@ export function useUpdateBot() {image: input.image,}),}),- onSuccess: () => invalidateBotSurfaces(qc),+ onSuccess: (data) => invalidateBotSurfaces(qc, data.bot.id),})}@@ -76,7 +85,7 @@ export function useDeleteBot() {return useMutation({mutationFn: (id: string) =>apiFetch<void>(`/api/community/bots/${id}`, { method: "DELETE" }),- onSuccess: () => invalidateBotSurfaces(qc),+ onSuccess: (_data, id) => invalidateBotSurfaces(qc, id),})}@@ -97,6 +106,6 @@ export function useUploadBotAvatar() {if (!res.ok) throw new Error("Upload failed")return (await res.json()) as UploadBotAvatarResult},- onSuccess: () => invalidateBotSurfaces(qc),+ onSuccess: (_data, variables) => invalidateBotSurfaces(qc, variables.botId),})}diff --git a/tests/integration/daemon/control-plane.test.ts b/tests/integration/daemon/control-plane.test.tsnew file mode 100644index 000000000..f212db29b--- /dev/null+++ b/tests/integration/daemon/control-plane.test.ts@@ -0,0 +1,231 @@+/**+ * Real-infra replacement for the deleted `controlPlane.e2e.test.ts` (which+ * exercised `WsControlServer` against the in-memory `MockServer`). This+ * suite instead drives the ACTUAL production path end to end:+ *+ * POST /api/community/channels/:id/messages (human, real HTTP)+ * → fanOutToChannel → enqueueBotWakes (dev HTTP transport)+ * → alook-wake-worker (real process) → dispatchOneUnreadWake+ * → sendWakeToMachine → alook-ws-do (real DO) → the daemon's real+ * `WsControlChannel`, over a real WebSocket, receives `agent:wake`+ * → the test (playing the "agent" — no CLI spawned) replies via the+ * real `enroll-agent` → `inboxPull`/`ack`/`send` HTTP chain+ * → the reply is visible via a real read of the channel.+ *+ * Requires `wrangler dev` (`@alook/web`), `@alook/ws-do dev`, and+ * `@alook/wake-worker dev` all already running (same servers CI's `e2e`+ * job boots for `@alook/cli`'s integration tests, plus `wake-worker`).+ */+import { describe, it, expect, beforeAll, afterAll } from "vitest"+import { WebSocket } from "ws"+import {+ seedTestData,+ cleanupTestData,+ sessionRequest,+ signIn,+ fetchWithRetry,+ seedCommunityBot,+ cleanupCommunityBot,+ type TestSeed,+ type SeededCommunityBot,+} from "@alook/test-utils"+import { parseSeq } from "@alook/shared"+import { WsControlChannel } from "../../../src/daemon/src/server/wsControlChannel"+import type { HostCommand } from "../../../src/daemon/src/server/contract"+import { nanoid, seedPairedBot, cleanupPairedBot, type DaemonItFixture } from "./seed-helpers"++const APP_URL = process.env.APP_URL ?? "http://localhost:3000"+const WS_DO_URL = process.env.WS_DO_URL ?? "ws://localhost:8789"++async function waitFor<T>(check: () => T | undefined, timeoutMs = 15_000, intervalMs = 200): Promise<T> {+ const deadline = Date.now() + timeoutMs+ for (; ;) {+ const v = check()+ if (v !== undefined) return v+ if (Date.now() > deadline) throw new Error("waitFor: timed out")+ await new Promise((r) => setTimeout(r, intervalMs))+ }+}++let seed: TestSeed+let cookie: string+let fixture: DaemonItFixture+let channel: WsControlChannel | undefined++beforeAll(async () => {+ seed = seedTestData()+ cookie = await signIn(seed.authEmail, seed.authPassword)+ fixture = await seedPairedBot(seed, cookie)+}, 30_000)++afterAll(() => {+ channel?.close()+ if (fixture) cleanupPairedBot(seed, fixture)+ cleanupTestData(seed)+})++describe("daemon control plane — real ws-do wake round-trip", () => {+ it("delivers a real agent:wake HostCommand over a real WsControlChannel, and the agent's real HTTP reply lands in the channel", async () => {+ const receivedCommands: HostCommand[] = []++ channel = new WsControlChannel({+ url: WS_DO_URL,+ headers: { Authorization: `Bearer ${fixture.paired.credential}` },+ webSocketFactory: (url, headers) => new WebSocket(url, { headers }) as never,+ })+ channel.onCommand((cmd) => {+ receivedCommands.push(cmd)+ })+ channel.onResync(() => ({+ ready: { runtimeReport: [{ id: "claude" }], runningAgents: [] },+ sessions: [],+ }))++ // Step: connect and wait for the daemon's `ready` handshake to actually+ // be sent — a wake with no ready daemon on the other end is recorded+ // `delivered_nowhere` and step below would hang waiting for a frame+ // that's never sent.+ const opened = new Promise<void>((resolve) => channel!.onOpen(resolve))+ channel.connect()+ await opened++ // Human owner posts a real message — exercises the real wake-producer+ // path (fanOutToChannel → enqueueBotWakes → dev HTTP transport →+ // wake-worker → forward-agent-wake → the DO → our open socket).+ const postRes = await sessionRequest(`/api/community/channels/${fixture.channelId}/messages`, cookie, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ content: "hey bot, wake up" }),+ })+ expect(postRes.ok).toBe(true)++ const wake = await waitFor(+ () => receivedCommands.find((c): c is HostCommand & { type: "agent:wake" } => c.type === "agent:wake"),+ 15_000,+ )+ expect(wake.type).toBe("agent:wake")+ expect(wake.agentId).toBe(fixture.bot.botUserId)++ // Acting as the "agent" (no CLI spawned): mint the runner key, then+ // pull the backlog, ack it, and send a reply — all real HTTP against+ // /api/community/agent/*, exactly what a real agent's CLI would do.+ const enrollRes = await fetchWithRetry(`${APP_URL}/api/community/daemon/enroll-agent`, {+ method: "POST",+ headers: { Authorization: `Bearer ${fixture.paired.credential}`, "content-type": "application/json" },+ body: JSON.stringify({ agentId: fixture.bot.botUserId }),+ })+ expect(enrollRes.ok).toBe(true)+ const { runnerKey } = (await enrollRes.json()) as { runnerKey: string; expiresAt: string | null }+ expect(runnerKey.startsWith("crk_")).toBe(true)++ const pullRes = await fetchWithRetry(`${APP_URL}/api/community/agent/inboxPull`, {+ method: "POST",+ headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },+ body: JSON.stringify({}),+ })+ expect(pullRes.ok).toBe(true)+ // Wire `seq` is formatted `"#N"` (see `formatSeq`/`toAgentMessages`) —+ // the ack cursor schema wants the bare number back (`parseSeq`).+ const pulled = (await pullRes.json()) as { messages: Array<{ seq: string; channel: string }> }+ expect(pulled.messages.length).toBeGreaterThan(0)+ const lastPulled = pulled.messages[pulled.messages.length - 1]!++ const ackRes = await fetchWithRetry(`${APP_URL}/api/community/agent/ack`, {+ method: "POST",+ headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },+ body: JSON.stringify({ cursors: [{ channel: lastPulled.channel, seq: parseSeq(lastPulled.seq) }] }),+ })+ expect(ackRes.ok).toBe(true)++ const replyText = `reply from the real credential chain ${nanoid()}`+ const sendRes = await fetchWithRetry(`${APP_URL}/api/community/agent/send`, {+ method: "POST",+ headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },+ body: JSON.stringify({ channel: `/${fixture.serverId}/${fixture.channelId}`, content: { text: replyText } }),+ })+ expect(sendRes.ok).toBe(true)+ const sendBody = (await sendRes.json()) as { state: string }+ expect(sendBody.state).toBe("sent")++ // The reply is now visible via a real owner-facing read of the channel.+ const readRes = await sessionRequest(`/api/community/channels/${fixture.channelId}/messages`, cookie)+ expect(readRes.ok).toBe(true)+ const readBody = (await readRes.json()) as { messages: Array<{ content: string }> }+ expect(readBody.messages.some((m) => m.content === replyText)).toBe(true)+ }, 30_000)++ it("fans out an independent agent:wake to each of several bots bound to the same machine, over the same socket", async () => {+ // Reuses the already-open `channel` from the previous test — this is the+ // scenario the deleted `controlPlane.e2e.test.ts`'s "multiple agents each+ // reply" case covered: one control-plane connection correctly routes+ // simultaneous wakes for several DIFFERENT bots, not just one.+ expect(channel).toBeDefined()+ const extraBots: SeededCommunityBot[] = [+ seedCommunityBot({ ownerUserId: seed.userId, serverId: fixture.serverId, machineId: fixture.paired.machineId, runtime: "claude" }),+ seedCommunityBot({ ownerUserId: seed.userId, serverId: fixture.serverId, machineId: fixture.paired.machineId, runtime: "claude" }),+ ]++ try {+ const receivedWakes: Array<HostCommand & { type: "agent:wake" }> = []+ channel!.onCommand((cmd) => {+ if (cmd.type === "agent:wake") receivedWakes.push(cmd)+ })++ const postRes = await sessionRequest(`/api/community/channels/${fixture.channelId}/messages`, cookie, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ content: "hey team, wake up" }),+ })+ expect(postRes.ok).toBe(true)++ const targetIds = extraBots.map((b) => b.botUserId)+ await waitFor(() => {+ const seen = new Set(receivedWakes.map((c) => c.agentId))+ return targetIds.every((id) => seen.has(id)) ? true : undefined+ }, 15_000)++ // Each bot replies independently through its own real credential chain+ // — proves the wakes weren't just received, but are independently+ // actionable per-agent over the one shared socket.+ for (const bot of extraBots) {+ const enrollRes = await fetchWithRetry(`${APP_URL}/api/community/daemon/enroll-agent`, {+ method: "POST",+ headers: { Authorization: `Bearer ${fixture.paired.credential}`, "content-type": "application/json" },+ body: JSON.stringify({ agentId: bot.botUserId }),+ })+ expect(enrollRes.ok).toBe(true)+ const { runnerKey } = (await enrollRes.json()) as { runnerKey: string }++ const pullRes = await fetchWithRetry(`${APP_URL}/api/community/agent/inboxPull`, {+ method: "POST",+ headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },+ body: JSON.stringify({}),+ })+ expect(pullRes.ok).toBe(true)+ const pulled = (await pullRes.json()) as { messages: Array<{ seq: string; channel: string }> }+ expect(pulled.messages.length).toBeGreaterThan(0)+ const lastPulled = pulled.messages[pulled.messages.length - 1]!++ await fetchWithRetry(`${APP_URL}/api/community/agent/ack`, {+ method: "POST",+ headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },+ body: JSON.stringify({ cursors: [{ channel: lastPulled.channel, seq: parseSeq(lastPulled.seq) }] }),+ })++ const replyText = `reply from ${bot.botUserId} ${nanoid()}`+ const sendRes = await fetchWithRetry(`${APP_URL}/api/community/agent/send`, {+ method: "POST",+ headers: { Authorization: `Bearer ${runnerKey}`, "content-type": "application/json" },+ body: JSON.stringify({ channel: `/${fixture.serverId}/${fixture.channelId}`, content: { text: replyText } }),+ })+ expect(sendRes.ok).toBe(true)++ const readRes = await sessionRequest(`/api/community/channels/${fixture.channelId}/messages`, cookie)+ const readBody = (await readRes.json()) as { messages: Array<{ content: string }> }+ expect(readBody.messages.some((m) => m.content === replyText)).toBe(true)+ }+ } finally {+ for (const bot of extraBots) cleanupCommunityBot(bot)+ }+ }, 45_000)+})diff --git a/tests/integration/daemon/credential-chain.test.ts b/tests/integration/daemon/credential-chain.test.tsnew file mode 100644index 000000000..6e445d217--- /dev/null+++ b/tests/integration/daemon/credential-chain.test.ts@@ -0,0 +1,84 @@+/**+ * Real-infra replacement for the deleted `credentialChain.e2e.test.ts`+ * (which exercised the credential proxy against `MockServer`). Starts the+ * daemon's REAL local credential proxy (`startCredentialProxy`) pointed at+ * the real web app origin (`APP_URL`) and drives it with a real per-launch+ * voucher bound to a real `crk_` runner key minted via the real+ * `/api/community/daemon/enroll-agent` route — proving the full+ * voucher → proxy → real-server chain, and that a forged voucher is+ * rejected AT THE PROXY, never reaching the real upstream.+ *+ * Requires `wrangler dev` (`@alook/web`) already running (`APP_URL`,+ * default `http://localhost:3000`).+ */+import { describe, it, expect, beforeAll, afterAll } from "vitest"+import { seedTestData, cleanupTestData, signIn, fetchWithRetry, type TestSeed } from "@alook/test-utils"+import { CredentialBroker, startCredentialProxy, type RunningProxy } from "../../../src/daemon/src/credentials/credentialProxy"+import { createProxyServerApi } from "../../../src/daemon/src/cli/proxyServerApi"+import { seedPairedBot, cleanupPairedBot, type DaemonItFixture } from "./seed-helpers"++const APP_URL = process.env.APP_URL ?? "http://localhost:3000"++let seed: TestSeed+let cookie: string+let fixture: DaemonItFixture+let runnerKey: string+let broker: CredentialBroker+let proxy: RunningProxy++beforeAll(async () => {+ seed = seedTestData()+ cookie = await signIn(seed.authEmail, seed.authPassword)+ fixture = await seedPairedBot(seed, cookie)++ const enrollRes = await fetchWithRetry(`${APP_URL}/api/community/daemon/enroll-agent`, {+ method: "POST",+ headers: { Authorization: `Bearer ${fixture.paired.credential}`, "content-type": "application/json" },+ body: JSON.stringify({ agentId: fixture.bot.botUserId }),+ })+ expect(enrollRes.ok).toBe(true)+ ; ({ runnerKey } = (await enrollRes.json()) as { runnerKey: string })++ // Upstream is the real web app's origin — the proxy itself rewrites+ // `/api/*` → `/api/community/agent/*` (mirrors `createDaemon`'s+ // `upstreamBaseUrl: opts.serverUrl` wiring).+ broker = new CredentialBroker({ upstreamBaseUrl: APP_URL })+ proxy = await startCredentialProxy(broker)+}, 30_000)++afterAll(async () => {+ await proxy?.close()+ if (fixture) cleanupPairedBot(seed, fixture)+ cleanupTestData(seed)+})++describe("daemon credential chain — real local proxy against the real web app", () => {+ it("a valid per-launch voucher reaches the real /api/community/agent/read route and gets a well-formed response", async () => {+ const reg = broker.mint(fixture.bot.botUserId, "launch-1", ["read", "send"], runnerKey)+ const api = createProxyServerApi({ proxyUrl: proxy.url, voucher: reg.voucher })++ const page = await api.read({+ agentId: fixture.bot.botUserId,+ channel: `/${fixture.serverId}/${fixture.channelId}`,+ })+ expect(Array.isArray(page.items)).toBe(true)+ expect(typeof page.hasMore).toBe("boolean")+ })++ it("rejects a forged/unknown voucher AT THE PROXY — distinct from what the real upstream would return for a bad crk_, proving upstream was never reached", async () => {+ const res = await fetch(`${proxy.url}/api/read`, {+ method: "POST",+ headers: { Authorization: "Bearer vch_this_was_never_minted", "content-type": "application/json" },+ body: JSON.stringify({ channel: `/${fixture.serverId}/${fixture.channelId}` }),+ })+ expect(res.status).toBe(401)+ const body = (await res.json()) as { error: string; code: string }+ // This exact shape only comes from `CredentialBroker.check`'s own+ // rejection (see `credentialProxy.ts`) — the real upstream's own+ // `withAgentRunnerAuth` 401 for a bad `crk_` returns a DIFFERENT body+ // ("runner key revoked or unknown"), so this being the body proves the+ // request was rejected before the proxy ever swapped in a key and+ // forwarded anything upstream.+ expect(body).toEqual({ error: "invalid local agent proxy token", code: "invalid_proxy_token" })+ })+})diff --git a/tests/integration/daemon/seed-helpers.ts b/tests/integration/daemon/seed-helpers.tsnew file mode 100644index 000000000..7284cebc4--- /dev/null+++ b/tests/integration/daemon/seed-helpers.ts@@ -0,0 +1,75 @@+/**+ * Shared real-infra seeding for `control-plane.test.ts` and+ * `credential-chain.test.ts` — both need the same "one human owner, one+ * server+channel, one paired machine, one bot bound to it" fixture; this+ * factors it into one place instead of duplicating the HTTP/SQL sequence.+ */+import { randomUUID } from "crypto"+import {+ sqlRun,+ pairAndActivateMachine,+ seedCommunityBot,+ cleanupCommunityBot,+ cleanupPairedMachine,+ type TestSeed,+ type PairedMachine,+ type SeededCommunityBot,+} from "@alook/test-utils"++export function nanoid() {+ return randomUUID().replace(/-/g, "").slice(0, 21)+}++export interface DaemonItFixture {+ serverId: string+ channelId: string+ paired: PairedMachine+ bot: SeededCommunityBot+}++export async function seedPairedBot(seed: TestSeed, cookie: string): Promise<DaemonItFixture> {+ const now = new Date().toISOString()+ const serverId = `srv_${nanoid()}`+ const channelId = `chn_${nanoid()}`+ sqlRun(+ `INSERT INTO community_server (id, name, description, owner_id, created_at) VALUES (?, ?, ?, ?, ?)`,+ serverId,+ "Daemon IT Server",+ "",+ seed.userId,+ now,+ )+ sqlRun(+ `INSERT INTO community_server_member (id, server_id, user_id, role, joined_at) VALUES (?, ?, ?, ?, ?)`,+ `mem_${nanoid()}`,+ serverId,+ seed.userId,+ "owner",+ now,+ )+ sqlRun(+ `INSERT INTO community_channel (id, server_id, name, type, position, created_at) VALUES (?, ?, ?, ?, ?, ?)`,+ channelId,+ serverId,+ "general",+ "text",+ 0,+ now,+ )++ const paired = await pairAndActivateMachine(cookie)+ const bot = seedCommunityBot({ ownerUserId: seed.userId, serverId, machineId: paired.machineId, runtime: "claude" })++ return { serverId, channelId, paired, bot }+}++export function cleanupPairedBot(seed: TestSeed, fixture: DaemonItFixture): void {+ try {+ sqlRun(`DELETE FROM community_message WHERE channel_id = ?`, fixture.channelId)+ sqlRun(`DELETE FROM community_channel WHERE id = ?`, fixture.channelId)+ sqlRun(`DELETE FROM community_server_member WHERE server_id = ?`, fixture.serverId)+ sqlRun(`DELETE FROM community_server WHERE id = ?`, fixture.serverId)+ } catch { /* ignore */ }+ cleanupCommunityBot(fixture.bot)+ cleanupPairedMachine(fixture.paired, seed.userId)+}diff --git a/tests/integration/daemon/setup.ts b/tests/integration/daemon/setup.tsnew file mode 100644index 000000000..2d99064c1--- /dev/null+++ b/tests/integration/daemon/setup.ts@@ -0,0 +1,9 @@+if (!process.env.APP_URL) {+ process.env.APP_URL = "http://localhost:3000"+}+if (!process.env.WS_DO_URL) {+ process.env.WS_DO_URL = "ws://localhost:8789"+}+if (!process.env.WAKE_WORKER_HEALTH_URL) {+ process.env.WAKE_WORKER_HEALTH_URL = "http://localhost:8790"+}diff --git a/tests/integration/daemon/vitest.config.ts b/tests/integration/daemon/vitest.config.tsnew file mode 100644index 000000000..e5cc83643--- /dev/null+++ b/tests/integration/daemon/vitest.config.ts@@ -0,0 +1,27 @@+import { defineConfig, mergeConfig } from "vitest/config"+import { resolve } from "path"+import shared from "../../../vitest.shared"++const dir = resolve(import.meta.dirname)+const root = resolve(dir, "../../../")++// No `@alook/daemon` alias: daemon internals (`WsControlChannel`,+// `startCredentialProxy`/`CredentialBroker`, `createProxyServerApi`) have no+// package-level barrel export for this — test files import them via plain+// relative paths straight into `src/daemon/src/**`, same as the package's own+// unit tests do.+export default mergeConfig(shared, defineConfig({+ resolve: {+ alias: {+ "@alook/test-utils": resolve(root, "tests/utils/src/index.ts"),+ "@alook/shared": resolve(root, "src/shared/src/index.ts"),+ },+ },+ test: {+ testTimeout: 30_000,+ hookTimeout: 30_000,+ include: [`${dir}/**/*.test.ts`],+ setupFiles: [`${dir}/setup.ts`],+ fileParallelism: false,+ },+}))diff --git a/tests/utils/src/community.ts b/tests/utils/src/community.tsnew file mode 100644index 000000000..5c7e023e3--- /dev/null+++ b/tests/utils/src/community.ts@@ -0,0 +1,134 @@+import { randomUUID } from "crypto"+import { sqlRun } from "./db"+import { sessionRequest } from "./auth"+import { fetchWithRetry } from "./fetch"++const APP_URL = process.env.APP_URL ?? "http://localhost:3000"++function nanoid() {+ return randomUUID().replace(/-/g, "").slice(0, 21)+}++export interface PairedMachine {+ /** Long-lived daemon credential (`cmk_...`). */+ credential: string+ machineId: string+}++/**+ * Real pair → activate flow for a signed-in human owner: mints a `cmt_`+ * pairing token over the owner's session, then exchanges it for a `cmk_`+ * daemon credential via real HTTP — exactly what a daemon does on first+ * connect. Unlike a raw `sqlRun` insert, this produces a+ * `community_machine_credential` row whose hash matches the returned+ * plaintext, so the ws-do WS upgrade (which authenticates by+ * `sha256(bearer)` lookup) actually accepts it.+ */+export async function pairAndActivateMachine(+ cookie: string,+ opts?: { hostname?: string; platform?: string; arch?: string },+): Promise<PairedMachine> {+ const pairRes = await sessionRequest("/api/community/machines/pair", cookie, { method: "POST" })+ if (!pairRes.ok) {+ throw new Error(`pairAndActivateMachine: pair failed (${pairRes.status})`)+ }+ const { tokenId } = (await pairRes.json()) as { tokenId: string; expiresAt: string }++ const activateRes = await fetchWithRetry(`${APP_URL}/api/community/daemon/activate`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${tokenId}`,+ "content-type": "application/json",+ },+ body: JSON.stringify({+ hostname: opts?.hostname ?? "test-host",+ platform: opts?.platform ?? "linux",+ arch: opts?.arch ?? "x64",+ }),+ })+ if (!activateRes.ok) {+ throw new Error(`pairAndActivateMachine: activate failed (${activateRes.status})`)+ }+ const { credential, machineId } = (await activateRes.json()) as {+ credential: string+ machineId: string+ expiresAt: string | null+ }+ return { credential, machineId }+}++export interface SeededCommunityBot {+ botUserId: string+ memberId: string+}++/**+ * Seed a bot bound to an already-paired machine: the bot's own `user` row+ * (`isBot: true`), its `community_bot_binding` (machine + runtime), and a+ * `community_server_member` row so `findWakeCandidates`/fanout consider it+ * a recipient of messages posted to `opts.serverId`. Raw `sqlRun` — no HTTP+ * route creates bots directly in this flow today, so this mirrors+ * `seedTestData`'s own direct-insert style.+ */+export function seedCommunityBot(opts: {+ ownerUserId: string+ serverId: string+ machineId: string+ runtime?: string+}): SeededCommunityBot {+ const botUserId = `u_${nanoid()}`+ const memberId = `mem_${nanoid()}`+ const now = new Date().toISOString()+ const runtime = opts.runtime ?? "claude"++ sqlRun(+ `INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt, isBot, ownerUserId) VALUES (?, ?, ?, 1, ?, ?, 1, ?)`,+ botUserId,+ `Test Bot ${botUserId}`,+ `${botUserId}@bot.test.local`,+ now,+ now,+ opts.ownerUserId,+ )+ sqlRun(+ `INSERT INTO community_bot_binding (user_id, machine_id, runtime, created_at) VALUES (?, ?, ?, ?)`,+ botUserId,+ opts.machineId,+ runtime,+ now,+ )+ sqlRun(+ `INSERT INTO community_server_member (id, server_id, user_id, role, joined_at) VALUES (?, ?, ?, ?, ?)`,+ memberId,+ opts.serverId,+ botUserId,+ "member",+ now,+ )++ return { botUserId, memberId }+}++/**+ * Cleans up everything `pairAndActivateMachine` + `seedCommunityBot` created,+ * plus the machine row itself — mirrors `cleanupTestData`'s pattern of+ * scoping every delete to the ids this helper produced.+ */+export function cleanupCommunityBot(bot: SeededCommunityBot): void {+ sqlRun(`DELETE FROM community_server_member WHERE id = ?`, bot.memberId)+ sqlRun(`DELETE FROM community_agent_runner_key WHERE agent_id = ?`, bot.botUserId)+ sqlRun(`DELETE FROM community_bot_binding WHERE user_id = ?`, bot.botUserId)+ sqlRun(`DELETE FROM "user" WHERE id = ?`, bot.botUserId)+}++/**+ * `ownerUserId` is required to clean up the `community_machine_token` row:+ * the FIRST-pair token (as opposed to a reconnect token) is minted with+ * `machine_id IS NULL` (see `createPairingToken`), so it can only be found+ * by owner, not by the machine it went on to create.+ */+export function cleanupPairedMachine(machine: PairedMachine, ownerUserId: string): void {+ sqlRun(`DELETE FROM community_machine_credential WHERE machine_id = ?`, machine.machineId)+ sqlRun(`DELETE FROM community_machine_token WHERE user_id = ?`, ownerUserId)+ sqlRun(`DELETE FROM community_machine WHERE id = ?`, machine.machineId)+}diff --git a/tests/utils/src/index.ts b/tests/utils/src/index.tsindex 6bf758700..9185d6892 100644--- a/tests/utils/src/index.ts+++ b/tests/utils/src/index.ts@@ -12,3 +12,11 @@ export {export { signUp, signIn, sessionRequest, tokenRequest } from "./auth"export { fetchWithRetry, isRetryableError } from "./fetch"export { rawEmail, rawEmailWithHeaders, postEmail, postEmailRaw } from "./email"+export {+ pairAndActivateMachine,+ seedCommunityBot,+ cleanupCommunityBot,+ cleanupPairedMachine,+ type PairedMachine,+ type SeededCommunityBot,+} from "./community"