Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat: add Automation actions, file messaging and model caching (#1098)
Gustavo Ye531d1ff1d2ac
diff --git a/package.json b/package.jsonindex 9549c0722..d1d50813c 100644--- a/package.json+++ b/package.json@@ -15,6 +15,7 @@"knip": "turbo run knip","dev:web": "pnpm --filter @alook/web dev","daemon": "pnpm --filter @alook/daemon exec tsx src/cli/index.ts daemon",+ "daemon-use": "pnpm --filter @alook/daemon exec tsx src/cli/index.ts use","dev:desktop": "pnpm --filter @alook/desktop dev","build:desktop": "pnpm --filter @alook/desktop build","dev:email": "pnpm --filter @alook/email-worker dev",diff --git a/scripts/ci/artwork-provenance.test.ts b/scripts/ci/artwork-provenance.test.tsindex e73080c08..b6b586a34 100644--- a/scripts/ci/artwork-provenance.test.ts+++ b/scripts/ci/artwork-provenance.test.ts@@ -96,5 +96,5 @@ describe("renderer-scoped artwork provenance", () => {expect(Object.values(hashes).every(hash => /^[a-f0-9]{64}$/.test(hash))).toBe(true)}stage("assertions:done")- })+ }, 15_000)})diff --git a/scripts/ci/fixtures/d1-dynamic-bind-sites.json b/scripts/ci/fixtures/d1-dynamic-bind-sites.jsonindex 857241c7e..5aefaf0c6 100644--- a/scripts/ci/fixtures/d1-dynamic-bind-sites.json+++ b/scripts/ci/fixtures/d1-dynamic-bind-sites.json@@ -209,6 +209,27 @@{"key": "src/shared/src/db/queries/agent.ts:getExistingHandles:inArray:1"},+ {+ "key": "src/shared/src/db/queries/automation.ts:createAccessCode:values:1"+ },+ {+ "key": "src/shared/src/db/queries/automation.ts:createAccessCode:values:2"+ },+ {+ "key": "src/shared/src/db/queries/automation.ts:friendScope:inArray:1"+ },+ {+ "key": "src/shared/src/db/queries/automation.ts:friendScope:inArray:2"+ },+ {+ "key": "src/shared/src/db/queries/automation.ts:getAccessCode:inArray:1"+ },+ {+ "key": "src/shared/src/db/queries/automation.ts:updateAccessCode:inArray:1"+ },+ {+ "key": "src/shared/src/db/queries/automation.ts:updateAccessCode:values:1"+ },{"key": "src/shared/src/db/queries/community/agent-inbox.ts:getInboxSnapshotForAgent:inArray:1"},diff --git a/src/daemon/README.md b/src/daemon/README.mdindex 88ec4af3f..df727629f 100644--- a/src/daemon/README.md+++ b/src/daemon/README.md@@ -409,3 +409,45 @@ The bool is explicit per plugin, including when a later plugin restores the textPlugins have no provided filesystem, process, environment, network, or module-import capabilities. They run with memory and execution limits. Adding appends a new filter and cannot replace an existing filter. The CLI has no disable/delete operation. The human owner manages those actions in Privacy while the daemon is online, including for inactive bots. A dispatched request is not an applied change; the page waits for the local daemon's result. Deleted defaults stay deleted after restart. Rules can miss sensitive values; review the pipeline and its scope before relying on it.The Privacy playground relays test text through Alook's server to the daemon and returns the selected pipeline's output. It uses the same runner and checks the displayed configuration revision. Test input and output are transient: they are not stored in configuration, chat history, replay queues or body logs. No chat message or model request is sent. Input and output must each fit 1024 UTF-8 bytes; a failed filter returns a safe error instead of partial output.++## User automation++Create an access code in user Settings → Automation. Choose Write permissions (**Create bots**, **Create servers**, **Invite friends to servers**, **Send messages**), an expiry, and the rate for each permission. Read permissions (**List machines**, **List friends**, **List servers**) start enabled and can each be turned off. Save the full code when it appears: it is returned only once. Editing name, permissions or rates preserves the expiry; explicitly saving a new expiry starts that duration again. Deleting a code rejects subsequent requests.++`use` runs independently of a daemon connection or Alook bot session. It calls dedicated Automation APIs authenticated by access code; the normal client and bot APIs keep their original authentication and do not consume Automation quotas. Set `ALOOK_ACCESS_CODE` in the calling process, or pass `--access-code-file <path>` before the resource command. Keep the file private. Do not put the code in a command argument or URL.++```sh+npx @alook/daemon use bot --create '{"name":"Helper","machineId":"mac1","backendId":"codex","model":"gpt-6"}'+npx @alook/daemon use server --create '{"name":"demo","description":"Team work"}'+npx @alook/daemon use server --invite '{"server":"demo#0042","friend":"alice#0042"}'+npx @alook/daemon use machine --list+npx @alook/daemon use friend --list+npx @alook/daemon use server --list+npx @alook/daemon use message --send --target '/demo#0042/general' --as me --file './message.txt'+npx @alook/daemon use message --send --target '/.dm/alice#0042' --as '@Helper#0042' --file './message.txt'+```++Run `npx @alook/daemon use expire` to expire the supplied access code immediately. It needs no extra permission or remaining quota and affects only that code. Later requests, including repeated expiry, are refused. Expired codes leave the active list; their records remain stored. Returning to Automation refreshes the list.++These are examples. Use an existing machine ID owned by the code's user, an available backend, and a supported model. Optional bot fields are `description` and `reasoningEffort`. Bot creation keeps the same machine readiness, model and plan checks as the web form. The code grants each selected action directly. Machine, friend and server listing each require their own Read permission; other account actions are unavailable. Creating a server does not add bots to it.++The invite command sends the normal server invitation link to an accepted friend by DM; it does not force that person to join. It accepts no arbitrary message content. The caller must be a member of that server. Server and friend arguments use the full name#NNNN handles returned by the list commands.++`message --send` requires the default-off `message.send` Write permission. It sends the UTF-8 file contents, preserving line breaks, rather than attaching the file or reading stdin. `--as me` selects the code owner; `--as @name#NNNN` selects an eligible bot owned by that same human. Other identities are rejected. Target refs and permissions are resolved for the selected sender through the existing send functions. Bot unread alignment, CAS and duplicate checks remain; this command does not pull its inbox. The standalone access-code path does not execute the bot credential proxy's local PII filters.++Read responses are deliberately small: machines return id/name/status/backends (machines have no name#NNNN handle); friends return name/handle/is_my_bot; servers return name/handle/channels. The Automation API applies this projection before returning data.++Each command returns one JSON line, for example:++```json+{"success":{"bot":{"id":"b1","handle":"Helper#0042"}}}+{"success":{"server":{"id":"s1","handle":"demo#0042","url":"https://alook.ai/c/channels/s1"}}}+```++A code's seven permissions count separately. Rates use the preceding hour or 24 hours, with a 64/hour cap per code and permission even for a day rate. Valid authenticated requests admitted by the limiter consume a request even if business validation or creation subsequently fails. Invalid basic input and over-limit requests do not consume another request. Policy edits preserve recent history. A denied request returns an error; HTTP 429 includes a retry interval.++Write POSTs are sent once. If the connection fails, a creation, invitation or message may already have succeeded; inspect Alook before trying again. `use` never automatically repeats a write request.++`use server --list` includes each server's participating top-level `channels`, with `name`, `type` (`text` or `forum`) and canonical `ref`. It uses `server.read`: public channels follow server membership; private channels require the code owner's creator or access membership. Threads and messages are not returned. Servers with no visible top-level channels keep an empty `channels` array.++For local development only, pass `use --server-url http://localhost:<port> …` or set `ALOOK_SERVER_URL`. Remote origins require HTTPS. `use` does not follow HTTP redirects with the access code.diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex 739b5bc0e..d730fd0cd 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -1,5 +1,6 @@#!/usr/bin/env nodeimport { registerPlatformCommands } from "./platform.js";+import { registerUseCommands } from "./use.js";/*** `alook` — the agent-facing CLI.*@@ -814,6 +815,7 @@ function buildProgram(stdin: CliInputStream): Command {.option("--agent <id>", "agent identity (or ALOOK_AGENT_ID env)");registerPlatformCommands(program, getApi, printEnvelope);+ registerUseCommands(program, printEnvelope);registerPiiCommands(program, printEnvelope);const message = program.command("message").description("message operations").exitOverride();diff --git a/src/daemon/src/cli/platform-proxy.test.ts b/src/daemon/src/cli/platform-proxy.test.tsindex b860c7b8c..47fcc8920 100644--- a/src/daemon/src/cli/platform-proxy.test.ts+++ b/src/daemon/src/cli/platform-proxy.test.ts@@ -3,12 +3,12 @@ import { createProxyServerApi } from "./proxyServerApi"afterEach(() => vi.useRealTimers())describe("platform proxy transport", () => {- it("reuses discovery dispatch without polling or reporting native completion", async () => {- const fetchImpl = vi.fn(async () => Response.json({ dispatched: true, requestId: "disc" }, { status: 202 }))+ it("reuses the synchronous discovery/cache route without polling", async () => {+ const fetchImpl = vi.fn(async () => Response.json({ source: "fresh_discovery", requestId: "disc", models: [] }))const api = createProxyServerApi({ proxyUrl: "http://proxy", voucher: "voucher", fetchImpl })- expect(await api.platformMachine!({ action: "models", machineId: "m1", backendId: "codex", requestId: "disc", refresh: true })).toEqual({ dispatched: true, requestId: "disc" })+ expect(await api.platformMachine!({ action: "models", machineId: "m1", backendId: "codex", requestId: "disc", refresh: true })).toEqual({ source: "fresh_discovery", requestId: "disc", models: [] })expect(fetchImpl).toHaveBeenCalledOnce()- expect(fetchImpl.mock.calls[0][0]).toBe("http://proxy/api/community/machines/m1/discover-models")+ expect(fetchImpl.mock.calls[0][0]).toBe("http://proxy/api/community/machines/m1/discover-models?wait=1")})it("keeps only agreed error evidence fields and never exposes arbitrary response properties", async () => {const fetchImpl = vi.fn(async () => Response.json({ error: "Unsupported effort", code: "INVALID_REASONING_EFFORT", itemIndex: 2, field: "reasoningEffort", allowedValues: ["low"], credential: "private", ownerSecret: "private" }, { status: 400 }))@@ -19,3 +19,15 @@ describe("platform proxy transport", () => {expect(error.platformDetails).not.toHaveProperty("ownerSecret")})})++it("posts cached and model-specific requests with a new correlation ID by default", async () => {+ const fetchImpl = vi.fn(async (_url: string, _init?: RequestInit) => Response.json({ source: "cached_report", models: [] }))+ const api = createProxyServerApi({ proxyUrl: "http://proxy", voucher: "voucher", fetchImpl })+ await api.platformMachine!({ action: "models", machineId: "m/1", backendId: "custom/backend", model: "provider/model" })+ await api.platformMachine!({ action: "models", machineId: "m/1", backendId: "custom/backend", model: "provider/model" })+ expect(fetchImpl).toHaveBeenCalledTimes(2)+ expect(fetchImpl.mock.calls[0][0]).toBe("http://proxy/api/community/machines/m%2F1/discover-models?wait=1&model=provider%2Fmodel")+ const bodies = fetchImpl.mock.calls.map((call) => JSON.parse(call[1]!.body as string))+ expect(bodies[0]).toEqual({ requestId: expect.any(String), runtimeId: "custom/backend" })+ expect(bodies[0].requestId).not.toBe(bodies[1].requestId)+})diff --git a/src/daemon/src/cli/platform.test.ts b/src/daemon/src/cli/platform.test.tsindex 07bec545e..3520090a7 100644--- a/src/daemon/src/cli/platform.test.ts+++ b/src/daemon/src/cli/platform.test.ts@@ -46,6 +46,9 @@ describe("platform command registration through the real proxy API client", () =})it("reads target models with the full model ID and never sends a self-asserted identity", async () => {const result = await run(["platform", "machine", "--models", "--id", "machine/one", "--backend", "codex", "--model", "provider/model"])- expect(result.fetchImpl.mock.calls[0][0]).toBe("http://proxy/api/community/machines/machine%2Fone/models?backend=codex&model=provider%2Fmodel")+ expect(result.fetchImpl.mock.calls[0][0]).toBe("http://proxy/api/community/machines/machine%2Fone/discover-models?wait=1&model=provider%2Fmodel")+ const init = (result.fetchImpl.mock.calls[0] as unknown as [string, RequestInit])[1]+ expect(init.method).toBe("POST")+ expect(JSON.parse(init.body as string)).toEqual({ requestId: expect.any(String), runtimeId: "codex" })})})diff --git a/src/daemon/src/cli/platform.ts b/src/daemon/src/cli/platform.tsindex cfb5fb9cc..ce149362c 100644--- a/src/daemon/src/cli/platform.ts+++ b/src/daemon/src/cli/platform.ts@@ -14,7 +14,7 @@ export function registerPlatformCommands(program: Command, getApi: () => ServerA.option("--id <id>", "owner machine ID").option("--backend <id>", "backend ID from the selected machine").option("--model <id>", "show effort for this full model ID")- .option("--refresh", "ask the target to refresh its reported models")+ .option("--refresh", "bypass the five-minute model cache and wait for fresh models")machine.action(async () => {const opts = machine.opts()const actions = [opts.list, opts.backends, opts.models].filter(Boolean).length@@ -27,7 +27,7 @@ export function registerPlatformCommands(program: Command, getApi: () => ServerAconst api = getApi()if (!api.platformMachine) throw failure("Platform machine commands are unavailable", "UPGRADE_REQUIRED")const result = await api.platformMachine(opts.list ? { action: "list" } : opts.backends ? { action: "backends", machineId: opts.id }- : { action: "models", machineId: opts.id, backendId: opts.backend, ...(opts.model ? { model: opts.model } : {}), refresh: opts.refresh === true, ...(opts.refresh ? { requestId: randomUUID() } : {}) })+ : { action: "models", machineId: opts.id, backendId: opts.backend, ...(opts.model ? { model: opts.model } : {}), refresh: opts.refresh === true, requestId: randomUUID() })output({ success: result })})const bot = platform.command("bot").description("read bots or request owner-approved creation").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} })diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.tsindex d8cb2d353..df5c7247b 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -694,8 +694,7 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {if (req.action === "list") return platformCall("/machines?view=list");const machine = `/machines/${encodeURIComponent(req.machineId)}`;if (req.action === "backends") return platformCall(machine);- if (req.refresh) return platformCall(`${machine}/discover-models`, "POST", { requestId: req.requestId ?? crypto.randomUUID(), runtimeId: req.backendId });- return platformCall(`${machine}/models?backend=${encodeURIComponent(req.backendId)}${req.model ? `&model=${encodeURIComponent(req.model)}` : ""}`);+ return platformCall(`${machine}/discover-models?wait=1${req.model ? `&model=${encodeURIComponent(req.model)}` : ""}`, "POST", { requestId: req.requestId ?? crypto.randomUUID(), runtimeId: req.backendId, ...(req.refresh ? { refresh: true } : {}) });}async function callPlatformBot(req: PlatformBotRequest): Promise<Record<string, unknown>> {diff --git a/src/daemon/src/cli/use.test.ts b/src/daemon/src/cli/use.test.tsnew file mode 100644index 000000000..2b48155de--- /dev/null+++ b/src/daemon/src/cli/use.test.ts@@ -0,0 +1,352 @@+import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"+import { Command } from "commander"+import { mkdtemp, writeFile, rm, stat } from "node:fs/promises"+import { tmpdir } from "node:os"+import { join } from "node:path"+import { registerUseCommands } from "./use"++vi.mock("node:fs/promises", async (original) => {+ const actual = await original<typeof import("node:fs/promises")>()+ return { ...actual, stat: vi.fn(actual.stat) }+})++const secret = "aac_" + "a".repeat(64)+function program() {+ const root = new Command().exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} })+ const output = vi.fn()+ registerUseCommands(root, output)+ return { output, run: (args: string[]) => root.parseAsync(args, { from: "user" }) }+}+beforeEach(() => { vi.stubEnv("ALOOK_ACCESS_CODE", secret); vi.stubEnv("ALOOK_SERVER_URL", "http://localhost:4328"); vi.stubGlobal("fetch", vi.fn()) })+afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs() })++describe("use automation CLI", () => {+ it("expires its supplied code without a target identity and refuses malformed success or repeated expiry", async () => {+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({ expired: true }))+ const { run, output } = program()+ await run(["use", "expire"])+ expect(fetch).toHaveBeenCalledExactlyOnceWith("http://localhost:4328/api/community/automation/expire", expect.objectContaining({+ method: "POST", headers: expect.objectContaining({ Authorization: `Bearer ${secret}` }), body: "{}",+ }))+ expect(output).toHaveBeenCalledExactlyOnceWith({ success: { expired: true } })+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({ expired: false }))+ await expect(program().run(["use", "expire"])).rejects.toThrow("invalid expiration result")+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({ error: "Invalid or unauthorized access code" }, { status: 401 }))+ await expect(program().run(["use", "expire"])).rejects.toThrow("Invalid or unauthorized access code")+ })++ it("creates a bot through the dedicated API without proxy or agent identity and maps backendId", async () => {+ vi.mocked(fetch).mockResolvedValue(Response.json({ bot: { id: "b1", name: "Helper", discriminator: "0042" } }, { status: 201 }))+ const { run, output } = program()+ await run(["use", "bot", "--create", JSON.stringify({ name: "Helper", machineId: "mac1", backendId: "codex", model: "gpt-6" })])+ expect(fetch).toHaveBeenCalledOnce()+ const [url, init] = vi.mocked(fetch).mock.calls[0]!+ expect(url).toBe("http://localhost:4328/api/community/automation/bots")+ expect(init).toMatchObject({ method: "POST", redirect: "error", headers: { Authorization: `Bearer ${secret}` } })+ expect(JSON.parse(init!.body as string)).toMatchObject({ runtime: "codex", machineId: "mac1" })+ expect(output).toHaveBeenCalledExactlyOnceWith({ success: { bot: { id: "b1", handle: "Helper#0042" } } })+ })+ it("returns a server URL, never the access code", async () => {+ vi.mocked(fetch).mockResolvedValue(Response.json({ server: { id: "s1", name: "demo", discriminator: "0042", ownerId: "private" } }, { status: 201 }))+ const { run, output } = program()+ await run(["use", "server", "--create", '{"name":"demo"}'])+ expect(output).toHaveBeenCalledExactlyOnceWith({ success: { server: { id: "s1", handle: "demo#0042", url: "http://localhost:4328/c/channels/s1" } } })+ expect(JSON.stringify(output.mock.calls)).not.toContain(secret)+ })+ it("rejects invalid input and insecure remote targets before network I/O", async () => {+ for (const args of [ ["use", "server", "--create", "null"], ["use", "bot", "--create", '{"name":"x"}'], ["use", "--server-url", "http://example.com", "server", "--create", '{"name":"x"}'] ]) {+ await expect(program().run(args)).rejects.toThrow()+ }+ expect(fetch).not.toHaveBeenCalled()+ })+ it("does not retry an unknown creation result or leak secret in server errors", async () => {+ vi.mocked(fetch).mockRejectedValueOnce(new Error("connection reset"))+ await expect(program().run(["use", "server", "--create", '{"name":"demo"}'])).rejects.toThrow("result may be unknown")+ expect(fetch).toHaveBeenCalledOnce()+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({ error: `rejected ${secret}` }, { status: 401 }))+ await expect(program().run(["use", "server", "--create", '{"name":"demo"}'])).rejects.toThrow("rejected [redacted]")+ })+ it("returns rate-limit recovery and refuses redirects", async () => {+ vi.mocked(fetch).mockResolvedValue(Response.json({ error: "Rate limited" }, { status: 429, headers: { "Retry-After": "60" } }))+ await expect(program().run(["use", "server", "--create", '{"name":"demo"}'])).rejects.toMatchObject({ hint: "Retry after 60 seconds" })+ })+ it("lists three minimal identities through their dedicated GET APIs", async () => {+ for (const [kind, path, result, expected] of [+ ["machine", "/api/community/automation/machines", { machines: [{ id: "mac1", name: "Mac", status: "online", backends: [], hostname: "secret-host" }] }, { machines: [{ id: "mac1", name: "Mac", status: "online", backends: [] }] }],+ ["friend", "/api/community/automation/friends", { friends: [{ name: "Alice", handle: "Alice#0001", is_my_bot: false, email: "private" }] }, { friends: [{ name: "Alice", handle: "Alice#0001", is_my_bot: false }] }],+ ["server", "/api/community/automation/servers", { servers: [{ name: "demo", handle: "demo#0001", ownerId: "private", channels: [] }] }, { servers: [{ name: "demo", handle: "demo#0001", channels: [] }] }],+ ] as const) {+ vi.mocked(fetch).mockResolvedValueOnce(Response.json(result))+ const { run, output } = program()+ await run(["use", kind, "--list"])+ expect(vi.mocked(fetch).mock.lastCall).toMatchObject([`http://localhost:4328${path}`, { method: "GET" }])+ expect(output).toHaveBeenCalledExactlyOnceWith({ success: expected })+ }+ })+ it("returns top-level server channel identities and strips unrelated fields", async () => {+ vi.mocked(fetch).mockResolvedValue(Response.json({ servers: [{ name: "demo", handle: "demo#0001", channels: [+ { name: "general", type: "text", ref: "/demo#0001/general", id: "internal", topic: "hidden" },+ { name: "ideas", type: "forum", ref: "/demo#0001/ideas" },+ ] }] }))+ const { run, output } = program()+ await run(["use", "server", "--list"])+ expect(output).toHaveBeenCalledExactlyOnceWith({ success: { servers: [{ name: "demo", handle: "demo#0001", channels: [+ { name: "general", type: "text", ref: "/demo#0001/general" },+ { name: "ideas", type: "forum", ref: "/demo#0001/ideas" },+ ] }] } })+ })+ it("rejects malformed or child-thread server channel results", async () => {+ for (const channels of [undefined, {}, [{ name: "child", type: "thread", ref: "/demo#0001/general/#1" }], [{ name: "general", type: "text" }]]) {+ vi.mocked(fetch).mockResolvedValue(Response.json({ servers: [{ name: "demo", handle: "demo#0001", channels }] }))+ await expect(program().run(["use", "server", "--list"])).rejects.toThrow("invalid server channel list")+ }+ })+ it("preserves own-bot flags and online/offline status while omitting unrelated API fields", async () => {+ const friends = [{ name: "Helper", handle: "Helper#0001", is_my_bot: true }, { name: "Alice", handle: "Alice#0002", is_my_bot: false }]+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({ friends: friends.map((friend) => ({ ...friend, ownerId: "private" })) }))+ const friendCommand = program()+ await friendCommand.run(["use", "friend", "--list"])+ expect(friendCommand.output).toHaveBeenCalledExactlyOnceWith({ success: { friends } })+ const machines = [{ id: "mac1", name: "Running", status: "online", backends: [] }, { id: "mac2", name: "Stopped", status: "offline", backends: [] }]+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({ machines: machines.map((machine) => ({ ...machine, hostname: "private" })) }))+ const machineCommand = program()+ await machineCommand.run(["use", "machine", "--list"])+ expect(machineCommand.output).toHaveBeenCalledExactlyOnceWith({ success: { machines } })+ })+ it("invites one full friend handle through the existing invites endpoint without generic message access", async () => {+ vi.mocked(fetch).mockResolvedValue(Response.json({ invitation: { server: "demo#0001", friend: "Alice#0001", sent: true } }, { status: 201 }))+ const { run, output } = program()+ await run(["use", "server", "--invite", '{"server":"demo#0001","friend":"Alice#0001"}'])+ expect(vi.mocked(fetch).mock.lastCall).toMatchObject(["http://localhost:4328/api/community/automation/servers/demo%230001/invites", { method: "POST", body: '{"friend":"Alice#0001"}' }])+ expect(output).toHaveBeenCalledExactlyOnceWith({ success: { invitation: { server: "demo#0001", friend: "Alice#0001", sent: true } } })+ await expect(program().run(["use", "server", "--list", "--create", '{"name":"demo"}'])).rejects.toThrow("exactly one")+ })+})++describe("Automation CLI input and response recovery", () => {+ it("keeps parent and child help and argument errors silent for the outer JSON handler", async () => {+ const stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true)+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true)+ try {+ for (const [args, code] of [+ [["use", "--help"], "commander.helpDisplayed"],+ [["use", "--unknown"], "commander.unknownOption"],+ [["use", "machine", "--help"], "commander.helpDisplayed"],+ [["use", "machine", "--unknown"], "commander.unknownOption"],+ ] as const) {+ const root = new Command().exitOverride()+ const output = vi.fn()+ registerUseCommands(root, output)+ await expect(root.parseAsync([...args], { from: "user" })).rejects.toMatchObject({ code })+ expect(output).not.toHaveBeenCalled()+ }+ expect(stdout).not.toHaveBeenCalled()+ expect(stderr).not.toHaveBeenCalled()+ expect(fetch).not.toHaveBeenCalled()+ } finally {+ stdout.mockRestore()+ stderr.mockRestore()+ }+ })++ it("reads a private code file before the environment and rejects oversized files", async () => {+ const dir = await mkdtemp(join(tmpdir(), "alook-use-"))+ const file = join(dir, "code")+ try {+ vi.stubEnv("ALOOK_ACCESS_CODE", "wrong")+ await writeFile(file, ` ${secret}\n`, { mode: 0o600 })+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({ machines: [] }))+ await program().run(["use", "--access-code-file", file, "machine", "--list"])+ expect(vi.mocked(fetch).mock.lastCall?.[1]?.headers).toMatchObject({ Authorization: `Bearer ${secret}` })+ await writeFile(file, "x".repeat(1025))+ await expect(program().run(["use", "--access-code-file", file, "machine", "--list"])).rejects.toThrow("file is too large")+ expect(fetch).toHaveBeenCalledOnce()+ } finally { await rm(dir, { recursive: true, force: true }) }+ })++ it("refuses missing credentials, malformed JSON and oversized requests before sending", async () => {+ for (const value of ["", "bad"]) {+ vi.stubEnv("ALOOK_ACCESS_CODE", value)+ await expect(program().run(["use", "machine", "--list"])).rejects.toThrow("Set ALOOK_ACCESS_CODE")+ }+ vi.stubEnv("ALOOK_ACCESS_CODE", secret)+ for (const [value, error] of [["not-json", "Invalid request JSON"], ["x".repeat(131073), "too large"]]) {+ await expect(program().run(["use", "server", "--create", value])).rejects.toThrow(error)+ }+ expect(fetch).not.toHaveBeenCalled()+ })++ it("uses the production default and only sends credentials to a bare approved origin", async () => {+ vi.stubEnv("ALOOK_SERVER_URL", "")+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({ machines: [] }))+ await program().run(["use", "machine", "--list"])+ expect(vi.mocked(fetch).mock.lastCall?.[0]).toBe("https://alook.ai/api/community/automation/machines")+ for (const origin of ["https://[email protected]", "https://:[email protected]", "https://example.com?q=x", "https://example.com#x", "https://example.com/path"]) {+ await expect(program().run(["use", "--server-url", origin, "machine", "--list"])).rejects.toThrow("must be a server origin")+ }+ expect(fetch).toHaveBeenCalledOnce()+ })++ it("reports unreadable and invalid server envelopes without replaying a request", async () => {+ const responses = [new Response("not-json", { status: 502 }), ...[null, [], 42].map((body) => Response.json(body))]+ for (const response of responses) {+ vi.mocked(fetch).mockClear().mockResolvedValueOnce(response)+ await expect(program().run(["use", "machine", "--list"])).rejects.toThrow(/valid result|invalid result/)+ expect(fetch).toHaveBeenCalledOnce()+ }+ vi.mocked(fetch).mockClear().mockRejectedValueOnce(new Error("offline"))+ await expect(program().run(["use", "machine", "--list"])).rejects.toThrow("Automation request failed")+ expect(fetch).toHaveBeenCalledOnce()+ })++ it("keeps safe error codes and retry guidance while redacting the code", async () => {+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({ code: `DENIED_${secret}` }, { status: 503 }))+ await expect(program().run(["use", "machine", "--list"])).rejects.toMatchObject({ message: "Automation failed: HTTP 503", code: "DENIED_[redacted]" })+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({}, { status: 429 }))+ await expect(program().run(["use", "machine", "--list"])).rejects.toMatchObject({ hint: "Retry after the indicated seconds" })+ })++ it("rejects incomplete or malformed minimal list identities", async () => {+ for (const [kind, body] of [+ ["machine", { machines: {} }], ["machine", { machines: [null] }], ["machine", { machines: ["bad"] }],+ ["machine", { machines: [{}] }], ["machine", { machines: [{ name: 1 }] }],+ ["machine", { machines: [{ name: "Mac" }] }], ["machine", { machines: [{ name: "Mac", id: 1 }] }],+ ["machine", { machines: [{ name: "Mac", id: "mac1" }] }],+ ...[null, true, "connected"].map((status) => ["machine", { machines: [{ name: "Mac", id: "mac1", status }] }] as const),+ ["friend", { friends: [{ name: "Alice", handle: 1 }] }],+ ["friend", { friends: [{ name: "Alice", handle: "Alice#0001" }] }],+ ...[null, "true", 1].map((is_my_bot) => ["friend", { friends: [{ name: "Alice", handle: "Alice#0001", is_my_bot }] }] as const),+ ] as const) {+ vi.mocked(fetch).mockResolvedValueOnce(Response.json(body))+ await expect(program().run(["use", kind, "--list"])).rejects.toThrow(/invalid list|invalid identity/)+ }+ })++ it("refuses incomplete invitation receipts instead of claiming a message was sent", async () => {+ for (const invitation of [null, "bad", {}, { sent: false }, { sent: true }, { sent: true, server: 1 }, { sent: true, server: "demo#0001" }, { sent: true, server: "demo#0001", friend: 1 }]) {+ vi.mocked(fetch).mockClear().mockResolvedValueOnce(Response.json({ invitation }))+ await expect(program().run(["use", "server", "--invite", '{"server":"demo#0001","friend":"Alice#0001"}'])).rejects.toThrow("invalid invitation result")+ expect(fetch).toHaveBeenCalledOnce()+ }+ })++ it("refuses incomplete creation receipts instead of inventing a resource identity", async () => {+ for (const server of [null, "bad", {}, { id: "s" }, { id: "s", name: "demo" }, { id: 1, name: "demo", discriminator: "0001" }, { id: "s", name: 1, discriminator: "0001" }, { id: "s", name: "demo", discriminator: 1 }]) {+ vi.mocked(fetch).mockClear().mockResolvedValueOnce(Response.json({ server }))+ await expect(program().run(["use", "server", "--create", '{"name":"demo"}'])).rejects.toThrow("invalid result")+ expect(fetch).toHaveBeenCalledOnce()+ }+ })+})++describe("Automation backend and model reads", () => {+ const backend = { id: "codex", version: "1", health: "healthy", modelRequired: false }+ const catalog = { machineId: "mac/1", backendId: "custom/x", source: "fresh_discovery", requestId: "request", readAt: "2026-10-29T00:00:00Z", observedAt: "2026-10-29T00:00:00Z",+ modelRequired: false, defaultModelId: "provider/a",+ models: [{ id: "provider/a", displayName: "A", reasoningEfforts: [{ value: "high", description: "More" }], defaultReasoningEffort: "high" }] }+ it("keeps backend fields while stripping diagnostics", async () => {+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({ machines: [{ id: "m", name: "M", status: "online", backends: [{ ...backend, catalogState: "reported", catalogOrigin: "native_report", lastError: "private" }] }] }))+ const command = program()+ await command.run(["use", "machine", "--list"])+ expect(command.output).toHaveBeenCalledWith({ success: { machines: [{ id: "m", name: "M", status: "online", backends: [backend] }] } })+ })+ it("rejects missing or malformed backend metadata", async () => {+ for (const backends of [undefined, null, {}, [null], [{ ...backend, health: "up" }], [{ ...backend, modelRequired: "false" }]]) {+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({ machines: [{ id: "m", name: "M", status: "online", backends }] }))+ await expect(program().run(["use", "machine", "--list"])).rejects.toThrow("invalid backend list")+ }+ })+ it("reads the selected backend catalog with encoded targets and projects models and efforts", async () => {+ vi.mocked(fetch).mockImplementationOnce(async (_url, init) => Response.json({ ...catalog, requestId: JSON.parse(init!.body as string).requestId, catalogState: "reported", catalogOrigin: "native_report", private: "hidden", models: catalog.models.map((model) => ({ ...model, private: "hidden" })) }))+ const command = program()+ await command.run(["use", "machine", "--list-models", "--id", "mac/1", "--backend", "custom/x"])+ expect(fetch).toHaveBeenCalledExactlyOnceWith("http://localhost:4328/api/community/automation/machines/mac%2F1/discover-models", expect.objectContaining({ method: "POST", body: expect.any(String) }))+ const requestId = JSON.parse(vi.mocked(fetch).mock.lastCall![1]!.body as string).requestId+ expect(command.output).toHaveBeenCalledExactlyOnceWith({ success: { ...catalog, requestId } })+ })+ it("preserves unreported versus empty catalogs and rejects malformed or mismatched reports", async () => {+ for (const report of [{ ...catalog, source: "cached_report", models: [] }, { ...catalog, models: null, defaultModelId: null }]) {+ vi.mocked(fetch).mockImplementationOnce(async (_url, init) => Response.json({ ...report, requestId: JSON.parse(init!.body as string).requestId }))+ const command = program()+ await command.run(["use", "machine", "--list-models", "--id", "mac/1", "--backend", "custom/x"])+ expect(command.output).toHaveBeenCalledWith({ success: { ...report, requestId: expect.any(String) } })+ }+ for (const report of [{}, { ...catalog, source: "stored_report" }, { ...catalog, machineId: "other" }, { ...catalog, backendId: "other" }, { ...catalog, models: undefined }, { ...catalog, models: [{ id: "x", reasoningEfforts: "high", defaultReasoningEffort: null }] }]) {+ vi.mocked(fetch).mockImplementationOnce(async (_url, init) => Response.json({ ...report, requestId: JSON.parse(init!.body as string).requestId }))+ await expect(program().run(["use", "machine", "--list-models", "--id", "mac/1", "--backend", "custom/x"])).rejects.toThrow("invalid model list")+ }+ })+ it("bypasses the server cache only when --refresh is requested", async () => {+ vi.mocked(fetch).mockImplementationOnce(async (_url, init) => Response.json({ ...catalog, requestId: JSON.parse(init!.body as string).requestId }))+ await program().run(["use", "machine", "--list-models", "--id", "mac/1", "--backend", "custom/x", "--refresh"])+ expect(JSON.parse(vi.mocked(fetch).mock.lastCall![1]!.body as string)).toMatchObject({ runtimeId: "custom/x", refresh: true })+ })+ it("rejects a different request receipt and never retries a failed discovery POST", async () => {+ vi.mocked(fetch).mockResolvedValueOnce(Response.json(catalog))+ await expect(program().run(["use", "machine", "--list-models", "--id", "mac/1", "--backend", "custom/x"])).rejects.toThrow("invalid model list")+ vi.mocked(fetch).mockClear().mockRejectedValueOnce(new Error("connection reset"))+ await expect(program().run(["use", "machine", "--list-models", "--id", "mac/1", "--backend", "custom/x"])).rejects.toThrow("result may be unknown")+ expect(fetch).toHaveBeenCalledOnce()+ })+ it("rejects missing targets, target flags on list and mixed actions before I/O", async () => {+ for (const args of [["--list-models"], ["--list-models", "--id", "m"], ["--list-models", "--backend", "x"], ["--list-models", "--id", " ", "--backend", "x"], ["--list", "--id", "m"], ["--list", "--backend", "x"], ["--list", "--refresh"], ["--list", "--list-models", "--id", "m", "--backend", "x"]]) {+ await expect(program().run(["use", "machine", ...args])).rejects.toThrow(/requires|require|exactly one/)+ }+ expect(fetch).not.toHaveBeenCalled()+ })+})++describe("Automation file message send", () => {+ async function fileRun(bytes: string | Uint8Array, callback: (path: string) => Promise<void>) {+ const dir = await mkdtemp(join(tmpdir(), "alook-use-message-"))+ try {+ const path = join(dir, "message.txt")+ await writeFile(path, bytes)+ await callback(path)+ } finally { await rm(dir, { recursive: true, force: true }) }+ }+ it("sends exact UTF-8 file contents as me or a bot using only the dedicated API", async () => {+ await fileRun("你好\nline two\n", async (path) => {+ for (const identity of ["me", "@Helper#0001"]) {+ vi.mocked(fetch).mockClear().mockResolvedValueOnce(Response.json({ state: "sent", seq: "#1", deduped: false }, { status: 201 }))+ const { run, output } = program()+ await run(["use", "message", "--send", "--target", "/.dm/Alice#0002", "--as", identity, "--file", path])+ expect(fetch).toHaveBeenCalledExactlyOnceWith("http://localhost:4328/api/community/automation/messages", expect.objectContaining({ method: "POST", redirect: "error" }))+ expect(JSON.parse(vi.mocked(fetch).mock.lastCall![1]!.body as string)).toEqual({ target: "/.dm/Alice#0002", as: identity, content: "你好\nline two\n", nonce: expect.any(String) })+ expect(output).toHaveBeenCalledWith({ success: { state: "sent", seq: "#1", deduped: false } })+ }+ })+ })+ it("rejects invalid/missing identities, targets, actions and files before network I/O", async () => {+ await fileRun("valid", async (path) => {+ for (const args of [[], ["--send"], ["--send", "--target", "/demo#0001/general", "--as", "me"], ["--target", "/demo#0001/general", "--as", "me", "--file", path], ["--send", "--target", "id", "--as", "me", "--file", path], ["--send", "--target", "/demo#0001/general", "--as", "Helper#0001", "--file", path], ["--send", "--target", "/demo#0001/general", "--as", "me", "--file", `${path}.missing`]]) {+ await expect(program().run(["use", "message", ...args])).rejects.toThrow()+ }+ })+ for (const bytes of [" ", "x".repeat(4001), "x".repeat(16001), new Uint8Array([0xc3, 0x28])]) {+ await fileRun(bytes, async (path) => {+ await expect(program().run(["use", "message", "--send", "--target", "/demo#0001/general", "--as", "me", "--file", path])).rejects.toThrow()+ })+ }+ expect(fetch).not.toHaveBeenCalled()+ })+ it("rejects a message file that grows beyond its inspected size", async () => {+ await fileRun("x".repeat(16001), async (path) => {+ vi.mocked(stat).mockResolvedValueOnce({ size: 10, isFile: () => true } as never)+ await expect(program().run(["use", "message", "--send", "--target", "/demo#0001/general", "--as", "me", "--file", path])).rejects.toThrow("Message file is too large")+ expect(fetch).not.toHaveBeenCalled()+ })+ })+ it("surfaces blocked sends, malformed receipts and unknown results without retry", async () => {+ await fileRun("body", async (path) => {+ const args = ["use", "message", "--send", "--target", "/demo#0001/general", "--as", "@Helper#0001", "--file", path]+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({ state: "blocked", reason: "unaligned" }))+ await expect(program().run(args)).rejects.toMatchObject({ code: "unaligned" })+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({}))+ await expect(program().run(args)).rejects.toThrow("invalid message result")+ vi.mocked(fetch).mockClear().mockRejectedValueOnce(new Error("reset"))+ await expect(program().run(args)).rejects.toThrow("result may be unknown")+ expect(fetch).toHaveBeenCalledOnce()+ })+ })+})diff --git a/src/daemon/src/cli/use.ts b/src/daemon/src/cli/use.tsnew file mode 100644index 000000000..92634a4c6--- /dev/null+++ b/src/daemon/src/cli/use.ts@@ -0,0 +1,176 @@+import { randomUUID } from "node:crypto"+import type { Command } from "commander"+import { readFile, stat } from "node:fs/promises"+import { z } from "zod"+import { CommunityBotCreateRequestSchema, MAX_SERVER_DESCRIPTION_LENGTH, MAX_SERVER_NAME_LENGTH, parseNameAndTag, AutomationMessageSendSchema, AutomationMessageSentSchema, MAX_MESSAGE_CONTENT_LENGTH } from "@alook/shared"++const BotInput = z.strictObject({+ ...CommunityBotCreateRequestSchema.omit({ runtime: true, image: true }).shape,+ backendId: z.string().min(1).max(64),+})+const ServerInput = z.strictObject({ name: z.string().trim().min(1).max(MAX_SERVER_NAME_LENGTH), description: z.string().max(MAX_SERVER_DESCRIPTION_LENGTH).optional() })+const BackendList = z.array(z.object({+ id: z.string().min(1), version: z.string().optional(), health: z.enum(["healthy", "unhealthy"]),+ modelRequired: z.boolean(),+}))++const ServerChannels = z.array(z.object({ name: z.string().min(1), type: z.enum(["text", "forum"]), ref: z.string().min(1) }))++const ModelList = z.object({+ machineId: z.string().min(1), backendId: z.string().min(1), source: z.enum(["fresh_discovery", "cached_report"]), requestId: z.string().min(1),+ readAt: z.string(), observedAt: z.iso.datetime(), modelRequired: z.boolean(), defaultModelId: z.string().nullable(),+ models: z.array(z.object({ id: z.string().min(1), displayName: z.string().optional(),+ reasoningEfforts: z.array(z.object({ value: z.string().min(1), description: z.string().optional() })),+ defaultReasoningEffort: z.string().nullable(),+ })).nullable(),+})++async function readAccessCode(file: string | undefined): Promise<string> {+ let secret = process.env.ALOOK_ACCESS_CODE?.trim()+ if (file) {+ if ((await stat(file)).size > 1024) throw new Error("Access code file is too large")+ secret = (await readFile(file, "utf8")).trim()+ }+ if (!secret || !/^aac_[a-f0-9]{64}$/.test(secret)) throw new Error("Set ALOOK_ACCESS_CODE or use --access-code-file with an Automation access code")+ return secret+}++function serverOrigin(value: string): string {+ const url = new URL(value)+ if (url.username || url.password || url.search || url.hash || url.pathname !== "/") throw new Error("--server-url must be a server origin")+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) throw new Error("--server-url requires HTTPS, except for local development")+ return url.origin+}++function parseInput<T>(value: string, schema: { safeParse(input: unknown): { success: true; data: T } | { success: false; error: { issues: { path: PropertyKey[]; message: string }[] } } }): T {+ if (Buffer.byteLength(value, "utf8") > 131072) throw new Error("Automation request is too large")+ let input: unknown+ try { input = JSON.parse(value) } catch { throw new Error("Invalid request JSON") }+ const parsed = schema.safeParse(input)+ if (!parsed.success) throw new Error(parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; "))+ return parsed.data+}++const InviteInput = z.strictObject({+ server: z.string().max(128).refine((value) => Boolean(parseNameAndTag(value)), "Use a full server handle"),+ friend: z.string().max(128).refine((value) => Boolean(parseNameAndTag(value)), "Use a full friend handle"),+})++export function registerUseCommands(program: Command, output: (value: { success: unknown }) => void) {+ const use = program.command("use").description("user Automation access: read lists, create resources, invite friends and send messages; no daemon connection required")+ .option("--access-code-file <path>", "read the code from a file instead of ALOOK_ACCESS_CODE")+ .option("--server-url <url>", "server origin (or ALOOK_SERVER_URL; defaults to production)")+ .exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} })+ const request = async (path: string, body?: unknown, timeoutMs = 30_000) => {+ const options = use.opts<{ accessCodeFile?: string; serverUrl?: string }>()+ const origin = serverOrigin(options.serverUrl || process.env.ALOOK_SERVER_URL || "https://alook.ai")+ const secret = await readAccessCode(options.accessCodeFile)+ let response: Response+ try {+ response = await fetch(`${origin}${path}`, {+ method: body === undefined ? "GET" : "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${secret}` },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), redirect: "error", signal: AbortSignal.timeout(timeoutMs),+ })+ } catch { throw new Error(body === undefined ? "Automation request failed" : "Automation request failed; the result may be unknown. Do not retry automatically.") }+ let raw: unknown+ try { raw = await response.json() } catch { throw new Error(`Automation returned HTTP ${response.status} without a valid result; do not retry automatically`) }+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("Automation returned an invalid result")+ const result = raw as Record<string, unknown>+ if (!response.ok) {+ const message = typeof result.error === "string" ? result.error.replaceAll(secret, "[redacted]") : `Automation failed: HTTP ${response.status}`+ throw Object.assign(new Error(message), {+ ...(typeof result.code === "string" ? { code: result.code.replaceAll(secret, "[redacted]") } : {}),+ ...(response.status === 429 ? { hint: `Retry after ${response.headers.get("Retry-After") ?? "the indicated"} seconds` } : {}),+ })+ }+ return { result, origin }+ }+ use.command("expire").description("expire the supplied access code immediately").action(async () => {+ const { result } = await request("/api/community/automation/expire", {})+ if (result.expired !== true) throw new Error("Automation returned an invalid expiration result")+ output({ success: { expired: true } })+ })+ use.command("message").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).description("send a UTF-8 file as yourself or an owned bot")+ .option("--send", "send one message")+ .requiredOption("--target <ref>", "channel or DM ref")+ .requiredOption("--as <identity>", "me or @name#NNNN of your bot")+ .requiredOption("--file <path>", "UTF-8 message body file")+ .action(async (options: { send?: boolean; target: string; as: string; file: string }) => {+ if (!options.send) throw new Error("Use message --send")+ const info = await stat(options.file)+ if (!info.isFile() || info.size > MAX_MESSAGE_CONTENT_LENGTH * 4) throw new Error("Message file is invalid or too large")+ const bytes = await readFile(options.file)+ if (bytes.length > MAX_MESSAGE_CONTENT_LENGTH * 4) throw new Error("Message file is too large")+ const content = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes)+ const body = parseInput(JSON.stringify({ target: options.target, as: options.as, content, nonce: randomUUID() }), AutomationMessageSendSchema)+ const { result } = await request("/api/community/automation/messages", body)+ if (result.state === "blocked") throw Object.assign(new Error("Bot has unread messages; use its normal inbox pull before sending"), { code: "unaligned" })+ const sent = AutomationMessageSentSchema.safeParse(result)+ if (!sent.success) throw new Error("Automation returned an invalid message result")+ output({ success: sent.data })+ })+ for (const kind of ["bot", "server", "machine", "friend"] as const) {+ const command = use.command(kind).description(`Automation ${kind} operations`).exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} })+ if (kind === "bot" || kind === "server") command.option("--create <json>", kind === "bot" ? "bot JSON: name, machineId, backendId, optional description/model/reasoningEffort" : "server JSON: name, optional description")+ if (kind !== "bot") command.option("--list", `list minimal ${kind} identities`)+ if (kind === "machine") command.option("--list-models", "fetch fresh backend models and reasoning efforts").option("--refresh", "bypass the five-minute model cache").option("--id <machine-id>", "target machine ID for --list-models").option("--backend <backend-id>", "target backend ID for --list-models")+ if (kind === "server") command.option("--invite <json>", "invite JSON: server and friend full handles")+ command.action(async () => {+ const options = command.opts<{ create?: string; list?: boolean; invite?: string; listModels?: boolean; id?: string; backend?: string; refresh?: boolean }>()+ if ([options.create !== undefined, options.list === true, options.invite !== undefined, options.listModels === true].filter(Boolean).length !== 1) throw new Error("Choose exactly one action: --create, --list, --invite, or --list-models")+ if (options.listModels) {+ if (!options.id?.trim() || !options.backend?.trim()) throw new Error("--list-models requires --id and --backend")+ const requestId = randomUUID()+ const { result } = await request(`/api/community/automation/machines/${encodeURIComponent(options.id)}/discover-models`, { requestId, runtimeId: options.backend, ...(options.refresh ? { refresh: true } : {}) }, 55_000)+ const parsed = ModelList.safeParse(result)+ if (!parsed.success || parsed.data.machineId !== options.id || parsed.data.backendId !== options.backend || parsed.data.requestId !== requestId) throw new Error("Automation returned an invalid model list")+ output({ success: parsed.data })+ return+ }+ if (options.id !== undefined || options.backend !== undefined || options.refresh) throw new Error("--id, --backend and --refresh require --list-models")+ if (options.list) {+ const key = `${kind}s`+ const { result } = await request(kind === "friend" ? "/api/community/automation/friends" : `/api/community/automation/${key}`)+ const rows = result[key]+ if (!Array.isArray(rows)) throw new Error("Automation returned an invalid list")+ const list = rows.map((row: unknown) => {+ if (!row || typeof row !== "object" || !("name" in row) || typeof row.name !== "string") throw new Error("Automation returned an invalid identity")+ if (kind === "machine" && "id" in row && typeof row.id === "string" && "status" in row && (row.status === "online" || row.status === "offline")) {+ const backends = BackendList.safeParse("backends" in row ? row.backends : undefined)+ if (!backends.success) throw new Error("Automation returned an invalid backend list")+ return { id: row.id, name: row.name, status: row.status, backends: backends.data }+ }+ if (kind === "friend" && "handle" in row && typeof row.handle === "string" && "is_my_bot" in row && typeof row.is_my_bot === "boolean") return { name: row.name, handle: row.handle, is_my_bot: row.is_my_bot }+ if (kind === "server" && "handle" in row && typeof row.handle === "string") {+ const channels = ServerChannels.safeParse("channels" in row ? row.channels : undefined)+ if (!channels.success) throw new Error("Automation returned an invalid server channel list")+ return { name: row.name, handle: row.handle, channels: channels.data }+ }+ throw new Error("Automation returned an invalid identity")+ })+ output({ success: { [key]: list } })+ return+ }+ if (options.invite !== undefined) {+ const input = parseInput(options.invite, InviteInput)+ const { result } = await request(`/api/community/automation/servers/${encodeURIComponent(input.server)}/invites`, { friend: input.friend })+ const value = result.invitation+ if (!value || typeof value !== "object" || !("sent" in value) || value.sent !== true || !("server" in value) || typeof value.server !== "string" || !("friend" in value) || typeof value.friend !== "string") throw new Error("Automation returned an invalid invitation result; do not retry automatically")+ output({ success: { invitation: { server: value.server, friend: value.friend, sent: true } } })+ return+ }+ let body: unknown+ if (kind === "bot") {+ const { backendId, ...bot } = parseInput(options.create!, BotInput)+ body = { ...bot, runtime: backendId }+ } else body = parseInput(options.create!, ServerInput)+ const { result, origin } = await request(`/api/community/automation/${kind}s`, body)+ const resource = result[kind]+ if (!resource || typeof resource !== "object" || !("id" in resource) || !("name" in resource) || !("discriminator" in resource) || typeof resource.id !== "string" || typeof resource.name !== "string" || typeof resource.discriminator !== "string") throw new Error("Automation returned an invalid result; do not retry automatically")+ output({ success: { [kind]: { id: resource.id, handle: `${resource.name}#${resource.discriminator}`,+ ...(kind === "server" ? { url: `${origin}/c/channels/${encodeURIComponent(resource.id)}` } : {}),+ } } })+ })+ }+}diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.tsindex 8e867f2d6..85d64f294 100644--- a/src/daemon/src/credentials/credentialProxy.test.ts+++ b/src/daemon/src/credentials/credentialProxy.test.ts@@ -249,6 +249,40 @@ describe("startCredentialProxy (zero-trust end to end)", () => {upstreamClose = undefined;});+ it("preserves waiting model query/body with a read voucher and gives only that route a longer timeout", async () => {+ const upstream = await startUpstream()+ upstreamClose = upstream.close+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url })+ proxy = await startCredentialProxy(broker)+ const reg = broker.mint("requester", "model-wait", ["read"], REAL_KEY)+ const timeout = vi.spyOn(http.ClientRequest.prototype, "setTimeout")+ try {+ const body = JSON.stringify({ requestId: "request", runtimeId: "codex", refresh: true })+ for (const path of ["/api/community/machines/m1/discover-models?wait=1&model=provider%2Fmodel", "/api/community/machines/m1/discover-models", "/api/community/machines/m1/models?backend=codex"]) {+ const method = path.includes("discover-models") ? "POST" : "GET"+ const response = await fetch(`${proxy.url}${path}`, { method, headers: { authorization: `Bearer ${reg.voucher}`, "content-type": "application/json" }, ...(method === "POST" ? { body } : {}) })+ expect(response.status).toBe(200)+ await response.text()+ }+ expect(timeout.mock.calls.map((call) => call[0])).toEqual([55_000, 20_000, 20_000])+ expect(upstream.seen[0]).toMatchObject({ path: "/api/community/machines/m1/discover-models?wait=1&model=provider%2Fmodel", body, authorization: `Bearer ${REAL_KEY}` })+ } finally { timeout.mockRestore(); broker.revoke(reg.voucher) }+ })++ it("keeps an explicit upstream timeout override for waiting model requests", async () => {+ const upstream = await startUpstream()+ upstreamClose = upstream.close+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url })+ proxy = await startCredentialProxy(broker, { upstreamTimeoutMs: 1234 })+ const reg = broker.mint("requester", "model-override", ["read"], REAL_KEY)+ const timeout = vi.spyOn(http.ClientRequest.prototype, "setTimeout")+ try {+ const response = await fetch(`${proxy.url}/api/community/machines/m1/discover-models?wait=1`, { method: "POST", headers: { authorization: `Bearer ${reg.voucher}` } })+ await response.text()+ expect(timeout.mock.calls.map((call) => call[0])).toEqual([1234])+ } finally { timeout.mockRestore(); broker.revoke(reg.voucher) }+ })+it("permits platform discovery and proposals but rejects machine management before forwarding", async () => {const upstream = await startUpstream();upstreamClose = upstream.close;diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.tsindex e5a430e8b..b5bacdfbf 100644--- a/src/daemon/src/credentials/credentialProxy.ts+++ b/src/daemon/src/credentials/credentialProxy.ts@@ -548,7 +548,8 @@ export async function startCredentialProxy(};const server = http.createServer(async (req, res) => {- const pathname = new URL(req.url ?? "/", "http://placeholder").pathname;+ const requestUrl = new URL(req.url ?? "/", "http://placeholder");+ const pathname = requestUrl.pathname;if (pathname === LOCAL_PII_PATH && (req.method === "GET" || req.method === "POST")) {const localVerdict = broker.check(req.headers["authorization"], req.method === "GET" ? "read" : "send");if (!localVerdict.ok) { writeJson(res, localVerdict.status, { error: localVerdict.error, code: localVerdict.code }); req.resume(); return; }@@ -856,7 +857,8 @@ export async function startCredentialProxy(// so it keeps firing across the whole exchange, not just while waiting// for headers — always destroy, but only write a 504 if we haven't// already committed to a response.- const upstreamTimeoutMs = options.upstreamTimeoutMs ?? DEFAULT_UPSTREAM_TIMEOUT_MS;+ const waitingForModels = req.method === "POST" && /^\/api\/community\/machines\/[^/]+\/discover-models$/.test(pathname) && requestUrl.searchParams.get("wait") === "1";+ const upstreamTimeoutMs = options.upstreamTimeoutMs ?? (waitingForModels ? 55_000 : DEFAULT_UPSTREAM_TIMEOUT_MS);upstreamReq.setTimeout(upstreamTimeoutMs, () => {upstreamReq.destroy();upstreamRes?.destroy();diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.tsindex 27dfe7493..649bfb97e 100644--- a/src/daemon/src/drivers/systemPrompt.ts+++ b/src/daemon/src/drivers/systemPrompt.ts@@ -169,7 +169,7 @@ function cliCommandsSection(): string {"",`1. \`${CLI} platform machine --list\` — list your owner's machines.`,`2. \`${CLI} platform machine --backends --id <machine-id>\` — read the selected online machine's backends.`,- `3. \`${CLI} platform machine --models --id <machine-id> --backend <backend-id> [--model <full-model-id>] [--refresh]\` — read reported models and model-specific effort options. \`--refresh\` only dispatches an asynchronous refresh; read once later without \`--refresh\` for the stored report. Do not poll.`,+ `3. \`${CLI} platform machine --models --id <machine-id> --backend <backend-id> [--model <full-model-id>] [--refresh]\` — read models and model-specific effort options using a five-minute server cache. A cache miss or expiry fetches fresh models and waits for the result; \`--refresh\` bypasses the cache. Failures do not return an old list. Do not poll.`,`4. \`${CLI} platform bot --list\` — list your owner's bots.`,`5. \`${CLI} platform bot --create '<bot-json>'\` — request new bots for your owner. Each JSON requires \`name\`, \`machineId\`, \`backendId\` and \`reason\`; optional fields are \`description\`, \`model\` and \`reasoningEffort\`. ` +`Use an online machine and its backend. The \`reason\` explains to your owner why the bot is needed and what work it will do; this text appears on the approval card. Repeat \`--create\` for up to 20 bots in one request. ` +diff --git a/src/shared/src/automation.ts b/src/shared/src/automation.tsnew file mode 100644index 000000000..2c57c9aa6--- /dev/null+++ b/src/shared/src/automation.ts@@ -0,0 +1,63 @@+import { z } from "zod"+import { MAX_MESSAGE_CONTENT_LENGTH } from "./constants/community"+import { parseNameAndTag } from "./lib/discriminator"+import { parseRef } from "./community-cli-contract"++export const AUTOMATION_WRITE_PERMISSIONS = ["bot.create", "server.create", "server.invite", "message.send"] as const+export const AUTOMATION_READ_PERMISSIONS = ["machine.read", "friend.read", "server.read"] as const+export const AutomationPermissionSchema = z.enum([...AUTOMATION_WRITE_PERMISSIONS, ...AUTOMATION_READ_PERMISSIONS])+export const AutomationExpirySchema = z.enum(["1h", "24h", "7d", "30d", "forever"])+export const AutomationPermissionPolicySchema = z.strictObject({+ permission: AutomationPermissionSchema,+ limit: z.number().int().positive(),+ period: z.enum(["hour", "day"]),+}).refine((value) => value.limit <= (value.period === "hour" ? 64 : 1536), {+ message: "Limit cannot exceed 64/hour or 1536/day", path: ["limit"],+})+const permissions = z.array(AutomationPermissionPolicySchema).min(1).max(AutomationPermissionSchema.options.length)+ .refine((values) => new Set(values.map((value) => value.permission)).size === values.length, "Duplicate permission")+export const AutomationAccessCodeCreateSchema = z.strictObject({+ name: z.string().trim().min(1).max(100),+ expiresIn: AutomationExpirySchema.default("24h"),+ permissions,+})+export const AutomationAccessCodeUpdateSchema = z.strictObject({+ name: z.string().trim().min(1).max(100).optional(),+ expiresIn: AutomationExpirySchema.optional(),+ permissions: permissions.optional(),+}).refine((value) => Object.keys(value).length > 0, "Provide at least one change")++export type AutomationPermission = z.infer<typeof AutomationPermissionSchema>+export type AutomationPermissionPolicy = z.infer<typeof AutomationPermissionPolicySchema>+export type AutomationExpiry = z.infer<typeof AutomationExpirySchema>+export type AutomationAccessCodeCreate = z.infer<typeof AutomationAccessCodeCreateSchema>+export type AutomationAccessCodeUpdate = z.infer<typeof AutomationAccessCodeUpdateSchema>+export interface AutomationAccessCode {+ id: string+ name: string+ createdAt: string+ expiresAt: string | null+ permissions: AutomationPermissionPolicy[]+}+export interface AutomationAccessCodeListResponse { accessCodes: AutomationAccessCode[] }+export interface AutomationAccessCodeCreateResponse { accessCode: AutomationAccessCode; secret: string }+export interface AutomationAccessCodeUpdateResponse { accessCode: AutomationAccessCode }++export function automationExpiresAt(expiry: AutomationExpiry, now = Date.now()): string | null {+ const hours = { "1h": 1, "24h": 24, "7d": 168, "30d": 720, forever: null }[expiry]+ return hours === null ? null : new Date(now + hours * 3_600_000).toISOString()+}++export const AutomationMessageSendSchema = z.strictObject({+ target: z.string().min(1).max(1024).refine((value) => { try { parseRef(value); return true } catch { return false } }, "Use a channel or DM ref"),+ as: z.string().max(128).refine((value) => value === "me" || value.startsWith("@") && Boolean(parseNameAndTag(value.slice(1))), "Use me or @name#NNNN"),+ content: z.string().max(MAX_MESSAGE_CONTENT_LENGTH).refine((value) => value.trim().length > 0, "Message content is required"),+ nonce: z.string().min(1).max(128),+})++export const AutomationMessageSentSchema = z.object({+ state: z.literal("sent"),+ seq: z.string().regex(/^#[1-9]\d*$/),+ deduped: z.boolean(),+ threadId: z.string().optional(),+})diff --git a/src/shared/src/db/automation-schema.ts b/src/shared/src/db/automation-schema.tsnew file mode 100644index 000000000..0cebba06f--- /dev/null+++ b/src/shared/src/db/automation-schema.ts@@ -0,0 +1,19 @@+import { index, integer, primaryKey, sqliteTable, text } from "drizzle-orm/sqlite-core"+import { user } from "./schema"+import type { AutomationPermission } from "../automation"++export const automationAccessCode = sqliteTable("automation_access_code", {+ id: text("id").primaryKey(),+ ownerId: text("owner_id").notNull().references(() => user.id, { onDelete: "cascade" }),+ name: text("name").notNull(),+ secretHash: text("secret_hash").notNull().unique(),+ expiresAt: text("expires_at"),+ createdAt: text("created_at").notNull(),+}, (table) => [index("idx_automation_code_owner").on(table.ownerId)])++export const automationAccessPermission = sqliteTable("automation_access_permission", {+ codeId: text("code_id").notNull().references(() => automationAccessCode.id, { onDelete: "cascade" }),+ permission: text("permission").$type<AutomationPermission>().notNull(),+ limit: integer("request_limit").notNull(),+ period: text("period", { enum: ["hour", "day"] }).notNull(),+}, (table) => [primaryKey({ columns: [table.codeId, table.permission] })])diff --git a/src/shared/src/db/index.ts b/src/shared/src/db/index.tsindex 7f3e90660..38d017346 100644--- a/src/shared/src/db/index.ts+++ b/src/shared/src/db/index.ts@@ -6,8 +6,9 @@ import * as billingSchema from "./billing-schema";import * as productPlanSchema from "./product-plan-schema";import * as communityFunnelAnalyticsSchema from "./community-funnel-analytics-schema";import * as botCreationSchema from "./bot-creation-schema";+import * as automationSchema from "./automation-schema";-const allSchema = { ...schema, ...communitySchema, ...communityMachineSchema, ...productPlanSchema, ...billingSchema, ...communityFunnelAnalyticsSchema, ...botCreationSchema };+const allSchema = { ...schema, ...communitySchema, ...communityMachineSchema, ...productPlanSchema, ...billingSchema, ...communityFunnelAnalyticsSchema, ...botCreationSchema, ...automationSchema };export function createDb(d1: AnyD1Database) {return drizzle(d1, { schema: allSchema });diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.tsindex 834ade925..75e6b62ba 100644--- a/src/shared/src/db/queries-index.ts+++ b/src/shared/src/db/queries-index.ts@@ -1,4 +1,5 @@import * as nativeOauthQueries from "./queries/native-oauth";+export * as automation from "./queries/automation";export * as user from "./queries/user";export * as member from "./queries/member";diff --git a/src/shared/src/db/queries/automation.ts b/src/shared/src/db/queries/automation.tsnew file mode 100644index 000000000..b6c0d5814--- /dev/null+++ b/src/shared/src/db/queries/automation.ts@@ -0,0 +1,121 @@+import { and, asc, desc, eq, exists, gt, inArray, isNull, ne, or } from "drizzle-orm"+import { nanoid } from "nanoid"+import { automationAccessCode as code, automationAccessPermission as policy } from "../automation-schema"+import { user } from "../schema"+import { communityMachine } from "../community-machine-schema"+import { communityFriendship } from "../community-schema"+import { parseNameAndTag } from "../../lib/discriminator"+import type { Database } from "../index"+import { automationExpiresAt, type AutomationAccessCode, type AutomationAccessCodeCreate, type AutomationAccessCodeUpdate, type AutomationPermission } from "../../automation"++const publicFields = { id: code.id, name: code.name, createdAt: code.createdAt, expiresAt: code.expiresAt }++export async function listAccessCodes(db: Database, ownerId: string, now = new Date().toISOString()): Promise<AutomationAccessCode[]> {+ const rows = await db.select({ ...publicFields, permission: policy.permission, limit: policy.limit, period: policy.period })+ .from(code).leftJoin(policy, eq(policy.codeId, code.id)).where(and(eq(code.ownerId, ownerId), or(isNull(code.expiresAt), gt(code.expiresAt, now))))+ .orderBy(desc(code.createdAt), asc(policy.permission))+ const codes = new Map<string, AutomationAccessCode>()+ for (const row of rows) {+ let item = codes.get(row.id)+ if (!item) {+ item = { id: row.id, name: row.name, createdAt: row.createdAt, expiresAt: row.expiresAt, permissions: [] }+ codes.set(row.id, item)+ }+ if (row.permission && row.limit !== null && row.period) item.permissions.push({ permission: row.permission, limit: row.limit, period: row.period })+ }+ return [...codes.values()]+}++export async function getAccessCode(db: Database, ownerId: string, id: string): Promise<AutomationAccessCode | null> {+ const [row] = await db.select(publicFields).from(code).where(and(eq(code.ownerId, ownerId), eq(code.id, id)))+ if (!row) return null+ const permissions = await db.select({ permission: policy.permission, limit: policy.limit, period: policy.period }).from(policy)+ .where(and(eq(policy.codeId, id), inArray(policy.codeId, db.select({ id: code.id }).from(code).where(eq(code.ownerId, ownerId)))))+ .orderBy(asc(policy.permission))+ return { ...row, permissions }+}++export async function createAccessCode(db: Database, ownerId: string, input: AutomationAccessCodeCreate, secretHash: string): Promise<AutomationAccessCode> {+ const row = { id: nanoid(), ownerId, name: input.name, secretHash, createdAt: new Date().toISOString(), expiresAt: automationExpiresAt(input.expiresIn) }+ await db.batch([+ db.insert(code).values(row),+ db.insert(policy).values(input.permissions.map((permission) => ({ ...permission, codeId: row.id }))),+ ])+ return { id: row.id, name: row.name, createdAt: row.createdAt, expiresAt: row.expiresAt, permissions: input.permissions }+}++export async function updateAccessCode(db: Database, ownerId: string, id: string, input: AutomationAccessCodeUpdate): Promise<AutomationAccessCode | null> {+ const current = await getAccessCode(db, ownerId, id)+ if (!current) return null+ const owned = and(eq(code.ownerId, ownerId), eq(code.id, id))+ const fields = {+ ...(input.name === undefined ? {} : { name: input.name }),+ ...(input.expiresIn === undefined ? {} : { expiresAt: automationExpiresAt(input.expiresIn) }),+ }+ if (input.permissions) {+ const remove = db.delete(policy).where(inArray(policy.codeId, db.select({ id: code.id }).from(code).where(owned)))+ const insert = db.insert(policy).values(input.permissions.map((permission) => ({ ...permission, codeId: id })))+ if (Object.keys(fields).length) await db.batch([db.update(code).set(fields).where(owned), remove, insert])+ else await db.batch([remove, insert])+ } else if (Object.keys(fields).length) await db.update(code).set(fields).where(owned)+ return getAccessCode(db, ownerId, id)+}++export async function deleteAccessCode(db: Database, ownerId: string, id: string): Promise<boolean> {+ const rows = await db.delete(code).where(and(eq(code.ownerId, ownerId), eq(code.id, id))).returning({ id: code.id })+ return rows.length > 0+}++export async function expireAccessCode(db: Database, secretHash: string, now = new Date().toISOString()): Promise<boolean> {+ const rows = await db.update(code).set({ expiresAt: now }).where(and(+ eq(code.secretHash, secretHash), or(isNull(code.expiresAt), gt(code.expiresAt, now)),+ exists(db.select({ id: user.id }).from(user).where(and(eq(user.id, code.ownerId), eq(user.isBot, false), isNull(user.deletedAt)))),+ )).returning({ id: code.id })+ return rows.length > 0+}++export async function authenticateAccessCode(db: Database, secretHash: string, permission: AutomationPermission, now = new Date().toISOString()) {+ const [row] = await db.select({ codeId: code.id, ownerId: code.ownerId, permission: policy.permission, limit: policy.limit, period: policy.period })+ .from(code).innerJoin(policy, and(eq(policy.codeId, code.id), eq(policy.permission, permission)))+ .innerJoin(user, and(eq(user.id, code.ownerId), eq(user.isBot, false), isNull(user.deletedAt)))+ .where(and(eq(code.secretHash, secretHash), or(isNull(code.expiresAt), gt(code.expiresAt, now))))+ return row ?? null+}++export function listMachines(db: Database, ownerId: string) {+ return db.select({ id: communityMachine.id, name: communityMachine.displayName, status: communityMachine.status, availableRuntimes: communityMachine.availableRuntimes }).from(communityMachine)+ .where(eq(communityMachine.userId, ownerId)).orderBy(asc(communityMachine.id))+}++function friendScope(db: Database, ownerId: string) {+ return and(isNull(user.deletedAt), ne(user.id, ownerId), or(+ and(eq(user.isBot, true), eq(user.ownerUserId, ownerId)),+ inArray(user.id, db.select({ id: communityFriendship.addresseeId }).from(communityFriendship)+ .where(and(eq(communityFriendship.status, "accepted"), eq(communityFriendship.requesterId, ownerId)))),+ inArray(user.id, db.select({ id: communityFriendship.requesterId }).from(communityFriendship)+ .where(and(eq(communityFriendship.status, "accepted"), eq(communityFriendship.addresseeId, ownerId)))),+ ))+}++export function listFriends(db: Database, ownerId: string) {+ return db.select({ name: user.name, discriminator: user.discriminator, isBot: user.isBot, ownerUserId: user.ownerUserId }).from(user)+ .where(friendScope(db, ownerId)).orderBy(asc(user.name), asc(user.discriminator))+}++export async function getFriendByHandle(db: Database, ownerId: string, handle: string) {+ const parsed = parseNameAndTag(handle)+ if (!parsed) return null+ const [row] = await db.select({ id: user.id, name: user.name, discriminator: user.discriminator }).from(user)+ .where(and(friendScope(db, ownerId), eq(user.name, parsed.name), eq(user.discriminator, parsed.discriminator)))+ return row ?? null+}++export async function getOwnedBotByHandle(db: Database, ownerId: string, handle: string) {+ const parsed = parseNameAndTag(handle)+ if (!parsed) return null+ const [row] = await db.select({ id: user.id }).from(user).where(and(+ eq(user.ownerUserId, ownerId), eq(user.isBot, true), isNull(user.deletedAt),+ eq(user.name, parsed.name), eq(user.discriminator, parsed.discriminator),+ )).limit(1)+ return row ?? null+}diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex 7d660c2ad..0b2824693 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -1570,7 +1570,10 @@ export async function getMachineForOwner(// Normalize: legacy rows store `string[]`, current rows store// `{id, version?, status?, lastError?, lastErrorAt?}[]`. Drop empty ids so// the route's `.includes()` / `.find()` checks can't be fooled by `""`.- const raw = (r.availableRuntimes ?? []) as Array<unknown>;+ return { id: r.id, displayName: r.displayName, status: r.status, availableRuntimes: normalizeMachineRuntimes(r.availableRuntimes ?? []) };+}++export function normalizeMachineRuntimes(raw: unknown[]): CommunityMachineRuntime[] {const normalized: CommunityMachineRuntime[] = [];for (const entry of raw) {if (typeof entry === "string") {@@ -1580,5 +1583,5 @@ export async function getMachineForOwner(if (parsed.success) normalized.push(parsed.data);}}- return { id: r.id, displayName: r.displayName, status: r.status, availableRuntimes: normalized };+ return normalized;}diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.tsindex defd481e2..729f514f5 100644--- a/src/shared/src/db/queries/community/channel.ts+++ b/src/shared/src/db/queries/community/channel.ts@@ -1107,7 +1107,7 @@ export function groupChannelRefDirectoryRows(}));}-export async function listChannelRefDirectoryForUser(db: Database, userId: string) {+export async function listChannelRefDirectoryForUser(db: Database, userId: string, options: { railOrder?: boolean } = {}) {const [servers, channels] = await Promise.all([db.select({@@ -1168,7 +1168,7 @@ export async function listChannelRefDirectoryForUser(db: Database, userId: strinasc(communityChannel.id)),]);- return groupChannelRefDirectoryRows(sortServerRailRows(await readServerRailSnapshot(db, userId), servers), channels);+ return groupChannelRefDirectoryRows(options.railOrder === false ? servers : sortServerRailRows(await readServerRailSnapshot(db, userId), servers), channels);}// Shared visibility computation for the nested-membership model. Assembles thediff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex fdf9ffb64..3a6ec946a 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -1,4 +1,5 @@// Types+export * from "./automation";export type {User,Workspace,diff --git a/src/shared/src/runtime-models-contract.ts b/src/shared/src/runtime-models-contract.tsindex 0b987aa9f..6729f4f4e 100644--- a/src/shared/src/runtime-models-contract.ts+++ b/src/shared/src/runtime-models-contract.ts@@ -23,3 +23,13 @@ export type RuntimeModelDiscoveryError = z.infer<typeof RuntimeModelDiscoveryErrexport type RuntimeModelDiscoveryResult =| { status: "complete"; catalog: RuntimeReasoningCatalog | null }| RuntimeModelDiscoveryError;++export const RUNTIME_MODEL_CATALOG_FINGERPRINT_HEADER = "x-model-catalog-fingerprint";++export async function fingerprintRuntimeModelCatalog(catalog: RuntimeReasoningCatalog | null): Promise<string> {+ const canonical = JSON.stringify(catalog, (_key, value) => value && typeof value === "object" && !Array.isArray(value)+ ? Object.fromEntries(Object.keys(value).sort().map((key) => [key, value[key]]))+ : value);+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical));+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");+}diff --git a/src/shared/test/automation.test.ts b/src/shared/test/automation.test.tsnew file mode 100644index 000000000..002a86a95--- /dev/null+++ b/src/shared/test/automation.test.ts@@ -0,0 +1,236 @@+import { afterEach, describe, expect, it } from "vitest"+import { readFileSync } from "node:fs"+import { getTableName } from "drizzle-orm"+import { getTableConfig } from "drizzle-orm/sqlite-core"+import { communityWriteDb } from "./helpers/community-write-db"+import * as queries from "../src/db/queries/automation"+import { automationAccessCode, automationAccessPermission } from "../src/db/automation-schema"+import { AutomationAccessCodeCreateSchema, AutomationAccessCodeUpdateSchema, automationExpiresAt, AutomationPermissionSchema, AutomationMessageSendSchema } from "../src/automation"++const databases: ReturnType<typeof communityWriteDb>[] = []+function fixture() {+ const value = communityWriteDb()+ value.sqlite.exec(readFileSync(new URL("../../web/migrations/0110_automation_access_code.sql", import.meta.url), "utf8"))+ databases.push(value)+ return value+}+afterEach(() => { for (const value of databases.splice(0)) value.sqlite.close() })+const input = () => AutomationAccessCodeCreateSchema.parse({ name: "Work", expiresIn: "24h", permissions: [{ permission: "bot.create", limit: 64, period: "hour" }, { permission: "server.create", limit: 100, period: "day" }] })++describe("Automation access codes", () => {+ it("enforces fixed expiry choices, integer rates, caps and unique granted permissions", () => {+ for (const data of [ { ...input(), expiresIn: "2h" }, { ...input(), permissions: [] }, { ...input(), permissions: [input().permissions[0], input().permissions[0]] }, ...[0, 1.5, 65].map((limit) => ({ ...input(), permissions: [{ permission: "bot.create", limit, period: "hour" }] })), { ...input(), permissions: [{ permission: "server.create", limit: 1537, period: "day" }] } ]) {+ expect(AutomationAccessCodeCreateSchema.safeParse(data).success).toBe(false)+ }+ expect(AutomationAccessCodeUpdateSchema.safeParse({}).success).toBe(false)+ expect(automationExpiresAt("forever")).toBeNull()+ expect(automationExpiresAt("7d", 0)).toBe("1970-01-08T00:00:00.000Z")+ })++ it("persists a hash and independent policies, while omitting private fields from management results", async () => {+ const { db, sqlite, batchSizes } = fixture()+ const code = await queries.createAccessCode(db, "author", input(), "digest")+ expect(await queries.listAccessCodes(db, "peer")).toEqual([])+ expect(await queries.getAccessCode(db, "peer", code.id)).toBeNull()+ const list = await queries.listAccessCodes(db, "author")+ expect(list).toEqual([code])+ expect(JSON.stringify(list)).not.toContain("digest")+ expect(list[0]).not.toHaveProperty("ownerId")+ expect(list[0]).not.toHaveProperty("prefix")+ expect(sqlite.prepare("PRAGMA table_info(automation_access_code)").all()).not.toEqual(expect.arrayContaining([expect.objectContaining({ name: "prefix" })]))+ expect(batchSizes).toEqual([[6, 8]])+ expect(sqlite.prepare("SELECT secret_hash FROM automation_access_code").get()).toEqual({ secret_hash: "digest" })+ expect(await queries.authenticateAccessCode(db, "digest", "server.create")).toMatchObject({ ownerId: "author", limit: 100, period: "day" })+ expect(await queries.authenticateAccessCode(db, "wrong", "bot.create")).toBeNull()+ })++ it("lists only unexpired owned codes without deleting expired records", async () => {+ const { db, sqlite } = fixture()+ const now = "2026-10-30T04:00:00.000Z"+ const codes = await Promise.all(["past", "boundary", "future", "permanent", "peer"].map((name) =>+ queries.createAccessCode(db, name === "peer" ? "peer" : "author", { ...input(), name }, name)))+ const expires = ["2026-10-30T03:59:59.999Z", now, "2026-10-30T04:00:00.001Z", null, null]+ for (const [index, code] of codes.entries()) sqlite.prepare("UPDATE automation_access_code SET expires_at = ? WHERE id = ?").run(expires[index], code.id)+ const listed = await queries.listAccessCodes(db, "author", now)+ expect(listed.map((code) => code.name).sort()).toEqual(["future", "permanent"])+ expect(listed.every((code) => code.permissions.length === 2)).toBe(true)+ expect(await queries.authenticateAccessCode(db, "past", "bot.create", now)).toBeNull()+ expect(await queries.authenticateAccessCode(db, "boundary", "bot.create", now)).toBeNull()+ expect(await queries.getAccessCode(db, "author", codes[0].id)).toMatchObject({ name: "past" })+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM automation_access_code").get()).toEqual({ count: 5 })+ })++ it("atomically expires only the presented active code without requiring a grant", async () => {+ const { db, sqlite } = fixture()+ const code = await queries.createAccessCode(db, "author", { ...input(), expiresIn: "forever" }, "self-digest")+ const peer = await queries.createAccessCode(db, "peer", input(), "peer-digest")+ sqlite.prepare("DELETE FROM automation_access_permission WHERE code_id = ?").run(code.id)+ const now = "2026-10-30T04:00:00.000Z"+ expect(await queries.expireAccessCode(db, "unknown", now)).toBe(false)+ expect(await queries.expireAccessCode(db, "self-digest", now)).toBe(true)+ expect(await queries.expireAccessCode(db, "self-digest", now)).toBe(false)+ expect(await queries.getAccessCode(db, "author", code.id)).toMatchObject({ expiresAt: now })+ expect(await queries.getAccessCode(db, "peer", peer.id)).toEqual(peer)+ expect(await queries.listAccessCodes(db, "author", now)).toEqual([])+ expect(await queries.authenticateAccessCode(db, "self-digest", "bot.create", now)).toBeNull()+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM automation_access_code").get()).toEqual({ count: 2 })+ })++ it("does not self-expire codes that are expired or owned by retired humans or bots", async () => {+ const { db, sqlite } = fixture()+ const code = await queries.createAccessCode(db, "author", input(), "self-digest")+ expect(await queries.expireAccessCode(db, "self-digest", code.expiresAt!)).toBe(false)+ sqlite.prepare("UPDATE user SET deletedAt = 'deleted' WHERE id = 'author'").run()+ expect(await queries.expireAccessCode(db, "self-digest")).toBe(false)+ sqlite.prepare("UPDATE user SET deletedAt = NULL, isBot = 1 WHERE id = 'author'").run()+ expect(await queries.expireAccessCode(db, "self-digest")).toBe(false)+ expect(await queries.getAccessCode(db, "author", code.id)).toEqual(code)+ })++ it("scopes edits and deletion, preserves expiry on policy edits and revokes removed policies", async () => {+ const { db, sqlite } = fixture()+ const code = await queries.createAccessCode(db, "author", input(), "digest")+ expect(await queries.updateAccessCode(db, "peer", code.id, { name: "Stolen" })).toBeNull()+ expect(await queries.deleteAccessCode(db, "peer", code.id)).toBe(false)+ const edited = await queries.updateAccessCode(db, "author", code.id, { permissions: [{ permission: "server.create", limit: 1, period: "day" }] })+ expect(edited?.expiresAt).toBe(code.expiresAt)+ expect(await queries.authenticateAccessCode(db, "digest", "bot.create")).toBeNull()+ expect(await queries.authenticateAccessCode(db, "digest", "server.create")).toMatchObject({ limit: 1 })+ expect((await queries.updateAccessCode(db, "author", code.id, { expiresIn: "forever" }))?.expiresAt).toBeNull()+ expect(await queries.deleteAccessCode(db, "author", code.id)).toBe(true)+ expect(await queries.authenticateAccessCode(db, "digest", "server.create")).toBeNull()+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM automation_access_permission").get()).toEqual({ count: 0 })+ })++ it.each([false, true])("renames an owned code while replacing policies: %s", async (replacePolicies) => {+ const { db, sqlite } = fixture()+ const code = await queries.createAccessCode(db, "author", input(), "digest")+ const peerCode = await queries.createAccessCode(db, "peer", input(), "peer-digest")+ const permissions = replacePolicies ? [{ permission: "server.invite" as const, limit: 2, period: "day" as const }] : code.permissions+ const edited = await queries.updateAccessCode(db, "author", code.id, {+ name: "Renamed",+ ...(replacePolicies ? { permissions } : {}),+ })++ expect(edited).toEqual({ ...code, name: "Renamed", permissions })+ expect(await queries.getAccessCode(db, "peer", peerCode.id)).toEqual(peerCode)+ expect(sqlite.prepare("SELECT owner_id, secret_hash FROM automation_access_code WHERE id = ?").get(code.id))+ .toEqual({ owner_id: "author", secret_hash: "digest" })+ expect(await queries.authenticateAccessCode(db, "digest", "bot.create"))+ .toEqual(replacePolicies ? null : expect.objectContaining({ ownerId: "author", limit: 64 }))+ if (replacePolicies) {+ expect(await queries.authenticateAccessCode(db, "digest", "server.invite"))+ .toMatchObject({ ownerId: "author", limit: 2, period: "day" })+ }+ })++ it("lists a code with missing policies without granting access, and leaves an empty query update unchanged", async () => {+ const { db, sqlite, batchSizes } = fixture()+ const code = await queries.createAccessCode(db, "author", input(), "digest")+ sqlite.prepare("DELETE FROM automation_access_permission WHERE code_id = ?").run(code.id)+ const withoutPolicies = { ...code, permissions: [] }++ expect(await queries.listAccessCodes(db, "author")).toEqual([withoutPolicies])+ expect(await queries.authenticateAccessCode(db, "digest", "bot.create")).toBeNull()+ expect(await queries.updateAccessCode(db, "author", code.id, {})).toEqual(withoutPolicies)+ expect(await queries.listAccessCodes(db, "author")).toEqual([withoutPolicies])+ expect(batchSizes).toHaveLength(1)+ })++ it("keeps declared owner and policy keys aligned with the migration and cascades only the deleted owner's codes", async () => {+ const { db, sqlite } = fixture()+ const codeConfig = getTableConfig(automationAccessCode)+ const policyConfig = getTableConfig(automationAccessPermission)+ for (const config of [codeConfig, policyConfig]) {+ const declared = config.foreignKeys.map((key) => {+ const reference = key.reference()+ return { from: reference.columns[0].name, table: getTableName(reference.foreignTable),+ to: reference.foreignColumns[0].name, on_delete: key.onDelete?.toUpperCase() }+ })+ const migrated = (sqlite.pragma(`foreign_key_list(${config.name})`) as Array<{+ from: string; table: string; to: string; on_delete: string;+ }>).map(({ from, table, to, on_delete }) => ({ from, table, to, on_delete }))+ expect(migrated).toEqual(declared)+ }+ expect(codeConfig.indexes.map(({ config }) => ({ name: config.name, columns: config.columns })))+ .toEqual([{ name: "idx_automation_code_owner", columns: [automationAccessCode.ownerId] }])+ expect(sqlite.pragma("index_info(idx_automation_code_owner)"))+ .toEqual([expect.objectContaining({ name: "owner_id" })])+ expect(policyConfig.primaryKeys[0].columns.map((column) => column.name)).toEqual(["code_id", "permission"])+ expect((sqlite.pragma("table_info(automation_access_permission)") as Array<{ name: string; pk: number }>)+ .filter(({ pk }) => pk > 0).map(({ name }) => name)).toEqual(["code_id", "permission"])++ const authorCode = await queries.createAccessCode(db, "author", input(), "author-digest")+ const peerCode = await queries.createAccessCode(db, "peer", input(), "peer-digest")+ sqlite.prepare("DELETE FROM user WHERE id = ?").run("author")+ expect(await queries.getAccessCode(db, "author", authorCode.id)).toBeNull()+ expect(sqlite.prepare("SELECT code_id FROM automation_access_permission WHERE code_id = ?").all(authorCode.id)).toEqual([])+ expect(await queries.getAccessCode(db, "peer", peerCode.id)).toEqual(peerCode)+ expect(sqlite.pragma("foreign_key_check")).toEqual([])+ })++ it("rejects expiry at the exact boundary, soft-deleted owners and bot owners", async () => {+ const { db, sqlite } = fixture()+ const code = await queries.createAccessCode(db, "author", input(), "digest")+ expect(await queries.authenticateAccessCode(db, "digest", "bot.create", code.expiresAt!)).toBeNull()+ sqlite.prepare("UPDATE user SET deletedAt = 'deleted' WHERE id = 'author'").run()+ expect(await queries.authenticateAccessCode(db, "digest", "bot.create")).toBeNull()+ sqlite.prepare("UPDATE user SET deletedAt = NULL, isBot = 1 WHERE id = 'author'").run()+ expect(await queries.authenticateAccessCode(db, "digest", "bot.create")).toBeNull()+ })++ it("scopes minimal read projections and friend resolution to the owner", async () => {+ const { db, sqlite } = fixture()+ sqlite.exec(`+ ALTER TABLE user ADD COLUMN name TEXT NOT NULL DEFAULT '';+ ALTER TABLE user ADD COLUMN discriminator TEXT NOT NULL DEFAULT '0001';+ UPDATE user SET name = id;+ INSERT INTO user (id,name) VALUES ('outsider','outside'), ('deleted','deleted');+ INSERT INTO user (id,name,isBot,ownerUserId) VALUES ('ownbot','Helper',1,'author'), ('otherbot','Other bot',1,'peer'), ('unrelatedbot','Unrelated bot',1,'peer');+ UPDATE user SET deletedAt='deleted' WHERE id='deleted';+ INSERT INTO community_friendship (id,requester_id,addressee_id,status) VALUES+ ('accepted','author','peer','accepted'), ('otherbot','otherbot','author','accepted'), ('pending','author','outsider','pending'), ('deleted','author','deleted','accepted');+ CREATE TABLE community_machine (id TEXT PRIMARY KEY,user_id TEXT,display_name TEXT,hostname TEXT,status TEXT,available_runtimes TEXT NOT NULL DEFAULT '[]');+ INSERT INTO community_machine (id,user_id,display_name,hostname,status) VALUES ('mac1','author','My Mac','hidden-host','online'),('mac0','author','Stopped Mac','hidden-host','offline'),('other','peer','Other','secret-host','online');+ `)+ sqlite.prepare("UPDATE community_machine SET available_runtimes = ? WHERE id = ?").run(JSON.stringify(["codex"]), "mac1")+ expect(await queries.listMachines(db, "author")).toEqual([{ id: "mac0", name: "Stopped Mac", status: "offline", availableRuntimes: [] }, { id: "mac1", name: "My Mac", status: "online", availableRuntimes: ["codex"] }])+ expect(await queries.listFriends(db, "author")).toEqual([+ { name: "Helper", discriminator: "0001", isBot: true, ownerUserId: "author" },+ { name: "Other bot", discriminator: "0001", isBot: true, ownerUserId: "peer" },+ { name: "peer", discriminator: "0001", isBot: false, ownerUserId: null },+ ])+ expect(await queries.getFriendByHandle(db, "author", "outside#0001")).toBeNull()+ for (const handle of ["", "peer", "peer#123", "peer#abcd", " #0001"]) {+ expect(await queries.getFriendByHandle(db, "author", handle)).toBeNull()+ }+ expect(await queries.getFriendByHandle(db, "author", "peer#0001")).toMatchObject({ id: "peer" })+ expect(await queries.getFriendByHandle(db, "author", "Helper#0001")).toMatchObject({ id: "ownbot" })+ })+})++it("supports seven independent grants and scopes bot identity resolution in SQL", async () => {+ const all = AutomationAccessCodeCreateSchema.parse({ name: "all", permissions: AutomationPermissionSchema.options.map((permission) => ({ permission, limit: 1, period: "hour" })) })+ expect(all.permissions).toHaveLength(7)+ const { db, sqlite } = fixture()+ const code = await queries.createAccessCode(db, "author", all, "send-digest")+ expect(await queries.authenticateAccessCode(db, "send-digest", "message.send")).toMatchObject({ ownerId: "author", permission: "message.send" })+ expect(code.permissions).toHaveLength(7)+ sqlite.exec(`ALTER TABLE user ADD COLUMN name TEXT NOT NULL DEFAULT ''; ALTER TABLE user ADD COLUMN discriminator TEXT NOT NULL DEFAULT '0001';+ INSERT INTO user (id,name,isBot,ownerUserId) VALUES ('ownbot','Helper',1,'author'), ('otherbot','Other',1,'peer'), ('deletedbot','Deleted',1,'author');+ UPDATE user SET deletedAt='deleted' WHERE id='deletedbot'; UPDATE user SET name=id WHERE id IN ('author','peer');`)+ expect(await queries.getOwnedBotByHandle(db, "author", "Helper#0001")).toEqual({ id: "ownbot" })+ for (const handle of ["Other#0001", "Deleted#0001", "author#0001", "peer#0001", "Helper", "@Helper#0001"]) {+ expect(await queries.getOwnedBotByHandle(db, "author", handle)).toBeNull()+ }+ expect(await queries.getOwnedBotByHandle(db, "peer", "Helper#0001")).toBeNull()+})++it("validates file-send requests without accepting extra authority fields", () => {+ const body = { target: "/.dm/Alice#0001", as: "me", content: "hello\n", nonce: "n" }+ expect(AutomationMessageSendSchema.parse(body)).toEqual(body)+ expect(AutomationMessageSendSchema.parse({ ...body, as: "@Helper#0001" }).as).toBe("@Helper#0001")+ for (const change of [{ as: "Helper#0001" }, { as: "@Helper" }, { content: " " }, { target: "id" }, { ownerId: "peer" }, { nonce: "" }]) {+ expect(AutomationMessageSendSchema.safeParse({ ...body, ...change }).success).toBe(false)+ }+})diff --git a/src/shared/test/queries/community-channel-directory.test.ts b/src/shared/test/queries/community-channel-directory.test.tsindex d9231a2f2..97479beb3 100644--- a/src/shared/test/queries/community-channel-directory.test.ts+++ b/src/shared/test/queries/community-channel-directory.test.ts@@ -125,6 +125,13 @@ describe("listChannelRefDirectoryForUser", () => {afterEach(() => sqlite.close());+ it("can skip UI rail reads while keeping the same scoped channel directory", async () => {+ const railOrdered = await listChannelRefDirectoryForUser(db, "viewer");+ sqlite.exec("DROP TABLE community_server_rail; DROP TABLE community_server_folder; DROP TABLE community_server_folder_item;");+ const directory = await listChannelRefDirectoryForUser(db, "viewer", { railOrder: false });+ expect(directory).toEqual([railOrdered[1], railOrdered[0]]);+ });+it("returns one rail-ordered directory scoped to member-visible top-level channels", async () => {await expect(listChannelRefDirectoryForUser(db, "viewer")).resolves.toEqual([{ id: "s2", name: "Second", discriminator: "0002", channels: [] },diff --git a/src/shared/test/runtime-model-catalog-fingerprint.test.ts b/src/shared/test/runtime-model-catalog-fingerprint.test.tsnew file mode 100644index 000000000..63c537725--- /dev/null+++ b/src/shared/test/runtime-model-catalog-fingerprint.test.ts@@ -0,0 +1,17 @@+import { expect, it } from "vitest"+import { fingerprintRuntimeModelCatalog } from "../src/runtime-models-contract"+import type { RuntimeReasoningCatalog } from "../src/runtime-config"+it("compares catalog data independently of object key insertion order", async () => {+ const first: RuntimeReasoningCatalog = { updateMode: "unsupported", defaultModelId: "a", models: [{ id: "a", supportedReasoningEfforts: [{ value: "high", description: "More" }] }] }+ const second: RuntimeReasoningCatalog = { models: [{ supportedReasoningEfforts: [{ description: "More", value: "high" }], id: "a" }], defaultModelId: "a", updateMode: "unsupported" }+ expect(await fingerprintRuntimeModelCatalog(first)).toMatch(/^[a-f0-9]{64}$/)+ expect(await fingerprintRuntimeModelCatalog(first)).toBe(await fingerprintRuntimeModelCatalog(second))+ expect(await fingerprintRuntimeModelCatalog({ ...first, defaultModelId: "b" })).not.toBe(await fingerprintRuntimeModelCatalog(first))+})+it("distinguishes missing catalogs, reported-empty catalogs and model/effort changes", async () => {+ const empty: RuntimeReasoningCatalog = { updateMode: "unsupported", models: [] }+ const model: RuntimeReasoningCatalog = { ...empty, models: [{ id: "a", supportedReasoningEfforts: [] }] }+ const effort: RuntimeReasoningCatalog = { ...empty, models: [{ id: "a", supportedReasoningEfforts: [{ value: "high" }] }] }+ const hashes = await Promise.all([null, empty, model, effort].map(fingerprintRuntimeModelCatalog))+ expect(new Set(hashes).size).toBe(4)+})diff --git a/src/web/migrations/0110_automation_access_code.sql b/src/web/migrations/0110_automation_access_code.sqlnew file mode 100644index 000000000..18800f7fc--- /dev/null+++ b/src/web/migrations/0110_automation_access_code.sql@@ -0,0 +1,17 @@+CREATE TABLE automation_access_code (+ id TEXT PRIMARY KEY NOT NULL,+ owner_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,+ name TEXT NOT NULL,+ secret_hash TEXT NOT NULL UNIQUE,+ expires_at TEXT,+ created_at TEXT NOT NULL+);+CREATE INDEX idx_automation_code_owner ON automation_access_code(owner_id);+CREATE TABLE automation_access_permission (+ code_id TEXT NOT NULL REFERENCES automation_access_code(id) ON DELETE CASCADE,+ permission TEXT NOT NULL,+ request_limit INTEGER NOT NULL CHECK (request_limit >= 1 AND request_limit = CAST(request_limit AS INTEGER)),+ period TEXT NOT NULL CHECK (period IN ('hour', 'day')),+ PRIMARY KEY (code_id, permission),+ CHECK ((period = 'hour' AND request_limit <= 64) OR (period = 'day' AND request_limit <= 1536))+);diff --git a/src/web/public/agent.md b/src/web/public/agent.mdnew file mode 100644index 000000000..469d9b6be--- /dev/null+++ b/src/web/public/agent.md@@ -0,0 +1,259 @@+# Alook agent guide++Each feature below has two parts. **Human — in Alook** gives the person’s setup and screen steps. **Agent — with the CLI** gives the commands an authorized agent can run. Read the part for your role.++The human owns the account, chooses the computer and backend, and decides what to authorize. An agent acts on the requested task within that authorization. A code grants capabilities; it does not request every action the code permits. A human can also run the CLI commands themselves.++- **Account:** a person or a bot, with a handle such as `alice#0042`.+- **Server:** a shared space containing members and channels. Its `name#NNNN` handle identifies a place, not an account.+- **Channel / DM:** a channel belongs to a server; a DM connects two accounts.+- **Backend / model:** a backend is an installed CLI runtime, such as Codex or Claude Code. A model is a choice supported by that backend. Signing in to Alook does not sign in to the backend.+- **Machine / daemon:** a machine is a connected computer. The daemon receives messages and runs its assigned bots through installed backends on that computer.++The examples use Node.js 20.9+ and npm. `daemon` manages a computer connection; `use` performs selected account actions with an Automation access code. A machine pairing key and an Automation access code are separate credentials. Neither is a browser login.++An agent already running as an Alook bot should follow its supplied `$ALOOK_CLI` instructions for messaging and bot-account actions. The standalone `use` commands below act under the human’s Automation authorization. They do not read chat history or pull a bot’s inbox.++## 1. Create, connect and manage a machine++### Human — in Alook++A machine is the Alook record for a computer running the daemon. **Connect a machine** is the entry for creating one; there is no separate machine-name form.++1. Choose the computer that will run the bots. Install Node.js with npm, and install and sign in to the backend you want there.+2. Open [Machines](https://alook.ai/c/me/machines) and click **Connect a machine**. Alook prepares a connection command with a pairing key valid for 15 minutes. The panel shows **Waiting for the daemon…**.+3. Click **Copy command**. Have an authorized agent on the chosen computer run it, or run it there yourself. In the desktop app, you can use **Connect this computer** when that button is available. Copying the command alone does not create the machine.+4. When the daemon activates the new connection, Alook creates the machine and uses the computer’s hostname as its displayed name. No manual machine ID or name is needed.+5. Wait for **Connected** and the computer’s name in the panel. Click **Done**; the machine card in **Machines** should show **Online**. If the key expires before use, open **Connect a machine** again for a fresh command. Keep the key out of chat.++Use the machine card’s three-dot menu to manage the connection:++- **Reconnect…:** generate a new connection command. This keeps the machine’s identity and replaces its connection credential.+- **Stop:** stop the daemon and check that the machine goes offline.+- **Delete:** remove its bots first, then delete the connection. Deletion revokes the connection credentials; it does not remove local projects or uninstall software.++Connecting a machine does not create a bot. Keep its computer, network and backend available while its bots work.++### Agent — with the CLI++To create a machine connection, run the human-provided command on the computer they selected. The initial connection command has this form:++```sh+npx --yes @alook/daemon@latest daemon start --machine-key '<pairing-key-from-generated-command>'+```++Use the complete generated command, including any extra endpoint options. Keep its key private; do not invent a key or request it in chat. The first activation registers this computer as a new machine, saves its local connection credential and starts the daemon. Confirm the returned machine ID and status, then report the result to the human. Creating the machine does not create a bot.++For a reconnect, use the newly generated **Reconnect…** command for the existing machine. That preserves its ID. `use machine --list` and `use machine --list-models` only inspect machines; Automation has no machine-create command.++To inspect or manage an existing local connection, use its saved machine record:++```sh+npx --yes @alook/daemon@latest daemon list+npx --yes @alook/daemon@latest daemon status '<machine-id>'+npx --yes @alook/daemon@latest daemon stop '<machine-id>'+npx --yes @alook/daemon@latest daemon start --id '<machine-id>'+```++Run only the requested operation. Get the ID from `daemon list`; `start --id` restarts a saved connection. If the connection used a custom data directory, use that same directory. Stopping leaves the machine record in Alook. These commands use saved local machine credentials; an Automation code cannot replace them.++## 2. Set up Automation access++### Human — in Alook++Create a code when you want an external agent or script to perform account actions. It needs no running daemon or bot session. Bot creation still needs a ready machine and backend.++1. Open [Alook](https://alook.ai/c) and sign in. On desktop, click the **User settings** gear beside your profile at the bottom-left. On a phone, return to the conversation list if the profile bar is hidden, then tap its gear.+2. Select **Automation**, then **Create access code**.+3. Enter a **Name** for the task. Choose **Expires in**: **1 hour**, **24 hours** (default), **7 days**, **30 days**, or **Never expires**.+4. Under **Permissions**, select the actions needed for the task. Read starts enabled; Write starts disabled. Turn off unused Read permissions too. At least one permission is required.+5. In **Advanced**, set limits for enabled permissions if needed. The default is 64 requests per hour. You can choose 1–64 per hour or 1–1,536 per day. Both use rolling windows; a daily limit also keeps a 64-request cap in the last hour.+6. Click **Create access code**, then **Copy code**. Save it privately before **Done → I’ve saved it**. Configure it in the agent’s environment or a private file; do not paste the secret into the conversation.++Choose these checkboxes for the work you want:++| Work | Checkboxes |+|---|---|+| Inspect computers and available models | List machines |+| Create a bot | List machines, Create bots |+| Inspect your friends | List friends |+| Inspect your servers and participating channels | List servers |+| Create a server | Create servers |+| Invite a friend to a server | Invite friends to servers; add List friends and List servers if the agent must find their handles |+| Send a message | Send messages; add List servers if the agent must find the channel |++**Copy prompt** copies a setup prompt you can paste into an agent for help. It does not create a code or send a message.++To change a code, click its pencil icon, edit its name, permissions, limits or expiry, then **Save changes**. **Keep current expiration** preserves its deadline. A lost secret needs a replacement code; editing cannot reveal it again. You decide whether to grant more access when an agent reports a missing permission.++### Agent — with the CLI++Use the configured `ALOOK_ACCESS_CODE` environment variable or a private text file containing the code. If the human wants you to run a task, ask for the configured file path rather than the secret in chat. Keep credentials out of source files, messages and logs.++With a private file, add `--access-code-file` after `use` in each command:++```sh+npx --yes @alook/daemon@latest use --access-code-file '/private/path/alook-code.txt' machine --list+```++The file takes precedence over the environment variable. The remaining examples assume `ALOOK_ACCESS_CODE` is set. Replace fictional IDs, handles and model choices with returned account values.++`use` calls the independent Automation API. The access code controls its permissions and request limits. Normal client and bot requests do not consume the code’s quota. You cannot use `use` to issue codes, edit their grants or replace a normal client/bot credential. If access is insufficient, report the failed action and needed permission; let the human decide what to change.++## 3. Create a bot++### Human — in Alook++To create the bot yourself:++1. Click **Home** with the Alook logo at the top-left, then **My Bots** in the left sidebar.+2. Click **Create a bot**. If Alook asks you to **Connect a machine**, finish the computer connection in section 1 first.+3. Set the name and description. Check the selected machine and runtime. If the form shows a default setup, click **Change** to choose another. Select a model and reasoning effort when available or required.+4. Click **Create bot**. The bot appears in **My Bots**. Creating it does not add it to a server.++To delegate creation, configure **List machines** and **Create bots** in section 2. Tell the agent the bot’s purpose and which computer to use.++### Agent — with the CLI++Required permissions: `machine.read` for discovery and `bot.create` for creation.++1. List machines. Choose a returned machine with `status: "online"` and a backend with `health: "healthy"`; use their exact IDs.+2. List models for that machine and backend. Use a returned model ID and a supported `reasoningEfforts` value if needed.+3. Create the requested bot once. Return its full handle to the human.++```sh+npx --yes @alook/daemon@latest use machine --list+npx --yes @alook/daemon@latest use machine --list-models --id mac1 --backend codex+npx --yes @alook/daemon@latest use bot --create \+ '{"name":"Helper","machineId":"mac1","backendId":"codex","model":"<supported-model-id>"}'+```++Pass an effort as `reasoningEffort` in the bot JSON. If `modelRequired` is false, you may omit `model`. If it is true and no usable catalog exists, resolve discovery or backend setup; do not guess IDs or substitute an old list after an error.++Model discovery reuses successful results for five minutes. After that, it asks the selected online machine to discover models and waits for the result. Add `--refresh` to bypass the cache. `source` is `cached_report` or `fresh_discovery`; `observedAt` is the server-recorded discovery time. `models: null` means no catalog was reported; `models: []` means a reported empty catalog. Timeout and discovery failure return errors.++## 4. Create or find a server++### Human — in Alook++To create a server yourself, click the **+** button (**Add a Server**) in the server list at the far left. Enter its name in **Create a server**, then click **Create server**. Open an existing server by clicking its icon in that list.++To delegate creation, enable **Create servers** in section 2 and give the agent the name and purpose. Enable **List servers** if the task also needs existing server or channel references. Keep it off when the task does not need that information.++### Agent — with the CLI++Required permissions: `server.create` to create; `server.read` to list servers and participating top-level channels.++```sh+npx --yes @alook/daemon@latest use server --list+npx --yes @alook/daemon@latest use server --create \+ '{"name":"demo","description":"Team work"}'+```++Return the created server’s URL to the human.++Each listed server has a `channels` array with `name`, `type` (`text` or `forum`), and a canonical `ref`, such as `/demo#0042/general`. Public channels appear through server membership. Private channels appear only when the code owner created or joined them. The list excludes threads, messages and other people’s private channels. A joined server can have `channels: []`. Listing channels uses the same `server.read` permission and request limit.++## 5. Invite someone to a server++### Human — in Alook++Open the server, then click **Invite to server** beside its name above the channel list. In **Invite friends to …**, find the friend and click **Invite**. Alook sends the invitation through a DM. **Invited** means the invitation was sent; the recipient still chooses whether to join.++To delegate, enable **Invite friends to servers** in section 2. Give the agent the server and recipient’s full handles, including `#NNNN`. If you want the agent to find them, also enable **List servers** and **List friends**. You must belong to the server; the recipient must be your friend or your own bot.++### Agent — with the CLI++Required permission: `server.invite`. Discovery also uses `friend.read` or `server.read` when needed.++```sh+npx --yes @alook/daemon@latest use friend --list+npx --yes @alook/daemon@latest use server --list+npx --yes @alook/daemon@latest use server --invite \+ '{"server":"demo#0042","friend":"alice#0042"}'+```++Use full returned handles. Friends include `is_my_bot`, true only for the code owner’s own bots. Send only the requested invitation. Report that it was sent; do not report that the recipient has joined.++## 6. Send a message++### Human — in Alook++To send as yourself, open the channel or DM, write in the message box at the bottom, then click **Send message**.++To delegate a send, enable **Send messages** in section 2; it starts disabled. Specify the destination, text and sender: yourself or one of your bots. Enable **List servers** if the agent needs to find a channel reference. Make sure the selected sender can access the destination; your channel list does not prove that your bot has access.++Automation sends do not run a bot’s local PII filters. If the task depends on that local filtering pipeline, use the bot’s normal local CLI workflow instead.++### Agent — with the CLI++Required permission: `message.send`. Save the requested text in a UTF-8 file. `--file` reads that text as the message body; it does not attach the file. This command takes a file, not stdin or a heredoc.++```sh+# Send as the human who issued the code.+npx --yes @alook/daemon@latest use message --send \+ --target '/demo#0042/general' --as me --file './message.txt'++# Send as one of that human’s bots.+npx --yes @alook/daemon@latest use message --send \+ --target '/.dm/alice#0042' --as '@Helper#0042' --file './message.txt'+```++`--as` is required. `me` selects the code owner; `@name#NNNN` selects a bot that the same human owns. Other people’s accounts or bots are rejected. Use a returned channel `ref` or a DM ref `/.dm/<peer#NNNN>` as the target. Alook resolves access for the selected sender.++Channel membership, private-channel access, DM restrictions and existing send checks still apply. A bot’s unread-alignment block remains a block; `use` cannot read its inbox or mark messages read to bypass it. This path does not pass through the bot’s local credential proxy or run its local PII filters.++The message file and `--access-code-file` are different: one contains text to send; the other contains the credential. Keep the code out of the message file. If a response is lost, check the destination before repeating the send.++## 7. End an access code’s access++### Human — in Alook++Open **User settings → Automation**, click the code’s trash icon, then confirm **Delete code**. This deletes its record and stops future requests. Expired codes leave the active list.++You can also ask the agent using a code to expire that code through the CLI. Deleting or expiring a code does not undo bots, servers, invitations or messages already created.++### Agent — with the CLI++When the human asks you to end the supplied code’s access, run:++```sh+npx --yes @alook/daemon@latest use expire+```++With a configured file:++```sh+npx --yes @alook/daemon@latest use --access-code-file '/private/path/alook-code.txt' expire+```++This affects only the supplied code. It needs no extra permission or remaining quota and returns `{"success":{"expired":true}}`. Later requests and repeated expiry are refused. Alook retains the expired record but excludes it from the active list; returning to Automation refreshes that list. You cannot use this command to expire another code.++## 8. Check results and resolve failures++### Human — in Alook++Check the result where it belongs: **My Bots** for a created bot, the server list for a new server, the recipient DM for an invitation, or the destination conversation for a message.++If the agent reports an access problem, open **User settings → Automation**. Decide whether to edit the code’s permissions or replace an invalid, expired, revoked or lost code. For a connection problem, open **Machines** and check the computer’s status. Keep new credentials in private configuration.++### Agent — with the CLI++Each action returns one JSON line. Check `success` or `error`; exit status 0 alone does not prove success. Return the result or one concrete next step to the human.++- **Code missing, invalid, expired or revoked:** check the configured private file or environment variable. Report when a replacement is needed; do not request the secret in chat.+- **Permission denied:** name the failed action and required permission. Leave the authorization decision to the human; do not expand access yourself.+- **Rate limited:** wait for the returned retry hint. Do not loop or issue another code to evade the limit. Editing limits does not erase recent usage.+- **Machine offline, backend unhealthy or discovery failed:** inspect the local daemon and backend if the task authorizes work on that computer. Report a connection or credential problem that needs the human. Request models after recovery.+- **Write response lost:** the action may have completed. Check the destination before repeating a create, invitation or send. Do not report success or issue the write again without resolving that uncertainty.++For command options:++```sh+npx --yes @alook/daemon@latest daemon --help+npx --yes @alook/daemon@latest use machine --help+npx --yes @alook/daemon@latest use bot --help+npx --yes @alook/daemon@latest use server --help+npx --yes @alook/daemon@latest use message --help+npx --yes @alook/daemon@latest use expire --help+```diff --git a/src/web/src/app/api/community/automation/access-codes/[codeId]/route.ts b/src/web/src/app/api/community/automation/access-codes/[codeId]/route.tsnew file mode 100644index 000000000..621780b2c--- /dev/null+++ b/src/web/src/app/api/community/automation/access-codes/[codeId]/route.ts@@ -0,0 +1,16 @@+import { AutomationAccessCodeUpdateSchema, queries } from "@alook/shared"+import { getPrimaryDb } from "@/lib/db"+import { withAutomationManagement } from "@/lib/automation"+import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers"++export const PATCH = withAutomationManagement(async (req, ctx) => {+ const [body, error] = await parseBody(req, AutomationAccessCodeUpdateSchema)+ if (error) return error+ const accessCode = await queries.automation.updateAccessCode(getPrimaryDb(ctx.env.DB), ctx.userId, ctx.params?.codeId ?? "", body)+ return accessCode ? writeJSON({ accessCode }) : writeError("Access code not found", 404)+})++export const DELETE = withAutomationManagement(async (_req, ctx) => {+ const deleted = await queries.automation.deleteAccessCode(getPrimaryDb(ctx.env.DB), ctx.userId, ctx.params?.codeId ?? "")+ return deleted ? writeJSON({ deleted: true }) : writeError("Access code not found", 404)+})diff --git a/src/web/src/app/api/community/automation/access-codes/route.test.ts b/src/web/src/app/api/community/automation/access-codes/route.test.tsnew file mode 100644index 000000000..e2a70a025--- /dev/null+++ b/src/web/src/app/api/community/automation/access-codes/route.test.ts@@ -0,0 +1,59 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"+const mocks = vi.hoisted(() => ({ list: vi.fn(), create: vi.fn(), update: vi.fn(), remove: vi.fn() }))+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }) }))+vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: (req: NextRequest, ctx: unknown) => Promise<Response>) => async (req: NextRequest, context?: { params?: Promise<Record<string, string>> }) => {+ if (req.headers.get("Cookie") !== "synthetic-human") return Response.json({}, { status: 401 })+ return handler(req, { env: { DB: {} }, userId: "owner", params: await context?.params })+} }))+vi.mock("@alook/shared", async (importOriginal) => ({ ...await importOriginal<typeof import("@alook/shared")>(), queries: { automation: { listAccessCodes: mocks.list, createAccessCode: mocks.create, updateAccessCode: mocks.update, deleteAccessCode: mocks.remove } } }))+import { GET, POST } from "./route"+import { PATCH, DELETE } from "./[codeId]/route"+import { hashAutomationSecret } from "@/lib/automation"++const code = { id: "code", name: "Task", createdAt: "now", expiresAt: null, permissions: [{ permission: "server.create", limit: 64, period: "hour" }] }+function request(method: string, body?: unknown) { return new NextRequest("http://localhost/api/community/automation/access-codes", { method, headers: { Cookie: "synthetic-human" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }) }+beforeEach(() => { vi.clearAllMocks(); mocks.list.mockResolvedValue([code]); mocks.create.mockResolvedValue(code); mocks.update.mockResolvedValue(code); mocks.remove.mockResolvedValue(true) })++describe("Automation access-code management routes", () => {+ it("requires human login and refuses bearer-based code management", async () => {+ expect((await GET(new NextRequest("http://localhost/api/community/automation/access-codes"))).status).toBe(401)+ const req = request("POST", { name: "Task", permissions: code.permissions })+ req.headers.set("Authorization", "Bearer aac_" + "a".repeat(64))+ expect((await POST(req)).status).toBe(401)+ expect(mocks.create).not.toHaveBeenCalled()+ })+ it("returns the generated secret once, and sends only its hash to persistence", async () => {+ const response = await POST(request("POST", { name: "Task", permissions: code.permissions }))+ expect(response.status).toBe(201)+ expect(response.headers.get("Cache-Control")).toBe("no-store")+ const body = await response.json()+ expect(body.accessCode).not.toHaveProperty("prefix")+ expect(body.secret).toMatch(/^aac_[a-f0-9]{64}$/)+ expect(mocks.create).toHaveBeenCalledWith({ primary: true }, "owner", { name: "Task", expiresIn: "24h", permissions: code.permissions }, await hashAutomationSecret(body.secret))+ expect(await (await GET(request("GET"))).json()).toEqual({ accessCodes: [code] })+ })+ it("validates requests and applies owner-scoped edits without implicit expiry renewal", async () => {+ expect((await POST(request("POST", { name: "Task", permissions: [{ permission: "unknown", limit: 1, period: "day" }] }))).status).toBe(400)+ const params = { params: Promise.resolve({ codeId: "code" }) }+ expect((await PATCH(request("PATCH", { name: "New" }), params)).status).toBe(200)+ expect(mocks.update).toHaveBeenCalledWith({ primary: true }, "owner", "code", { name: "New" })+ expect((await DELETE(request("DELETE"), params)).status).toBe(200)+ expect(mocks.remove).toHaveBeenCalledWith({ primary: true }, "owner", "code")+ mocks.update.mockResolvedValueOnce(null)+ expect((await PATCH(request("PATCH", { name: "New" }), params)).status).toBe(404)+ mocks.remove.mockResolvedValueOnce(false)+ expect((await DELETE(request("DELETE"), params)).status).toBe(404)+ })+})++it("rejects invalid edits and keeps missing route IDs within the signed-in owner scope", async () => {+ expect((await PATCH(request("PATCH", {}), { params: Promise.resolve({ codeId: "code" }) })).status).toBe(400)+ expect(mocks.update).not.toHaveBeenCalled()+ mocks.update.mockResolvedValueOnce(null)+ expect((await PATCH(request("PATCH", { name: "Missing ID" }))).status).toBe(404)+ expect(mocks.update).toHaveBeenCalledExactlyOnceWith({ primary: true }, "owner", "", { name: "Missing ID" })+ mocks.remove.mockResolvedValueOnce(false)+ expect((await DELETE(request("DELETE"))).status).toBe(404)+ expect(mocks.remove).toHaveBeenCalledExactlyOnceWith({ primary: true }, "owner", "")+})diff --git a/src/web/src/app/api/community/automation/access-codes/route.ts b/src/web/src/app/api/community/automation/access-codes/route.tsnew file mode 100644index 000000000..8ad1bc43d--- /dev/null+++ b/src/web/src/app/api/community/automation/access-codes/route.ts@@ -0,0 +1,16 @@+import { AutomationAccessCodeCreateSchema, queries } from "@alook/shared"+import { getPrimaryDb } from "@/lib/db"+import { hashAutomationSecret, newAutomationSecret, withAutomationManagement } from "@/lib/automation"+import { parseBody, writeJSON } from "@/lib/middleware/helpers"++export const GET = withAutomationManagement(async (_req, ctx) => writeJSON({ accessCodes: await queries.automation.listAccessCodes(getPrimaryDb(ctx.env.DB), ctx.userId) }))++export const POST = withAutomationManagement(async (req, ctx) => {+ const [body, error] = await parseBody(req, AutomationAccessCodeCreateSchema)+ if (error) return error+ const secret = newAutomationSecret()+ const accessCode = await queries.automation.createAccessCode(getPrimaryDb(ctx.env.DB), ctx.userId, body, await hashAutomationSecret(secret))+ const response = writeJSON({ accessCode, secret }, 201)+ response.headers.set("Cache-Control", "no-store")+ return response+})diff --git a/src/web/src/app/api/community/automation/bots/route.ts b/src/web/src/app/api/community/automation/bots/route.tsnew file mode 100644index 000000000..f431478c0--- /dev/null+++ b/src/web/src/app/api/community/automation/bots/route.ts@@ -0,0 +1,3 @@+import { withAutomation } from "@/lib/automation"+import { createBotForUser } from "@/lib/community/create-bot.server"+export const POST = withAutomation("bot.create", createBotForUser)diff --git a/src/web/src/app/api/community/automation/expire/route.ts b/src/web/src/app/api/community/automation/expire/route.tsnew file mode 100644index 000000000..4248cc47e--- /dev/null+++ b/src/web/src/app/api/community/automation/expire/route.ts@@ -0,0 +1 @@+export { expireAutomationAccessCode as POST } from "@/lib/automation"diff --git a/src/web/src/app/api/community/automation/friends/route.ts b/src/web/src/app/api/community/automation/friends/route.tsnew file mode 100644index 000000000..812ab3b4f--- /dev/null+++ b/src/web/src/app/api/community/automation/friends/route.ts@@ -0,0 +1,3 @@+import { withAutomation } from "@/lib/automation"+import { readAutomationFriends } from "@/lib/community/automation-read.server"+export const GET = withAutomation("friend.read", readAutomationFriends)diff --git a/src/web/src/app/api/community/automation/machines/[id]/discover-models/route.test.ts b/src/web/src/app/api/community/automation/machines/[id]/discover-models/route.test.tsnew file mode 100644index 000000000..9880208eb--- /dev/null+++ b/src/web/src/app/api/community/automation/machines/[id]/discover-models/route.test.ts@@ -0,0 +1,83 @@+import { fingerprintRuntimeModelCatalog } from "@alook/shared"+import { beforeEach, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"+const mocks = vi.hoisted(() => ({ machine: vi.fn(), dispatch: vi.fn(), admit: vi.fn() }))+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }) }))+vi.mock("@/lib/broadcast", () => ({ wsDoFetch: mocks.dispatch }))+vi.mock("@alook/shared", async (importOriginal) => { const actual = await importOriginal<typeof import("@alook/shared")>(); return { ...actual, queries: { ...actual.queries, communityMachine: { getMachineByIdForUser: mocks.machine } } } })+vi.mock("@/lib/middleware/community-actor", () => ({ withCommunityActor: (handler: unknown) => handler }))+vi.mock("@/lib/automation", () => ({ withAutomation: (permission: string, handler: (...args: any[]) => unknown) => {+ expect(permission).toBe("machine.read")+ return (req: NextRequest) => handler(req, { env: { DB: {} }, userId: "code-owner", params: { id: "m1" }, beforeCreate: mocks.admit })+} }))+import { POST } from "./route"+const catalog = { catalogOrigin: "native_report", updateMode: "unsupported", defaultModelId: "fresh/model", models: [{ id: "fresh/model", supportedReasoningEfforts: [{ value: "high" }], defaultReasoningEffort: "high" }] }+const request = (body: unknown = { requestId: "request", runtimeId: "codex" }) => new NextRequest("http://localhost/api/community/automation/machines/m1/discover-models", { method: "POST", body: JSON.stringify(body) })+beforeEach(() => {+ vi.clearAllMocks()+ mocks.machine.mockResolvedValue({ status: "online", availableRuntimes: [{ id: "codex", reasoning: { models: [{ id: "old" }] } }] })+ mocks.admit.mockResolvedValue(null)+ mocks.dispatch.mockResolvedValue(Response.json({ sent: 1, unsupported: 0, observedAt: "2026-10-29T00:00:00Z", result: { status: "complete", catalog } }))+})+it("admits once, refreshes the owner target and projects the matching fresh result", async () => {+ const response = await POST(request())+ expect(response.status).toBe(200)+ expect(mocks.machine).toHaveBeenCalledWith({ primary: true }, "code-owner", "m1")+ expect(mocks.admit).toHaveBeenCalledOnce()+ expect(mocks.dispatch).toHaveBeenCalledWith({ DB: {} }, "/community-machine/by-id/m1/discover-models?wait=1&cache=1", expect.objectContaining({ method: "POST", body: JSON.stringify({ requestId: "request", runtimeId: "codex" }) }))+ expect(await response.json()).toEqual({ machineId: "m1", backendId: "codex", source: "fresh_discovery", requestId: "request", readAt: expect.any(String), observedAt: "2026-10-29T00:00:00Z", modelRequired: false, defaultModelId: "fresh/model", models: [{ id: "fresh/model", reasoningEfforts: [{ value: "high" }], defaultReasoningEffort: "high" }] })+})+it("returns fresh missing and empty catalogs without the two removed metadata fields", async () => {+ for (const value of [null, { updateMode: "unsupported", models: [] }]) {+ mocks.dispatch.mockResolvedValueOnce(Response.json({ sent: 1, unsupported: 0, observedAt: "2026-10-29T00:00:00Z", result: { status: "complete", catalog: value } }))+ const body = await (await POST(request())).json()+ expect(body.models).toEqual(value ? [] : null)+ expect(body).not.toHaveProperty("catalogState")+ expect(body).not.toHaveProperty("catalogOrigin")+ }+})+it("does not dispatch on denied quota, malformed request, foreign/offline machine or unknown runtime", async () => {+ mocks.admit.mockResolvedValueOnce(Response.json({ error: "limited" }, { status: 429 }))+ expect((await POST(request())).status).toBe(429)+ expect((await POST(request({}))).status).toBe(400)+ mocks.machine.mockResolvedValueOnce(null)+ expect((await POST(request())).status).toBe(404)+ mocks.machine.mockResolvedValueOnce({ status: "offline" })+ expect((await POST(request())).status).toBe(409)+ expect((await POST(request({ requestId: "request", runtimeId: "missing" }))).status).toBe(400)+ expect(mocks.dispatch).not.toHaveBeenCalled()+})+it("returns discovery errors and refuses missing/corrupt results instead of using old models", async () => {+ mocks.dispatch.mockResolvedValueOnce(Response.json({ sent: 1, unsupported: 0, result: { status: "error", code: "AUTH_REQUIRED", message: "Sign in" } }))+ const response = await POST(request())+ expect(response.status).toBe(502)+ expect(await response.json()).toEqual({ error: "Sign in", code: "AUTH_REQUIRED", machineId: "m1", backendId: "codex", requestId: "request" })+ for (const result of [undefined, {}, { status: "complete", catalog: "bad" }]) {+ mocks.dispatch.mockResolvedValueOnce(Response.json({ sent: 1, unsupported: 0, result }))+ expect((await POST(request())).status).toBe(503)+ }+})++it("returns a timestamped server cache hit and allows an explicit refresh without forwarding refresh to the daemon", async () => {+ mocks.machine.mockResolvedValueOnce({ status: "online", availableRuntimes: [{ id: "codex", status: "healthy", reasoning: catalog }] })+ mocks.dispatch.mockResolvedValueOnce(Response.json({ sent: 0, unsupported: 0, cached: true, observedAt: "2026-10-29T00:00:00Z", catalogFingerprint: await fingerprintRuntimeModelCatalog(catalog as never) }))+ expect(await (await POST(request())).json()).toMatchObject({ source: "cached_report", observedAt: "2026-10-29T00:00:00Z" })+ await POST(request({ requestId: "force", runtimeId: "codex", refresh: true }))+ expect(mocks.dispatch.mock.lastCall?.[1]).toBe("/community-machine/by-id/m1/discover-models?wait=1")+ expect(JSON.parse(mocks.dispatch.mock.lastCall?.[2].body)).toEqual({ requestId: "force", runtimeId: "codex" })+ expect((await POST(request({ requestId: "force", runtimeId: "codex", refresh: "yes" }))).status).toBe(400)+})++it("rejects mismatched cache metadata instead of pairing it with an unrelated D1 snapshot", async () => {+ mocks.dispatch.mockResolvedValueOnce(Response.json({ sent: 0, unsupported: 0, cached: true, observedAt: "2026-10-29T00:00:00Z", catalogFingerprint: "b".repeat(64) }))+ expect((await POST(request())).status).toBe(503)+})++it("fails closed on HTTP transport failure and invalid observation timestamps", async () => {+ mocks.dispatch.mockResolvedValueOnce(new Response("down", { status: 503 }))+ expect((await POST(request())).status).toBe(503)+ for (const observedAt of [undefined, "invalid"]) {+ mocks.dispatch.mockResolvedValueOnce(Response.json({ sent: 1, observedAt, result: { status: "complete", catalog } }))+ expect((await POST(request())).status).toBe(503)+ }+})diff --git a/src/web/src/app/api/community/automation/machines/[id]/discover-models/route.ts b/src/web/src/app/api/community/automation/machines/[id]/discover-models/route.tsnew file mode 100644index 000000000..c78e00715--- /dev/null+++ b/src/web/src/app/api/community/automation/machines/[id]/discover-models/route.ts@@ -0,0 +1,11 @@+import { withAutomation } from "@/lib/automation"+import { discoverRuntimeModels, discoveryFailure } from "@/lib/community/discover-models.server"+import { projectModelOptions } from "@/lib/community/machine-options.server"+import { writeJSON } from "@/lib/middleware/helpers"++export const POST = withAutomation("machine.read", async (req, ctx) => {+ const id = ctx.params?.id as string+ const response = await discoverRuntimeModels(req, ctx, true, (message, status) => discoveryFailure(message, status, id))+ if (response instanceof Response) return response+ return writeJSON({ ...projectModelOptions(id, { id: response.backendId, ...(response.result.catalog ? { reasoning: response.result.catalog } : {}) }, null, { includeCatalogMetadata: false }), source: response.source, observedAt: response.observedAt, requestId: response.requestId })+})diff --git a/src/web/src/app/api/community/automation/machines/route.ts b/src/web/src/app/api/community/automation/machines/route.tsnew file mode 100644index 000000000..9f58060ea--- /dev/null+++ b/src/web/src/app/api/community/automation/machines/route.ts@@ -0,0 +1,3 @@+import { withAutomation } from "@/lib/automation"+import { readAutomationMachines } from "@/lib/community/automation-read.server"+export const GET = withAutomation("machine.read", readAutomationMachines)diff --git a/src/web/src/app/api/community/automation/messages/route.ts b/src/web/src/app/api/community/automation/messages/route.tsnew file mode 100644index 000000000..3a4dbc5ab--- /dev/null+++ b/src/web/src/app/api/community/automation/messages/route.ts@@ -0,0 +1,3 @@+import { withAutomation } from "@/lib/automation"+import { sendAutomationMessage } from "@/lib/community/automation-message.server"+export const POST = withAutomation("message.send", sendAutomationMessage)diff --git a/src/web/src/app/api/community/automation/servers/[id]/invites/route.ts b/src/web/src/app/api/community/automation/servers/[id]/invites/route.tsnew file mode 100644index 000000000..d71cec398--- /dev/null+++ b/src/web/src/app/api/community/automation/servers/[id]/invites/route.ts@@ -0,0 +1,3 @@+import { withAutomation } from "@/lib/automation"+import { inviteAutomationFriend } from "@/lib/community/automation-invite.server"+export const POST = withAutomation("server.invite", inviteAutomationFriend)diff --git a/src/web/src/app/api/community/automation/servers/route.ts b/src/web/src/app/api/community/automation/servers/route.tsnew file mode 100644index 000000000..4945eeac0--- /dev/null+++ b/src/web/src/app/api/community/automation/servers/route.ts@@ -0,0 +1,5 @@+import { withAutomation } from "@/lib/automation"+import { createServerForUser } from "@/lib/community/create-server.server"+import { readAutomationServers } from "@/lib/community/automation-read.server"+export const GET = withAutomation("server.read", readAutomationServers)+export const POST = withAutomation("server.create", createServerForUser)diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.tsindex f3dacfa6a..e2158c05e 100644--- a/src/web/src/app/api/community/bots/route.test.ts+++ b/src/web/src/app/api/community/bots/route.test.ts@@ -130,6 +130,30 @@ describe("POST /api/community/bots — model", () => {expect(await response.json()).toMatchObject({ code: "MACHINE_OFFLINE", machineId: "mac1" })expect(mockCreateBot).not.toHaveBeenCalled()})+ it("rejects a machine outside the caller's ownership before creation or dispatch", async () => {+ mockGetMachineForOwner.mockResolvedValueOnce(null)++ const response = await POST(postReq(base()), ctx)++ expect(response.status).toBe(404)+ expect(await response.json()).toEqual({ error: "machine not found" })+ expect(mockGetMachineForOwner).toHaveBeenCalledExactlyOnceWith({}, "mac1", "u1")+ expect(mockCreateBot).not.toHaveBeenCalled()+ expect(mockGetUserPublic).not.toHaveBeenCalled()+ expect(mockPushBotEventToMachine).not.toHaveBeenCalled()+ })+ it("reports an unresolved owner after creation without dispatching an ownerless bot", async () => {+ mockGetUserPublic.mockResolvedValueOnce(null)++ const response = await POST(postReq(base()), ctx)++ expect(response.status).toBe(500)+ expect(await response.json()).toEqual({ error: "owner not resolvable — retry after re-authenticating" })+ expect(mockCreateBot).toHaveBeenCalledOnce()+ expect(mockGetUserPublic).toHaveBeenCalledExactlyOnceWith({}, "u1")+ expect(mockEnsureNewSiblingBotFriendships).not.toHaveBeenCalled()+ expect(mockPushBotEventToMachine).not.toHaveBeenCalled()+ })it("persists model_name and returns it in the 201 body", async () => {const res = await POST(postReq(base("claude-opus-4-6")), ctx)expect(res.status).toBe(201)diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.tsindex 743ff5afe..8f3148156 100644--- a/src/web/src/app/api/community/bots/route.ts+++ b/src/web/src/app/api/community/bots/route.ts@@ -1,16 +1,9 @@-import { NextRequest } from "next/server"-import {- queries,- CommunityBotCreateRequestSchema,- resolveBotCreationConfiguration,- BotCreationError,- requiresExplicitModel,-} from "@alook/shared"-import { getDb, getPrimaryDb } from "@/lib/db"+import { getDb } from "@/lib/db"+import { queries } from "@alook/shared"import { withCommunityActor } from "@/lib/middleware/community-actor"import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"-import { completeBotCreation } from "@/lib/community/bot-creation.server"+import { writeJSON } from "@/lib/middleware/helpers"+import { createBotForUser } from "@/lib/community/create-bot.server"import { readCommunityBots } from "@/lib/community/bots.server"export { tokenUsageDayWindow } from "@/lib/community/bots.server"@@ -22,102 +15,4 @@ export const GET = withCommunityActor(async (_req, ctx) => {machineId: bot.machineId, backendId: bot.runtime, model: bot.modelName, reasoningEffort: bot.reasoningEffort, isActive: bot.isActive, presence: bot.presence })) })})-export const POST = withAuth(async (req: NextRequest, ctx) => {- const [body, err] = await parseBody(req, CommunityBotCreateRequestSchema)- if (err) return err- if (requiresExplicitModel(body.runtime) && !body.model?.trim()) {- return writeError("Choose a model before saving", 400)- }-- const db = getPrimaryDb(ctx.env.DB)-- let capacity = await queries.productPlan.getBotCapacitySummary(db, ctx.userId)- if (capacity.ownedCount >= capacity.limit) {- return writeJSON({- error: "BOT_LIMIT_REACHED",- plan: capacity.plan.id,- planDisplayName: capacity.plan.displayName,- limit: capacity.limit,- ownedCount: capacity.ownedCount,- activeCount: capacity.activeCount,- }, 409)- }-- // Machine must be owned by caller AND runtime must be in its availableRuntimes- // AND currently healthy. Unhealthy runtimes (e.g. broken binary caught by- // spawn ENOENT and marked by the daemon) are rejected here so a UX picker- // race doesn't create a bot bound to something that will always fail.- const machine = await queries.communityBot.getMachineForOwner(- db,- body.machineId,- ctx.userId,- )- if (!machine) return writeError("machine not found", 404)- // getMachineForOwner canonicalizes `availableRuntimes` to include status/lastError- // via the shared schema, so we can consult status here directly.- const runtime = machine.availableRuntimes.find((r) => r.id === body.runtime)- const modelName = body.model ?? null- let effortResolution- try { effortResolution = resolveBotCreationConfiguration(machine, runtime, { backendId: body.runtime, model: modelName, reasoningEffort: body.reasoningEffort ?? null }) }- catch (error) {- if (error instanceof BotCreationError) return writeJSON({ error: error.message, code: error.code, ...error.details }, error.status)- throw error- }-- let created: Awaited<ReturnType<typeof queries.communityBot.createBot>>- try {- created = await queries.communityBot.createBot(db, {- ownerId: ctx.userId,- name: body.name,- description: body.description,- machineId: body.machineId,- runtime: body.runtime,- image: body.image ?? null,- modelName,- reasoningEffort: effortResolution.canonicalEffort,- })- } catch (error) {- if (!queries.communityBot.isBotEntitlementLimitError(error)) throw error- capacity = await queries.productPlan.getBotCapacitySummary(db, ctx.userId)- return writeJSON({- error: "BOT_LIMIT_REACHED",- plan: capacity.plan.id,- planDisplayName: capacity.plan.displayName,- limit: capacity.limit,- ownedCount: capacity.ownedCount,- activeCount: capacity.activeCount,- }, 409)- }-- // The bot's owner is the authenticated caller — resolve their handle to- // carry in the bot:added push so the daemon can tell the agent who owns it.- // The owner MUST resolve: if getUserPublic can't find the authenticated- // caller we've hit an integrity bug (auth accepted a user id that no longer- // has a row), and pushing a bot:added with empty owner fields would- // silently strip the "You are owned by …" privacy paragraph from the- // agent's system prompt.- const owner = await queries.user.getUserPublic(db, ctx.userId)- if (!owner) return writeError("owner not resolvable — retry after re-authenticating", 500)-- await completeBotCreation(ctx.env, db, ctx.userId, owner, [{ id: created.botId, name: created.name, discriminator: created.discriminator, description: created.description, machineId: body.machineId }])-- return writeJSON(- {- bot: {- id: created.botId,- name: created.name,- discriminator: created.discriminator,- description: created.description,- image: created.image,- avatarVersion: 0,- machineId: body.machineId,- runtime: body.runtime,- modelName,- reasoningEffort: effortResolution.canonicalEffort,- runtimeConfigRevision: 0,- isActive: true,- },- },- 201,- )-})+export const POST = withAuth(createBotForUser)diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.tsindex 03650a339..82e6d0036 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts@@ -98,6 +98,7 @@ describe("message HTTP route — concurrent nonce with real SQL writes", () => {const bodies = await Promise.all(responses.map((response) => response.json()))expect(responses.map((response) => response.status)).toEqual(kind === "human" ? [201, 201] : [200, 200])expect(bodies[0].message.id).toBe(bodies[1].message.id)+ if (kind === "human") expect(bodies.map((body) => body.message.clientNonce)).toEqual(["same-nonce", "same-nonce"])expect(bodies.filter((body) => body.deduped)).toHaveLength(1)expect(fixture.sqlite.prepare("SELECT count(*) AS count FROM community_message").get()).toEqual({ count: 1 })expect(fixture.sqlite.prepare("SELECT message_id FROM community_message_attachment").get()).toEqual({ message_id: bodies[0].message.id })diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.tsindex fb647a16c..c7fd4de4b 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.send-into-forum.test.ts@@ -7,6 +7,8 @@ vi.mock("@/lib/db", () => ({getPrimaryDb: vi.fn(() => ({})),}))+let actorKind: "human" | "bot" = "bot"+const mockSentStatement = vi.fn(() => ({ activity: "sent" }))const mockCreateMessageWithThread = vi.fn()const mockResolveTargetForMember = vi.fn()@@ -53,7 +55,7 @@ vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn(async () => ({ allowevi.mock("@/lib/middleware/community-actor", () => ({withCommunityActor: (handler: any) => async (req: any, ctx?: any) => handler(req, {env: { DB: {} },- actor: { kind: "bot", userId: "bot_1", ownerUserId: "owner_1", machineId: "m_1" },+ actor: { kind: actorKind, userId: "bot_1", ownerUserId: "owner_1", machineId: "m_1" },params: ctx?.params instanceof Promise ? await ctx.params : ctx?.params,}),}))@@ -77,6 +79,7 @@ const request = (body: unknown) => new NextRequest("http://localhost/api/communidescribe("forum sends open a thread through the canonical message route", () => {beforeEach(() => {vi.clearAllMocks()+ actorKind = "bot"mockResolveTargetForMember.mockResolvedValue({ channelId: "forum_1" })mockRequireMessageSurfaceAccess.mockResolvedValue({ok: true,@@ -198,4 +201,29 @@ describe("forum sends open a thread through the canonical message route", () =>expect(response.status).toBe(400)expect(await response.json()).toEqual({ error: "attachment not found or not attachable to this thread" })})+ it.each([{}, { content: " " }, { content: 7 }])("rejects empty human forum titles before creating a thread %j", async (body) => {+ actorKind = "human"+ const response = await POST(request(body), { params: { id: "forum_1" } })+ expect(response.status).toBe(400)+ expect(await response.json()).toEqual({ error: "content is required" })+ expect(mockCreateMessageWithThread).not.toHaveBeenCalled()+ })++ it("preserves human opener primitive failures without a success confirmation", async () => {+ actorKind = "human"+ mockCreateMessageWithThread.mockResolvedValueOnce({ ok: false, status: 409, error: "forum unavailable" })+ const response = await POST(request({ content: "Title" }), { params: { id: "forum_1" } })+ expect(response.status).toBe(409)+ expect(await response.json()).toEqual({ error: "forum unavailable" })+ })++ it("preserves a forum replay primitive failure instead of returning sent", async () => {+ mockGetCommunityMessageReplay.mockResolvedValueOnce({ row: { id: "old" } })+ mockCreateMessageWithThread.mockResolvedValueOnce({ ok: false, status: 400, error: "replay thread unavailable" })+ const response = await POST(request({ channel: "/demo/forum", content: { text: "Title" }, nonce: "old-nonce" }), ctx)+ expect(response.status).toBe(400)+ expect(await response.json()).toEqual({ error: "replay thread unavailable" })+ expect(mockHasDeliverableUnreadForAgentScope).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.tsindex 3db10a1ce..efabad24b 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts@@ -300,9 +300,9 @@ describe("POST /api/community/channels/[id]/messages", () => {mockGetDMBetween.mockResolvedValue(null)})- it.each([false, true])("confirms a full v3 human message with replay=%s", async (replay) => {+ it.each([false, true])("confirms a full v3 human message from a nonce-free read-back with replay=%s", async (replay) => {const row = { id: "m1", channelId: "c1", seq: 12, authorId: "u1", authorName: "Alice", authorImage: null, authorAvatarVersion: 0,- content: "hello", type: "default", mentionType: null, replyToId: null, clientNonce: "v3-nonce", embeds: null, createdAt: "now" }+ content: "hello", type: "default", mentionType: null, replyToId: null, embeds: null, createdAt: "now" }mockGetMessage.mockResolvedValue(row)mockGetMessageByAuthorAndNonce.mockResolvedValue(replay ? row : null)const request = postReq({ content: "hello", nonce: "v3-nonce" })@@ -420,6 +420,24 @@ describe("POST /api/community/channels/[id]/messages", () => {expect(mockDispatchCommittedMessage).not.toHaveBeenCalled()})+ it.each([false, true])("resolves a bot reply only within the selected channel (found=%s)", async (found) => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "s1" }])+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "c1", serverId: "s1", type: "text", parentChannelId: null }])+ mockGetMessageByChannelAndSeq.mockResolvedValueOnce(found ? { id: "reply_1" } : null)+ if (found) mockGetMessageInScope.mockResolvedValueOnce({ id: "reply_1", authorId: "u2", content: "original" })+ const response = await POST(botPostReq({ channel: "/demo#0042/general", content: { text: "reply" }, replyToSeq: 7 }), ctx)+ expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith({}, { channelId: "c1" }, 7)+ if (found) {+ expect(response.status).toBe(200)+ expect((await response.json()).state).toBe("sent")+ expect(mockCreateMessage.mock.calls[0][1].replyToId).toBe("reply_1")+ } else {+ expect(response.status).toBe(400)+ expect(await response.json()).toEqual({ error: "reply target #7 not found in /demo#0042/general" })+ expect(mockCreateMessage).not.toHaveBeenCalled()+ }+ })+it("preserves the alignment CAS when a message arrives during JEV evaluation", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "s1" }])mockResolveChannelByNameForMember.mockResolvedValue([{ id: "c1", serverId: "s1", type: "text", parentChannelId: null }])@@ -431,6 +449,17 @@ describe("POST /api/community/channels/[id]/messages", () => {expect(mockDispatchCommittedMessage).not.toHaveBeenCalled()})+ it.each([undefined, "", "resolve"])("rejects a human send without a real path ID (%s), even with a body ref", async (id) => {+ const params: Record<string, string> = id === undefined ? {} : { id }+ const response = await POST(postReq({ content: "hello", channel: "/demo#0042/general" }), { params })+ expect(response.status).toBe(400)+ expect(await response.json()).toEqual({ error: "missing channel id" })+ expect(mockCheckMessageRateLimit).not.toHaveBeenCalled()+ expect(mockGetChannel).not.toHaveBeenCalled()+ expect(mockCreateMessage).not.toHaveBeenCalled()+ expect(mockHasDeliverableUnreadForAgentScope).not.toHaveBeenCalled()+ })+it("starts the write path on a first-primary D1 session", async () => {const res = await POST(postReq({ content: "hello" }), ctx)diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.tsindex 9e6559813..001af32ce 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.ts@@ -1,25 +1,14 @@-import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"-import { flattenError } from "zod"+import { COMMUNITY_RESOURCE_CONTRACT_VERSION, MAX_FORUM_TAG_LENGTH, queries, requestsCommunityContract, requestedCommunityContract } from "@alook/shared"import { NextRequest, NextResponse } from "next/server"import { withCommunityActor } from "@/lib/middleware/community-actor"import { writeError } from "@/lib/middleware/helpers"import { getDb, getPrimaryDb } from "@/lib/db"-import { queries, withD1Retry, CommunityAgentSendRequestSchema, MAX_FORUM_TAG_LENGTH, utcDayKey, WS_EVENTS, PARTICIPANT_SOURCE } from "@alook/shared"import { parseCommunityMessageWindow } from "@/lib/community/messages"-import { mapPostedMessageForApi, readCommunityMessageProfiles } from "@/lib/community/message-payload"import { readCommunityMessageWindow } from "@/lib/community/message-window.server"import { readCommunityConversationEntry } from "@/lib/community/conversation-entry.server"-import { requestsCommunityContract, requestedCommunityContract, COMMUNITY_CONTRACT_HEADER, CommunityMessagePostedSchema, type CommunityContract } from "@alook/shared"import { writeCommunityMessagesRead, writeCommunityConversationEntryRead } from "@/lib/community/read-contract"-import { checkRateLimit } from "@/lib/rate-limit"-import { createCommunityMessage, getCommunityMessageReplay } from "@/lib/community/message-handler"-import { createMessageWithThread } from "@/lib/community/create-channels"-import {- resolveMessageTarget,- type MessageTargetDescriptor,-} from "@/lib/community/message-door"-import { broadcastToUserSafe } from "@/lib/community/fanout"-import { isDuplicateBotMessage, DUPLICATE_MESSAGE_ERROR } from "@/lib/community/jev-send-dedup"+import { resolveMessageTarget } from "@/lib/community/message-door"+import { handleHumanSend, handleBotSend } from "@/lib/community/message-send.server"// A bot addresses by ref-in-body; the path `[id]` is then a placeholder// (`channels/resolve/messages`) since a ref carries `/` and can't sit in a path@@ -166,293 +155,7 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {if (ctx.actor.kind === "bot") {return handleBotSend(db, ctx.actor.userId, ctx.env, raw)}- return handleHumanSend(db, ctx.actor.userId, ctx.env, ctx.params?.id, raw, COMMUNITY_RESOURCE_CONTRACT_VERSION)+ const pathId = ctx.params?.id+ if (!pathId || pathId === REF_PLACEHOLDER_ID) return NextResponse.json({ error: "missing channel id" }, { status: 400 })+ return handleHumanSend(db, ctx.actor.userId, ctx.env, { id: pathId }, raw, COMMUNITY_RESOURCE_CONTRACT_VERSION)})--/**- * Human/web arm — real channelId in the path (id descriptor). Rate-limit +- * nonce + 201 shape preserved from the pre-fold channels POST; the raw body is- * now schema-tightened via the door-core descriptor + createCommunityMessage's- * own validation (the direction Ingaborg #196 flagged).- */-async function handleHumanSend(- db: ReturnType<typeof getDb>,- userId: string,- env: Env,- pathId: string | undefined,- raw: unknown,- contract: CommunityContract,-): Promise<NextResponse> {- if (!pathId || pathId === REF_PLACEHOLDER_ID) {- return NextResponse.json({ error: "missing channel id" }, { status: 400 })- }-- const descriptor: MessageTargetDescriptor = { id: pathId }-- const rateLimit = await checkRateLimit(env, "community:msgSend", userId)- if (!rateLimit.allowed) {- return NextResponse.json({ error: "rate limited" }, { status: 429, headers: { "Retry-After": String(rateLimit.retryAfterSec) } })- }-- // SINGLE authorization entry — resolveMessageTarget's communication intent- // subsumes member/DM friendship + returns the target (no standalone gate).- const resolved = await resolveMessageTarget(db, userId, descriptor, "human", "communicate")- if (!resolved.ok) return NextResponse.json({ error: resolved.error }, { status: resolved.status })-- const body = raw as { nonce?: unknown; attachments?: unknown }- const clientNonce = typeof body?.nonce === "string" ? body.nonce : undefined- const target = resolved.value.target-- const attachmentIds = Array.isArray(body.attachments)- ? (body.attachments as unknown[]).filter((x): x is string => typeof x === "string")- : []- // A human send into a forum uses the same canonical message door and the- // same opener+thread primitive as the bot arm. The body is sent separately- // through this ordinary message door after the caller receives threadId.- if (target.kind === "forum") {- const forumBody = raw as { content?: unknown; mentionType?: unknown }- const content = typeof forumBody.content === "string" ? forumBody.content : ""- if (!content.trim()) return NextResponse.json({ error: "content is required" }, { status: 400 })- const created = await createMessageWithThread({- db,- authorId: userId,- authorKind: "human",- parentChannelId: target.channelId,- serverId: target.serverId,- body: { content, mentionType: forumBody.mentionType },- clientNonce,- source: "web",- })- if (!created.ok) return NextResponse.json({ error: created.error }, { status: created.status })- const response = humanMessageConfirmation(db, contract, target.channelId, {- message: await mapPostedMessageForApi(db, target.channelId, created.message, contract),- threadId: created.thread.id,- deduped: created.deduped,- }, created.deduped ? 200 : 201)- return response- }-- const replay = await getCommunityMessageReplay({- db,- authorId: userId,- channelId: target.channelId,- clientNonce,- })- if (replay) {- return humanMessageConfirmation(db, contract, target.channelId, { message: await mapPostedMessageForApi(db, target.channelId, replay.row, contract), deduped: true }, 200)- }-- const result = await createCommunityMessage({- db,- authorId: userId,- authorKind: "human",- target,- body: raw as Record<string, unknown>,- source: "web",- clientNonce,- attachmentIds: attachmentIds.length > 0 ? attachmentIds : undefined,- })- if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })- const response = humanMessageConfirmation(db, contract, target.channelId, { message: await mapPostedMessageForApi(db, target.channelId, result.row, contract), deduped: result.deduped }, 201)- return response-}--async function humanMessageConfirmation(db: ReturnType<typeof getDb>, contract: CommunityContract, channelId: string, payload: { message: unknown; deduped?: boolean; threadId?: string }, status: number): Promise<NextResponse> {- const message = CommunityMessagePostedSchema.shape.message.parse(payload.message)- const profiles = await readCommunityMessageProfiles(db, [message])- return NextResponse.json(CommunityMessagePostedSchema.parse({ contractVersion: contract, channelId, ...payload, profiles, deduped: payload.deduped === true }), {- status, headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_RESOURCE_CONTRACT_VERSION) },- })-}--/**- * Bot arm — ref-in-body (`channel`), the former `send` verb's behavior verbatim:- * single resolve WITH create-if-missing, channel-alignment gate, CAS via- * `expectedSeq`, SENT-heatmap bump, agent-message response. Target resolution +- * per-surface auth flow through the shared door-core (single mask entry).- */-async function handleBotSend(- db: ReturnType<typeof getDb>,- botUserId: string,- env: RuntimeEnv,- raw: unknown,-): Promise<NextResponse> {- const parsed = CommunityAgentSendRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload", details: flattenError(parsed.error) }, { status: 400 })- }- const body = parsed.data-- const descriptor: MessageTargetDescriptor = {- ref: body.channel,- createDmIfMissing: true,- createThreadIfMissing: true,- }- const resolved = await resolveMessageTarget(db, botUserId, descriptor, "bot", "communicate")- if (!resolved.ok) {- return NextResponse.json(- { error: resolved.error, ...(resolved.hint ? { hint: resolved.hint } : {}) },- { status: resolved.status },- )- }- const target = resolved.value.target- const channelId = target.channelId- const createForumOpener = (serverId: string, expectedSeq?: number) =>- createMessageWithThread({- db,- authorId: botUserId,- authorKind: "bot",- parentChannelId: channelId,- serverId,- body: { content: body.content.text },- clientNonce: body.nonce,- ...(expectedSeq !== undefined ? { expectedSeq } : {}),- source: "cli",- extraStatements: [- queries.communityBot.bumpBotDailyActivityStatement(db, botUserId, utcDayKey(new Date()), "sent"),- ],- })-- const replayResponse = async () => {- const replay = await getCommunityMessageReplay({- db,- authorId: botUserId,- channelId,- clientNonce: body.nonce,- })- if (!replay) return null- if (target.kind === "forum") {- const created = await createForumOpener(target.serverId)- if (!created.ok) return NextResponse.json({ error: created.error }, { status: created.status })- const message = await queries.communityAgentInbox.toAgentMessage(db, created.message, botUserId)- return NextResponse.json({- state: "sent",- message,- threadId: created.thread.id,- deduped: created.deduped,- })- }- const orderedAttachments = replay.attachments.map((a) => ({ id: a.id, filename: a.filename, contentType: a.contentType, size: a.size }))- const message = await queries.communityAgentInbox.toAgentMessage(db, replay.row, botUserId, orderedAttachments)- return NextResponse.json({ state: "sent", message, deduped: true })- }- const replay = await replayResponse()- if (replay) return replay-- if (target.kind === "thread") {- const created = await withD1Retry(- () => queries.communityThread.addThreadParticipant(db, {- threadChannelId: channelId,- userId: botUserId,- source: PARTICIPANT_SOURCE.ADDED,- }),- { route: "community/messages:thread-auto-join" },- )- if (created) {- const event = {- type: WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE,- relation: "notify",- present: true,- serverId: target.serverId,- channelId,- userId: botUserId,- } as const- const recipients = await queries.communityThread.listThreadParticipantUserIds(db, channelId)- await Promise.all(- [...new Set(recipients)].map((userId) => broadcastToUserSafe(userId, event)),- )- }- }-- const scopeTarget = { channelId }- const [latestSeq, readState] = await Promise.all([- withD1Retry(() => queries.communityAgentInbox.getLatestSeqForScope(db, channelId), { route: "community/messages:latest-seq" }),- withD1Retry(() => queries.communityReadState.getReadState(db, { userId: botUserId, ...scopeTarget }), { route: "community/messages:read-state" }),- ])- const seen = body.seenUpToSeq ?? readState?.lastReadSeq ?? 0- const hasUnread = await withD1Retry(- () => queries.communityAgentInbox.hasDeliverableUnreadForAgentScope(db, botUserId, channelId, seen),- { route: "community/messages:has-unread" },- )- if (hasUnread) {- const replay = await replayResponse()- if (replay) return replay- return NextResponse.json({ state: "blocked", reason: "unaligned", unreadCount: Math.max(0, latestSeq - seen), latestSeq })- }-- if (!body.force && target.kind !== "dm" && await isDuplicateBotMessage({- db, env, channelId, authorId: botUserId,- content: body.content.text,- })) {- const replay = await replayResponse()- if (replay) return replay- return NextResponse.json({ error: DUPLICATE_MESSAGE_ERROR, code: "duplicate_message" }, { status: 422 })- }-- if (target.kind === "forum") {- const created = await createForumOpener(target.serverId, latestSeq)- if (!created.ok) {- if (created.status === 409) {- const freshLatestSeq = await withD1Retry(- () => queries.communityAgentInbox.getLatestSeqForScope(db, channelId),- { route: "community/messages:forum-fresh-latest-seq" },- )- return NextResponse.json({- state: "blocked",- reason: "unaligned",- unreadCount: Math.max(0, freshLatestSeq - seen),- latestSeq: freshLatestSeq,- })- }- return NextResponse.json({ error: created.error }, { status: created.status })- }- const message = await queries.communityAgentInbox.toAgentMessage(db, created.message, botUserId)- return NextResponse.json({- state: "sent",- message,- threadId: created.thread.id,- deduped: created.deduped,- })- }-- let replyToId: string | undefined- if (body.replyToSeq !== undefined) {- const replyTarget = await withD1Retry(- () => queries.communityMessage.getMessageByChannelAndSeq(db, scopeTarget, body.replyToSeq!),- { route: "community/messages:reply-lookup" },- )- if (!replyTarget) {- return NextResponse.json({ error: `reply target #${body.replyToSeq} not found in ${body.channel}` }, { status: 400 })- }- replyToId = replyTarget.id- }-- const result = await createCommunityMessage({- db,- authorId: botUserId,- authorKind: "bot",- target,- body: { content: body.content.text, replyToId },- source: "cli",- expectedSeq: latestSeq,- attachmentIds: body.attachments.length > 0 ? body.attachments : undefined,- clientNonce: body.nonce,- extraStatements: [- queries.communityBot.bumpBotDailyActivityStatement(db, botUserId, utcDayKey(new Date()), "sent"),- ],- })- if (!result.ok) {- if (result.status === 409) {- const freshLatestSeq = await withD1Retry(- () => queries.communityAgentInbox.getLatestSeqForScope(db, channelId),- { route: "community/messages:fresh-latest-seq" },- )- return NextResponse.json({ state: "blocked", reason: "unaligned", unreadCount: Math.max(0, freshLatestSeq - seen), latestSeq: freshLatestSeq })- }- return NextResponse.json({ error: result.error }, { status: result.status })- }-- const orderedAttachments = (result.attachments ?? []).map((a) => ({ id: a.id, filename: a.filename, contentType: a.contentType, size: a.size }))- const message = await queries.communityAgentInbox.toAgentMessage(db, result.row, botUserId, orderedAttachments)- return NextResponse.json({ state: "sent", message, deduped: result.deduped })-}diff --git a/src/web/src/app/api/community/friends/accepted/route.ts b/src/web/src/app/api/community/friends/accepted/route.tsindex bfc1debe1..2d3d41771 100644--- a/src/web/src/app/api/community/friends/accepted/route.ts+++ b/src/web/src/app/api/community/friends/accepted/route.ts@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db"import { withCommunityActor } from "@/lib/middleware/community-actor"import { resolvePresence, toFriendCard } from "@/lib/community/friend-cards"+export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)const userId = ctx.actor.userIddiff --git a/src/web/src/app/api/community/machines/[id]/discover-models/route.test.ts b/src/web/src/app/api/community/machines/[id]/discover-models/route.test.tsindex 260754057..fbdbc857f 100644--- a/src/web/src/app/api/community/machines/[id]/discover-models/route.test.ts+++ b/src/web/src/app/api/community/machines/[id]/discover-models/route.test.ts@@ -1,3 +1,4 @@+import { fingerprintRuntimeModelCatalog } from "@alook/shared"import { beforeEach, describe, expect, it, vi } from "vitest"import { NextRequest } from "next/server"const mocks = vi.hoisted(() => ({ machine: vi.fn(), dispatch: vi.fn(), bot: vi.fn() }))@@ -5,7 +6,7 @@ vi.mock("@/lib/db", () => ({ getDb: () => ({ authDb: true }), getPrimaryDb: () =vi.mock("@/lib/broadcast", () => ({ wsDoFetch: mocks.dispatch }))vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return { ...actual, queries: { communityMachine: { getMachineByIdForUser: mocks.machine } } }+ return { ...actual, queries: { ...actual.queries, communityMachine: { getMachineByIdForUser: mocks.machine } } }})vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: any) => (req: any) => handler(req, { env: { DB: {} }, userId: "owner", params: { id: "machine" } }) }))vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: async () => ({ env: { DB: {} } }) }))@@ -95,3 +96,51 @@ describe("bot model discovery error and dispatch contract", () => {expect(await response.json()).toMatchObject({ code, machineId: "machine" })})})++describe("bot synchronous cached model queries", () => {+ const botRequest = (query = "?wait=1", body: unknown = payload) => new NextRequest(`http://localhost/api/community/machines/machine/discover-models${query}`, { method: "POST", headers: { authorization: "Bearer crk_synthetic" }, body: JSON.stringify(body) })+ const catalog = { updateMode: "unsupported", catalogOrigin: "native_report", defaultModelId: "provider/model", models: [{ id: "provider/model", supportedReasoningEfforts: [{ value: "high" }], defaultReasoningEffort: "high" }] }+ const fresh = { sent: 1, unsupported: 0, cached: false, observedAt: "2026-10-29T00:00:00Z", result: { status: "complete", catalog } }+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.bot.mockResolvedValue({ kind: "bot", actor: { botUserId: "requester", ownerUserId: "owner", machineId: "source", isActive: true } })+ mocks.machine.mockResolvedValue({ status: "online", availableRuntimes: [{ id: "codex" }] })+ mocks.dispatch.mockImplementation(async () => Response.json(fresh))+ })+ it("uses the authenticated owner and returns fresh/cache model reports through the same wait path", async () => {+ const response = await POST(botRequest(), { params: { id: "machine" } })+ expect(response.status).toBe(200)+ expect(mocks.machine).toHaveBeenCalledWith({ db: true }, "owner", "machine")+ expect(mocks.dispatch.mock.lastCall?.[1]).toBe("/community-machine/by-id/machine/discover-models?wait=1&cache=1")+ expect(await response.json()).toMatchObject({ source: "fresh_discovery", observedAt: fresh.observedAt, catalogState: "reported", catalogOrigin: "native_report", models: [{ id: "provider/model", reasoningEfforts: [{ value: "high" }] }] })+ mocks.machine.mockResolvedValueOnce({ status: "online", availableRuntimes: [{ id: "codex", status: "healthy", reasoning: catalog }] })+ mocks.dispatch.mockResolvedValueOnce(Response.json({ ...fresh, sent: 0, cached: true, catalogFingerprint: await fingerprintRuntimeModelCatalog(catalog as never) }))+ expect(await (await POST(botRequest(), { params: { id: "machine" } })).json()).toMatchObject({ source: "cached_report", observedAt: fresh.observedAt })+ })+ it("preserves model-specific projection and forces refresh without forwarding CLI-only fields", async () => {+ const response = await POST(botRequest("?wait=1&model=provider%2Fmodel", { ...payload, refresh: true }), { params: { id: "machine" } })+ expect(mocks.dispatch.mock.lastCall?.[1]).toBe("/community-machine/by-id/machine/discover-models?wait=1")+ expect(JSON.parse(mocks.dispatch.mock.lastCall?.[2].body)).toEqual(payload)+ expect(await response.json()).toMatchObject({ source: "fresh_discovery", inCatalog: true, model: { id: "provider/model", reasoningEfforts: [{ value: "high" }], defaultReasoningEffort: "high" } })+ const unknown = await POST(botRequest("?wait=1&model=custom%2Funknown"), { params: { id: "machine" } })+ expect(await unknown.json()).toMatchObject({ inCatalog: false, model: { id: "custom/unknown", reasoningEfforts: null, defaultReasoningEffort: null } })+ })+ it("returns a discovery failure instead of a stored report and refuses corrupt force options", async () => {+ mocks.dispatch.mockResolvedValueOnce(Response.json({ sent: 1, unsupported: 0, result: { status: "error", code: "failed", message: "Failed" } }))+ const response = await POST(botRequest(), { params: { id: "machine" } })+ expect(response.status).toBe(502)+ expect(await response.json()).toMatchObject({ code: "failed" })+ expect((await POST(botRequest("?wait=1", { ...payload, refresh: "true" }), { params: { id: "machine" } })).status).toBe(400)+ })+ it("shares human fresh/cache/force discovery while returning the native UI catalog", async () => {+ const human = (body: unknown = payload) => new NextRequest("http://localhost/api/community/machines/machine/discover-models?wait=1", { method: "POST", body: JSON.stringify(body) })+ expect(await (await POST(human())).json()).toEqual({ machineId: "machine", backendId: "codex", requestId: "request", source: "fresh_discovery", observedAt: fresh.observedAt, result: fresh.result })+ expect(mocks.dispatch.mock.lastCall?.[1]).toBe("/community-machine/by-id/machine/discover-models?wait=1&cache=1")+ mocks.machine.mockResolvedValueOnce({ status: "online", availableRuntimes: [{ id: "codex", reasoning: catalog }] })+ mocks.dispatch.mockResolvedValueOnce(Response.json({ sent: 0, unsupported: 0, cached: true, observedAt: fresh.observedAt, catalogFingerprint: await fingerprintRuntimeModelCatalog(catalog as never) }))+ expect(await (await POST(human())).json()).toMatchObject({ source: "cached_report", result: fresh.result })+ expect((await POST(human({ ...payload, refresh: true }))).status).toBe(200)+ expect(mocks.dispatch.mock.lastCall?.[1]).toBe("/community-machine/by-id/machine/discover-models?wait=1")+ expect(JSON.parse(mocks.dispatch.mock.lastCall?.[2].body)).toEqual(payload)+ })+})diff --git a/src/web/src/app/api/community/machines/[id]/discover-models/route.ts b/src/web/src/app/api/community/machines/[id]/discover-models/route.tsindex 462b45582..0fb940c48 100644--- a/src/web/src/app/api/community/machines/[id]/discover-models/route.ts+++ b/src/web/src/app/api/community/machines/[id]/discover-models/route.ts@@ -1,40 +1,4 @@-import { queries, readBoundedJsonRequest, RuntimeModelDiscoveryRequestSchema } from "@alook/shared"-import { getPrimaryDb } from "@/lib/db"import { withCommunityActor } from "@/lib/middleware/community-actor"-import { writeError, writeJSON } from "@/lib/middleware/helpers"-import { wsDoFetch } from "@/lib/broadcast"+import { discoverModels } from "@/lib/community/discover-models.server"-export const POST = withCommunityActor(async (req, ctx) => {- const id = ctx.params?.id as string- const failure = (message: string, status: number) => {- if (ctx.actor.kind === "human") return writeError(message, status)- const code = message === "MACHINE_OFFLINE" || message === "UPGRADE_REQUIRED" ? message- : message === "machine not found" ? "MACHINE_NOT_FOUND" : message === "runtime not found" ? "BACKEND_NOT_FOUND"- : message === "invalid request" ? "INVALID_DISCOVERY_REQUEST" : "DISCOVERY_UNAVAILABLE"- const text = code === "MACHINE_OFFLINE" ? "Target machine is offline" : code === "UPGRADE_REQUIRED" ? "Target daemon must be upgraded to discover models" : message- return writeJSON({ error: text, code, machineId: id }, status)- }- const machine = await queries.communityMachine.getMachineByIdForUser(getPrimaryDb(ctx.env.DB), ctx.actor.kind === "bot" ? ctx.actor.ownerUserId : ctx.actor.userId, id)- if (!machine) return failure("machine not found", 404)- if (machine.status !== "online") return failure("MACHINE_OFFLINE", 409)- const input = await readBoundedJsonRequest(req, 4096)- const payload = RuntimeModelDiscoveryRequestSchema.safeParse(input.ok ? input.value : null)- if (!payload.success) return failure("invalid request", 400)- if (!machine.availableRuntimes.some((runtime) => runtime.id === payload.data.runtimeId)) {- return failure("runtime not found", 400)- }- try {- const response = await wsDoFetch(ctx.env, `/community-machine/by-id/${encodeURIComponent(id)}/discover-models`, {- method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(payload.data),- })- if (!response.ok) return failure("model discovery unavailable", 503)- const receipt = await response.json() as { sent?: unknown; unsupported?: unknown }- if (typeof receipt.sent !== "number" || !Number.isSafeInteger(receipt.sent) || receipt.sent < 0) {- return failure("model discovery unavailable", 503)- }- if (receipt.sent > 0) return writeJSON({ dispatched: true, requestId: payload.data.requestId }, 202)- return failure(typeof receipt.unsupported === "number" && receipt.unsupported > 0 ? "UPGRADE_REQUIRED" : "MACHINE_OFFLINE", 409)- } catch {- return failure("model discovery unavailable", 503)- }-})+export const POST = withCommunityActor((req, ctx) => discoverModels(req, { ...ctx, kind: ctx.actor.kind, userId: ctx.actor.kind === "bot" ? ctx.actor.ownerUserId : ctx.actor.userId }))diff --git a/src/web/src/app/api/community/machines/[id]/models/route.test.ts b/src/web/src/app/api/community/machines/[id]/models/route.test.tsnew file mode 100644index 000000000..23f7bae5c--- /dev/null+++ b/src/web/src/app/api/community/machines/[id]/models/route.test.ts@@ -0,0 +1,35 @@+import { beforeEach, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"+const mocks = vi.hoisted(() => ({ machine: vi.fn(), actor: { kind: "human", userId: "owner", ownerUserId: "owner" } }))+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }) }))+vi.mock("@alook/shared", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@alook/shared")>()+ return { ...actual, queries: { ...actual.queries, communityBot: { ...actual.queries.communityBot, getMachineForOwner: mocks.machine } } }+})+vi.mock("@/lib/middleware/community-actor", () => ({ withCommunityActor: (handler: (...args: any[]) => unknown) => (req: NextRequest) => handler(req, { env: { DB: {} }, actor: mocks.actor, params: { id: "m1" } }) }))+import { GET } from "./route"+const request = (backend = "codex") => new NextRequest(`http://localhost/api/community/machines/m1/models?backend=${backend}`)+beforeEach(() => { vi.clearAllMocks(); mocks.actor = { kind: "human", userId: "owner", ownerUserId: "owner" }; mocks.machine.mockResolvedValue({ id: "m1", status: "online", availableRuntimes: [{ id: "codex", status: "healthy" }] }) })+it.each(["human", "bot"])("scopes the existing %s model read to the human owner", async (kind) => {+ mocks.actor = { kind, userId: kind === "bot" ? "bot" : "owner", ownerUserId: "owner" }+ const response = await GET(request())+ expect(mocks.machine).toHaveBeenCalledExactlyOnceWith({ primary: true }, "m1", "owner")+ expect(await response.json()).toMatchObject({ machineId: "m1", backendId: "codex", source: "stored_report", models: null })+})+it("retains owner, online and installed-backend guards", async () => {+ mocks.machine.mockResolvedValueOnce(null)+ expect((await GET(request())).status).toBe(404)+ mocks.machine.mockResolvedValueOnce({ id: "m1", status: "offline", availableRuntimes: [] })+ expect((await GET(request())).status).toBe(409)+ const response = await GET(request("missing"))+ expect(response.status).toBe(404)+ expect(await response.json()).toMatchObject({ code: "BACKEND_NOT_FOUND" })+})+it("returns model defaults and effort options without runtime diagnostics", async () => {+ mocks.machine.mockResolvedValueOnce({ id: "m1", status: "online", availableRuntimes: [{ id: "codex", status: "healthy", lastError: "private", reasoning: { updateMode: "live_next_turn", defaultModelId: "provider/model", catalogOrigin: "native_report", models: [{ id: "provider/model", supportedReasoningEfforts: [{ value: "high" }], defaultReasoningEffort: "high" }] } }] })+ const body = await (await GET(request())).json()+ expect(body).toMatchObject({ defaultModelId: "provider/model", models: [{ id: "provider/model", reasoningEfforts: [{ value: "high" }], defaultReasoningEffort: "high" }] })+ expect(JSON.stringify(body)).not.toContain("private")+ expect(body.catalogState).toBe("reported")+ expect(body.catalogOrigin).toBe("native_report")+})diff --git a/src/web/src/app/api/community/machines/[id]/route.ts b/src/web/src/app/api/community/machines/[id]/route.tsindex 62fb2e2ce..20910f84b 100644--- a/src/web/src/app/api/community/machines/[id]/route.ts+++ b/src/web/src/app/api/community/machines/[id]/route.ts@@ -1,6 +1,6 @@import { withCommunityActor } from "@/lib/middleware/community-actor"import { getPrimaryDb } from "@/lib/db"-import { requiresExplicitModel } from "@alook/shared"+import { projectMachineBackends } from "@/lib/community/machine-options.server"import { NextRequest, NextResponse } from "next/server"import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, WS_EVENTS } from "@alook/shared"@@ -119,8 +119,5 @@ export const GET = withCommunityActor(async (_req, ctx) => {const machine = await queries.communityBot.getMachineForOwner(db, ctx.params?.id as string, ownerId)if (!machine) return writeJSON({ error: "machine not found", code: "MACHINE_NOT_FOUND", machineId: ctx.params?.id }, 404)if (machine.status !== "online") return writeJSON({ error: "Target machine is offline", code: "MACHINE_OFFLINE", machineId: machine.id }, 409)- return writeJSON({ machineId: machine.id, status: machine.status, backends: machine.availableRuntimes.map((runtime) => ({- id: runtime.id, version: runtime.version, health: runtime.status, modelRequired: requiresExplicitModel(runtime.id),- catalogState: runtime.reasoning ? "reported" : "not_reported", catalogOrigin: runtime.reasoning?.catalogOrigin ?? "unknown",- })) })+ return writeJSON({ machineId: machine.id, status: machine.status, backends: projectMachineBackends(machine.availableRuntimes) })})diff --git a/src/web/src/app/api/community/servers/route.test.ts b/src/web/src/app/api/community/servers/route.test.tsindex af3d16cfe..3d75d6821 100644--- a/src/web/src/app/api/community/servers/route.test.ts+++ b/src/web/src/app/api/community/servers/route.test.ts@@ -44,7 +44,7 @@ vi.mock("@/lib/middleware/helpers", () => {})import { POST } from "./route"-import { WS_EVENTS, ROLES } from "@alook/shared"+import { WS_EVENTS, ROLES, MAX_SERVER_NAME_LENGTH, MAX_SERVER_DESCRIPTION_LENGTH } from "@alook/shared"function postReq(body: unknown) {return new NextRequest("http://localhost/api/community/servers", {@@ -123,6 +123,47 @@ describe("POST /api/community/servers", () => {expect(fanOut).not.toHaveBeenCalled()})+ it("rejects malformed JSON without creating or publishing a server", async () => {+ const response = await POST(new NextRequest("http://localhost/api/community/servers", {+ method: "POST", body: "{", headers: { "Content-Type": "application/json" },+ }))+ expect(response.status).toBe(400)+ expect(await response.json()).toEqual({ error: "invalid request body" })+ expect(createServer).not.toHaveBeenCalled()+ expect(fanOut).not.toHaveBeenCalled()+ })++ it.each([" ", "n".repeat(MAX_SERVER_NAME_LENGTH + 1)])("rejects a blank or overlength name", async (name) => {+ const response = await POST(postReq({ name }))+ expect(response.status).toBe(400)+ expect(await response.json()).toEqual({ error: `name must be 1-${MAX_SERVER_NAME_LENGTH} characters` })+ expect(createServer).not.toHaveBeenCalled()+ expect(fanOut).not.toHaveBeenCalled()+ })++ it.each([null, 42, "d".repeat(MAX_SERVER_DESCRIPTION_LENGTH + 1)])("rejects an invalid description", async (description) => {+ const response = await POST(postReq({ name: "New", description }))+ expect(response.status).toBe(400)+ expect(await response.json()).toEqual({ error: typeof description === "string"+ ? `description must be ≤ ${MAX_SERVER_DESCRIPTION_LENGTH} characters` : "description must be a string" })+ expect(createServer).not.toHaveBeenCalled()+ expect(fanOut).not.toHaveBeenCalled()+ })++ it.each(["", " Keep these spaces\nand this line. ", "d".repeat(MAX_SERVER_DESCRIPTION_LENGTH)])("preserves a valid description verbatim", async (description) => {+ const server = { id: "srv_description", name: "New", description, ownerId: "u1" }+ createServer.mockResolvedValueOnce({ server,+ ownerMember: { id: "mem_description", userId: "u1", joinedAt, userName: "Alice" },+ })++ const response = await POST(postReq({ name: "New", description }))++ expect(response.status).toBe(201)+ expect(createServer).toHaveBeenCalledExactlyOnceWith({}, { name: "New", description, ownerId: "u1" })+ expect(await response.json()).toEqual({ server })+ expect(fanOut).toHaveBeenCalledOnce()+ })+it("normalizes a spaced name via slugify before creating the server", async () => {createServer.mockResolvedValue({server: { id: "srv_1", name: "My-Home", ownerId: "u1" },diff --git a/src/web/src/app/api/community/servers/route.ts b/src/web/src/app/api/community/servers/route.tsindex baa3ebeda..9fb80e27d 100644--- a/src/web/src/app/api/community/servers/route.ts+++ b/src/web/src/app/api/community/servers/route.ts@@ -1,18 +1,9 @@-import { NextRequest } from "next/server"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb, getPrimaryDb } from "@/lib/db"-import {- queries,- MAX_SERVER_NAME_LENGTH,- MAX_SERVER_DESCRIPTION_LENGTH,- ROLES,- WS_EVENTS,- slugify,- withD1Retry,-} from "@alook/shared"+import { queries, withD1Retry } from "@alook/shared"+import { writeJSON } from "@/lib/middleware/helpers"+import { getPrimaryDb } from "@/lib/db"import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"-import { fanOutToServerMembers } from "@/lib/community/fanout"-import { canonicalUserImage, serverIconUrl } from "@/lib/community/storage"+import { serverIconUrl } from "@/lib/community/storage"+import { createServerForUser } from "@/lib/community/create-server.server"export const GET = withCommunityActor(async (_req, ctx) => {const db = getPrimaryDb(ctx.env.DB)@@ -64,72 +55,8 @@ export const GET = withCommunityActor(async (_req, ctx) => {})})-/**- * POST — create a server. Human-only: there is no bot create-server verb today,- * so a bot actor is rejected 403 (`rejectBot`) rather than silently granted a- * new capability by the actor unification (plan §5 — capabilities are explicit,- * not "whatever the route happens to accept").- */-export const POST = withCommunityActor(async (req: NextRequest, ctx) => {+export const POST = withCommunityActor(async (req, ctx) => {const denied = rejectBot(ctx.actor)if (denied) return denied-- const db = getDb(ctx.env.DB)-- let body: { name?: string; description?: string }- try {- body = await req.json()- } catch {- return writeError("invalid request body", 400)- }-- if (!body.name || typeof body.name !== "string") {- return writeError("name is required", 400)- }- const trimmed = body.name.trim()- if (!trimmed || trimmed.length > MAX_SERVER_NAME_LENGTH) {- return writeError(`name must be 1-${MAX_SERVER_NAME_LENGTH} characters`, 400)- }- const name = slugify(trimmed)- if (!name) {- return writeError("name is required", 400)- }-- let description: string | undefined- if (body.description !== undefined) {- if (typeof body.description !== "string") {- return writeError("description must be a string", 400)- }- if (body.description.length > MAX_SERVER_DESCRIPTION_LENGTH) {- return writeError(`description must be ≤ ${MAX_SERVER_DESCRIPTION_LENGTH} characters`, 400)- }- description = body.description- }-- const { server, ownerMember } = await queries.communityServer.createServer(db, {- name,- description,- ownerId: ctx.actor.userId,- })-- fanOutToServerMembers(server.id, {- type: WS_EVENTS.MEMBER_JOIN,- serverId: server.id,- member: {- id: ownerMember.id,- userId: ctx.actor.userId,- name: ownerMember.userName,- discriminator: ownerMember.userDiscriminator,- avatar: canonicalUserImage(- ownerMember.userId,- ownerMember.userImage,- ownerMember.userAvatarVersion,- ),- avatarVersion: ownerMember.userAvatarVersion,- role: ROLES.OWNER,- joinedAt: ownerMember.joinedAt,- },- })-- return writeJSON({ server }, 201)+ return createServerForUser(req, { env: ctx.env, userId: ctx.actor.userId })})diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.cssindex b9a00a1f0..e5766a178 100644--- a/src/web/src/app/globals.css+++ b/src/web/src/app/globals.css@@ -599,6 +599,11 @@ body.driver-active .community-ws-reconnect-overlay * {background-color: oklch(var(--forum-tag-bg-l) var(--forum-tag-bg-c) var(--forum-tag-hue));}+.automation-write-color {+ color: oklch(var(--forum-tag-bg-l) var(--forum-tag-bg-c) var(--forum-tag-hue));+ background-color: oklch(var(--forum-tag-text-l) var(--forum-tag-text-c) var(--forum-tag-hue));+}+/* ── Object-mimicry card grain texture (shared) ── */.card-grain {position: relative;diff --git a/src/web/src/components/community/bots/bot-memberships-sheet.tsx b/src/web/src/components/community/bots/bot-memberships-sheet.tsxindex 82a042795..620bcbd2d 100644--- a/src/web/src/components/community/bots/bot-memberships-sheet.tsx+++ b/src/web/src/components/community/bots/bot-memberships-sheet.tsx@@ -1,13 +1,14 @@"use client"import { useAtom, useCreateAtom } from "@tanstack/react-store"-import { Loader2, Lock, LogOut } from "lucide-react"+import { Loader2, Lock, LogOut, Network } from "lucide-react"import { AgentAvatar } from "@/components/avatar"import { Button } from "@/components/ui/button"import { Skeleton } from "@/components/ui/skeleton"import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"import { CommunitySheet } from "../shell/community-sheet"import { ServerIcon } from "../server-icon"+import { EmptyState } from "../empty-state"import { EntityIcon } from "../entity-icon"import { avatarInitial } from "@/lib/community/avatar"import { tid } from "@/lib/community/testids"@@ -33,10 +34,10 @@ export function BotMembershipsSheet({ bot, open, onOpenChange }: {}}return <>- <CommunitySheet open={open} onOpenChange={(next) => { if (!next) setTarget(null); onOpenChange(next) }} title="Servers & channels" description={<span className="flex min-w-0 items-center gap-2"><AgentAvatar name={bot.name} avatarUrl={bot.image} seed={bot.id} size={24} /><span className="min-w-0 truncate" title={bot.name}>{bot.name}</span></span>} contentTestId={tid.botMembershipsSheet}>+ <CommunitySheet open={open} onOpenChange={(next) => { if (!next) setTarget(null); onOpenChange(next) }} title="Servers & channels" description={<span className="flex min-w-0 items-center gap-2"><AgentAvatar name={bot.name} avatarUrl={bot.image} seed={bot.id} size={24} /><span className="min-w-0 truncate" title={bot.name}>{bot.name}</span></span>} contentTestId={tid.botMembershipsSheet} bodyClassName="flex flex-col">{memberships.isPending ? <div className="space-y-6" aria-label="Loading servers and channels" aria-busy="true">{[0, 1, 2].map((i) => <div key={i} className="space-y-3"><Skeleton className="h-4 w-36" /><Skeleton className="ml-6 h-9 w-3/4" /><Skeleton className="ml-6 h-9 w-2/3" /></div>)}</div>: memberships.isError ? <div className="space-y-3 py-6"><p role="alert" className="text-sm text-muted-foreground">Could not load servers and channels.</p><Button variant="outline" disabled={memberships.isFetching} onClick={() => void memberships.refetch()}>Try again</Button></div>- : memberships.data?.servers.length === 0 ? <div className="py-8"><p className="font-medium">No servers yet</p><p className="mt-1 text-sm text-muted-foreground">{bot.name} hasn't joined any servers.</p></div>+ : memberships.data?.servers.length === 0 ? <EmptyState icon={Network} label={`${bot.name} hasn't joined any servers.`} />: <div className="space-y-6">{memberships.data?.servers.map((server) => <section key={server.id} data-testid={tid.botMembershipsServer(server.id)}><div className="flex min-h-11 items-center gap-2"><ServerIcon id={server.id} name={server.name} initial={avatarInitial(server.name)} icon={server.icon} size={16} className="shrink-0 rounded-sm" />diff --git a/src/web/src/components/community/messages/message.render.dom.test.ts b/src/web/src/components/community/messages/message.render.dom.test.tsindex 3d40da4e6..5ac439cc3 100644--- a/src/web/src/components/community/messages/message.render.dom.test.ts+++ b/src/web/src/components/community/messages/message.render.dom.test.ts@@ -93,8 +93,8 @@ vi.mock("@/components/ui/context-menu", async (importOriginal) => {style: { ...props.style, ...render.props.style },"data-slot": "context-menu-trigger",} as React.HTMLAttributes<HTMLElement>),- ContextMenuContent: ({ children }: { children: React.ReactNode }) =>- ReactModule.createElement("mock-context-menu-content", null, children),+ ContextMenuContent: ({ children, ...props }: { children: React.ReactNode; finalFocus?: unknown }) =>+ ReactModule.createElement("mock-context-menu-content", props, children),ContextMenuItem: ({children,...props@@ -2164,3 +2164,37 @@ describe("Message lazy overlays", () => {expect(otherCallback).not.toHaveBeenCalled()})})+++describe("Message selected-text menu focus", () => {+ it("retains keyboard focus policy through close and leaves pointer focus alone", () => {+ const view = rtlRender(makeTree({ m: baseMsg({ content: "selected message" }), hoverCapable: true, onCopy: vi.fn() }))+ const row = view.container.querySelector('[data-slot="context-menu-trigger"]') as HTMLElement+ fireEvent.pointerEnter(row, { pointerType: "mouse" })+ const popup = () => view.container.querySelector("mock-context-menu-content")!+ expect(hostProps(popup()).finalFocus).toBeUndefined()+ const body = row.querySelector("[data-community-message-body]")!+ const range = document.createRange()+ range.selectNodeContents(body)+ const selection = window.getSelection()!+ selection.removeAllRanges()+ selection.addRange(range)+ fireEvent.contextMenu(body)+ const menu = view.container.querySelector("mock-context-menu")!+ act(() => (hostProps(menu).onOpenChange as (open: boolean) => void)(false))+ const finalFocus = hostProps(popup()).finalFocus as (type: string) => boolean+ expect(finalFocus).toBeTypeOf("function")+ const focus = vi.spyOn(row, "focus")+ expect(finalFocus("mouse")).toBe(false)+ expect(focus).not.toHaveBeenCalled()+ expect(finalFocus("keyboard")).toBe(false)+ expect(focus).toHaveBeenCalledWith({ preventScroll: true })+ expect(row).toHaveFocus()+ // jsdom collapses selection on every focus(); real preservation is covered by browser test23.+ selection.removeAllRanges()+ fireEvent.contextMenu(body)+ expect(hostProps(popup()).finalFocus).toBeUndefined()+ view.unmount()+ expect(finalFocus("keyboard")).toBe(false)+ })+})diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsxindex 227d5a52f..ca13ff34d 100644--- a/src/web/src/components/community/messages/message.tsx+++ b/src/web/src/components/community/messages/message.tsx@@ -246,6 +246,7 @@ function MessageImpl({// Right-click context-menu open state — tracked so the Mark/Unmark label's// lazy read fires for the context menu too, not just the ⋯ dropdown.const [contextOpen, setContextOpen] = useAtom(useCreateAtom(false))+ const contextRowRef = useRef<HTMLDivElement | null>(null)const [contextSelectedText, setContextSelectedText] = useAtom(useCreateAtom<string | null>(null))// Touch devices use a normal tap-triggered dropdown. Long-press is left to// the browser so message text keeps native selection/copy behavior.@@ -405,6 +406,8 @@ function MessageImpl({<divdata-base-ui-swipe-ignore={pageSwipe.page ? "y" : ""}data-page-swipe-reply-row=""+ ref={contextRowRef}+ tabIndex={interactive && contextMenuEnabled ? -1 : undefined}data-message-context-menu={interactive && contextMenuEnabled ? "true" : undefined}className={["group relative -mx-2 -my-1 flex gap-2 rounded px-2 py-1 transition-colors",@@ -969,7 +972,6 @@ function MessageImpl({setContextOpen(open && contextMenuEnabled)if (!open) {setLinkTarget(null)- setContextSelectedText(null)}}}>@@ -979,7 +981,13 @@ function MessageImpl({render={row}/>{activated && !touchMenuActive && (- <ContextMenuContent className="w-48">+ <ContextMenuContent className="w-48" finalFocus={contextSelectedText ? (closeType) => {+ // Keep this policy through the exit animation. The next context+ // gesture replaces the selection snapshot, including with null.+ // Editor focus would collapse the selected message text.+ if (closeType === "keyboard") contextRowRef.current?.focus({ preventScroll: true })+ return false+ } : undefined}><MessageContextItems{...menuHandlers}{...linkMenuHandlers}diff --git a/src/web/src/components/community/settings/automation-settings.dom.test.tsx b/src/web/src/components/community/settings/automation-settings.dom.test.tsxnew file mode 100644index 000000000..946f640bf--- /dev/null+++ b/src/web/src/components/community/settings/automation-settings.dom.test.tsx@@ -0,0 +1,209 @@+import React from "react"+import { describe, it, expect, vi, beforeEach } from "vitest"+import { render, screen, setupUser, waitFor } from "@/test/react-dom-harness"+import type { AutomationAccessCode } from "@alook/shared"+import { AutomationCodeForm, AutomationSettings } from "./automation-settings"++vi.mock("./automation-setup-prompt", () => ({ AutomationSetupPrompt: () => null }))++const fixture: AutomationAccessCode = { id: "code-1", name: "Build script", createdAt: "2026-01-01T00:00:00Z", expiresAt: "2030-01-01T00:00:00Z", permissions: [{ permission: "bot.create", limit: 12, period: "day" }] }+const state = vi.hoisted(() => ({ execute: vi.fn(), refetch: vi.fn(), data: { accessCodes: [] as AutomationAccessCode[] }, isError: false, isPending: false }))+vi.mock("@/hooks/community/use-automation", () => ({ useAutomation: () => ({ list: { data: state.data, isError: state.isError, isPending: state.isPending, refetch: state.refetch }, execute: state.execute, pending: false }) }))+vi.mock("@/hooks/community/use-community-view-source", () => ({ useCommunityViewSource: () => ({ capture: () => Object.assign(() => {}, { signal: new AbortController().signal }) }) }))+beforeEach(() => {+ state.execute.mockReset(); state.refetch.mockReset(); state.data = { accessCodes: [] }; state.isError = false; state.isPending = false+})++describe("Automation form", () => {+ it("requires a permission and creates with 24h and independent default rates", async () => {+ const user = setupUser(), save = vi.fn().mockResolvedValue(undefined)+ render(<AutomationCodeForm pending={false} onCancel={() => {}} onSave={save} />)+ await user.type(screen.getByRole("textbox", { name: "Name" }), "Deploy")+ for (const name of ["List machines", "List friends", "List servers"]) await user.click(screen.getByRole("checkbox", { name }))+ await user.click(screen.getByRole("button", { name: "Create access code" }))+ expect(save).not.toHaveBeenCalled()+ expect(screen.getByRole("alert")).toHaveTextContent("at least one permission")+ await user.click(screen.getByRole("checkbox", { name: "Create bots" }))+ await user.click(screen.getByRole("checkbox", { name: "Create servers" }))+ await user.click(screen.getByRole("button", { name: "Advanced" }))+ await user.clear(screen.getByRole("spinbutton", { name: "Create bots request limit" }))+ await user.type(screen.getByRole("spinbutton", { name: "Create bots request limit" }), "5")+ await user.click(screen.getByRole("button", { name: "Create access code" }))+ expect(save).toHaveBeenCalledWith({ name: "Deploy", expiresIn: "24h", permissions: [{ permission: "bot.create", limit: 5, period: "hour" }, { permission: "server.create", limit: 64, period: "hour" }] }, true)+ })+ it("groups seven permissions and defaults only the three reads on", async () => {+ const user = setupUser(), save = vi.fn().mockResolvedValue(undefined)+ render(<AutomationCodeForm pending={false} onCancel={() => {}} onSave={save} />)+ expect(screen.getByRole("group", { name: /^Read$/ })).toBeInTheDocument()+ expect(screen.getByRole("group", { name: /^Write$/ })).toBeInTheDocument()+ expect(screen.getAllByRole("checkbox")).toHaveLength(7)+ for (const name of ["List machines", "List friends", "List servers"]) expect(screen.getByRole("checkbox", { name })).toBeChecked()+ for (const name of ["Create bots", "Create servers", "Invite friends to servers", "Send messages"]) expect(screen.getByRole("checkbox", { name })).not.toBeChecked()+ await user.type(screen.getByRole("textbox", { name: "Name" }), "Invitations")+ await user.click(screen.getByRole("checkbox", { name: "Invite friends to servers" }))+ await user.click(screen.getByRole("button", { name: "Create access code" }))+ expect(save).toHaveBeenCalledWith({ name: "Invitations", expiresIn: "24h", permissions: ["server.invite", "machine.read", "friend.read", "server.read"].map((permission) => ({ permission, limit: 64, period: "hour" })) }, true)+ })+ it("allows all seven permissions to be saved together", async () => {+ const user = setupUser(), save = vi.fn().mockResolvedValue(undefined)+ render(<AutomationCodeForm pending={false} onCancel={() => {}} onSave={save} />)+ await user.type(screen.getByRole("textbox", { name: "Name" }), "All actions")+ for (const name of ["Create bots", "Create servers", "Invite friends to servers", "Send messages"]) await user.click(screen.getByRole("checkbox", { name }))+ await user.click(screen.getByRole("button", { name: "Create access code" }))+ expect(save).toHaveBeenCalledWith({ name: "All actions", expiresIn: "24h", permissions: ["bot.create", "server.create", "server.invite", "message.send", "machine.read", "friend.read", "server.read"].map((permission) => ({ permission, limit: 64, period: "hour" })) }, true)+ })+ it("saves an opt-in send permission with its own limit", async () => {+ const user = setupUser(), save = vi.fn().mockResolvedValue(undefined)+ render(<AutomationCodeForm pending={false} onCancel={() => {}} onSave={save} />)+ await user.type(screen.getByRole("textbox", { name: "Name" }), "Messages")+ for (const name of ["List machines", "List friends", "List servers"]) await user.click(screen.getByRole("checkbox", { name }))+ await user.click(screen.getByRole("checkbox", { name: "Send messages" }))+ await user.click(screen.getByRole("button", { name: "Advanced" }))+ await user.clear(screen.getByRole("spinbutton", { name: "Send messages request limit" }))+ await user.type(screen.getByRole("spinbutton", { name: "Send messages request limit" }), "9")+ await user.click(screen.getByRole("button", { name: "Create access code" }))+ expect(save).toHaveBeenCalledWith({ name: "Messages", expiresIn: "24h", permissions: [{ permission: "message.send", limit: 9, period: "hour" }] }, true)+ })+ it("hides rates in Advanced without losing an edited limit when collapsed", async () => {+ const user = setupUser(), save = vi.fn().mockResolvedValue(undefined)+ render(<AutomationCodeForm code={fixture} pending={false} onCancel={() => {}} onSave={save} />)+ expect(screen.queryByRole("spinbutton")).not.toBeInTheDocument()+ expect(screen.getByRole("button", { name: "Advanced" })).toHaveAttribute("aria-expanded", "false")+ await user.click(screen.getByRole("button", { name: "Advanced" }))+ await user.clear(screen.getByRole("spinbutton"))+ await user.type(screen.getByRole("spinbutton"), "20")+ await user.click(screen.getByRole("button", { name: "Advanced" }))+ expect(screen.queryByRole("spinbutton")).not.toBeInTheDocument()+ await user.click(screen.getByRole("button", { name: "Save changes" }))+ expect(save).toHaveBeenCalledWith(expect.objectContaining({ permissions: [{ permission: "bot.create", limit: 20, period: "day" }] }), false)+ })+ it("opens Advanced to reveal invalid limits submitted after collapsing", async () => {+ const user = setupUser(), save = vi.fn()+ render(<AutomationCodeForm code={fixture} pending={false} onCancel={() => {}} onSave={save} />)+ await user.click(screen.getByRole("button", { name: "Advanced" }))+ await user.clear(screen.getByRole("spinbutton"))+ await user.type(screen.getByRole("spinbutton"), "0")+ await user.click(screen.getByRole("button", { name: "Advanced" }))+ await user.click(screen.getByRole("button", { name: "Save changes" }))+ expect(save).not.toHaveBeenCalled()+ expect(screen.getByRole("spinbutton")).toHaveValue(0)+ expect(screen.getByRole("alert")).toHaveTextContent("whole-number limit")+ })+ it("prepopulates edits and preserves expiration unless a preset is selected", async () => {+ const user = setupUser(), save = vi.fn().mockResolvedValue(undefined)+ render(<AutomationCodeForm code={fixture} pending={false} onCancel={() => {}} onSave={save} />)+ await user.click(screen.getByRole("button", { name: "Advanced" }))+ expect(screen.getByRole("spinbutton")).toHaveValue(12)+ expect(screen.getByRole("combobox", { name: "Expiration" })).toHaveTextContent("Keep current expiration")+ await user.click(screen.getByRole("button", { name: "Save changes" }))+ expect(save).toHaveBeenLastCalledWith(expect.objectContaining({ permissions: fixture.permissions }), false)+ await user.click(screen.getByRole("combobox", { name: "Expiration" }))+ await user.click(await screen.findByRole("option", { name: "7 days" }))+ await user.click(screen.getByRole("button", { name: "Save changes" }))+ expect(save).toHaveBeenLastCalledWith(expect.objectContaining({ expiresIn: "7d" }), true)+ })+ it("omits a removed permission and preserves draft when save fails", async () => {+ const user = setupUser(), save = vi.fn().mockRejectedValue(new Error("Try again later"))+ render(<AutomationCodeForm code={fixture} pending={false} onCancel={() => {}} onSave={save} />)+ await user.click(screen.getByRole("checkbox", { name: "Create bots" }))+ await user.click(screen.getByRole("checkbox", { name: "Create servers" }))+ await user.click(screen.getByRole("button", { name: "Save changes" }))+ expect(save).toHaveBeenCalledWith(expect.objectContaining({ permissions: [{ permission: "server.create", limit: 64, period: "hour" }] }), false)+ expect(await screen.findByRole("alert")).toHaveTextContent("Try again later")+ expect(screen.getByRole("textbox", { name: "Name" })).toHaveValue("Build script")+ })+ it("uses native integer boundaries and disables controls during submit", async () => {+ const view = render(<AutomationCodeForm code={fixture} pending={false} onCancel={() => {}} onSave={vi.fn()} />)+ await setupUser().click(screen.getByRole("button", { name: "Advanced" }))+ view.rerender(<AutomationCodeForm code={fixture} pending onCancel={() => {}} onSave={vi.fn()} />)+ expect(screen.getByRole("spinbutton")).toHaveAttribute("max", "1536")+ expect(screen.getByRole("spinbutton")).toHaveAttribute("min", "1")+ expect(screen.getByRole("spinbutton")).toHaveAttribute("step", "1")+ expect(screen.getByRole("spinbutton")).toBeDisabled()+ expect(screen.getByRole("button", { name: "Saving…" })).toBeDisabled()+ })+})++describe("Automation settings", () => {+ it("shows the send Write badge and preserves its policy when editing", async () => {+ const policy = { permission: "message.send" as const, limit: 9, period: "day" as const }+ state.data = { accessCodes: [{ ...fixture, permissions: [policy] }] }+ state.execute.mockResolvedValue(undefined)+ const user = setupUser()+ render(<AutomationSettings userId="owner" />)+ expect(screen.getByLabelText("Write: Send messages")).toBeInTheDocument()+ await user.click(screen.getByRole("button", { name: "Edit Build script" }))+ expect(screen.getByRole("checkbox", { name: "Send messages" })).toBeChecked()+ await user.click(screen.getByRole("button", { name: "Advanced" }))+ expect(screen.getByRole("spinbutton", { name: "Send messages request limit" })).toHaveValue(9)+ await user.click(screen.getByRole("button", { name: "Save changes" }))+ expect(state.execute).toHaveBeenCalledWith({ kind: "update", id: fixture.id, data: { name: fixture.name, permissions: [policy] } })+ })+ it("shows loading and errors without a false empty state", async () => {+ state.isPending = true+ const view = render(<AutomationSettings userId="owner" />)+ expect(screen.getByRole("status", { name: "Loading access codes" })).toBeInTheDocument()+ state.isPending = false; state.isError = true+ view.rerender(<AutomationSettings userId="owner" />)+ expect(screen.getByRole("alert")).toHaveTextContent("Could not load access codes")+ expect(screen.queryByText(/No access codes yet/)).not.toBeInTheDocument()+ await setupUser().click(screen.getByRole("button", { name: "Try again" }))+ expect(state.refetch).toHaveBeenCalledOnce()+ })+ it("shows the secret only after creation and clears it with Done", async () => {+ const user = setupUser()+ state.execute.mockImplementation(async (_command, created) => created?.({ accessCode: fixture, secret: "synthetic-secret-for-test" }))+ render(<AutomationSettings userId="owner" />)+ await user.click(screen.getByRole("button", { name: "Create access code" }))+ await user.type(screen.getByRole("textbox", { name: "Name" }), "Test")+ await user.click(screen.getByRole("checkbox", { name: "Create bots" }))+ await user.click(screen.getByRole("button", { name: "Create access code" }))+ expect(await screen.findByDisplayValue("synthetic-secret-for-test")).toBeInTheDocument()+ await user.click(screen.getByRole("button", { name: "Done" }))+ expect(screen.getByRole("heading", { name: "Have you saved your access code?" })).toBeInTheDocument()+ await user.click(screen.getByRole("button", { name: "Cancel" }))+ expect(screen.getByDisplayValue("synthetic-secret-for-test")).toBeInTheDocument()+ await user.click(screen.getByRole("button", { name: "Done" }))+ await user.click(screen.getByRole("button", { name: "I've saved it" }))+ expect(screen.queryByDisplayValue("synthetic-secret-for-test")).not.toBeInTheDocument()+ })+ it("keeps the one-time code selectable when clipboard access fails", async () => {+ const user = setupUser()+ const copy = vi.spyOn(navigator.clipboard, "writeText").mockRejectedValue(new Error("Clipboard denied"))+ state.execute.mockImplementation(async (_command, created) => created?.({ accessCode: fixture, secret: "synthetic-only-copy-test" }))+ render(<AutomationSettings userId="owner" />)+ await user.click(screen.getByRole("button", { name: "Create access code" }))+ await user.type(screen.getByRole("textbox", { name: "Name" }), "Test")+ await user.click(screen.getByRole("button", { name: "Create access code" }))+ await user.click(await screen.findByRole("button", { name: "Copy code" }))+ expect(screen.getByRole("status")).toHaveTextContent("Copy failed. Select the code and copy it manually.")+ expect(screen.getByDisplayValue("synthetic-only-copy-test")).toHaveAttribute("readonly")+ copy.mockRestore()+ })+ it("shows a compact permission summary and preserves expiration when editing details", async () => {+ state.data = { accessCodes: [fixture] }; state.execute.mockResolvedValue(undefined)+ const user = setupUser()+ render(<AutomationSettings userId="owner" />)+ expect(screen.getByText("Create bots")).toBeInTheDocument()+ expect(screen.queryByText(/12\/day/)).not.toBeInTheDocument()+ await user.click(screen.getByRole("button", { name: "Edit Build script" }))+ await user.click(screen.getByRole("button", { name: "Advanced" }))+ expect(screen.getByRole("spinbutton")).toHaveValue(12)+ await user.click(screen.getByRole("button", { name: "Save changes" }))+ expect(state.execute).toHaveBeenCalledWith({ kind: "update", id: fixture.id, data: { name: fixture.name, permissions: fixture.permissions } })+ })+ it("confirms the named code before deletion and retains it on failure", async () => {+ state.data = { accessCodes: [fixture] }; state.execute.mockRejectedValue(new Error("Deletion unavailable"))+ const user = setupUser()+ render(<AutomationSettings userId="owner" />)+ await user.click(screen.getByRole("button", { name: "Delete Build script" }))+ expect(screen.getByRole("heading", { name: "Delete “Build script”?" })).toBeInTheDocument()+ await user.click(screen.getByRole("button", { name: "Cancel" }))+ expect(state.execute).not.toHaveBeenCalled()+ await user.click(screen.getByRole("button", { name: "Delete Build script" }))+ await user.click(screen.getByRole("button", { name: "Delete code" }))+ await waitFor(() => expect(state.execute).toHaveBeenCalledWith({ kind: "delete", id: fixture.id }))+ expect(await screen.findByRole("alert")).toHaveTextContent("Deletion unavailable")+ expect(screen.getByText("Build script")).toBeInTheDocument()+ })+})diff --git a/src/web/src/components/community/settings/automation-settings.tsx b/src/web/src/components/community/settings/automation-settings.tsxnew file mode 100644index 000000000..88a19482b--- /dev/null+++ b/src/web/src/components/community/settings/automation-settings.tsx@@ -0,0 +1,213 @@+"use client"++import type { CSSProperties } from "react"+import { useAtom, useCreateAtom } from "@tanstack/react-store"+import { AUTOMATION_READ_PERMISSIONS, AutomationAccessCodeCreateSchema, type AutomationAccessCode, type AutomationAccessCodeCreate, type AutomationAccessCodeCreateResponse, type AutomationExpiry, type AutomationPermissionPolicy } from "@alook/shared"+import { ChevronDown, Copy, Pencil, Trash2 } from "lucide-react"+import { Button } from "@/components/ui/button"+import { Badge } from "@/components/ui/badge"+import { Input } from "@/components/ui/input"+import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "@/components/ui/select"+import { ConfirmDialog } from "@/components/ui/confirm-dialog"+import { Skeleton } from "@/components/ui/skeleton"+import { useAutomation } from "@/hooks/community/use-automation"+import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"+import { getErrorMessage } from "@/lib/api/client"+import { isAbortError } from "@/lib/errors"+import { tid } from "@/lib/community/testids"+import { tagColorClassName } from "@/lib/community/tag-color"+import { AutomationSetupPrompt } from "./automation-setup-prompt"++const expiryOptions = [+ ["1h", "1 hour"], ["24h", "24 hours"], ["7d", "7 days"], ["30d", "30 days"], ["forever", "Never expires"],+] as const+const permissionOptions = [+ { permission: "bot.create", label: "Create bots", group: "Write" },+ { permission: "server.create", label: "Create servers", group: "Write" },+ { permission: "server.invite", label: "Invite friends to servers", group: "Write" },+ { permission: "message.send", label: "Send messages", group: "Write" },+ { permission: "machine.read", label: "List machines", group: "Read" },+ { permission: "friend.read", label: "List friends", group: "Read" },+ { permission: "server.read", label: "List servers", group: "Read" },+] as const+const permissionColors: Record<"Read" | "Write", CSSProperties & { "--forum-tag-hue": number }> = {+ Read: { "--forum-tag-hue": 145 },+ Write: { "--forum-tag-hue": 30 },+}+const control = "h-11 sm:h-8"+const selectControl = "data-[size=default]:h-11 sm:data-[size=default]:h-8"++function expiryLabel(code: AutomationAccessCode) {+ if (!code.expiresAt) return "Never expires"+ const time = new Date(code.expiresAt)+ return `${time.getTime() <= Date.now() ? "Expired" : "Expires"} ${time.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" })}`+}++type DraftPolicy = { enabled: boolean; limit: string; period: AutomationPermissionPolicy["period"] }++export function AutomationCodeForm({ code, pending, onCancel, onSave }: {+ code?: AutomationAccessCode+ pending: boolean+ onCancel: () => void+ onSave: (data: AutomationAccessCodeCreate, renew: boolean) => Promise<void>+}) {+ const [advanced, setAdvanced] = useAtom(useCreateAtom(false))+ const [name, setName] = useAtom(useCreateAtom(code?.name ?? ""))+ const [expiry, setExpiry] = useAtom(useCreateAtom<AutomationExpiry | "keep">(code ? "keep" : "24h"))+ const [policies, setPolicies] = useAtom(useCreateAtom<DraftPolicy[]>(permissionOptions.map(({ permission }) => {+ const existing = code?.permissions.find((policy) => policy.permission === permission)+ return { enabled: code ? Boolean(existing) : (AUTOMATION_READ_PERMISSIONS as readonly string[]).includes(permission), limit: String(existing?.limit ?? 64), period: existing?.period ?? "hour" }+ })))+ const [error, setError] = useAtom(useCreateAtom<string | null>(null))+ const updatePolicy = (index: number, patch: Partial<DraftPolicy>) => setPolicies((current) => current.map((policy, i) => i === index ? { ...policy, ...patch } : policy))+ return (+ <form className="space-y-8" onSubmit={async (event) => {+ event.preventDefault()+ if (pending) return+ setError(null)+ const parsed = AutomationAccessCodeCreateSchema.safeParse({+ name, expiresIn: expiry === "keep" ? "24h" : expiry,+ permissions: policies.flatMap((policy, index) => policy.enabled ? [{ permission: permissionOptions[index].permission, limit: Number(policy.limit), period: policy.period }] : []),+ })+ if (!parsed.success) { if (parsed.error.issues.some((issue) => issue.path.includes("limit"))) setAdvanced(true); setError("Enter a name, select at least one permission, and use a whole-number limit from 1–64 per hour or 1–1,536 per day."); return }+ try { await onSave(parsed.data, expiry !== "keep") } catch (cause) {+ if (!isAbortError(cause)) setError(getErrorMessage(cause, "Could not save this access code. Try again."))+ }+ }}>+ <h2 className="text-base font-medium">{code ? "Edit access code" : "Create access code"}</h2>+ <div className="space-y-4">+ <div className="space-y-2">+ <label htmlFor="automation-name" className="text-sm font-medium">Name</label>+ <Input id="automation-name" data-testid={tid.automationName} className={control} value={name} onChange={(event) => setName(event.target.value)} maxLength={100} required autoComplete="off" placeholder="e.g. Project setup" disabled={pending} />+ </div>+ <div className="space-y-2">+ <label id="automation-expiry-label" className="text-sm font-medium">{code ? "Expiration" : "Expires in"}</label>+ <Select value={expiry} onValueChange={(value) => { if (value) setExpiry(value) }} disabled={pending}>+ <SelectTrigger aria-labelledby="automation-expiry-label" data-testid={tid.automationExpiry} className={`${selectControl} w-full`}><SelectValue>{expiry === "keep" ? "Keep current expiration" : expiryOptions.find(([value]) => value === expiry)?.[1]}</SelectValue></SelectTrigger>+ <SelectContent>{code ? <SelectItem value="keep" className="min-h-11 sm:min-h-8">Keep current expiration</SelectItem> : null}{expiryOptions.map(([value, label]) => <SelectItem key={value} value={value} className="min-h-11 sm:min-h-8">{label}</SelectItem>)}</SelectContent>+ </Select>+ {code ? <p className="text-xs leading-5 text-muted-foreground">{expiry === "keep" ? expiryLabel(code) : "The new expiration starts when you save."}</p> : null}+ </div>+ </div>+ <fieldset className="space-y-4" disabled={pending}>+ <legend className="mb-2 text-sm font-medium">Permissions</legend>+ <p className="text-sm text-muted-foreground">Choose what this code can do. Each permission has its own request limit.</p>+ {(["Read", "Write"] as const).map((group) => <fieldset key={group} className="space-y-2">+ <legend className="mb-2 text-xs font-medium text-muted-foreground">{group}</legend>+ {permissionOptions.map(({ permission, label, group: permissionGroup }, index) => {+ if (permissionGroup !== group) return null+ const policy = policies[index]+ return <div key={permission} className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">+ <label className="flex min-h-11 cursor-pointer items-center gap-2 text-sm sm:min-h-8">+ <input type="checkbox" checked={policy.enabled} onChange={(event) => updatePolicy(index, { enabled: event.target.checked })} className="size-4 accent-primary focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-ring" />+ {label}+ </label>+ </div>+ })}+ </fieldset>)}+ </fieldset>+ <section className="space-y-4">+ <Button type="button" variant="ghost" className={`${control} -ml-2 justify-start gap-2 px-2`} aria-expanded={advanced} aria-controls="automation-rate-limits" onClick={() => setAdvanced(!advanced)} disabled={pending}>+ <ChevronDown className={`size-4 transition-transform ${advanced ? "rotate-180" : ""}`} />Advanced+ </Button>+ {advanced ? <fieldset id="automation-rate-limits" className="space-y-4" disabled={pending}>+ <legend className="mb-2 text-sm font-medium">Request limits</legend>+ <p className="text-xs leading-5 text-muted-foreground">Each permission defaults to 64 requests per hour. Limits use the last hour or 24 hours. Daily limits also have a cap of 64 requests in the last hour.</p>+ {permissionOptions.map(({ permission, label }, index) => {+ const policy = policies[index]+ if (!policy.enabled) return null+ return <div key={permission} className="flex items-center gap-4">+ <span className="min-w-0 flex-1 text-sm">{label}</span>+ <div className="flex shrink-0 items-center gap-2">+ <Input type="number" aria-label={`${label} request limit`} className={`${control} w-24 font-mono tabular-nums`} min={1} max={policy.period === "hour" ? 64 : 1536} step={1} required value={policy.limit} onChange={(event) => updatePolicy(index, { limit: event.target.value })} />+ <Select value={policy.period} onValueChange={(value) => { if (value) updatePolicy(index, { period: value }) }} disabled={pending}>+ <SelectTrigger className={selectControl} aria-label={`${label} limit period`}><SelectValue>{policy.period === "hour" ? "per hour" : "per day"}</SelectValue></SelectTrigger>+ <SelectContent><SelectItem value="hour" className="min-h-11 sm:min-h-8">per hour</SelectItem><SelectItem value="day" className="min-h-11 sm:min-h-8">per day</SelectItem></SelectContent>+ </Select>+ </div>+ </div>+ })}+ </fieldset> : null}+ </section>+ {error ? <p role="alert" className="text-sm text-destructive">{error}</p> : null}+ <div className="flex justify-end gap-2">+ <Button type="button" variant="ghost" className={control} onClick={onCancel} disabled={pending}>Cancel</Button>+ <Button type="submit" className={control} data-testid={tid.automationSave} disabled={pending}>{pending ? "Saving…" : code ? "Save changes" : "Create access code"}</Button>+ </div>+ </form>+ )+}++function CreatedCode({ result, onDone }: { result: AutomationAccessCodeCreateResponse; onDone: () => void }) {+ const [copyState, setCopyState] = useAtom(useCreateAtom<"idle" | "copied" | "error">("idle"))+ const [confirmDone, setConfirmDone] = useAtom(useCreateAtom(false))+ const source = useCommunityViewSource("automation-secret")+ return <section className="space-y-8">+ <div className="space-y-2">+ <h2 className="text-base font-medium">Access code created</h2>+ <p className="text-sm leading-6 text-muted-foreground">Copy this code now. You cannot view it again after leaving this screen.</p>+ </div>+ <div className="space-y-2">+ <label htmlFor="automation-secret" className="block wrap-break-word text-sm font-medium">{result.accessCode.name}</label>+ <Input id="automation-secret" data-testid={tid.automationSecret} className={`${control} font-mono`} readOnly value={result.secret} autoComplete="off" spellCheck={false} onFocus={(event) => event.target.select()} />+ <div className="flex flex-wrap items-center gap-2">+ <Button type="button" className={control} onClick={async () => {+ const assert = source.capture()+ try { assert(); await navigator.clipboard.writeText(result.secret); assert(); setCopyState("copied") } catch (cause) {+ if (!isAbortError(cause)) { try { assert(); setCopyState("error") } catch { return } }+ }+ }}><Copy className="size-4" />{copyState === "copied" ? "Copied" : "Copy code"}</Button>+ <span role="status" className="text-xs text-muted-foreground">{copyState === "error" ? "Copy failed. Select the code and copy it manually." : copyState === "copied" ? "Code copied" : ""}</span>+ </div>+ </div>+ <div className="flex justify-end"><Button variant="outline" className={control} onClick={() => setConfirmDone(true)}>Done</Button></div>+ <ConfirmDialog open={confirmDone} onOpenChange={setConfirmDone} title="Have you saved your access code?" description="You cannot view this code again after leaving this screen." confirmLabel="I've saved it" confirmVariant="default" onConfirm={onDone} />+ </section>+}++export function AutomationSettings({ userId }: { userId: string }) {+ const { list, execute, pending } = useAutomation(userId)+ const [editing, setEditing] = useAtom(useCreateAtom<AutomationAccessCode | "new" | null>(null))+ const [created, setCreated] = useAtom(useCreateAtom<AutomationAccessCodeCreateResponse | null>(null))+ const [deleting, setDeleting] = useAtom(useCreateAtom<AutomationAccessCode | null>(null))+ const [error, setError] = useAtom(useCreateAtom<string | null>(null))+ return <div className="w-full space-y-8" data-testid={tid.automationPanel}>+ {created ? <CreatedCode result={created} onDone={() => setCreated(null)} /> : editing ? (+ <AutomationCodeForm key={editing === "new" ? "new" : editing.id} code={editing === "new" ? undefined : editing} pending={pending} onCancel={() => setEditing(null)} onSave={async (data, renew) => {+ if (editing === "new") await execute({ kind: "create", data }, setCreated)+ else await execute({ kind: "update", id: editing.id, data: { name: data.name, permissions: data.permissions, ...(renew ? { expiresIn: data.expiresIn } : {}) } })+ setEditing(null)+ }} />+ ) : <>+ <div className="space-y-4">+ <div className="space-y-2">+ <p className="max-w-prose text-sm leading-6 text-muted-foreground">Access codes let scripts read your lists, create bots and servers, invite friends, or send messages. You choose the permissions and limits.</p>+ </div>+ <Button className={control} data-testid={tid.automationCreate} onClick={() => { setError(null); setEditing("new") }}>Create access code</Button>+ </div>+ {list.isPending ? <div aria-label="Loading access codes" role="status" className="space-y-4">{[0, 1].map((i) => <div key={i} className="space-y-2 py-4"><Skeleton className="h-5 w-40" /><Skeleton className="h-4 w-64 max-w-full" /><Skeleton className="h-4 w-48" /></div>)}</div>+ : list.isError ? <div className="space-y-2"><p role="alert" className="text-sm text-destructive">Could not load access codes.</p><Button variant="outline" className={control} onClick={() => { void list.refetch() }}>Try again</Button></div>+ : !list.data?.accessCodes.length ? <p className="min-h-32 py-4 text-sm text-muted-foreground">No access codes yet. Create one to allow a script to act on your behalf.</p>+ : <ul className="divide-y divide-border">{list.data.accessCodes.map((code) => <li key={code.id} data-testid={tid.automationCode(code.id)} className="space-y-4 py-4 first:pt-0">+ <div className="grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-4 gap-y-2">+ <h2 className="flex min-h-11 min-w-0 items-center text-base leading-6 font-medium sm:min-h-8"><span className="min-w-0 wrap-break-word">{code.name}</span></h2>+ <div className="flex items-center gap-2">+ <Button variant="ghost" size="icon" className="size-11 sm:size-8" aria-label={`Edit ${code.name}`} onClick={() => { setError(null); setEditing(code) }}><Pencil className="size-4" /></Button>+ <Button variant="ghost" size="icon" className="size-11 sm:size-8" aria-label={`Delete ${code.name}`} onClick={() => { setError(null); setDeleting(code) }}><Trash2 className="size-4" /></Button>+ </div>+ <p className="col-span-2 text-xs leading-5 text-muted-foreground">{expiryLabel(code)}</p>+ </div>+ <div className="flex flex-wrap gap-2">{(["Read", "Write"] as const).flatMap((group) => permissionOptions.filter((option) => option.group === group && code.permissions.some((policy) => policy.permission === option.permission)).map(({ permission, label }) => <Badge key={permission} variant="secondary" className={group === "Write" ? "automation-write-color" : tagColorClassName} style={permissionColors[group]} aria-label={`${group}: ${label}`} title={group}>{label}</Badge>))}</div>+ </li>)}</ul>}+ {error ? <p role="alert" className="text-sm text-destructive">{error}</p> : null}+ <AutomationSetupPrompt />+ </>}+ <ConfirmDialog open={Boolean(deleting)} onOpenChange={(open) => { if (!open && !pending) setDeleting(null) }} title={`Delete “${deleting?.name ?? "access code"}”?`} description="Scripts using this code will lose access. This cannot be undone." confirmLabel="Delete code" loadingLabel="Deleting…" loading={pending} onConfirm={async () => {+ if (!deleting || pending) return+ setError(null)+ try { await execute({ kind: "delete", id: deleting.id }); setDeleting(null) } catch (cause) {+ if (!isAbortError(cause)) { setDeleting(null); setError(getErrorMessage(cause, "Could not delete this access code. Try again.")) }+ }+ }} />+ </div>+}diff --git a/src/web/src/components/community/settings/automation-setup-prompt.dom.test.tsx b/src/web/src/components/community/settings/automation-setup-prompt.dom.test.tsxnew file mode 100644index 000000000..ef85d9427--- /dev/null+++ b/src/web/src/components/community/settings/automation-setup-prompt.dom.test.tsx@@ -0,0 +1,33 @@+import { expect, it, vi } from "vitest"+import { render, screen, setupUser } from "@/test/react-dom-harness"+import { AutomationSetupPrompt } from "./automation-setup-prompt"++it("copies the visible setup prompt for any agent without requiring a bot", async () => {+ const user = setupUser()+ const copy = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue(undefined)+ render(<AutomationSetupPrompt />)+ const prompt = screen.getByRole("textbox", { name: "Automation setup prompt" }) as HTMLInputElement+ expect(prompt).toHaveAttribute("readonly")+ expect(prompt.value).toContain("https://alook.ai/agent.md")+ expect(prompt.value).toContain("permissions and limits")+ expect(screen.getByText(/paste it into any agent/)).toBeInTheDocument()+ await user.click(screen.getByRole("button", { name: "Copy prompt" }))+ expect(copy).toHaveBeenCalledWith(prompt.value)+ expect(screen.getByRole("status")).toHaveTextContent("Prompt copied")+})++it("keeps the prompt selectable when clipboard access fails", async () => {+ const user = setupUser()+ vi.spyOn(navigator.clipboard, "writeText").mockRejectedValue(new Error("Clipboard denied"))+ render(<AutomationSetupPrompt />)+ const prompt = screen.getByRole("textbox", { name: "Automation setup prompt" }) as HTMLInputElement+ const value = prompt.value+ await user.click(screen.getByRole("button", { name: "Copy prompt" }))+ expect(screen.getByRole("status")).toHaveTextContent("Copy failed. Select the prompt and copy it manually.")+ expect(prompt).toBeEnabled()+ prompt.focus()+ prompt.select()+ expect(prompt.selectionStart).toBe(0)+ expect(prompt.selectionEnd).toBe(value.length)+ expect(prompt.value).toBe(value)+})diff --git a/src/web/src/components/community/settings/automation-setup-prompt.tsx b/src/web/src/components/community/settings/automation-setup-prompt.tsxnew file mode 100644index 000000000..a2dccab27--- /dev/null+++ b/src/web/src/components/community/settings/automation-setup-prompt.tsx@@ -0,0 +1,23 @@+"use client"++import { useAtom, useCreateAtom } from "@tanstack/react-store"+import { Check, Copy } from "lucide-react"+import { Button } from "@/components/ui/button"+import { Input } from "@/components/ui/input"++const setupPrompt = "Read https://alook.ai/agent.md and help me configure Alook Automation. Ask what I want to automate, guide me through choosing access-code permissions and limits, then help me configure the code locally and run the right CLI commands."++export function AutomationSetupPrompt() {+ const [copyState, setCopyState] = useAtom(useCreateAtom<"idle" | "copied" | "error">("idle"))+ return <div className="space-y-3 border-t border-border pt-6" data-testid="automation-setup-prompt">+ <p className="text-xs leading-5 text-muted-foreground">Copy this prompt and paste it into any agent to set up Automation.</p>+ <div className="relative">+ <Input aria-label="Automation setup prompt" readOnly value={setupPrompt} className="h-11 truncate pr-12 text-sm" />+ <Button type="button" variant="ghost" size="icon" aria-label="Copy prompt" title={copyState === "copied" ? "Prompt copied" : "Copy prompt"} className="absolute top-0 right-0 size-11 rounded-l-none" onClick={async () => {+ try { await navigator.clipboard.writeText(setupPrompt); setCopyState("copied") }+ catch { setCopyState("error") }+ }}>{copyState === "copied" ? <Check className="size-4" /> : <Copy className="size-4" />}</Button>+ </div>+ <span role="status" className={copyState === "error" ? "block text-xs leading-5 text-muted-foreground" : "sr-only"}>{copyState === "copied" ? "Prompt copied" : copyState === "error" ? "Copy failed. Select the prompt and copy it manually." : ""}</span>+ </div>+}diff --git a/src/web/src/components/community/settings/settings-shell.tsx b/src/web/src/components/community/settings/settings-shell.tsxindex 5d4bbe06a..dd9834cfc 100644--- a/src/web/src/components/community/settings/settings-shell.tsx+++ b/src/web/src/components/community/settings/settings-shell.tsx@@ -8,6 +8,7 @@ import { Button } from "@/components/ui/button"import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"import { useBreakpoint } from "@/hooks/use-mobile"import { tid } from "@/lib/community/testids"+import { cn } from "@/lib/utils"import {SETTINGS_NAV_CLASS,SETTINGS_NAV_FOOTER_CLASS,@@ -20,6 +21,7 @@ export type SettingsShellTab<Value extends string> = {value: Valuelabel: stringicon: LucideIcon+ hideIconOnDesktop?: boolean}export function SettingsShellPanel(@@ -81,7 +83,7 @@ export function SettingsShell<Value extends string>({><div className={SETTINGS_NAV_LABEL_CLASS} data-testid={tid.settingsLabel}>{label}</div><TabsList variant="line" className={SETTINGS_TABS_LIST_CLASS}>- {tabs.map(({ value: tabValue, label: tabLabel, icon: Icon }) => (+ {tabs.map(({ value: tabValue, label: tabLabel, icon: Icon, hideIconOnDesktop }) => (<TabsTriggerkey={tabValue}value={tabValue}@@ -89,7 +91,7 @@ export function SettingsShell<Value extends string>({className={SETTINGS_TAB_CLASS}data-testid={tid.settingsTab(tabValue)}>- <Icon className="size-4" />+ <Icon className={cn("size-4", hideIconOnDesktop && "sm:invisible")} /><span className="sr-only whitespace-nowrap sm:not-sr-only">{tabLabel}</span></TabsTrigger>))}diff --git a/src/web/src/components/community/settings/user-settings.tsx b/src/web/src/components/community/settings/user-settings.tsxindex 05dccb371..9c435aff1 100644--- a/src/web/src/components/community/settings/user-settings.tsx+++ b/src/web/src/components/community/settings/user-settings.tsx@@ -7,7 +7,7 @@ import { useAtom, useCreateAtom, useCreateStore } from "@tanstack/react-store";import { useEffect, useLayoutEffect } from "react"import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"import { toastApiError } from "@/lib/api/client"-import { User, LogOut, Palette, Sun, Moon, Monitor, Database, Camera, Shield, CreditCard, FileText } from "lucide-react"+import { User, LogOut, Palette, Sun, Moon, Monitor, Database, Camera, Shield, CreditCard, FileText, KeyRound } from "lucide-react"import { useTheme } from "next-themes"import { Button } from "@/components/ui/button"import { AutoResizeTextarea } from "@/components/ui/auto-resize-textarea"@@ -29,6 +29,7 @@ import {import { SettingsShell, SettingsShellPanel, type SettingsShellTab } from "./settings-shell"import { BillingContent } from "../billing/billing-sheet"import { useBilling, type BillingReturn } from "@/hooks/community/use-billing"+import { AutomationSettings } from "./automation-settings"import { AccountDeletionFlow } from "./account-deletion-flow"const THEME_OPTIONS = [@@ -37,15 +38,16 @@ const THEME_OPTIONS = [{ value: "system", label: "System", icon: Monitor },] as const-type UserSettingsTab = "profile" | "appearance" | "advanced" | "privacy" | "terms" | "billing"+type UserSettingsTab = "profile" | "appearance" | "advanced" | "privacy" | "terms" | "billing" | "automation"const USER_SETTINGS_TABS: SettingsShellTab<UserSettingsTab>[] = [{ value: "profile", label: "My Profile", icon: User },- { value: "billing", label: "Subscription & billing", icon: CreditCard },+ { value: "billing", label: "Subscription & billing", icon: CreditCard, hideIconOnDesktop: true },{ value: "appearance", label: "Appearance", icon: Palette },- { value: "advanced", label: "Advanced", icon: Database },- { value: "privacy", label: "Privacy", icon: Shield },- { value: "terms", label: "Terms", icon: FileText },+ { value: "automation", label: "Automation", icon: KeyRound, hideIconOnDesktop: true },+ { value: "advanced", label: "Advanced", icon: Database, hideIconOnDesktop: true },+ { value: "privacy", label: "Privacy", icon: Shield, hideIconOnDesktop: true },+ { value: "terms", label: "Terms", icon: FileText, hideIconOnDesktop: true },]function AppearanceSettings() {@@ -246,13 +248,13 @@ export function UserSettings({ initialTab = "profile", billingReturn = null, onCvalue={tab}onValueChange={setTab}label="User Settings"- title={tab === "billing" ? "Subscription & billing" : deletionOpen ? "Delete account" : tab === "appearance" ? "Appearance" : tab === "advanced" ? "Advanced" : tab === "privacy" ? "Privacy Policy" : tab === "terms" ? "Terms of Service" : "My Profile"}+ title={tab === "automation" ? "Automation" : tab === "billing" ? "Subscription & billing" : deletionOpen ? "Delete account" : tab === "appearance" ? "Appearance" : tab === "advanced" ? "Advanced" : tab === "privacy" ? "Privacy Policy" : tab === "terms" ? "Terms of Service" : "My Profile"}tabs={USER_SETTINGS_TABS}onClose={onClose}disabled={deletionOpen}navFooter={<Button variant="ghost" className={SETTINGS_LOGOUT_CLASS} size="sm" onClick={onLogout} aria-label="Log out" disabled={deletionOpen}>- <LogOut className="size-4" /> <span className="sr-only sm:not-sr-only">Log Out</span>+ <LogOut className="size-4 sm:invisible" /> <span className="sr-only sm:not-sr-only">Log Out</span></Button>}>@@ -333,6 +335,9 @@ export function UserSettings({ initialTab = "profile", billingReturn = null, onC</div></div></SettingsShellPanel>+ <SettingsShellPanel value="automation">+ {tab === "automation" && userId ? <AutomationSettings key={userId} userId={userId} /> : null}+ </SettingsShellPanel><SettingsShellPanel value="appearance"><AppearanceSettings /></SettingsShellPanel>diff --git a/src/web/src/components/terms/terms-content.test.ts b/src/web/src/components/terms/terms-content.test.tsindex a95ace666..f637c90cb 100644--- a/src/web/src/components/terms/terms-content.test.ts+++ b/src/web/src/components/terms/terms-content.test.ts@@ -28,7 +28,7 @@ describe("Terms of Service", () => {it("uses the same content in its own Settings tab and keeps public sharing metadata canonical", () => {const settings = readFileSync(new URL("../community/settings/user-settings.tsx", import.meta.url), "utf8")- expect(settings).toContain('{ value: "terms", label: "Terms", icon: FileText }')+ expect(settings).toMatch(/\{\s*value: "terms",\s*label: "Terms",/)expect(settings).toContain('<SettingsShellPanel value="terms">')expect(settings).toContain("<TermsContent />")expect(settings).toContain("<PrivacyPolicyContent />")diff --git a/src/web/src/hooks/community/community-ws/presence-machine-events.ts b/src/web/src/hooks/community/community-ws/presence-machine-events.tsindex 601f93626..de643700e 100644--- a/src/web/src/hooks/community/community-ws/presence-machine-events.ts+++ b/src/web/src/hooks/community/community-ws/presence-machine-events.ts@@ -4,6 +4,7 @@ import { replaceMachines, type MachinesResponse } from "@/hooks/community/use-maimport { captureMachinesPublication, publishMachines } from "@/lib/community/machines"import { assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"import type {+ RuntimeModelDiscoveryResult,CommunityBotAuditEvent,CommunityMachineCreated,CommunityMachineRemoved,@@ -16,9 +17,13 @@ import type {import { communityKeys } from "@/lib/query-keys"-import type { RuntimeModelsState } from "@/hooks/community/use-runtime-models"import type { PresenceMachineEventContext } from "@/hooks/community/community-ws/handler-context"+export type RuntimeModelsState = { requestId: string; transport?: "http" } & (+ | { status: "pending" | "cancelled" }+ | RuntimeModelDiscoveryResult+)+export function handlePresenceUpdate(event: CommunityPresenceUpdate,{ queryClient }: PresenceMachineEventContext,@@ -113,10 +118,10 @@ export async function handleMachineRemoved()}-export async function handleRuntimeModels(event: Extract<CommunityWsEvent, { type: "community:runtime.models" }>, { queryClient }: PresenceMachineEventContext) {+export async function handleRuntimeModels(event: Extract<CommunityWsEvent, { type: "community:runtime.models" }>, { queryClient }: PresenceMachineEventContext, transport: "ws" | "http" = "ws") {const key = communityKeys.runtimeModels(event.machineId, event.runtimeId)const pending = queryClient.getQueryData<RuntimeModelsState>(key)- if (pending?.status !== "pending" || pending.requestId !== event.requestId) return+ if (pending?.status !== "pending" || pending.requestId !== event.requestId || (pending.transport === "http" && transport !== "http")) returnqueryClient.setQueryData<RuntimeModelsState>(key, { requestId: event.requestId, ...event.result })if (event.result.status !== "complete") returnconst catalog = event.result.catalogdiff --git a/src/web/src/hooks/community/use-automation.dom.test.tsx b/src/web/src/hooks/community/use-automation.dom.test.tsxnew file mode 100644index 000000000..2e316ae1f--- /dev/null+++ b/src/web/src/hooks/community/use-automation.dom.test.tsx@@ -0,0 +1,149 @@+import React from "react"+import { QueryClient } from "@tanstack/react-query"+import { CommunityTestProvider } from "@/test/community-owner-fixture"+import { act, renderHook, waitFor } from "@/test/react-dom-harness"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { useAutomation } from "./use-automation"++const mocks = vi.hoisted(() => ({ api: vi.fn() }))+vi.mock("@/lib/api/client", () => ({ apiFetch: mocks.api }))+const create = { kind: "create" as const, data: { name: "Script", expiresIn: "24h" as const, permissions: [{ permission: "bot.create" as const, limit: 64, period: "hour" as const }] } }+const response = { accessCode: { id: "code", name: "Script", permissions: create.data.permissions, expiresAt: null, createdAt: "2026-01-01T00:00:00Z" }, secret: "synthetic-only-secret" }+function setup() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })+ const wrapper = ({ children }: { children: React.ReactNode }) => <CommunityTestProvider client={client}>{children}</CommunityTestProvider>+ return { ...renderHook(() => useAutomation("owner"), { wrapper }), client }+}+beforeEach(() => { mocks.api.mockReset(); mocks.api.mockResolvedValue({ accessCodes: [] }) })+describe("Automation request ownership", () => {+ it("filters expired codes and removes future codes while the page stays open", async () => {+ const now = Date.now(), code = response.accessCode+ mocks.api.mockResolvedValue({ accessCodes: [+ { ...code, id: "expired", expiresAt: new Date(now - 1000).toISOString() },+ { ...code, id: "soon", expiresAt: new Date(now + 10_000).toISOString() },+ { ...code, id: "later", expiresAt: new Date(now + 20_000).toISOString() }, code,+ ] })+ const view = setup()+ await waitFor(() => expect(view.result.current.list.isSuccess).toBe(true))+ expect(view.result.current.list.data?.accessCodes.map(code => code.id)).toEqual(["soon", "later", "code"])+ vi.useFakeTimers()+ try {+ vi.setSystemTime(now + 10_000)+ await act(async () => window.dispatchEvent(new Event("focus")))+ expect(view.result.current.list.data?.accessCodes.map(code => code.id)).toEqual(["later", "code"])+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })+ expect(view.result.current.list.data?.accessCodes.map(code => code.id)).toEqual(["code"])+ expect(mocks.api).toHaveBeenCalledTimes(2)+ } finally { view.unmount(); view.client.clear(); vi.useRealTimers() }+ })+ it("rechecks expiry and refreshes server state on visibility change", async () => {+ const now = Date.now()+ mocks.api.mockResolvedValue({ accessCodes: [{ ...response.accessCode, expiresAt: new Date(now + 60_000).toISOString() }] })+ const view = setup()+ await waitFor(() => expect(view.result.current.list.data?.accessCodes).toHaveLength(1))+ vi.useFakeTimers()+ try {+ vi.setSystemTime(now + 60_000)+ await act(async () => document.dispatchEvent(new Event("visibilitychange")))+ expect(view.result.current.list.data?.accessCodes).toEqual([])+ expect(mocks.api).toHaveBeenCalledTimes(2)+ } finally { view.unmount(); view.client.clear(); vi.useRealTimers() }+ })+ it("does not refetch when the document is hidden or after unmount", async () => {+ const view = setup()+ await waitFor(() => expect(view.result.current.list.isSuccess).toBe(true))+ const visibility = vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden")+ try {+ await act(async () => document.dispatchEvent(new Event("visibilitychange")))+ expect(mocks.api).toHaveBeenCalledTimes(1)+ view.unmount()+ visibility.mockReturnValue("visible")+ await act(async () => window.dispatchEvent(new Event("focus")))+ expect(mocks.api).toHaveBeenCalledTimes(1)+ } finally { visibility.mockRestore(); view.unmount(); view.client.clear() }+ })+ it("removes a code expired by the CLI when the page becomes visible again", async () => {+ mocks.api.mockResolvedValue({ accessCodes: [response.accessCode] })+ const view = setup()+ await waitFor(() => expect(view.result.current.list.data?.accessCodes).toHaveLength(1))+ mocks.api.mockResolvedValue({ accessCodes: [] })+ await act(async () => document.dispatchEvent(new Event("visibilitychange")))+ await waitFor(() => expect(view.result.current.list.data?.accessCodes).toEqual([]))+ expect(mocks.api).toHaveBeenCalledTimes(2)+ view.unmount(); view.client.clear()+ })+ it("refreshes metadata after create without putting the secret in a query or mutation result", async () => {+ const view = setup()+ await waitFor(() => expect(view.result.current.list.isSuccess).toBe(true))+ const created = vi.fn()+ mocks.api.mockResolvedValueOnce(response).mockResolvedValue({ accessCodes: [response.accessCode] })+ await act(async () => { await view.result.current.execute(create, created) })+ expect(created).toHaveBeenCalledWith(response)+ await waitFor(() => expect(view.result.current.list.data?.accessCodes).toHaveLength(1))+ expect(JSON.stringify(view.client.getQueryCache().getAll().map((query) => query.state.data))).not.toContain(response.secret)+ expect(view.client.getMutationCache().getAll().every((mutation) => mutation.state.data === undefined)).toBe(true)+ view.unmount()+ })+ it("updates an encoded code path and refreshes its metadata", async () => {+ const view = setup()+ await waitFor(() => expect(view.result.current.list.isSuccess).toBe(true))+ const data = { name: "Renamed", permissions: create.data.permissions }+ const updated = { ...response.accessCode, name: data.name }+ const created = vi.fn()+ mocks.api.mockResolvedValueOnce({ accessCode: updated }).mockResolvedValue({ accessCodes: [updated] })+ await act(async () => { await view.result.current.execute({ kind: "update", id: "code/with space", data }, created) })+ expect(mocks.api).toHaveBeenCalledWith("/api/community/automation/access-codes/code%2Fwith%20space", expect.objectContaining({ method: "PATCH", body: JSON.stringify(data) }))+ await waitFor(() => expect(view.result.current.list.data?.accessCodes).toEqual([updated]))+ expect(created).not.toHaveBeenCalled()+ view.unmount()+ })+ it("deletes an encoded code path without a body and refreshes the list", async () => {+ mocks.api.mockResolvedValue({ accessCodes: [response.accessCode] })+ const view = setup()+ await waitFor(() => expect(view.result.current.list.data?.accessCodes).toHaveLength(1))+ const created = vi.fn()+ mocks.api.mockResolvedValueOnce({ deleted: true }).mockResolvedValue({ accessCodes: [] })+ await act(async () => { await view.result.current.execute({ kind: "delete", id: "code/with space" }, created) })+ const deletion = mocks.api.mock.calls.find(([, options]) => options?.method === "DELETE")+ expect(deletion?.[0]).toBe("/api/community/automation/access-codes/code%2Fwith%20space")+ expect(deletion?.[1]).not.toHaveProperty("body")+ await waitFor(() => expect(view.result.current.list.data?.accessCodes).toEqual([]))+ expect(created).not.toHaveBeenCalled()+ view.unmount()+ })+ it("rejects a delayed creation response after leaving the panel", async () => {+ const view = setup()+ await waitFor(() => expect(view.result.current.list.isSuccess).toBe(true))+ let resolve!: (value: typeof response) => void+ mocks.api.mockReturnValueOnce(new Promise((done) => { resolve = done }))+ const created = vi.fn()+ let work!: Promise<unknown>+ await act(async () => { work = view.result.current.execute(create, created).catch((error: unknown) => error) })+ view.unmount()+ resolve(response)+ const error = await work+ expect(error).toMatchObject({ name: "AbortError" })+ expect(created).not.toHaveBeenCalled()+ })+ it("does not replay a failed POST or allow duplicate in-flight submissions", async () => {+ const view = setup()+ await waitFor(() => expect(view.result.current.list.isSuccess).toBe(true))+ let reject!: (reason: Error) => void+ mocks.api.mockReturnValueOnce(new Promise((_done, fail) => { reject = fail }))+ let first!: Promise<unknown>+ await act(async () => { first = view.result.current.execute(create).catch((error: unknown) => error) })+ await expect(view.result.current.execute(create)).rejects.toMatchObject({ name: "AbortError" })+ await act(async () => { reject(new Error("Network failed")); await first })+ expect(mocks.api.mock.calls.filter(([, options]) => options?.method === "POST")).toHaveLength(1)+ view.unmount()+ })+ it("does not continue a callback saved from an unmounted account view", async () => {+ const view = setup()+ await waitFor(() => expect(view.result.current.list.isSuccess).toBe(true))+ const execute = view.result.current.execute+ const calls = mocks.api.mock.calls.length+ view.unmount()+ await expect(execute(create)).rejects.toMatchObject({ name: "AbortError" })+ expect(mocks.api).toHaveBeenCalledTimes(calls)+ })+})diff --git a/src/web/src/hooks/community/use-automation.ts b/src/web/src/hooks/community/use-automation.tsnew file mode 100644index 000000000..780991252--- /dev/null+++ b/src/web/src/hooks/community/use-automation.ts@@ -0,0 +1,80 @@+"use client"++import { useCallback, useEffect } from "react"+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"+import { useAtom, useCreateAtom, useCreateStore } from "@tanstack/react-store"+import type { AutomationAccessCodeCreate, AutomationAccessCodeUpdate, AutomationAccessCodeListResponse, AutomationAccessCodeCreateResponse } from "@alook/shared"+import { useCommunityMutationOrigin } from "./community-origin"+import { useCommunityViewSource } from "./use-community-view-source"++const path = "/api/community/automation/access-codes"+type Command = { kind: "create"; data: AutomationAccessCodeCreate } | { kind: "update"; id: string; data: AutomationAccessCodeUpdate } | { kind: "delete"; id: string }++export function useAutomation(userId: string) {+ const origin = useCommunityMutationOrigin()+ const view = useCommunityViewSource(`automation:${userId}`)+ const client = useQueryClient()+ const lock = useCreateStore({ pending: false })+ const queryKey = ["community", "automation-access-codes", userId] as const+ const list = useQuery({+ queryKey, retry: false, staleTime: 0, gcTime: 0,+ queryFn: ({ signal }) => origin.fetch<AutomationAccessCodeListResponse>(path, { signal }),+ })+ const refetch = list.refetch+ const [now, setNow] = useAtom(useCreateAtom<number | null>(null))+ useEffect(() => {+ let timer: ReturnType<typeof setTimeout> | undefined+ const refresh = () => {+ clearTimeout(timer)+ const current = Date.now()+ setNow(current)+ const next = list.data?.accessCodes.reduce((next, code) => {+ const expires = code.expiresAt ? Date.parse(code.expiresAt) : Infinity+ return expires > current ? Math.min(next, expires) : next+ }, Infinity) ?? Infinity+ if (Number.isFinite(next)) timer = setTimeout(refresh, Math.min(next - current, 2_147_483_647))+ }+ refresh()+ const resume = () => {+ refresh()+ if (document.visibilityState === "visible") void refetch({ cancelRefetch: false })+ }+ window.addEventListener("focus", resume)+ document.addEventListener("visibilitychange", resume)+ return () => {+ clearTimeout(timer)+ window.removeEventListener("focus", resume)+ document.removeEventListener("visibilitychange", resume)+ }+ }, [list.data, setNow, refetch])+ const data = list.data ? { ...list.data, accessCodes: list.data.accessCodes.filter((code) => !code.expiresAt || Date.parse(code.expiresAt) > (now ?? Infinity)) } : undefined+ type Intent = { action: Command; assert: ReturnType<typeof view.capture>; token: ReturnType<typeof origin.begin>["token"]; onCreated?: (result: AutomationAccessCodeCreateResponse) => void }+ const mutation = useMutation({+ meta: { observabilityAction: "automation.access_code.command" },+ mutationKey: [...queryKey, "action"], retry: false, gcTime: 0,+ mutationFn: async ({ action, assert, token, onCreated }: Intent) => {+ assert()+ const result = await origin.request<AutomationAccessCodeCreateResponse | undefined>(token,+ action.kind === "create" ? path : `${path}/${encodeURIComponent(action.id)}`, {+ method: action.kind === "create" ? "POST" : action.kind === "update" ? "PATCH" : "DELETE",+ ...(action.kind === "delete" ? {} : { body: JSON.stringify(action.data) }),+ signal: assert.signal, assertActive: assert,+ })+ assert()+ if (action.kind === "create" && result) onCreated?.(result)+ void client.invalidateQueries({ queryKey, exact: true }).catch(() => undefined)+ },+ })+ const mutateAsync = mutation.mutateAsync+ const execute = useCallback(async (action: Command, onCreated?: Intent["onCreated"]) => {+ if (lock.get().pending) throw new DOMException("Automation request already pending", "AbortError")+ const assert = view.capture()+ assert()+ lock.setState(() => ({ pending: true }))+ try {+ await mutateAsync({ action, assert, token: origin.begin().token, onCreated })+ assert()+ } finally { lock.setState(() => ({ pending: false })) }+ }, [view, origin, mutateAsync, lock])+ return { list: { ...list, data }, execute, pending: mutation.isPending }+}diff --git a/src/web/src/hooks/community/use-channel-ref-directory.dom.test.ts b/src/web/src/hooks/community/use-channel-ref-directory.dom.test.tsindex d5cd3a0b2..e77709ec9 100644--- a/src/web/src/hooks/community/use-channel-ref-directory.dom.test.ts+++ b/src/web/src/hooks/community/use-channel-ref-directory.dom.test.ts@@ -30,6 +30,20 @@ function seed(qc: QueryClient, channels = true) {beforeEach(() => { api.mockReset() })beforeEach(() => () => { act(() => { clients.splice(0).forEach((qc) => qc.clear()) }) })describe("native canonical channel directory", () => {+ it("keeps the request lease fetcher callable for a later invalidation", async () => {+ const held = deferred()+ api.mockReturnValueOnce(held.promise).mockResolvedValue(directoryResponse())+ const qc = client(), view = mount(qc)+ await waitFor(() => expect(api).toHaveBeenCalledOnce())+ const query = qc.getQueryCache().find({ queryKey: communityKeys.channelRefDirectory(), exact: true })!+ expect(query.observers.every(observer => typeof observer.options.queryFn === "function")).toBe(true)+ await act(async () => held.resolve(directoryResponse()))+ await waitFor(() => expect(view.result.current.isResolved).toBe(true))+ await act(async () => { await qc.invalidateQueries({ queryKey: communityKeys.channelRefDirectory(), exact: true }) })+ expect(api).toHaveBeenCalledTimes(2)+ expect(view.result.current.isError).toBe(false)+ view.unmount()+ })it("uses the qualified lightweight API helper", async () => {api.mockResolvedValue(directoryResponse()); const options = { authenticationAccount: "viewer" }await expect(channelRefDirectoryQueryFn(options)).resolves.toEqual(directoryResponse())diff --git a/src/web/src/hooks/community/use-channel-ref-directory.ts b/src/web/src/hooks/community/use-channel-ref-directory.tsindex 4beb55d7f..d078d6243 100644--- a/src/web/src/hooks/community/use-channel-ref-directory.ts+++ b/src/web/src/hooks/community/use-channel-ref-directory.ts@@ -3,6 +3,7 @@ import type { CommunityResourceBundle } from "@alook/shared"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"import {+ type QueryFunctionContext,useQuery,QueryObserver,useQueryClient,@@ -36,25 +37,26 @@ export function useChannelRefDirectory(enabled = true): {} {const queryClient = useQueryClient()const dbDirectory = useChannelRefDirectoryProjection()+ const queryFn = async ({ signal }: QueryFunctionContext): Promise<string[]> => {+ const observer = new QueryObserver<string[]>(queryClient, { queryKey: communityKeys.channelRefDirectory(), queryFn, enabled: false })+ const release = observer.subscribe(() => {+ if (queryClient.getQueryState(communityKeys.channelRefDirectory())?.fetchStatus === "idle") {+ signal.removeEventListener("abort", release)+ release()+ }+ })+ signal.addEventListener("abort", release, { once: true })+ const token = captureCommunityLiveSnapshotToken(queryClient)+ const { directory, resources } = await channelRefDirectoryQueryFn(communityRequestOptions(queryClient, token, signal))+ publishCommunityChannelDirectory(queryClient, {+ directory, resources,+ proof: { token, signal },+ })+ return directory.map((server) => server.id)+ }const query = useQuery<string[]>({queryKey: communityKeys.channelRefDirectory(),- queryFn: async ({ signal }) => {- const observer = new QueryObserver<string[]>(queryClient, { queryKey: communityKeys.channelRefDirectory(), enabled: false })- const release = observer.subscribe(() => {- if (queryClient.getQueryState(communityKeys.channelRefDirectory())?.fetchStatus === "idle") {- signal.removeEventListener("abort", release)- release()- }- })- signal.addEventListener("abort", release, { once: true })- const token = captureCommunityLiveSnapshotToken(queryClient)- const { directory, resources } = await channelRefDirectoryQueryFn(communityRequestOptions(queryClient, token, signal))- publishCommunityChannelDirectory(queryClient, {- directory, resources,- proof: { token, signal },- })- return directory.map((server) => server.id)- },+ queryFn,enabled,staleTime: Infinity,refetchOnReconnect: true,diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.tsindex 6cb957a7e..b43d0838f 100644--- a/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts@@ -1055,6 +1055,29 @@ describe("forum sidebar canonical projection", () => {await invalidateForumSidebarBaseExact(queryClient, "server-1")})+ it("keeps the server expiry deadline when a title update rebuilds the timer", async () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date("2026-10-30T00:00:00.000Z"))+ const { queryClient, wrapper } = await setup()+ const response = envelopeFor(["post-1"])+ const serverNow = Date.now() + 60 * 60 * 1000+ response.serverNow = new Date(serverNow).toISOString()+ setActivity(response, 0, new Date(serverNow - 72 * 60 * 60 * 1000 + 60_000).toISOString())+ publish(queryClient, response, true)+ apiFetchMock.mockReturnValue(new Promise(() => {}))+ const rendered = renderHook(() => useForumSidebarThreads("server-1", null), { wrapper })+ await act(async () => { await vi.advanceTimersByTimeAsync(30_000) })+ act(() => { patchForumSidebarTitleExact(queryClient, "server-1", "post-1", "Changed") })+ expect(rendered.result.current.threads[0]?.title).toBe("Changed")+ await act(async () => { await vi.advanceTimersByTimeAsync(30_024) })+ expect(rendered.result.current.threads).toHaveLength(1)+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })+ expect(rendered.result.current.threads).toEqual([])+ expect(getCanonicalCommunityChannels(queryClient).some(({ id }) => id === "post-1")).toBe(true)+ rendered.unmount()+ queryClient.clear()+ })+it("deduplicates one cold request across a StrictMode-style remount", async () => {const { wrapper, queryClient } = await setup()let resolveRequest!: (value: SidebarThreadEnvelope) => voiddiff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.tsindex e367f8a93..a039b401f 100644--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts@@ -502,10 +502,10 @@ export function useForumSidebarThreads(if (nextExpiry === undefined) returnconst timeout = globalThis.setTimeout(() => setClockNowMs(Date.now()),- Math.max(0, nextExpiry - serverNowMs) + 25,+ Math.max(0, nextExpiry - (Date.now() + (query.data?.serverClockOffsetMs ?? 0))) + 25,)return () => globalThis.clearTimeout(timeout)- }, [projection.threads, retainId, serverNowMs, setClockNowMs])+ }, [projection.threads, retainId, serverNowMs, setClockNowMs, query.data?.serverClockOffsetMs])return {...query,threads: projection.threads,diff --git a/src/web/src/hooks/community/use-runtime-models.dom.test.ts b/src/web/src/hooks/community/use-runtime-models.dom.test.tsindex 1b6970a24..d3efb76b1 100644--- a/src/web/src/hooks/community/use-runtime-models.dom.test.ts+++ b/src/web/src/hooks/community/use-runtime-models.dom.test.ts@@ -10,168 +10,134 @@ import { useRuntimeModels, type RuntimeModelsState } from "./use-runtime-models"import type { MachinesResponse } from "./use-machines"const apiFetch = vi.fn()+const pending: { resolve: (value: unknown) => void; reject: (error: unknown) => void }[] = []vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetch(...args) }))-beforeEach(() => { apiFetch.mockReset(); apiFetch.mockResolvedValue({ dispatched: true }) })-+beforeEach(() => {+ pending.length = 0+ apiFetch.mockReset().mockImplementation(() => new Promise((resolve, reject) => pending.push({ resolve, reject })))+})+const catalog = { updateMode: "live_next_turn", defaultModelId: "native-model", models: [{ id: "native-model", supportedReasoningEfforts: [{ value: "high" }], defaultReasoningEffort: "high" }] }function mount() {const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: queryClient }, children)- const hook = renderHook(({ machine, runtime }) => useRuntimeModels(machine, runtime), {- wrapper, initialProps: { machine: "m1", runtime: "codex" },- })+ const hook = renderHook(({ machine, runtime }) => useRuntimeModels(machine, runtime), { wrapper, initialProps: { machine: "m1", runtime: "codex" } })const request = (machine = "m1", runtime = "codex") => queryClient.getQueryData<RuntimeModelsState>(communityKeys.runtimeModels(machine, runtime))!- const complete = (requestId: string, machineId = "m1", runtimeId = "codex") => act(() => handleRuntimeModels({- type: "community:runtime.models", requestId, machineId, runtimeId, result: { status: "complete", catalog: null },- }, { queryClient }))- return { ...hook, queryClient, request, complete }+ const open = async () => { const count = apiFetch.mock.calls.length; act(() => hook.result.current.onOpenChange(true)); await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(count + 1)) }+ const reply = (index = 0, overrides: Record<string, unknown> = {}) => {+ const body = JSON.parse(apiFetch.mock.calls[index][1].body)+ return { machineId: "m1", backendId: body.runtimeId, requestId: body.requestId, source: "fresh_discovery", observedAt: "2026-10-29T00:00:00Z", result: { status: "complete", catalog }, ...overrides }+ }+ const complete = async (index = 0, overrides: Record<string, unknown> = {}) => act(async () => pending[index].resolve(reply(index, overrides)))+ queryClient.setQueryData(communityKeys.machines(), { machines: [{ id: "m1", availableRuntimes: [{ id: "codex", status: "healthy" }], quota: [{ keep: true }] }], extra: "keep" })+ return { ...hook, queryClient, request, open, reply, complete }}-describe("on-demand runtime models", () => {- it("does not prefetch on mount or runtime change, and sends the selected scope only on open", async () => {+describe("server-cached UI runtime models", () => {+ it("does not prefetch and opens the selected machine/backend through the waiting cache path", async () => {const h = mount()h.rerender({ machine: "m2", runtime: "agy" })expect(apiFetch).not.toHaveBeenCalled()- act(() => h.result.current.onOpenChange(true))- await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(1))- expect(apiFetch.mock.calls[0][0]).toBe("/api/community/machines/m2/discover-models")+ await h.open()+ expect(apiFetch.mock.calls[0][0]).toBe("/api/community/machines/m2/discover-models?wait=1")expect(JSON.parse(apiFetch.mock.calls[0][1].body)).toEqual({ requestId: h.request("m2", "agy").requestId, runtimeId: "agy" })expect(h.result.current.isPending).toBe(true)act(() => h.result.current.onOpenChange(true))expect(apiFetch).toHaveBeenCalledTimes(1)+ await h.complete(0, { machineId: "m2" })+ await waitFor(() => expect(h.result.current.isPending).toBe(false))})- it("accepts only the matching pending WS result and preserves machine metadata", async () => {+ it.each(["fresh_discovery", "cached_report"])("publishes the %s native catalog without losing machine metadata", async (source) => {const h = mount()- const machine = { id: "m1", availableRuntimes: [{ id: "codex", status: "healthy", reasoning: { updateMode: "unsupported", models: [] } }], quota: [{ keep: true }] }- h.queryClient.setQueryData(communityKeys.machines(), { machines: [machine], extra: "keep" })- act(() => h.result.current.onOpenChange(true))- await h.complete("older")- await h.complete(h.request().requestId, "other")- expect(h.request().status).toBe("pending")- await h.complete(h.request().requestId)- await waitFor(() => expect(h.result.current.isPending).toBe(false))+ await h.open()+ await h.complete(0, { source })+ expect(h.result.current.error).toBeNull()+ expect(h.request()).toMatchObject({ status: "complete", catalog })const cached = h.queryClient.getQueryData<MachinesResponse>(communityKeys.machines())!- expect(cached.machines[0].availableRuntimes).toEqual([{ id: "codex", status: "healthy" }])+ expect(cached.machines[0].availableRuntimes).toEqual([{ id: "codex", status: "healthy", reasoning: catalog }])expect(cached.machines[0].quota).toEqual([{ keep: true }])expect(cached).toHaveProperty("extra", "keep")+ await h.open()+ expect(JSON.parse(apiFetch.mock.calls[1][1].body)).not.toHaveProperty("refresh")})- it("retires pending requests on close and machine/runtime change", async () => {+ it("uses HTTP completion while ignoring earlier matching or unrelated WS notifications", async () => {const h = mount()- act(() => h.result.current.onOpenChange(true))- const first = h.request().requestId- act(() => h.result.current.onOpenChange(false))- await h.complete(first)- expect(h.request().status).toBe("cancelled")- act(() => h.result.current.onOpenChange(true))- const second = h.request().requestId- expect(second).not.toBe(first)- h.rerender({ machine: "m2", runtime: "agy" })- await h.complete(second)- expect(h.request().status).toBe("cancelled")- expect(h.queryClient.getQueryData(communityKeys.runtimeModels("m2", "agy"))).toBeUndefined()+ await h.open()+ for (const requestId of ["other", h.request().requestId]) await act(async () => handleRuntimeModels({ type: "community:runtime.models", requestId, machineId: "m1", runtimeId: "codex", result: { status: "complete", catalog: null } }, { queryClient: h.queryClient }))+ expect(h.request().status).toBe("pending")+ await h.complete()+ expect(h.request()).toMatchObject({ status: "complete", catalog })})- it("shows a readable offline failure and Retry starts a fresh request", async () => {- apiFetch.mockRejectedValueOnce(new Error("MACHINE_OFFLINE"))+ it("keeps legacy WS pending handling and applies a missing catalog without destroying metadata", async () => {const h = mount()- act(() => h.result.current.onOpenChange(true))- const first = h.request().requestId- await waitFor(() => expect(h.result.current.error).toBe("This machine is offline."))- act(() => h.result.current.retry())- expect(h.request().requestId).not.toBe(first)- await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(2))- expect(h.result.current.isPending).toBe(true)+ act(() => h.queryClient.setQueryData(communityKeys.runtimeModels("m1", "codex"), { requestId: "legacy", status: "pending" }))+ await act(async () => handleRuntimeModels({ type: "community:runtime.models", requestId: "legacy", machineId: "m1", runtimeId: "codex", result: { status: "complete", catalog: null } }, { queryClient: h.queryClient }))+ expect(h.request()).toEqual({ requestId: "legacy", status: "complete", catalog: null })+ expect(h.queryClient.getQueryData<MachinesResponse>(communityKeys.machines())!.machines[0].availableRuntimes).toEqual([{ id: "codex", status: "healthy" }])})- it.each([- { scenario: "generic fallback", error: "invalid error response", expected: "Could not load models." },- { scenario: "daemon upgrade instruction", error: new Error("UPGRADE_REQUIRED"), expected: "Update this machine’s daemon to load models." },- { scenario: "native error message", error: new Error("Native model query failed."), expected: "Native model query failed." },- ])("shows the $scenario after request failure", async ({ error, expected }) => {- apiFetch.mockRejectedValueOnce(error)+ it.each(["close", "scope", "unmount"])("ignores a late HTTP result after %s", async (action) => {const h = mount()- act(() => h.result.current.onOpenChange(true))- await waitFor(() => expect(h.result.current.error).toBe(expected))- expect(h.result.current.isPending).toBe(false)- expect(apiFetch).toHaveBeenCalledTimes(1)+ await h.open()+ if (action === "close") act(() => h.result.current.onOpenChange(false))+ if (action === "scope") h.rerender({ machine: "m2", runtime: "agy" })+ if (action === "unmount") h.unmount()+ await h.complete()+ expect(h.request().status).toBe("cancelled")+ expect(h.queryClient.getQueryData<MachinesResponse>(communityKeys.machines())!.machines[0].availableRuntimes?.[0]).not.toHaveProperty("reasoning")})- it("a late failed request does not recreate a removed cache or affect the new machine", async () => {- let rejectRequest!: (error: unknown) => void- apiFetch.mockImplementationOnce(() => new Promise((_, reject) => { rejectRequest = reject }))+ it("a late failure does not recreate removed state or affect a new machine", async () => {const h = mount()- act(() => h.result.current.onOpenChange(true))- await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(1))+ await h.open()h.rerender({ machine: "m2", runtime: "agy" })act(() => h.queryClient.removeQueries({ queryKey: communityKeys.runtimeModels("m1", "codex"), exact: true }))- await act(async () => { rejectRequest(new Error("Late native failure.")) })+ await act(async () => pending[0].reject(new Error("Late failure")))expect(h.queryClient.getQueryData(communityKeys.runtimeModels("m1", "codex"))).toBeUndefined()expect(h.queryClient.getQueryData(communityKeys.runtimeModels("m2", "agy"))).toBeUndefined()- expect(h.result.current.error).toBeNull()- expect(h.result.current.isPending).toBe(false)- expect(apiFetch).toHaveBeenCalledTimes(1)})- it("opening while disconnected ends loading without dispatching a request", async () => {+ it.each([+ { error: new Error("MACHINE_OFFLINE"), expected: "This machine is offline." },+ { error: new Error("UPGRADE_REQUIRED"), expected: "Update this machine’s daemon to load models." },+ { error: "invalid error response", expected: "Could not load models." },+ { error: new DOMException("timeout", "TimeoutError"), expected: "Model discovery timed out. Retry to load models." },+ ])("reports $expected and Retry forces a new discovery", async ({ error, expected }) => {const h = mount()- act(() => getCommunityRuntime(h.queryClient).ws.actions.setConnectionStatus("failed"))- act(() => h.result.current.onOpenChange(true))- await waitFor(() => expect(h.result.current.error).toBe("Reconnect to load models."))- expect(h.result.current.isPending).toBe(false)- expect(apiFetch).not.toHaveBeenCalled()+ await h.open()+ const first = h.request().requestId+ await act(async () => pending[0].reject(error))+ await waitFor(() => expect(h.result.current.error).toBe(expected))+ act(() => h.result.current.retry())+ await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(2))+ expect(h.request().requestId).not.toBe(first)+ expect(JSON.parse(apiFetch.mock.calls[1][1].body)).toMatchObject({ refresh: true })})- it("a late aborted request does not replace the cancelled state with an error", async () => {- let rejectRequest!: (error: unknown) => void- apiFetch.mockImplementationOnce(() => new Promise((_, reject) => { rejectRequest = reject }))+ it("can load the server cache without the browser WS connection", async () => {const h = mount()- act(() => h.result.current.onOpenChange(true))- await waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(1))- const id = h.request().requestId- act(() => h.result.current.onOpenChange(false))- await act(async () => { rejectRequest(new DOMException("Request cancelled", "AbortError")) })- await waitFor(() => expect(h.result.current.isPending).toBe(false))- expect(h.request()).toEqual({ requestId: id, status: "cancelled" })+ act(() => getCommunityRuntime(h.queryClient).ws.actions.setConnectionStatus("failed"))+ await h.open()+ await h.complete(0, { source: "cached_report" })expect(h.result.current.error).toBeNull()+ expect(h.request().status).toBe("complete")})- it("ends loading on disconnect and ignores the late native result", async () => {- const h = mount()- act(() => h.result.current.onOpenChange(true))- const id = h.request().requestId- act(() => getCommunityRuntime(h.queryClient).ws.actions.setConnectionStatus("reconnecting"))- await waitFor(() => expect(h.result.current.error).toBe("Connection lost. Retry to load models."))- await h.complete(id)- expect(h.request().status).toBe("error")- })-- it("ends loading at 45 seconds and ignores a result after timeout", async () => {+ it.each([{ requestId: "other" }, { machineId: "other" }, { backendId: "other" }, { result: {} }, { source: "stored_report" }, { observedAt: "invalid" }])("refuses a mismatched or invalid HTTP receipt %j", async (overrides) => {const h = mount()- const timeout = vi.spyOn(globalThis, "setTimeout")- act(() => h.result.current.onOpenChange(true))- await waitFor(() => expect(h.result.current.isPending).toBe(true))- const id = h.request().requestId- const callback = timeout.mock.calls.find((call) => call[1] === 45_000)?.[0]- expect(callback).toBeTypeOf("function")- act(() => { if (typeof callback === "function") callback() })- await waitFor(() => expect(h.result.current.error).toBe("Model discovery timed out. Retry to load models."))- await h.complete(id)- expect(h.request().status).toBe("error")- timeout.mockRestore()+ await h.open()+ await h.complete(0, overrides)+ await waitFor(() => expect(h.result.current.error).toBe("Could not load models."))})- it("applies the native catalog and preserves it when a later discovery fails", async () => {+ it("an aborted late request leaves cancellation intact", async () => {const h = mount()- h.queryClient.setQueryData(communityKeys.machines(), { machines: [{ id: "m1", availableRuntimes: [{ id: "codex" }] }] })- act(() => h.result.current.onOpenChange(true))- const catalog = { updateMode: "live_next_turn" as const, models: [{ id: "native-model", supportedReasoningEfforts: [] }] }- await act(async () => handleRuntimeModels({ type: "community:runtime.models", machineId: "m1", runtimeId: "codex", requestId: h.request().requestId, result: { status: "complete", catalog } }, { queryClient: h.queryClient }))- expect(h.queryClient.getQueryData<MachinesResponse>(communityKeys.machines())!.machines[0].availableRuntimes?.[0].reasoning).toEqual(catalog)- act(() => h.result.current.retry())- await act(async () => handleRuntimeModels({ type: "community:runtime.models", machineId: "m1", runtimeId: "codex", requestId: h.request().requestId, result: { status: "error", code: "model_discovery_timeout", message: "Model query timed out." } }, { queryClient: h.queryClient }))- await waitFor(() => expect(h.result.current.error).toBe("Model query timed out."))- expect(h.queryClient.getQueryData<MachinesResponse>(communityKeys.machines())!.machines[0].availableRuntimes?.[0].reasoning).toEqual(catalog)+ await h.open()+ act(() => h.result.current.onOpenChange(false))+ await act(async () => pending[0].reject(new DOMException("cancelled", "AbortError")))+ expect(h.request().status).toBe("cancelled")+ expect(h.result.current.error).toBeNull()})-})diff --git a/src/web/src/hooks/community/use-runtime-models.ts b/src/web/src/hooks/community/use-runtime-models.tsindex ac11bf8dc..17f16c39d 100644--- a/src/web/src/hooks/community/use-runtime-models.ts+++ b/src/web/src/hooks/community/use-runtime-models.ts@@ -2,22 +2,18 @@import { useCallback, useEffect, useMemo, useRef } from "react"import { skipToken, useQuery, useQueryClient } from "@tanstack/react-query"-import type { RuntimeModelDiscoveryResult } from "@alook/shared"+import { RuntimeModelDiscoveryResultSchema } from "@alook/shared"import { communityKeys } from "@/lib/query-keys"import { isAbortError } from "@/lib/errors"-import { useCommunityWsStore } from "@/stores/community/ws"+import { handleRuntimeModels, type RuntimeModelsState } from "./community-ws/presence-machine-events"import { useCommunityMutationOrigin } from "./community-origin"-export type RuntimeModelsState = { requestId: string } & (- | { status: "pending" | "cancelled" }- | RuntimeModelDiscoveryResult-)+export type { RuntimeModelsState } from "./community-ws/presence-machine-events"export function useRuntimeModels(machineId: string, runtimeId: string) {const queryClient = useQueryClient()const origin = useCommunityMutationOrigin()const ownedRequest = useRef<string | null>(null)- const connectionStatus = useCommunityWsStore((state) => state.connectionStatus)const queryKey = useMemo(() => communityKeys.runtimeModels(machineId, runtimeId), [machineId, runtimeId])const { data } = useQuery<RuntimeModelsState>({ queryKey, queryFn: skipToken, gcTime: 60_000 })@@ -37,42 +33,35 @@ export function useRuntimeModels(machineId: string, runtimeId: string) {ownedRequest.current = null}, [queryClient, queryKey])- function discover() {+ function discover(refresh = false) {if (queryClient.getQueryData<RuntimeModelsState>(queryKey)?.status === "pending") returnconst requestId = crypto.randomUUID()ownedRequest.current = requestId- queryClient.setQueryData<RuntimeModelsState>(queryKey, { requestId, status: "pending" })- if (connectionStatus !== "connected") {- finishError(requestId, "Reconnect to load models.")- return- }+ queryClient.setQueryData<RuntimeModelsState>(queryKey, { requestId, status: "pending", transport: "http" })const { token } = origin.begin()- void origin.request(token, `/api/community/machines/${encodeURIComponent(machineId)}/discover-models`, {- method: "POST", body: JSON.stringify({ requestId, runtimeId }),+ void origin.request<{ requestId: string; machineId: string; backendId: string; source: string; observedAt: string; result: unknown }>(token, `/api/community/machines/${encodeURIComponent(machineId)}/discover-models?wait=1`, {+ method: "POST", body: JSON.stringify({ requestId, runtimeId, ...(refresh ? { refresh: true } : {}) }), signal: AbortSignal.timeout(55_000),+ }).then(async (response) => {+ origin.assert(token)+ const result = RuntimeModelDiscoveryResultSchema.safeParse(response.result)+ if (response.requestId !== requestId || response.machineId !== machineId || response.backendId !== runtimeId || !result.success+ || !["cached_report", "fresh_discovery"].includes(response.source) || !Number.isFinite(Date.parse(response.observedAt))) throw new Error("Could not load models.")+ await handleRuntimeModels({ type: "community:runtime.models", requestId, machineId, runtimeId, result: result.data }, { queryClient }, "http")}).catch((error: unknown) => {if (isAbortError(error)) return- const message = error instanceof Error ? error.message : "Could not load models."+ const message = typeof error === "object" && error !== null && "name" in error && error.name === "TimeoutError" ? "Model discovery timed out. Retry to load models."+ : error instanceof Error ? error.message : "Could not load models."finishError(requestId, message === "UPGRADE_REQUIRED" ? "Update this machine’s daemon to load models.": message === "MACHINE_OFFLINE" ? "This machine is offline." : message)})}- useEffect(() => {- if (data?.status !== "pending") return- if (connectionStatus !== "connected") {- finishError(data.requestId, "Connection lost. Retry to load models.")- return- }- const timer = setTimeout(() => finishError(data.requestId, "Model discovery timed out. Retry to load models."), 45_000)- return () => clearTimeout(timer)- }, [data?.requestId, data?.status, connectionStatus, finishError])-useEffect(() => cancel, [cancel])return {isPending: data?.status === "pending",error: data?.status === "error" ? data.message : null,onOpenChange: (open: boolean) => open ? discover() : cancel(),- retry: discover,+ retry: () => discover(true),}}diff --git a/src/web/src/lib/automation-routes.test.ts b/src/web/src/lib/automation-routes.test.tsnew file mode 100644index 000000000..7453e89ea--- /dev/null+++ b/src/web/src/lib/automation-routes.test.ts@@ -0,0 +1,60 @@+import { beforeEach, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"+const mocks = vi.hoisted(() => ({ authenticate: vi.fn(), limiter: vi.fn(), action: vi.fn() }))+vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: async () => ({ env: { DB: {} } }) }))+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }) }))+vi.mock("@/lib/broadcast", () => ({ wsDoFetch: mocks.limiter }))+vi.mock("@/lib/middleware/auth", () => ({ withAuth: () => { throw new Error("normal authentication must not be used") } }))+vi.mock("@alook/shared", async (original) => ({ ...await original<typeof import("@alook/shared")>(), queries: { automation: { authenticateAccessCode: mocks.authenticate } } }))+vi.mock("@/lib/community/create-bot.server", () => ({ createBotForUser: mocks.action }))+vi.mock("@/lib/community/create-server.server", () => ({ createServerForUser: mocks.action }))+vi.mock("@/lib/community/automation-read.server", () => ({ readAutomationMachines: mocks.action, readAutomationFriends: mocks.action, readAutomationServers: mocks.action }))+vi.mock("@/lib/community/automation-invite.server", () => ({ inviteAutomationFriend: mocks.action }))+vi.mock("@/lib/community/automation-message.server", () => ({ sendAutomationMessage: mocks.action }))+import { POST as createBot } from "@/app/api/community/automation/bots/route"+import { GET as servers, POST as createServer } from "@/app/api/community/automation/servers/route"+import { GET as machines } from "@/app/api/community/automation/machines/route"+import { GET as friends } from "@/app/api/community/automation/friends/route"+import { POST as invite } from "@/app/api/community/automation/servers/[id]/invites/route"+import { POST as send } from "@/app/api/community/automation/messages/route"+const routes = [[createBot, "bot.create"], [createServer, "server.create"], [servers, "server.read"], [machines, "machine.read"], [friends, "friend.read"], [invite, "server.invite"], [send, "message.send"]] as const+const secret = "aac_" + "a".repeat(64)+const req = (token = secret) => new NextRequest("http://localhost/api/community/automation/test", { headers: { Authorization: `Bearer ${token}`, cookie: "session=present" } })+beforeEach(() => {+ vi.clearAllMocks()+ mocks.authenticate.mockImplementation(async (_db, _hash, permission) => ({ codeId: "one-code", ownerId: "owner", permission, limit: 2, period: "hour" }))+ mocks.limiter.mockImplementation(async () => Response.json({ allowed: true }))+ mocks.action.mockImplementation(async (_req, ctx) => await ctx.beforeCreate() ?? Response.json({ owner: ctx.userId, params: ctx.params }))+})+it("wires each dedicated operation to its own grant and code quota without normal authentication", async () => {+ for (const [route, permission] of routes) {+ const response = await route(req(), { params: { id: "demo#0001" } })+ expect(response.status).toBe(200)+ expect(await response.json()).toEqual({ owner: "owner", params: { id: "demo#0001" } })+ expect(mocks.authenticate.mock.lastCall?.[2]).toBe(permission)+ expect(JSON.parse(mocks.limiter.mock.lastCall?.[2].body)).toEqual({ name: permission, key: "one-code", max: 2, period: "hour" })+ expect(response.headers.get("cache-control")).toBe("no-store")+ }+})+it("rejects cookie-only, machine and bot credentials at every dedicated operation", async () => {+ for (const [route] of routes) {+ for (const token of ["", "al_machine", "crk_bot", "aac_bad"]) expect((await route(req(token))).status).toBe(401)+ expect((await route(new NextRequest("http://localhost/api/community/automation/test", { headers: { cookie: "session=present" } }))).status).toBe(401)+ }+ expect(mocks.action).not.toHaveBeenCalled()+ expect(mocks.authenticate).not.toHaveBeenCalled()+ expect(mocks.limiter).not.toHaveBeenCalled()+})+it("denies missing grants before a business action and returns each grant's quota failure", async () => {+ for (const [route] of routes) {+ mocks.authenticate.mockResolvedValueOnce(null)+ expect((await route(req())).status).toBe(401)+ }+ expect(mocks.action).not.toHaveBeenCalled()+ mocks.limiter.mockImplementation(async () => Response.json({ allowed: false, retryAfterSec: 9 }))+ for (const [route] of routes) {+ const response = await route(req())+ expect(response.status).toBe(429)+ expect(response.headers.get("Retry-After")).toBe("9")+ }+})diff --git a/src/web/src/lib/automation.test.ts b/src/web/src/lib/automation.test.tsnew file mode 100644index 000000000..6e7a148ce--- /dev/null+++ b/src/web/src/lib/automation.test.ts@@ -0,0 +1,119 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++const { authenticate, expire, transport, fallback } = vi.hoisted(() => ({ authenticate: vi.fn(), expire: vi.fn(), transport: vi.fn(), fallback: vi.fn() }))+vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: async () => ({ env: { DB: {} } }) }))+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }) }))+vi.mock("@/lib/broadcast", () => ({ wsDoFetch: transport }))+vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: unknown) => fallback.mockImplementation(async (request: NextRequest) => (handler as (req: NextRequest, ctx: unknown) => Promise<Response>)(request, { env: { DB: {} }, userId: "human" })) }))+vi.mock("@alook/shared", async (importOriginal) => ({ ...await importOriginal<typeof import("@alook/shared")>(), queries: { automation: { authenticateAccessCode: authenticate, expireAccessCode: expire } } }))++import { hashAutomationSecret, newAutomationSecret, withAutomation, withAutomationManagement } from "./automation"+import { POST as expireCode } from "@/app/api/community/automation/expire/route"++const secret = "aac_" + "a".repeat(64)+const request = (token = secret) => new NextRequest("http://localhost/api/community/bots", { method: "POST", headers: { Authorization: `Bearer ${token}` }, body: JSON.stringify({ name: "test" }) })+beforeEach(() => {+ vi.clearAllMocks()+ authenticate.mockResolvedValue({ codeId: "code", ownerId: "owner", permission: "bot.create", limit: 64, period: "hour" })+ transport.mockResolvedValue(Response.json({ allowed: true }))+})+afterEach(() => vi.restoreAllMocks())+const create = async (_req: NextRequest, ctx: { userId: string; beforeCreate: () => Promise<Response | null> }) =>+ await ctx.beforeCreate() ?? Response.json({ ownerId: ctx.userId }, { status: 201 })++describe("automation authorization boundary", () => {+ it("self-expires a hashed credential without permissions, quota or normal-session authority", async () => {+ expire.mockResolvedValueOnce(true)+ const result = await expireCode(request())+ expect(result.status).toBe(200)+ expect(await result.json()).toEqual({ expired: true })+ expect(result.headers.get("Cache-Control")).toBe("no-store")+ expect(expire).toHaveBeenCalledExactlyOnceWith({ primary: true }, await hashAutomationSecret(secret))+ expect(authenticate).not.toHaveBeenCalled()+ expect(transport).not.toHaveBeenCalled()+ expect(fallback).not.toHaveBeenCalled()+ expire.mockResolvedValueOnce(false)+ expect((await expireCode(request())).status).toBe(401)+ expire.mockRejectedValueOnce(new Error("D1 unavailable"))+ expect((await expireCode(request())).status).toBe(503)+ })++ it("refuses missing, malformed, bot and machine credentials before self-expiry", async () => {+ for (const token of ["", "aac_bad", "al_machine", "crk_bot"]) expect((await expireCode(request(token))).status).toBe(401)+ const cookieOnly = new NextRequest("http://localhost/api/community/automation/expire", { method: "POST", headers: { Cookie: "session=present" } })+ expect((await expireCode(cookieOnly)).status).toBe(401)+ expect(expire).not.toHaveBeenCalled()+ expect(fallback).not.toHaveBeenCalled()+ })++ it("derives owner from a hashed primary lookup and uses the indexed permission for its own limiter", async () => {+ const response = await withAutomation("bot.create", create)(request())+ expect(response.status).toBe(201)+ expect(await response.json()).toEqual({ ownerId: "owner" })+ expect(authenticate).toHaveBeenCalledWith({ primary: true }, await hashAutomationSecret(secret), "bot.create")+ const payload = JSON.parse(transport.mock.calls[0]![2].body as string)+ expect(payload).toEqual({ name: "bot.create", key: "code", max: 64, period: "hour" })+ expect(JSON.stringify(payload)).not.toContain(secret)+ expect(response.headers.get("Cache-Control")).toBe("no-store")+ expect(fallback).not.toHaveBeenCalled()+ })+ it("rejects missing permission, deleted/expired secrets and malformed credentials before creation", async () => {+ const handler = vi.fn(create)+ authenticate.mockResolvedValue(null)+ expect((await withAutomation("bot.create", handler)(request())).status).toBe(401)+ expect((await withAutomation("bot.create", handler)(request("al_machine"))).status).toBe(401)+ expect(handler).not.toHaveBeenCalled()+ expect(transport).not.toHaveBeenCalled()+ })+ it("fails closed on auth/limiter failure, invalid policy and invalid limiter results", async () => {+ authenticate.mockRejectedValueOnce(new Error("D1 down"))+ expect((await withAutomation("bot.create", create)(request())).status).toBe(503)+ for (const body of [null, { allowed: "true" }, { allowed: false }, { allowed: false, retryAfterSec: -1 }]) {+ transport.mockResolvedValueOnce(Response.json(body))+ expect((await withAutomation("bot.create", create)(request())).status).toBe(503)+ }+ transport.mockRejectedValueOnce(new Error("DO down"))+ expect((await withAutomation("bot.create", create)(request())).status).toBe(503)+ authenticate.mockResolvedValueOnce({ codeId: "code", ownerId: "owner", limit: 65, period: "hour" })+ expect((await withAutomation("bot.create", create)(request())).status).toBe(503)+ })+ it("returns Retry-After and does not run business creation when denied", async () => {+ transport.mockResolvedValue(Response.json({ allowed: false, retryAfterSec: 20 }))+ const response = await withAutomation("bot.create", create)(request())+ expect(response.status).toBe(429)+ expect(response.headers.get("Retry-After")).toBe("20")+ })+ it("accepts only standalone access codes, even when a session cookie is present", async () => {+ const handler = vi.fn(create)+ const route = withAutomation("bot.create", handler)+ for (const token of ["aac_bad", "al_machine", "crk_bot", ""]) {+ const req = request(token)+ req.headers.set("cookie", "session=present")+ expect((await route(req)).status).toBe(401)+ }+ expect(handler).not.toHaveBeenCalled()+ expect(fallback).not.toHaveBeenCalled()+ expect(transport).not.toHaveBeenCalled()+ })+ it("does not permit bearer credentials to manage their own codes", async () => {+ const managed = withAutomationManagement(async () => Response.json({ created: true }))+ expect((await managed(request())).status).toBe(401)+ expect((await managed(new NextRequest("http://localhost/api/community/automation/access-codes"))).status).toBe(200)+ })+ it("generates high-entropy secrets and stores only irreversible fixed-size digests", async () => {+ const one = newAutomationSecret(), two = newAutomationSecret()+ expect(one).toMatch(/^aac_[a-f0-9]{64}$/)+ expect(one).not.toBe(two)+ expect(await hashAutomationSecret(one)).toMatch(/^[a-f0-9]{64}$/)+ expect(await hashAutomationSecret(one)).not.toBe(await hashAutomationSecret(two))+ })+})++it("refuses absent credentials and an HTTP failure from the rate limiter", async () => {+ const missing = new NextRequest("http://localhost/api/community/bots", { method: "POST" })+ expect((await withAutomation("bot.create", create)(missing)).status).toBe(401)+ expect(authenticate).not.toHaveBeenCalled()+ transport.mockResolvedValueOnce(new Response("unavailable", { status: 503 }))+ expect((await withAutomation("bot.create", create)(request())).status).toBe(503)+})diff --git a/src/web/src/lib/automation.ts b/src/web/src/lib/automation.tsnew file mode 100644index 000000000..1700e2ae2--- /dev/null+++ b/src/web/src/lib/automation.ts@@ -0,0 +1,78 @@+import { getCloudflareContext } from "@opennextjs/cloudflare"+import { NextRequest } from "next/server"+import { AutomationPermissionPolicySchema, queries, type AutomationPermission } from "@alook/shared"+import { getPrimaryDb } from "@/lib/db"+import { wsDoFetch } from "@/lib/broadcast"+import { writeError } from "@/lib/middleware/helpers"+import { withAuth, type AuthenticatedHandler } from "@/lib/middleware/auth"++export async function hashAutomationSecret(secret: string): Promise<string> {+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret))+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")+}++export function newAutomationSecret(): string {+ return "aac_" + Array.from(crypto.getRandomValues(new Uint8Array(32)), (byte) => byte.toString(16).padStart(2, "0")).join("")+}++export function withAutomationManagement(handler: AuthenticatedHandler) {+ const authenticated = withAuth(handler)+ return (...args: Parameters<typeof authenticated>) => args[0].headers.has("Authorization")+ ? Promise.resolve(writeError("Sign in to manage access codes", 401))+ : authenticated(...args)+}++type RouteContext = { params?: Promise<Record<string, string>> | Record<string, string> }+type AutomationHandler = (req: NextRequest, ctx: { env: Env; userId: string; params?: Record<string, string>; beforeCreate: () => Promise<Response | null> }) => Promise<Response>++function readAutomationSecret(req: NextRequest): string | undefined {+ return /^Bearer (aac_[a-f0-9]{64})$/.exec(req.headers.get("Authorization") ?? "")?.[1]+}++export async function expireAutomationAccessCode(req: NextRequest): Promise<Response> {+ const secret = readAutomationSecret(req)+ if (!secret) return writeError("Invalid or unauthorized access code", 401)+ try {+ const env = (await getCloudflareContext({ async: true })).env as Env+ const expired = await queries.automation.expireAccessCode(getPrimaryDb(env.DB), await hashAutomationSecret(secret))+ return Response.json(expired ? { expired: true } : { error: "Invalid or unauthorized access code" }, {+ status: expired ? 200 : 401, headers: { "Cache-Control": "no-store" },+ })+ } catch { return writeError("Automation expiration unavailable", 503) }+}++export function withAutomation(permission: AutomationPermission, handler: AutomationHandler) {+ return async (req: NextRequest, context?: RouteContext): Promise<Response> => {+ const secret = readAutomationSecret(req)+ if (!secret) return writeError("Invalid or unauthorized access code", 401)+ let env: Env+ let access: Awaited<ReturnType<typeof queries.automation.authenticateAccessCode>>+ try {+ env = (await getCloudflareContext({ async: true })).env as Env+ access = await queries.automation.authenticateAccessCode(getPrimaryDb(env.DB), await hashAutomationSecret(secret), permission)+ } catch { return writeError("Automation authentication unavailable", 503) }+ if (!access) return writeError("Invalid or unauthorized access code", 401)+ const policy = AutomationPermissionPolicySchema.safeParse({ permission, limit: access.limit, period: access.period })+ if (!policy.success) return writeError("Automation policy unavailable", 503)+ const beforeCreate = async (): Promise<Response | null> => {+ try {+ const res = await wsDoFetch(env, "/rate-limit/automation", {+ method: "POST", headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: permission, key: access.codeId, max: policy.data.limit, period: policy.data.period }),+ }, { type: "automation-limit" })+ if (!res.ok) return writeError("Automation rate limiter unavailable", 503)+ const result: unknown = await res.json()+ if (typeof result !== "object" || result === null || !("allowed" in result)) return writeError("Automation rate limiter unavailable", 503)+ if (result.allowed === true) return null+ if (result.allowed === false && "retryAfterSec" in result && typeof result.retryAfterSec === "number" && Number.isFinite(result.retryAfterSec) && result.retryAfterSec > 0) {+ return writeError("Automation rate limit exceeded", 429, { "Retry-After": String(Math.ceil(result.retryAfterSec)) })+ }+ } catch { }+ return writeError("Automation rate limiter unavailable", 503)+ }+ const params = await context?.params+ const response = await handler(req, { env, userId: access.ownerId, params, beforeCreate })+ response.headers.set("Cache-Control", "no-store")+ return response+ }+}diff --git a/src/web/src/lib/community-db/projections.dom.test.ts b/src/web/src/lib/community-db/projections.dom.test.tsindex 5009aa463..86677e9f2 100644--- a/src/web/src/lib/community-db/projections.dom.test.ts+++ b/src/web/src/lib/community-db/projections.dom.test.ts@@ -2,7 +2,7 @@ import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"import { channelResourceFixture, categoryResourceFixture, serverResourceFixture, messageSeedFixture } from "@/test/community-resource-fixtures"import { serverRailResponseFixture } from "@/test/community-resource-fixtures"import { serverDirectoryFixture } from "@/test/community-resource-fixtures"-import { dehydrate, QueryClient, QueryClientProvider } from "@tanstack/react-query"+import { dehydrate, QueryClient, QueryClientProvider, QueryObserver } from "@tanstack/react-query"import React, { type ReactNode } from "react"import { describe, expect, it, vi } from "vitest"import { act, renderHook, waitFor } from "@/test/react-dom-harness"@@ -32,6 +32,32 @@ import { PERSIST_BUSTER, readCommunityRestoredCollections } from "@/lib/query-peimport { profileSchema } from "./schema"describe("community DB projections", () => {+ it("preserves the real fetcher when a passive tree mounts after a read and the key is invalidated", async () => {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const key = communityKeys.server("srv")+ const queryFn = vi.fn().mockResolvedValue({ schemaVersion: BUSINESS_SCHEMA_VERSION, accountId: "viewer", serverId: "srv", categoryIds: [], channelIds: [] })+ const owner = new QueryObserver(client, { queryKey: key, queryFn, staleTime: Infinity })+ const release = owner.subscribe(() => {})+ await owner.refetch()+ const wrapper = ({ children }: { children: ReactNode }) => React.createElement(QueryClientProvider, { client }, children)+ const view = renderHook(() => useServerTreeProjection("srv"), { wrapper })+ try {+ await act(async () => { await client.invalidateQueries({ queryKey: key, exact: true }) })+ expect(queryFn).toHaveBeenCalledTimes(2)+ expect(client.getQueryState(key)?.status).toBe("success")+ } finally { view.unmount(); release(); client.clear() }+ })+ it("subscribes to an empty server cache without a missing query function warning", async () => {+ const client = new QueryClient()+ const error = vi.spyOn(console, "error").mockImplementation(() => {})+ const wrapper = ({ children }: { children: ReactNode }) => React.createElement(QueryClientProvider, { client }, children)+ const view = renderHook(() => useServerTreeProjection(null), { wrapper })+ try {+ await act(async () => {})+ expect(error.mock.calls.flat().join(" ")).not.toContain("queryFn")+ expect(view.result.current).toBeUndefined()+ } finally { view.unmount(); client.clear(); error.mockRestore() }+ })it("carries native preparation and failure through member reads and recovers from actual canonical data", async () => {const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })let reject!: (error: Error) => voiddiff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.tsindex 41cf3b36c..479c647ba 100644--- a/src/web/src/lib/community-db/projections.ts+++ b/src/web/src/lib/community-db/projections.ts@@ -4,10 +4,10 @@ import type { CommunityResourceProfile } from "@alook/shared"import { getServerDirectoryWindow, readServerDirectoryWindow, serverDirectoryWindowComplete } from "@/lib/community/server-directory-window"import { communityKeys } from "@/lib/query-keys"-import { useQuery } from "@tanstack/react-query"+import { useQueryClient } from "@tanstack/react-query"import { forumSidebarWindowComplete, type ForumSidebarWindow } from "@/lib/community/forum-sidebar-window"-import { createContext, createElement, useContext, useMemo, type Context, type ReactNode } from "react"+import { createContext, createElement, useContext, useMemo, useCallback, useSyncExternalStore, type Context, type ReactNode } from "react"import { ApplicationOwnerProvider, createApplicationOwner } from "@/lib/application-owner"import { DbProvider, and, eq, inArray, useLiveQuery as useNativeLiveQuery, type WhereCallback, type ContextFromSource } from "@tanstack/react-db"import { createStore, useSelector } from "@tanstack/react-store"@@ -202,7 +202,14 @@ export function useServerRailProjection() {export function useServerTreeProjection(serverId: string | null) {const registry = useOptionalCommunityDbRegistry()- const directory = useQuery({ queryKey: communityKeys.server(serverId ?? "__none__"), enabled: false, select: readServerDirectoryWindow }).data+ const queryClient = useQueryClient()+ const read = useCallback(() => queryClient.getQueryData(communityKeys.server(serverId ?? "__none__")), [queryClient, serverId])+ const subscribe = useCallback((notify: () => void) => queryClient.getQueryCache().subscribe((event) => {+ const key = event.query.queryKey+ if (key.length === 3 && key[0] === "community" && key[1] === "servers" && key[2] === (serverId ?? "__none__")) notify()+ }), [queryClient, serverId])+ const snapshot = useSyncExternalStore(subscribe, read, read)+ const directory = useMemo(() => readServerDirectoryWindow(snapshot), [snapshot])const servers = useCollectionQuery("servers", ({ row }) => eq(row.id, serverId ?? ""))const categories = useCollectionQuery("categories", ({ row }) => eq(row.serverId, serverId ?? ""))const channels = useCollectionQuery("channels", ({ row }) => eq(row.serverId, serverId ?? ""))diff --git a/src/web/src/lib/community/automation-actions.test.ts b/src/web/src/lib/community/automation-actions.test.tsnew file mode 100644index 000000000..dad775570--- /dev/null+++ b/src/web/src/lib/community/automation-actions.test.ts@@ -0,0 +1,159 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"+const mocks = vi.hoisted(() => ({ machines: vi.fn(), friends: vi.fn(), servers: vi.fn(), friend: vi.fn(), server: vi.fn(), listInvites: vi.fn(), createInvite: vi.fn(), dm: vi.fn(), message: vi.fn(), rate: vi.fn(), fanout: vi.fn() }))+vi.mock("@alook/shared", async (importOriginal) => { const actual = await importOriginal<typeof import("@alook/shared")>(); return { ...actual, queries: { ...actual.queries,+ automation: { listMachines: mocks.machines, listFriends: mocks.friends, getFriendByHandle: mocks.friend },+ communityChannel: { listChannelRefDirectoryForUser: mocks.servers },+ communityServer: { resolveServerByNameForMember: mocks.server }, communityInvite: { listServerInvites: mocks.listInvites, createInvite: mocks.createInvite }, communityDm: { createOrGetDM: mocks.dm },+} } })+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }), getDb: () => ({ primary: true }) }))+vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: mocks.rate }))+vi.mock("./message-handler", () => ({ createCommunityMessage: mocks.message }))+vi.mock("./fanout", () => ({ fanOutToServerMembers: mocks.fanout }))+import { readAutomationMachines, readAutomationFriends, readAutomationServers } from "./automation-read.server"+import { inviteAutomationFriend } from "./automation-invite.server"+import { createBotForUser } from "./create-bot.server"+import { createServerForUser } from "./create-server.server"++const request = (body: unknown = { friend: "Alice#0001" }) => new NextRequest("http://localhost/api/community/servers/demo%230001/invites", { method: "POST", body: JSON.stringify(body) })+function context() { return { env: { DB: {} } as Env, userId: "owner", params: { id: "demo#0001" }, beforeCreate: vi.fn(async (): Promise<Response | null> => null) } }+beforeEach(() => {+ vi.clearAllMocks()+ mocks.machines.mockResolvedValue([{ id: "mac1", name: "Mac", status: "online", hostname: "private", availableRuntimes: [] }])+ mocks.friends.mockResolvedValue([{ id: "hidden", name: "Alice", discriminator: "0001", isBot: false, ownerUserId: null, email: "private" }])+ mocks.servers.mockResolvedValue([{ id: "hidden", name: "demo", discriminator: "0001", ownerId: "private", channels: [{ id: "private-id", name: "general", type: "text", topic: "private" }, { id: "forum-id", name: "ideas", type: "forum" }] }])+ mocks.server.mockResolvedValue([{ id: "s1", name: "demo", discriminator: "0001" }])+ mocks.friend.mockResolvedValue({ id: "friend", name: "Alice", discriminator: "0001" })+ mocks.rate.mockResolvedValue({ allowed: true })+ mocks.listInvites.mockResolvedValue([])+ mocks.createInvite.mockResolvedValue({ id: "invite", token: "token", maxUses: null, uses: 0, expiresAt: null, createdAt: "now", serverId: "s1" })+ mocks.dm.mockResolvedValue({ id: "dm" })+ mocks.message.mockResolvedValue({ ok: true })+})++describe("Automation Read and invitation boundaries", () => {+ it("projects minimal API fields before returning lists, and scopes queries to the code owner", async () => {+ const ctx = context()+ expect(await (await readAutomationMachines(request(), ctx)).json()).toEqual({ machines: [{ id: "mac1", name: "Mac", status: "online", backends: [] }] })+ expect(await (await readAutomationFriends(request(), ctx)).json()).toEqual({ friends: [{ name: "Alice", handle: "Alice#0001", is_my_bot: false }] })+ expect(await (await readAutomationServers(request(), ctx)).json()).toEqual({ servers: [{ name: "demo", handle: "demo#0001", channels: [{ name: "general", type: "text", ref: "/demo#0001/general" }, { name: "ideas", type: "forum", ref: "/demo#0001/ideas" }] }] })+ expect(mocks.servers).toHaveBeenCalledExactlyOnceWith({ primary: true }, "owner", { railOrder: false })+ for (const query of [mocks.machines, mocks.friends]) expect(query).toHaveBeenCalledExactlyOnceWith({ primary: true }, "owner")+ })+ it("keeps joined servers with no participating channels and handles no joined servers", async () => {+ mocks.servers.mockResolvedValueOnce([{ id: "s1", name: "demo", discriminator: "0001", channels: [] }])+ expect(await (await readAutomationServers(request(), context())).json()).toEqual({ servers: [{ name: "demo", handle: "demo#0001", channels: [] }] })+ mocks.servers.mockResolvedValueOnce([])+ expect(await (await readAutomationServers(request(), context())).json()).toEqual({ servers: [] })+ })+ it("marks only the code owner's bots and returns both persisted machine statuses without private fields", async () => {+ mocks.friends.mockResolvedValue([+ { name: "Helper", discriminator: "0001", isBot: true, ownerUserId: "owner", id: "private" },+ { name: "Peer bot", discriminator: "0002", isBot: true, ownerUserId: "other", email: "private" },+ { name: "Human", discriminator: "0003", isBot: false, ownerUserId: "owner" },+ ])+ mocks.machines.mockResolvedValue([+ { id: "online", name: "Running", status: "online", hostname: "private", availableRuntimes: [] },+ { id: "offline", name: "Stopped", status: "offline", availableRuntimes: [] },+ ])+ expect(await (await readAutomationFriends(request(), context())).json()).toEqual({ friends: [+ { name: "Helper", handle: "Helper#0001", is_my_bot: true },+ { name: "Peer bot", handle: "Peer bot#0002", is_my_bot: false },+ { name: "Human", handle: "Human#0003", is_my_bot: false },+ ] })+ expect(await (await readAutomationMachines(request(), context())).json()).toEqual({ machines: [+ { id: "online", name: "Running", status: "online", backends: [] },+ { id: "offline", name: "Stopped", status: "offline", backends: [] },+ ] })+ })+ it("rejects invalid creation input before quota admission and stops valid input on denial", async () => {+ const ctx = context()+ expect((await createBotForUser(request({ name: "Only a name" }), ctx)).status).toBe(400)+ expect((await createServerForUser(request(null), ctx)).status).toBe(400)+ expect(ctx.beforeCreate).not.toHaveBeenCalled()+ ctx.beforeCreate.mockResolvedValue(Response.json({}, { status: 429 }))+ expect((await createBotForUser(request({ name: "Bot", machineId: "mac1", runtime: "claude" }), ctx)).status).toBe(429)+ expect((await createServerForUser(request({ name: "demo" }), ctx)).status).toBe(429)+ })+ it("does not read resource data when its independent quota is denied", async () => {+ const ctx = context()+ ctx.beforeCreate.mockResolvedValue(Response.json({ error: "limited" }, { status: 429 }))+ for (const read of [readAutomationMachines, readAutomationFriends, readAutomationServers]) expect((await read(request(), ctx)).status).toBe(429)+ expect(mocks.machines).not.toHaveBeenCalled()+ expect(mocks.friends).not.toHaveBeenCalled()+ expect(mocks.servers).not.toHaveBeenCalled()+ })+ it("sends only the generated invitation link to an accepted friend, with no forced join", async () => {+ const response = await inviteAutomationFriend(request(), context())+ expect(response.status).toBe(201)+ expect(await response.json()).toEqual({ invitation: { server: "demo#0001", friend: "Alice#0001", sent: true } })+ expect(mocks.server).toHaveBeenCalledWith({ primary: true }, "owner", "demo#0001")+ expect(mocks.friend).toHaveBeenCalledWith({ primary: true }, "owner", "Alice#0001")+ expect(mocks.message).toHaveBeenCalledExactlyOnceWith({ db: { primary: true }, authorId: "owner", authorKind: "human", target: { kind: "dm", channelId: "dm", otherUserId: "friend" }, body: { content: "http://localhost/c/invite/token" }, source: "web" })+ expect(mocks.fanout).toHaveBeenCalledOnce()+ })+ it("does not grant arbitrary DM content, nonfriend targets or inaccessible servers", async () => {+ expect((await inviteAutomationFriend(request({ friend: "Alice#0001", content: "arbitrary text" }), context())).status).toBe(400)+ mocks.friend.mockResolvedValueOnce(null)+ expect((await inviteAutomationFriend(request(), context())).status).toBe(404)+ mocks.server.mockResolvedValueOnce([])+ expect((await inviteAutomationFriend(request(), context())).status).toBe(404)+ expect(mocks.createInvite).not.toHaveBeenCalled()+ expect(mocks.dm).not.toHaveBeenCalled()+ expect(mocks.message).not.toHaveBeenCalled()+ })+ it("preserves both automation quota and normal message rate limiting", async () => {+ const ctx = context()+ ctx.beforeCreate.mockResolvedValueOnce(Response.json({}, { status: 429 }))+ expect((await inviteAutomationFriend(request(), ctx)).status).toBe(429)+ expect(mocks.server).not.toHaveBeenCalled()+ mocks.rate.mockResolvedValueOnce({ allowed: false, retryAfterSec: 10 })+ const response = await inviteAutomationFriend(request(), context())+ expect(response.status).toBe(429)+ expect(response.headers.get("Retry-After")).toBe("10")+ expect(mocks.message).not.toHaveBeenCalled()+ })+ it("reuses only the caller's live invite and reports existing capacity/message errors", async () => {+ mocks.listInvites.mockResolvedValueOnce([{ creatorId: "owner", token: "reused", maxUses: 2, uses: 1, expiresAt: null }])+ expect((await inviteAutomationFriend(request(), context())).status).toBe(201)+ expect(mocks.createInvite).not.toHaveBeenCalled()+ expect(mocks.fanout).not.toHaveBeenCalled()+ mocks.createInvite.mockResolvedValueOnce(null)+ expect((await inviteAutomationFriend(request(), context())).status).toBe(409)+ mocks.message.mockResolvedValueOnce({ ok: false, status: 409, error: "Message failed" })+ expect((await inviteAutomationFriend(request(), context())).status).toBe(409)+ })+})++it("rejects missing or malformed server handles before admission", async () => {+ const ctx = context()+ for (const params of [undefined, {}, { id: "not-a-handle" }]) {+ expect((await inviteAutomationFriend(request(), { ...ctx, params })).status).toBe(400)+ }+ expect(ctx.beforeCreate).not.toHaveBeenCalled()+ expect(mocks.server).not.toHaveBeenCalled()+ expect(mocks.message).not.toHaveBeenCalled()+})++it("skips another author's, expired and exhausted invitations before reusing a valid one", async () => {+ mocks.listInvites.mockResolvedValueOnce([+ { creatorId: "other", token: "other", maxUses: null, uses: 0, expiresAt: null },+ { creatorId: "owner", token: "expired", maxUses: null, uses: 0, expiresAt: "2000-01-01T00:00:00Z" },+ { creatorId: "owner", token: "exhausted", maxUses: 1, uses: 1, expiresAt: null },+ { creatorId: "owner", token: "valid", maxUses: 2, expiresAt: "2999-01-01T00:00:00Z" },+ ])+ expect((await inviteAutomationFriend(request(), context())).status).toBe(201)+ expect(mocks.createInvite).not.toHaveBeenCalled()+ expect(mocks.message.mock.lastCall?.[0].body).toEqual({ content: "http://localhost/c/invite/valid" })+})++it("normalizes legacy backends and strips runtime diagnostics and model bodies from the machine list", async () => {+ mocks.machines.mockResolvedValue([{ id: "m", name: "M", status: "online", availableRuntimes: ["codex", "", null,+ { id: "opencode", status: "unhealthy", version: "1", lastError: "private", reasoning: { updateMode: "unsupported", catalogOrigin: "adapter_suggestions", models: [] } },+ { id: "bad runtime", status: "healthy" },+ ] }])+ expect(await (await readAutomationMachines(request(), context())).json()).toEqual({ machines: [{ id: "m", name: "M", status: "online", backends: [+ { id: "codex", health: "healthy", modelRequired: false },+ { id: "opencode", version: "1", health: "unhealthy", modelRequired: true },+ ] }] })+})diff --git a/src/web/src/lib/community/automation-invite.server.ts b/src/web/src/lib/community/automation-invite.server.tsnew file mode 100644index 000000000..496ae2285--- /dev/null+++ b/src/web/src/lib/community/automation-invite.server.ts@@ -0,0 +1,45 @@+import type { NextRequest } from "next/server"+import { queries, parseNameAndTag, formatHandle, MAX_ACTIVE_INVITES_PER_SERVER, WS_EVENTS } from "@alook/shared"+import { z } from "zod"+import { getPrimaryDb } from "@/lib/db"+import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers"+import { checkRateLimit } from "@/lib/rate-limit"+import { createCommunityMessage } from "./message-handler"+import { fanOutToServerMembers } from "./fanout"++const InvitationInput = z.strictObject({ friend: z.string().min(1).max(128).refine((value) => Boolean(parseNameAndTag(value)), "Use a full friend handle") })++export async function inviteAutomationFriend(req: NextRequest, ctx: { env: Env; userId: string; params?: Record<string, string>; beforeCreate: () => Promise<Response | null> }) {+ const [body, error] = await parseBody(req, InvitationInput)+ if (error) return error+ const serverRef = ctx.params?.id ?? ""+ if (!parseNameAndTag(serverRef)) return writeError("Use a full server handle", 400)+ const denied = await ctx.beforeCreate()+ if (denied) return denied+ const db = getPrimaryDb(ctx.env.DB)+ const [server] = await queries.communityServer.resolveServerByNameForMember(db, ctx.userId, serverRef)+ if (!server) return writeError("Server not found", 404)+ const friend = await queries.automation.getFriendByHandle(db, ctx.userId, body.friend)+ if (!friend) return writeError("Friend not found", 404)+ const messageLimit = await checkRateLimit(ctx.env, "community:msgSend", ctx.userId)+ if (!messageLimit.allowed) return writeError("Message rate limit exceeded", 429, { "Retry-After": String(messageLimit.retryAfterSec) })+ const now = new Date().toISOString()+ const invites = await queries.communityInvite.listServerInvites(db, server.id)+ let invite = invites.find((item) => item.creatorId === ctx.userId && (!item.expiresAt || item.expiresAt > now) && (item.maxUses === null || (item.uses ?? 0) < item.maxUses))+ if (!invite) {+ const created = await queries.communityInvite.createInvite(db, { serverId: server.id, createdBy: ctx.userId, maxActive: MAX_ACTIVE_INVITES_PER_SERVER })+ if (created) {+ fanOutToServerMembers(server.id, { type: WS_EVENTS.INVITE_CREATE, serverId: server.id,+ invite: { id: created.id, token: created.token, maxUses: created.maxUses, uses: created.uses, expiresAt: created.expiresAt, createdAt: created.createdAt } })+ invite = { ...created, creatorId: ctx.userId, creatorName: null, creatorEmail: null, creatorImage: null, creatorAvatarVersion: null }+ }+ }+ if (!invite) return writeError("Server has reached its active invite limit", 409)+ const dm = await queries.communityDm.createOrGetDM(db, { userId1: ctx.userId, userId2: friend.id })+ const result = await createCommunityMessage({+ db, authorId: ctx.userId, authorKind: "human", target: { kind: "dm", channelId: dm.id, otherUserId: friend.id },+ body: { content: `${new URL(req.url).origin}/c/invite/${encodeURIComponent(invite.token)}` }, source: "web",+ })+ if (!result.ok) return writeError(result.error, result.status)+ return writeJSON({ invitation: { server: formatHandle(server.name, server.discriminator), friend: formatHandle(friend.name, friend.discriminator), sent: true } }, 201)+}diff --git a/src/web/src/lib/community/automation-message.server.test.ts b/src/web/src/lib/community/automation-message.server.test.tsnew file mode 100644index 000000000..a0c8bf1c3--- /dev/null+++ b/src/web/src/lib/community/automation-message.server.test.ts@@ -0,0 +1,75 @@+import { beforeEach, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"+const mocks = vi.hoisted(() => ({ owned: vi.fn(), actor: vi.fn(), human: vi.fn(), bot: vi.fn(), admit: vi.fn() }))+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }) }))+vi.mock("@alook/shared", async (original) => ({ ...await original<typeof import("@alook/shared")>(), queries: { automation: { getOwnedBotByHandle: mocks.owned } } }))+vi.mock("@/lib/middleware/community-agent-runner-auth", () => ({ resolveOwnedBotActor: mocks.actor }))+vi.mock("./message-send.server", () => ({ handleHumanSend: mocks.human, handleBotSend: mocks.bot }))+import { sendAutomationMessage } from "./automation-message.server"+const body = { target: "/demo#0001/general", as: "me", content: "你好\nsecond line\n", nonce: "n1" }+const req = (input: unknown = body) => new NextRequest("http://localhost/api/community/automation/messages", { method: "POST", body: JSON.stringify(input) })+const ctx = { env: { DB: {} } as Env, userId: "owner", beforeCreate: mocks.admit }+beforeEach(() => {+ vi.clearAllMocks()+ mocks.owned.mockResolvedValue({ id: "ownbot" })+ mocks.actor.mockResolvedValue({ kind: "bot", actor: { botUserId: "ownbot" } })+ mocks.admit.mockResolvedValue(null)+ mocks.human.mockResolvedValue(Response.json({ message: { id: "hm", seq: 3 } }, { status: 201 }))+ mocks.bot.mockResolvedValue(Response.json({ state: "sent", message: { seq: "#4" } }))+})+it("uses the code owner, exact file content and existing human sender with ref addressing", async () => {+ const response = await sendAutomationMessage(req(), ctx)+ expect(response.status).toBe(201)+ expect(await response.json()).toEqual({ state: "sent", seq: "#3", deduped: false })+ expect(mocks.human).toHaveBeenCalledWith({ primary: true }, "owner", ctx.env,+ { ref: body.target, createDmIfMissing: true, createThreadIfMissing: true }, { content: body.content, nonce: "n1" }, expect.any(Number))+ expect(mocks.admit).toHaveBeenCalledOnce()+ expect(mocks.owned).not.toHaveBeenCalled()+ expect(mocks.bot).not.toHaveBeenCalled()+})+it("resolves ownership and ordinary bot eligibility before invoking the existing bot sender as that bot", async () => {+ const response = await sendAutomationMessage(req({ ...body, as: "@Helper#0001", target: "/.dm/Alice#0002" }), ctx)+ expect(await response.json()).toEqual({ state: "sent", seq: "#4", deduped: false })+ expect(mocks.owned).toHaveBeenCalledWith({ primary: true }, "owner", "Helper#0001")+ expect(mocks.actor).toHaveBeenCalledWith({ primary: true }, "ownbot", "owner")+ expect(mocks.bot).toHaveBeenCalledExactlyOnceWith({ primary: true }, "ownbot", ctx.env,+ { channel: "/.dm/Alice#0002", content: { text: body.content }, nonce: "n1" })+ expect(mocks.human).not.toHaveBeenCalled()+})+it("rejects foreign/deleted/human handles and ineligible bot bindings without spending a send or calling a sender", async () => {+ mocks.owned.mockResolvedValueOnce(null)+ expect((await sendAutomationMessage(req({ ...body, as: "@Other#0001" }), ctx)).status).toBe(404)+ mocks.actor.mockResolvedValueOnce({ kind: "error", response: Response.json({ error: "inactive" }, { status: 403 }) })+ expect((await sendAutomationMessage(req({ ...body, as: "@Helper#0001" }), ctx)).status).toBe(403)+ expect(mocks.admit).not.toHaveBeenCalled()+ expect(mocks.human).not.toHaveBeenCalled()+ expect(mocks.bot).not.toHaveBeenCalled()+})+it("rejects invalid identity/target/content and spoofed body fields before any actor lookup", async () => {+ for (const input of [null, {}, { ...body, as: "owner" }, { ...body, as: "Helper#0001" }, { ...body, as: "@Helper" }, { ...body, target: "channel-id" }, { ...body, content: " " }, { ...body, content: "x".repeat(4001) }, { ...body, userId: "foreign" }, { ...body, seenUpToSeq: 999 }]) {+ expect((await sendAutomationMessage(req(input), ctx)).status).toBe(400)+ }+ expect(mocks.owned).not.toHaveBeenCalled()+ expect(mocks.admit).not.toHaveBeenCalled()+ expect(mocks.human).not.toHaveBeenCalled()+ expect(mocks.bot).not.toHaveBeenCalled()+})+it("returns quota failures and original alignment/permission failures without changing them", async () => {+ mocks.admit.mockResolvedValueOnce(Response.json({ error: "limited" }, { status: 429, headers: { "Retry-After": "17" } }))+ const limited = await sendAutomationMessage(req(), ctx)+ expect(limited.status).toBe(429)+ expect(limited.headers.get("Retry-After")).toBe("17")+ expect(mocks.human).not.toHaveBeenCalled()+ const blocked = { state: "blocked", reason: "unaligned", unreadCount: 2, latestSeq: 4 }+ mocks.bot.mockResolvedValueOnce(Response.json(blocked))+ expect(await (await sendAutomationMessage(req({ ...body, as: "@Helper#0001" }), ctx)).json()).toEqual(blocked)+ mocks.human.mockResolvedValueOnce(Response.json({ error: "forbidden" }, { status: 403 }))+ expect((await sendAutomationMessage(req(), ctx)).status).toBe(403)+})++it("keeps the same Automation receipt for human and bot forum openers and replays", async () => {+ mocks.human.mockResolvedValueOnce(Response.json({ message: { seq: 8 }, threadId: "thread-h", deduped: true }))+ expect(await (await sendAutomationMessage(req(), ctx)).json()).toEqual({ state: "sent", seq: "#8", threadId: "thread-h", deduped: true })+ mocks.bot.mockResolvedValueOnce(Response.json({ state: "sent", message: { seq: "#9" }, threadId: "thread-b", deduped: true }))+ expect(await (await sendAutomationMessage(req({ ...body, as: "@Helper#0001" }), ctx)).json()).toEqual({ state: "sent", seq: "#9", threadId: "thread-b", deduped: true })+})diff --git a/src/web/src/lib/community/automation-message.server.ts b/src/web/src/lib/community/automation-message.server.tsnew file mode 100644index 000000000..3a429e047--- /dev/null+++ b/src/web/src/lib/community/automation-message.server.ts@@ -0,0 +1,29 @@+import type { NextRequest } from "next/server"+import { AutomationMessageSendSchema, COMMUNITY_RESOURCE_CONTRACT_VERSION, queries } from "@alook/shared"+import { getPrimaryDb } from "@/lib/db"+import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers"+import { resolveOwnedBotActor } from "@/lib/middleware/community-agent-runner-auth"+import { handleHumanSend, handleBotSend } from "./message-send.server"++export async function sendAutomationMessage(req: NextRequest, ctx: { env: Env; userId: string; beforeCreate: () => Promise<Response | null> }) {+ const [body, error] = await parseBody(req, AutomationMessageSendSchema)+ if (error) return error+ const db = getPrimaryDb(ctx.env.DB)+ let botId: string | undefined+ if (body.as !== "me") {+ const bot = await queries.automation.getOwnedBotByHandle(db, ctx.userId, body.as.slice(1))+ if (!bot) return writeError("Bot not found", 404)+ const actor = await resolveOwnedBotActor(db, bot.id, ctx.userId)+ if (actor.kind === "error") return actor.response+ botId = actor.actor.botUserId+ }+ const denied = await ctx.beforeCreate()+ if (denied) return denied+ const response = botId ? await handleBotSend(db, botId, ctx.env, { channel: body.target, content: { text: body.content }, nonce: body.nonce })+ : await handleHumanSend(db, ctx.userId, ctx.env, { ref: body.target, createDmIfMissing: true, createThreadIfMissing: true }, { content: body.content, nonce: body.nonce }, COMMUNITY_RESOURCE_CONTRACT_VERSION)+ if (!response.ok) return response+ const result = await response.json() as { state?: string; message: { seq: number | string }; deduped?: boolean; threadId?: string }+ if (result.state === "blocked") return writeJSON(result, response.status)+ const seq = botId ? result.message.seq : `#${result.message.seq}`+ return writeJSON({ state: "sent", seq, deduped: result.deduped === true, ...(result.threadId ? { threadId: result.threadId } : {}) }, response.status)+}diff --git a/src/web/src/lib/community/automation-read.server.ts b/src/web/src/lib/community/automation-read.server.tsnew file mode 100644index 000000000..914fb9f72--- /dev/null+++ b/src/web/src/lib/community/automation-read.server.ts@@ -0,0 +1,34 @@+import { queries, formatHandle, formatCanonicalRef } from "@alook/shared"+import { getPrimaryDb } from "@/lib/db"+import { writeJSON } from "@/lib/middleware/helpers"+import type { NextRequest } from "next/server"+import { projectMachineBackends } from "./machine-options.server"++type ReadContext = { env: Env; userId: string; beforeCreate: () => Promise<Response | null> }++export async function readAutomationMachines(_req: NextRequest, ctx: ReadContext) {+ const denied = await ctx.beforeCreate()+ if (denied) return denied+ const machines = await queries.automation.listMachines(getPrimaryDb(ctx.env.DB), ctx.userId)+ return writeJSON({ machines: machines.map(({ id, name, status, availableRuntimes }) => ({ id, name, status, backends: projectMachineBackends(queries.communityBot.normalizeMachineRuntimes(availableRuntimes), { includeCatalogMetadata: false }) })) })+}++export async function readAutomationFriends(_req: NextRequest, ctx: ReadContext) {+ const denied = await ctx.beforeCreate()+ if (denied) return denied+ const friends = await queries.automation.listFriends(getPrimaryDb(ctx.env.DB), ctx.userId)+ return writeJSON({ friends: friends.map((friend) => ({ name: friend.name, handle: formatHandle(friend.name, friend.discriminator), is_my_bot: friend.isBot && friend.ownerUserId === ctx.userId })) })+}++export async function readAutomationServers(_req: NextRequest, ctx: ReadContext) {+ const denied = await ctx.beforeCreate()+ if (denied) return denied+ const servers = await queries.communityChannel.listChannelRefDirectoryForUser(getPrimaryDb(ctx.env.DB), ctx.userId, { railOrder: false })+ return writeJSON({ servers: servers.map((server) => {+ const handle = formatHandle(server.name, server.discriminator)+ return { name: server.name, handle, channels: server.channels.map((channel) => ({+ name: channel.name, type: channel.type,+ ref: formatCanonicalRef({ type: channel.type, serverHandle: handle, name: channel.name }),+ })) }+ }) })+}diff --git a/src/web/src/lib/community/create-bot.server.ts b/src/web/src/lib/community/create-bot.server.tsnew file mode 100644index 000000000..c96b3d06c--- /dev/null+++ b/src/web/src/lib/community/create-bot.server.ts@@ -0,0 +1,114 @@+import { NextRequest } from "next/server"+import { queries, CommunityBotCreateRequestSchema, resolveBotCreationConfiguration, BotCreationError, requiresExplicitModel } from "@alook/shared"+import { getPrimaryDb } from "@/lib/db"+import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"+import { completeBotCreation } from "@/lib/community/bot-creation.server"++export interface ResourceCreationContext {+ env: Env+ userId: string+ beforeCreate?: () => Promise<Response | null>+}++export async function createBotForUser(req: NextRequest, ctx: ResourceCreationContext): Promise<Response> {+ const [body, err] = await parseBody(req, CommunityBotCreateRequestSchema)+ if (err) return err+ if (requiresExplicitModel(body.runtime) && !body.model?.trim()) {+ return writeError("Choose a model before saving", 400)+ }++ const denied = await ctx.beforeCreate?.()+ if (denied) return denied++ const db = getPrimaryDb(ctx.env.DB)++ let capacity = await queries.productPlan.getBotCapacitySummary(db, ctx.userId)+ if (capacity.ownedCount >= capacity.limit) {+ return writeJSON({+ error: "BOT_LIMIT_REACHED",+ plan: capacity.plan.id,+ planDisplayName: capacity.plan.displayName,+ limit: capacity.limit,+ ownedCount: capacity.ownedCount,+ activeCount: capacity.activeCount,+ }, 409)+ }++ // Machine must be owned by caller AND runtime must be in its availableRuntimes+ // AND currently healthy. Unhealthy runtimes (e.g. broken binary caught by+ // spawn ENOENT and marked by the daemon) are rejected here so a UX picker+ // race doesn't create a bot bound to something that will always fail.+ const machine = await queries.communityBot.getMachineForOwner(+ db,+ body.machineId,+ ctx.userId,+ )+ if (!machine) return writeError("machine not found", 404)+ // getMachineForOwner canonicalizes `availableRuntimes` to include status/lastError+ // via the shared schema, so we can consult status here directly.+ const runtime = machine.availableRuntimes.find((r) => r.id === body.runtime)+ const modelName = body.model ?? null+ let effortResolution+ try { effortResolution = resolveBotCreationConfiguration(machine, runtime, { backendId: body.runtime, model: modelName, reasoningEffort: body.reasoningEffort ?? null }) }+ catch (error) {+ if (error instanceof BotCreationError) return writeJSON({ error: error.message, code: error.code, ...error.details }, error.status)+ throw error+ }++ let created: Awaited<ReturnType<typeof queries.communityBot.createBot>>+ try {+ created = await queries.communityBot.createBot(db, {+ ownerId: ctx.userId,+ name: body.name,+ description: body.description,+ machineId: body.machineId,+ runtime: body.runtime,+ image: body.image ?? null,+ modelName,+ reasoningEffort: effortResolution.canonicalEffort,+ })+ } catch (error) {+ if (!queries.communityBot.isBotEntitlementLimitError(error)) throw error+ capacity = await queries.productPlan.getBotCapacitySummary(db, ctx.userId)+ return writeJSON({+ error: "BOT_LIMIT_REACHED",+ plan: capacity.plan.id,+ planDisplayName: capacity.plan.displayName,+ limit: capacity.limit,+ ownedCount: capacity.ownedCount,+ activeCount: capacity.activeCount,+ }, 409)+ }++ // The bot's owner is the authenticated caller — resolve their handle to+ // carry in the bot:added push so the daemon can tell the agent who owns it.+ // The owner MUST resolve: if getUserPublic can't find the authenticated+ // caller we've hit an integrity bug (auth accepted a user id that no longer+ // has a row), and pushing a bot:added with empty owner fields would+ // silently strip the "You are owned by …" privacy paragraph from the+ // agent's system prompt.+ const owner = await queries.user.getUserPublic(db, ctx.userId)+ if (!owner) return writeError("owner not resolvable — retry after re-authenticating", 500)++ await completeBotCreation(ctx.env, db, ctx.userId, owner, [{ id: created.botId, name: created.name, discriminator: created.discriminator, description: created.description, machineId: body.machineId }])++ return writeJSON(+ {+ bot: {+ id: created.botId,+ name: created.name,+ discriminator: created.discriminator,+ description: created.description,+ image: created.image,+ avatarVersion: 0,+ machineId: body.machineId,+ runtime: body.runtime,+ modelName,+ reasoningEffort: effortResolution.canonicalEffort,+ runtimeConfigRevision: 0,+ isActive: true,+ },+ },+ 201,+ )+}diff --git a/src/web/src/lib/community/create-community-message-allowlist.test.ts b/src/web/src/lib/community/create-community-message-allowlist.test.tsindex 60a8f80ff..722a509ea 100644--- a/src/web/src/lib/community/create-community-message-allowlist.test.ts+++ b/src/web/src/lib/community/create-community-message-allowlist.test.ts@@ -9,16 +9,15 @@ import { join, relative, sep } from "path"* the set equals a hand-maintained allowlist — a NEW caller (e.g. a re-added flat* verb, or a route that should have folded into the canonical door) fails the* test until it's consciously added here. That's the point: the allowlist is the- * positive proof that the flat tree stayed deleted and no fourth door-bypass+ * positive proof that the flat tree stayed deleted and no unapproved door-bypass* caller crept in (Melly #346 / Aigneis ③).** Paths are repo-relative to src/web (the vitest cwd). `message-handler.ts` is* excluded — it DEFINES createCommunityMessage, it doesn't call it.*/const ALLOWLIST = [- // The canonical id-in-path message door (human + bot, folds flat `send` and- // the former dm/[id]/messages route — DM now flows through this one tree).- "src/app/api/community/channels/[id]/messages/route.ts",+ // Shared canonical sender used by the normal and Automation message doors.+ "src/lib/community/message-send.server.ts",// First-run onboarding placeholder. Role events start the bots first, then// this invokes the deferred canonical dispatcher so normal mention, wake,// broadcast, and typing behavior all remain intact.@@ -27,6 +26,7 @@ const ALLOWLIST = [// primitive — shared by the send-fold (step 4) and the existing-data// migration (step 5) to open a message with its own auto-created thread."src/lib/community/create-channels.ts",+ "src/lib/community/automation-invite.server.ts",].sort()function walk(dir: string, acc: string[] = []): string[] {diff --git a/src/web/src/lib/community/create-server.server.ts b/src/web/src/lib/community/create-server.server.tsnew file mode 100644index 000000000..6ad9fb4f1--- /dev/null+++ b/src/web/src/lib/community/create-server.server.ts@@ -0,0 +1,71 @@+import { NextRequest } from "next/server"+import { queries, MAX_SERVER_NAME_LENGTH, MAX_SERVER_DESCRIPTION_LENGTH, ROLES, WS_EVENTS, slugify } from "@alook/shared"+import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { getDb } from "@/lib/db"+import { fanOutToServerMembers } from "@/lib/community/fanout"+import { canonicalUserImage } from "@/lib/community/storage"+import type { ResourceCreationContext } from "./create-bot.server"++export async function createServerForUser(req: NextRequest, ctx: ResourceCreationContext): Promise<Response> {+ const db = getDb(ctx.env.DB)++ let body: { name?: string; description?: string }+ try {+ body = await req.json()+ } catch {+ return writeError("invalid request body", 400)+ }++ if (!body || typeof body !== "object" || !body.name || typeof body.name !== "string") {+ return writeError("name is required", 400)+ }+ const trimmed = body.name.trim()+ if (!trimmed || trimmed.length > MAX_SERVER_NAME_LENGTH) {+ return writeError(`name must be 1-${MAX_SERVER_NAME_LENGTH} characters`, 400)+ }+ const name = slugify(trimmed)+ if (!name) {+ return writeError("name is required", 400)+ }++ let description: string | undefined+ if (body.description !== undefined) {+ if (typeof body.description !== "string") {+ return writeError("description must be a string", 400)+ }+ if (body.description.length > MAX_SERVER_DESCRIPTION_LENGTH) {+ return writeError(`description must be ≤ ${MAX_SERVER_DESCRIPTION_LENGTH} characters`, 400)+ }+ description = body.description+ }++ const denied = await ctx.beforeCreate?.()+ if (denied) return denied++ const { server, ownerMember } = await queries.communityServer.createServer(db, {+ name,+ description,+ ownerId: ctx.userId,+ })++ fanOutToServerMembers(server.id, {+ type: WS_EVENTS.MEMBER_JOIN,+ serverId: server.id,+ member: {+ id: ownerMember.id,+ userId: ctx.userId,+ name: ownerMember.userName,+ discriminator: ownerMember.userDiscriminator,+ avatar: canonicalUserImage(+ ownerMember.userId,+ ownerMember.userImage,+ ownerMember.userAvatarVersion,+ ),+ avatarVersion: ownerMember.userAvatarVersion,+ role: ROLES.OWNER,+ joinedAt: ownerMember.joinedAt,+ },+ })++ return writeJSON({ server }, 201)+}diff --git a/src/web/src/lib/community/discover-models.server.ts b/src/web/src/lib/community/discover-models.server.tsnew file mode 100644index 000000000..2e5eff397--- /dev/null+++ b/src/web/src/lib/community/discover-models.server.ts@@ -0,0 +1,70 @@+import { z } from "zod"+import type { NextRequest } from "next/server"+import { projectModelOptions } from "@/lib/community/machine-options.server"+import { queries, readBoundedJsonRequest, RuntimeModelDiscoveryRequestSchema, RuntimeModelDiscoveryResultSchema, fingerprintRuntimeModelCatalog, RUNTIME_MODEL_CATALOG_FINGERPRINT_HEADER } from "@alook/shared"+import { getPrimaryDb } from "@/lib/db"+import { writeError, writeJSON } from "@/lib/middleware/helpers"+import { wsDoFetch } from "@/lib/broadcast"++type DiscoveryContext = { env: Env; userId: string; params?: Record<string, string>; beforeCreate?: () => Promise<Response | null> }++export function discoveryFailure(message: string, status: number, machineId: string) {+ const code = message === "MACHINE_OFFLINE" || message === "UPGRADE_REQUIRED" ? message+ : message === "machine not found" ? "MACHINE_NOT_FOUND" : message === "runtime not found" ? "BACKEND_NOT_FOUND"+ : message === "invalid request" ? "INVALID_DISCOVERY_REQUEST" : "DISCOVERY_UNAVAILABLE"+ const text = code === "MACHINE_OFFLINE" ? "Target machine is offline" : code === "UPGRADE_REQUIRED" ? "Target daemon must be upgraded to discover models" : message+ return writeJSON({ error: text, code, machineId }, status)+}++export async function discoverRuntimeModels(req: NextRequest, ctx: DiscoveryContext, wait: boolean, failure: (message: string, status: number) => Response) {+ const id = ctx.params?.id as string+ const machine = await queries.communityMachine.getMachineByIdForUser(getPrimaryDb(ctx.env.DB), ctx.userId, id)+ if (!machine) return failure("machine not found", 404)+ if (machine.status !== "online") return failure("MACHINE_OFFLINE", 409)+ const input = await readBoundedJsonRequest(req, 4096)+ const payload = (wait ? RuntimeModelDiscoveryRequestSchema.extend({ refresh: z.boolean().optional() }) : RuntimeModelDiscoveryRequestSchema).safeParse(input.ok ? input.value : null)+ if (!payload.success) return failure("invalid request", 400)+ const runtime = queries.communityBot.normalizeMachineRuntimes(machine.availableRuntimes).find((runtime) => runtime.id === payload.data.runtimeId)+ if (!runtime) {+ return failure("runtime not found", 400)+ }+ const forceRefresh = "refresh" in payload.data && payload.data.refresh === true+ const discoveryRequest = { requestId: payload.data.requestId, runtimeId: payload.data.runtimeId }+ const denied = await ctx.beforeCreate?.()+ if (denied) return denied+ const catalogFingerprint = wait && !forceRefresh ? await fingerprintRuntimeModelCatalog(runtime.reasoning ?? null) : undefined+ try {+ const response = await wsDoFetch(ctx.env, `/community-machine/by-id/${encodeURIComponent(id)}/discover-models${wait ? `?wait=1${forceRefresh ? "" : "&cache=1"}` : ""}`, {+ method: "POST", headers: { "content-type": "application/json", ...(catalogFingerprint ? { [RUNTIME_MODEL_CATALOG_FINGERPRINT_HEADER]: catalogFingerprint } : {}) }, body: JSON.stringify(discoveryRequest),+ })+ if (!response.ok) return failure("model discovery unavailable", 503)+ const receipt = await response.json() as { sent?: unknown; unsupported?: unknown; result?: unknown; cached?: unknown; observedAt?: unknown; catalogFingerprint?: unknown }+ if (typeof receipt.sent !== "number" || !Number.isSafeInteger(receipt.sent) || receipt.sent < 0) {+ return failure("model discovery unavailable", 503)+ }+ if (receipt.sent > 0 || (wait && receipt.cached === true)) {+ if (!wait) return writeJSON({ dispatched: true, requestId: payload.data.requestId }, 202)+ if (receipt.cached === true && (!catalogFingerprint || receipt.catalogFingerprint !== catalogFingerprint)) return failure("model discovery unavailable", 503)+ const result = RuntimeModelDiscoveryResultSchema.safeParse(receipt.cached === true ? { status: "complete", catalog: runtime.reasoning ?? null } : receipt.result)+ if (!result.success || (receipt.cached === true && result.data.status !== "complete")) return failure("model discovery unavailable", 503)+ if (result.data.status === "error") return writeJSON({ error: result.data.message, code: result.data.code, machineId: id, backendId: payload.data.runtimeId, requestId: payload.data.requestId }, 502)+ if (typeof receipt.observedAt !== "string" || !Number.isFinite(Date.parse(receipt.observedAt))) return failure("model discovery unavailable", 503)+ return { machineId: id, backendId: payload.data.runtimeId, requestId: payload.data.requestId,+ source: receipt.cached === true ? "cached_report" : "fresh_discovery", observedAt: receipt.observedAt, result: result.data }++ }+ return failure(typeof receipt.unsupported === "number" && receipt.unsupported > 0 ? "UPGRADE_REQUIRED" : "MACHINE_OFFLINE", 409)+ } catch {+ return failure("model discovery unavailable", 503)+ }+}+++export async function discoverModels(req: NextRequest, ctx: DiscoveryContext & { kind: "human" | "bot" }) {+ const query = new URL(req.url).searchParams+ const id = ctx.params?.id as string+ const response = await discoverRuntimeModels(req, ctx, query.get("wait") === "1", (message, status) => ctx.kind === "human" ? writeError(message, status) : discoveryFailure(message, status, id))+ if (response instanceof Response) return response+ if (ctx.kind === "human") return writeJSON(response)+ return writeJSON({ ...projectModelOptions(id, { id: response.backendId, ...(response.result.catalog ? { reasoning: response.result.catalog } : {}) }, query.get("model")), source: response.source, observedAt: response.observedAt, requestId: response.requestId })+}diff --git a/src/web/src/lib/community/machine-options.server.ts b/src/web/src/lib/community/machine-options.server.tsindex 7c741e5f1..3edbe666f 100644--- a/src/web/src/lib/community/machine-options.server.ts+++ b/src/web/src/lib/community/machine-options.server.ts@@ -6,10 +6,17 @@ export async function readPlatformMachines(db: Database, ownerId: string, requesreturn { machines: machines.map((machine) => ({ id: machine.id, name: machine.displayName, status: machine.status, daemonVersion: machine.daemonVersion })), requesterMachineId }}-export function projectModelOptions(machineId: string, runtime: Pick<CommunityMachineRuntime, "id" | "reasoning">, model?: string | null) {+export function projectMachineBackends(runtimes: CommunityMachineRuntime[], options: { includeCatalogMetadata?: boolean } = {}) {+ return runtimes.map((runtime) => ({+ id: runtime.id, version: runtime.version, health: runtime.status, modelRequired: requiresExplicitModel(runtime.id),+ ...(options.includeCatalogMetadata === false ? {} : { catalogState: runtime.reasoning ? "reported" : "not_reported", catalogOrigin: runtime.reasoning?.catalogOrigin ?? "unknown" }),+ }))+}++export function projectModelOptions(machineId: string, runtime: Pick<CommunityMachineRuntime, "id" | "reasoning">, model?: string | null, options: { includeCatalogMetadata?: boolean } = {}) {const catalog: RuntimeReasoningCatalog | undefined = runtime.reasoningconst base = { machineId, backendId: runtime.id, source: "stored_report", readAt: new Date().toISOString(), observedAt: null,- catalogOrigin: catalog?.catalogOrigin ?? "unknown", catalogState: catalog ? "reported" : "not_reported", modelRequired: requiresExplicitModel(runtime.id) }+ ...(options.includeCatalogMetadata === false ? {} : { catalogOrigin: catalog?.catalogOrigin ?? "unknown", catalogState: catalog ? "reported" : "not_reported" }), modelRequired: requiresExplicitModel(runtime.id) }const present = (entry: NonNullable<RuntimeReasoningCatalog["models"]>[number]) => ({ id: entry.id, ...(entry.displayName ? { displayName: entry.displayName } : {}), reasoningEfforts: entry.supportedReasoningEfforts, defaultReasoningEffort: entry.defaultReasoningEffort ?? null })if (model != null) {const entry = catalog?.models.find((entry) => entry.id === model)diff --git a/src/web/src/lib/community/message-send.server.ts b/src/web/src/lib/community/message-send.server.tsnew file mode 100644index 000000000..4e24cca4a--- /dev/null+++ b/src/web/src/lib/community/message-send.server.ts@@ -0,0 +1,293 @@+import { NextResponse } from "next/server"+import { flattenError } from "zod"+import { queries, withD1Retry, CommunityAgentSendRequestSchema, utcDayKey, WS_EVENTS, PARTICIPANT_SOURCE, COMMUNITY_CONTRACT_HEADER, COMMUNITY_RESOURCE_CONTRACT_VERSION, CommunityMessagePostedSchema, type CommunityContract } from "@alook/shared"+import { getDb } from "@/lib/db"+import { mapPostedMessageForApi, readCommunityMessageProfiles } from "./message-payload"+import { checkRateLimit } from "@/lib/rate-limit"+import { createCommunityMessage, getCommunityMessageReplay } from "./message-handler"+import { createMessageWithThread } from "./create-channels"+import { resolveMessageTarget, type MessageTargetDescriptor } from "./message-door"+import { broadcastToUserSafe } from "./fanout"+import { isDuplicateBotMessage, DUPLICATE_MESSAGE_ERROR } from "./jev-send-dedup"++/**+ * Human/web arm — real channelId in the path (id descriptor). Rate-limit ++ * nonce + 201 shape preserved from the pre-fold channels POST; the raw body is+ * now schema-tightened via the door-core descriptor + createCommunityMessage's+ * own validation (the direction Ingaborg #196 flagged).+ */+export async function handleHumanSend(+ db: ReturnType<typeof getDb>,+ userId: string,+ env: Env,+ descriptor: MessageTargetDescriptor,+ raw: unknown,+ contract: CommunityContract,+): Promise<NextResponse> {+ const rateLimit = await checkRateLimit(env, "community:msgSend", userId)+ if (!rateLimit.allowed) {+ return NextResponse.json({ error: "rate limited" }, { status: 429, headers: { "Retry-After": String(rateLimit.retryAfterSec) } })+ }++ // SINGLE authorization entry — resolveMessageTarget's communication intent+ // subsumes member/DM friendship + returns the target (no standalone gate).+ const resolved = await resolveMessageTarget(db, userId, descriptor, "human", "communicate")+ if (!resolved.ok) return NextResponse.json({ error: resolved.error }, { status: resolved.status })++ const body = raw as { nonce?: unknown; attachments?: unknown }+ const clientNonce = typeof body?.nonce === "string" ? body.nonce : undefined+ const target = resolved.value.target++ const attachmentIds = Array.isArray(body.attachments)+ ? (body.attachments as unknown[]).filter((x): x is string => typeof x === "string")+ : []+ // A human send into a forum uses the same canonical message door and the+ // same opener+thread primitive as the bot arm. The body is sent separately+ // through this ordinary message door after the caller receives threadId.+ if (target.kind === "forum") {+ const forumBody = raw as { content?: unknown; mentionType?: unknown }+ const content = typeof forumBody.content === "string" ? forumBody.content : ""+ if (!content.trim()) return NextResponse.json({ error: "content is required" }, { status: 400 })+ const created = await createMessageWithThread({+ db,+ authorId: userId,+ authorKind: "human",+ parentChannelId: target.channelId,+ serverId: target.serverId,+ body: { content, mentionType: forumBody.mentionType },+ clientNonce,+ source: "web",+ })+ if (!created.ok) return NextResponse.json({ error: created.error }, { status: created.status })+ const response = humanMessageConfirmation(db, contract, target.channelId, {+ message: await mapPostedMessageForApi(db, target.channelId, { ...created.message, clientNonce }, contract),+ threadId: created.thread.id,+ deduped: created.deduped,+ }, created.deduped ? 200 : 201)+ return response+ }++ const replay = await getCommunityMessageReplay({+ db,+ authorId: userId,+ channelId: target.channelId,+ clientNonce,+ })+ if (replay) {+ return humanMessageConfirmation(db, contract, target.channelId, { message: await mapPostedMessageForApi(db, target.channelId, { ...replay.row, clientNonce }, contract), deduped: true }, 200)+ }++ const result = await createCommunityMessage({+ db,+ authorId: userId,+ authorKind: "human",+ target,+ body: raw as Record<string, unknown>,+ source: "web",+ clientNonce,+ attachmentIds: attachmentIds.length > 0 ? attachmentIds : undefined,+ })+ if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })+ const response = humanMessageConfirmation(db, contract, target.channelId, { message: await mapPostedMessageForApi(db, target.channelId, { ...result.row, clientNonce }, contract), deduped: result.deduped }, 201)+ return response+}++async function humanMessageConfirmation(db: ReturnType<typeof getDb>, contract: CommunityContract, channelId: string, payload: { message: unknown; deduped?: boolean; threadId?: string }, status: number): Promise<NextResponse> {+ const message = CommunityMessagePostedSchema.shape.message.parse(payload.message)+ const profiles = await readCommunityMessageProfiles(db, [message])+ return NextResponse.json(CommunityMessagePostedSchema.parse({ contractVersion: contract, channelId, ...payload, profiles, deduped: payload.deduped === true }), {+ status, headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_RESOURCE_CONTRACT_VERSION) },+ })+}++/**+ * Bot arm — ref-in-body (`channel`), the former `send` verb's behavior verbatim:+ * single resolve WITH create-if-missing, channel-alignment gate, CAS via+ * `expectedSeq`, SENT-heatmap bump, agent-message response. Target resolution ++ * per-surface auth flow through the shared door-core (single mask entry).+ */+export async function handleBotSend(+ db: ReturnType<typeof getDb>,+ botUserId: string,+ env: RuntimeEnv,+ raw: unknown,+): Promise<NextResponse> {+ const parsed = CommunityAgentSendRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload", details: flattenError(parsed.error) }, { status: 400 })+ }+ const body = parsed.data++ const descriptor: MessageTargetDescriptor = {+ ref: body.channel,+ createDmIfMissing: true,+ createThreadIfMissing: true,+ }+ const resolved = await resolveMessageTarget(db, botUserId, descriptor, "bot", "communicate")+ if (!resolved.ok) {+ return NextResponse.json(+ { error: resolved.error, ...(resolved.hint ? { hint: resolved.hint } : {}) },+ { status: resolved.status },+ )+ }+ const target = resolved.value.target+ const channelId = target.channelId+ const createForumOpener = (serverId: string, expectedSeq?: number) =>+ createMessageWithThread({+ db,+ authorId: botUserId,+ authorKind: "bot",+ parentChannelId: channelId,+ serverId,+ body: { content: body.content.text },+ clientNonce: body.nonce,+ ...(expectedSeq !== undefined ? { expectedSeq } : {}),+ source: "cli",+ extraStatements: [+ queries.communityBot.bumpBotDailyActivityStatement(db, botUserId, utcDayKey(new Date()), "sent"),+ ],+ })++ const replayResponse = async () => {+ const replay = await getCommunityMessageReplay({+ db,+ authorId: botUserId,+ channelId,+ clientNonce: body.nonce,+ })+ if (!replay) return null+ if (target.kind === "forum") {+ const created = await createForumOpener(target.serverId)+ if (!created.ok) return NextResponse.json({ error: created.error }, { status: created.status })+ const message = await queries.communityAgentInbox.toAgentMessage(db, created.message, botUserId)+ return NextResponse.json({+ state: "sent",+ message,+ threadId: created.thread.id,+ deduped: created.deduped,+ })+ }+ const orderedAttachments = replay.attachments.map((a) => ({ id: a.id, filename: a.filename, contentType: a.contentType, size: a.size }))+ const message = await queries.communityAgentInbox.toAgentMessage(db, replay.row, botUserId, orderedAttachments)+ return NextResponse.json({ state: "sent", message, deduped: true })+ }+ const replay = await replayResponse()+ if (replay) return replay++ if (target.kind === "thread") {+ const created = await withD1Retry(+ () => queries.communityThread.addThreadParticipant(db, {+ threadChannelId: channelId,+ userId: botUserId,+ source: PARTICIPANT_SOURCE.ADDED,+ }),+ { route: "community/messages:thread-auto-join" },+ )+ if (created) {+ const event = {+ type: WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE,+ relation: "notify",+ present: true,+ serverId: target.serverId,+ channelId,+ userId: botUserId,+ } as const+ const recipients = await queries.communityThread.listThreadParticipantUserIds(db, channelId)+ await Promise.all(+ [...new Set(recipients)].map((userId) => broadcastToUserSafe(userId, event)),+ )+ }+ }++ const scopeTarget = { channelId }+ const [latestSeq, readState] = await Promise.all([+ withD1Retry(() => queries.communityAgentInbox.getLatestSeqForScope(db, channelId), { route: "community/messages:latest-seq" }),+ withD1Retry(() => queries.communityReadState.getReadState(db, { userId: botUserId, ...scopeTarget }), { route: "community/messages:read-state" }),+ ])+ const seen = body.seenUpToSeq ?? readState?.lastReadSeq ?? 0+ const hasUnread = await withD1Retry(+ () => queries.communityAgentInbox.hasDeliverableUnreadForAgentScope(db, botUserId, channelId, seen),+ { route: "community/messages:has-unread" },+ )+ if (hasUnread) {+ const replay = await replayResponse()+ if (replay) return replay+ return NextResponse.json({ state: "blocked", reason: "unaligned", unreadCount: Math.max(0, latestSeq - seen), latestSeq })+ }++ if (!body.force && target.kind !== "dm" && await isDuplicateBotMessage({+ db, env, channelId, authorId: botUserId,+ content: body.content.text,+ })) {+ const replay = await replayResponse()+ if (replay) return replay+ return NextResponse.json({ error: DUPLICATE_MESSAGE_ERROR, code: "duplicate_message" }, { status: 422 })+ }++ if (target.kind === "forum") {+ const created = await createForumOpener(target.serverId, latestSeq)+ if (!created.ok) {+ if (created.status === 409) {+ const freshLatestSeq = await withD1Retry(+ () => queries.communityAgentInbox.getLatestSeqForScope(db, channelId),+ { route: "community/messages:forum-fresh-latest-seq" },+ )+ return NextResponse.json({+ state: "blocked",+ reason: "unaligned",+ unreadCount: Math.max(0, freshLatestSeq - seen),+ latestSeq: freshLatestSeq,+ })+ }+ return NextResponse.json({ error: created.error }, { status: created.status })+ }+ const message = await queries.communityAgentInbox.toAgentMessage(db, created.message, botUserId)+ return NextResponse.json({+ state: "sent",+ message,+ threadId: created.thread.id,+ deduped: created.deduped,+ })+ }++ let replyToId: string | undefined+ if (body.replyToSeq !== undefined) {+ const replyTarget = await withD1Retry(+ () => queries.communityMessage.getMessageByChannelAndSeq(db, scopeTarget, body.replyToSeq!),+ { route: "community/messages:reply-lookup" },+ )+ if (!replyTarget) {+ return NextResponse.json({ error: `reply target #${body.replyToSeq} not found in ${body.channel}` }, { status: 400 })+ }+ replyToId = replyTarget.id+ }++ const result = await createCommunityMessage({+ db,+ authorId: botUserId,+ authorKind: "bot",+ target,+ body: { content: body.content.text, replyToId },+ source: "cli",+ expectedSeq: latestSeq,+ attachmentIds: body.attachments.length > 0 ? body.attachments : undefined,+ clientNonce: body.nonce,+ extraStatements: [+ queries.communityBot.bumpBotDailyActivityStatement(db, botUserId, utcDayKey(new Date()), "sent"),+ ],+ })+ if (!result.ok) {+ if (result.status === 409) {+ const freshLatestSeq = await withD1Retry(+ () => queries.communityAgentInbox.getLatestSeqForScope(db, channelId),+ { route: "community/messages:fresh-latest-seq" },+ )+ return NextResponse.json({ state: "blocked", reason: "unaligned", unreadCount: Math.max(0, freshLatestSeq - seen), latestSeq: freshLatestSeq })+ }+ return NextResponse.json({ error: result.error }, { status: result.status })+ }++ const orderedAttachments = (result.attachments ?? []).map((a) => ({ id: a.id, filename: a.filename, contentType: a.contentType, size: a.size }))+ const message = await queries.communityAgentInbox.toAgentMessage(db, result.row, botUserId, orderedAttachments)+ return NextResponse.json({ state: "sent", message, deduped: result.deduped })+}diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 822d7a000..c8190851e 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -52,6 +52,13 @@ export const tid = {settingsClose: "community-settings-close",settingsLabel: "community-settings-label",settingsWebVersion: "community-settings-web-version",+ automationPanel: "community-automation-panel",+ automationCreate: "community-automation-create",+ automationName: "community-automation-name",+ automationExpiry: "community-automation-expiry",+ automationSave: "community-automation-save",+ automationSecret: "community-automation-secret",+ automationCode: (id: string) => `community-automation-code-${id}`,settingsCacheSize: "community-settings-cache-size",analyticsConsentBanner: "analytics-consent-banner",ahrefsAnalyticsFrame: "ahrefs-analytics-frame",diff --git a/src/web/src/lib/observability/actions.ts b/src/web/src/lib/observability/actions.tsindex 82d3a2269..b5183b39d 100644--- a/src/web/src/lib/observability/actions.ts+++ b/src/web/src/lib/observability/actions.ts@@ -1,4 +1,5 @@export const actionVariants = {+ "automation.access_code.command": { create: "automation.access_code.create", update: "automation.access_code.update", delete: "automation.access_code.delete" },"friend.command": { "send": "friend.request.send", "accept": "friend.request.accept", "reject": "friend.request.reject", "remove": "friend.remove", "cancel": "friend.request.cancel", "owner-decision": "friend.owner_decision.command", "block": "user.block", "unblock": "user.unblock" },"friend.owner_decision.command": { "approve": "friend.request.approve", "deny": "friend.request.deny" },"member.management.command": { "kick": "server.member.kick", "leave": "channel.member.leave", "remove": "channel.member.remove" },diff --git a/src/web/src/lib/observability/coverage.test.ts b/src/web/src/lib/observability/coverage.test.tsindex 92b72f790..53fd3b6e3 100644--- a/src/web/src/lib/observability/coverage.test.ts+++ b/src/web/src/lib/observability/coverage.test.ts@@ -43,6 +43,7 @@ it("keeps existing mutation owners inventoried and semantic variants on the whit})const mutationCoverage = [+ { file: "src/web/src/hooks/community/use-automation.ts", owner: "useAutomation", action: "automation.access_code.command" },{ "file": "src/web/src/hooks/community/use-bot-memberships.ts", "owner": "useBotMemberships", "action": "community.command" },{ "file": "src/web/src/hooks/community/mutations/bot-creation.ts", "owner": "useBotCreationDecision", "action": "bot.creation.decision" },{diff --git a/src/web/src/lib/observability/coverage.ts b/src/web/src/lib/observability/coverage.tsindex 3688cb10a..194a7ceb9 100644--- a/src/web/src/lib/observability/coverage.ts+++ b/src/web/src/lib/observability/coverage.ts@@ -43,6 +43,16 @@ export const apiRoutes = ["/api/community/billing/cancel-change","/api/community/billing/checkout","/api/community/billing/portal",+ "/api/community/automation/bots",+ "/api/community/automation/servers",+ "/api/community/automation/machines",+ "/api/community/automation/friends",+ "/api/community/automation/servers/[id]/invites",+ "/api/community/automation/machines/[id]/discover-models",+ "/api/community/automation/messages",+ "/api/community/automation/access-codes",+ "/api/community/automation/access-codes/[codeId]",+ "/api/community/automation/expire","/api/community/bots","/api/community/bots/[id]","/api/community/bots/[id]/active",@@ -183,6 +193,10 @@ export const actionNames = ["auth_send_code","auth_social","auth_verify_code",+ "automation.access_code.command",+ "automation.access_code.create",+ "automation.access_code.update",+ "automation.access_code.delete","billing.change.cancel","billing.checkout.start","billing.portal.open",diff --git a/src/web/src/test/architecture/community-read-state-writer-contract.test.ts b/src/web/src/test/architecture/community-read-state-writer-contract.test.tsindex 256157f23..82038470f 100644--- a/src/web/src/test/architecture/community-read-state-writer-contract.test.ts+++ b/src/web/src/test/architecture/community-read-state-writer-contract.test.ts@@ -142,8 +142,11 @@ describe("human account read-state writer contract", () => {it("makes every production message door state the author kind explicitly", () => {const route = source("src/web/src/app/api/community/channels/[id]/messages/route.ts")- expect(route.match(/authorKind: "human"/g)).toHaveLength(2)- expect(route.match(/authorKind: "bot"/g)).toHaveLength(2)+ expect(route).toContain("return handleBotSend(db, ctx.actor.userId, ctx.env, raw)")+ expect(route).toContain("return handleHumanSend(db, ctx.actor.userId, ctx.env, { id: pathId }, raw,")+ const sender = source("src/web/src/lib/community/message-send.server.ts")+ expect(sender.match(/authorKind: "human"/g)).toHaveLength(2)+ expect(sender.match(/authorKind: "bot"/g)).toHaveLength(2)const friendship = source("src/shared/src/db/queries/community/friendship.ts")expect(friendship.match(/authorKind: "bot"/g)).toHaveLength(2)diff --git a/src/web/src/test/e2e-ui/23-message-selection-context-menu.spec.ts b/src/web/src/test/e2e-ui/23-message-selection-context-menu.spec.tsindex 349a8afb3..69d50dca4 100644--- a/src/web/src/test/e2e-ui/23-message-selection-context-menu.spec.ts+++ b/src/web/src/test/e2e-ui/23-message-selection-context-menu.spec.ts@@ -1,5 +1,5 @@import { test, expect } from "./_fixtures/case-fixture"-import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"import { tid } from "./_fixtures/testids"@@ -47,6 +47,7 @@ test("message context menu preserves and copies selected text", async ({ caseActawait expect(messageBody).toContainText(body)await row.hover()+ const contextMenu = page.locator('[data-slot="context-menu-content"]')const openContextMenu = page.locator('[data-slot="context-menu-content"][data-open]')const trigger = row.locator('[data-slot="context-menu-trigger"]')await expect(trigger).toHaveCount(1)@@ -85,7 +86,17 @@ test("message context menu preserves and copies selected text", async ({ caseAct.toBe("copy only this phrase")await page.keyboard.press("Escape")- await expect(openContextMenu).toHaveCount(0)+ await expect(contextMenu).toHaveCount(0)+ await expect(trigger).toBeFocused()+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString()))+ .toBe("copy only this phrase")+ await page.keyboard.press("Shift+F10")+ await expect(openContextMenu).toBeVisible()+ await page.keyboard.press("Escape")+ await expect(contextMenu).toHaveCount(0)+ await expect(trigger).toBeFocused()+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString()))+ .toBe("copy only this phrase")await observeNextContextMenu(page)await page.mouse.click(points.outsideSelection.x, points.outsideSelection.y, { button: "right" })@@ -95,18 +106,17 @@ test("message context menu preserves and copies selected text", async ({ caseAct.toBe("copy only this phrase")await openContextMenu.getByRole("menuitem", { name: "Copy Text", exact: true }).click()await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("copy only this phrase")- await expect(openContextMenu).toHaveCount(0)+ await expect(contextMenu).toHaveCount(0)await page.evaluate(() => window.getSelection()?.removeAllRanges())await page.mouse.click(points.selection.x, points.selection.y, { button: "right" })await expect(openContextMenu).toBeVisible()await openContextMenu.getByRole("menuitem", { name: "Copy Text", exact: true }).click()await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(body)- await expect(openContextMenu).toHaveCount(0)+ await expect(contextMenu).toHaveCount(0)await page.evaluate(() => navigator.clipboard.writeText("keyboard-copy-sentinel"))await trigger.evaluate((element) => {- element.setAttribute("tabindex", "0")element.focus()})await page.keyboard.press("Shift+F10")@@ -114,5 +124,30 @@ test("message context menu preserves and copies selected text", async ({ caseActawait openContextMenu.getByRole("menuitem", { name: "Copy Text", exact: true }).focus()await page.keyboard.press("Enter")await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(body)- await expect(openContextMenu).toHaveCount(0)+ await expect(contextMenu).toHaveCount(0)+ await expect.poll(() => trigger.evaluate((element) => element.contains(document.activeElement))).toBe(true)+ await page.keyboard.press("Shift+F10")+ await expect(openContextMenu).toBeVisible()+ await page.keyboard.press("Escape")+ await expect(contextMenu).toHaveCount(0)+ await expect.poll(() => trigger.evaluate((element) => element.contains(document.activeElement))).toBe(true)++ await page.mouse.click(points.selection.x, points.selection.y, { button: "right" })+ await expect(openContextMenu).toBeVisible()+ const editor = composerEditable(page)+ const editorBox = await editor.boundingBox()+ if (!editorBox) throw new Error("composer has no visible bounds")+ await page.mouse.click(editorBox.x + editorBox.width / 2, editorBox.y + editorBox.height / 2)+ const focusDuringExit = await editor.evaluate((element) => {+ const popup = document.querySelector('[data-slot="context-menu-content"]')+ ;(element as HTMLElement).focus()+ return {+ popupMounted: popup?.isConnected === true,+ popupClosing: popup?.hasAttribute("data-closed") === true,+ editorFocused: document.activeElement === element,+ }+ })+ expect(focusDuringExit).toEqual({ popupMounted: true, popupClosing: true, editorFocused: true })+ await expect(contextMenu).toHaveCount(0)+ await expect(editor).toBeFocused()})diff --git a/src/web/src/test/e2e-ui/68-bot-memberships.spec.ts b/src/web/src/test/e2e-ui/68-bot-memberships.spec.tsindex adf503e7b..4403cdc09 100644--- a/src/web/src/test/e2e-ui/68-bot-memberships.spec.ts+++ b/src/web/src/test/e2e-ui/68-bot-memberships.spec.ts@@ -203,7 +203,10 @@ test("owned bot exits preserve other identities, child participation boundariesexpect((await history.json() as {messages:Array<{id:string}>}).messages.some(m=>m.id===release.messageId)).toBe(true)await page.getByTestId(tid.botMembershipsLeave(studio.id)).click()await confirm.click()- await expect(sheet.getByText("No servers yet",{exact:true})).toBeVisible()+ await expect(sheet.getByText(`${first.name} hasn't joined any servers.`,{exact:true})).toBeVisible()+ const emptyMemberships = await call("/api/community/servers/channels","GET",undefined,actorHeader)+ expect(emptyMemberships.status).toBe(200)+ expect(await emptyMemberships.json()).toMatchObject({servers:[],groups:[]})await page.keyboard.press("Escape")await expect(sheet).toHaveCount(0)await expect(trigger).toBeFocused()diff --git a/src/ws-do/src/rate-limit-do.ts b/src/ws-do/src/rate-limit-do.tsindex 3e856bc5a..39e843498 100644--- a/src/ws-do/src/rate-limit-do.ts+++ b/src/ws-do/src/rate-limit-do.ts@@ -39,6 +39,16 @@ export class RateLimitDurableObject extends DurableObject<Env> {async fetch(request: Request): Promise<Response> {const url = new URL(request.url)+ if (url.pathname === "/check-automation" && request.method === "POST") {+ let body: unknown+ try { body = await request.json() } catch { return new Response("invalid json", { status: 400 }) }+ const { max, period } = (body ?? {}) as { max?: unknown; period?: unknown }+ if ((period !== "hour" && period !== "day") || typeof max !== "number" || !Number.isInteger(max) || max < 1 || max > (period === "hour" ? 64 : 1536)) {+ return new Response("invalid automation policy", { status: 400 })+ }+ return Response.json(await this.checkAutomation(max, period))+ }+if (url.pathname === "/check" && request.method === "POST") {let body: unknowntry {@@ -59,6 +69,24 @@ export class RateLimitDurableObject extends DurableObject<Env> {return new Response("not found", { status: 404 })}+ private async checkAutomation(max: number, period: "hour" | "day"): Promise<RateLimitResult> {+ return this.ctx.storage.transaction(async (transaction) => {+ const now = Date.now()+ const hour = 3_600_000+ const timestamps = (await transaction.get<number[]>("automation")) ?? []+ const day = timestamps.filter((time) => time > now - 24 * hour)+ const recentHour = day.filter((time) => time > now - hour)+ const configured = period === "hour" ? recentHour : day+ let retryMs = 0+ if (recentHour.length >= 64) retryMs = recentHour[recentHour.length - 64]! + hour - now+ if (configured.length >= max) retryMs = Math.max(retryMs, configured[configured.length - max]! + (period === "hour" ? hour : 24 * hour) - now)+ if (retryMs > 0) return { allowed: false, retryAfterSec: Math.max(1, Math.ceil(retryMs / 1000)) }+ day.push(now)+ await transaction.put("automation", day)+ return { allowed: true }+ })+ }+private async check(windowMs: number, max: number): Promise<RateLimitResult> {const now = Date.now()const state = (await this.ctx.storage.get<WindowState>(STATE_KEY)) ?? nulldiff --git a/src/ws-do/src/routes/community-machine-models.test.ts b/src/ws-do/src/routes/community-machine-models.test.tsindex f09772073..8fffc3c5e 100644--- a/src/ws-do/src/routes/community-machine-models.test.ts+++ b/src/ws-do/src/routes/community-machine-models.test.ts@@ -33,3 +33,31 @@ describe("model discovery worker routing", () => {expect((await (await loadRouter()).fetch(request(), env as any)).status).toBe(503)})})++it("forwards the wait mode and returns only the selected credential's terminal discovery result", async () => {+ const { env, doMock } = createRouterTestContext()+ mocks.getActiveDoNamesForMachine.mockResolvedValue(["old", "current", "other"])+ const result = { status: "complete", catalog: null }+ doMock.stubFetch.mockResolvedValueOnce(Response.json({ sent: 0, unsupported: 0 })).mockResolvedValueOnce(Response.json({ sent: 1, unsupported: 0, observedAt: "2026-10-29T00:00:00Z", result }))+ const response = await (await loadRouter()).fetch(new Request("http://localhost/community-machine/by-id/machine/discover-models?wait=1", { method: "POST", body: JSON.stringify({ requestId: "fresh", runtimeId: "codex" }) }), env as any)+ expect(await response.json()).toEqual({ sent: 1, unsupported: 0, cached: false, observedAt: "2026-10-29T00:00:00Z", result })+ expect(doMock.stubFetch).toHaveBeenCalledTimes(2)+ expect((doMock.stubFetch.mock.calls[1][0] as Request).url).toBe("http://internal/discover-models?wait=1")+})+it("rejects a wait receipt without a terminal result", async () => {+ const { env, doMock } = createRouterTestContext()+ mocks.getActiveDoNamesForMachine.mockResolvedValue(["current"])+ doMock.stubFetch.mockResolvedValue(Response.json({ sent: 1, unsupported: 0 }))+ const response = await (await loadRouter()).fetch(new Request("http://localhost/community-machine/by-id/machine/discover-models?wait=1", { method: "POST", body: JSON.stringify({ requestId: "fresh", runtimeId: "codex" }) }), env as any)+ expect(response.status).toBe(503)+})++it("preserves a cache hit with zero dispatches and forwards the cache flag", async () => {+ const { env, doMock } = createRouterTestContext()+ mocks.getActiveDoNamesForMachine.mockResolvedValue(["current"])+ const receipt = { sent: 0, unsupported: 0, cached: true, observedAt: "2026-10-29T00:00:00Z", catalogFingerprint: "a".repeat(64) }+ doMock.stubFetch.mockResolvedValue(Response.json(receipt))+ const response = await (await loadRouter()).fetch(new Request("http://localhost/community-machine/by-id/machine/discover-models?wait=1&cache=1", { method: "POST", headers: { "x-model-catalog-fingerprint": "a".repeat(64) }, body: JSON.stringify({ requestId: "cache", runtimeId: "codex" }) }), env as any)+ expect(await response.json()).toEqual(receipt)+ expect((doMock.stubFetch.mock.calls[0][0] as Request).url).toBe("http://internal/discover-models?wait=1&cache=1")+})diff --git a/src/ws-do/src/routes/community-machine-models.ts b/src/ws-do/src/routes/community-machine-models.tsindex 57305d62a..c91e7213f 100644--- a/src/ws-do/src/routes/community-machine-models.ts+++ b/src/ws-do/src/routes/community-machine-models.ts@@ -1,4 +1,4 @@-import { createDb, queries, RuntimeModelDiscoveryRequestSchema } from "@alook/shared"+import { createDb, queries, RuntimeModelDiscoveryRequestSchema, RuntimeModelDiscoveryResultSchema, RUNTIME_MODEL_CATALOG_FINGERPRINT_HEADER } from "@alook/shared"import { readBoundedJsonRequest } from "../community-browser-event-ingress"import type { RouterContext } from "../router-context"@@ -11,19 +11,30 @@ export async function handleMachineModels({ request, env, url }: RouterContext):try {const machineId = decodeURIComponent(match[1])const doNames = await queries.communityMachine.getActiveDoNamesForMachine(createDb(env.DB), machineId)+ const wait = url.searchParams.get("wait") === "1"+ const catalogFingerprint = request.headers.get(RUNTIME_MODEL_CATALOG_FINGERPRINT_HEADER)let sent = 0let unsupported = 0for (const name of doNames) {const stub = env.WS_DO.get(env.WS_DO.idFromName("community-machine:" + name))- const response = await stub.fetch(new Request("http://internal/discover-models", {+ const response = await stub.fetch(new Request(`http://internal/discover-models${wait ? `?wait=1${url.searchParams.get("cache") === "1" ? "&cache=1" : ""}` : ""}`, {method: "POST",- headers: { "content-type": "application/json" },+ headers: { "content-type": "application/json", ...(catalogFingerprint ? { [RUNTIME_MODEL_CATALOG_FINGERPRINT_HEADER]: catalogFingerprint } : {}) },body: JSON.stringify({ type: "runtime:discover_models", ...payload.data }),}))if (!response.ok) throw new Error("dispatch failed")- const receipt = await response.json() as { sent?: unknown; unsupported?: unknown }+ const receipt = await response.json() as { sent?: unknown; unsupported?: unknown; result?: unknown; cached?: unknown; observedAt?: unknown; catalogFingerprint?: unknown }if (!Number.isSafeInteger(receipt.sent) || (receipt.sent as number) < 0|| !Number.isSafeInteger(receipt.unsupported) || (receipt.unsupported as number) < 0) throw new Error("invalid receipt")+ if (wait && ((receipt.sent as number) > 0 || receipt.cached === true)) {+ if (receipt.cached === true) {+ if (!catalogFingerprint || receipt.catalogFingerprint !== catalogFingerprint || typeof receipt.observedAt !== "string" || !Number.isFinite(Date.parse(receipt.observedAt))) throw new Error("invalid cached report")+ return Response.json({ sent: 0, unsupported: 0, cached: true, observedAt: receipt.observedAt, catalogFingerprint })+ }+ const result = RuntimeModelDiscoveryResultSchema.safeParse(receipt.result)+ if (!result.success || (result.data.status === "complete" && (typeof receipt.observedAt !== "string" || !Number.isFinite(Date.parse(receipt.observedAt)))) || (receipt.cached === true && result.data.status !== "complete")) throw new Error("invalid discovery result")+ return Response.json({ sent: receipt.sent, unsupported: receipt.unsupported, result: result.data, cached: receipt.cached === true, observedAt: receipt.observedAt })+ }sent += receipt.sent as numberunsupported += receipt.unsupported as number}diff --git a/src/ws-do/src/routes/rate-limit.test.ts b/src/ws-do/src/routes/rate-limit.test.tsindex 77e5ecddb..d1968aa68 100644--- a/src/ws-do/src/routes/rate-limit.test.ts+++ b/src/ws-do/src/routes/rate-limit.test.ts@@ -1,4 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { handleRateLimit } from "./rate-limit"import {createRouterTestContext,loadRouter,@@ -101,3 +102,18 @@ describe("ws-do router", () => {})})})+++it("leaves unrelated paths and non-POST requests for the router", async () => {+ for (const [pathname, method] of [["/rate-limit/automation", "GET"], ["/rate-limit/check", "GET"], ["/unrelated", "POST"]]) {+ const req = new Request(`http://localhost${pathname}`, { method })+ expect(await handleRateLimit(req, {} as Env, new URL(req.url))).toBeNull()+ }+})++it("rejects a null automation policy before selecting a Durable Object", async () => {+ const req = new Request("http://localhost/rate-limit/automation", { method: "POST", body: "null" })+ const response = await handleRateLimit(req, {} as Env, new URL(req.url))+ expect(response?.status).toBe(400)+ expect(await response?.text()).toBe("name required")+})diff --git a/src/ws-do/src/routes/rate-limit.ts b/src/ws-do/src/routes/rate-limit.tsindex def287f00..83144776e 100644--- a/src/ws-do/src/routes/rate-limit.ts+++ b/src/ws-do/src/routes/rate-limit.ts@@ -11,7 +11,8 @@ export async function handleRateLimit(// so ceilings live in one place, not scattered across route handlers.//// See `rate-limit-do.ts` for the counter logic.- if (url.pathname !== "/rate-limit/check" || request.method !== "POST") return null+ const automation = url.pathname === "/rate-limit/automation"+ if ((!automation && url.pathname !== "/rate-limit/check") || request.method !== "POST") return nulllet body: unknowntry {@@ -19,11 +20,12 @@ export async function handleRateLimit(} catch {return new Response("invalid json", { status: 400 })}- const { name, key, windowMs, max } = (body ?? {}) as {+ const { name, key, windowMs, max, period } = (body ?? {}) as {name?: unknownkey?: unknownwindowMs?: unknownmax?: unknown+ period?: unknown}if (typeof name !== "string" || name.length === 0) {return new Response("name required", { status: 400 })@@ -31,13 +33,13 @@ export async function handleRateLimit(if (typeof key !== "string" || key.length === 0) {return new Response("key required", { status: 400 })}- const doId = env.RATE_LIMIT_DO.idFromName(name + ":" + key)+ const doId = env.RATE_LIMIT_DO.idFromName((automation ? "automation:" : "") + name + ":" + key)const stub = env.RATE_LIMIT_DO.get(doId)return stub.fetch(- new Request("http://internal/check", {+ new Request(automation ? "http://internal/check-automation" : "http://internal/check", {method: "POST",headers: { "content-type": "application/json" },- body: JSON.stringify({ windowMs, max }),+ body: JSON.stringify(automation ? { period, max } : { windowMs, max }),}),)}diff --git a/src/ws-do/src/ws-durable/machine-control.test.ts b/src/ws-do/src/ws-durable/machine-control.test.tsindex b5c641db0..735e5b808 100644--- a/src/ws-do/src/ws-durable/machine-control.test.ts+++ b/src/ws-do/src/ws-durable/machine-control.test.ts@@ -551,6 +551,33 @@ describe("on-demand model discovery dispatch", () => {expect(sockets[1].send).not.toHaveBeenCalled()expect(sockets[2].send).not.toHaveBeenCalled()})+ it("returns a fingerprint-matched cached wait result without dispatching to a daemon", async () => {+ const { durable, store, getWebSockets, storage } = createDO()+ const socket = createMockWebSocket()+ socket.serializeAttachment({ type: "community-machine", authenticated: true, machineId: "machine", userId: "owner", modelDiscovery: true })+ getWebSockets.mockReturnValue([socket])+ const observedAt = Date.now()+ const catalogFingerprint = "a".repeat(64)+ store.set("model-discovery-cache:codex", { observedAt, catalogFingerprint })+ const response = await durable.fetch(new Request("http://internal/discover-models?wait=1&cache=1", { method: "POST", headers: { "x-model-catalog-fingerprint": catalogFingerprint }, body: JSON.stringify({ type: "runtime:discover_models", runtimeId: "codex", requestId: "request" }) }))+ expect(response.status).toBe(200)+ expect(await response.json()).toEqual({ sent: 0, unsupported: 0, cached: true, observedAt: new Date(observedAt).toISOString(), catalogFingerprint })+ expect(socket.send).not.toHaveBeenCalled()+ expect(storage.put).not.toHaveBeenCalled()+ })+ it("returns an unavailable wait response on pending overload without sending or leaking storage details", async () => {+ const { durable, getWebSockets, storage } = createDO()+ const socket = createMockWebSocket()+ socket.serializeAttachment({ type: "community-machine", authenticated: true, machineId: "machine", userId: "owner", modelDiscovery: true })+ getWebSockets.mockReturnValue([socket])+ const entries = new Map(Array.from({ length: 16 }, (_, i) => [`model-discovery-wait:${i}`, { runtimeId: "codex", expiresAt: Date.now() + 45_000 }]))+ Object.assign(storage, { transaction: async (run: (txn: { list: () => Promise<typeof entries> }) => Promise<unknown>) => run({ list: async () => entries }) })+ const response = await durable.fetch(new Request("http://internal/discover-models?wait=1", { method: "POST", body: JSON.stringify({ type: "runtime:discover_models", runtimeId: "codex", requestId: "request" }) }))+ expect(response.status).toBe(503)+ expect(await response.json()).toEqual({ error: "model discovery unavailable" })+ expect(socket.send).not.toHaveBeenCalled()+ expect(storage.put).not.toHaveBeenCalled()+ })it("rejects extra command fields without socket delivery", async () => {const { durable, getWebSockets } = createDO()const socket = createMockWebSocket()diff --git a/src/ws-do/src/ws-durable/machine-control.ts b/src/ws-do/src/ws-durable/machine-control.tsindex 64e2a1b90..a964c794e 100644--- a/src/ws-do/src/ws-durable/machine-control.ts+++ b/src/ws-do/src/ws-durable/machine-control.ts@@ -1,5 +1,6 @@+import { waitForModelDiscovery } from "./model-discovery-wait"import { readBoundedJsonRequest } from "../community-browser-event-ingress"-import { createDb, PII_REQUEST_MAX_BYTES, PiiCommandSchema, DiagnosticCollectCommandSchema, RuntimeModelDiscoveryCommandSchema, queries } from "@alook/shared"+import { createDb, PII_REQUEST_MAX_BYTES, PiiCommandSchema, DiagnosticCollectCommandSchema, RuntimeModelDiscoveryCommandSchema, RUNTIME_MODEL_CATALOG_FINGERPRINT_HEADER, queries } from "@alook/shared"import {HANDLE_KEY,IDENTITY_KEY,@@ -38,8 +39,12 @@ export async function handleMachineControlFetch(const input = await readBoundedJsonRequest(request, 4096)const command = RuntimeModelDiscoveryCommandSchema.safeParse(input.ok ? input.value : null)if (!command.success) return new Response(JSON.stringify({ error: "invalid request" }), { status: 400, headers: { "Content-Type": "application/json" } })- const { sent, unsupported } = forwardToCommunityMachine(context, JSON.stringify(command.data), "modelDiscovery")- return new Response(JSON.stringify({ sent, unsupported }), { headers: { "Content-Type": "application/json" } })+ const dispatch = () => forwardToCommunityMachine(context, JSON.stringify(command.data), "modelDiscovery")+ if (url.searchParams.get("wait") === "1") {+ try { return Response.json(await waitForModelDiscovery(context, command.data, dispatch, { useCache: url.searchParams.get("cache") === "1", catalogFingerprint: request.headers.get(RUNTIME_MODEL_CATALOG_FINGERPRINT_HEADER) ?? undefined })) }+ catch { return Response.json({ error: "model discovery unavailable" }, { status: 503 }) }+ }+ return new Response(JSON.stringify(dispatch()), { headers: { "Content-Type": "application/json" } })}if (url.pathname === "/pii" && request.method === "POST") {diff --git a/src/ws-do/src/ws-durable/machine-models.ts b/src/ws-do/src/ws-durable/machine-models.tsindex 72381fb2c..1b4b32e78 100644--- a/src/ws-do/src/ws-durable/machine-models.ts+++ b/src/ws-do/src/ws-durable/machine-models.ts@@ -1,5 +1,6 @@import { createDb, HostRuntimeModelsFrameSchema, queries, WS_EVENTS, type RuntimeModelDiscoveryResult } from "@alook/shared"import type { CommunityMachineIdentity, WsDurableContext } from "./internal"+import { completeModelDiscoveryWait } from "./model-discovery-wait"import { notifyUserDO } from "./presence-typing"export async function handleRuntimeModelsFrame(@@ -30,6 +31,7 @@ export async function handleRuntimeModelsFrame(context.log.warn("runtime model discovery persistence failed", { machineId: identity.machineId, runtimeId: frame.runtimeId })result = { status: "error", code: "model_discovery_failed", message: "Could not save the discovered models" }}+ await completeModelDiscoveryWait(context, frame.requestId, frame.runtimeId, result)await notifyUserDO(context, identity.userId, {type: WS_EVENTS.RUNTIME_MODELS,machineId: identity.machineId,diff --git a/src/ws-do/src/ws-durable/model-discovery-wait.test.ts b/src/ws-do/src/ws-durable/model-discovery-wait.test.tsnew file mode 100644index 000000000..edbf4522e--- /dev/null+++ b/src/ws-do/src/ws-durable/model-discovery-wait.test.ts@@ -0,0 +1,196 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest"+import { fingerprintRuntimeModelCatalog } from "@alook/shared"+import { waitForModelDiscovery, completeModelDiscoveryWait } from "./model-discovery-wait"+const command = { requestId: "request", runtimeId: "codex" }+const result = { status: "complete" as const, catalog: { updateMode: "unsupported" as const, models: [{ id: "fresh-model", supportedReasoningEfforts: [] }] } }+function fixture() {+ const store = new Map<string, any>()+ let queue = Promise.resolve()+ const methods = (target: Map<string, any>) => ({+ get: async (key: string) => target.get(key),+ put: async (key: string | Record<string, unknown>, value?: unknown) => { if (typeof key === "string") target.set(key, value); else for (const [name, entry] of Object.entries(key)) target.set(name, entry) },+ delete: async (keys: string | string[]) => { for (const key of Array.isArray(keys) ? keys : [keys]) target.delete(key) },+ list: async ({ prefix }: { prefix: string }) => new Map([...target].filter(([key]) => key.startsWith(prefix))),+ })+ const storage = { ...methods(store), transaction: async (run: (txn: ReturnType<typeof methods>) => Promise<any>) => {+ const operation = queue.then(async () => { const copy = new Map(store); const result = await run(methods(copy)); store.clear(); for (const [key, value] of copy) store.set(key, value); return result })+ queue = operation.catch(() => {})+ return operation+ } }+ const context = { ctx: { storage } } as never+ const dispatch = vi.fn(() => ({ sent: 1, unsupported: 0 }))+ return { store, context, dispatch }+}+let catalogFingerprint: string+beforeEach(async () => { vi.useFakeTimers(); catalogFingerprint = await fingerprintRuntimeModelCatalog(result.catalog) })+afterEach(() => vi.useRealTimers())+it("registers before dispatch and returns only its matching terminal catalog", async () => {+ const f = fixture()+ const waiting = waitForModelDiscovery(f.context, command, f.dispatch)+ await vi.advanceTimersByTimeAsync(0)+ expect(f.dispatch).toHaveBeenCalledOnce()+ expect(f.store.has("model-discovery-wait:request")).toBe(true)+ await completeModelDiscoveryWait(f.context, "other-request", "codex", result)+ await completeModelDiscoveryWait(f.context, "request", "other-runtime", result)+ expect(f.store.get("model-discovery-wait:request").completed).toBeUndefined()+ await completeModelDiscoveryWait(f.context, "request", "codex", result)+ await completeModelDiscoveryWait(f.context, "request", "codex", { status: "error", code: "late", message: "late" })+ await vi.advanceTimersByTimeAsync(250)+ expect(await waiting).toEqual({ sent: 1, unsupported: 0, cached: false, observedAt: expect.any(String), result })+ expect([...f.store.keys()].filter((key) => /model-discovery-(wait|result):/.test(key))).toEqual([])+})+it("returns errors and removes all durable state without substituting a catalog", async () => {+ const f = fixture()+ const waiting = waitForModelDiscovery(f.context, command, f.dispatch)+ await vi.advanceTimersByTimeAsync(0)+ const error = { status: "error" as const, code: "auth_required", message: "Sign in" }+ await completeModelDiscoveryWait(f.context, command.requestId, command.runtimeId, error)+ await vi.advanceTimersByTimeAsync(250)+ expect(await waiting).toMatchObject({ result: error })+ expect(f.store.size).toBe(0)+})+it("bounds waits and drops late results", async () => {+ const f = fixture()+ const waiting = waitForModelDiscovery(f.context, command, f.dispatch)+ await vi.advanceTimersByTimeAsync(45_000)+ expect(await waiting).toMatchObject({ result: { status: "error", code: "MODEL_DISCOVERY_TIMEOUT" } })+ await completeModelDiscoveryWait(f.context, command.requestId, command.runtimeId, result)+ expect(f.store.size).toBe(0)+})+it("cleans zero-delivery and throwing dispatches", async () => {+ const f = fixture()+ expect(await waitForModelDiscovery(f.context, command, () => ({ sent: 0, unsupported: 1 }))).toEqual({ sent: 0, unsupported: 1 })+ await expect(waitForModelDiscovery(f.context, command, () => { throw new Error("offline") })).rejects.toThrow("offline")+ expect(f.store.size).toBe(0)+})+it("rejects duplicate/capacity requests before dispatch and reclaims expired records", async () => {+ const f = fixture()+ for (let index = 0; index < 16; index++) f.store.set(`model-discovery-wait:${index}`, { runtimeId: "codex", expiresAt: Date.now() + 1000 })+ await expect(waitForModelDiscovery(f.context, command, f.dispatch)).rejects.toThrow("busy")+ expect(f.dispatch).not.toHaveBeenCalled()+ f.store.clear()+ f.store.set("model-discovery-wait:request", { runtimeId: "codex", expiresAt: Date.now() + 1000 })+ await expect(waitForModelDiscovery(f.context, command, f.dispatch)).rejects.toThrow("busy")+ f.store.set("model-discovery-wait:request", { runtimeId: "codex", expiresAt: Date.now() - 1, completed: true })+ f.store.set("model-discovery-result:request", "expired")+ await waitForModelDiscovery(f.context, command, () => ({ sent: 0, unsupported: 0 }))+ expect(f.store.size).toBe(0)+})+it("preserves a large Unicode catalog in one bounded temporary result record", async () => {+ const f = fixture()+ const waiting = waitForModelDiscovery(f.context, command, f.dispatch)+ await vi.advanceTimersByTimeAsync(0)+ const large = { status: "complete" as const, catalog: { updateMode: "unsupported" as const, models: Array.from({ length: 1024 }, (_, index) => ({ id: `model-${index}`, displayName: "模型".repeat(100), supportedReasoningEfforts: [] })) } }+ await completeModelDiscoveryWait(f.context, command.requestId, command.runtimeId, large)+ expect(f.store.get("model-discovery-wait:request").completed).toBe(true)+ const records = [...f.store].filter(([key]) => key.startsWith("model-discovery-result:"))+ expect(records).toHaveLength(1)+ expect(Buffer.byteLength(records[0][1])).toBeGreaterThan(128 * 1024)+ expect(Buffer.byteLength(records[0][0]) + records[0][1].byteLength).toBeLessThanOrEqual(2_000_000)+ await vi.advanceTimersByTimeAsync(250)+ expect(await waiting).toMatchObject({ result: large })+ expect([...f.store.keys()].filter((key) => /model-discovery-(wait|result):/.test(key))).toEqual([])+})++it("reuses five-minute successful cache without dispatch, forces refresh and expires at the boundary", async () => {+ const f = fixture()+ const first = waitForModelDiscovery(f.context, command, f.dispatch, { useCache: true, catalogFingerprint })+ await vi.advanceTimersByTimeAsync(0)+ await completeModelDiscoveryWait(f.context, command.requestId, command.runtimeId, result)+ await vi.advanceTimersByTimeAsync(250)+ const fresh = await first+ const cached = await waitForModelDiscovery(f.context, command, f.dispatch, { useCache: true, catalogFingerprint })+ expect(cached).toEqual({ sent: 0, unsupported: 0, cached: true, observedAt: fresh.observedAt, catalogFingerprint })+ expect(f.dispatch).toHaveBeenCalledOnce()+ const forced = waitForModelDiscovery(f.context, command, f.dispatch)+ await vi.advanceTimersByTimeAsync(0)+ expect(f.dispatch).toHaveBeenCalledTimes(2)+ await completeModelDiscoveryWait(f.context, command.requestId, command.runtimeId, result)+ await vi.advanceTimersByTimeAsync(250)+ await forced+ await vi.advanceTimersByTimeAsync(299_750)+ const expired = waitForModelDiscovery(f.context, command, f.dispatch, { useCache: true, catalogFingerprint })+ await vi.advanceTimersByTimeAsync(0)+ expect(f.dispatch).toHaveBeenCalledTimes(3)+ await completeModelDiscoveryWait(f.context, command.requestId, command.runtimeId, result)+ await vi.advanceTimersByTimeAsync(250)+ expect(await expired).toMatchObject({ cached: false })+})+it("does not cache errors or extend cache age from duplicate, late or unrelated reports", async () => {+ const f = fixture()+ const first = waitForModelDiscovery(f.context, command, f.dispatch)+ await vi.advanceTimersByTimeAsync(0)+ await completeModelDiscoveryWait(f.context, command.requestId, command.runtimeId, result)+ await vi.advanceTimersByTimeAsync(250)+ await first+ const original = structuredClone(f.store.get("model-discovery-cache:codex"))+ await vi.advanceTimersByTimeAsync(1000)+ await completeModelDiscoveryWait(f.context, command.requestId, command.runtimeId, result)+ await completeModelDiscoveryWait(f.context, "unrelated", command.runtimeId, result)+ const failure = waitForModelDiscovery(f.context, command, f.dispatch)+ await vi.advanceTimersByTimeAsync(0)+ await completeModelDiscoveryWait(f.context, command.requestId, command.runtimeId, { status: "error", code: "failed", message: "Failed" })+ await vi.advanceTimersByTimeAsync(250)+ await failure+ expect(f.store.get("model-discovery-cache:codex")).toEqual(original)+})++it("bounds retained backend metadata and deletes expired entries", async () => {+ const f = fixture()+ for (let index = 0; index < 64; index++) {+ f.store.set(`model-discovery-cache:backend${index}`, { catalogFingerprint, observedAt: Date.now() - 1000 + index })+ }+ const waiting = waitForModelDiscovery(f.context, command, f.dispatch)+ await vi.advanceTimersByTimeAsync(0)+ await completeModelDiscoveryWait(f.context, command.requestId, command.runtimeId, result)+ await vi.advanceTimersByTimeAsync(250)+ await waiting+ expect([...f.store.keys()].filter((key) => key.startsWith("model-discovery-cache:"))).toHaveLength(64)+ expect(f.store.has("model-discovery-cache:backend0")).toBe(false)+ await vi.advanceTimersByTimeAsync(300_000)+ const renewal = waitForModelDiscovery(f.context, command, f.dispatch)+ await vi.advanceTimersByTimeAsync(0)+ await completeModelDiscoveryWait(f.context, command.requestId, command.runtimeId, result)+ await vi.advanceTimersByTimeAsync(250)+ await renewal+ expect([...f.store.keys()].filter((key) => key.startsWith("model-discovery-cache:"))).toEqual(["model-discovery-cache:codex"])+ expect(f.store.has("model-discovery-cache:backend1")).toBe(false)+})+it("does not share a cache across credential contexts or trust a future discovery timestamp", async () => {+ const f = fixture()+ f.store.set("model-discovery-cache:codex", { catalogFingerprint, observedAt: Date.now() + 1 })+ await waitForModelDiscovery(f.context, command, () => ({ sent: 0, unsupported: 1 }), { useCache: true, catalogFingerprint })+ const other = fixture()+ await waitForModelDiscovery(other.context, command, () => ({ sent: 0, unsupported: 1 }), { useCache: true, catalogFingerprint })+ expect(other.store.size).toBe(0)+})++it("retains only discovery metadata and invalidates a cache when the D1 catalog fingerprint changes", async () => {+ const f = fixture()+ const first = waitForModelDiscovery(f.context, command, f.dispatch)+ await vi.advanceTimersByTimeAsync(0)+ await completeModelDiscoveryWait(f.context, command.requestId, command.runtimeId, result)+ await vi.advanceTimersByTimeAsync(250)+ await first+ expect(f.store.get("model-discovery-cache:codex")).toEqual({ observedAt: expect.any(Number), catalogFingerprint })+ expect([...f.store.keys()]).toEqual(["model-discovery-cache:codex"])+ const changed = waitForModelDiscovery(f.context, command, f.dispatch, { useCache: true, catalogFingerprint: "b".repeat(64) })+ await vi.advanceTimersByTimeAsync(0)+ expect(f.dispatch).toHaveBeenCalledTimes(2)+ await completeModelDiscoveryWait(f.context, command.requestId, command.runtimeId, result)+ await vi.advanceTimersByTimeAsync(250)+ expect(await changed).toMatchObject({ cached: false, result })+})+it("returns an explicit bounded error for an oversized result and does not cache it", async () => {+ const f = fixture()+ const waiting = waitForModelDiscovery(f.context, command, f.dispatch)+ await vi.advanceTimersByTimeAsync(0)+ const huge = { status: "complete" as const, catalog: { updateMode: "unsupported" as const, models: [{ id: "huge", displayName: "x".repeat(2_000_000), supportedReasoningEfforts: [] }] } }+ await completeModelDiscoveryWait(f.context, command.requestId, command.runtimeId, huge)+ const record = f.store.get("model-discovery-result:request")+ expect(Buffer.byteLength(record)).toBeLessThan(1000)+ expect(f.store.has("model-discovery-cache:codex")).toBe(false)+ await vi.advanceTimersByTimeAsync(250)+ expect(await waiting).toMatchObject({ result: { status: "error", code: "MODEL_DISCOVERY_RESULT_TOO_LARGE" } })+ expect(f.store.size).toBe(0)+})diff --git a/src/ws-do/src/ws-durable/model-discovery-wait.ts b/src/ws-do/src/ws-durable/model-discovery-wait.tsnew file mode 100644index 000000000..c6da762d8--- /dev/null+++ b/src/ws-do/src/ws-durable/model-discovery-wait.ts@@ -0,0 +1,104 @@+import { fingerprintRuntimeModelCatalog, type RuntimeModelDiscoveryRequest, type RuntimeModelDiscoveryResult } from "@alook/shared"+import type { WsDurableContext } from "./internal"++const PREFIX = "model-discovery-wait:"+const RESULT_PREFIX = "model-discovery-result:"+const CACHE_PREFIX = "model-discovery-cache:"+const CACHE_MS = 5 * 60_000+const MAX_CACHED = 64+const MAX_PENDING = 16+const WAIT_MS = 45_000+const MAX_RESULT_BYTES = 2_000_000++type Pending = { runtimeId: string; expiresAt: number; completed?: boolean; observedAt?: number }+type Cached = { observedAt: number; catalogFingerprint: string }+const resultKey = (requestId: string) => RESULT_PREFIX + requestId++export async function waitForModelDiscovery(+ context: WsDurableContext,+ command: RuntimeModelDiscoveryRequest,+ dispatch: () => { sent: number; unsupported: number },+ options: { useCache?: boolean; catalogFingerprint?: string } = {},+) {+ const storage = context.ctx.storage+ const key = PREFIX + command.requestId+ const now = Date.now()+ if (options.useCache) {+ const cached = await storage.get<Cached>(CACHE_PREFIX + command.runtimeId)+ if (cached && options.catalogFingerprint && cached.catalogFingerprint === options.catalogFingerprint && cached.observedAt <= now && now - cached.observedAt < CACHE_MS) {+ return { sent: 0, unsupported: 0, cached: true, observedAt: new Date(cached.observedAt).toISOString(), catalogFingerprint: cached.catalogFingerprint }+ }+ }+ await storage.transaction(async (txn) => {+ const entries = await txn.list<Pending>({ prefix: PREFIX })+ for (const [entryKey, pending] of entries) {+ if (pending.expiresAt <= now) {+ await txn.delete([entryKey, resultKey(entryKey.slice(PREFIX.length))])+ entries.delete(entryKey)+ }+ }+ if (entries.has(key) || entries.size >= MAX_PENDING) throw new Error("Model discovery is busy")+ await txn.put<Pending>(key, { runtimeId: command.runtimeId, expiresAt: now + WAIT_MS })+ })+ try {+ const receipt = dispatch()+ if (receipt.sent === 0) return receipt+ while (Date.now() < now + WAIT_MS) {+ const pending = await storage.get<Pending>(key)+ if (!pending) break+ if (pending.completed) {+ const bytes = await storage.get<Uint8Array>(resultKey(command.requestId))+ if (bytes === undefined) throw new Error("Model discovery result unavailable")+ return { ...receipt, cached: false, observedAt: new Date(pending.observedAt!).toISOString(), result: JSON.parse(new TextDecoder().decode(bytes)) as RuntimeModelDiscoveryResult }+ }+ await new Promise((resolve) => setTimeout(resolve, 250))+ }+ return { ...receipt, result: { status: "error" as const, code: "MODEL_DISCOVERY_TIMEOUT", message: "Model discovery timed out" } }+ } finally {+ await storage.transaction(async (txn) => {+ const pending = await txn.get<Pending>(key)+ if (pending?.expiresAt === now + WAIT_MS) await txn.delete([key, resultKey(command.requestId)])+ })+ }+}++export async function completeModelDiscoveryWait(+ context: WsDurableContext,+ requestId: string,+ runtimeId: string,+ result: RuntimeModelDiscoveryResult,+) {+ const storage = context.ctx.storage+ const key = PREFIX + requestId+ if (!await storage.get<Pending>(key)) return+ const recordKey = resultKey(requestId)+ const encoder = new TextEncoder()+ let saved = result+ let bytes = encoder.encode(JSON.stringify(saved))+ if (encoder.encode(recordKey).byteLength + bytes.byteLength > MAX_RESULT_BYTES) {+ saved = { status: "error", code: "MODEL_DISCOVERY_RESULT_TOO_LARGE", message: "Model discovery result is too large" }+ bytes = encoder.encode(JSON.stringify(saved))+ }+ const catalogFingerprint = saved.status === "complete" ? await fingerprintRuntimeModelCatalog(saved.catalog) : undefined+ await storage.transaction(async (txn) => {+ const pending = await txn.get<Pending>(key)+ if (!pending || pending.runtimeId !== runtimeId || pending.expiresAt <= Date.now() || pending.completed) return+ const observedAt = Date.now()+ await txn.put(recordKey, bytes)+ if (catalogFingerprint) {+ const entries = await txn.list<Cached>({ prefix: CACHE_PREFIX })+ for (const [cacheKey, cached] of entries) {+ if (observedAt - cached.observedAt >= CACHE_MS || cached.observedAt > observedAt) {+ await txn.delete(cacheKey)+ entries.delete(cacheKey)+ }+ }+ if (!entries.has(CACHE_PREFIX + runtimeId) && entries.size >= MAX_CACHED) {+ const oldest = [...entries].sort((a, b) => a[1].observedAt - b[1].observedAt)[0]+ await txn.delete(oldest[0])+ }+ await txn.put<Cached>(CACHE_PREFIX + runtimeId, { catalogFingerprint, observedAt })+ }+ await txn.put<Pending>(key, { ...pending, completed: true, observedAt })+ })+}diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.tsindex a5a59d1f3..daa2abbc5 100644--- a/src/ws-do/src/ws-durable/test-harness.ts+++ b/src/ws-do/src/ws-durable/test-harness.ts@@ -26,6 +26,12 @@ export class CFResponse {private _body: BodyInit | nullprivate _headers: Headers+ static json(body: unknown, init: ResponseInit = {}) {+ const headers = new Headers(init.headers)+ if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json")+ return new CFResponse(JSON.stringify(body), { ...init, headers })+ }+constructor(body: BodyInit | null = null, init: ResponseInit & { webSocket?: unknown } = {}) {this._body = bodythis._headers = new Headers(init.headers)diff --git a/src/ws-do/test-runtime/automation.runtime.test.ts b/src/ws-do/test-runtime/automation.runtime.test.tsnew file mode 100644index 000000000..914f378c8--- /dev/null+++ b/src/ws-do/test-runtime/automation.runtime.test.ts@@ -0,0 +1,81 @@+/// <reference types="@cloudflare/vitest-plugin/types" />+import { runInDurableObject } from "cloudflare:test"+import { env, exports } from "cloudflare:workers"+import { describe, expect, it } from "vitest"++const runtimeEnv = env as unknown as { RATE_LIMIT_DO: DurableObjectNamespace }+const worker = (exports as unknown as { default: { fetch(request: Request): Promise<Response> } }).default+function check(stub: DurableObjectStub, max = 64, period = "hour") {+ return stub.fetch(new Request("https://worker.test/check-automation", { method: "POST", body: JSON.stringify({ max, period }) }))+}+function stub() { return runtimeEnv.RATE_LIMIT_DO.get(runtimeEnv.RATE_LIMIT_DO.idFromName(crypto.randomUUID())) }++describe("automation rolling limits in real workerd", () => {+ it("atomically admits only 64 concurrent day requests within an hour and persists across stubs", async () => {+ const id = runtimeEnv.RATE_LIMIT_DO.idFromName(crypto.randomUUID())+ const first = runtimeEnv.RATE_LIMIT_DO.get(id)+ const results = await Promise.all(Array.from({ length: 80 }, async () => (await check(first, 1536, "day")).json<{ allowed: boolean }>()))+ expect(results.filter((result) => result.allowed)).toHaveLength(64)+ expect(results.filter((result) => !result.allowed)).toHaveLength(16)+ const another = runtimeEnv.RATE_LIMIT_DO.get(id)+ expect(await (await check(another, 1536, "day")).json()).toMatchObject({ allowed: false, retryAfterSec: expect.any(Number) })+ await runInDurableObject(another, async (_instance, state) => {+ expect(await state.storage.get<number[]>("automation")).toHaveLength(64)+ })+ })+ it("retains history when lowering rates or switching periods", async () => {+ const target = stub()+ expect(await (await check(target, 64)).json()).toEqual({ allowed: true })+ expect(await (await check(target, 1, "day")).json()).toMatchObject({ allowed: false })+ expect(await (await check(target, 1, "hour")).json()).toMatchObject({ allowed: false })+ expect(await (await check(target, 2, "hour")).json()).toEqual({ allowed: true })+ await runInDurableObject(target, async (_instance, state) => {+ expect(await state.storage.get<number[]>("automation")).toHaveLength(2)+ })+ })+ it("retains admitted usage after the Durable Object is reset", async () => {+ const id = runtimeEnv.RATE_LIMIT_DO.idFromName(crypto.randomUUID())+ const original = runtimeEnv.RATE_LIMIT_DO.get(id)+ expect(await (await check(original, 1)).json()).toEqual({ allowed: true })+ await expect(runInDurableObject(original, (_instance, state) => {+ state.abort("automation restart probe")+ })).rejects.toThrow()+ const restarted = runtimeEnv.RATE_LIMIT_DO.get(id)+ expect(await (await check(restarted, 1)).json()).toMatchObject({ allowed: false })+ })+ it("prunes rolling 24h history and computes retry time for every active constraint", async () => {+ const target = stub()+ await runInDurableObject(target, async (_instance, state) => {+ const now = Date.now()+ await state.storage.put("automation", [now - 86_400_001, now - 3_600_000 + 120_000])+ })+ expect(await (await check(target, 1)).json()).toMatchObject({ allowed: false, retryAfterSec: expect.any(Number) })+ await runInDurableObject(target, async (_instance, state) => {+ await state.storage.put("automation", [Date.now() - 86_400_001])+ })+ expect(await (await check(target, 1, "day")).json()).toEqual({ allowed: true })+ await runInDurableObject(target, async (_instance, state) => {+ expect(await state.storage.get<number[]>("automation")).toHaveLength(1)+ })+ })+ it("isolates code and permission shards through the real router", async () => {+ const key = crypto.randomUUID()+ const call = async (name: string, code: string) => (await worker.fetch(new Request("https://worker.test/rate-limit/automation", {+ method: "POST", body: JSON.stringify({ name, key: code, max: 1, period: "day" }),+ }))).json()+ expect(await call("bot.create", key)).toEqual({ allowed: true })+ expect(await call("bot.create", key)).toMatchObject({ allowed: false })+ expect(await call("server.create", key)).toEqual({ allowed: true })+ expect(await call("bot.create", crypto.randomUUID())).toEqual({ allowed: true })+ })+ it("rejects invalid policy input without creating state", async () => {+ const target = stub()+ for (const [max, period] of [[65, "hour"], [1537, "day"], [1.5, "day"], [0, "hour"], [1, "week"]] as const) {+ expect((await check(target, max, period)).status).toBe(400)+ }+ expect((await target.fetch(new Request("https://worker.test/check-automation", { method: "POST", body: "null" }))).status).toBe(400)+ await runInDurableObject(target, async (_instance, state) => {+ expect(await state.storage.get("automation")).toBeUndefined()+ })+ })+})