Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(agents): create and assign agents atomically (#164)

OKNOTOK8f81aac404d8
diff --git a/server/src/__integration__/agent-creation.test.ts b/server/src/__integration__/agent-creation.test.ts
new file mode 100644
index 0000000..7bdf774
--- /dev/null
+++ b/server/src/__integration__/agent-creation.test.ts
@@ -0,0 +1,128 @@
+import { after, before, beforeEach, test } from 'node:test'
+import assert from 'node:assert/strict'
+import { pool } from '../db/pool.js'
+import { AgentCreationError, createAgentRecord } from '../agents/create.js'
+import { ensureSchemaOnce, resetAllTables, seedUserMembership, teardownAll } from './_helpers.js'
+
+const COMPANY_ID = 'co-agent-create'
+const OWNER_ID = 'u-agent-create'
+const COMPUTER_ID = 'comp-agent-create'
+
+before(async () => { await ensureSchemaOnce() })
+beforeEach(async () => {
+ await resetAllTables()
+ await pool.query(
+ `INSERT INTO users (id, email, display_name, tier)
+ VALUES ($1, $2, 'Agent Creator', 'pro')`,
+ [OWNER_ID, `${OWNER_ID}@test.local`],
+ )
+ await pool.query(
+ `INSERT INTO companies (id, name, slug, owner_user_id)
+ VALUES ($1, 'Agent Create Co', 'agent-create-co', $2)`,
+ [COMPANY_ID, OWNER_ID],
+ )
+ await seedUserMembership(OWNER_ID, COMPANY_ID, {
+ email: `${OWNER_ID}@test.local`,
+ displayName: 'Agent Creator',
+ })
+ await pool.query(
+ `INSERT INTO computers
+ (id, company_id, owner_user_id, name, kind, available_engines, status)
+ VALUES ($1, $2, $3, 'Creator Mac', 'local', $4::jsonb, 'online')`,
+ [COMPUTER_ID, COMPANY_ID, OWNER_ID, JSON.stringify(['claude', 'codex'])],
+ )
+})
+after(async () => { await teardownAll() })
+
+function input(overrides: Partial<Parameters<typeof createAgentRecord>[0]> = {}) {
+ return {
+ companyId: COMPANY_ID,
+ tier: 'pro' as const,
+ maxActiveAgents: 20,
+ requestId: 'agent-create-request-1',
+ name: 'Atomic Atlas',
+ role: 'Researcher',
+ systemPrompt: 'Investigate carefully and explain every conclusion.',
+ computerId: COMPUTER_ID,
+ engine: 'codex',
+ inherit: false,
+ ...overrides,
+ }
+}
+
+test('[integration] concurrent Agent-create retries return one atomically assigned Agent', async () => {
+ const [first, second] = await Promise.all([
+ createAgentRecord(input()),
+ createAgentRecord(input()),
+ ])
+
+ assert.equal(first.id, second.id)
+ assert.deepEqual([first.created, second.created].sort(), [false, true])
+ assert.deepEqual(first.placement, { kind: 'local', engine: 'codex', inherit: false })
+ assert.deepEqual(second.placement, first.placement)
+
+ const { rows } = await pool.query<{
+ id: string
+ computer_id: string | null
+ engine: string | null
+ engine_inherit: boolean
+ creation_request_id: string | null
+ }>(
+ `SELECT id, computer_id, engine, engine_inherit, creation_request_id
+ FROM participants
+ WHERE company_id = $1 AND kind = 'agent'`,
+ [COMPANY_ID],
+ )
+ assert.deepEqual(rows, [{
+ id: first.id,
+ computer_id: COMPUTER_ID,
+ engine: 'codex',
+ engine_inherit: false,
+ creation_request_id: 'agent-create-request-1',
+ }])
+})
+
+test('[integration] invalid placement rolls back without creating an Agent', async () => {
+ await pool.query(
+ 'UPDATE computers SET available_engines = $2::jsonb WHERE id = $1',
+ [COMPUTER_ID, JSON.stringify(['claude'])],
+ )
+
+ await assert.rejects(
+ createAgentRecord(input({ requestId: 'agent-create-request-2' })),
+ (error: unknown) => error instanceof AgentCreationError
+ && error.status === 400
+ && /invalid computer or engine/.test(error.message),
+ )
+
+ const { rows } = await pool.query<{ count: number }>(
+ `SELECT COUNT(*)::int AS count
+ FROM participants
+ WHERE company_id = $1 AND kind = 'agent'`,
+ [COMPANY_ID],
+ )
+ assert.equal(rows[0]?.count, 0)
+})
+
+test('[integration] reusing a request id with different data is rejected', async () => {
+ const created = await createAgentRecord(input({ requestId: 'agent-create-request-3' }))
+ assert.equal(created.created, true)
+
+ await assert.rejects(
+ createAgentRecord(input({
+ requestId: 'agent-create-request-3',
+ name: 'Different Agent',
+ })),
+ (error: unknown) => error instanceof AgentCreationError
+ && error.status === 409
+ && /different agent data/.test(error.message),
+ )
+
+ const { rows } = await pool.query<{ count: number }>(
+ `SELECT COUNT(*)::int AS count
+ FROM participants
+ WHERE company_id = $1 AND kind = 'agent'`,
+ [COMPANY_ID],
+ )
+ assert.equal(rows[0]?.count, 1)
+})
diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.ts
index 62f97ae..7b0f79f 100644
--- a/server/src/agents/computer/registry.ts
+++ b/server/src/agents/computer/registry.ts
@@ -63,6 +63,13 @@ const PAIRABLE: Record<Exclude<EngineId, 'managed'>, true> = {
}
const PAIRABLE_ENGINES: ReadonlySet<string> = new Set<string>(Object.keys(PAIRABLE))
+type Queryable = {
+ query<T extends object = Record<string, unknown>>(
+ text: string,
+ params?: readonly unknown[],
+ ): Promise<{ rows: T[]; rowCount?: number | null }>
+}
+
/** Merge a fresh PATH detection into a computer's advertised engine list.
*
* `available_engines[0]` is the computer's DEFAULT — pairComputer's comment
@@ -661,22 +668,25 @@ export function isByoaKind(kind: ComputerKind | null): boolean {
return kind === 'local' || kind === 'vps'
}
-/** Assign an agent to a computer (move it between Cumora Cloud and a paired
- * machine). Resolves the engine: 'managed' for cloud, else the requested
- * engine if the computer advertises it, else the computer's first engine.
- * Returns the resolved { kind, engine } or null if the computer/agent is
- * invalid for this company. */
-export async function assignAgentToComputer(args: {
- agentId: string
+/** Resolve and lock a valid Computer placement without mutating an Agent.
+ *
+ * Creation uses this inside the participant INSERT transaction so a rejected
+ * or revoked Computer can never leave behind an unassigned Agent. Existing
+ * assignment callers retain their historical fallback behavior; creation sets
+ * `strictEngine` so an unavailable explicit pin fails instead of silently
+ * selecting the Computer default. */
+export async function resolveComputerAssignment(args: {
companyId: string
computerId: string
engine?: string
/** When true (or when no engine is named), follow the computer default. */
inherit?: boolean
-}): Promise<{ kind: ComputerKind; engine: EngineId; inherit: boolean } | null> {
- const { rows } = await pool.query<{ kind: ComputerKind; available_engines: string[] }>(
+ strictEngine?: boolean
+}, db: Queryable = pool): Promise<{ kind: ComputerKind; engine: EngineId; inherit: boolean } | null> {
+ const { rows } = await db.query<{ kind: ComputerKind; available_engines: string[] }>(
`SELECT kind, available_engines FROM computers
- WHERE id = $1 AND company_id = $2 AND revoked_at IS NULL LIMIT 1`,
+ WHERE id = $1 AND company_id = $2 AND revoked_at IS NULL
+ LIMIT 1 FOR SHARE`,
[args.computerId, args.companyId],
)
const computer = rows[0]
@@ -691,6 +701,9 @@ export async function assignAgentToComputer(args: {
const advertised = computer.available_engines ?? []
const wantInherit = args.inherit === true || !args.engine
const requested = args.engine && PAIRABLE_ENGINES.has(args.engine) ? (args.engine as EngineId) : null
+ if (!wantInherit && args.strictEngine && (!requested || !advertised.includes(requested))) {
+ return null
+ }
const pick = (
wantInherit
? advertised[0]
@@ -701,13 +714,32 @@ export async function assignAgentToComputer(args: {
inherit = wantInherit
}
+ return { kind: computer.kind, engine, inherit }
+}
+
+/** Assign an agent to a computer (move it between Cumora Cloud and a paired
+ * machine). Resolves the engine: 'managed' for cloud, else the requested
+ * engine if the computer advertises it, else the computer's first engine.
+ * Returns the resolved { kind, engine } or null if the computer/agent is
+ * invalid for this company. */
+export async function assignAgentToComputer(args: {
+ agentId: string
+ companyId: string
+ computerId: string
+ engine?: string
+ /** When true (or when no engine is named), follow the computer default. */
+ inherit?: boolean
+}): Promise<{ kind: ComputerKind; engine: EngineId; inherit: boolean } | null> {
+ const placement = await resolveComputerAssignment(args)
+ if (!placement) return null
+
const { rowCount } = await pool.query(
`UPDATE participants SET computer_id = $1, engine = $2, engine_inherit = $3
WHERE id = $4 AND company_id = $5 AND kind = 'agent'`,
- [args.computerId, engine, inherit, args.agentId, args.companyId],
+ [args.computerId, placement.engine, placement.inherit, args.agentId, args.companyId],
)
if (!rowCount) return null
- return { kind: computer.kind, engine, inherit }
+ return placement
}
/** Ask the online daemon to re-probe PATH on its next heartbeat. */
diff --git a/server/src/agents/create.ts b/server/src/agents/create.ts
new file mode 100644
index 0000000..065d2a8
--- /dev/null
+++ b/server/src/agents/create.ts
@@ -0,0 +1,231 @@
+import { createHash } from 'node:crypto'
+import { pool } from '../db/pool.js'
+import {
+ cloudComputerId,
+ type ComputerKind,
+ type EngineId,
+ resolveComputerAssignment,
+} from './computer/registry.js'
+
+const AVATAR_PALETTE = [
+ '#FFB088', '#FFD9D2', '#FFB7AF', '#F4B740',
+ '#7C5CFF', '#A593FF', '#4FC2F4', '#41B5DC',
+ '#4FC2A1', '#6EC56A', '#E9A0E9', '#FF7AB6',
+] as const
+
+export class AgentCreationError extends Error {
+ constructor(public status: number, message: string) {
+ super(message)
+ }
+}
+
+export interface CreateAgentRecordInput {
+ companyId: string
+ tier: 'free' | 'pro' | 'max'
+ maxActiveAgents: number
+ requestId?: string | null
+ name: string
+ role?: string
+ systemPrompt: string
+ bio?: string
+ initial?: string
+ avatarBg?: string
+ model?: string | null
+ fastModel?: string | null
+ tools?: string[]
+ computerId?: string | null
+ engine?: string
+ inherit?: boolean
+}
+
+export interface CreateAgentRecordResult {
+ id: string
+ created: boolean
+ placement: {
+ kind: ComputerKind
+ engine: EngineId
+ inherit: boolean
+ } | null
+}
+
+function slugifyAgentName(name: string): string {
+ const lowered = name.toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '')
+ let slug = lowered
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .replace(/-{2,}/g, '-')
+ .slice(0, 24)
+ if (!/^[a-z]/.test(slug)) slug = `a-${slug}`.slice(0, 24)
+ if (slug.length === 0) slug = 'agent'
+ return slug
+}
+
+function candidateAgentIds(name: string): string[] {
+ const base = slugifyAgentName(name)
+ return [
+ base,
+ ...Array.from({ length: 8 }, () => `${base}-${Math.random().toString(36).slice(2, 6)}`),
+ ]
+}
+
+function defaultAvatarBg(id: string): string {
+ let hash = 0
+ for (let i = 0; i < id.length; i++) hash = (hash * 31 + id.charCodeAt(i)) >>> 0
+ return AVATAR_PALETTE[hash % AVATAR_PALETTE.length]
+}
+
+function normalizeRequestId(value: string | null | undefined): string | null {
+ if (value == null) return null
+ const requestId = value.trim()
+ if (!/^[A-Za-z0-9._:-]{8,128}$/.test(requestId)) {
+ throw new AgentCreationError(400, 'requestId must be 8-128 safe characters')
+ }
+ return requestId
+}
+
+function creationRequestHash(input: CreateAgentRecordInput): string {
+ const canonical = JSON.stringify({
+ name: input.name,
+ role: input.role ?? '',
+ systemPrompt: input.systemPrompt,
+ bio: input.bio ?? '',
+ initial: input.initial ?? '',
+ avatarBg: input.avatarBg ?? '',
+ model: input.model ?? null,
+ fastModel: input.fastModel ?? null,
+ tools: input.tools ?? ['bash'],
+ computerId: input.computerId ?? null,
+ engine: input.engine ?? null,
+ inherit: input.inherit === true,
+ })
+ return createHash('sha256').update(canonical).digest('base64url')
+}
+
+/**
+ * Persist an Agent and its initial Computer placement as one idempotent unit.
+ *
+ * Locking the company row serializes capacity checks and same-workspace
+ * creation retries. The request id then turns an ambiguous HTTP retry into a
+ * lookup of the already committed Agent instead of a second INSERT. Computer
+ * validation uses a row lock in this same transaction, so revocation or an
+ * invalid explicit engine pin rolls the whole create back.
+ */
+export async function createAgentRecord(
+ input: CreateAgentRecordInput,
+): Promise<CreateAgentRecordResult> {
+ const requestId = normalizeRequestId(input.requestId)
+ const requestHash = requestId ? creationRequestHash(input) : null
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ const company = await client.query(
+ 'SELECT id FROM companies WHERE id = $1 FOR UPDATE',
+ [input.companyId],
+ )
+ if (!company.rowCount) throw new AgentCreationError(404, 'company not found')
+
+ if (requestId) {
+ const { rows } = await client.query<{
+ id: string
+ creation_request_hash: string | null
+ computer_id: string | null
+ engine: EngineId | null
+ engine_inherit: boolean
+ kind: ComputerKind | null
+ }>(
+ `SELECT p.id, p.creation_request_hash, p.computer_id, p.engine,
+ p.engine_inherit, c.kind
+ FROM participants p
+ LEFT JOIN computers c
+ ON c.id = p.computer_id AND c.company_id = p.company_id
+ WHERE p.company_id = $1 AND p.kind = 'agent'
+ AND p.creation_request_id = $2
+ LIMIT 1`,
+ [input.companyId, requestId],
+ )
+ const existing = rows[0]
+ if (existing) {
+ if (existing.creation_request_hash !== requestHash) {
+ throw new AgentCreationError(409, 'requestId was already used with different agent data')
+ }
+ await client.query('COMMIT')
+ return {
+ id: existing.id,
+ created: false,
+ placement: existing.computer_id && existing.kind && existing.engine
+ ? { kind: existing.kind, engine: existing.engine, inherit: existing.engine_inherit }
+ : null,
+ }
+ }
+ }
+
+ const { rows: countRows } = await client.query<{ count: number }>(
+ `SELECT COUNT(*)::int AS count
+ FROM participants
+ WHERE company_id = $1 AND kind = 'agent' AND departed_at IS NULL`,
+ [input.companyId],
+ )
+ if ((countRows[0]?.count ?? 0) >= input.maxActiveAgents) {
+ throw new AgentCreationError(
+ 403,
+ `${input.tier} tier workspaces can have at most ${input.maxActiveAgents} active agents`,
+ )
+ }
+
+ let placement: CreateAgentRecordResult['placement'] = null
+ const computerId = input.computerId?.trim() || null
+ if (computerId) {
+ if (computerId === cloudComputerId(input.companyId) && input.tier === 'free') {
+ throw new AgentCreationError(
+ 403,
+ 'Free tier agents run on your own computer. Upgrade to Pro to use Cumora Cloud.',
+ )
+ }
+ placement = await resolveComputerAssignment({
+ companyId: input.companyId,
+ computerId,
+ engine: input.engine,
+ inherit: input.inherit,
+ strictEngine: true,
+ }, client)
+ if (!placement) {
+ throw new AgentCreationError(400, 'invalid computer or engine for this company')
+ }
+ }
+
+ const tools = input.tools ?? ['bash']
+ for (const agentId of candidateAgentIds(input.name)) {
+ const initial = input.initial || input.name.charAt(0).toUpperCase()
+ const avatarBg = input.avatarBg || defaultAvatarBg(agentId)
+ const { rows } = await client.query<{ id: string }>(
+ `INSERT INTO participants
+ (id, kind, name, role, initial, avatar_bg, status, bio, tools,
+ system_prompt, model, fast_model, company_id, computer_id, engine,
+ engine_inherit, creation_request_id, creation_request_hash)
+ VALUES
+ ($1, 'agent', $2, $3, $4, $5, 'avail', $6, $7::jsonb,
+ $8, $9, $10, $11, $12, $13, $14, $15, $16)
+ ON CONFLICT DO NOTHING
+ RETURNING id`,
+ [
+ agentId, input.name, input.role ?? '', initial, avatarBg, input.bio ?? '',
+ JSON.stringify(tools), input.systemPrompt, input.model ?? null,
+ input.fastModel ?? null, input.companyId, computerId,
+ placement?.engine ?? null, placement?.inherit ?? true,
+ requestId, requestHash,
+ ],
+ )
+ if (rows[0]) {
+ await client.query('COMMIT')
+ return { id: rows[0].id, created: true, placement }
+ }
+ }
+
+ throw new AgentCreationError(500, 'could not pick a unique agent id — please retry')
+ } catch (error) {
+ await client.query('ROLLBACK').catch(() => {})
+ throw error
+ } finally {
+ client.release()
+ }
+}
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index 13e029c..9e3e0e3 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -14,6 +14,7 @@ import { ensureDirectConversation } from '../agents/private_chat.js'
import { fetchImageBytes } from '../agents/image-fetcher.js'
import { getTriageEconomics, getWakeEconomics } from '../agents/observability.js'
import { resolveKanbanAssigneeChange, wakeKanbanAgents } from '../agents/kanban-wake.js'
+import { AgentCreationError, createAgentRecord } from '../agents/create.js'
import { BUSY_STATUS_LEASE_MS } from '../status.js'
import { notifyMessage, computeMessageRecipients } from '../push.js'
import { randomUUID, randomBytes, createHash, timingSafeEqual } from 'node:crypto'
@@ -2026,17 +2027,6 @@ api.get('/participants', async (req, res) => {
/* ============== Agent CRUD ============== */
-const AVATAR_PALETTE = [
- '#FFB088', '#FFD9D2', '#FFB7AF', '#F4B740',
- '#7C5CFF', '#A593FF', '#4FC2F4', '#41B5DC',
- '#4FC2A1', '#6EC56A', '#E9A0E9', '#FF7AB6',
-]
-function defaultAvatarBg(id: string): string {
- let h = 0
- for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) >>> 0
- return AVATAR_PALETTE[h % AVATAR_PALETTE.length]
-}
-
/* ============== Deterministic visual signature per agent ============== */
// FNV-1a hash — stable across runs, no deps.
@@ -2458,48 +2448,6 @@ function readAgentBody(b: AgentBody): {
return out as ReturnType<typeof readAgentBody>
}
-/** Slugify a display name into a candidate agent id: lowercase ASCII
- * letters/digits/hyphens, starts with a letter, capped at 24 chars.
- * Falls back to `'agent'` when the name has no usable ASCII tail
- * (e.g. an all-CJK / emoji name). Used by /agents POST to derive
- * the agent id from the user-supplied name — users no longer enter
- * an id directly, so we get to enforce shape AND global uniqueness
- * invisibly. */
-function slugifyAgentName(name: string): string {
- const lowered = name.toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '')
- let slug = lowered
- .replace(/[^a-z0-9]+/g, '-')
- .replace(/^-+|-+$/g, '')
- .replace(/-{2,}/g, '-')
- .slice(0, 24)
- if (!/^[a-z]/.test(slug)) slug = `a-${slug}`.slice(0, 24)
- if (slug.length === 0) slug = 'agent'
- return slug
-}
-
-/** Pick a globally-unique agent id, preferring the slug of `name` and
- * falling back to `${slug}-${random4}` if (and as many times as)
- * needed. The participants table enforces global uniqueness on
- * `id WHERE kind='agent'` via a partial unique index, so this loop
- * + the INSERT race together can still 409 if a peer wins; the
- * caller catches that and retries with a fresh suffix. */
-async function pickUniqueAgentId(baseName: string): Promise<string> {
- const base = slugifyAgentName(baseName)
- const tryIds: string[] = [base]
- for (let i = 0; i < 8; i++) {
- tryIds.push(`${base}-${Math.random().toString(36).slice(2, 6)}`)
- }
- for (const candidate of tryIds) {
- const { rows } = await pool.query<{ exists: boolean }>(
- `SELECT EXISTS(SELECT 1 FROM participants WHERE id = $1) AS exists`,
- [candidate],
- )
- if (!rows[0].exists) return candidate
- }
- // Wildly unlikely with 8 random suffixes.
- throw new HttpError(500, 'could not pick a unique agent id — please retry')
-}
-
api.post('/agents', async (req, res) => {
// Agents are shared workspace identities — they speak on behalf of the
// company, hold their own LLM budget, and can email out. Restricting
@@ -2511,33 +2459,43 @@ api.post('/agents', async (req, res) => {
if (!data.systemPrompt || data.systemPrompt.trim().length < 10) {
res.status(400).json({ error: 'systemPrompt required (at least 10 chars — describe the agent\'s style)' }); return
}
- await assertCompanyAgentLimit(tenant)
- // The id is now SERVER-generated from the name (slugified) rather
- // than user-supplied — users can't accidentally cause cross-tenant
- // id collisions, and the same display name landing in two
- // workspaces still produces two distinct ids (the second one gets
- // a random suffix).
- const agentId = await pickUniqueAgentId(data.name)
- const initial = data.initial || data.name.charAt(0).toUpperCase()
- const avatarBg = data.avatarBg || defaultAvatarBg(agentId)
+ if (req.body?.requestId !== undefined && typeof req.body.requestId !== 'string') {
+ res.status(400).json({ error: 'requestId must be a string' }); return
+ }
+ if (req.body?.computerId !== undefined && typeof req.body.computerId !== 'string') {
+ res.status(400).json({ error: 'computerId must be a string' }); return
+ }
+ const tier = await companyPlanTier(tenant)
+ const computerId = typeof req.body?.computerId === 'string' ? req.body.computerId.trim() || null : null
+ const engine = typeof req.body?.engine === 'string' ? req.body.engine : undefined
+ const inherit = req.body?.inherit === true
+ let creation: Awaited<ReturnType<typeof createAgentRecord>>
try {
- await pool.query(
- `INSERT INTO participants (id, kind, name, role, initial, avatar_bg, status, bio, tools, system_prompt, model, fast_model, company_id)
- VALUES ($1, 'agent', $2, $3, $4, $5, 'avail', $6, $7::jsonb, $8, $9, $10, $11)`,
- [agentId, data.name, data.role ?? '', initial, avatarBg, data.bio ?? '',
- JSON.stringify(data.tools ?? ['bash']), data.systemPrompt, data.model ?? null, data.fastModel ?? null, tenant],
- )
+ creation = await createAgentRecord({
+ companyId: tenant,
+ tier,
+ maxActiveAgents: TIER_LIMITS[tier].agentsPerCompany,
+ requestId: typeof req.body?.requestId === 'string' ? req.body.requestId : null,
+ name: data.name,
+ role: data.role,
+ systemPrompt: data.systemPrompt,
+ bio: data.bio,
+ initial: data.initial,
+ avatarBg: data.avatarBg,
+ model: data.model,
+ fastModel: data.fastModel,
+ tools: data.tools ?? undefined,
+ computerId,
+ engine,
+ inherit,
+ })
} catch (e) {
+ const status = e instanceof AgentCreationError ? e.status : 500
const msg = e instanceof Error ? e.message : String(e)
- if (/duplicate key|participants_agent_id_unique/.test(msg)) {
- // Race window between pickUniqueAgentId's SELECT and the INSERT
- // — another POST squatted on this id. Client can retry.
- res.status(409).json({ error: 'agent id collision — please retry' })
- } else {
- res.status(500).json({ error: msg })
- }
+ res.status(status).json({ error: msg })
return
}
+ const agentId = creation.id
// Re-bind data.id for the rest of the handler so subsequent code
// (workspace seeding, all-hands join, response payload) sees it.
data.id = agentId
@@ -2600,12 +2558,18 @@ api.post('/agents', async (req, res) => {
// with their initial-letter avatar; the real portrait shows up on the
// next /participants poll once the image is ready. We deliberately
// don't block the 201 response since image gen can take several seconds.
- const newAgentId = data.id
- void generateAndPersistAvatar({ agentId: newAgentId, tenant })
- .then(() => console.log(`[agents] auto-portrait ready for ${newAgentId}`))
- .catch((e) => console.warn(`[agents] auto-portrait failed for ${newAgentId}`, e))
+ if (creation.created) {
+ const newAgentId = data.id
+ void generateAndPersistAvatar({ agentId: newAgentId, tenant })
+ .then(() => console.log(`[agents] auto-portrait ready for ${newAgentId}`))
+ .catch((e) => console.warn(`[agents] auto-portrait failed for ${newAgentId}`, e))
+ }
- res.status(201).json({ id: data.id })
+ res.status(creation.created ? 201 : 200).json({
+ id: data.id,
+ replayed: !creation.created,
+ ...(creation.placement ?? {}),
+ })
})
api.put('/agents/:id', async (req, res) => {
diff --git a/server/src/db/migrate.ts b/server/src/db/migrate.ts
index cd8ac23..603c010 100644
--- a/server/src/db/migrate.ts
+++ b/server/src/db/migrate.ts
@@ -1554,6 +1554,11 @@ ALTER TABLE computers ADD COLUMN IF NOT EXISTS engines_detected_at TIMESTAMP WIT
ALTER TABLE computers ADD COLUMN IF NOT EXISTS detect_requested_at TIMESTAMP WITH TIME ZONE;
-- true = follow computers.available_engines[0]; false = pin participants.engine.
ALTER TABLE participants ADD COLUMN IF NOT EXISTS engine_inherit BOOLEAN NOT NULL DEFAULT TRUE;
+-- Stable browser-generated key for idempotent Agent creation. The hash binds
+-- the key to the sanitized create payload so accidental key reuse cannot
+-- silently return a differently configured Agent.
+ALTER TABLE participants ADD COLUMN IF NOT EXISTS creation_request_id TEXT;
+ALTER TABLE participants ADD COLUMN IF NOT EXISTS creation_request_hash TEXT;
-- ============== Evidence-backed feature shipping =======================
-- A shipping feature is deliberately distinct from a generic board card.
@@ -2122,6 +2127,11 @@ export async function ensureSchema(): Promise<void> {
CREATE UNIQUE INDEX IF NOT EXISTS participants_agent_id_unique
ON participants(id) WHERE kind = 'agent'
`)
+ await client.query(`
+ CREATE UNIQUE INDEX IF NOT EXISTS uniq_participants_agent_creation_request
+ ON participants(company_id, creation_request_id)
+ WHERE kind = 'agent' AND creation_request_id IS NOT NULL
+ `)
await ensureMessageClientIdIndex(client)
console.log('[db] schema ensured')
@@ -2235,7 +2245,11 @@ async function schemaAlreadyCurrent(client: import('pg').PoolClient): Promise<bo
const { tables, columns } = ddlExpectations()
// Indexes are not derivable the same way (partial/concurrent/renamed), so
// the few that gate correctness stay explicit.
- const indexes = ['participants_agent_id_unique', 'uniq_messages_client_id']
+ const indexes = [
+ 'participants_agent_id_unique',
+ 'uniq_participants_agent_creation_request',
+ 'uniq_messages_client_id',
+ ]
const { rows } = await client.query<{
missing_tables: string[]; missing_columns: string[]; missing_indexes: string[]
}>(
diff --git a/src/api/client.ts b/src/api/client.ts
index 5db6c47..e69ccda 100644
--- a/src/api/client.ts
+++ b/src/api/client.ts
@@ -311,6 +311,15 @@ export interface AgentInput {
tools?: string[]
}
+export interface AgentCreateInput extends AgentInput {
+ /** Stable for the lifetime of one create form so ambiguous retries replay. */
+ requestId: string
+ /** Initial host placement is committed atomically with the Agent row. */
+ computerId?: string | null
+ engine?: EngineId
+ inherit?: boolean
+}
+
export interface ApiAttachment {
url: string
name: string
@@ -960,8 +969,14 @@ export const api = {
http<{ ok: boolean; kind: ComputerKind; engine: EngineId; inherit?: boolean }>(
`/agents/${encodeURIComponent(agentId)}/computer`,
{ method: 'POST', body: JSON.stringify({ computerId, engine, inherit }) }),
- createAgent: (input: AgentInput) =>
- http<{ id: string }>('/agents', { method: 'POST', body: JSON.stringify(input) }),
+ createAgent: (input: AgentCreateInput) =>
+ http<{
+ id: string
+ replayed: boolean
+ kind?: ComputerKind
+ engine?: EngineId
+ inherit?: boolean
+ }>('/agents', { method: 'POST', body: JSON.stringify(input) }),
updateAgent: (id: string, input: AgentInput) =>
http<{ ok: boolean }>(`/agents/${encodeURIComponent(id)}`, { method: 'PUT', body: JSON.stringify(input) }),
/** Soft-delete: marks the agent as off-boarded. Memory + log preserved. */
diff --git a/src/components/AgentEditor.tsx b/src/components/AgentEditor.tsx
index 26de444..77ac0ba 100644
--- a/src/components/AgentEditor.tsx
+++ b/src/components/AgentEditor.tsx
@@ -14,6 +14,12 @@ import { engineLabel } from '@/lib/engines'
const INHERIT_ENGINE = '__inherit__'
+function newCreateRequestId(): string {
+ return typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
+ ? crypto.randomUUID()
+ : `agent-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
+}
+
/** Which engine-dropdown value to show for a saved agent.
* Official production has no `engineInherit`: a stored engine that isn't
* the computer default means the user pinned it. */
@@ -59,6 +65,9 @@ export function AgentEditor({ agent, onClose, onSaved }: Props) {
const [repairCode, setRepairCode] = useState<string | null>(null)
const [repairErr, setRepairErr] = useState<string | null>(null)
const [repairCopied, setRepairCopied] = useState(false)
+ // Survives an ambiguous network failure and the user's retry click, but a
+ // newly opened editor gets a fresh key. The server binds it to the payload.
+ const createRequestId = useRef(newCreateRequestId())
// "Runs on" — which Computer hosts this agent. Cloud = managed engine.
// Free tier is BYOA-only: it has no real Cumora Cloud computer; we show a
@@ -144,6 +153,8 @@ export function AgentEditor({ agent, onClose, onSaved }: Props) {
const current = agent?.computerId ?? cloud?.id
const targetComputer = target ? computersById[target] : undefined
const isByoaTarget = !!targetComputer && targetComputer.kind !== 'cloud'
+ const inherit = engineChoice === INHERIT_ENGINE
+ const pinned = inherit ? undefined : (engineChoice as EngineId)
const payload: AgentInput = {
name, role, systemPrompt, bio, avatarBg,
model: model.trim() || null,
@@ -155,21 +166,28 @@ export function AgentEditor({ agent, onClose, onSaved }: Props) {
if ((agent!.avatarUrl ?? null) !== avatarUrl) payload.avatarUrl = avatarUrl
await api.updateAgent(agent!.id, payload)
} else {
- // No `id` field on create — server slugifies it from `name`
- // and guarantees global uniqueness.
- const created = await api.createAgent(payload)
+ // Creation + initial host/engine assignment is one transaction. The
+ // stable request id makes retry-after-timeout return that same Agent.
+ const created = await api.createAgent({
+ ...payload,
+ requestId: createRequestId.current,
+ computerId: target || null,
+ engine: isByoaTarget ? pinned : undefined,
+ inherit: isByoaTarget ? inherit : false,
+ })
agentId = created.id
+ if (isByoaTarget && pinned && created.engine !== pinned) {
+ throw new Error(t('agent.enginePinRejected', { engine: engineLabel(pinned) }))
+ }
}
// Persist the host assignment when the computer OR the engine changed.
// (Engine lives in the same assign call; gating only on the computer
// would silently drop a Claude→Codex switch on the same machine.) Still
// skipped on a plain style edit to avoid the owner/admin-gated call.
- const inherit = engineChoice === INHERIT_ENGINE
- const pinned = inherit ? undefined : (engineChoice as EngineId)
const savedChoice = initialEngineChoice(agent, targetComputer)
const inheritChanged = isByoaTarget && inherit !== (savedChoice === INHERIT_ENGINE)
const engineChanged = isByoaTarget && !inherit && pinned !== ((agent?.engine as EngineId) ?? null)
- if (agentId && target && (target !== current || inheritChanged || engineChanged)) {
+ if (editing && agentId && target && (target !== current || inheritChanged || engineChanged)) {
const out = await api.assignAgentComputer(agentId, target, isByoaTarget ? pinned : undefined, isByoaTarget ? inherit : false)
if (isByoaTarget && pinned && out.engine !== pinned) {
throw new Error(t('agent.enginePinRejected', { engine: engineLabel(pinned) }))