Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add owner-approved bot creation requests (#1049)

Gustavo Ye9ce61f990861
diff --git a/src/daemon/agent-driver/src/adapters/agy/index.ts b/src/daemon/agent-driver/src/adapters/agy/index.ts
index 82029ad37..0cfacd3c0 100644
--- a/src/daemon/agent-driver/src/adapters/agy/index.ts
+++ b/src/daemon/agent-driver/src/adapters/agy/index.ts
@@ -17,6 +17,7 @@ function nativeId(value: unknown): string | undefined {
export class AgyDriver implements BackendAdapter<"agy"> {
readonly id = "agy";
+ readonly modelCatalogOrigin = "native_report" as const;
readonly instructionDelivery = { kind: "native" } as const;
readonly execution = {
lifetime: "session", transport: { kind: "stdio_stream", protocol: "agy.stream-json.v1" },
diff --git a/src/daemon/agent-driver/src/adapters/antigravity/index.ts b/src/daemon/agent-driver/src/adapters/antigravity/index.ts
index d494212ab..e1031cebd 100644
--- a/src/daemon/agent-driver/src/adapters/antigravity/index.ts
+++ b/src/daemon/agent-driver/src/adapters/antigravity/index.ts
@@ -8,6 +8,7 @@ import { antigravitySpawnSpec, probeAntigravity } from "./probe.js";
export class AntigravityDriver implements BackendAdapter {
readonly id = "antigravity";
+ readonly modelCatalogOrigin = "native_report" as const;
readonly instructionDelivery = { kind: "native" } as const;
readonly execution = {
lifetime: "session",
diff --git a/src/daemon/agent-driver/src/adapters/claude/index.ts b/src/daemon/agent-driver/src/adapters/claude/index.ts
index b5637b5ad..aea7f8a63 100644
--- a/src/daemon/agent-driver/src/adapters/claude/index.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/index.ts
@@ -33,6 +33,7 @@ const CLAUDE_MODEL_CATALOG = {
export class ClaudeDriver implements BackendAdapter {
readonly id = "claude";
+ readonly modelCatalogOrigin = "adapter_suggestions" as const;
readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;
readonly execution = {
lifetime: "session",
diff --git a/src/daemon/agent-driver/src/adapters/codex/index.ts b/src/daemon/agent-driver/src/adapters/codex/index.ts
index b8f71b160..8596db3f5 100644
--- a/src/daemon/agent-driver/src/adapters/codex/index.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/index.ts
@@ -56,6 +56,7 @@ function isCodexMissingRolloutError(message: string): boolean {
export class CodexDriver implements BackendAdapter {
readonly id = "codex";
+ readonly modelCatalogOrigin = "native_report" as const;
readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;
readonly execution = {
lifetime: "session",
diff --git a/src/daemon/agent-driver/src/adapters/cursor/index.ts b/src/daemon/agent-driver/src/adapters/cursor/index.ts
index f06dbcf21..95254f25a 100644
--- a/src/daemon/agent-driver/src/adapters/cursor/index.ts
+++ b/src/daemon/agent-driver/src/adapters/cursor/index.ts
@@ -28,6 +28,7 @@ import { discoverCursorRecentContext } from "./recent-context.js";
export class CursorDriver implements BackendAdapter, CursorAcpProcessFactory {
readonly id = "cursor";
+ readonly modelCatalogOrigin = "native_report" as const;
readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;
readonly execution = {
lifetime: "session",
diff --git a/src/daemon/agent-driver/src/adapters/grok/index.ts b/src/daemon/agent-driver/src/adapters/grok/index.ts
index a72e98b80..a2ce49aab 100644
--- a/src/daemon/agent-driver/src/adapters/grok/index.ts
+++ b/src/daemon/agent-driver/src/adapters/grok/index.ts
@@ -22,6 +22,7 @@ type GrokSpawn = (
export class GrokDriver implements BackendAdapter, GrokAcpProcessFactory {
readonly id = "grok";
+ readonly modelCatalogOrigin = "native_report" as const;
readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;
readonly execution = {
lifetime: "session",
diff --git a/src/daemon/agent-driver/src/adapters/opencode/index.ts b/src/daemon/agent-driver/src/adapters/opencode/index.ts
index 671da7bd7..a8a83f9ae 100644
--- a/src/daemon/agent-driver/src/adapters/opencode/index.ts
+++ b/src/daemon/agent-driver/src/adapters/opencode/index.ts
@@ -38,6 +38,7 @@ function createOpenCodeMessageId(): string {
export class OpenCodeDriver implements BackendAdapter, OpenCodeServiceProcessFactory {
readonly id = "opencode";
+ readonly modelCatalogOrigin = "native_report" as const;
readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;
readonly execution = {
lifetime: "session",
diff --git a/src/daemon/agent-driver/src/adapters/pi/index.ts b/src/daemon/agent-driver/src/adapters/pi/index.ts
index ca8374956..8bea7f3e9 100644
--- a/src/daemon/agent-driver/src/adapters/pi/index.ts
+++ b/src/daemon/agent-driver/src/adapters/pi/index.ts
@@ -250,6 +250,7 @@ export function mapPiSdkEvent(event: any, sessionId: string, state: PiEventState
export class PiDriver implements BackendAdapter {
readonly id = "pi";
+ readonly modelCatalogOrigin = "native_report" as const;
readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;
readonly execution = {
lifetime: "session",
diff --git a/src/daemon/agent-driver/src/contract.ts b/src/daemon/agent-driver/src/contract.ts
index dd98afaf9..93e11013c 100644
--- a/src/daemon/agent-driver/src/contract.ts
+++ b/src/daemon/agent-driver/src/contract.ts
@@ -23,6 +23,7 @@ export type RuntimeSettingsUpdateResult =
| { readonly status: "failed"; readonly error: AgentDriverError };
export type RuntimeReasoningCatalog = {
+ readonly catalogOrigin?: "native_report" | "adapter_suggestions";
readonly updateMode: "live_next_turn" | "context_preserving_restart" | "unsupported";
readonly defaultModelId?: string;
readonly models: readonly {
diff --git a/src/daemon/agent-driver/src/internal/adapter.ts b/src/daemon/agent-driver/src/internal/adapter.ts
index 0bcef844a..1f321dd32 100644
--- a/src/daemon/agent-driver/src/internal/adapter.ts
+++ b/src/daemon/agent-driver/src/internal/adapter.ts
@@ -203,6 +203,7 @@ export interface VendorSessionHandle {
}
export interface BackendAdapter<Id extends string = BuiltinBackendId, Config = BackendConfig> {
+ readonly modelCatalogOrigin?: "native_report" | "adapter_suggestions";
readonly id: Id;
readonly instructionDelivery:
| { readonly kind: "native" }
diff --git a/src/daemon/agent-driver/src/sdk.test.ts b/src/daemon/agent-driver/src/sdk.test.ts
index 14f4c2ebb..8b56b1db9 100644
--- a/src/daemon/agent-driver/src/sdk.test.ts
+++ b/src/daemon/agent-driver/src/sdk.test.ts
@@ -71,6 +71,13 @@ describe("createAgentDriverSdk", () => {
expect(probe).toHaveBeenLastCalledWith(undefined);
});
+ it.each(["healthy", "unhealthy"] as const)("labels Claude %s model suggestions at the producer boundary", async (status) => {
+ vi.spyOn(ClaudeDriver.prototype, "probe").mockResolvedValue({ status, reasoning: { models: [{ id: "sonnet", supportedReasoningEfforts: [] }], updateMode: "unsupported" } });
+ await expect(createAgentDriverSdk().probe({ backend: "claude" })).resolves.toMatchObject({
+ reasoning: { catalogOrigin: "adapter_suggestions", models: [{ id: "sonnet" }] },
+ });
+ });
+
it("maps healthy, unhealthy, and thrown adapter probes", async () => {
const sdk = createAgentDriverSdk();
const probe = vi.spyOn(ClaudeDriver.prototype, "probe");
@@ -115,7 +122,7 @@ describe("createAgentDriverSdk", () => {
if (process.platform !== "win32") chmodSync(command, 0o755);
await expect(createAgentDriverSdk().probe({ backend: "opencode", command })).resolves.toMatchObject({
status: "healthy", version: "opencode v2.0.28",
- reasoning: { models: [{ id: "opencode/space-bunny-free" }] },
+ reasoning: { catalogOrigin: "native_report", models: [{ id: "opencode/space-bunny-free" }] },
});
} finally { rmSync(directory, { recursive: true, force: true }); }
});
diff --git a/src/daemon/agent-driver/src/sdk.ts b/src/daemon/agent-driver/src/sdk.ts
index 15755002d..89f7a30cb 100644
--- a/src/daemon/agent-driver/src/sdk.ts
+++ b/src/daemon/agent-driver/src/sdk.ts
@@ -118,7 +118,7 @@ export function createAgentDriverSdkWithRegistry<Specs>(
status: "healthy",
version: result.version,
capabilities,
- reasoning: result.reasoning,
+ reasoning: result.reasoning && adapter.modelCatalogOrigin ? { ...result.reasoning, catalogOrigin: adapter.modelCatalogOrigin } : result.reasoning,
};
}
return {
@@ -130,7 +130,7 @@ export function createAgentDriverSdkWithRegistry<Specs>(
retryable: true,
},
capabilities,
- reasoning: result.reasoning,
+ reasoning: result.reasoning && adapter.modelCatalogOrigin ? { ...result.reasoning, catalogOrigin: adapter.modelCatalogOrigin } : result.reasoning,
};
} catch (error) {
const contractInvalid = error instanceof Error && (
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index 49c2f3946..5cd7c3e6f 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -2235,3 +2235,16 @@ describe("nap", () => {
expect(help).not.toContain("--text");
});
});
+
+describe("platform main CLI envelopes", () => {
+ it("prints batch field errors as one JSON line through main", async () => {
+ setApiForTesting(stubApi({ platformBot: async () => { throw Object.assign(new Error("Unsupported effort"), { code: "INVALID_REASONING_EFFORT", platformDetails: { itemIndex: 2, field: "reasoningEffort", allowedValues: ["low"] } }) } }))
+ await main(["platform", "bot", "--create", JSON.stringify({ name: "Reviewer", machineId: "machine", backendId: "codex", reason: "Independent check" })])
+ expect(parseEnvelope(cap.lines())).toEqual({ error: "Unsupported effort", code: "INVALID_REASONING_EFFORT", itemIndex: 2, field: "reasoningEffort", allowedValues: ["low"] })
+ })
+ it("prints refresh failures directly through the real main error path", async () => {
+ setApiForTesting(stubApi({ platformMachine: async () => { throw Object.assign(new Error("Target machine is offline"), { code: "MACHINE_OFFLINE", platformDetails: { machineId: "machine" } }) } }))
+ await main(["platform", "machine", "--models", "--id", "machine", "--backend", "codex", "--refresh"])
+ expect(parseEnvelope(cap.lines())).toEqual({ error: "Target machine is offline", code: "MACHINE_OFFLINE", machineId: "machine" })
+ })
+})
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index 58763bd07..9731c8ca6 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -1,4 +1,5 @@
#!/usr/bin/env node
+import { registerPlatformCommands } from "./platform.js";
/**
* `alook` — the agent-facing CLI.
*
@@ -51,6 +52,7 @@ interface Envelope {
/** Stable machine code carried up from an upstream error body (e.g.
* `already_friends`, `blocked`). Present only on the error envelope. */
code?: string;
+ platformDetails?: Record<string, unknown>;
}
/** A command failure with a human-readable message destined for `error`. */
@@ -68,6 +70,7 @@ function printEnvelope(env: Envelope): void {
if (env.error !== undefined && env.error !== null) out.error = env.error;
if (env.code !== undefined && env.code !== null) out.code = env.code;
if (env.hint !== undefined && env.hint !== null) out.hint = env.hint;
+ if (env.platformDetails) Object.assign(out, env.platformDetails);
process.stdout.write(JSON.stringify(out) + "\n");
}
@@ -808,6 +811,8 @@ function buildProgram(stdin: CliInputStream): Command {
})
.option("--agent <id>", "agent identity (or ALOOK_AGENT_ID env)");
+ registerPlatformCommands(program, getApi, printEnvelope);
+
const message = program.command("message").description("message operations").exitOverride();
message.configureOutput({ writeOut: () => {}, writeErr: () => {} });
@@ -1301,6 +1306,7 @@ export async function main(argv = process.argv.slice(2), io: CliIo = {}): Promis
error: (err as Error).message,
code: (err as { code?: string }).code,
hint: (err as { hint?: string }).hint,
+ platformDetails: (err as { platformDetails?: Record<string, unknown> }).platformDetails,
});
}
// Public agent-facing commands keep their JSON-only result contract. The
diff --git a/src/daemon/src/cli/platform-proxy.test.ts b/src/daemon/src/cli/platform-proxy.test.ts
new file mode 100644
index 000000000..b860c7b8c
--- /dev/null
+++ b/src/daemon/src/cli/platform-proxy.test.ts
@@ -0,0 +1,21 @@
+import { afterEach, describe, expect, it, vi } from "vitest"
+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 }))
+ 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(fetchImpl).toHaveBeenCalledOnce()
+ expect(fetchImpl.mock.calls[0][0]).toBe("http://proxy/api/community/machines/m1/discover-models")
+ })
+ 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 }))
+ const api = createProxyServerApi({ proxyUrl: "http://proxy", voucher: "voucher", fetchImpl })
+ await expect(api.platformBot!({ action: "create", requestId: "request", bots: [] })).rejects.toMatchObject({ code: "INVALID_REASONING_EFFORT", platformDetails: { itemIndex: 2, field: "reasoningEffort", allowedValues: ["low"] } })
+ const error = await api.platformBot!({ action: "list" }).catch((error) => error)
+ expect(error.platformDetails).not.toHaveProperty("credential")
+ expect(error.platformDetails).not.toHaveProperty("ownerSecret")
+ })
+})
diff --git a/src/daemon/src/cli/platform.test.ts b/src/daemon/src/cli/platform.test.ts
new file mode 100644
index 000000000..07bec545e
--- /dev/null
+++ b/src/daemon/src/cli/platform.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it, vi } from "vitest"
+import { Command } from "commander"
+import { registerPlatformCommands } from "./platform"
+import { createProxyServerApi } from "./proxyServerApi"
+
+async function run(args: string[], fetchImpl = vi.fn(async () => Response.json({ machines: [] }))) {
+ const output = vi.fn()
+ const program = new Command("alook").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ registerPlatformCommands(program, () => createProxyServerApi({ proxyUrl: "http://proxy", voucher: "vch_private", fetchImpl }), output)
+ await program.parseAsync(args, { from: "user" })
+ return { output, fetchImpl }
+}
+const bot = { name: "Reviewer", machineId: "m1", backendId: "codex", model: "full/model-id", reasoningEffort: "high", description: "Check sources", reason: "Independent review" }
+
+describe("platform command registration through the real proxy API client", () => {
+ it("uses exactly two action-flag entrypoints and no-argument help has no network effects", async () => {
+ const fetchImpl = vi.fn()
+ const result = await run(["platform", "machine"], fetchImpl)
+ expect(result.output.mock.calls[0][0].success.usage).toContain("--models")
+ expect(fetchImpl).not.toHaveBeenCalled()
+ await expect(run(["platform", "bot", "--list", "--create", JSON.stringify(bot)], fetchImpl)).rejects.toMatchObject({ code: "INVALID_ACTION" })
+ await expect(run(["platform", "machine", "--backends", "--models", "--id", "m1"], fetchImpl)).rejects.toMatchObject({ code: "INVALID_ACTION" })
+ await expect(run(["platform", "bot", "--request-status", "request"], fetchImpl)).rejects.toThrow("unknown option")
+ expect(fetchImpl).not.toHaveBeenCalled()
+ })
+ it("normalizes one or multiple --create flags to one request and preserves independent configurations", async () => {
+ for (const items of [[bot], [bot, { ...bot, name: "Researcher", model: "other/model", reasoningEffort: "low" }]]) {
+ const fetchImpl = vi.fn(async () => Response.json({ status: "pending", count: items.length, requestId: "request" }))
+ const result = await run(["platform", "bot", ...items.flatMap((item) => ["--create", JSON.stringify(item)])], fetchImpl)
+ expect(fetchImpl).toHaveBeenCalledOnce()
+ const [url, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit]
+ expect(url).toBe("http://proxy/api/community/bots/creation-requests")
+ expect(JSON.parse(init.body as string)).toMatchObject({ requestId: expect.any(String), bots: items })
+ expect(init.headers).toEqual(expect.objectContaining({ authorization: "Bearer vch_private" }))
+ expect(result.output).toHaveBeenCalledWith({ success: { status: "pending", count: items.length, requestId: "request" } })
+ }
+ })
+ it("rejects invalid JSON, blank reason, owner injection and an oversized batch before transport", async () => {
+ const fetchImpl = vi.fn()
+ await expect(run(["platform", "bot", "--create", "{"], fetchImpl)).rejects.toMatchObject({ code: "INVALID_PROPOSAL", platformDetails: { itemIndex: 1 } })
+ await expect(run(["platform", "bot", "--create", JSON.stringify(bot), "--create", JSON.stringify({ ...bot, reason: " " })], fetchImpl)).rejects.toMatchObject({ code: "REASON_REQUIRED", platformDetails: { itemIndex: 2, field: "reason" } })
+ await expect(run(["platform", "bot", "--create", JSON.stringify({ ...bot, reason: "x".repeat(1001) })], fetchImpl)).rejects.toMatchObject({ code: "INVALID_PROPOSAL", platformDetails: { itemIndex: 1, field: "reason" } })
+ await expect(run(["platform", "bot", "--create", JSON.stringify({ ...bot, ownerId: "stranger" })], fetchImpl)).rejects.toMatchObject({ code: "INVALID_PROPOSAL" })
+ await expect(run(["platform", "bot", ...Array.from({ length: 21 }, () => ["--create", JSON.stringify(bot)]).flat()], fetchImpl)).rejects.toMatchObject({ code: "INVALID_PROPOSAL" })
+ expect(fetchImpl).not.toHaveBeenCalled()
+ })
+ 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")
+ })
+})
diff --git a/src/daemon/src/cli/platform.ts b/src/daemon/src/cli/platform.ts
new file mode 100644
index 000000000..cfb5fb9cc
--- /dev/null
+++ b/src/daemon/src/cli/platform.ts
@@ -0,0 +1,59 @@
+import type { Command } from "commander"
+import { randomUUID } from "node:crypto"
+import { BotCreationSubmitSchema, BOT_CREATION_BODY_MAX_BYTES } from "@alook/shared"
+import type { ServerApi } from "../server/contract.js"
+
+const failure = (message: string, code: string, details?: Record<string, unknown>) => Object.assign(new Error(message), { code, platformDetails: details })
+
+export function registerPlatformCommands(program: Command, getApi: () => ServerApi, output: (value: { success: unknown }) => void) {
+ const platform = program.command("platform").description("owner-scoped platform capabilities").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ const machine = platform.command("machine").description("read machines, backends, models and model-specific effort").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ .option("--list", "list your owner's machines")
+ .option("--backends", "show backends on --id")
+ .option("--models", "show models and effort for --id and --backend")
+ .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")
+ machine.action(async () => {
+ const opts = machine.opts()
+ const actions = [opts.list, opts.backends, opts.models].filter(Boolean).length
+ if (!actions && Object.keys(opts).length === 0) { output({ success: { usage: machine.helpInformation() } }); return }
+ if (actions !== 1) throw failure("Choose one action: --list, --backends, or --models", "INVALID_ACTION")
+ if (opts.list && (opts.id || opts.backend || opts.model || opts.refresh)) throw failure("--list does not accept target or model flags", "INVALID_ACTION")
+ if (!opts.list && !opts.id) throw failure("--id is required", "MACHINE_REQUIRED")
+ if (opts.backends && (opts.backend || opts.model || opts.refresh)) throw failure("--backends only accepts --id", "INVALID_ACTION")
+ if (opts.models && !opts.backend) throw failure("--models requires --backend", "BACKEND_REQUIRED")
+ const 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() } : {}) })
+ output({ success: result })
+ })
+ const bot = platform.command("bot").description("read bots or request owner-approved creation").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ .option("--list", "list your owner's bot summaries")
+ .option("--create <bot-json>", "request one bot; repeat for one gallery request", (value: string, previous: string[]) => [...previous, value], [])
+ bot.action(async () => {
+ const opts = bot.opts()
+ const values: string[] = opts.create
+ const actions = [opts.list, values.length > 0].filter(Boolean).length
+ if (!actions) { output({ success: { usage: bot.helpInformation() } }); return }
+ if (actions !== 1) throw failure("Choose one action: --list or one or more --create values", "INVALID_ACTION")
+ const api = getApi()
+ if (!api.platformBot) throw failure("Platform bot commands are unavailable", "UPGRADE_REQUIRED")
+ if (opts.list) { output({ success: await api.platformBot({ action: "list" }) }); return }
+ if (Buffer.byteLength(values.join(""), "utf8") > BOT_CREATION_BODY_MAX_BYTES) throw failure("Creation request is too large", "REQUEST_TOO_LARGE")
+ const bots = values.map((value, index) => {
+ try { return JSON.parse(value) as unknown } catch { throw failure("Invalid bot JSON", "INVALID_PROPOSAL", { itemIndex: index + 1 }) }
+ })
+ const parsed = BotCreationSubmitSchema.safeParse({ requestId: randomUUID(), bots })
+ if (!parsed.success) {
+ const issue = parsed.error.issues[0]!
+ const field = issue.path.at(-1)
+ const itemIndex = typeof issue.path[1] === "number" ? issue.path[1] + 1 : undefined
+ throw failure(issue.message, field === "reason" && issue.code === "too_small" ? "REASON_REQUIRED" : "INVALID_PROPOSAL", { ...(itemIndex ? { itemIndex } : {}), field })
+ }
+ if (Buffer.byteLength(JSON.stringify(parsed.data), "utf8") > BOT_CREATION_BODY_MAX_BYTES) throw failure("Creation request is too large", "REQUEST_TOO_LARGE")
+ output({ success: await api.platformBot({ action: "create", ...parsed.data }) })
+ })
+}
diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.ts
index 6b87cc67e..d8cb2d353 100644
--- a/src/daemon/src/cli/proxyServerApi.ts
+++ b/src/daemon/src/cli/proxyServerApi.ts
@@ -1,3 +1,4 @@
+import { type PlatformMachineRequest, type PlatformBotRequest } from "@alook/shared";
/**
* Proxy-routed `ServerApi` client — the agent's REAL data-plane path.
*
@@ -128,6 +129,8 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {
// without this the owner-mismatch hint never leaves this file (see
// plan's "Hint propagation" note).
if (json?.hint !== undefined) (e as { hint?: string }).hint = json.hint;
+ const safeFields = ["requestId", "machineId", "backendId", "itemIndex", "field", "required", "available", "status", "allowedValues"];
+ (e as Error & { platformDetails?: Record<string, unknown> }).platformDetails = Object.fromEntries(Object.entries(json ?? {}).filter(([key]) => safeFields.includes(key)));
throw e;
}
return json as T;
@@ -680,7 +683,29 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {
return { left: req.server, scope: "server" };
}
+ async function platformCall(path: string, method = "GET", body?: unknown): Promise<Record<string, unknown>> {
+ const response = await fetchImpl(`${base}/api/community${path}`, { method,
+ headers: { authorization: `Bearer ${config.voucher}`, ...(body === undefined ? {} : { "content-type": "application/json" }) },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+ return parseJsonResponse<Record<string, unknown>>(response, "platform");
+ }
+
+ async function callPlatformMachine(req: PlatformMachineRequest): Promise<Record<string, unknown>> {
+ 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)}` : ""}`);
+ }
+
+ async function callPlatformBot(req: PlatformBotRequest): Promise<Record<string, unknown>> {
+ if (req.action === "list") return platformCall("/bots");
+ return platformCall("/bots/creation-requests", "POST", { requestId: req.requestId, bots: req.bots });
+ }
+
return {
+ platformMachine: callPlatformMachine,
+ platformBot: callPlatformBot,
listServers: (_r: { agentId: AgentId }) => callListServers(),
joinServer: callJoinServer,
leaveServer: callLeaveServer,
diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.ts
index cfe680083..8e867f2d6 100644
--- a/src/daemon/src/credentials/credentialProxy.test.ts
+++ b/src/daemon/src/credentials/credentialProxy.test.ts
@@ -249,6 +249,33 @@ describe("startCredentialProxy (zero-trust end to end)", () => {
upstreamClose = undefined;
});
+ it("permits platform discovery and proposals but rejects machine management before forwarding", async () => {
+ const upstream = await startUpstream();
+ upstreamClose = upstream.close;
+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });
+ proxy = await startCredentialProxy(broker);
+ const reg = broker.mint("requester", "launch", ["read", "send"], REAL_KEY);
+ const allowed = [
+ ["GET", "/api/community/machines"],
+ ["GET", "/api/community/machines/m1"],
+ ["GET", "/api/community/machines/m1/models?runtimeId=codex"],
+ ["POST", "/api/community/machines/m1/discover-models"],
+ ["POST", "/api/community/bots/creation-requests"],
+ ];
+ for (const [method, path] of allowed) {
+ const response = await fetch(`${proxy.url}${path}`, { method, headers: { authorization: `Bearer ${reg.voucher}` } });
+ expect(response.status).toBe(200);
+ await response.text();
+ }
+ for (const [method, path] of [["DELETE", "/api/community/machines/m1"], ["POST", "/api/community/machines"], ["PATCH", "/api/community/machines/m1"], ["POST", "/api/community/machines/m1/restart"], ["GET", "/api/community/machines/m1/keys"]]) {
+ const response = await fetch(`${proxy.url}${path}`, { method, headers: { authorization: `Bearer ${reg.voucher}` } });
+ expect(response.status).toBe(403);
+ await response.text();
+ }
+ expect(upstream.seen).toHaveLength(allowed.length);
+ expect(upstream.seen.every(request => request.authorization === `Bearer ${REAL_KEY}`)).toBe(true);
+ });
+
it("consumes a valid reminder locally with voucher-derived identity and no audit/forward", async () => {
const upstream = await startUpstream();
upstreamClose = upstream.close;
diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.ts
index ab866dc59..c23c98106 100644
--- a/src/daemon/src/credentials/credentialProxy.ts
+++ b/src/daemon/src/credentials/credentialProxy.ts
@@ -250,6 +250,9 @@ function parseBearer(authHeader: string | undefined): string | null {
export type CapabilityResolver = (method: string, pathname: string) => Capability | undefined;
export const DEFAULT_CAPABILITY_RESOLVER: CapabilityResolver = (method, pathname) => {
+ if (pathname.startsWith("/api/community/machines")) return "read";
+ if (pathname === "/api/community/bots" && method === "GET") return "read";
+ if (pathname === "/api/community/bots/creation-requests" && method === "POST") return "send";
if (
((method === "GET" || method === "PATCH") && pathname === "/api/community/users/me/profile")
|| (method === "POST" && pathname === "/api/community/users/me/avatar")
@@ -586,7 +589,14 @@ export async function startCredentialProxy(
// Bot traffic has one canonical REST namespace. The deleted flat
// `/api/<verb>` surface must fail at this boundary rather than reaching an
// upstream that might accidentally grow a matching route later.
- const canonicalCommunityDoor = /^\/api\/community\/(channels|messages|servers|invites|friends|users|bots)(\/|$)/.test(pathname);
+ if (pathname.startsWith("/api/community/machines") && !(
+ (req.method === "GET" && /^\/api\/community\/machines(?:\/[^/]+(?:\/models)?)?$/.test(pathname))
+ || (req.method === "POST" && /^\/api\/community\/machines\/[^/]+\/discover-models$/.test(pathname))
+ )) {
+ writeJson(res, 403, { error: "Machine management is not available to bots", code: "forbidden" });
+ return;
+ }
+ const canonicalCommunityDoor = /^\/api\/community\/(channels|messages|servers|invites|friends|users|bots|machines)(\/|$)/.test(pathname);
if (pathname === "/api" || (pathname.startsWith("/api/") && !canonicalCommunityDoor)) {
res.writeHead(404, { "content-type": "application/json" });
res.end(JSON.stringify({ error: "unknown API route", code: "not_found" }));
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index 33991082e..8038e9fe3 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -159,6 +159,20 @@ function cliCommandsSection(): string {
`2. \`${CLI} friend list\` — list your friends and pending requests ` +
`(\`accepted\`, \`pendingOutgoing\`, \`pendingIncoming\`).`,
"",
+ "### Platform",
+ "",
+ "A machine is one of your owner's computers connected to Alook through its daemon. A backend is an AI runtime on that machine, such as Codex or Claude Code. A bot is an Alook account that belongs to your owner and runs with a selected machine and backend.",
+ "",
+ "Only submit a bot creation request when your owner explicitly asks you to. Do not request new bots on your own initiative, even though the owner must approve them later.",
+ "",
+ `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.`,
+ `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. ` +
+ `The command submits one approval card to the DM between you and your owner. It creates no bots until your human owner approves the request.`,
+ "",
"### Settings",
"",
`1. \`${CLI} setting profile --set-bio <text> --set-avatar <path>\` — update your public bio ` +
diff --git a/src/shared/src/community-bot-creation.ts b/src/shared/src/community-bot-creation.ts
new file mode 100644
index 000000000..903a3285f
--- /dev/null
+++ b/src/shared/src/community-bot-creation.ts
@@ -0,0 +1,66 @@
+import { z } from "zod"
+import { resolveReasoningEffort } from "./community/bot-reasoning-effort"
+import { requiresExplicitModel } from "./community/bot-model"
+import type { CommunityMachineRuntime } from "./schemas"
+import { CommunityBotCreateRequestSchema } from "./schemas"
+
+export const BOT_CREATION_MAX_ITEMS = 20
+export const BOT_CREATION_BODY_MAX_BYTES = 131072
+
+export const BotCreationProposalSchema = z.strictObject({
+ ...CommunityBotCreateRequestSchema.omit({ runtime: true, image: true }).shape,
+ backendId: z.string().min(1).max(64),
+ reason: z.string().trim().min(1).max(1000),
+})
+
+export const BotCreationSubmitSchema = z.strictObject({
+ requestId: z.string().min(1).max(128),
+ bots: z.array(BotCreationProposalSchema).min(1).max(BOT_CREATION_MAX_ITEMS),
+})
+
+export const BotCreationIdentitySchema = z.strictObject({
+ id: z.string(),
+ name: z.string(),
+ discriminator: z.string(),
+ image: z.string().nullable(),
+ avatarVersion: z.number().int().nonnegative(),
+})
+
+export const BotCreationItemSchema = BotCreationProposalSchema.extend({
+ itemId: z.string(),
+ description: z.string(),
+ model: z.string().nullable(),
+ reasoningEffort: z.string().nullable(),
+ machineName: z.string(),
+ createdBot: BotCreationIdentitySchema.nullable(),
+})
+
+export const BotCreationPayloadSchema = z.strictObject({
+ requestId: z.string(),
+ status: z.enum(["pending", "approved", "declined"]),
+ requesterId: z.string(),
+ ownerUserId: z.string(),
+ createdAt: z.string(),
+ resolvedAt: z.string().nullable(),
+ bots: z.array(BotCreationItemSchema).min(1).max(BOT_CREATION_MAX_ITEMS),
+})
+
+export const BotCreationDecisionSchema = z.strictObject({ decision: z.enum(["approve", "decline"]) })
+export type BotCreationProposal = z.infer<typeof BotCreationProposalSchema>
+export type BotCreationSubmit = z.infer<typeof BotCreationSubmitSchema>
+export type BotCreationItem = z.infer<typeof BotCreationItemSchema>
+export type BotCreationPayload = z.infer<typeof BotCreationPayloadSchema>
+
+export class BotCreationError extends Error {
+ constructor(public code: string, message: string, public status = 400, public details: Record<string, unknown> = {}) { super(message) }
+}
+
+export function resolveBotCreationConfiguration(machine: { id: string; status: string }, runtime: CommunityMachineRuntime | undefined, bot: Pick<BotCreationProposal, "backendId" | "model" | "reasoningEffort">) {
+ if (machine.status !== "online") throw new BotCreationError("MACHINE_OFFLINE", "Target machine is offline", 409, { machineId: machine.id })
+ if (!runtime) throw new BotCreationError("BACKEND_NOT_FOUND", `runtime ${bot.backendId} not available on this machine`)
+ if (runtime.status === "unhealthy") throw new BotCreationError("BACKEND_UNHEALTHY", `runtime ${bot.backendId} is currently unavailable on this machine — check the daemon logs`)
+ if (requiresExplicitModel(bot.backendId) && !bot.model?.trim()) throw new BotCreationError("MODEL_REQUIRED", "Choose a model before saving")
+ const effort = resolveReasoningEffort(runtime, bot.model ?? null, bot.reasoningEffort ?? null)
+ if (!effort.supported) throw new BotCreationError("INVALID_REASONING_EFFORT", `reasoning effort ${bot.reasoningEffort} is not supported by this runtime/model`, 400, { allowedValues: effort.options.map((option) => option.value) })
+ return effort
+}
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 5eab4c09f..87926873b 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -1,3 +1,4 @@
+import type { PlatformMachineRequest, PlatformBotRequest } from "./community-platform";
/**
* Server API contract — the agent ⇄ server boundary.
*
@@ -629,6 +630,8 @@ export interface FriendCard {
* messages by channel + seq. No structured Target or message id crosses the wire.
*/
export interface ServerApi {
+ platformMachine?(req: PlatformMachineRequest): Promise<Record<string, unknown>>;
+ platformBot?(req: PlatformBotRequest): Promise<Record<string, unknown>>;
/** Which servers/workspaces this agent participates in. */
listServers(req: { agentId: AgentId }): Promise<{ servers: Server[] }>;
diff --git a/src/shared/src/community-platform.ts b/src/shared/src/community-platform.ts
new file mode 100644
index 000000000..8cf4f5c78
--- /dev/null
+++ b/src/shared/src/community-platform.ts
@@ -0,0 +1,8 @@
+import type { BotCreationSubmit } from "./community-bot-creation"
+
+export type PlatformMachineRequest =
+ | { action: "list" }
+ | { action: "backends"; machineId: string }
+ | { action: "models"; machineId: string; backendId: string; model?: string; refresh?: boolean; requestId?: string }
+
+export type PlatformBotRequest = { action: "list" } | ({ action: "create" } & BotCreationSubmit)
diff --git a/src/shared/src/community-resources.ts b/src/shared/src/community-resources.ts
index d614950be..ac87822af 100644
--- a/src/shared/src/community-resources.ts
+++ b/src/shared/src/community-resources.ts
@@ -1,6 +1,7 @@
import { z } from "zod"
import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "./community-contract"
import { FriendApprovalPayloadSchema } from "./community-friend-approval"
+import { BotCreationPayloadSchema } from "./community-bot-creation"
const id = z.string().min(1)
const nullableId = id.nullable()
@@ -144,6 +145,7 @@ export const CommunityMessageResourceSchema = z.strictObject({
})).optional(),
thread: messageThreadSchema.optional(),
approval: FriendApprovalPayloadSchema.optional(),
+ botCreation: BotCreationPayloadSchema.optional(),
})
export const CommunityMessagePreviewSchema = CommunityMessageResourceSchema.partial().required({
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index 731d30002..d03142a60 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -2,6 +2,7 @@ import { z } from "zod"
import type { CommunityContract } from "./community-contract"
import { CommunityMachineSummarySchema, RuntimeModelDiscoveryResultSchema } from "./schemas"
import { FriendApprovalPayloadSchema } from "./community-friend-approval"
+import { BotCreationPayloadSchema } from "./community-bot-creation"
import { CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityMemberRelationSchema, CommunityResourceProfileSchema } from "./community-resources"
export { FriendApprovalPayloadSchema } from "./community-friend-approval"
@@ -24,7 +25,7 @@ const messageAttachmentSchema = z.strictObject({
const messageSchema = CommunityMessageResourceSchema.pick({
content: true, type: true, systemKind: true, authorAvatar: true, authorAvatarVersion: true,
- mentionType: true, embeds: true, createdAt: true, approval: true,
+ mentionType: true, embeds: true, createdAt: true, approval: true, botCreation: true,
}).extend({
id: string,
seq: z.number(),
@@ -53,8 +54,9 @@ const communityMessageUpdatedSchema = z.strictObject({
type: z.literal("community:message.updated"),
channelId: string,
messageId: string,
- approval: FriendApprovalPayloadSchema,
-})
+ approval: FriendApprovalPayloadSchema.optional(),
+ botCreation: BotCreationPayloadSchema.optional(),
+}).refine((event) => event.approval !== undefined || event.botCreation !== undefined)
const communityMessageEditedSchema = z.strictObject({
type: z.literal("community:message.edited"),
diff --git a/src/shared/src/db/bot-creation-schema.ts b/src/shared/src/db/bot-creation-schema.ts
new file mode 100644
index 000000000..c73157136
--- /dev/null
+++ b/src/shared/src/db/bot-creation-schema.ts
@@ -0,0 +1,17 @@
+import { index, sqliteTable, text } from "drizzle-orm/sqlite-core"
+import { user } from "./schema"
+import { communityMessage, communityChannel } from "./community-schema"
+import type { BotCreationItem } from "../community-bot-creation"
+
+export const communityBotCreationRequest = sqliteTable("community_bot_creation_request", {
+ id: text("id").primaryKey(),
+ requesterId: text("requester_id").notNull().references(() => user.id, { onDelete: "cascade" }),
+ ownerId: text("owner_id").notNull().references(() => user.id, { onDelete: "cascade" }),
+ channelId: text("channel_id").notNull().references(() => communityChannel.id, { onDelete: "cascade" }),
+ messageId: text("message_id").notNull().unique().references(() => communityMessage.id, { onDelete: "cascade" }),
+ status: text("status", { enum: ["pending", "approved", "declined"] }).notNull().default("pending"),
+ bots: text("bots", { mode: "json" }).$type<BotCreationItem[]>().notNull(),
+ decisionNonce: text("decision_nonce"),
+ createdAt: text("created_at").notNull(),
+ resolvedAt: text("resolved_at"),
+}, (t) => [index("idx_bot_creation_requester").on(t.requesterId, t.createdAt), index("idx_bot_creation_owner").on(t.ownerId, t.createdAt)])
diff --git a/src/shared/src/db/index.ts b/src/shared/src/db/index.ts
index 566f2029c..7f3e90660 100644
--- a/src/shared/src/db/index.ts
+++ b/src/shared/src/db/index.ts
@@ -5,8 +5,9 @@ import * as communityMachineSchema from "./community-machine-schema";
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";
-const allSchema = { ...schema, ...communitySchema, ...communityMachineSchema, ...productPlanSchema, ...billingSchema, ...communityFunnelAnalyticsSchema };
+const allSchema = { ...schema, ...communitySchema, ...communityMachineSchema, ...productPlanSchema, ...billingSchema, ...communityFunnelAnalyticsSchema, ...botCreationSchema };
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.ts
index 0a153b35e..834ade925 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -50,6 +50,7 @@ export * as communityAttention from "./queries/community/attention";
export * as communityMachine from "./queries/community/machine";
export * as communityMachineSession from "./queries/community/machine-session-epoch";
export * as communityBot from "./queries/community/bot";
+export * as communityBotCreation from "./queries/community/bot-creation";
export * as communityAgentInbox from "./queries/community/agent-inbox";
export * as communityBotAuditLog from "./queries/community/bot-audit-log";
export * as communityMessageTag from "./queries/community/message-tag";
diff --git a/src/shared/src/db/queries/community/bot-creation.ts b/src/shared/src/db/queries/community/bot-creation.ts
new file mode 100644
index 000000000..b8dd80e01
--- /dev/null
+++ b/src/shared/src/db/queries/community/bot-creation.ts
@@ -0,0 +1,128 @@
+import { and, eq, exists, inArray, isNull, or } from "drizzle-orm"
+import { nanoid } from "nanoid"
+import type { Database } from "../../index"
+import { communityBotCreationRequest as requests } from "../../bot-creation-schema"
+import { communityMachine } from "../../community-machine-schema"
+import { user } from "../../schema"
+import { BotCreationError, resolveBotCreationConfiguration, BotCreationPayloadSchema, type BotCreationItem, type BotCreationPayload, type BotCreationProposal, type BotCreationSubmit } from "../../../community-bot-creation"
+import { buildBotCreationStatements, getMachineForOwner, isBotEntitlementLimitError } from "./bot"
+import { getBotCapacitySummary } from "../product-plan"
+import { createOrGetDM } from "./dm"
+import { createMessage } from "./message"
+import { computeDiscriminator } from "../../../lib/discriminator"
+import { withUniqueDiscriminator } from "../user"
+import { jsonTextSet } from "../_json-set"
+
+export { BotCreationError } from "../../../community-bot-creation"
+
+export async function validateBotConfigurations(db: Database, ownerId: string, bots: readonly Pick<BotCreationProposal, "machineId" | "backendId" | "model" | "reasoningEffort">[]) {
+ const machines = new Map<string, Awaited<ReturnType<typeof getMachineForOwner>>>()
+ const resolved = []
+ for (const [index, bot] of bots.entries()) {
+ const details = { itemIndex: index + 1 }
+ if (!machines.has(bot.machineId)) machines.set(bot.machineId, await getMachineForOwner(db, bot.machineId, ownerId))
+ const machine = machines.get(bot.machineId)
+ if (!machine) throw new BotCreationError("MACHINE_NOT_FOUND", "machine not found", 404, details)
+ const runtime = machine.availableRuntimes.find((candidate) => candidate.id === bot.backendId)
+ let effort
+ try { effort = resolveBotCreationConfiguration(machine, runtime, bot) }
+ catch (error) {
+ if (error instanceof BotCreationError) error.details = { ...error.details, ...details }
+ throw error
+ }
+ resolved.push({ machine, reasoningEffort: effort.canonicalEffort })
+ }
+ return resolved
+}
+
+async function assertCapacity(db: Database, ownerId: string, required: number) {
+ const capacity = await getBotCapacitySummary(db, ownerId)
+ const available = Math.max(0, capacity.limit - capacity.ownedCount)
+ if (available < required) throw new BotCreationError("BOT_LIMIT_REACHED", "Not enough bot slots for this request", 409, { required, available, plan: capacity.plan.id, limit: capacity.limit, ownedCount: capacity.ownedCount, activeCount: capacity.activeCount })
+}
+
+async function assertRequester(db: Database, ownerId: string, requesterId: string) {
+ const rows = await db.select({ id: user.id }).from(user).where(and(eq(user.id, requesterId), eq(user.ownerUserId, ownerId), eq(user.isBot, true), isNull(user.deletedAt)))
+ const owners = await db.select({ id: user.id }).from(user).where(and(eq(user.id, ownerId), eq(user.isBot, false), isNull(user.deletedAt)))
+ if (!rows.length || !owners.length) throw new BotCreationError("REQUESTER_UNAVAILABLE", "Requesting bot or owner is unavailable", 409)
+}
+
+export function projectCreationRequest(row: typeof requests.$inferSelect): BotCreationPayload {
+ return BotCreationPayloadSchema.parse({ requestId: row.id, status: row.status, requesterId: row.requesterId, ownerUserId: row.ownerId,
+ createdAt: row.createdAt, resolvedAt: row.resolvedAt, bots: row.bots })
+}
+
+export async function getCreationRequest(db: Database, requestId: string, scope: { ownerId: string } | { requesterId: string }) {
+ const rows = await db.select().from(requests).where(and(eq(requests.id, requestId), "ownerId" in scope ? eq(requests.ownerId, scope.ownerId) : eq(requests.requesterId, scope.requesterId))).limit(1)
+ return rows[0] ?? null
+}
+
+
+export async function submitCreationRequest(db: Database, ownerId: string, requesterId: string, input: BotCreationSubmit) {
+ const existing = await getCreationRequest(db, input.requestId, { requesterId })
+ if (existing) return { row: existing, isNew: false }
+ await assertRequester(db, ownerId, requesterId)
+ await assertCapacity(db, ownerId, input.bots.length)
+ const configured = await validateBotConfigurations(db, ownerId, input.bots)
+ const bots: BotCreationItem[] = input.bots.map((bot, index) => ({ ...bot, itemId: nanoid(), description: bot.description ?? "", model: bot.model ?? null,
+ reasoningEffort: configured[index]!.reasoningEffort, machineName: configured[index]!.machine.displayName,
+ createdBot: null }))
+ const dm = await createOrGetDM(db, { userId1: ownerId, userId2: requesterId })
+ const messageId = nanoid()
+ const row: typeof requests.$inferInsert = { id: input.requestId, requesterId, ownerId, channelId: dm.id, messageId, status: "pending", bots, createdAt: new Date().toISOString(), resolvedAt: null, decisionNonce: null }
+ try {
+ await createMessage(db, { id: messageId, authorId: requesterId, channelId: dm.id, content: `Request to create ${bots.length} bot${bots.length === 1 ? "" : "s"}`, type: "bot_creation_request", clientNonce: `bot-creation:${input.requestId}`, extraStatements: [db.insert(requests).values(row)] })
+ } catch (error) {
+ const winner = await getCreationRequest(db, input.requestId, { requesterId })
+ if (winner) return { row: winner, isNew: false }
+ throw error
+ }
+ return { row: (await getCreationRequest(db, input.requestId, { requesterId }))!, isNew: true }
+}
+
+export async function decideCreationRequest(db: Database, ownerId: string, requestId: string, decision: "approve" | "decline") {
+ const row = await getCreationRequest(db, requestId, { ownerId })
+ if (!row) throw new BotCreationError("REQUEST_NOT_FOUND", "Creation request not found", 404)
+ if (row.status !== "pending") return { row, changed: false }
+ const pending = and(eq(requests.id, requestId), eq(requests.ownerId, ownerId), eq(requests.status, "pending"))
+ const now = new Date().toISOString()
+ if (decision === "decline") {
+ const changed = await db.update(requests).set({ status: "declined", resolvedAt: now }).where(pending).returning({ id: requests.id })
+ return { row: (await getCreationRequest(db, requestId, { ownerId }))!, changed: changed.length > 0 }
+ }
+ await assertRequester(db, ownerId, row.requesterId)
+ await assertCapacity(db, ownerId, row.bots.length)
+ const configured = await validateBotConfigurations(db, ownerId, row.bots)
+ const decisionNonce = nanoid()
+ const ids = row.bots.map((item) => item.itemId)
+ const initialSalt = computeDiscriminator(requestId)
+ try {
+ return await withUniqueDiscriminator(db, { id: requestId, name: "bot creation request" }, async (salt) => {
+ const bots: BotCreationItem[] = row.bots.map((item, index) => ({ ...item, reasoningEffort: configured[index]!.reasoningEffort,
+ machineName: configured[index]!.machine.displayName,
+ createdBot: { id: ids[index]!, name: item.name, discriminator: salt === initialSalt ? computeDiscriminator(ids[index]!) : computeDiscriminator(`${ids[index]}:${salt}`, salt.length), image: null, avatarVersion: 0 } }))
+ const validOwner = exists(db.select({ id: user.id }).from(user).where(and(eq(user.id, ownerId), eq(user.isBot, false), isNull(user.deletedAt))))
+ const validRequester = exists(db.select({ id: user.id }).from(user).where(and(eq(user.id, row.requesterId), eq(user.ownerUserId, ownerId), eq(user.isBot, true), isNull(user.deletedAt))))
+ const claim = db.update(requests).set({ status: "approved", bots, resolvedAt: now, decisionNonce }).where(and(pending, validOwner, validRequester)).returning({ id: requests.id })
+ const claimed = exists(db.select({ id: requests.id }).from(requests).where(and(eq(requests.id, requestId), eq(requests.ownerId, ownerId), eq(requests.status, "approved"), eq(requests.decisionNonce, decisionNonce))))
+ const statements = bots.flatMap((item) => {
+ const ownedMachine = exists(db.select({ id: communityMachine.id }).from(communityMachine).where(and(eq(communityMachine.id, item.machineId), eq(communityMachine.userId, ownerId), eq(communityMachine.status, "online"))))
+ return buildBotCreationStatements(db, { ownerId, name: item.name, description: item.description, machineId: item.machineId, runtime: item.backendId, modelName: item.model, reasoningEffort: item.reasoningEffort }, { botId: item.createdBot!.id, discriminator: item.createdBot!.discriminator, nowIso: now }, and(claimed, ownedMachine))
+ })
+ const results = await db.batch([claim, ...statements] as never)
+ return { row: (await getCreationRequest(db, requestId, { ownerId }))!, changed: (results[0] as Array<{ id: string }>).length > 0 }
+ })
+ } catch (error) {
+ const winner = await getCreationRequest(db, requestId, { ownerId })
+ if (winner?.status !== "pending" && winner) return { row: winner, changed: false }
+ if (isBotEntitlementLimitError(error)) await assertCapacity(db, ownerId, row.bots.length)
+ await validateBotConfigurations(db, ownerId, row.bots)
+ throw error
+ }
+}
+
+export async function hydrateCreationRequestsForDmMessages(db: Database, messageIds: string[], viewerId: string) {
+ if (!messageIds.length) return new Map<string, BotCreationPayload>()
+ const rows = await db.select().from(requests).where(and(inArray(requests.messageId, jsonTextSet(db, messageIds)), or(eq(requests.ownerId, viewerId), eq(requests.requesterId, viewerId))))
+ return new Map(rows.map((row) => [row.messageId, projectCreationRequest(row)]))
+}
diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.ts
index c4fdcfba8..e7b7e21a4 100644
--- a/src/shared/src/db/queries/community/bot.ts
+++ b/src/shared/src/db/queries/community/bot.ts
@@ -18,7 +18,7 @@
* return null / 404 at the route. The victim's state must be untouched.
*/
-import { aliasedTable, and, count, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, ne, notExists, or, sql } from "drizzle-orm";
+import { type SQL, aliasedTable, and, count, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, ne, notExists, or, sql } from "drizzle-orm";
import { user } from "../../schema";
import {
communityBotBinding,
@@ -1013,12 +1013,46 @@ export type CreateBotInput = {
* statements together so the binding/profile rows always land alongside the
* user row that actually won the discriminator. Returns the bot row.
*/
+export function buildBotCreationStatements(
+ db: Database,
+ data: CreateBotInput,
+ identity: { botId: string; discriminator: string; nowIso: string },
+ guard?: SQL,
+) {
+ const { botId, discriminator, nowIso } = identity;
+ const description = data.description ?? "";
+ return [
+ db.insert(user).values({
+ id: botId,
+ name: guard ? sql<string>`CASE WHEN ${guard} THEN ${data.name} ELSE NULL END` : data.name,
+ email: communityBotSyntheticEmail(botId),
+ emailVerified: true,
+ image: data.image ?? null,
+ isBot: true,
+ ownerUserId: data.ownerId,
+ discriminator,
+ createdAt: nowIso,
+ updatedAt: nowIso,
+ }),
+ db.insert(communityBotBinding).values({
+ userId: botId,
+ machineId: data.machineId,
+ runtime: data.runtime,
+ instruction: description,
+ modelName: data.modelName ?? null,
+ reasoningEffort: data.reasoningEffort ?? null,
+ createdAt: nowIso,
+ }),
+ db.insert(communityUserProfile).values({ userId: botId, aboutMe: description })
+ .onConflictDoUpdate({ target: communityUserProfile.userId, set: { aboutMe: description } }),
+ ];
+}
+
export async function createBot(
db: Database,
data: CreateBotInput
): Promise<{ botId: string; name: string; discriminator: string; description: string; image: string | null }> {
const botId = nanoid();
- const email = communityBotSyntheticEmail(botId);
const nowIso = new Date().toISOString();
const description = data.description ?? "";
@@ -1027,38 +1061,7 @@ export async function createBot(
{ id: botId, name: data.name },
async (discriminator) => {
// Three-statement batch. D1 rolls back all on any error.
- const stmt1 = db.insert(user).values({
- id: botId,
- name: data.name,
- email,
- emailVerified: true,
- image: data.image ?? null,
- isBot: true,
- ownerUserId: data.ownerId,
- discriminator,
- createdAt: nowIso,
- updatedAt: nowIso,
- });
- const stmt2 = db.insert(communityBotBinding).values({
- userId: botId,
- machineId: data.machineId,
- runtime: data.runtime,
- instruction: description,
- modelName: data.modelName ?? null,
- reasoningEffort: data.reasoningEffort ?? null,
- createdAt: nowIso,
- });
- // Match updateBot's upsert semantics — reincarnation paths (nanoid collision
- // aside, future flows that recycle a botId) shouldn't roll the batch back on
- // a profile PK conflict.
- const stmt3 = db
- .insert(communityUserProfile)
- .values({ userId: botId, aboutMe: description })
- .onConflictDoUpdate({
- target: communityUserProfile.userId,
- set: { aboutMe: description },
- });
- await db.batch([stmt1, stmt2, stmt3] as any);
+ await db.batch(buildBotCreationStatements(db, data, { botId, discriminator, nowIso }) as never);
return discriminator;
}
);
@@ -1547,11 +1550,15 @@ export async function getMachineForOwner(
ownerId: string
): Promise<{
id: string;
+ displayName: string;
+ status: string;
availableRuntimes: CommunityMachineRuntime[];
} | null> {
const rows = await db
.select({
id: communityMachine.id,
+ displayName: communityMachine.displayName,
+ status: communityMachine.status,
availableRuntimes: communityMachine.availableRuntimes,
})
.from(communityMachine)
@@ -1572,5 +1579,5 @@ export async function getMachineForOwner(
if (parsed.success) normalized.push(parsed.data);
}
}
- return { id: r.id, availableRuntimes: normalized };
+ return { id: r.id, displayName: r.displayName, status: r.status, availableRuntimes: normalized };
}
diff --git a/src/shared/src/db/queries/community/friendship.ts b/src/shared/src/db/queries/community/friendship.ts
index 9544a0f3e..a8cd9b372 100644
--- a/src/shared/src/db/queries/community/friendship.ts
+++ b/src/shared/src/db/queries/community/friendship.ts
@@ -6,6 +6,7 @@ import {
communityChannelMember,
} from "../../community-schema";
import { user } from "../../schema";
+import { communityBotBinding } from "../../community-machine-schema";
import type { Database } from "../../index";
import { isAccepted, isBlocked as isBlockedStatus } from "../../../utils/friendship";
import { WS_EVENTS } from "../../../community-ws-events";
@@ -18,6 +19,7 @@ import { createOrGetDM } from "./dm";
import { createMessage, listMessagesReferencingFriendship } from "./message";
import { nanoid } from "nanoid";
import { jsonTextSet } from "../_json-set";
+import { chunk, maxRowsPerInsert } from "../_chunk";
function newFriendshipId(): string {
return "fr_" + nanoid();
@@ -1306,6 +1308,30 @@ export async function cancelPendingRequest(
// ─── Sibling-bot auto-friendship ─────────────────────────────────────────────
+export async function ensureNewSiblingBotFriendships(db: Database, ownerId: string, newBotIds: readonly string[]) {
+ if (!newBotIds.length) return;
+ const siblings = await db.select({ id: user.id }).from(user).innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id)).where(and(eq(user.ownerUserId, ownerId), eq(user.isBot, true), isNull(user.deletedAt)));
+ const ids = siblings.map((bot) => bot.id);
+ const created = new Set(newBotIds);
+ if (!ids.some((id) => created.has(id))) return;
+ const existing = await db.select({ requesterId: communityFriendship.requesterId, addresseeId: communityFriendship.addresseeId }).from(communityFriendship).where(and(
+ inArray(communityFriendship.requesterId, jsonTextSet(db, ids)),
+ inArray(communityFriendship.addresseeId, jsonTextSet(db, ids)),
+ inArray(communityFriendship.status, ["pending", "accepted", "blocked"]),
+ ));
+ const connected = new Set(existing.map((pair) => [pair.requesterId, pair.addresseeId].sort().join(":")));
+ const now = nowIso();
+ const rows: (typeof communityFriendship.$inferInsert)[] = [];
+ for (const [index, a] of ids.entries()) for (const b of ids.slice(index + 1)) {
+ if ((!created.has(a) && !created.has(b)) || connected.has([a, b].sort().join(":"))) continue;
+ rows.push({ id: newFriendshipId(), requesterId: a, addresseeId: b, status: "accepted", needsOwnerApproval: null, resolvedAt: now, createdAt: now, updatedAt: now });
+ }
+ if (!rows.length) return;
+ const paramsPerRow = db.insert(communityFriendship).values(rows[0]!).onConflictDoNothing().toSQL().params.length;
+ const [first, ...rest] = chunk(rows, maxRowsPerInsert(paramsPerRow)).map((part) => db.insert(communityFriendship).values(part).onConflictDoNothing());
+ if (first) await db.batch([first, ...rest]);
+}
+
export type EnsureSiblingResult =
| { blocked: true }
| { blocked: false; friendshipId: string; wasCreated: boolean };
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index af3d8b543..2b6f4637c 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -727,6 +727,8 @@ export type {
} from "./community-server-rail";
export * as schema from "./db/schema";
export * as queries from "./db/queries-index";
+export { BotCreationError, resolveBotCreationConfiguration, BotCreationProposalSchema, BotCreationSubmitSchema, BotCreationPayloadSchema, BotCreationDecisionSchema, BOT_CREATION_MAX_ITEMS, BOT_CREATION_BODY_MAX_BYTES } from "./community-bot-creation";
+export type { BotCreationProposal, BotCreationSubmit, BotCreationItem, BotCreationPayload } from "./community-bot-creation";
export { communityServer, communityServerInvite, communityFriendship, communityServerMember, communityServerFolder, communityServerFolderItem, communityBotActivityEvent, communityBotDailyActivity, communityPushDevice } from "./db/community-schema";
// Logger
@@ -829,3 +831,5 @@ export * from "./community-resources";
export * from "./runtime-models-contract";
export { readBoundedJsonRequest } from "./http-json";
+
+export type { PlatformMachineRequest, PlatformBotRequest } from "./community-platform";
diff --git a/src/shared/src/runtime-config.ts b/src/shared/src/runtime-config.ts
index 0570a31ec..5cf72c8dc 100644
--- a/src/shared/src/runtime-config.ts
+++ b/src/shared/src/runtime-config.ts
@@ -45,6 +45,7 @@ export type ReasoningEffortOption = {
* models with no effort metadata use an empty options array.
*/
export type RuntimeReasoningCatalog = {
+ readonly catalogOrigin?: "native_report" | "adapter_suggestions";
readonly updateMode: "live_next_turn" | "context_preserving_restart" | "unsupported";
readonly defaultModelId?: string;
readonly models: readonly {
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index f8f1e5d35..f065f78de 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -875,6 +875,7 @@ const RuntimeReasoningModelSchema = z.object({
});
export const RuntimeReasoningCatalogSchema = z.object({
+ catalogOrigin: z.enum(["native_report", "adapter_suggestions"]).optional().catch(undefined),
updateMode: z.enum(["live_next_turn", "context_preserving_restart", "unsupported"]),
defaultModelId: z.string().min(1).max(100).optional().catch(undefined),
models: z
diff --git a/src/shared/test/queries/community-bot-creation.test.ts b/src/shared/test/queries/community-bot-creation.test.ts
new file mode 100644
index 000000000..57b02c470
--- /dev/null
+++ b/src/shared/test/queries/community-bot-creation.test.ts
@@ -0,0 +1,198 @@
+import { beforeEach, afterEach, describe, it, expect } from "vitest"
+import { readFileSync, readdirSync } from "node:fs"
+import Sqlite from "better-sqlite3"
+import { drizzle } from "drizzle-orm/better-sqlite3"
+import { getTableName } from "drizzle-orm"
+import { getTableConfig } from "drizzle-orm/sqlite-core"
+import { communityBotCreationRequest } from "../../src/db/bot-creation-schema"
+import type { Database } from "../../src/db"
+import { submitCreationRequest, decideCreationRequest, getCreationRequest, hydrateCreationRequestsForDmMessages } from "../../src/db/queries/community/bot-creation"
+import { ensureNewSiblingBotFriendships } from "../../src/db/queries/community/friendship"
+
+let sqlite: Sqlite.Database
+let db: Database
+let queryLog: { sql: string; params: unknown[] }[]
+const proposal = (name: string) => ({ name, machineId: "m1", backendId: "codex", model: "custom/model", reason: "Independent review" })
+const count = () => (sqlite.prepare('SELECT count(*) AS n FROM user WHERE isBot=1').get() as { n: number }).n
+beforeEach(() => {
+ sqlite = new Sqlite(":memory:")
+ sqlite.pragma("foreign_keys = ON")
+ const root = new URL("../../../web/migrations/", import.meta.url)
+ for (const file of readdirSync(root).filter((file) => file.endsWith(".sql")).sort()) sqlite.exec(readFileSync(new URL(file, root), "utf8"))
+ queryLog = []
+ const orm = drizzle(sqlite, { logger: { logQuery(sql, params) { queryLog.push({ sql, params }) } } })
+ db = orm as unknown as Database
+ ;(db as any).batch = async (statements: any[]) => sqlite.transaction(() => statements.map((statement) => sqlite.prepare(statement.toSQL().sql).reader ? statement.all() : statement.run()))()
+ sqlite.prepare('INSERT INTO user(id,name,email,emailVerified,createdAt,updatedAt,isBot,ownerUserId,discriminator) VALUES (?,?,?,?,?,?,?,?,?)').run("owner", "Owner", "[email protected]", 1, "now", "now", 0, null, "0001")
+ sqlite.prepare('INSERT INTO user(id,name,email,emailVerified,createdAt,updatedAt,isBot,ownerUserId,discriminator) VALUES (?,?,?,?,?,?,?,?,?)').run("requester", "Requester", "[email protected]", 1, "now", "now", 1, "owner", "0002")
+ sqlite.prepare('INSERT INTO community_machine(id,user_id,display_name,hostname,platform,arch,available_runtimes,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?)').run("m1", "owner", "Work Mac", "host", "darwin", "arm64", JSON.stringify([{ id: "codex", status: "healthy", reasoning: { updateMode: "live_next_turn", models: [{ id: "listed", supportedReasoningEfforts: [{ value: "high" }] }] } }]), "online", "now", "now")
+ sqlite.prepare('INSERT INTO community_bot_binding(user_id,machine_id,runtime,created_at) VALUES (?,?,?,?)').run("requester", "m1", "codex", "now")
+ sqlite.exec("UPDATE product_plan_entitlement SET value_json='10' WHERE entitlement_key='bots.max'")
+})
+afterEach(() => sqlite.close())
+
+describe("bot creation requests on real migrated SQLite", () => {
+ it("matches migrated foreign keys and lookup indexes, and enforces card identity and valid state", async () => {
+ const config = getTableConfig(communityBotCreationRequest)
+ 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() }
+ }).sort((a, b) => a.from.localeCompare(b.from))
+ const migrated = (sqlite.pragma("foreign_key_list(community_bot_creation_request)") as typeof declared).map(({ from, table, to, on_delete }) => ({ from, table, to, on_delete })).sort((a, b) => a.from.localeCompare(b.from))
+ expect(declared).toHaveLength(4)
+ expect(migrated).toEqual(declared)
+ expect(config.indexes.map((index) => index.config.name).sort()).toEqual(["idx_bot_creation_owner", "idx_bot_creation_requester"])
+ for (const index of config.indexes) {
+ const columns = index.config.columns.map((column) => "name" in column ? column.name : undefined)
+ expect(sqlite.pragma(`index_info(${index.config.name})`)).toEqual(columns.map((name, seqno) => expect.objectContaining({ name, seqno })))
+ }
+ const { row } = await submitCreationRequest(db, "owner", "requester", { requestId: "schema", bots: [proposal("A")] })
+ expect(() => sqlite.prepare("UPDATE community_bot_creation_request SET status='unknown' WHERE id=?").run(row.id)).toThrow(/CHECK/)
+ expect(() => sqlite.prepare("UPDATE community_bot_creation_request SET bots='invalid json' WHERE id=?").run(row.id)).toThrow(/CHECK/)
+ expect(() => sqlite.prepare("UPDATE community_bot_creation_request SET owner_id='missing' WHERE id=?").run(row.id)).toThrow(/FOREIGN KEY/)
+ expect(() => sqlite.prepare("INSERT INTO community_bot_creation_request SELECT 'duplicate',requester_id,owner_id,channel_id,message_id,status,bots,decision_nonce,created_at,resolved_at FROM community_bot_creation_request WHERE id=?").run(row.id)).toThrow(/UNIQUE/)
+ sqlite.prepare("DELETE FROM community_message WHERE id=?").run(row.messageId)
+ expect(await getCreationRequest(db, row.id, { requesterId: "requester" })).toBeNull()
+ expect(sqlite.pragma("foreign_key_check")).toEqual([])
+ })
+ it("returns the committed winner for concurrent submissions without duplicating the card or request", async () => {
+ const input = { requestId: "race", bots: [proposal("A")] }
+ const results = await Promise.all([submitCreationRequest(db, "owner", "requester", input), submitCreationRequest(db, "owner", "requester", input)])
+ expect(results.map((result) => result.isNew).sort()).toEqual([false, true])
+ expect(results[0]!.row).toEqual(results[1]!.row)
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_bot_creation_request").get()).toEqual({ n: 1 })
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_message").get()).toEqual({ n: 1 })
+ expect(count()).toBe(1)
+ })
+ it("propagates a failed submission with no winner and rolls back its card and request", async () => {
+ sqlite.exec("CREATE TRIGGER reject_request BEFORE INSERT ON community_bot_creation_request BEGIN SELECT RAISE(ABORT, 'request insert failed'); END")
+ await expect(submitCreationRequest(db, "owner", "requester", { requestId: "failed", bots: [proposal("A")] })).rejects.toThrow("request insert failed")
+ expect(await getCreationRequest(db, "failed", { requesterId: "requester" })).toBeNull()
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_message").get()).toEqual({ n: 0 })
+ expect(count()).toBe(1)
+ })
+ it("connects twenty new bots to twenty existing siblings within D1 query and parameter limits", async () => {
+ sqlite.exec("UPDATE product_plan_entitlement SET value_json='40' WHERE entitlement_key='bots.max'")
+ for (let index = 1; index < 20; index++) {
+ const id = `existing-${index}`
+ sqlite.prepare('INSERT INTO user(id,name,email,emailVerified,createdAt,updatedAt,isBot,ownerUserId,discriminator) VALUES (?,?,?,?,?,?,?,?,?)').run(id, id, `${id}@test.local`, 1, "now", "now", 1, "owner", "0001")
+ sqlite.prepare('INSERT INTO community_bot_binding(user_id,machine_id,runtime,created_at) VALUES (?,?,?,?)').run(id, "m1", "codex", "now")
+ }
+ await submitCreationRequest(db, "owner", "requester", { requestId: "max", bots: Array.from({ length: 20 }, (_, index) => proposal(`New ${index}`)) })
+ const result = await decideCreationRequest(db, "owner", "max", "approve")
+ const created = result.row.bots.map((item) => item.createdBot!.id)
+ expect(count()).toBe(40)
+ queryLog = []
+ await ensureNewSiblingBotFriendships(db, "owner", created)
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_friendship WHERE status='accepted'").get()).toEqual({ n: 590 })
+ expect(queryLog.length).toBeLessThanOrEqual(62)
+ expect(queryLog.every((query) => query.params.length <= 100)).toBe(true)
+ console.info(JSON.stringify({ case: "siblings-20-existing-20-new", sqlStatements: queryLog.length, maxBoundParameters: Math.max(...queryLog.map((query) => query.params.length)) }))
+ queryLog = []
+ await Promise.all([ensureNewSiblingBotFriendships(db, "owner", created), ensureNewSiblingBotFriendships(db, "owner", created)])
+ expect(sqlite.prepare('SELECT count(*) AS n FROM community_friendship').get()).toEqual({ n: 590 })
+ expect(queryLog.length).toBeLessThanOrEqual(4)
+ })
+ it("preserves blocked and pending pairs, permits terminal re-friending and excludes foreign or deleted bots", async () => {
+ await submitCreationRequest(db, "owner", "requester", { requestId: "pairs", bots: [proposal("A"), proposal("B")] })
+ const result = await decideCreationRequest(db, "owner", "pairs", "approve")
+ const [a, b] = result.row.bots.map((item) => item.createdBot!.id)
+ sqlite.prepare('INSERT INTO user(id,name,email,emailVerified,createdAt,updatedAt,isBot,ownerUserId,discriminator) VALUES (?,?,?,?,?,?,?,?,?)').run("other-owner", "Other owner", "[email protected]", 1, "now", "now", 0, null, "0001")
+ sqlite.prepare('INSERT INTO user(id,name,email,emailVerified,createdAt,updatedAt,isBot,ownerUserId,discriminator,deletedAt) VALUES (?,?,?,?,?,?,?,?,?,?)').run("foreign", "Foreign", "[email protected]", 1, "now", "now", 1, "other-owner", "0001", null)
+ sqlite.prepare('INSERT INTO user(id,name,email,emailVerified,createdAt,updatedAt,isBot,ownerUserId,discriminator,deletedAt) VALUES (?,?,?,?,?,?,?,?,?,?)').run("deleted", "Deleted", "[email protected]", 1, "now", "now", 1, "owner", "0001", "now")
+ for (const id of ["foreign", "deleted"]) sqlite.prepare('INSERT INTO community_bot_binding(user_id,machine_id,runtime,created_at) VALUES (?,?,?,?)').run(id, "m1", "codex", "now")
+ const insert = sqlite.prepare('INSERT INTO community_friendship(id,requester_id,addressee_id,status,created_at,updated_at) VALUES (?,?,?,?,?,?)')
+ insert.run("blocked", a, "requester", "blocked", "now", "now")
+ insert.run("pending", "requester", b, "pending", "now", "now")
+ insert.run("denied", b, a, "denied", "now", "now")
+ await Promise.all([ensureNewSiblingBotFriendships(db, "owner", [a!, b!, "foreign", "deleted"]), ensureNewSiblingBotFriendships(db, "owner", [a!, b!])])
+ expect(sqlite.prepare('SELECT status FROM community_friendship WHERE id=?').get("blocked")).toEqual({ status: "blocked" })
+ expect(sqlite.prepare('SELECT status FROM community_friendship WHERE id=?').get("pending")).toEqual({ status: "pending" })
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_friendship WHERE status='accepted'").get()).toEqual({ n: 1 })
+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_friendship WHERE requester_id IN ('foreign','deleted') OR addressee_id IN ('foreign','deleted')").get()).toEqual({ n: 0 })
+ expect(sqlite.prepare('SELECT count(*) AS n FROM community_friendship').get()).toEqual({ n: 4 })
+ })
+ it("stores one DM card for multiple proposals without creating or reserving bots", async () => {
+ const result = await submitCreationRequest(db, "owner", "requester", { requestId: "r1", bots: [proposal("A"), proposal("B")] })
+ expect(result.row.status).toBe("pending")
+ expect(result.row.bots[0]).not.toHaveProperty("machineStatus")
+ expect(count()).toBe(1)
+ expect(sqlite.prepare('SELECT count(*) AS n FROM community_message').get()).toEqual({ n: 1 })
+ expect(sqlite.prepare('SELECT count(*) AS n FROM community_bot_binding').get()).toEqual({ n: 1 })
+ expect((await hydrateCreationRequestsForDmMessages(db, [result.row.messageId], "owner")).get(result.row.messageId)?.ownerUserId).toBe("owner")
+ expect((await hydrateCreationRequestsForDmMessages(db, [result.row.messageId], "stranger")).size).toBe(0)
+ await submitCreationRequest(db, "owner", "requester", { requestId: "r1", bots: [proposal("A"), proposal("B")] })
+ expect(sqlite.prepare('SELECT count(*) AS n FROM community_message').get()).toEqual({ n: 1 })
+ })
+ it("approves all once, preserves custom models and keeps identity stable on repeated and concurrent decisions", async () => {
+ const pending = await submitCreationRequest(db, "owner", "requester", { requestId: "r1", bots: [proposal("A"), proposal("B")] })
+ const previewIds = pending.row.bots.map((item) => item.itemId)
+ const [a, b] = await Promise.all([decideCreationRequest(db, "owner", "r1", "approve"), decideCreationRequest(db, "owner", "r1", "approve")])
+ expect(a.row.status).toBe("approved")
+ expect(b.row.bots).toEqual(a.row.bots)
+ expect(a.row.bots.map((item) => item.createdBot!.id)).toEqual(previewIds)
+ expect(new Set(previewIds).size).toBe(2)
+ for (const id of previewIds) {
+ expect(sqlite.prepare('SELECT id,ownerUserId,image,avatarVersion FROM user WHERE id=?').get(id)).toEqual({ id, ownerUserId: "owner", image: null, avatarVersion: 0 })
+ expect(sqlite.prepare('SELECT machine_id FROM community_bot_binding WHERE user_id=?').get(id)).toEqual({ machine_id: "m1" })
+ }
+ expect(count()).toBe(3)
+ expect(sqlite.prepare("SELECT model_name FROM community_bot_binding WHERE user_id != 'requester'").all()).toEqual([{ model_name: "custom/model" }, { model_name: "custom/model" }])
+ expect((await decideCreationRequest(db, "owner", "r1", "decline")).row.status).toBe("approved")
+ expect(count()).toBe(3)
+ })
+ it("does not rewrite historical approved identities when their proposal IDs differ", async () => {
+ await submitCreationRequest(db, "owner", "requester", { requestId: "legacy", bots: [proposal("Legacy")] })
+ const approved = await decideCreationRequest(db, "owner", "legacy", "approve")
+ const legacyBots = approved.row.bots.map((item) => ({ ...item, itemId: "historical-preview-id" }))
+ sqlite.prepare('UPDATE community_bot_creation_request SET bots=? WHERE id=?').run(JSON.stringify(legacyBots), "legacy")
+ const before = sqlite.prepare('SELECT bots FROM community_bot_creation_request WHERE id=?').get("legacy")
+ const result = await decideCreationRequest(db, "owner", "legacy", "approve")
+ expect(result.changed).toBe(false)
+ expect(result.row.bots).toEqual(legacyBots)
+ expect(result.row.bots[0]!.createdBot!.id).toBe(approved.row.bots[0]!.createdBot!.id)
+ expect(sqlite.prepare('SELECT bots FROM community_bot_creation_request WHERE id=?').get("legacy")).toEqual(before)
+ expect(count()).toBe(2)
+ })
+ it("rolls back every bot and approval if a later item insert fails", async () => {
+ await submitCreationRequest(db, "owner", "requester", { requestId: "r1", bots: [proposal("A"), proposal("B")] })
+ sqlite.exec("CREATE TRIGGER reject_second BEFORE INSERT ON user WHEN NEW.name='B' BEGIN SELECT RAISE(ABORT, 'second item failed'); END")
+ await expect(decideCreationRequest(db, "owner", "r1", "approve")).rejects.toThrow("second item failed")
+ expect(count()).toBe(1)
+ expect((await getCreationRequest(db, "r1", { ownerId: "owner" }))?.status).toBe("pending")
+ expect(sqlite.prepare('SELECT count(*) AS n FROM community_bot_binding').get()).toEqual({ n: 1 })
+ })
+ it("rechecks capacity and leaves the entire request pending when insufficient", async () => {
+ await submitCreationRequest(db, "owner", "requester", { requestId: "r1", bots: [proposal("A"), proposal("B")] })
+ sqlite.exec("UPDATE product_plan_entitlement SET value_json='2' WHERE entitlement_key='bots.max'")
+ await expect(decideCreationRequest(db, "owner", "r1", "approve")).rejects.toMatchObject({ code: "BOT_LIMIT_REACHED" })
+ expect(count()).toBe(1)
+ expect((await getCreationRequest(db, "r1", { ownerId: "owner" }))?.status).toBe("pending")
+ })
+ it("denies cross-owner reads/decisions, and decline never creates", async () => {
+ await submitCreationRequest(db, "owner", "requester", { requestId: "r1", bots: [proposal("A")] })
+ expect(await getCreationRequest(db, "r1", { ownerId: "stranger" })).toBe(null)
+ await expect(decideCreationRequest(db, "stranger", "r1", "approve")).rejects.toMatchObject({ code: "REQUEST_NOT_FOUND" })
+ await decideCreationRequest(db, "owner", "r1", "decline")
+ expect((await decideCreationRequest(db, "owner", "r1", "approve")).row.status).toBe("declined")
+ expect(count()).toBe(1)
+ })
+ it("rejects offline submission and rechecks machine connectivity before approval", async () => {
+ sqlite.exec("UPDATE community_machine SET status='offline' WHERE id='m1'")
+ await expect(submitCreationRequest(db, "owner", "requester", { requestId: "offline", bots: [proposal("A")] })).rejects.toMatchObject({ code: "MACHINE_OFFLINE", details: { machineId: "m1", itemIndex: 1 } })
+ expect(sqlite.prepare('SELECT count(*) AS n FROM community_message').get()).toEqual({ n: 0 })
+ sqlite.exec("UPDATE community_machine SET status='online' WHERE id='m1'")
+ await submitCreationRequest(db, "owner", "requester", { requestId: "r1", bots: [proposal("A"), proposal("B")] })
+ sqlite.exec("UPDATE community_machine SET status='offline' WHERE id='m1'")
+ await expect(decideCreationRequest(db, "owner", "r1", "approve")).rejects.toMatchObject({ code: "MACHINE_OFFLINE" })
+ expect(count()).toBe(1)
+ expect((await getCreationRequest(db, "r1", { ownerId: "owner" }))?.status).toBe("pending")
+ })
+ it("rejects a stolen machine and per-model effort without any card", async () => {
+ sqlite.exec("UPDATE community_machine SET user_id='requester' WHERE id='m1'")
+ await expect(submitCreationRequest(db, "owner", "requester", { requestId: "r1", bots: [proposal("A")] })).rejects.toMatchObject({ code: "MACHINE_NOT_FOUND", details: { itemIndex: 1 } })
+ sqlite.exec("UPDATE community_machine SET user_id='owner' WHERE id='m1'")
+ await expect(submitCreationRequest(db, "owner", "requester", { requestId: "r1", bots: [{ ...proposal("A"), reasoningEffort: "high" }] })).rejects.toMatchObject({ code: "INVALID_REASONING_EFFORT" })
+ expect(sqlite.prepare('SELECT count(*) AS n FROM community_message').get()).toEqual({ n: 0 })
+ })
+})
diff --git a/src/web/migrations/0108_bot_creation_request.sql b/src/web/migrations/0108_bot_creation_request.sql
new file mode 100644
index 000000000..c71e2cdc1
--- /dev/null
+++ b/src/web/migrations/0108_bot_creation_request.sql
@@ -0,0 +1,14 @@
+CREATE TABLE community_bot_creation_request (
+ id TEXT PRIMARY KEY NOT NULL,
+ requester_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ owner_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ channel_id TEXT NOT NULL REFERENCES community_channel(id) ON DELETE CASCADE,
+ message_id TEXT NOT NULL UNIQUE REFERENCES community_message(id) ON DELETE CASCADE,
+ status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','approved','declined')),
+ bots TEXT NOT NULL CHECK (json_valid(bots)),
+ decision_nonce TEXT,
+ created_at TEXT NOT NULL,
+ resolved_at TEXT
+);
+CREATE INDEX idx_bot_creation_requester ON community_bot_creation_request(requester_id, created_at);
+CREATE INDEX idx_bot_creation_owner ON community_bot_creation_request(owner_id, created_at);
diff --git a/src/web/src/app/api/community/bots/creation-requests/[id]/route.ts b/src/web/src/app/api/community/bots/creation-requests/[id]/route.ts
new file mode 100644
index 000000000..9f9a745e6
--- /dev/null
+++ b/src/web/src/app/api/community/bots/creation-requests/[id]/route.ts
@@ -0,0 +1,29 @@
+import { queries, BotCreationDecisionSchema, WS_EVENTS } from "@alook/shared"
+import { getPrimaryDb } from "@/lib/db"
+import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"
+import { botCreationFailure, completeBotCreation } from "@/lib/community/bot-creation.server"
+import { broadcastToUserSafe } from "@/lib/community/fanout"
+
+export const PATCH = withCommunityActor(async (req, ctx) => {
+ if (ctx.actor.kind !== "human" || ctx.actor.isBot) return writeError("Only the human owner can decide", 403)
+ const [body, error] = await parseBody(req, BotCreationDecisionSchema)
+ if (error) return error
+ const db = getPrimaryDb(ctx.env.DB)
+ try {
+ const result = await queries.communityBotCreation.decideCreationRequest(db, ctx.actor.userId, ctx.params?.id as string, body.decision)
+ const botCreation = queries.communityBotCreation.projectCreationRequest(result.row)
+ if (result.changed && result.row.status === "approved") {
+ const owner = await queries.user.getUserPublic(db, ctx.actor.userId)
+ if (owner) await completeBotCreation(ctx.env, db, ctx.actor.userId, owner, result.row.bots.flatMap((item) => item.createdBot ? [{ ...item.createdBot, description: item.description, machineId: item.machineId }] : []))
+ }
+ if (result.changed) await broadcastToUserSafe(ctx.actor.userId, { type: WS_EVENTS.MESSAGE_UPDATED, channelId: result.row.channelId, messageId: result.row.messageId, botCreation })
+ return writeJSON({ botCreation })
+ } catch (error) {
+ if (error instanceof queries.communityBotCreation.BotCreationError) {
+ const current = await queries.communityBotCreation.getCreationRequest(db, ctx.params?.id as string, { ownerId: ctx.actor.userId })
+ return botCreationFailure(error, { requestId: ctx.params?.id, ...(current ? { status: current.status } : {}) })
+ }
+ return botCreationFailure(error)
+ }
+})
diff --git a/src/web/src/app/api/community/bots/creation-requests/route.test.ts b/src/web/src/app/api/community/bots/creation-requests/route.test.ts
new file mode 100644
index 000000000..0e9df039e
--- /dev/null
+++ b/src/web/src/app/api/community/bots/creation-requests/route.test.ts
@@ -0,0 +1,94 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const mocks = vi.hoisted(() => ({ actor: { kind: "bot", userId: "requester", ownerUserId: "owner", machineId: "machine", isActive: true } as Record<string, unknown>, submit: vi.fn(), get: vi.fn(), decide: vi.fn(), dispatch: vi.fn(), complete: vi.fn(), broadcast: vi.fn() }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({}) }))
+vi.mock("@/lib/middleware/community-actor", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/middleware/community-actor")>("@/lib/middleware/community-actor")
+ return { ...actual, withCommunityActor: (handler: (req: NextRequest, context: any) => unknown) => (req: NextRequest) => handler(req, { env: { DB: {} }, actor: mocks.actor, params: { id: "request" } }) }
+})
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return { ...actual, queries: { ...actual.queries, user: { ...actual.queries.user, getUserPublic: async () => ({ name: "Owner", discriminator: "0001" }) }, communityBotCreation: { ...actual.queries.communityBotCreation, submitCreationRequest: (...args: unknown[]) => mocks.submit(...args), getCreationRequest: (...args: unknown[]) => mocks.get(...args), decideCreationRequest: (...args: unknown[]) => mocks.decide(...args) } } }
+})
+vi.mock("@/lib/community/message-dispatcher", () => ({ dispatchCommittedMessage: (...args: unknown[]) => mocks.dispatch(...args) }))
+vi.mock("@/lib/community/fanout", () => ({ broadcastToUserSafe: (...args: unknown[]) => mocks.broadcast(...args) }))
+vi.mock("@/lib/community/bot-creation.server", async () => ({ ...await vi.importActual<typeof import("@/lib/community/bot-creation.server")>("@/lib/community/bot-creation.server"), completeBotCreation: (...args: unknown[]) => mocks.complete(...args) }))
+import { POST } from "./route"
+import { PATCH } from "./[id]/route"
+import { BotCreationError } from "@alook/shared"
+
+const item = { itemId: "item", name: "Reviewer", description: "Review sources", reason: "Independent review", machineId: "machine", machineName: "Work Mac", backendId: "codex", model: "custom/model", reasoningEffort: null, createdBot: null }
+const row = { id: "request", requesterId: "requester", ownerId: "owner", channelId: "dm", messageId: "card", status: "pending" as const, bots: [item], createdAt: "2026-10-22T00:00:00.000Z", resolvedAt: null, decisionNonce: null }
+const proposal = { name: "Reviewer", description: "Review sources", reason: "Independent review", machineId: "machine", backendId: "codex", model: "custom/model" }
+const request = (body: unknown, method = "POST") => new NextRequest("http://local/api/community/bots/creation-requests", { method, body: JSON.stringify(body) })
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.actor = { kind: "bot", userId: "requester", ownerUserId: "owner", machineId: "machine", isActive: true }
+ mocks.submit.mockResolvedValue({ row, isNew: true })
+ mocks.get.mockResolvedValue(row)
+})
+describe("bot creation request API authorization and envelopes", () => {
+ it("returns a typed submission failure without dispatching a card", async () => {
+ mocks.submit.mockRejectedValueOnce(new BotCreationError("MACHINE_OFFLINE", "Target machine is offline", 409, { machineId: "machine", itemIndex: 1 }))
+ const response = await POST(request({ requestId: "request", bots: [proposal] }))
+ expect(response.status).toBe(409)
+ expect(await response.json()).toEqual({ error: "Target machine is offline", code: "MACHINE_OFFLINE", machineId: "machine", itemIndex: 1 })
+ expect(mocks.dispatch).not.toHaveBeenCalled()
+ })
+ it("propagates unexpected decision failures without publishing an approval", async () => {
+ mocks.actor = { kind: "human", userId: "owner", isBot: false }
+ mocks.decide.mockRejectedValueOnce(new Error("decision storage unavailable"))
+ await expect(PATCH(request({ decision: "approve" }, "PATCH"))).rejects.toThrow("decision storage unavailable")
+ expect(mocks.complete).not.toHaveBeenCalled()
+ expect(mocks.broadcast).not.toHaveBeenCalled()
+ })
+ it("derives both identities from bot authentication and dispatches exactly one committed card", async () => {
+ const response = await POST(request({ requestId: "request", bots: [proposal] }))
+ expect(response.status).toBe(201)
+ expect(mocks.submit).toHaveBeenCalledWith(expect.anything(), "owner", "requester", { requestId: "request", bots: [proposal] })
+ expect(mocks.dispatch).toHaveBeenCalledWith(expect.anything(), "card")
+ expect(await response.json()).toMatchObject({ status: "pending", count: 1, cardMessageId: "card", dmRef: "/.dm/Owner#0001" })
+ mocks.submit.mockResolvedValue({ row, isNew: false })
+ await POST(request({ requestId: "request", bots: [proposal] }))
+ expect(mocks.dispatch).toHaveBeenCalledTimes(1)
+ })
+ it("rejects blank reasons and identity injection before writing", async () => {
+ const blank = await POST(request({ requestId: "request", bots: [proposal, { ...proposal, reason: " " }] }))
+ expect(blank.status).toBe(400)
+ expect(await blank.json()).toMatchObject({ code: "REASON_REQUIRED", itemIndex: 2, field: "reason" })
+ expect((await POST(request({ requestId: "request", bots: [proposal], ownerId: "stranger" }))).status).toBe(400)
+ expect(mocks.submit).not.toHaveBeenCalled()
+ })
+ it("denies human submission and bot approval without falling through", async () => {
+ mocks.actor = { kind: "human", userId: "owner", isBot: false }
+ expect((await POST(request({ requestId: "request", bots: [proposal] }))).status).toBe(403)
+ mocks.actor = { kind: "bot", userId: "requester", ownerUserId: "owner" }
+ expect((await PATCH(request({ decision: "approve" }, "PATCH"))).status).toBe(403)
+ expect(mocks.submit).not.toHaveBeenCalled()
+ expect(mocks.decide).not.toHaveBeenCalled()
+ })
+ it("publishes authoritative approval and only runs post-create effects for the winning decision", async () => {
+ mocks.actor = { kind: "human", userId: "owner", isBot: false }
+ const approved = { ...row, status: "approved", resolvedAt: row.createdAt, bots: [{ ...item, createdBot: { id: "newbot", name: item.name, discriminator: "0002", image: null, avatarVersion: 0 } }] }
+ mocks.decide.mockResolvedValue({ row: approved, changed: true })
+ const response = await PATCH(request({ decision: "approve" }, "PATCH"))
+ expect(response.status).toBe(200)
+ expect(mocks.decide).toHaveBeenCalledWith(expect.anything(), "owner", "request", "approve")
+ expect(mocks.complete).toHaveBeenCalledOnce()
+ expect(mocks.broadcast).toHaveBeenCalledWith("owner", expect.objectContaining({ type: "community:message.updated", channelId: "dm", messageId: "card", botCreation: expect.objectContaining({ status: "approved" }) }))
+ mocks.decide.mockResolvedValue({ row: approved, changed: false })
+ await PATCH(request({ decision: "approve" }, "PATCH"))
+ expect(mocks.complete).toHaveBeenCalledTimes(1)
+ expect(mocks.broadcast).toHaveBeenCalledTimes(1)
+ })
+ it("keeps useful capacity errors and does not claim approval or dispatch effects", async () => {
+ mocks.actor = { kind: "human", userId: "owner", isBot: false }
+ mocks.decide.mockRejectedValue(new BotCreationError("BOT_LIMIT_REACHED", "Not enough bot slots", 409, { required: 2, available: 1 }))
+ const response = await PATCH(request({ decision: "approve" }, "PATCH"))
+ expect(response.status).toBe(409)
+ expect(await response.json()).toMatchObject({ code: "BOT_LIMIT_REACHED", required: 2, available: 1 })
+ expect(mocks.complete).not.toHaveBeenCalled()
+ expect(mocks.broadcast).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/bots/creation-requests/route.ts b/src/web/src/app/api/community/bots/creation-requests/route.ts
new file mode 100644
index 000000000..cec4b54b2
--- /dev/null
+++ b/src/web/src/app/api/community/bots/creation-requests/route.ts
@@ -0,0 +1,28 @@
+import { queries, BotCreationSubmitSchema, BOT_CREATION_BODY_MAX_BYTES, readBoundedJsonRequest, formatHandle } from "@alook/shared"
+import { getPrimaryDb } from "@/lib/db"
+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"
+import { writeJSON } from "@/lib/middleware/helpers"
+import { botCreationFailure } from "@/lib/community/bot-creation.server"
+import { dispatchCommittedMessage } from "@/lib/community/message-dispatcher"
+
+export const POST = withCommunityActor(async (req, ctx) => {
+ const gate = requireBot(ctx.actor)
+ if (!gate.ok) return gate.response
+ const raw = await readBoundedJsonRequest(req, BOT_CREATION_BODY_MAX_BYTES)
+ if (!raw.ok && raw.reason === "oversized") return writeJSON({ error: "Creation request is too large", code: "REQUEST_TOO_LARGE" }, 413)
+ const parsed = BotCreationSubmitSchema.safeParse(raw.ok ? raw.value : null)
+ if (!parsed.success) {
+ const issue = parsed.error.issues[0]
+ const index = issue?.path[0] === "bots" && typeof issue.path[1] === "number" ? issue.path[1] + 1 : undefined
+ return writeJSON({ error: issue?.message ?? "Invalid creation proposal", code: issue?.path.at(-1) === "reason" && issue.code === "too_small" ? "REASON_REQUIRED" : "INVALID_PROPOSAL", ...(index ? { itemIndex: index } : {}), field: issue?.path.at(-1) }, 400)
+ }
+ const db = getPrimaryDb(ctx.env.DB)
+ try {
+ const result = await queries.communityBotCreation.submitCreationRequest(db, gate.bot.ownerUserId, gate.bot.userId, parsed.data)
+ if (result.isNew) await dispatchCommittedMessage(db, result.row.messageId)
+ const owner = await queries.user.getUserPublic(db, gate.bot.ownerUserId)
+ return writeJSON({ kind: "bot_creation_request", requestId: result.row.id, status: result.row.status, count: result.row.bots.length,
+ cardMessageId: result.row.messageId, dmRef: owner ? `/.dm/${formatHandle(owner.name, owner.discriminator)}` : null,
+ hint: "Your owner must approve this request in DM before any bots are created." }, result.isNew ? 201 : 200)
+ } catch (error) { return botCreationFailure(error) }
+})
diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.ts
index 5c208a6fa..c143e2338 100644
--- a/src/web/src/app/api/community/bots/route.test.ts
+++ b/src/web/src/app/api/community/bots/route.test.ts
@@ -1,6 +1,10 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
+import * as shared from "@alook/shared"
import { NextRequest } from "next/server"
+const mockResolveBotActor = vi.fn()
+vi.mock("@/lib/middleware/community-agent-runner-auth", () => ({ resolveBotActor: (...args: unknown[]) => mockResolveBotActor(...args) }))
+
const mockCountLiveBotsForOwner = vi.fn()
const mockGetMachineForOwner = vi.fn()
const mockCreateBot = vi.fn()
@@ -9,14 +13,14 @@ const mockPushBotEventToMachine = vi.fn()
const mockListBotsForOwner = vi.fn()
const mockGetBotDailyActivityForOwner = vi.fn()
const mockGetBotDailyTokenUsageForOwner = vi.fn()
-const mockEnsureSiblingBotFriendship = vi.fn()
+const mockEnsureNewSiblingBotFriendships = vi.fn()
const mockGetBotCapacitySummary = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
}))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})), getPrimaryDb: vi.fn(() => ({})) }))
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -36,7 +40,7 @@ vi.mock("@alook/shared", async () => {
getBotCapacitySummary: (...a: unknown[]) => mockGetBotCapacitySummary(...a),
},
communityFriendship: {
- ensureSiblingBotFriendship: (...a: unknown[]) => mockEnsureSiblingBotFriendship(...a),
+ ensureNewSiblingBotFriendships: (...a: unknown[]) => mockEnsureNewSiblingBotFriendships(...a),
},
user: {
getUserPublic: (...a: unknown[]) => mockGetUserPublic(...a),
@@ -100,15 +104,28 @@ describe("POST /api/community/bots — model", () => {
activeCount: 0,
})
mockGetMachineForOwner.mockResolvedValue({
- id: "mac1",
+ id: "mac1", status: "online",
availableRuntimes: [{ id: "claude", status: "healthy" }, { id: "codex", status: "healthy" }],
})
mockCreateBot.mockResolvedValue({ botId: "b1", name: "MyBot", discriminator: "0001", description: "", image: null })
mockGetUserPublic.mockResolvedValue({ id: "u1", name: "Owner", discriminator: "9999" })
mockListBotsForOwner.mockResolvedValue([{ id: "b1" }])
- mockEnsureSiblingBotFriendship.mockResolvedValue({ blocked: false })
+ mockEnsureNewSiblingBotFriendships.mockResolvedValue({ blocked: false })
})
+ it("propagates unexpected configuration failures before creating a bot", async () => {
+ const error = new Error("configuration unavailable")
+ vi.spyOn(shared, "resolveBotCreationConfiguration").mockImplementationOnce(() => { throw error })
+ await expect(POST(postReq(base()), ctx)).rejects.toThrow(error)
+ expect(mockCreateBot).not.toHaveBeenCalled()
+ })
+ it("rejects an offline machine on the existing human create path", async () => {
+ mockGetMachineForOwner.mockResolvedValue({ id: "mac1", status: "offline", availableRuntimes: [{ id: "claude", status: "healthy" }] })
+ const response = await POST(postReq(base()), ctx)
+ expect(response.status).toBe(409)
+ expect(await response.json()).toMatchObject({ code: "MACHINE_OFFLINE", machineId: "mac1" })
+ expect(mockCreateBot).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)
@@ -139,7 +156,7 @@ describe("POST /api/community/bots — model", () => {
})
it("creates the separately reported agy backend with its own default model", async () => {
- mockGetMachineForOwner.mockResolvedValue({ id: "mac1", availableRuntimes: [{ id: "agy", status: "healthy" }] })
+ mockGetMachineForOwner.mockResolvedValue({ id: "mac1", status: "online", availableRuntimes: [{ id: "agy", status: "healthy" }] })
const res = await POST(postReq(base(undefined, "agy")), ctx)
expect(res.status).toBe(201)
expect(mockCreateBot).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ runtime: "agy", modelName: null }))
@@ -165,7 +182,7 @@ describe("POST /api/community/bots — model", () => {
})
it("creates OpenCode with an explicit custom model absent from its catalog", async () => {
- mockGetMachineForOwner.mockResolvedValue({ id: "mac1", availableRuntimes: [{ id: "opencode", status: "healthy" }] })
+ mockGetMachineForOwner.mockResolvedValue({ id: "mac1", status: "online", availableRuntimes: [{ id: "opencode", status: "healthy" }] })
const res = await POST(postReq(base("provider/custom", "opencode")), ctx)
expect(res.status).toBe(201)
expect((await res.json()).bot.modelName).toBe("provider/custom")
@@ -178,16 +195,17 @@ describe("POST /api/community/bots — model", () => {
const res = await POST(postReq(base()), ctx)
expect(res.status).toBe(201)
- expect(mockEnsureSiblingBotFriendship).toHaveBeenCalledOnce()
- expect(mockEnsureSiblingBotFriendship).toHaveBeenCalledWith(
+ expect(mockEnsureNewSiblingBotFriendships).toHaveBeenCalledOnce()
+ expect(mockEnsureNewSiblingBotFriendships).toHaveBeenCalledWith(
expect.anything(),
- { botA: "b1", botB: "b2" },
+ "u1",
+ ["b1"],
)
})
it("still returns 201 when sibling auto-friendship fails", async () => {
mockListBotsForOwner.mockResolvedValue([{ id: "b1" }, { id: "b2" }])
- mockEnsureSiblingBotFriendship.mockRejectedValue(new Error("D1 unavailable"))
+ mockEnsureNewSiblingBotFriendships.mockRejectedValue(new Error("D1 unavailable"))
const res = await POST(postReq(base()), ctx)
@@ -259,7 +277,7 @@ describe("POST /api/community/bots — model", () => {
it("persists a supported capability-backed reasoning effort", async () => {
mockGetMachineForOwner.mockResolvedValue({
- id: "mac1",
+ id: "mac1", status: "online",
availableRuntimes: [{
id: "codex",
status: "healthy",
@@ -291,7 +309,7 @@ describe("POST /api/community/bots — model", () => {
it("rejects an explicit effort the selected model did not report", async () => {
mockGetMachineForOwner.mockResolvedValue({
- id: "mac1",
+ id: "mac1", status: "online",
availableRuntimes: [{
id: "codex",
status: "healthy",
@@ -321,6 +339,16 @@ describe("GET /api/community/bots — heatmap activity", () => {
})
})
+ it("projects the owner's bots for a runner without exposing private owner usage", async () => {
+ mockResolveBotActor.mockResolvedValueOnce({ kind: "bot", actor: { botUserId: "requester", ownerUserId: "owner", machineId: "m1", isActive: true } })
+ mockListBotsForOwner.mockResolvedValueOnce([{ id: "sibling", name: "Reviewer", discriminator: "0042", machineId: "m2", runtime: "codex", modelName: "custom/model", reasoningEffort: "high", isActive: true, presence: "online", dailyActivity: ["private"], description: "private" }])
+ const response = await GET(new NextRequest("http://localhost/api/community/bots", { headers: { Authorization: "Bearer crk_test_fixture" } }), ctx)
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({ bots: [{ id: "sibling", handle: "Reviewer#0042", name: "Reviewer", machineId: "m2", backendId: "codex", model: "custom/model", reasoningEffort: "high", isActive: true, presence: "online" }] })
+ expect(mockListBotsForOwner).toHaveBeenCalledWith({}, "owner")
+ expect(mockGetBotDailyActivityForOwner).not.toHaveBeenCalled()
+ expect(mockGetBotCapacitySummary).not.toHaveBeenCalled()
+ })
it("attaches each bot's 30-day dailyActivity from the batched owner read", async () => {
mockListBotsForOwner.mockResolvedValue([
{ id: "bot_1", name: "A", machineId: "m1", runtime: "claude", modelName: null },
diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.ts
index fdad366dc..743ff5afe 100644
--- a/src/web/src/app/api/community/bots/route.ts
+++ b/src/web/src/app/api/community/bots/route.ts
@@ -2,18 +2,25 @@ import { NextRequest } from "next/server"
import {
queries,
CommunityBotCreateRequestSchema,
- resolveReasoningEffort,
+ resolveBotCreationConfiguration,
+ BotCreationError,
requiresExplicitModel,
} from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { getDb, getPrimaryDb } from "@/lib/db"
+import { withCommunityActor } from "@/lib/middleware/community-actor"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"
-import { pushBotEventToMachine } from "@/lib/community/bot-push"
+import { completeBotCreation } from "@/lib/community/bot-creation.server"
import { readCommunityBots } from "@/lib/community/bots.server"
export { tokenUsageDayWindow } from "@/lib/community/bots.server"
-export const GET = withAuth(async (_req, ctx) => writeJSON(await readCommunityBots(getDb(ctx.env.DB), ctx.userId)))
+export const GET = withCommunityActor(async (_req, ctx) => {
+ if (ctx.actor.kind === "human") return writeJSON(await readCommunityBots(getDb(ctx.env.DB), ctx.actor.userId))
+ const bots = await queries.communityBot.listBotsForOwner(getDb(ctx.env.DB), ctx.actor.ownerUserId)
+ return writeJSON({ bots: bots.map((bot) => ({ id: bot.id, handle: `${bot.name}#${bot.discriminator}`, name: bot.name,
+ 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)
@@ -22,7 +29,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
return writeError("Choose a model before saving", 400)
}
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
let capacity = await queries.productPlan.getBotCapacitySummary(db, ctx.userId)
if (capacity.ownedCount >= capacity.limit) {
@@ -49,24 +56,12 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
// 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)
- if (!runtime) {
- return writeError(
- `runtime ${body.runtime} not available on this machine`,
- 400,
- )
- }
- if (runtime.status === "unhealthy") {
- return writeError(
- `runtime ${body.runtime} is currently unavailable on this machine — check the daemon logs`,
- 400,
- )
- }
-
const modelName = body.model ?? null
- const effort = body.reasoningEffort ?? null
- const effortResolution = resolveReasoningEffort(runtime, modelName, effort)
- if (effort !== null && !effortResolution.supported) {
- return writeError(`reasoning effort ${effort} is not supported by this runtime/model`, 400)
+ 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>>
@@ -104,40 +99,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const owner = await queries.user.getUserPublic(db, ctx.userId)
if (!owner) return writeError("owner not resolvable — retry after re-authenticating", 500)
- // Same-owner sibling auto-friendship fanout. After createBot commits, insert a
- // real accepted community_friendship row for every existing live sibling.
- // Idempotent (ON CONFLICT DO NOTHING) so a concurrent createBot race is
- // absorbed. A per-sibling failure never fails createBot — the
- // bot exists and is usable; siblings can reconcile via the CLI later.
- try {
- const siblings = await queries.communityBot.listBotsForOwner(db, ctx.userId)
- for (const sibling of siblings) {
- if (sibling.id === created.botId) continue
- try {
- await queries.communityFriendship.ensureSiblingBotFriendship(db, {
- botA: created.botId,
- botB: sibling.id,
- })
- } catch (err) {
- void err
- }
- }
- } catch {
- // listBotsForOwner failed — the bot is still usable; siblings reconcile
- // via the CLI. Nothing user-visible to fail here.
- }
-
- // Best-effort WS push — daemon may be offline. Cold-start warmup re-syncs
- // authoritative state on reconnect.
- await pushBotEventToMachine(ctx.env, body.machineId, {
- type: "bot:added",
- botId: created.botId,
- name: created.name,
- discriminator: created.discriminator,
- description: created.description || undefined,
- ownerName: owner.name,
- ownerDiscriminator: owner.discriminator,
- })
+ 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(
{
diff --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.ts
index 47cd295cf..260754057 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,13 +1,15 @@
import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
-const mocks = vi.hoisted(() => ({ machine: vi.fn(), dispatch: vi.fn() }))
-vi.mock("@/lib/db", () => ({ getDb: () => ({ db: true }) }))
+const mocks = vi.hoisted(() => ({ machine: vi.fn(), dispatch: vi.fn(), bot: vi.fn() }))
+vi.mock("@/lib/db", () => ({ getDb: () => ({ authDb: true }), getPrimaryDb: () => ({ db: true }) }))
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 } } }
})
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: {} } }) }))
+vi.mock("@/lib/middleware/community-agent-runner-auth", () => ({ resolveBotActor: mocks.bot }))
import { POST } from "./route"
const payload = { runtimeId: "codex", requestId: "request" }
const request = (body: unknown = payload) => new NextRequest("http://localhost/api/community/machines/machine/discover-models", { method: "POST", body: JSON.stringify(body) })
@@ -16,6 +18,7 @@ describe("model discovery owner route", () => {
vi.clearAllMocks()
mocks.machine.mockResolvedValue({ status: "online", availableRuntimes: [{ id: "codex" }] })
mocks.dispatch.mockResolvedValue(Response.json({ sent: 1, unsupported: 0 }))
+ mocks.bot.mockResolvedValue({ kind: "ok", actor: { botUserId: "requester", ownerUserId: "owner", machineId: "source", isActive: true } })
})
it("scopes lookup before dispatch and acknowledges the correlated request", async () => {
const response = await POST(request())
@@ -54,3 +57,41 @@ describe("model discovery owner route", () => {
expect(mocks.dispatch).not.toHaveBeenCalled()
})
})
+
+
+describe("bot model discovery error and dispatch contract", () => {
+ const botRequest = () => new NextRequest("http://localhost/api/community/machines/machine/discover-models", { method: "POST", headers: { authorization: "Bearer crk_synthetic" }, body: JSON.stringify(payload) })
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.bot.mockResolvedValue({ kind: "ok", actor: { botUserId: "requester", ownerUserId: "owner", machineId: "source", isActive: true } })
+ mocks.machine.mockResolvedValue({ status: "online", availableRuntimes: [{ id: "codex" }] })
+ mocks.dispatch.mockResolvedValue(Response.json({ sent: 1 }))
+ })
+ it("derives owner and requester from authentication and reuses the existing discovery request", async () => {
+ const response = await POST(botRequest(), { params: { id: "machine" } })
+ expect(response.status).toBe(202)
+ expect(mocks.machine).toHaveBeenCalledWith({ db: true }, "owner", "machine")
+ expect(JSON.parse(mocks.dispatch.mock.calls[0]?.[2].body)).toEqual(payload)
+ })
+ it.each([
+ [null, "MACHINE_NOT_FOUND", 404],
+ [{ status: "offline" }, "MACHINE_OFFLINE", 409],
+ [{ status: "online", availableRuntimes: [] }, "BACKEND_NOT_FOUND", 400],
+ ])("returns a structured machine validation failure %s", async (machine, code, status) => {
+ mocks.machine.mockResolvedValue(machine)
+ const response = await POST(botRequest(), { params: { id: "machine" } })
+ expect(response.status).toBe(status)
+ expect(await response.json()).toMatchObject({ code, machineId: "machine" })
+ expect(mocks.dispatch).not.toHaveBeenCalled()
+ })
+ it.each([
+ [{ sent: 0, unsupported: 1 }, "UPGRADE_REQUIRED", 409],
+ [{ sent: 0, unsupported: 0 }, "MACHINE_OFFLINE", 409],
+ [{ sent: "1" }, "DISCOVERY_UNAVAILABLE", 503],
+ ])("preserves dispatch failure codes at the API boundary %j", async (receipt, code, status) => {
+ mocks.dispatch.mockResolvedValue(Response.json(receipt))
+ const response = await POST(botRequest(), { params: { id: "machine" } })
+ expect(response.status).toBe(status)
+ expect(await response.json()).toMatchObject({ code, machineId: "machine" })
+ })
+})
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.ts
index 2a87bddb3..462b45582 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,32 +1,40 @@
import { queries, readBoundedJsonRequest, RuntimeModelDiscoveryRequestSchema } from "@alook/shared"
-import { getDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { getPrimaryDb } from "@/lib/db"
+import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
import { wsDoFetch } from "@/lib/broadcast"
-export const POST = withAuth(async (req, ctx) => {
+export const POST = withCommunityActor(async (req, ctx) => {
const id = ctx.params?.id as string
- const machine = await queries.communityMachine.getMachineByIdForUser(getDb(ctx.env.DB), ctx.userId, id)
- if (!machine) return writeError("machine not found", 404)
- if (machine.status !== "online") return writeError("MACHINE_OFFLINE", 409)
+ 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 writeError("invalid request", 400)
+ if (!payload.success) return failure("invalid request", 400)
if (!machine.availableRuntimes.some((runtime) => runtime.id === payload.data.runtimeId)) {
- return writeError("runtime not found", 400)
+ 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 writeError("model discovery unavailable", 503)
+ 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 writeError("model discovery unavailable", 503)
+ return failure("model discovery unavailable", 503)
}
if (receipt.sent > 0) return writeJSON({ dispatched: true, requestId: payload.data.requestId }, 202)
- return writeError(typeof receipt.unsupported === "number" && receipt.unsupported > 0 ? "UPGRADE_REQUIRED" : "MACHINE_OFFLINE", 409)
+ return failure(typeof receipt.unsupported === "number" && receipt.unsupported > 0 ? "UPGRADE_REQUIRED" : "MACHINE_OFFLINE", 409)
} catch {
- return writeError("model discovery unavailable", 503)
+ return failure("model discovery unavailable", 503)
}
})
diff --git a/src/web/src/app/api/community/machines/[id]/models/route.ts b/src/web/src/app/api/community/machines/[id]/models/route.ts
new file mode 100644
index 000000000..bcb6f1696
--- /dev/null
+++ b/src/web/src/app/api/community/machines/[id]/models/route.ts
@@ -0,0 +1,16 @@
+import { queries } from "@alook/shared"
+import { getPrimaryDb } from "@/lib/db"
+import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { writeJSON } from "@/lib/middleware/helpers"
+import { projectModelOptions } from "@/lib/community/machine-options.server"
+
+export const GET = withCommunityActor(async (req, ctx) => {
+ const ownerId = ctx.actor.kind === "bot" ? ctx.actor.ownerUserId : ctx.actor.userId
+ const machine = await queries.communityBot.getMachineForOwner(getPrimaryDb(ctx.env.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)
+ const query = new URL(req.url).searchParams
+ const runtime = machine.availableRuntimes.find((runtime) => runtime.id === query.get("backend"))
+ if (!runtime) return writeJSON({ error: "backend not found", code: "BACKEND_NOT_FOUND", machineId: machine.id, backendId: query.get("backend") }, 404)
+ return writeJSON(projectModelOptions(machine.id, runtime, query.get("model")))
+})
diff --git a/src/web/src/app/api/community/machines/[id]/route.test.ts b/src/web/src/app/api/community/machines/[id]/route.test.ts
index 53597b091..974860b08 100644
--- a/src/web/src/app/api/community/machines/[id]/route.test.ts
+++ b/src/web/src/app/api/community/machines/[id]/route.test.ts
@@ -5,6 +5,7 @@ const mockGetCloudflareContext = vi.fn()
const mockWaitUntil = vi.fn()
const mockMediaDelete = vi.fn()
const mockGetMachineByIdForUser = vi.fn()
+const mockGetMachineForOwner = vi.fn()
const mockListBotsBoundToMachine = vi.fn()
const mockGetBotOwnedBy = vi.fn()
const mockListBotServerMemberships = vi.fn()
@@ -20,7 +21,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: (...args: unknown[]) => mockGetCloudflareContext(...args),
}))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})), getPrimaryDb: vi.fn(() => ({})) }))
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -28,6 +29,7 @@ vi.mock("@alook/shared", async () => {
...actual,
queries: {
communityBot: {
+ getMachineForOwner: (...args: unknown[]) => mockGetMachineForOwner(...args),
getBotOwnedBy: (...args: unknown[]) => mockGetBotOwnedBy(...args),
listBotsBoundToMachine: (...args: unknown[]) => mockListBotsBoundToMachine(...args),
listBotServerMemberships: (...args: unknown[]) => mockListBotServerMemberships(...args),
@@ -74,7 +76,8 @@ vi.mock("@/lib/middleware/helpers", () => {
}
})
-import { DELETE } from "./route"
+import { DELETE, GET } from "./route"
+import { GET as modelOptionsGET } from "./models/route"
function request(cascade?: boolean) {
return new NextRequest("http://localhost/api/community/machines/m1", {
@@ -218,3 +221,33 @@ describe("DELETE /api/community/machines/[id]", () => {
})
})
})
+
+
+describe("platform target machine queries", () => {
+ it("returns a scoped 404 when the target does not belong to the caller", async () => {
+ mockGetMachineForOwner.mockResolvedValueOnce(null)
+ const response = await GET(new NextRequest("http://localhost/api/community/machines/m1"), ctx)
+ expect(response.status).toBe(404)
+ expect(await response.json()).toEqual({ error: "machine not found", code: "MACHINE_NOT_FOUND", machineId: "m1" })
+ expect(mockGetMachineForOwner).toHaveBeenLastCalledWith({}, "m1", "u1")
+ })
+ it("projects backend health and catalog provenance only for an online owned machine", async () => {
+ mockGetMachineForOwner.mockResolvedValueOnce({ id: "m1", status: "online", availableRuntimes: [{ id: "codex", version: "1.0", status: "healthy", reasoning: { catalogOrigin: "native_report" } }, { id: "opencode", status: "unhealthy" }] })
+ const response = await GET(new NextRequest("http://localhost/api/community/machines/m1"), ctx)
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({ machineId: "m1", status: "online", backends: [{ id: "codex", version: "1.0", health: "healthy", modelRequired: false, catalogState: "reported", catalogOrigin: "native_report" }, { id: "opencode", health: "unhealthy", modelRequired: true, catalogState: "not_reported", catalogOrigin: "unknown" }] })
+ })
+ it.each([GET, modelOptionsGET])("rejects an offline target instead of returning cached capabilities", async (handler) => {
+ mockGetMachineForOwner.mockResolvedValue({ id: "m1", status: "offline", availableRuntimes: [{ id: "codex", status: "healthy" }] })
+ const response = await handler(new NextRequest("http://localhost/api/community/machines/m1/models?backend=codex"), ctx)
+ expect(response.status).toBe(409)
+ expect(await response.json()).toEqual({ error: "Target machine is offline", code: "MACHINE_OFFLINE", machineId: "m1" })
+ expect(mockGetMachineForOwner).toHaveBeenLastCalledWith({}, "m1", "u1")
+ })
+ it("reads model-specific effort from an owned online machine without replacing custom IDs", async () => {
+ mockGetMachineForOwner.mockResolvedValue({ id: "m1", status: "online", availableRuntimes: [{ id: "codex", status: "healthy", reasoning: { catalogOrigin: "native_report", models: [{ id: "provider/model", supportedReasoningEfforts: [{ value: "high" }] }] } }] })
+ const response = await modelOptionsGET(new NextRequest("http://localhost/api/community/machines/m1/models?backend=codex&model=provider%2Fmodel"), ctx)
+ expect(response.status).toBe(200)
+ expect(await response.json()).toMatchObject({ catalogOrigin: "native_report", inCatalog: true, model: { id: "provider/model", reasoningEfforts: [{ value: "high" }] } })
+ })
+})
diff --git a/src/web/src/app/api/community/machines/[id]/route.ts b/src/web/src/app/api/community/machines/[id]/route.ts
index 3f606e638..62fb2e2ce 100644
--- a/src/web/src/app/api/community/machines/[id]/route.ts
+++ b/src/web/src/app/api/community/machines/[id]/route.ts
@@ -1,3 +1,6 @@
+import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { getPrimaryDb } from "@/lib/db"
+import { requiresExplicitModel } from "@alook/shared"
import { NextRequest, NextResponse } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { queries, WS_EVENTS } from "@alook/shared"
@@ -109,3 +112,15 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {
return new NextResponse(null, { status: 204 })
})
+
+export const GET = withCommunityActor(async (_req, ctx) => {
+ const db = getPrimaryDb(ctx.env.DB)
+ const ownerId = ctx.actor.kind === "bot" ? ctx.actor.ownerUserId : ctx.actor.userId
+ 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",
+ })) })
+})
diff --git a/src/web/src/app/api/community/machines/route.ts b/src/web/src/app/api/community/machines/route.ts
index efa12278c..9db218e52 100644
--- a/src/web/src/app/api/community/machines/route.ts
+++ b/src/web/src/app/api/community/machines/route.ts
@@ -1,14 +1,16 @@
import { readCommunityMachines, readCommunityMachineList, readCommunityMachineObservations } from "@/lib/community/machines.server"
import { queries } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { withAuth } from "@/lib/middleware/auth"
+import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { readPlatformMachines } from "@/lib/community/machine-options.server"
import { writeJSON } from "@/lib/middleware/helpers"
-export const GET = withAuth(async (req, ctx) => {
+export const GET = withCommunityActor(async (req, ctx) => {
const db = getPrimaryDb(ctx.env.DB)
+ if (ctx.actor.kind === "bot") return writeJSON(await readPlatformMachines(db, ctx.actor.ownerUserId, ctx.actor.machineId))
try {
const view = new URL(req.url).searchParams.get("view")
- return writeJSON(await (view === "list" ? readCommunityMachineList(db, ctx.userId) : view === "observations" ? readCommunityMachineObservations(db, ctx.userId) : readCommunityMachines(db, ctx.userId)))
+ return writeJSON(await (view === "list" ? readCommunityMachineList(db, ctx.actor.userId) : view === "observations" ? readCommunityMachineObservations(db, ctx.actor.userId) : readCommunityMachines(db, ctx.actor.userId)))
} catch (error) {
if (error instanceof queries.productPlan.ProductEntitlementUnavailableError) {
return writeJSON({ error: "MACHINE_LIMIT_UNAVAILABLE" }, 503)
diff --git a/src/web/src/app/c/QueryProvider.bots-document.dom.test.tsx b/src/web/src/app/c/QueryProvider.bots-document.dom.test.tsx
index 64f6eff91..ce492574d 100644
--- a/src/web/src/app/c/QueryProvider.bots-document.dom.test.tsx
+++ b/src/web/src/app/c/QueryProvider.bots-document.dom.test.tsx
@@ -22,6 +22,7 @@ vi.mock("@/components/community/billing/billing-sheet", () => ({ BillingSheet: (
vi.mock("@/components/community/onboarding-tiles/create-tile", () => ({ CreateTile: () => React.createElement("div") }))
import { readCommunityDocumentSeed } from "@/lib/community/document-seed.server"
import { QueryProvider } from "@/app/c/QueryProvider"
+import { CurrentUserProvider } from "@/contexts/community/current-user"
import { BotList } from "@/components/community/bots/bot-list"
const profile = { id: "viewer", name: "Viewer", discriminator: "0042", avatar: "/avatar", avatarVersion: 1, aboutMe: "", bannerColor: null, statusEmoji: null, statusText: "" }
const bots = { bots: [], plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 0, activeCount: 0 }
@@ -46,7 +47,7 @@ it("keeps actual empty Bots heading and CTA stable through native provider resto
React.useLayoutEffect(() => { registry = owner; restoring = phase }, [owner, phase])
return <BotList />
}
- const view = render(<QueryProvider userId="viewer" initialSeed={seed}><Probe /></QueryProvider>)
+ const view = render(<QueryProvider userId="viewer" initialSeed={seed}><CurrentUserProvider initialUser={{ ...profile, email: "[email protected]" }}><Probe /></CurrentUserProvider></QueryProvider>)
const sample = () => ({ heading: view.container.querySelector("h2")?.textContent, button: Array.from(view.container.querySelectorAll("button")).find(button => /machine|bot/i.test(button.textContent ?? ""))?.textContent })
try {
expect(restoring).toBe(true)
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index 4a282ef42..aed2da0ea 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -57,6 +57,7 @@
--color-status-offline: var(--status-offline);
--color-destructive: var(--destructive);
--color-warning: var(--warning);
+ --color-approval-pass: var(--approval-pass);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
@@ -489,6 +490,7 @@ body.driver-active .community-ws-reconnect-overlay * {
--link: oklch(0.5 0.18 270);
--destructive: oklch(0.577 0.245 27.325);
--warning: oklch(0.62 0.11 75);
+ --approval-pass: oklch(0.45 0.12 155);
--border: oklch(0.86 0.01 80);
--input: oklch(0.86 0.01 80);
--ring: oklch(0.55 0.03 230);
@@ -545,6 +547,7 @@ body.driver-active .community-ws-reconnect-overlay * {
--link: oklch(0.75 0.14 270);
--destructive: oklch(0.704 0.191 22.216);
--warning: oklch(0.76 0.1 75);
+ --approval-pass: oklch(0.8 0.14 155);
--border: oklch(1 0.005 80 / 10%);
--input: oklch(1 0.005 80 / 15%);
--ring: oklch(0.55 0.01 60);
diff --git a/src/web/src/components/community/bots/bot-list-card.dom.test.ts b/src/web/src/components/community/bots/bot-list-card.dom.test.ts
index dc44cdbd3..8dd7bf1e9 100644
--- a/src/web/src/components/community/bots/bot-list-card.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-list-card.dom.test.ts
@@ -32,6 +32,8 @@ vi.mock("@/hooks/community/use-bots", () => ({
useResetBotSession: () => ({ mutateAsync: vi.fn(), isPending: false }),
useResetMachineAgents: () => ({ mutateAsync: vi.fn(), isPending: false }),
}))
+vi.mock("@/contexts/community/current-user", () => ({ useCurrentUser: () => ({ id: "viewer", name: "Viewer", avatar: "V" }) }))
+vi.mock("@/hooks/community/use-dm-message-sender", () => ({ useDmMessageSender: () => ({ accept: vi.fn() }) }))
vi.mock("@/hooks/community/mutations", () => ({
useCreateOrGetDm: () => ({ mutateAsync: vi.fn() }),
}))
diff --git a/src/web/src/components/community/bots/bot-list-controller.dom.test.ts b/src/web/src/components/community/bots/bot-list-controller.dom.test.ts
index ed7a142c6..6b2ef6075 100644
--- a/src/web/src/components/community/bots/bot-list-controller.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-list-controller.dom.test.ts
@@ -44,6 +44,7 @@ const mocks = vi.hoisted(() => ({
push: vi.fn(),
replace: vi.fn(),
createDm: vi.fn(),
+ acceptDm: vi.fn(),
del: vi.fn(),
resetBot: vi.fn(),
resetMachine: vi.fn(),
@@ -126,6 +127,8 @@ vi.mock("@/hooks/community/mutations", () => ({
return { mutateAsync: mocks.createDm }
},
}))
+vi.mock("@/contexts/community/current-user", () => ({ useCurrentUser: () => ({ id: "viewer", name: "Viewer", avatar: "V" }) }))
+vi.mock("@/hooks/community/use-dm-message-sender", () => ({ useDmMessageSender: () => ({ accept: mocks.acceptDm }) }))
vi.mock("@/lib/community-onboarding", () => ({
useCommunityOnboarding: () => {
mocks.hookOrder.push("onboarding")
@@ -256,6 +259,7 @@ describe("useBotListController", () => {
mocks.actionState = null
mocks.onProbeLayout = null
mocks.createDm.mockResolvedValue({ conversation: { id: "dm1" } })
+ mocks.acceptDm.mockReturnValue({ accepted: true, committed: Promise.resolve({ ok: true, message: { id: "msg1", seq: 1 } }) })
mocks.del.mockResolvedValue(undefined)
mocks.resetBot.mockResolvedValue({ ok: true })
mocks.resetMachine.mockResolvedValue({ dispatched: 2 })
@@ -790,6 +794,100 @@ describe("useBotListController", () => {
expect(latest.createOpen).toBe(false)
})
+ it("asks the first online active bot and accepts the message before navigation", async () => {
+ mocks.bots = [bot("offline", "mac1"), { ...bot("inactive", "mac1"), isActive: false }, bot("online", "mac2"), bot("later", "mac2")]
+ mocks.online = new Set(["inactive", "online", "later"])
+ render()
+ act(() => latest.setCreateOpen(true))
+ await act(async () => { await latest.askBotToCreate() })
+ expect(latest.createOpen).toBe(false)
+ expect(mocks.createDm).toHaveBeenCalledWith({ userId: "online", assertActive: expect.any(Function) })
+ expect(mocks.acceptDm).toHaveBeenCalledWith(expect.objectContaining({ dmId: "dm1", content: "Help me create a bot. Ask me what I need.", author: expect.objectContaining({ id: expect.any(String) }) }))
+ expect(mocks.acceptDm.mock.invocationCallOrder[0]).toBeLessThan(mocks.push.mock.invocationCallOrder[0])
+ expect(mocks.push).toHaveBeenCalledWith("/c/me/dm1")
+ expect(latest.startingBotChat).toBe(false)
+ })
+
+ it("falls back to the first offline bot and does nothing with no bots", async () => {
+ mocks.bots = [bot("first", "mac1"), bot("second", "mac1")]
+ render()
+ await act(async () => { await latest.askBotToCreate() })
+ expect(mocks.createDm).toHaveBeenCalledWith(expect.objectContaining({ userId: "first" }))
+ mocks.bots = []
+ render()
+ await act(async () => { await latest.askBotToCreate() })
+ expect(mocks.createDm).toHaveBeenCalledOnce()
+ expect(mocks.acceptDm).toHaveBeenCalledOnce()
+ })
+
+ it("blocks rapid repeat clicks until the accepted send settles", async () => {
+ let finish!: (value: unknown) => void
+ mocks.acceptDm.mockReturnValue({ accepted: true, committed: new Promise(resolve => { finish = resolve }) })
+ render()
+ let first!: Promise<void>
+ await act(async () => { first = latest.askBotToCreate(); await latest.askBotToCreate() })
+ expect(latest.startingBotChat).toBe(true)
+ expect(mocks.createDm).toHaveBeenCalledOnce()
+ expect(mocks.acceptDm).toHaveBeenCalledOnce()
+ await act(async () => { await latest.askBotToCreate(); finish({ ok: true }); await first })
+ expect(mocks.createDm).toHaveBeenCalledOnce()
+ expect(latest.startingBotChat).toBe(false)
+ })
+
+ it("allows a new attempt after DM failure without sending or navigating", async () => {
+ mocks.createDm.mockRejectedValueOnce(new Error("offline"))
+ render()
+ act(() => latest.setCreateOpen(true))
+ await act(async () => { await latest.askBotToCreate() })
+ expect(latest.createOpen).toBe(true)
+ expect(mocks.acceptDm).not.toHaveBeenCalled()
+ expect(mocks.push).not.toHaveBeenCalled()
+ expect(mocks.toastApiError).toHaveBeenCalledWith(expect.any(Error), "Failed to start bot creation chat", expect.any(Function))
+ expect(latest.startingBotChat).toBe(false)
+ await act(async () => { await latest.askBotToCreate() })
+ expect(mocks.acceptDm).toHaveBeenCalledOnce()
+ })
+
+ it("does not navigate if the send intent is rejected", async () => {
+ mocks.acceptDm.mockReturnValueOnce({ accepted: false })
+ render()
+ await act(async () => { await latest.askBotToCreate() })
+ expect(mocks.push).not.toHaveBeenCalled()
+ expect(mocks.toastApiError).toHaveBeenCalled()
+ expect(latest.startingBotChat).toBe(false)
+ })
+
+ it("does not send when another navigation starts while the DM opens", async () => {
+ let finish!: (value: unknown) => void
+ mocks.createDm.mockReturnValueOnce(new Promise(resolve => { finish = resolve }))
+ let navigation!: ReturnType<typeof useCommunityNavigationController>
+ const frame = { ...normalizeCommunityHref("/c/me/bots"), revision: 0 }
+ function Scenario() {
+ const currentNavigation = useCommunityNavigationController(frame)
+ React.useLayoutEffect(() => { navigation = currentNavigation }, [currentNavigation])
+ return React.createElement(CommunityRouteContext, { value: { frame, navigation: currentNavigation, breakpoint: "desktop", ownerDeleteRouteScope: undefined } }, React.createElement(Probe))
+ }
+ rtlRender(React.createElement(Scenario))
+ let task!: Promise<void>
+ act(() => { task = latest.askBotToCreate() })
+ act(() => navigation.pushImmediate("/c/me/friends"))
+ await act(async () => { finish({ conversation: { id: "dm1" } }); await task })
+ expect(mocks.acceptDm).not.toHaveBeenCalled()
+ expect(navigation.pendingHref).toBe("/c/me/friends")
+ })
+
+ it("does not accept or navigate when the source view retires during DM creation", async () => {
+ let finish!: (value: unknown) => void
+ mocks.createDm.mockReturnValueOnce(new Promise(resolve => { finish = resolve }))
+ const view = render()
+ let task!: Promise<void>
+ act(() => { task = latest.askBotToCreate() })
+ view.unmount()
+ await act(async () => { finish({ conversation: { id: "dm1" } }); await task })
+ expect(mocks.acceptDm).not.toHaveBeenCalled()
+ expect(mocks.push).not.toHaveBeenCalled()
+ })
+
it("opens normal chat on success and reports exact failure without navigation", async () => {
mocks.target = null
render()
diff --git a/src/web/src/components/community/bots/bot-list-controller.ts b/src/web/src/components/community/bots/bot-list-controller.ts
index 96bef3edc..723cdbfff 100644
--- a/src/web/src/components/community/bots/bot-list-controller.ts
+++ b/src/web/src/components/community/bots/bot-list-controller.ts
@@ -5,8 +5,11 @@ import { useCommunityRuntime } from "@/stores/community/runtime"
import { createStore, useSelector, useAtom, useCreateAtom } from "@tanstack/react-store";
import { useMutationState, useQueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
+import { useCurrentUser } from "@/contexts/community/current-user"
+import { useDmMessageSender } from "@/hooks/community/use-dm-message-sender"
import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react"
+import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef } from "react"
+import { CommunityRouteContext } from "@/contexts/community/route-frame"
import { useCommunityModuleLocation } from "@/contexts/community/module-route"
import { isPresenceOnline } from "@alook/shared"
import { toast } from "sonner"
@@ -43,6 +46,7 @@ export function useBotListController(): BotListController {
const source = useCommunityViewSource("bot-list")
const uiHandlers = useUiHandlers()
const { router, searchParams, routeCommitted } = useCommunityModuleLocation()
+ const navigation = useContext(CommunityRouteContext)?.navigation
const botsQuery = useBots()
const { bots } = botsQuery
const isLoading = botsQuery.isPending || botsQuery.profilesPending === true
@@ -93,6 +97,10 @@ export function useBotListController(): BotListController {
const resetMachineAgents = useResetMachineAgents()
const setActive = useSetBotActive()
const createOrGetDm = useCreateOrGetDm()
+ const currentUser = useCurrentUser()
+ const { accept: acceptDmMessage } = useDmMessageSender()
+ const [startingBotChat, setStartingBotChat] = useAtom(useCreateAtom(false))
+ const botChatInFlight = useRef(false)
const onboardingState = useCommunityOnboarding()
const guidedActive = onboardingState?.status === "active" && onboardingState.stage === "bot"
const guidedPendingBotId = guidedActive ? onboardingState.botId : undefined
@@ -131,6 +139,37 @@ export function useBotListController(): BotListController {
}
}
+ const askBotToCreate = async () => {
+ const bot = bots.find((item) => item.isActive && profilesByUserId.get(item.id)?.presence === "online") ?? bots[0]
+ if (!bot || botChatInFlight.current) return
+ const assert = source.capture()
+ botChatInFlight.current = true
+ setStartingBotChat(true)
+ try {
+ assert()
+ uiHandlers.cancelPendingNavigation?.()
+ const intentCurrent = navigation?.captureIntent() ?? (() => true)
+ const data = await createOrGetDm.mutateAsync({ userId: bot.id, assertActive: assert })
+ assert()
+ if (!intentCurrent()) throw new DOMException("Retired bot chat navigation", "AbortError")
+ const receipt = acceptDmMessage({
+ dmId: data.conversation.id,
+ content: "Help me create a bot. Ask me what I need.",
+ author: { id: currentUser.id, name: currentUser.name, avatar: currentUser.avatar },
+ assertActive: assert,
+ })
+ if (!receipt.accepted) throw new Error("Failed to send message")
+ setCreateOpen(false)
+ router.push(`/c/me/${data.conversation.id}`)
+ await receipt.committed
+ } catch (error) {
+ toastApiError(error, "Failed to start bot creation chat", assert)
+ } finally {
+ botChatInFlight.current = false
+ setStartingBotChat(false)
+ }
+ }
+
const openGuidedBotDm = async (botId: string) => {
const assert = source.capture()
assert()
@@ -429,6 +468,8 @@ export function useBotListController(): BotListController {
highlightId,
groupRefs,
chatWithBot,
+ askBotToCreate,
+ startingBotChat,
onBotCreated,
openGuidedCreate,
openMachines,
diff --git a/src/web/src/components/community/bots/bot-list-machine-group.dom.test.ts b/src/web/src/components/community/bots/bot-list-machine-group.dom.test.ts
index 695f8ff81..484c2fe3f 100644
--- a/src/web/src/components/community/bots/bot-list-machine-group.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-list-machine-group.dom.test.ts
@@ -102,6 +102,8 @@ function controller(overrides: Partial<BotListController> = {}): BotListControll
machineName: () => "My Mac",
bringMachineOnline: noop,
chatWithBot: noop,
+ askBotToCreate: noop,
+ startingBotChat: false,
...overrides,
} as BotListController
}
@@ -235,6 +237,16 @@ describe("renderBotMachineGroup", () => {
expect(setBotActive).toHaveBeenCalledWith(item, true)
})
+ it("keeps full long names and model values available with bot actions", () => {
+ const name = "Long name " + "W".repeat(100)
+ const modelName = "provider/" + "W".repeat(180)
+ const view = render(renderBotMachineGroup(group({ bots: [bot({ name, modelName })] }), controller()))
+ expect(view.getByTitle(name)).toHaveTextContent(name)
+ expect(view.getByTestId(tid.botCardModel)).toHaveAttribute("title", modelName)
+ expect(view.getByTestId(tid.botCardModel)).toHaveTextContent(modelName)
+ expect(view.getByRole("button", { name: "Bot actions" })).toBeEnabled()
+ })
+
it("projects bot-owned fixed-scale heatmaps and machine-scoped quota once", () => {
const usage = {
capability: "supported" as const,
diff --git a/src/web/src/components/community/bots/bot-list-machine-group.tsx b/src/web/src/components/community/bots/bot-list-machine-group.tsx
index de096e46b..ee4ca477f 100644
--- a/src/web/src/components/community/bots/bot-list-machine-group.tsx
+++ b/src/web/src/components/community/bots/bot-list-machine-group.tsx
@@ -68,7 +68,7 @@ export function renderBotMachineGroup(
<Button
variant="ghost"
size="sm"
- className="ml-auto h-7 gap-1.5 px-2 text-xs text-muted-foreground hover:text-foreground"
+ className="ml-auto h-7 shrink-0 gap-1.5 px-2 text-xs text-muted-foreground hover:text-foreground"
onClick={() => controller.setConfirmResetMachine(machineId)}
>
<RotateCcw className="size-3.5" />
@@ -90,9 +90,9 @@ export function renderBotMachineGroup(
<div className="flex items-start justify-between gap-3">
<AgentAvatar name={bot.name} avatarUrl={bot.image} seed={bot.id} size={40} />
<div className="flex min-w-0 flex-1 flex-wrap items-start gap-x-3 gap-y-2.5">
- <div className="flex min-w-55 flex-1 flex-col gap-1">
- <div className="flex items-center gap-2">
- <span className="truncate text-[15px] font-medium text-foreground">
+ <div className="flex min-w-0 basis-55 grow flex-col gap-1">
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <span title={bot.name} className="min-w-0 max-w-full truncate text-[15px] font-medium text-foreground">
{bot.name}
</span>
<span
@@ -131,14 +131,14 @@ export function renderBotMachineGroup(
</Button>
)}
</div>
- <span className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs text-muted-foreground">
- <span className="flex items-center gap-1.5">
+ <span className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs text-muted-foreground">
+ <span className="flex min-w-0 max-w-full items-center gap-1.5">
<ProviderLogo provider={bot.runtime} className="size-3.5 shrink-0" />
- <span>{runtimeLabel(bot.runtime)}</span>
+ <span className="truncate" title={runtimeLabel(bot.runtime)}>{runtimeLabel(bot.runtime)}</span>
</span>
<span aria-hidden className="shrink-0">·</span>
{formatModelLabel(bot.runtime, bot.modelName) ? (
- <span data-testid={tid.botCardModel} className="font-mono">
+ <span data-testid={tid.botCardModel} title={bot.modelName ?? undefined} className="min-w-0 max-w-full truncate font-mono">
{formatModelLabel(bot.runtime, bot.modelName)}
</span>
) : (
diff --git a/src/web/src/components/community/bots/bot-list-overlays.dom.test.ts b/src/web/src/components/community/bots/bot-list-overlays.dom.test.ts
index e773798ad..a9fe2e7f9 100644
--- a/src/web/src/components/community/bots/bot-list-overlays.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-list-overlays.dom.test.ts
@@ -56,6 +56,9 @@ import { renderBotListOverlaySlots } from "./bot-list-overlays"
function controller(overrides: Partial<BotListController> = {}): BotListController {
const noop = vi.fn()
return {
+ bots: [],
+ askBotToCreate: noop,
+ startingBotChat: false,
createOpen: false,
setCreateOpen: noop,
onBotCreated: noop,
@@ -92,6 +95,12 @@ function controller(overrides: Partial<BotListController> = {}): BotListControll
describe("renderBotListOverlaySlots", () => {
beforeEach(() => vi.clearAllMocks())
+ it("passes chat creation to the sheet only when bots exist", () => {
+ const state = controller({ bots: [{ id: "b1" }] as BotListController["bots"], startingBotChat: true })
+ expect(renderBotListOverlaySlots(state).create.props).toMatchObject({ onAskBotToCreate: state.askBotToCreate, askingBotToCreate: true })
+ expect(renderBotListOverlaySlots(controller()).create.props.onAskBotToCreate).toBeUndefined()
+ })
+
it("returns all named elements without an aggregate reconciliation boundary", () => {
const emptySlots = renderBotListOverlaySlots(controller())
expect(emptySlots.bug).toBeNull()
@@ -159,6 +168,8 @@ describe("renderBotListOverlaySlots", () => {
onCreated: state.onBotCreated,
guided: true,
avatarSeed: "seed",
+ onAskBotToCreate: undefined,
+ askingBotToCreate: false,
})
expect(slots.edit.props).toEqual({ bot, open: true, onOpenChange: setEditOpen })
expect(slots.activity.key).toBe("7")
diff --git a/src/web/src/components/community/bots/bot-list-overlays.tsx b/src/web/src/components/community/bots/bot-list-overlays.tsx
index 7e61461c1..67cb9b9ac 100644
--- a/src/web/src/components/community/bots/bot-list-overlays.tsx
+++ b/src/web/src/components/community/bots/bot-list-overlays.tsx
@@ -28,6 +28,8 @@ export function renderBotListOverlaySlots(
onCreated={controller.onBotCreated}
guided={controller.guidedActive}
avatarSeed={controller.guidedAvatarSeed}
+ onAskBotToCreate={controller.bots.length ? controller.askBotToCreate : undefined}
+ askingBotToCreate={controller.startingBotChat}
/>
),
help: (
diff --git a/src/web/src/components/community/bots/bot-list-types.ts b/src/web/src/components/community/bots/bot-list-types.ts
index 037affc45..e80ae1206 100644
--- a/src/web/src/components/community/bots/bot-list-types.ts
+++ b/src/web/src/components/community/bots/bot-list-types.ts
@@ -64,6 +64,8 @@ export type BotListController = {
groups: BotMachineGroup[]
highlightId: string | null
groupRefs: { current: Record<string, HTMLDivElement | null> }
+ startingBotChat: boolean
+ askBotToCreate: () => Promise<void>
chatWithBot: (bot: BotSummary) => Promise<void>
onBotCreated: (bot: BotSummary) => Promise<void>
openGuidedCreate: () => void
diff --git a/src/web/src/components/community/bots/bot-list-view.dom.test.ts b/src/web/src/components/community/bots/bot-list-view.dom.test.ts
index bba449f7d..57b38fc50 100644
--- a/src/web/src/components/community/bots/bot-list-view.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-list-view.dom.test.ts
@@ -95,6 +95,8 @@ function controller(overrides: Partial<BotListController> = {}): BotListControll
highlightId: null,
groupRefs: { current: {} },
chatWithBot: noop,
+ askBotToCreate: noop,
+ startingBotChat: false,
onBotCreated: noop,
openGuidedCreate: noop,
openMachines: noop,
@@ -120,6 +122,14 @@ function withClassFragment(container: HTMLElement, className: string): HTMLEleme
describe("renderBotListView", () => {
beforeEach(() => vi.clearAllMocks())
+ it("keeps the creation chat action out of the list header", () => {
+ for (const bots of [[], [{ id: "b1" }]]) {
+ const view = render(renderBotListView({}, controller({ bots: bots as BotListController["bots"], groups: [] })))
+ expect(view.queryByRole("button", { name: "Ask your bot to create more bots." })).toBeNull()
+ view.unmount()
+ }
+ })
+
it("shows Retry for an unconfirmed cold failure without claiming an empty bots list", () => {
const retry = vi.fn()
const view = render(renderBotListView({}, controller({ initialError: true, retryInitialLoad: retry })))
diff --git a/src/web/src/components/community/bots/bot-list-view.tsx b/src/web/src/components/community/bots/bot-list-view.tsx
index 5832d19bc..72c02237b 100644
--- a/src/web/src/components/community/bots/bot-list-view.tsx
+++ b/src/web/src/components/community/bots/bot-list-view.tsx
@@ -155,7 +155,7 @@ export function renderBotListView(
{backBar}
<div className="flex flex-1 flex-col gap-6 overflow-y-auto thin-scrollbar p-6">
<header className="flex items-center justify-between gap-4">
- <div className="flex flex-col gap-1">
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
<h1 className="text-xl font-medium text-foreground">My Bots</h1>
<BotActiveSummary onViewPlan={controller.viewPlan} summary={controller.planSummary} isFounder={controller.planSummary?.isFounder} />
</div>
diff --git a/src/web/src/components/community/bots/create-bot-sheet.dom.test.ts b/src/web/src/components/community/bots/create-bot-sheet.dom.test.ts
index ff803b6c0..c8742df5a 100644
--- a/src/web/src/components/community/bots/create-bot-sheet.dom.test.ts
+++ b/src/web/src/components/community/bots/create-bot-sheet.dom.test.ts
@@ -126,12 +126,14 @@ vi.mock("@/hooks/community/use-bots", () => ({
vi.mock("@/components/community/shell/community-sheet", () => {
return {
- CommunitySheet: ({ children, footer }: {
+ CommunitySheet: ({ children, footer, description }: {
+ description?: React.ReactNode
children?: React.ReactNode
footer?: React.ReactNode | ((requestClose: () => void) => React.ReactNode)
}) => React.createElement(
"div",
{ "data-mock": "sheet" },
+ React.createElement("div", { "data-testid": "sheet-description" }, description),
children,
typeof footer === "function" ? footer(vi.fn()) : footer,
),
@@ -188,7 +190,7 @@ function checkedValue(renderer: ReturnType<typeof rtlRender>, name: string): str
return radios(renderer, name).find((r) => r.checked)?.value ?? null
}
-function render(props: { avatarSeed?: string; guided?: boolean } = {}) {
+function render(props: Partial<React.ComponentProps<typeof CreateBotSheet>> = {}) {
return rtlRender(
React.createElement(CreateBotSheet, { open: true, onOpenChange: vi.fn(), ...props }),
)
@@ -203,6 +205,23 @@ describe("CreateBotSheet — auto-select defaults", () => {
reasoningDaemonVersionRenders.length = 0
})
+ it("shows the optional chat action only in the sheet subheader and respects busy state", () => {
+ useMachinesMock.mockReturnValue({ machines: [] })
+ const onAskBotToCreate = vi.fn()
+ const view = render({ onAskBotToCreate })
+ const button = view.getByRole("button", { name: "Ask your bot to create more bots." })
+ expect(view.getByTestId("sheet-description").contains(button)).toBe(true)
+ fireEvent.click(button)
+ expect(onAskBotToCreate).toHaveBeenCalledOnce()
+ view.rerender(React.createElement(CreateBotSheet, { open: true, onOpenChange: vi.fn(), onAskBotToCreate, askingBotToCreate: true }))
+ expect(button).toBeDisabled()
+ expect(button).toHaveAttribute("aria-busy", "true")
+ fireEvent.click(button)
+ expect(onAskBotToCreate).toHaveBeenCalledOnce()
+ view.rerender(React.createElement(CreateBotSheet, { open: true, onOpenChange: vi.fn() }))
+ expect(view.queryByRole("button", { name: "Ask your bot to create more bots." })).toBeNull()
+ })
+
it("uses the guide companion seed for a guided bot avatar", () => {
useMachinesMock.mockReturnValue({ machines: [] })
render({ avatarSeed: "guide-face-7" })
diff --git a/src/web/src/components/community/bots/create-bot-sheet.tsx b/src/web/src/components/community/bots/create-bot-sheet.tsx
index e4a45db71..768ffd14a 100644
--- a/src/web/src/components/community/bots/create-bot-sheet.tsx
+++ b/src/web/src/components/community/bots/create-bot-sheet.tsx
@@ -81,12 +81,16 @@ export function CreateBotSheet({
onCreated,
guided = false,
avatarSeed,
+ onAskBotToCreate,
+ askingBotToCreate = false,
}: {
open: boolean
onOpenChange: (open: boolean) => void
onCreated?: (bot: BotSummary) => void | Promise<void>
guided?: boolean
avatarSeed?: string
+ onAskBotToCreate?: () => void | Promise<void>
+ askingBotToCreate?: boolean
}) {
const source = useCommunityViewSource("create-bot", open)
const client = useQueryClient()
@@ -233,6 +237,9 @@ export function CreateBotSheet({
open={open}
onOpenChange={handleOpenChange}
title="Create a bot"
+ description={onAskBotToCreate ? (
+ <button type="button" onClick={() => void onAskBotToCreate()} disabled={askingBotToCreate} aria-busy={askingBotToCreate} className="w-fit max-w-full rounded-sm text-left text-sm text-muted-foreground underline underline-offset-4 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-wait disabled:opacity-50"><span aria-hidden="true">👉 </span>Ask your bot to create more bots.</button>
+ ) : undefined}
bodyClassName="flex flex-col gap-6"
footer={(requestClose) => (
<>
diff --git a/src/web/src/components/community/messages/message-menu-parity.test.ts b/src/web/src/components/community/messages/message-menu-parity.test.ts
index 73bf03c5c..de546aa0f 100644
--- a/src/web/src/components/community/messages/message-menu-parity.test.ts
+++ b/src/web/src/components/community/messages/message-menu-parity.test.ts
@@ -50,6 +50,7 @@ describe("messageCanShare — the derivation that gives every surface Share", ()
attachments: [{ kind: "file", name: "notes.txt", url: "/notes.txt", size: "1 KB" }],
}), false)).toBe(false)
expect(messageCanShare(msg({ approval: {} as RenderMsg["approval"] }), false)).toBe(false)
+ expect(messageCanShare(msg({ botCreation: {} as RenderMsg["botCreation"] }), false)).toBe(false)
expect(messageCanShare(msg(), true)).toBe(false) // compact rows opt out
})
})
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index a6abaf44f..9d9d5b227 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -21,6 +21,7 @@ import {
type MessageExternalLinkTarget,
} from "./message-external-link"
import { BotApprovalCard } from "../social/bot-approval-card"
+import { BotCreationRequestCard } from "../social/bot-creation-request-card"
import { EmojiPickerPopover } from "./emoji-picker"
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"
import { MessageContextItems, MessageDropdownItems, hasMessageMenu } from "./message-menu"
@@ -59,6 +60,7 @@ import { RemoteContentImage, RemoteIdentityImage } from "@/components/remote-ima
export function messageCanShare(m: RenderMsg, compact?: boolean): boolean {
return !compact
&& !m.approval
+ && !m.botCreation
&& (
!!(m.content ?? "")
|| !!m.attachments?.some((attachment) => attachment.kind === "image")
@@ -311,7 +313,7 @@ function MessageImpl({
|| (!desktopMenuInputActive && touchInputCapable)
// A hybrid device can alternate between mouse and touch. Switching the menu
// shell after a mouse gesture must not remove the row's touch swipe handler.
- const swipePointerEnabled = interactive && touchInputCapable && !selectMode
+ const swipePointerEnabled = interactive && touchInputCapable && !selectMode && !m.botCreation
const swipeReplyEnabled = swipePointerEnabled && !!onReply
const activateOverlays = interactive && !selectMode && !activated
? (event: React.SyntheticEvent<HTMLElement>) => {
@@ -711,7 +713,9 @@ function MessageImpl({
)}
</div>
)}
- {m.approval ? (
+ {m.botCreation ? (
+ <BotCreationRequestCard key={m.botCreation.requestId} request={m.botCreation} messageId={m.id} viewerUserId={viewerUserId} onOpenProfile={onOpenProfile} />
+ ) : m.approval ? (
<BotApprovalCard approval={m.approval} />
) : (
visibleContent && (
@@ -1010,6 +1014,7 @@ function messagePropsEqual(prev: MessageProps, next: MessageProps): boolean {
a.content !== b.content ||
a.grouped !== b.grouped ||
a.failed !== b.failed ||
+ a.botCreation !== b.botCreation ||
a.authorId !== b.authorId ||
a.color !== b.color ||
a.createdAt !== b.createdAt ||
diff --git a/src/web/src/components/community/shell/explicit-navigation-entries.dom.test.ts b/src/web/src/components/community/shell/explicit-navigation-entries.dom.test.tsx
similarity index 94%
rename from src/web/src/components/community/shell/explicit-navigation-entries.dom.test.ts
rename to src/web/src/components/community/shell/explicit-navigation-entries.dom.test.tsx
index b9a3a0af1..b84476231 100644
--- a/src/web/src/components/community/shell/explicit-navigation-entries.dom.test.ts
+++ b/src/web/src/components/community/shell/explicit-navigation-entries.dom.test.tsx
@@ -11,6 +11,7 @@ import { useBotListController } from "../bots/bot-list-controller"
import type { BotSummary } from "@/hooks/community/use-bots"
import { CommunityInviteCard } from "../social/community-invite-card"
import { useCommunityNavigationController } from "./use-community-navigation-controller"
+import { CurrentUserProvider } from "@/contexts/community/current-user"
import MeFriendsPage from "@/app/c/me/friends/page"
const mocks = vi.hoisted(() => ({
@@ -37,7 +38,8 @@ vi.mock("@/hooks/community/use-machines", () => ({
useMachines: () => ({ machines: [{ id: "machine", status: "online" }], isLoading: false }),
}))
vi.mock("@/lib/community-db/projections", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/community-db/projections")>(), useCanonicalProfilesByUserId: () => new Map() }))
-vi.mock("@/hooks/community/mutations", () => ({
+vi.mock("@/hooks/community/mutations", async (importOriginal) => ({
+ ...await importOriginal<typeof import("@/hooks/community/mutations")>(),
useCreateOrGetDm: () => ({ mutateAsync: mocks.createDm }),
useSendFriendRequest: () => ({}),
useAcceptFriendRequest: () => ({}),
@@ -100,7 +102,13 @@ function renderEntries() {
createElement(MeFriendsPage),
)
}
- render(createElement(QueryClientProvider, { client: queryClient }, createElement(Capture)))
+ render(
+ <QueryClientProvider client={queryClient}>
+ <CurrentUserProvider initialUser={{ id: "viewer", name: "Viewer", email: "[email protected]", avatar: "" }}>
+ <Capture />
+ </CurrentUserProvider>
+ </QueryClientProvider>,
+ )
return { queryClient, get navigation() { return navigation }, get bots() { return bots } }
}
diff --git a/src/web/src/components/community/social/bot-creation-request-card.dom.test.tsx b/src/web/src/components/community/social/bot-creation-request-card.dom.test.tsx
new file mode 100644
index 000000000..d17b95548
--- /dev/null
+++ b/src/web/src/components/community/social/bot-creation-request-card.dom.test.tsx
@@ -0,0 +1,141 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { Message } from "../messages/message"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { render, fireEvent } from "@/test/react-dom-harness"
+import { botCreationFixture } from "@/test/bot-creation-fixtures"
+import { tid } from "@/lib/community/testids"
+import { BotCreationRequestCard } from "./bot-creation-request-card"
+
+const profiles = vi.hoisted(() => new Map<string, { id: string; name: string; discriminator: string; avatar?: string | null }>())
+const command = vi.hoisted(() => ({ mutate: vi.fn(), isPending: false, error: null as Error | null, variables: undefined as { decision: string } | undefined }))
+vi.mock("@/hooks/community/mutations/bot-creation", () => ({ useBotCreationDecision: () => command }))
+vi.mock("@/lib/community-db/projections", async (original) => ({ ...await original<typeof import("@/lib/community-db/projections")>(), useCanonicalCommunityProfile: (id?: string) => id ? profiles.get(id) : undefined }))
+beforeEach(() => { profiles.clear(); command.mutate.mockReset(); command.isPending = false; command.error = null; command.variables = undefined })
+
+describe("bot creation request gallery", () => {
+ it("refreshes a memoized message when only its request resolution changes", () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const request = botCreationFixture()
+ const openThread = () => undefined
+ const message = { id: "message-1", type: "chat" as const, grouped: false, content: "", botCreation: request }
+ const view = render(<QueryClientProvider client={client}><Message m={message} viewerUserId="viewer" onOpenThread={openThread} /></QueryClientProvider>)
+ expect(view.getByRole("button", { name: "Create bot" })).toBeVisible()
+ view.rerender(<QueryClientProvider client={client}><Message m={{ ...message, botCreation: { ...request, status: "declined" } }} viewerUserId="viewer" onOpenThread={openThread} /></QueryClientProvider>)
+ expect(view.queryByTestId(tid.botCreationApprove)).toBeNull()
+ expect(view.getByRole("img", { name: "Declined" })).toHaveTextContent("NOT PASS")
+ expect(view.queryByRole("status")).toBeNull()
+ expect(view.queryByText("Declined")).toBeNull()
+ client.clear()
+ })
+
+ it("leaves gallery touch panning native while normal messages still swipe to reply", () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const request = botCreationFixture()
+ const onReply = vi.fn()
+ const tree = (botCreation?: typeof request) => <QueryClientProvider client={client}>
+ <Message m={{ id: "touch-message", type: "chat", grouped: false, content: botCreation ? "" : "Plain message", botCreation }}
+ viewerUserId="viewer" hoverCapable={false} onOpenThread={() => undefined} onReply={onReply} />
+ </QueryClientProvider>
+ const swipe = (target: HTMLElement) => {
+ let move!: Event
+ for (const [type, x] of [["pointerdown", 100], ["pointermove", 190], ["pointerup", 190]] as const) {
+ const event = new Event(type, { bubbles: true, cancelable: true })
+ Object.defineProperties(event, { pointerType: { value: "touch" }, pointerId: { value: 1 }, clientX: { value: x }, clientY: { value: 100 } })
+ fireEvent(target, event)
+ if (type === "pointermove") move = event
+ }
+ return move
+ }
+ const view = render(tree(request))
+ expect(swipe(view.getByText(request.bots[0]!.reason)).defaultPrevented).toBe(false)
+ expect(onReply).not.toHaveBeenCalled()
+ view.rerender(tree())
+ expect(swipe(view.getByText("Plain message")).defaultPrevented).toBe(true)
+ expect(onReply).toHaveBeenCalledOnce()
+ view.unmount()
+ client.clear()
+ })
+
+ it("renders one gallery and one whole-batch action group with visible reasons and configuration badges", () => {
+ const first = botCreationFixture().bots[0]!
+ const request = botCreationFixture({ bots: [first, { ...first, itemId: "item-2", name: "Reviewer", model: null, reasoningEffort: null, reason: "Review the result" }] })
+ const view = render(<BotCreationRequestCard request={request} messageId="message-1" viewerUserId="viewer" />)
+ expect(view.getAllByTestId(tid.botCreationRequestCard)).toHaveLength(1)
+ expect(view.getAllByRole("article")).toHaveLength(2)
+ expect(view.getByText("Check sources independently")).toBeVisible()
+ expect(view.getByText("Review the result")).toBeVisible()
+ expect(view.getByText("model-a")).toBeVisible()
+ expect(view.getByText("high")).toBeVisible()
+ expect(view.queryByText("Runtime default")).toBeNull()
+ expect(view.queryByText("Local default")).toBeNull()
+ expect(view.queryByText("Offline")).toBeNull()
+ fireEvent.click(view.getByRole("button", { name: "Create 2 bots" }))
+ expect(command.mutate).toHaveBeenCalledExactlyOnceWith({ requestId: "request-1", messageId: "message-1", decision: "approve" })
+ fireEvent.click(view.getByRole("button", { name: "Decline" }))
+ expect(command.mutate).toHaveBeenLastCalledWith({ requestId: "request-1", messageId: "message-1", decision: "decline" })
+ })
+
+ it("keeps single creation in the same gallery and displays untrusted text literally", () => {
+ const request = botCreationFixture()
+ request.bots[0]!.reason = '<img src=x onerror="alert(1)">'
+ const view = render(<BotCreationRequestCard request={request} messageId="message-1" viewerUserId="viewer" />)
+ expect(view.getAllByRole("article")).toHaveLength(1)
+ expect(view.getByText(request.bots[0]!.reason)).toBeVisible()
+ expect(view.container.querySelector("img[src=x]")).toBeNull()
+ expect(view.getByRole("button", { name: "Create bot" })).toBeEnabled()
+ expect(view.queryByText("Find sources and report uncertainty")).toBeNull()
+ expect(view.queryByRole("tab")).toBeNull()
+ })
+
+ it("disables both decisions while creating and keeps a failed request actionable", () => {
+ const request = botCreationFixture()
+ command.isPending = true; command.variables = { decision: "approve" }
+ const view = render(<BotCreationRequestCard request={request} messageId="message-1" viewerUserId="viewer" />)
+ expect(view.getByRole("button", { name: "Creating…" })).toBeDisabled()
+ expect(view.getByRole("button", { name: "Decline" })).toBeDisabled()
+ fireEvent.click(view.getByTestId(tid.botCreationApprove))
+ expect(command.mutate).not.toHaveBeenCalled()
+ command.isPending = false; command.error = new Error("Not enough bot slots. Free a slot and try again.")
+ view.rerender(<BotCreationRequestCard request={request} messageId="message-1" viewerUserId="viewer" />)
+ expect(view.getByRole("alert")).toHaveTextContent("Free a slot")
+ expect(view.getByRole("button", { name: "Create bot" })).toBeEnabled()
+ })
+
+ it("shows no decisions to the requester or on terminal cards, and hides a retired error", () => {
+ const request = botCreationFixture()
+ const view = render(<BotCreationRequestCard request={request} messageId="message-1" viewerUserId="requester" />)
+ expect(view.queryByRole("button")).toBeNull()
+ expect(view.getByRole("status")).toHaveTextContent("Waiting for your owner")
+ view.rerender(<BotCreationRequestCard request={{ ...request, status: "declined" }} messageId="message-1" viewerUserId="viewer" />)
+ expect(view.getByRole("img", { name: "Declined" })).toHaveTextContent("NOT PASS")
+ expect(view.queryByRole("status")).toBeNull()
+ expect(view.queryByText("Declined")).toBeNull()
+ expect(view.queryByRole("img", { name: "Approved" })).toBeNull()
+ const first = request.bots[0]!
+ view.rerender(<BotCreationRequestCard request={{ ...request, status: "approved", bots: [first, { ...first, itemId: "item-2" }] }} messageId="message-1" viewerUserId="viewer" />)
+ expect(view.getAllByRole("img", { name: "Approved" })).toHaveLength(2)
+ expect(view.getAllByRole("img", { name: "Approved" }).every((stamp) => stamp.textContent === "PASS")).toBe(true)
+ expect(view.queryByRole("status")).toBeNull()
+ expect(view.queryByTestId(tid.botCreationApprove)).toBeNull()
+ command.error = new DOMException("Retired account", "AbortError")
+ view.rerender(<BotCreationRequestCard request={{ ...request }} messageId="message-1" viewerUserId="viewer" />)
+ expect(view.queryByRole("alert")).toBeNull()
+ })
+
+ it("opens the actual created identity after approval rather than the proposal name", () => {
+ const request = botCreationFixture({ status: "approved" })
+ request.bots[0]!.createdBot = { id: "created-1", name: "Actual Bot", discriminator: "0042", image: null, avatarVersion: 0 }
+ const open = vi.fn()
+ const view = render(<BotCreationRequestCard request={request} messageId="message-1" viewerUserId="viewer" onOpenProfile={open} />)
+ fireEvent.click(view.getByRole("button", { name: "Actual Bot#0042" }))
+ expect(open).toHaveBeenCalledWith("Actual Bot", expect.anything(), "0042", "created-1")
+ expect(view.queryByTestId(tid.botCreationApprove)).toBeNull()
+ profiles.set("created-1", { id: "created-1", name: "Renamed Bot", discriminator: "0042", avatar: null })
+ view.rerender(<BotCreationRequestCard request={request} messageId="message-1" viewerUserId="viewer" onOpenProfile={open} />)
+ expect(view.getByRole("button", { name: "Renamed Bot#0042" })).toBeVisible()
+ expect(view.queryByRole("button", { name: "Actual Bot#0042" })).toBeNull()
+ request.bots[0]!.createdBot.image = "https://example.com/stale-avatar.png"
+ view.rerender(<BotCreationRequestCard request={request} messageId="message-1" viewerUserId="viewer" onOpenProfile={open} />)
+ expect(view.container.querySelector('[data-avatar-kind="photo"]')).toBeNull()
+ })
+})
diff --git a/src/web/src/components/community/social/bot-creation-request-card.module.css b/src/web/src/components/community/social/bot-creation-request-card.module.css
new file mode 100644
index 000000000..dc096a3eb
--- /dev/null
+++ b/src/web/src/components/community/social/bot-creation-request-card.module.css
@@ -0,0 +1,13 @@
+@media (hover: hover) and (prefers-reduced-motion: no-preference) {
+ .card:hover {
+ animation: sway 300ms ease-in-out;
+ transform-origin: center 70%;
+ }
+}
+
+@keyframes sway {
+ 0%, 100% { transform: rotate(0deg); }
+ 25% { transform: rotate(-1deg); }
+ 60% { transform: rotate(0.8deg); }
+ 85% { transform: rotate(-0.3deg); }
+}
diff --git a/src/web/src/components/community/social/bot-creation-request-card.tsx b/src/web/src/components/community/social/bot-creation-request-card.tsx
new file mode 100644
index 000000000..abff18047
--- /dev/null
+++ b/src/web/src/components/community/social/bot-creation-request-card.tsx
@@ -0,0 +1,115 @@
+"use client"
+
+import { Monitor, Box, Gauge } from "lucide-react"
+import { ScrollArea } from "@base-ui/react/scroll-area"
+import type { BotCreationItem, BotCreationPayload } from "@alook/shared"
+import { Button } from "@/components/ui/button"
+import { Badge } from "@/components/ui/badge"
+import { ProfileAvatar, SeededBackdrop } from "@/components/avatar"
+import { ProviderLogo } from "@/components/provider-logo"
+import { useBotCreationDecision } from "@/hooks/community/mutations/bot-creation"
+import { useCanonicalCommunityProfile } from "@/lib/community-db/projections"
+import { runtimeLabel } from "@/lib/community/runtime-label"
+import { isAbortError } from "@/lib/errors"
+import { tid } from "@/lib/community/testids"
+import type { OpenProfile } from "./profile-types"
+import styles from "./bot-creation-request-card.module.css"
+
+export function BotCreationRequestCard({ request, messageId, viewerUserId, onOpenProfile }: {
+ request: BotCreationPayload
+ messageId: string
+ viewerUserId?: string
+ onOpenProfile?: OpenProfile
+}) {
+ const decide = useBotCreationDecision()
+ const count = request.bots.length
+ const pending = request.status === "pending"
+ const actionable = pending && viewerUserId === request.ownerUserId
+ const error = actionable && !isAbortError(decide.error) ? decide.error : null
+ const submit = (decision: "approve" | "decline") => {
+ if (decide.isPending) return
+ decide.mutate({ requestId: request.requestId, messageId, decision })
+ }
+
+ return (
+ <section className={`flex w-full min-w-0 flex-col ${count > 1 ? "max-w-2xl" : "max-w-80"}`}
+ aria-label="Bot creation request" data-testid={tid.botCreationRequestCard} data-request-status={request.status}>
+ <ScrollArea.Root className={count > 1 ? "-ml-2 min-w-0 pb-4" : "-ml-2 min-w-0"} data-swipe-ignore="">
+ <ScrollArea.Viewport role="group" aria-label="Proposed bots" tabIndex={0}
+ className="min-w-0 snap-x snap-mandatory scroll-px-2 overscroll-x-contain rounded-sm focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
+ <ScrollArea.Content className="flex gap-4 p-2">
+ {request.bots.map((bot) => <BotProposal key={bot.itemId} bot={bot} status={request.status} onOpenProfile={onOpenProfile} />)}
+ </ScrollArea.Content>
+ </ScrollArea.Viewport>
+ <ScrollArea.Scrollbar orientation="horizontal" className="mx-2 flex h-6 items-center px-1">
+ <ScrollArea.Thumb className="relative h-full after:pointer-events-none after:absolute after:inset-x-0 after:top-1/2 after:h-1 after:-translate-y-1/2 after:rounded-full after:bg-border hover:after:bg-muted-foreground active:after:bg-muted-foreground" />
+ </ScrollArea.Scrollbar>
+ </ScrollArea.Root>
+ {actionable ? (
+ <div className="flex flex-col gap-2">
+ {error && <p role="alert" className="wrap-anywhere text-sm text-destructive">{error.message}</p>}
+ <div className="flex justify-start gap-2" aria-busy={decide.isPending}>
+ <Button size="sm" className="h-11 sm:h-9" disabled={decide.isPending}
+ data-testid={tid.botCreationApprove} onClick={() => submit("approve")}>
+ {decide.isPending && decide.variables?.decision === "approve" ? "Creating…" : `Create ${count === 1 ? "bot" : `${count} bots`}`}
+ </Button>
+ <Button size="sm" variant="ghost" className="h-11 sm:h-9" disabled={decide.isPending}
+ data-testid={tid.botCreationDecline} onClick={() => submit("decline")}>
+ {decide.isPending && decide.variables?.decision === "decline" ? "Declining…" : "Decline"}
+ </Button>
+ </div>
+ </div>
+ ) : !pending ? null : <p role="status" className="text-xs font-medium text-muted-foreground">
+ Waiting for your owner’s decision
+ </p>}
+ </section>
+ )
+}
+
+function BotProposal({ bot, status, onOpenProfile }: { bot: BotCreationItem; status: BotCreationPayload["status"]; onOpenProfile?: OpenProfile }) {
+ const identity = bot.createdBot
+ const canonical = useCanonicalCommunityProfile(identity?.id)
+ const name = canonical?.name ?? identity?.name ?? bot.name
+ const discriminator = canonical?.discriminator ?? identity?.discriminator
+ const seed = identity?.id ?? bot.itemId
+ const avatar = canonical ? canonical.avatar : identity?.image
+ const heading = <><span className="min-w-0 truncate">{name}</span>{identity && <span className="ml-1.5 shrink-0 text-sm font-normal tracking-wide text-muted-foreground">#{discriminator}</span>}</>
+ const badgeClass = "min-w-0 max-w-full shrink-0 whitespace-nowrap text-left"
+
+ return <article className={`${styles.card} relative flex h-70 w-70 min-w-0 shrink-0 snap-start flex-col overflow-hidden rounded-xl border border-border bg-popover p-2`} aria-label={bot.name}>
+ {status !== "pending" && <span role="img" aria-label={status === "approved" ? "Approved" : "Declined"}
+ className={`pointer-events-none absolute right-3 top-3 z-10 -rotate-8 px-3 py-2 text-xl font-black leading-none tracking-wide ${status === "approved" ? "text-approval-pass" : "text-destructive"}`}>
+ <svg aria-hidden="true" focusable="false" viewBox="0 0 144 48" preserveAspectRatio="none" className="absolute inset-0 size-full fill-none stroke-current">
+ <path d="M8 3 19 2.5 29 3.4 40 2.5 53 3.2 66 2.4 80 3.3 95 2.6 110 3.4 124 2.5 136 3 Q141 3 141 8 L140.4 15 141.3 22 140.5 30 141 38 Q142 44 136 44.5 L122 43.8 109 45 94 44 80 44.8 65 43.9 50 44.8 37 44 22 45 8 44.5 Q3 44 3.5 39 L2.7 30 3.5 23 2.6 15 3.4 8 Q3 3 8 3Z" strokeWidth="2.5" strokeDasharray="49 1.2 22 0.8 67 1.8 31 0.7" strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />
+ <path d="M9 8 34 7.5 62 8.2 91 7.6 117 8.3 135 8 135.5 21 135 39.5 110 39 83 40 57 39.4 31 40 9 39.5 8.5 25Z" strokeWidth="1" strokeDasharray="20 1 45 2 12 0.8 35 1.4" strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />
+ </svg>
+ {status === "approved" ? "PASS" : "NOT PASS"}
+ </span>}
+ <div className="relative -m-2 mb-0 h-12 shrink-0 overflow-hidden rounded-t-lg">
+ <SeededBackdrop seed={seed} />
+ </div>
+ <div className="relative -mt-7 mb-2 flex shrink-0 items-end gap-2 px-2">
+ <div className="shrink-0 rounded-full ring-[5px] ring-popover">
+ <ProfileAvatar label={name} seed={seed} src={avatar} size={56} />
+ </div>
+ <div title={runtimeLabel(bot.backendId)} className="flex min-w-0 max-w-32 translate-y-1 items-center gap-2 rounded-full border border-border bg-secondary px-2 py-0.5 text-[13px] text-secondary-foreground shadow-(--e1)">
+ <ProviderLogo provider={bot.backendId} className="size-3.5 shrink-0" />
+ <span className="truncate">{runtimeLabel(bot.backendId)}</span>
+ </div>
+ </div>
+ <div className="mx-1 mb-1 flex min-h-0 flex-1 flex-col rounded-lg bg-card p-3">
+ {identity && onOpenProfile ? <button type="button" aria-label={`${name}#${discriminator}`} title={`${name}#${discriminator}`}
+ className="flex min-h-11 min-w-0 shrink-0 items-baseline text-left text-lg font-semibold leading-tight tracking-[-0.015em] underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring sm:min-h-7"
+ onClick={(event) => onOpenProfile(name, event, discriminator, identity.id)}>{heading}</button>
+ : <p title={name} className="flex min-w-0 shrink-0 items-baseline text-lg font-semibold leading-tight tracking-[-0.015em]">{heading}</p>}
+ <div tabIndex={0} aria-label={`${name} reason`} className="mt-2 min-h-0 flex-1 overflow-y-auto overscroll-y-contain rounded-sm pr-2 thin-scrollbar focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
+ <p className="wrap-anywhere whitespace-pre-wrap text-sm leading-relaxed text-muted-foreground">{bot.reason}</p>
+ </div>
+ <div tabIndex={0} aria-label={`${name} configuration`} className="mt-3 flex max-h-12 shrink-0 flex-wrap items-start gap-1.5 overflow-y-auto overscroll-y-contain rounded-sm thin-scrollbar focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
+ <Badge variant="secondary" className={badgeClass} title={`Machine: ${bot.machineName}`}><Monitor aria-hidden className="shrink-0" /><span className="truncate">{bot.machineName}</span></Badge>
+ {bot.model && <Badge variant="secondary" className={badgeClass} title={`Model: ${bot.model}`}><Box aria-hidden className="shrink-0" /><span className="truncate">{bot.model}</span></Badge>}
+ {bot.reasoningEffort && <Badge variant="secondary" className={badgeClass} title={`Effort: ${bot.reasoningEffort}`}><Gauge aria-hidden className="shrink-0" /><span className="truncate">{bot.reasoningEffort}</span></Badge>}
+ </div>
+ </div>
+ </article>
+}
diff --git a/src/web/src/components/home/landing-workspace-home.tsx b/src/web/src/components/home/landing-workspace-home.tsx
index 65c58b71e..78edb23bc 100644
--- a/src/web/src/components/home/landing-workspace-home.tsx
+++ b/src/web/src/components/home/landing-workspace-home.tsx
@@ -56,6 +56,7 @@ export function WorkspaceHome({ page, onBack, onDm, onOpenProfile, onMachines }:
bugReportBot: null, setBugReportBot: () => {}, bugReportOpen: false, setBugReportOpen: () => setPanel("Report a problem"),
confirmDelete: null, setConfirmDelete: (bot) => { edit(bot); setPanel("Delete bot") }, confirmReset: null, setConfirmReset: (bot) => { edit(bot); setPanel("Reset session") },
confirmResetMachine: null, setConfirmResetMachine: () => setPanel("Reset sessions"), helpOpen: false, setHelpOpen: () => setPanel("How your agent works"), guidedActive: false, guidedCreateLabel: "Create bot", guidedAvatarSeed: undefined,
+ startingBotChat: false, askBotToCreate: async () => { const bot = bots.find((item) => item.isActive && DEMO_PROFILES.get(item.id)?.presence === "online") ?? bots[0]; if (bot) onDm(bot.id) },
chatWithBot: async (bot) => onDm(bot.id), onBotCreated: async () => {}, openGuidedCreate: () => { edit(null); setPanel("Create bot") }, openMachines: onMachines,
bringMachineOnline: () => setMachines((rows) => rows.map((row) => ({ ...row, status: "online" }))), machineName: () => MACHINE.displayName,
deleteConfirmedBot: async () => {}, resetConfirmedBot: async () => {}, resetConfirmedMachine: async () => {},
diff --git a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts b/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
index 26483e68a..968718ff7 100644
--- a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
@@ -1,3 +1,4 @@
+import { botCreationFixture } from "@/test/bot-creation-fixtures"
import { conversationEntryFromChannel } from "@/test/conversation-entry-fixtures"
import { seedCanonicalFocusedChannel } from "./test-harness"
import { act } from "@/test/react-dom-harness"
@@ -10,7 +11,7 @@ import type {
CommunityReactionAdd,
} from "@alook/shared"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
-import { beginCommunityProfileSeed } from "@/lib/community/profile-seed"
+import { writeCommunityProfilePatches, beginCommunityProfileSeed } from "@/lib/community/profile-seed"
import { getMessageStreamState } from "@/test/community-query-owner"
import { communityKeys } from "@/lib/query-keys"
import { getCanonicalCommunityChannels } from "@/lib/community-db/sync"
@@ -980,6 +981,24 @@ describe("useCommunityWs — reactions", () => {
})
describe("useCommunityWs — message.updated", () => {
+ it("projects gallery resolution without erasing friendship approval or overwriting a renamed identity", async () => {
+ getCapturedRuntime().ui.actions.subscribe({ dmConversationId: "dm_1" })
+ await mountHook()
+ const profile = { id: "friend", name: "Friend", discriminator: "0001", image: null, avatarVersion: 0 }
+ const approval = { friendshipId: "friendship", status: "pending" as const, waitingOn: "you" as const, otherProfile: profile, botProfile: { ...profile, id: "bot" }, waitingOnProfile: null }
+ seedCanonicalStream({ kind: "dm", id: "dm_1" }, { type: "wsMessage", message: { id: "gallery-message", seq: 4, type: "chat", content: "", approval, botCreation: botCreationFixture() } })
+ capturedQueryClient.setQueryData(communityKeys.bots(), { bots: [] })
+ const request = botCreationFixture({ status: "approved" })
+ request.bots[0]!.createdBot = { id: "new-bot", name: "Researcher", discriminator: "0042", image: null, avatarVersion: 0 }
+ writeCommunityProfilePatches([{ id: "new-bot", identityAbout: { name: "Renamed Bot", discriminator: "0042" } }], getCommunityDbRegistry(capturedQueryClient), { command: true })
+ capturedOnMessage!({ type: "community:message.updated", channelId: "dm_1", messageId: "gallery-message", botCreation: request })
+ expect(canonicalMessage("gallery-message")).toMatchObject({ approval, botCreation: request })
+ expect(getCommunityDbRegistry(capturedQueryClient)!.collections.profiles.get("new-bot")).toMatchObject({ name: "Renamed Bot", discriminator: "0042" })
+ expect(capturedQueryClient.getQueryState(communityKeys.bots())?.isInvalidated).toBe(true)
+ capturedOnMessage!({ type: "community:message.updated", channelId: "dm_1", messageId: "gallery-message", approval: { ...approval, status: "denied", waitingOn: null } })
+ expect(canonicalMessage("gallery-message")?.botCreation).toEqual(request)
+ })
+
it("refreshes approval fields on a focused DM row that exists only in the overlay", async () => {
const { useCommunityStore } = await import("@/stores/community")
getCapturedRuntime().ui.actions.subscribe({ dmConversationId: "dm_1" })
diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.ts
index 3bb53f082..71861c22a 100644
--- a/src/web/src/hooks/community/community-ws/message-events.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.ts
@@ -1,3 +1,4 @@
+import { invalidateBotSurfaces } from "@/hooks/community/use-bots"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { getCommunityRuntime, readCurrentCommunityChannelMeta } from "@/stores/community/runtime"
import type {
@@ -174,11 +175,12 @@ export function handleMessageUpdated(
context: CommunityWsHandlerContext,
) {
writeCommunityProfilePatches(approvalProfilePatches(event.approval), getCommunityDbRegistry(context.queryClient), { event: true })
+ if (event.botCreation?.status === "approved") invalidateBotSurfaces(context.queryClient)
// When a card resolves (accepted/denied/superseded), the friend graph
// changed — invalidate friends + pending so the owner's lists reflect
// it. This is the owner's only signal in the J2 tail (Alice's accept
// dead-letters FRIEND_ACCEPT to the bot).
- if (event.approval.status !== "pending" || event.approval.waitingOn !== "you") {
+ if (event.approval && (event.approval.status !== "pending" || event.approval.waitingOn !== "you")) {
invalidateFriends(context.projection)
}
}
diff --git a/src/web/src/hooks/community/mutations/bot-creation.dom.test.tsx b/src/web/src/hooks/community/mutations/bot-creation.dom.test.tsx
new file mode 100644
index 000000000..c81559c52
--- /dev/null
+++ b/src/web/src/hooks/community/mutations/bot-creation.dom.test.tsx
@@ -0,0 +1,94 @@
+import { createElement, type PropsWithChildren } from "react"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { act, renderHook, waitFor } from "@/test/react-dom-harness"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { botCreationFixture } from "@/test/bot-creation-fixtures"
+import { ingestMessages, projectCommunityWsEventToDb } from "@/lib/community-db/sync"
+import { communityKeys } from "@/lib/query-keys"
+import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"
+import { messageProfileIds } from "@/lib/community/models/message"
+import { useBotCreationDecision } from "./bot-creation"
+
+const api = vi.fn()
+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => api(...args) }))
+beforeEach(() => api.mockReset())
+async function owner() {
+ const state = await createCommunityQueryOwner()
+ ingestMessages(state.registry, "dm-1", [{ id: "message-1", type: "chat", seq: 1, content: "", botCreation: botCreationFixture() }])
+ state.client.setQueryData(communityKeys.bots(), { bots: [] })
+ state.client.setQueryData(communityKeys.machines(), { machines: [] })
+ function Wrapper({ children }: PropsWithChildren) { return createElement(CommunityTestProvider, { ...state, retainOwner: true }, children) }
+ const view = renderHook(useBotCreationDecision, { wrapper: Wrapper })
+ return { ...state, view }
+}
+const input = { requestId: "request-1", messageId: "message-1", decision: "approve" as const }
+function approved() {
+ const request = botCreationFixture({ status: "approved", resolvedAt: "2026-10-22T09:01:00Z" })
+ request.bots[0]!.createdBot = { id: "created-1", name: "Researcher", discriminator: "0042", image: null, avatarVersion: 0 }
+ return request
+}
+
+describe("bot creation owner decision", () => {
+ it("does not overwrite a renamed bot when an old approved card is loaded", async () => {
+ const state = await owner()
+ writeCommunityProfilePatches([{ id: "created-1", identityAbout: { name: "Renamed Bot", discriminator: "0042" }, avatar: { avatar: "new-avatar", avatarVersion: 2 } }], state.registry, { command: true })
+ ingestMessages(state.registry, "dm-1", [{ id: "historical-card", type: "chat", seq: 2, botCreation: approved() }])
+ expect(state.registry.collections.profiles.get("created-1")).toMatchObject({ name: "Renamed Bot", avatar: "new-avatar", avatarVersion: 2 })
+ api.mockResolvedValueOnce({ botCreation: approved() })
+ await act(async () => { await state.view.result.current.mutateAsync(input) })
+ expect(state.registry.collections.profiles.get("created-1")).toMatchObject({ name: "Renamed Bot", avatar: "new-avatar", avatarVersion: 2 })
+ })
+
+ it.each(["approve", "decline"] as const)("sends %s and publishes the authoritative card", async (decision) => {
+ const state = await owner()
+ const request = decision === "approve" ? approved() : botCreationFixture({ status: "declined" })
+ api.mockResolvedValue({ botCreation: request })
+ await act(async () => { await state.view.result.current.mutateAsync({ ...input, decision }) })
+ expect(api).toHaveBeenCalledWith("/api/community/bots/creation-requests/request-1", expect.objectContaining({ method: "PATCH", body: JSON.stringify({ decision }), signal: expect.any(AbortSignal) }))
+ expect(state.registry.collections.messages.get("message-1")?.botCreation).toEqual(request)
+ if (decision === "approve") {
+ expect(state.registry.collections.profiles.has("created-1")).toBe(false)
+ expect(state.client.getQueryState(communityKeys.bots())?.isInvalidated).toBe(true)
+ expect(state.client.getQueryState(communityKeys.machines())?.isInvalidated).toBe(false)
+ expect(messageProfileIds(state.registry.collections.messages.get("message-1")!)).toContain("created-1")
+ }
+ })
+
+ it("keeps a quota failure pending and rejects a mismatched response", async () => {
+ const state = await owner()
+ api.mockRejectedValueOnce(new Error("Not enough bot slots"))
+ await act(async () => { await expect(state.view.result.current.mutateAsync(input)).rejects.toThrow("Not enough bot slots") })
+ expect(state.registry.collections.messages.get("message-1")?.botCreation?.status).toBe("pending")
+ api.mockResolvedValueOnce({ botCreation: { ...approved(), requestId: "another-request" } })
+ await act(async () => { await expect(state.view.result.current.mutateAsync(input)).rejects.toThrow("request changed") })
+ expect(state.registry.collections.messages.get("message-1")?.botCreation?.status).toBe("pending")
+ })
+
+ it("preserves a newer WS resolution and a late snapshot cannot revert it", async () => {
+ const state = await owner()
+ let resolve!: (value: unknown) => void
+ api.mockImplementationOnce(() => new Promise((done) => { resolve = done }))
+ let pending!: Promise<unknown>
+ act(() => { pending = state.view.result.current.mutateAsync(input) })
+ await waitFor(() => expect(api).toHaveBeenCalledOnce())
+ const terminal = approved()
+ act(() => projectCommunityWsEventToDb(state.client, { type: "community:message.updated", channelId: "dm-1", messageId: "message-1", botCreation: terminal }))
+ await act(async () => { resolve({ botCreation: botCreationFixture({ status: "declined" }) }); await pending })
+ expect(state.registry.collections.messages.get("message-1")?.botCreation).toEqual(terminal)
+ })
+
+ it.each(["success", "failure"] as const)("withholds retired-owner %s and callbacks", async (outcome) => {
+ const state = await owner(), success = vi.fn(), failure = vi.fn()
+ let resolve!: (value: unknown) => void, reject!: (error: Error) => void
+ api.mockImplementationOnce(() => new Promise((done, fail) => { resolve = done; reject = fail }))
+ let pending!: Promise<unknown>
+ act(() => { pending = state.view.result.current.mutateAsync(input, { onSuccess: success, onError: failure }).catch((error: unknown) => error) })
+ await waitFor(() => expect(api).toHaveBeenCalledOnce())
+ state.runtime.ws.actions.activateProfileAccount("other"); state.runtime.ws.actions.activateProfileAccount("viewer")
+ await act(async () => { if (outcome === "success") resolve({ botCreation: approved() }); else reject(new Error("old failure")); expect(await pending).toMatchObject({ name: "AbortError" }) })
+ expect(success).not.toHaveBeenCalled(); expect(failure).not.toHaveBeenCalled()
+ expect(state.registry.collections.messages.get("message-1")?.botCreation?.status).toBe("pending")
+ expect(state.registry.collections.profiles.has("created-1")).toBe(false)
+ })
+})
diff --git a/src/web/src/hooks/community/mutations/bot-creation.ts b/src/web/src/hooks/community/mutations/bot-creation.ts
new file mode 100644
index 000000000..310b20c0a
--- /dev/null
+++ b/src/web/src/hooks/community/mutations/bot-creation.ts
@@ -0,0 +1,38 @@
+"use client"
+
+import { useQueryClient } from "@tanstack/react-query"
+import { BotCreationPayloadSchema, type BotCreationPayload } from "@alook/shared"
+import { useCommunityCommandMutation } from "../use-community-command-mutation"
+import { useCommunityMutationOrigin } from "../community-origin"
+import { publishCommunityMessageFields } from "@/lib/community-db/sync"
+import { invalidateBotSurfaces } from "../use-bots"
+
+type DecisionInput = {
+ requestId: string
+ messageId: string
+ decision: "approve" | "decline"
+}
+
+export function useBotCreationDecision() {
+ const origin = useCommunityMutationOrigin()
+ const client = useQueryClient()
+ return useCommunityCommandMutation<{ botCreation: BotCreationPayload }, Error, DecisionInput>(origin, {
+ mutationKey: ["community", "bot-creation", "decision"],
+ meta: { observabilityAction: "bot.creation.decision" },
+ retry: false,
+ mutationFn: async ({ requestId, messageId, decision, original }) => {
+ const data = await origin.request<{ botCreation: BotCreationPayload }>(original,
+ `/api/community/bots/creation-requests/${encodeURIComponent(requestId)}`,
+ { method: "PATCH", body: JSON.stringify({ decision }) },
+ )
+ const botCreation = BotCreationPayloadSchema.parse(data.botCreation)
+ if (botCreation.requestId !== requestId) throw new Error("The request changed. Reload this conversation before trying again.")
+ origin.assert(original)
+ publishCommunityMessageFields(client, messageId, { botCreation }, { token: original })
+ return { botCreation }
+ },
+ onSuccess: ({ botCreation }, { resources }) => {
+ if (botCreation.status === "approved") invalidateBotSurfaces(client, undefined, resources.filter(({ queryKey }) => queryKey[0] === "community" && ["bots", "friends", "dms"].includes(String(queryKey[1]))))
+ },
+ })
+}
diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.ts
index 93092c8c9..199ec4a96 100644
--- a/src/web/src/lib/community-db/sync.ts
+++ b/src/web/src/lib/community-db/sync.ts
@@ -2724,16 +2724,21 @@ export function projectCommunityWsEventToDb(
patchMessageFirstPreview(registry, event.channelId, event.messageId, event.content)
return
}
- case "community:message.updated":
+ case "community:message.updated": {
+ const changes = {
+ ...(event.approval !== undefined ? { approval: event.approval } : {}),
+ ...(event.botCreation !== undefined ? { botCreation: event.botCreation } : {}),
+ }
patchRows(
registry,
"messages",
- (row) => ({ ...row, approval: event.approval }),
- (row) => row.id === event.messageId,
+ (row) => row.channelId === event.channelId ? { ...row, ...changes } : row,
+ (row) => row.id === event.messageId && row.channelId === event.channelId,
[event.messageId],
- ["approval"],
+ Object.keys(changes),
)
return
+ }
case "community:reaction.add":
case "community:reaction.remove":
patchRows(
diff --git a/src/web/src/lib/community/bot-creation.server.test.ts b/src/web/src/lib/community/bot-creation.server.test.ts
new file mode 100644
index 000000000..32d64acc0
--- /dev/null
+++ b/src/web/src/lib/community/bot-creation.server.test.ts
@@ -0,0 +1,22 @@
+import { beforeEach, expect, it, vi } from "vitest"
+const mocks = vi.hoisted(() => ({ connect: vi.fn(), push: vi.fn() }))
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return { ...actual, queries: { ...actual.queries, communityFriendship: { ensureNewSiblingBotFriendships: mocks.connect } } }
+})
+vi.mock("./bot-push", () => ({ pushBotEventToMachine: mocks.push }))
+import { completeBotCreation, botCreationFailure } from "./bot-creation.server"
+
+beforeEach(() => vi.clearAllMocks())
+it("connects new siblings in one batch and still pushes every created bot after a friendship failure", async () => {
+ mocks.connect.mockRejectedValueOnce(new Error("temporary friendship failure"))
+ const bots = ["a", "b"].map(id => ({ id, name: id, discriminator: "0001", description: "Role", machineId: "machine" }))
+ await completeBotCreation({} as Env, {} as never, "owner", { name: "Owner", discriminator: "0002" }, bots)
+ expect(mocks.connect).toHaveBeenCalledExactlyOnceWith({}, "owner", ["a", "b"])
+ expect(mocks.push.mock.calls.map(([, machineId, event]) => [machineId, event.type, event.botId])).toEqual([["machine", "bot:added", "a"], ["machine", "bot:added", "b"]])
+})
+
+it("preserves unexpected errors for the route error handler", () => {
+ const error = new Error("unexpected creation failure")
+ expect(() => botCreationFailure(error, { requestId: "request" })).toThrow(error)
+})
diff --git a/src/web/src/lib/community/bot-creation.server.ts b/src/web/src/lib/community/bot-creation.server.ts
new file mode 100644
index 000000000..c6e874478
--- /dev/null
+++ b/src/web/src/lib/community/bot-creation.server.ts
@@ -0,0 +1,17 @@
+import { queries, type Database } from "@alook/shared"
+import { pushBotEventToMachine } from "./bot-push"
+
+export async function completeBotCreation(env: Env, db: Database, ownerId: string, owner: { name: string; discriminator: string }, bots: readonly { id: string; name: string; discriminator: string; description: string; machineId: string }[]) {
+ try {
+ await queries.communityFriendship.ensureNewSiblingBotFriendships(db, ownerId, bots.map((bot) => bot.id))
+ } catch { }
+ for (const bot of bots) await pushBotEventToMachine(env, bot.machineId, {
+ type: "bot:added", botId: bot.id, name: bot.name, discriminator: bot.discriminator,
+ description: bot.description || undefined, ownerName: owner.name, ownerDiscriminator: owner.discriminator,
+ })
+}
+
+export function botCreationFailure(error: unknown, context: Record<string, unknown> = {}) {
+ if (error instanceof queries.communityBotCreation.BotCreationError) return Response.json({ error: error.message, code: error.code, ...error.details, ...context }, { status: error.status })
+ throw error
+}
diff --git a/src/web/src/lib/community/enrich-messages.test.ts b/src/web/src/lib/community/enrich-messages.test.ts
index f5eee34be..c423dc233 100644
--- a/src/web/src/lib/community/enrich-messages.test.ts
+++ b/src/web/src/lib/community/enrich-messages.test.ts
@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({
getFirstMessages: vi.fn(),
listParticipants: vi.fn(),
hydrateApprovals: vi.fn(),
+ hydrateCreation: vi.fn(),
getLatestSeq: vi.fn(),
}))
@@ -47,6 +48,7 @@ vi.mock("@alook/shared", async () => {
...actual.queries.communityThread,
listParticipantsForChannels: (...args: unknown[]) => mocks.listParticipants(...args),
},
+ communityBotCreation: { hydrateCreationRequestsForDmMessages: (...args: unknown[]) => mocks.hydrateCreation(...args) },
communityFriendship: {
...actual.queries.communityFriendship,
hydrateApprovalsForDmMessages: (...args: unknown[]) => mocks.hydrateApprovals(...args),
@@ -56,6 +58,7 @@ vi.mock("@alook/shared", async () => {
})
import { enrichMessages } from "./enrich-messages"
+import { botCreationFixture } from "@/test/bot-creation-fixtures"
describe("enrichMessages attachment projection", () => {
beforeEach(() => {
@@ -67,6 +70,7 @@ describe("enrichMessages attachment projection", () => {
mocks.getFirstMessages.mockResolvedValue([])
mocks.listParticipants.mockResolvedValue([])
mocks.hydrateApprovals.mockResolvedValue(new Map())
+ mocks.hydrateCreation.mockResolvedValue(new Map())
mocks.getLatestSeq.mockResolvedValue(9)
})
@@ -81,6 +85,20 @@ describe("enrichMessages attachment projection", () => {
expect(mocks.getLatestSeq).toHaveBeenCalledWith(db, { channelId: "dm1" })
})
+ it("hydrates only creation IDs in a mixed DM and does no creation lookup for ordinary/friend messages", async () => {
+ mocks.listAttachments.mockResolvedValue([])
+ const base = { seq: 1, authorId: "u1", authorName: "Alice", authorImage: null, content: "hello", mentionType: null, replyToId: null, embeds: null, createdAt: "2026-08-13T00:00:00.000Z", channelId: "dm1" }
+ const ordinary = [{ ...base, id: "chat", type: "default" }, { ...base, id: "friend", type: "friend_approval" }]
+ await enrichMessages({} as never, "u1", { channelId: "dm1", isDm: true }, ordinary)
+ expect(mocks.hydrateCreation).not.toHaveBeenCalled()
+ const payload = botCreationFixture()
+ mocks.hydrateCreation.mockResolvedValue(new Map([["creation", payload]]))
+ const result = await enrichMessages({} as never, "u1", { channelId: "dm1", isDm: true }, [...ordinary, { ...base, id: "creation", type: "bot_creation_request" }])
+ expect(mocks.hydrateCreation).toHaveBeenCalledExactlyOnceWith({}, ["creation"], "u1")
+ expect(result.messages.find(message => message.id === "creation")?.botCreation).toEqual(payload)
+ expect(result.messages.find(message => message.id === "chat")?.botCreation).toBeUndefined()
+ })
+
it("projects a canonical thumbnail beside reply enrichment", async () => {
mocks.listAttachments.mockResolvedValue([{
id: "att_1",
diff --git a/src/web/src/lib/community/enrich-messages.ts b/src/web/src/lib/community/enrich-messages.ts
index fb634e79c..e8894e9c5 100644
--- a/src/web/src/lib/community/enrich-messages.ts
+++ b/src/web/src/lib/community/enrich-messages.ts
@@ -26,9 +26,10 @@ export async function enrichMessages(
): Promise<{ messages: unknown[]; latestSeq: number }> {
const isDm = scope.isDm === true
const messageIds = items.map((m) => m.id)
+ const creationMessageIds = items.filter((message) => message.type === "bot_creation_request").map((message) => message.id)
const replyToIds = items.flatMap((row) => row.replyToId ? [row.replyToId] : [])
- const [contextForChannel, childChannels, latestSeq, approvalByMessageId] = await Promise.all([
+ const [contextForChannel, childChannels, latestSeq, approvalByMessageId, botCreationByMessageId] = await Promise.all([
loadApiMessageContext(db, userId, messageIds, () => replyToIds.length > 0
? withD1Retry(
() => queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, { channelId: scope.channelId }),
@@ -47,6 +48,9 @@ export async function enrichMessages(
isDm && messageIds.length > 0
? queries.communityFriendship.hydrateApprovalsForDmMessages(db, messageIds, userId)
: Promise.resolve(new Map()),
+ isDm && creationMessageIds.length > 0
+ ? queries.communityBotCreation.hydrateCreationRequestsForDmMessages(db, creationMessageIds, userId)
+ : Promise.resolve(new Map()),
])
const context = contextForChannel(scope.channelId)
@@ -107,6 +111,7 @@ export async function enrichMessages(
mapMessageForApi(r, {
...context,
threadByMessageId,
+ botCreationByMessageId,
approvalByMessageId: approvalByMessageId as Map<string, import("@alook/shared").FriendApprovalPayload>,
}, scope.contract, scope.channelId),
)
diff --git a/src/web/src/lib/community/machine-options.server.test.ts b/src/web/src/lib/community/machine-options.server.test.ts
new file mode 100644
index 000000000..4875f4ec5
--- /dev/null
+++ b/src/web/src/lib/community/machine-options.server.test.ts
@@ -0,0 +1,23 @@
+import { beforeEach, expect, it, vi } from "vitest"
+const mocks = vi.hoisted(() => ({ list: vi.fn() }))
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return { ...actual, queries: { ...actual.queries, communityMachine: { ...actual.queries.communityMachine, listMachinesForUser: mocks.list } } }
+})
+import { readPlatformMachines, projectModelOptions } from "./machine-options.server"
+
+beforeEach(() => vi.clearAllMocks())
+it("scopes the machine list to the owner and projects both online and offline targets", async () => {
+ const db = {} as never
+ mocks.list.mockResolvedValueOnce([{ id: "m1", displayName: "Work", status: "online", daemonVersion: "1.0", hostname: "private" }, { id: "m2", displayName: "Home", status: "offline", daemonVersion: "0.9" }])
+ expect(await readPlatformMachines(db, "owner", "m1")).toEqual({ machines: [{ id: "m1", name: "Work", status: "online", daemonVersion: "1.0" }, { id: "m2", name: "Home", status: "offline", daemonVersion: "0.9" }], requesterMachineId: "m1" })
+ expect(mocks.list).toHaveBeenCalledExactlyOnceWith(db, "owner")
+})
+it("keeps reported model defaults, display names and effort values", () => {
+ const option = projectModelOptions("m1", { id: "codex", reasoning: { updateMode: "live_next_turn", catalogOrigin: "native_report", defaultModelId: "model/a", models: [{ id: "model/a", displayName: "Model A", supportedReasoningEfforts: [{ value: "high" }], defaultReasoningEffort: "high" }, { id: "custom/b", supportedReasoningEfforts: [] }] } })
+ expect(option).toEqual({ machineId: "m1", backendId: "codex", source: "stored_report", readAt: expect.any(String), observedAt: null, catalogOrigin: "native_report", catalogState: "reported", modelRequired: false, defaultModelId: "model/a", models: [{ id: "model/a", displayName: "Model A", reasoningEfforts: [{ value: "high" }], defaultReasoningEffort: "high" }, { id: "custom/b", reasoningEfforts: [], defaultReasoningEffort: null }] })
+})
+it("distinguishes an unreported catalog from a reported empty catalog", () => {
+ expect(projectModelOptions("m1", { id: "opencode" })).toMatchObject({ modelRequired: true, catalogState: "not_reported", catalogOrigin: "unknown", defaultModelId: null, models: null })
+ expect(projectModelOptions("m1", { id: "codex", reasoning: { updateMode: "live_next_turn", models: [] } })).toMatchObject({ catalogState: "reported", defaultModelId: null, models: [] })
+})
diff --git a/src/web/src/lib/community/machine-options.server.ts b/src/web/src/lib/community/machine-options.server.ts
new file mode 100644
index 000000000..7c741e5f1
--- /dev/null
+++ b/src/web/src/lib/community/machine-options.server.ts
@@ -0,0 +1,19 @@
+import { queries, requiresExplicitModel, type CommunityMachineRuntime, type RuntimeReasoningCatalog } from "@alook/shared"
+import type { Database } from "@alook/shared"
+
+export async function readPlatformMachines(db: Database, ownerId: string, requesterMachineId: string) {
+ const machines = await queries.communityMachine.listMachinesForUser(db, ownerId)
+ return { 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) {
+ const catalog: RuntimeReasoningCatalog | undefined = runtime.reasoning
+ const 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) }
+ 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)
+ return { ...base, inCatalog: Boolean(entry), model: entry ? present(entry) : { id: model, reasoningEfforts: null, defaultReasoningEffort: null } }
+ }
+ return { ...base, defaultModelId: catalog?.defaultModelId ?? null, models: catalog ? catalog.models.map(present) : null }
+}
diff --git a/src/web/src/lib/community/message-dispatcher.test.ts b/src/web/src/lib/community/message-dispatcher.test.ts
index 6c71d65b8..cd5d565fc 100644
--- a/src/web/src/lib/community/message-dispatcher.test.ts
+++ b/src/web/src/lib/community/message-dispatcher.test.ts
@@ -16,6 +16,7 @@ const mockResolveNotificationRecipients = vi.fn()
const mockResolveEligibility = vi.fn()
const mockFindWakeCandidates = vi.fn()
const mockLogWarn = vi.fn()
+const mockHydrateCreation = vi.fn()
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -56,6 +57,7 @@ vi.mock("@alook/shared", async () => {
communityNotificationSetting: {
policyAllows: actual.queries.communityNotificationSetting.policyAllows,
},
+ communityBotCreation: { hydrateCreationRequestsForDmMessages: (...args: unknown[]) => mockHydrateCreation(...args) },
communityBot: {
findWakeCandidates: (...args: unknown[]) => mockFindWakeCandidates(...args),
},
@@ -157,6 +159,7 @@ describe("planCommittedMessage", () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetMessage.mockResolvedValue(message)
+ mockHydrateCreation.mockResolvedValue(new Map())
mockGetWakeContextMessageInScope.mockResolvedValue(null)
mockGetMessageClientNonceForDelivery.mockResolvedValue("nonce_1")
mockGetChannel.mockResolvedValue(channel)
@@ -397,6 +400,19 @@ describe("planCommittedMessage", () => {
expect(plan.pushUserIds).toEqual(["private_member"])
})
+ it("carries the same owner identity in requester realtime and canonical REST projections", async () => {
+ const botCreation = { requestId: "request", requesterId: "author_1", ownerUserId: "owner", status: "pending", createdAt: message.createdAt, resolvedAt: null,
+ bots: [{ itemId: "item", name: "Reviewer", machineId: "machine", machineName: "Work Mac", backendId: "codex", model: "custom/model", reasoningEffort: null, description: "Review sources", reason: "Independent review", createdBot: null }] }
+ mockGetMessage.mockResolvedValue({ ...message, type: "bot_creation_request" })
+ mockGetChannel.mockResolvedValue({ ...channel, type: "dm", serverId: null })
+ mockResolveRecipients.mockResolvedValue(["author_1", "owner"])
+ mockHydrateCreation.mockResolvedValue(new Map([[message.id, botCreation]]))
+ const plan = await planCommittedMessage({} as never, message.id)
+ expect(plan.messageEvent.message.botCreation).toEqual(botCreation)
+ expect(plan.messageEvent.message.botCreation).not.toHaveProperty("canDecide")
+ expect(mockHydrateCreation).toHaveBeenCalledWith(expect.anything(), [message.id], "author_1")
+ })
+
it("plans a DM from its two resolved members without server projections", async () => {
mockGetChannel.mockResolvedValue({
...channel,
@@ -417,6 +433,7 @@ describe("planCommittedMessage", () => {
expect(plan.pushUserIds).toEqual(["dm_peer"])
expect(plan.messageEvent).not.toHaveProperty("serverId")
expect(plan).not.toHaveProperty("parentProjection")
+ expect(mockHydrateCreation).not.toHaveBeenCalled()
})
it("keeps the author in content while excluding them from every side effect", async () => {
diff --git a/src/web/src/lib/community/message-dispatcher.ts b/src/web/src/lib/community/message-dispatcher.ts
index 3ede6ad41..ee9da6854 100644
--- a/src/web/src/lib/community/message-dispatcher.ts
+++ b/src/web/src/lib/community/message-dispatcher.ts
@@ -182,6 +182,9 @@ export async function planCommittedMessage(
content: replyTarget.content,
})
}
+ const creationRequest = channel.type === "dm" && message.type === "bot_creation_request"
+ ? (await queries.communityBotCreation.hydrateCreationRequestsForDmMessages(db, [message.id], message.authorId)).get(message.id)
+ : undefined
const messageInput = {
type: WS_EVENTS.MESSAGE_CREATE,
channelId: message.channelId,
@@ -189,6 +192,7 @@ export async function planCommittedMessage(
...(channel.parentChannelId ? { parentChannelId: channel.parentChannelId } : {}),
message: mapMessageForWs(message, {
replyMap,
+ botCreation: creationRequest,
clientNonce: clientNonce ?? undefined,
...(contract === 3 ? { resourceAttachments: groupAttachments(attachments)[message.id] ?? [] } : {}),
attachments: attachments.map((attachment) => ({
diff --git a/src/web/src/lib/community/message-payload.test.ts b/src/web/src/lib/community/message-payload.test.ts
index cfc542718..884e9cdbe 100644
--- a/src/web/src/lib/community/message-payload.test.ts
+++ b/src/web/src/lib/community/message-payload.test.ts
@@ -1,5 +1,11 @@
-import { describe, it, expect } from "vitest"
-import { mapMessageForApi, mapMessageForWs, type MessageRow } from "./message-payload"
+import { beforeEach, describe, it, expect, vi } from "vitest"
+const creationMocks = vi.hoisted(() => ({ hydrate: vi.fn(), attachments: vi.fn(), reactions: vi.fn() }))
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return { ...actual, queries: { ...actual.queries, communityBotCreation: { hydrateCreationRequestsForDmMessages: creationMocks.hydrate }, communityAttachment: { listByMessageIds: creationMocks.attachments }, communityReaction: { listReactionsByMessageIds: creationMocks.reactions } } }
+})
+import { botCreationFixture } from "@/test/bot-creation-fixtures"
+import { readCommunityMessageResource, mapMessageForApi, mapMessageForWs, type MessageRow } from "./message-payload"
const baseRow: MessageRow = {
id: "m1",
@@ -208,3 +214,24 @@ describe("attachment contract selection", () => {
expect(mapMessageForApi({ ...baseRow, authorAvatarVersion: 2 }, ctx, 3, "channel").attachments).toEqual([attachment])
})
})
+
+
+describe("single-message creation payload hydration", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ creationMocks.attachments.mockResolvedValue([])
+ creationMocks.reactions.mockResolvedValue([])
+ })
+ it.each(["default", "friend_approval"])("does not query creation requests for %s", async type => {
+ await readCommunityMessageResource({} as never, "viewer", { ...baseRow, type, channelId: "dm" }, 3)
+ expect(creationMocks.hydrate).not.toHaveBeenCalled()
+ })
+ it("hydrates a creation card with the same immutable owner identity", async () => {
+ const payload = botCreationFixture()
+ creationMocks.hydrate.mockResolvedValue(new Map([[baseRow.id, payload]]))
+ const message = await readCommunityMessageResource({} as never, "viewer", { ...baseRow, type: "bot_creation_request", channelId: "dm" }, 3)
+ expect(creationMocks.hydrate).toHaveBeenCalledExactlyOnceWith({}, [baseRow.id], "viewer")
+ expect(message.botCreation).toEqual(payload)
+ expect(message.botCreation).not.toHaveProperty("canDecide")
+ })
+})
diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.ts
index e82fb0a95..ae2a20e1d 100644
--- a/src/web/src/lib/community/message-payload.ts
+++ b/src/web/src/lib/community/message-payload.ts
@@ -15,7 +15,7 @@
* field on the wire is one edit, not four.
*/
import { CommunityMessageResourceSchema, queries, truncateMessagePreview, type CommunityContract, type Database, type MentionType, type CommunityMessageResource, type CommunityMessageAttachment, type CommunityLegacyMessageCreate } from "@alook/shared"
-import type { FriendApprovalPayload } from "@alook/shared"
+import type { BotCreationPayload, FriendApprovalPayload } from "@alook/shared"
import { avatarInitial } from "@/lib/community/avatar"
import { canonicalUserImage } from "@/lib/community/storage"
import { projectMessageWireType } from "@/lib/community/message-wire-type"
@@ -85,6 +85,7 @@ export type ApiMessageContext = {
threadByMessageId?: Map<string, ThreadPreview>
/** Optional: only the DM messages route hydrates friend-approval cards. */
approvalByMessageId?: Map<string, FriendApprovalPayload>
+ botCreationByMessageId?: Map<string, BotCreationPayload>
}
export async function loadApiMessageContext(db: Database, userId: string, ids: string[], readReplies: () => ReturnType<typeof queries.communityMessage.getMessagesByIdsInChannels>, skipEmpty = false) {
@@ -102,7 +103,8 @@ export async function loadApiMessageContext(db: Database, userId: string, ids: s
export async function readCommunityMessageResource(db: Database, userId: string, message: Parameters<typeof mapMessageForApi>[0] & { channelId: string }, contract: CommunityContract) {
const context = await loadApiMessageContext(db, userId, [message.id], () => message.replyToId
? queries.communityMessage.getMessagesByIdsInScope(db, [message.replyToId], { channelId: message.channelId }) : Promise.resolve([]))
- return mapMessageForApi(message, context(message.channelId), contract, message.channelId)
+ const botCreationByMessageId = message.type === "bot_creation_request" ? await queries.communityBotCreation.hydrateCreationRequestsForDmMessages(db, [message.id], userId) : new Map<string, BotCreationPayload>()
+ return mapMessageForApi(message, { ...context(message.channelId), botCreationByMessageId }, contract, message.channelId)
}
// Splits the DB's `type` column value into the wire's `{ type, systemKind }`
@@ -128,6 +130,7 @@ export function mapMessageForApi(row: MessageRow, ctx: ApiMessageContext, contra
...(Array.isArray(row.embeds) ? { embeds: row.embeds } : {}),
reactions: ctx.reactionsByMessage[row.id], thread: ctx.threadByMessageId?.get(row.id),
approval: ctx.approvalByMessageId?.get(row.id),
+ botCreation: ctx.botCreationByMessageId?.get(row.id),
})
return {
...coreFields(row, ctx.replyMap),
@@ -139,6 +142,7 @@ export function mapMessageForApi(row: MessageRow, ctx: ApiMessageContext, contra
reactions: ctx.reactionsByMessage[row.id]?.length ? ctx.reactionsByMessage[row.id] : undefined,
thread: ctx.threadByMessageId?.get(row.id),
approval: ctx.approvalByMessageId?.get(row.id),
+ botCreation: ctx.botCreationByMessageId?.get(row.id),
}
}
@@ -165,11 +169,13 @@ export type WsMessageContext = {
* is filtered out below so a content fingerprint never reaches the wire.
*/
clientNonce?: string
+ botCreation?: BotCreationPayload
}
export function mapMessageForWs(row: MessageRow, ctx: WsMessageContext, contract: CommunityContract = 2, channelId?: string) {
if (contract === 3) return CommunityMessageResourceSchema.required({ authorName: true, authorAvatarVersion: true }).parse({
...coreFields(row, ctx.replyMap, ctx.clientNonce ?? null),
+ botCreation: ctx.botCreation,
channelId,
authorAvatar: canonicalUserImage(row.authorId, row.authorImage, row.authorAvatarVersion),
clientNonce: ctx.clientNonce && !ctx.clientNonce.startsWith("srv:") ? ctx.clientNonce : null,
@@ -183,6 +189,7 @@ export function mapMessageForWs(row: MessageRow, ctx: WsMessageContext, contract
// nonce, but if a `srv:` value ever reaches here it is dropped, not fanned.
return {
...coreFields(row, ctx.replyMap, ctx.clientNonce ?? null),
+ botCreation: ctx.botCreation,
// The shared CommunityMessageCreate.embeds is `unknown[]` — narrow here
// rather than widening the wire type.
embeds: Array.isArray(row.embeds) ? row.embeds : undefined,
diff --git a/src/web/src/lib/community/models/message.ts b/src/web/src/lib/community/models/message.ts
index 9cb1566bc..2092aea1b 100644
--- a/src/web/src/lib/community/models/message.ts
+++ b/src/web/src/lib/community/models/message.ts
@@ -63,9 +63,10 @@ export function applyMessageReaction(source: Msg["reactions"], emoji: string, us
return rows.filter((row) => row.userIds.length).map((row) => ({ ...row, count: row.userIds.length, me: viewerId !== null && row.userIds.includes(viewerId) }))
}
-export function messageProfileIds(message: Pick<CommunityMessagePreview, "authorId" | "replyTo" | "thread" | "approval">): string[] {
+export function messageProfileIds(message: Pick<CommunityMessagePreview, "authorId" | "replyTo" | "thread" | "approval" | "botCreation">): string[] {
return [
...(message.authorId ? [message.authorId] : []),
+ ...(message.botCreation ? [message.botCreation.requesterId, ...message.botCreation.bots.flatMap((bot) => bot.createdBot ? [bot.createdBot.id] : [])] : []),
...(message.replyTo?.authorId ? [message.replyTo.authorId] : []),
...(message.thread?.participants ?? []).map((participant) => participant.id),
...[message.approval?.otherProfile, message.approval?.botProfile, message.approval?.waitingOnProfile]
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 7d12d7628..8841edec3 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -2,6 +2,9 @@
// product components (so the attribute strings are never hand-typed) and the
// Playwright specs (via _fixtures/testids). Naming: community-<区域>-<元素>[-<标识>].
export const tid = {
+ botCreationRequestCard: "community-bot-creation-request-card",
+ botCreationApprove: "community-bot-creation-approve",
+ botCreationDecline: "community-bot-creation-decline",
composerInput: "community-composer-input",
channelComposerShell: "community-composer-shell",
composerFileInput: "community-composer-file-input",
diff --git a/src/web/src/lib/observability/coverage.test.ts b/src/web/src/lib/observability/coverage.test.ts
index fe9492d59..306839f9e 100644
--- a/src/web/src/lib/observability/coverage.test.ts
+++ b/src/web/src/lib/observability/coverage.test.ts
@@ -36,6 +36,7 @@ it("keeps existing mutation owners inventoried and semantic variants on the whit
})
const mutationCoverage = [
+ { "file": "src/web/src/hooks/community/mutations/bot-creation.ts", "owner": "useBotCreationDecision", "action": "bot.creation.decision" },
{
"file": "src/web/src/app/c/invite/[token]/invite-accept-client.tsx",
"owner": "InviteAcceptInner",
diff --git a/src/web/src/lib/observability/coverage.ts b/src/web/src/lib/observability/coverage.ts
index 86b456575..0a4cf130c 100644
--- a/src/web/src/lib/observability/coverage.ts
+++ b/src/web/src/lib/observability/coverage.ts
@@ -49,6 +49,8 @@ export const apiRoutes = [
"/api/community/bots/[id]/notifications/channel/[scopeId]",
"/api/community/bots/[id]/notifications/server/[scopeId]",
"/api/community/bots/[id]/reset-session",
+ "/api/community/bots/creation-requests",
+ "/api/community/bots/creation-requests/[id]",
"/api/community/bots/me/nap",
"/api/community/channels",
"/api/community/channels/[id]",
@@ -91,6 +93,7 @@ export const apiRoutes = [
"/api/community/machines",
"/api/community/machines/[id]",
"/api/community/machines/[id]/discover-models",
+ "/api/community/machines/[id]/models",
"/api/community/machines/[id]/reconnect",
"/api/community/machines/[id]/reset-agents",
"/api/community/machines/[id]/stop",
@@ -184,6 +187,7 @@ export const actionNames = [
"bot.bug_report.submit",
"bot.command",
"bot.create",
+ "bot.creation.decision",
"bot.delete",
"bot.notification.update",
"bot.session.reset",
diff --git a/src/web/src/test/bot-creation-fixtures.ts b/src/web/src/test/bot-creation-fixtures.ts
new file mode 100644
index 000000000..b1b38f69b
--- /dev/null
+++ b/src/web/src/test/bot-creation-fixtures.ts
@@ -0,0 +1,14 @@
+import type { BotCreationPayload } from "@alook/shared"
+
+export function botCreationFixture(overrides: Partial<BotCreationPayload> = {}): BotCreationPayload {
+ return {
+ requestId: "request-1", status: "pending", requesterId: "requester", ownerUserId: "viewer",
+ createdAt: "2026-10-22T09:00:00Z", resolvedAt: null,
+ bots: [{
+ itemId: "item-1", name: "Researcher", machineId: "machine-1", backendId: "codex",
+ model: "model-a", reasoningEffort: "high", reason: "Check sources independently",
+ description: "Find sources and report uncertainty", machineName: "Work Mac", createdBot: null,
+ }],
+ ...overrides,
+ }
+}
diff --git a/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts b/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
index a8dead0ee..ee68920ed 100644
--- a/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
+++ b/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
@@ -1,6 +1,7 @@
import { test, expect } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
import { WEB_URL } from "./_setup/paths"
+import { connectMachine } from "./_fixtures/community-machine"
import type { CaseActors, CaseResources } from "./_fixtures/case-fixture"
async function prepareCase(actors: CaseActors, caseResources: CaseResources) {
@@ -42,6 +43,7 @@ async function prepareCase(actors: CaseActors, caseResources: CaseResources) {
expect(activate.status).toBe(200)
const body = await activate.json() as {
machineId: string
+ credential: string
}
const machineId = body.machineId
caseResources.own(machineId, async (id) => {
@@ -51,6 +53,7 @@ async function prepareCase(actors: CaseActors, caseResources: CaseResources) {
activationProof.response = activate
activationProof.machineId = machineId
await pairingToken.close()
+ await connectMachine(body.credential, caseResources, { machineId, headers: aliceHeaders() }).opened
return machineId
}
async function createBot(machineId: string, name: string): Promise<string> {
diff --git a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
index b9653dda3..b2a0e1a3a 100644
--- a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
+++ b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
@@ -1,11 +1,10 @@
-import { createRequire } from "module"
-import { resolve } from "path"
import type { Locator, Page, Route, TestInfo, WebSocket as BrowserSocket } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"
import { tid } from "./_fixtures/testids"
-import { MACHINE_WS_URL, REPO_ROOT, WEB_URL } from "./_setup/paths"
+import { WEB_URL } from "./_setup/paths"
+import { connectMachine } from "./_fixtures/community-machine"
import type { CaseActors, CaseResources, OwnedCaseResource } from "./_fixtures/case-fixture"
async function prepareCase(actors: CaseActors, caseResources: CaseResources) {
@@ -369,43 +368,6 @@ async function setBotMark(
await expect(response.json()).resolves.toMatchObject({ type: "mark", value: true })
}
-type MachineSocket = {
- send: (data: string) => void
- close: () => void
- readonly readyState: number
- once(event: "close", listener: () => void): void
- once(event: "open", listener: () => void): void
- once(event: "error", listener: (error: Error) => void): void
- once(event: "message", listener: (data: unknown) => void): void
- on(event: "message", listener: (data: unknown) => void): void
- off(event: "message", listener: (data: unknown) => void): void
-}
-
-function connectMachine(credential: string, caseResources: CaseResources) {
- const requireFromDaemon = createRequire(resolve(REPO_ROOT, "src/daemon/package.json"))
- const Ws = requireFromDaemon("ws") as {
- WebSocket: new (url: string, options: { headers: Record<string, string> }) => MachineSocket
- }
- const socket = new Ws.WebSocket(MACHINE_WS_URL.replace(/^http/, "ws"), {
- headers: { Authorization: `Bearer ${credential}` },
- })
- const ownedSocket = caseResources.own(socket, async (captured) => {
- await new Promise<void>((resolve) => {
- if (captured.readyState === 3) { resolve(); return }
- captured.once("close", resolve)
- captured.close()
- })
- })
- return {
- socket,
- close: () => ownedSocket.close(),
- opened: new Promise<void>((resolveOpen, reject) => {
- socket.once("open", () => resolveOpen())
- socket.once("error", reject)
- }),
- }
-}
-
async function openBotProfile(page: Page, botName: string): Promise<void> {
await page.getByRole("button", { name: botName, exact: true }).click()
await expect(page.getByTestId(tid.profileCard)).toBeVisible()
@@ -543,9 +505,9 @@ test("full audit log reveals a truncated row by hover and touch", async ({ caseA
const longAuditTarget = `/Users/alice/workspace/${"deeply-nested-audit-target/".repeat(5)}result-${suffix}.md`
const fullAuditText = `read · ${longAuditTarget}`
const { credential, machineId } = await pairMachine()
- const botId = await createBot(machineId, `Tooltip bot ${suffix}`)
- const machine = connectMachine(credential, caseResources)
+ const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })
await machine.opened
+ const botId = await createBot(machineId, `Tooltip bot ${suffix}`)
let caseJourneyFailure1: unknown
let caseJourneyFailure1Present = false
@@ -625,7 +587,7 @@ test("owned bot profile preview stays root-bounded from its first visible frame"
const actors = await caseActors(["alice", "bob"])
const { asUser } = actors
const { seedChannel, seedForumThread, seedJoinServer, seedServer } = actors.seed
- const { jsonRequest, pairMachine, createBot, joinBotToServer } = await prepareCase(actors, caseResources)
+ const { jsonRequest, pairMachine, createBot, joinBotToServer, headersFor } = await prepareCase(actors, caseResources)
const suffix = Date.now().toString(36)
const serverId = await seedServer("alice", `preview-overflow-${suffix}`)
@@ -642,6 +604,8 @@ test("owned bot profile preview stays root-bounded from its first visible frame"
await seedJoinServer("alice", "bob", serverId)
const { credential, machineId } = await pairMachine()
+ const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })
+ await machine.opened
const botName = `Overflow bot ${suffix}`
const botId = await createBot(machineId, botName)
const runnerKey = await enrollBot(credential, botId)
@@ -738,6 +702,8 @@ test("owner-only bot mark sticker, Stop lifecycle, owner swap, and URL-owned aud
await seedJoinServer("alice", "bob", serverId)
const { credential, machineId } = await pairMachine()
+ const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })
+ await machine.opened
const botName = `Preview bot ${suffix} long-name`
const botId = await createBot(machineId, botName)
const runnerKey = await enrollBot(credential, botId)
@@ -794,8 +760,6 @@ test("owner-only bot mark sticker, Stop lifecycle, owner swap, and URL-owned aud
)
expect(removeStaleBot.status).toBe(204)
- const machine = connectMachine(credential, caseResources)
- await machine.opened
let caseJourneyFailure2: unknown
let caseJourneyFailure2Present = false
try {
@@ -928,7 +892,14 @@ let caseJourneyFailure2Present = false
await attachPageScreenshot(testInfo, "bot-work-sticker-activity-running-desktop", alice.page)
await marksTab.click()
const interruptFrame = new Promise<unknown>((resolveFrame) => {
- machine.socket.once("message", (data) => resolveFrame(JSON.parse(String(data))))
+ const onMessage = (data: unknown) => {
+ const frame = JSON.parse(String(data)) as { type: string }
+ if (frame.type === "machine:heartbeat") return
+ machine.socket.off("message", onMessage)
+ resolveFrame(frame)
+ }
+ caseResources.own(onMessage, async captured => { machine.socket.off("message", captured) })
+ machine.socket.on("message", onMessage)
})
await stop.click()
await expect(stop).toContainText("Stopping…")
@@ -1057,9 +1028,11 @@ test("CommunitySheet footers keep four consumers horizontal and intrinsic at 390
const actors = await caseActors(["alice"])
const { asUser } = actors
const { seedChannel, seedServer } = actors.seed
- const { cleanupCreatedResources, jsonRequest, pairMachine, createBot } = await prepareCase(actors, caseResources)
+ const { cleanupCreatedResources, jsonRequest, pairMachine, createBot, headersFor } = await prepareCase(actors, caseResources)
- const { machineId } = await pairMachine()
+ const { credential, machineId } = await pairMachine()
+ const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })
+ await machine.opened
const botName = `Footer bot ${Date.now().toString(36)}`
await createBot(machineId, botName)
const { page } = await asUser("alice")
@@ -1334,12 +1307,12 @@ for (const scenario of ["same-day", "cross-day"] as const) {
test(`Activity ${scenario} older pages preserve real event positions at ${width}`, async ({ caseActors, caseResources }, testInfo) => {
test.setTimeout(120_000)
const actors = await caseActors(["alice"])
- const { pairMachine, createBot, jsonRequest } = await prepareCase(actors, caseResources)
+ const { pairMachine, createBot, jsonRequest, headersFor } = await prepareCase(actors, caseResources)
const { credential, machineId } = await pairMachine()
+ const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })
+ await machine.opened
const suffix = Date.now().toString(36)
const botId = await createBot(machineId, `Anchor ${scenario} ${width} ${suffix}`)
- const machine = connectMachine(credential, caseResources)
- await machine.opened
let gate: Awaited<ReturnType<typeof gateOlderActivityPages>> | undefined
let journeyFailure: unknown
let journeyFailurePresent = false
@@ -1434,17 +1407,17 @@ for (const width of [1280, 390] as const) {
test(`Activity recovery, live reading and reopen preserve event ownership at ${width}`, async ({ caseActors, caseResources }, testInfo) => {
test.setTimeout(120_000)
const actors = await caseActors(["alice"])
- const { pairMachine, createBot, jsonRequest } = await prepareCase(actors, caseResources)
+ const { pairMachine, createBot, jsonRequest, headersFor } = await prepareCase(actors, caseResources)
const suffix = Date.now().toString(36)
const { credential, machineId } = await pairMachine()
+ const machine = connectMachine(credential, caseResources, { machineId, headers: headersFor("alice") })
+ await machine.opened
const botId = await createBot(machineId, `Recovery ${width} ${suffix}`)
- const machine = connectMachine(credential, caseResources)
let gate: Awaited<ReturnType<typeof gateOlderActivityPages>> | undefined
let journeyFailure: unknown
let journeyFailurePresent = false
const steps: Array<Record<string, unknown>> = []
try {
- await machine.opened
const history = await seedActivityHistory({ machine, botId, suffix, scenario: "same-day", caseResources, jsonRequest, testInfo })
const { page } = await actors.asUser("alice", { viewport: { width, height: 900 }, colorScheme: width === 390 ? "dark" : "light" })
const frames = observeActivityFrames(page, caseResources)
diff --git a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts
index a788603bc..699cba7d5 100644
--- a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts
+++ b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts
@@ -6,6 +6,7 @@ import { calendarDayKeyDaysAgo, dayKeyInTimeZone } from "@alook/shared"
import { test, expect } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
import { tid } from "./_fixtures/testids"
+import { connectMachine } from "./_fixtures/community-machine"
import { REPO_ROOT, WEB_URL } from "./_setup/paths"
import type { CaseActors } from "./_fixtures/case-fixture"
@@ -516,6 +517,7 @@ test("My Bots renders Pi usage through real D1 and the unmocked bots API", async
const ownerId = userId("alice")
let machineId: string | undefined
let botId: string | undefined
+ let machine: ReturnType<typeof connectMachine> | undefined
const ownedD1 = caseResources.own(ownerId, async () => {
executeLocalD1([
botId ? `DELETE FROM community_bot_daily_token_usage WHERE bot_id = ${sqlLiteral(botId)}` : "",
@@ -549,7 +551,10 @@ let caseJourneyFailure1Present = false
}),
})
expect(activateResponse.ok).toBe(true)
- machineId = ((await activateResponse.json()) as { machineId: string }).machineId
+ const activation = await activateResponse.json() as { machineId: string; credential: string }
+ machineId = activation.machineId
+ machine = connectMachine(activation.credential, caseResources, { machineId, headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL } })
+ await machine.opened
const createResponse = await postAsAlice("/api/community/bots", {
name: `Local Day ${randomUUID().slice(0, 8)}`,
@@ -672,6 +677,7 @@ let caseJourneyFailure1Present = false
} catch (error) { caseJourneyFailure1 = error; caseJourneyFailure1Present = true; throw error } finally {
try {
+ await machine?.close()
await ownedD1.close()
} catch (cleanupError) { if (caseJourneyFailure1Present) throw new AggregateError([caseJourneyFailure1, cleanupError], "Journey and resource exit both failed"); throw cleanupError }
diff --git a/src/web/src/test/e2e-ui/_fixtures/community-machine.ts b/src/web/src/test/e2e-ui/_fixtures/community-machine.ts
new file mode 100644
index 000000000..21f46b58a
--- /dev/null
+++ b/src/web/src/test/e2e-ui/_fixtures/community-machine.ts
@@ -0,0 +1,67 @@
+import { createRequire } from "node:module"
+import { resolve } from "node:path"
+import { expect } from "@playwright/test"
+import type { CommunityMachineSummary } from "@alook/shared"
+import type { CaseResources } from "./case-fixture"
+import { MACHINE_WS_URL, REPO_ROOT, WEB_URL } from "../_setup/paths"
+
+type MachineSocket = {
+ send: (data: string) => void
+ close: () => void
+ readonly readyState: number
+ once(event: "close", listener: () => void): void
+ once(event: "open", listener: () => void): void
+ once(event: "error", listener: (error: Error) => void): void
+ on(event: "error", listener: (error: Error) => void): void
+ on(event: "message", listener: (data: unknown) => void): void
+ off(event: "message", listener: (data: unknown) => void): void
+}
+
+export function connectMachine(credential: string, resources: CaseResources, scope: { machineId: string; headers: Record<string, string> }) {
+ const requireFromDaemon = createRequire(resolve(REPO_ROOT, "src/daemon/package.json"))
+ const { WebSocket } = requireFromDaemon("ws") as {
+ WebSocket: new (url: string, options: { headers: Record<string, string> }) => MachineSocket
+ }
+ const socket = new WebSocket(MACHINE_WS_URL.replace(/^http/, "ws"), {
+ headers: { Authorization: `Bearer ${credential}` },
+ })
+ const closed = new Promise<void>(resolveClose => socket.once("close", resolveClose))
+ const owner = resources.own(socket, async captured => {
+ if (captured.readyState !== 3) captured.close()
+ await closed
+ })
+ let failure: Error | undefined
+ socket.on("error", error => { failure = error })
+ socket.on("message", data => {
+ const frame = JSON.parse(String(data)) as { type: string; nonce?: string }
+ if (frame.type === "machine:heartbeat") socket.send(JSON.stringify({ type: "machine_heartbeat_ack", nonce: frame.nonce }))
+ })
+ const opened = new Promise<void>((resolveOpen, reject) => {
+ socket.once("open", resolveOpen)
+ socket.once("error", reject)
+ socket.once("close", () => reject(new Error("Machine socket closed before ready")))
+ })
+ const readMachine = async () => {
+ const response = await fetch(`${WEB_URL}/api/community/machines`, { headers: scope.headers })
+ expect(response.status).toBe(200)
+ const body = await response.json() as { machines: CommunityMachineSummary[] }
+ return body.machines.find(machine => machine.id === scope.machineId)
+ }
+ return {
+ socket,
+ close: () => owner.close(),
+ opened: (async () => {
+ await opened
+ const machine = await readMachine()
+ if (!machine) throw new Error("Owned machine missing before ready")
+ const { hostname, platform, arch, osRelease, daemonVersion, availableRuntimes } = machine
+ socket.send(JSON.stringify({ type: "ready", hostname, platform, arch, osRelease, daemonVersion,
+ runtimeReport: availableRuntimes, runningAgents: [], capabilities: ["control-heartbeat-v1"] }))
+ await expect.poll(async () => {
+ if (failure) throw failure
+ expect(socket.readyState).toBe(1)
+ return (await readMachine())?.status
+ }).toBe("online")
+ })(),
+ }
+}