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: close remaining runtime and BYOA audit gaps (#108)

OKNOTOK9726fecdf930
diff --git a/server/src/__integration__/runtime-server.test.ts b/server/src/__integration__/runtime-server.test.ts
index 3e503ce..d2d83bd 100644
--- a/server/src/__integration__/runtime-server.test.ts
+++ b/server/src/__integration__/runtime-server.test.ts
@@ -274,6 +274,35 @@ test('[integration] runtime: /context rejects a stale production token after ten
assert.deepEqual(r.body?.rows ?? [], [])
})
+test('[integration] runtime: /inbox-triage/payload rejects a stale token before loading the new tenant inbox', async () => {
+ const originalTenant = await seedAgent()
+ const currentTenant = await seedAgent()
+ const staleToken = await mintAssignedAgentRuntimeToken(originalTenant)
+
+ const moved = await pool.query(
+ `UPDATE participants
+ SET company_id = $1, computer_id = NULL, engine = NULL
+ WHERE id = $2 AND company_id = $3`,
+ [currentTenant.companyId, originalTenant.agentId, originalTenant.companyId],
+ )
+ assert.equal(moved.rowCount, 1)
+
+ await seedContextConversation({
+ companyId: currentTenant.companyId,
+ members: [originalTenant.agentId, currentTenant.agentId],
+ authorId: currentTenant.agentId,
+ body: 'new-tenant-inbox-private',
+ })
+
+ const r = await call('/runtime/inbox-triage/payload', {
+ method: 'GET',
+ token: staleToken,
+ })
+
+ assert.equal(r.status, 403)
+ assert.match(String(r.body?.error ?? ''), /token tenant/i)
+})
+
test('[integration] runtime: /faces requires a tenant-pinned token', async () => {
const { agentId } = await seedAgent()
const token = signAgentToken({ agentId, companyId: null })
diff --git a/server/src/__tests__/agents-computer-engine-opencode.test.ts b/server/src/__tests__/agents-computer-engine-opencode.test.ts
index d4ca34a..8065116 100644
--- a/server/src/__tests__/agents-computer-engine-opencode.test.ts
+++ b/server/src/__tests__/agents-computer-engine-opencode.test.ts
@@ -52,6 +52,16 @@ process.stdin.on('end', () => {
process.exitCode = 2
return
}
+ if (scenario === 'stderr-json') {
+ // Diagnostics may happen to be JSON. They are not part of OpenCode's
+ // stdout protocol and must not alter session/error/usage state.
+ process.stderr.write(JSON.stringify({ sessionID: 'ses_stderr', type: 'step_finish', part: {
+ tokens: { input: 900, output: 90, reasoning: 9, cache: { read: 80, write: 7 } },
+ } }) + '\\n')
+ process.stderr.write(JSON.stringify({ sessionID: 'ses_stderr', type: 'error', error: {
+ data: { message: 'stderr diagnostic only' },
+ } }) + '\\n')
+ }
out({ type: 'step_start', part: { type: 'step-start' } })
if (scenario === 'missing-finish') {
out({ type: 'text', part: { type: 'text', text: 'partial', time: { end: Date.now() } } })
@@ -303,6 +313,34 @@ test('opencode stream error fails a turn even when the process exits zero', { sk
assert.equal(result.sessionId, 'ses_opencode_new')
})
+test('opencode never parses JSON diagnostics from stderr as protocol events', { skip: IS_WIN }, async () => {
+ const f = await fixture('stderr-json')
+ const hops: EngineHopReport[] = []
+ const logs: string[] = []
+ const result = await getAdapter('opencode').run({
+ home: f.home,
+ prompt: 'stderr stays diagnostic',
+ env: f.env,
+ model: null,
+ fastModel: null,
+ resumeSessionId: null,
+ onLog: (line) => logs.push(line),
+ onHopUsage: (hop) => hops.push(hop),
+ signal: new AbortController().signal,
+ })
+
+ assert.equal(result.exitCode, 0, result.error)
+ assert.equal(result.sessionId, 'ses_opencode_new')
+ assert.deepEqual(result.usage, {
+ input_tokens: 100,
+ output_tokens: 15,
+ cache_read_input_tokens: 40,
+ cache_creation_input_tokens: 2,
+ })
+ assert.equal(hops.length, 1)
+ assert.ok(logs.some((line) => line.includes('stderr diagnostic only')), 'stderr stays observable')
+})
+
test('opencode accepts a clean exit when the best-effort stream omits step_finish', { skip: IS_WIN }, async () => {
const f = await fixture('missing-finish')
const result = await getAdapter('opencode').run({
@@ -350,6 +388,7 @@ test('opencode custom args keep stdin and resume while making output opaque', {
signal: new AbortController().signal,
})
assert.equal(result.exitCode, 0, result.error)
+ assert.equal(result.sessionId, 'ses_custom', 'camelCase sessionID must survive the opaque override path')
const call = (await fakeLog(f))[0]
assert.deepEqual(call?.argv, ['run', '--pure', '--session', 'ses_custom'])
assert.equal(call?.stdin, 'custom')
diff --git a/server/src/__tests__/agents-runtime-byoa-source.test.ts b/server/src/__tests__/agents-runtime-byoa-source.test.ts
new file mode 100644
index 0000000..ff9c071
--- /dev/null
+++ b/server/src/__tests__/agents-runtime-byoa-source.test.ts
@@ -0,0 +1,13 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { BYOA_SOURCES, normalizeByoaSource } from '../agents/runtime/byoa-source.js'
+
+test('runtime ledger accepts every supported BYOA source', () => {
+ for (const source of BYOA_SOURCES) assert.equal(normalizeByoaSource(source), source)
+})
+
+test('runtime ledger rejects arbitrary and non-string source values', () => {
+ for (const source of ['cloud', 'byoa-forged', '', null, undefined, 7, {}]) {
+ assert.equal(normalizeByoaSource(source), 'byoa-claude')
+ }
+})
diff --git a/server/src/__tests__/agents-wake-options.test.ts b/server/src/__tests__/agents-wake-options.test.ts
index 47a3161..d4d5815 100644
--- a/server/src/__tests__/agents-wake-options.test.ts
+++ b/server/src/__tests__/agents-wake-options.test.ts
@@ -6,7 +6,7 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
-import { buildKanbanWakeBrief } from '../agents/kanban-wake.js'
+import { buildKanbanWakeBrief, resolveKanbanAssigneeChange } from '../agents/kanban-wake.js'
import {
mergeWakeBackgroundBriefs,
mergeWakeTurnOptions,
@@ -105,6 +105,25 @@ test('shared Kanban brief names the card and actionable CLI commands', () => {
assert.match(brief.body, /cumora card move card-1/)
})
+test('assignee wake is emitted only for a real assignment transition', () => {
+ assert.deepEqual(resolveKanbanAssigneeChange('agent-1', 'agent-1'), {
+ nextAssigneeId: 'agent-1',
+ changed: false,
+ })
+ assert.deepEqual(resolveKanbanAssigneeChange('agent-1', ' agent-2 '), {
+ nextAssigneeId: 'agent-2',
+ changed: true,
+ })
+ assert.deepEqual(resolveKanbanAssigneeChange('agent-1', null), {
+ nextAssigneeId: null,
+ changed: true,
+ })
+ assert.deepEqual(resolveKanbanAssigneeChange('agent-1', undefined), {
+ nextAssigneeId: 'agent-1',
+ changed: false,
+ })
+})
+
test('malformed or oversized wake payloads cannot manufacture work', () => {
assert.deepEqual(parseWakeData('{broken'), {
conversationId: null,
diff --git a/server/src/__tests__/computer-engine-redetect.test.ts b/server/src/__tests__/computer-engine-redetect.test.ts
index 91c54c9..c04cdb1 100644
--- a/server/src/__tests__/computer-engine-redetect.test.ts
+++ b/server/src/__tests__/computer-engine-redetect.test.ts
@@ -21,9 +21,11 @@ const { heartbeatComputer, mergeDetectedEngines } = await import('../agents/comp
const { pool } = await import('../db/pool.js')
const originalQuery = pool.query.bind(pool)
+const originalWarn = console.warn
afterEach(() => {
;(pool as unknown as { query: typeof originalQuery }).query = originalQuery
+ console.warn = originalWarn
})
test('a newly installed engine is appended without re-pairing', () => {
@@ -105,3 +107,24 @@ test('heartbeat persists a successful empty detection', async () => {
assert.ok(inventoryUpdate)
assert.equal(inventoryUpdate.params[1], '[]')
})
+
+test('heartbeat persists liveness before a failing inventory refresh', async () => {
+ const calls: string[] = []
+ const warnings: string[] = []
+ console.warn = (...args: unknown[]) => { warnings.push(args.map(String).join(' ')) }
+ ;(pool as unknown as {
+ query: (sql: string, params?: unknown[]) => Promise<{ rows: unknown[]; rowCount: number }>
+ }).query = async (sql: string) => {
+ calls.push(sql)
+ if (/UPDATE computers SET last_seen_at/.test(sql)) return { rows: [{ '?column?': 1 }], rowCount: 1 }
+ if (/SELECT available_engines/.test(sql)) throw new Error('transient inventory read failure')
+ throw new Error(`unexpected query: ${sql}`)
+ }
+
+ await heartbeatComputer('comp-1', '0.8.0', true, ['claude'])
+
+ assert.match(calls[0] ?? '', /UPDATE computers SET last_seen_at/)
+ assert.match(calls[1] ?? '', /SELECT available_engines/)
+ assert.equal(warnings.length, 1)
+ assert.match(warnings[0], /transient inventory read failure/)
+})
diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.ts
index 2c0a09c..be4bf4d 100644
--- a/server/src/agents/computer/engine.ts
+++ b/server/src/agents/computer/engine.ts
@@ -481,7 +481,7 @@ function spawnEngine(
bin: string,
args: string[],
{ home, env, onLog, signal, onHopUsage }: EngineRunArgs,
- spawnOpts: { shell?: boolean; stdinText?: string } = {},
+ spawnOpts: { shell?: boolean; stdinText?: string; onStdoutLine?: (line: string) => void } = {},
): Promise<EngineRunResult> {
return new Promise((resolve, reject) => {
const child = spawn(bin, args, {
@@ -536,10 +536,11 @@ function spawnEngine(
// Sniff the engine's session id (to `--resume` next wake), the final
// `result` event's usage (cache-aware cost), and the actual model id
// (real pricing). Cheap: only parse stdout JSON objects carrying one.
- if (stream === 'stdout' && cleaned.startsWith('{') && (cleaned.includes('"session_id"') || cleaned.includes('"usage"') || cleaned.includes('"model"'))) {
+ if (stream === 'stdout' && cleaned.startsWith('{') && (cleaned.includes('"session_id"') || cleaned.includes('"sessionID"') || cleaned.includes('"usage"') || cleaned.includes('"model"'))) {
try {
- const obj = JSON.parse(cleaned) as { session_id?: unknown; type?: unknown; usage?: EngineUsage; model?: unknown; message?: { model?: unknown; usage?: EngineUsage; content?: unknown } }
- if (typeof obj.session_id === 'string' && obj.session_id) sessionId = obj.session_id
+ const obj = JSON.parse(cleaned) as { session_id?: unknown; sessionID?: unknown; type?: unknown; usage?: EngineUsage; model?: unknown; message?: { model?: unknown; usage?: EngineUsage; content?: unknown } }
+ const sniffedSessionId = typeof obj.session_id === 'string' ? obj.session_id : obj.sessionID
+ if (typeof sniffedSessionId === 'string' && sniffedSessionId) sessionId = sniffedSessionId
// The terminal `result` event carries the authoritative turn total.
if (obj.type === 'result' && obj.usage && typeof obj.usage === 'object') usage = obj.usage
// assistant events carry message.model; some events carry top-level model.
@@ -562,6 +563,7 @@ function spawnEngine(
if (obj.type === 'result') { hopStartedAt = null; hopIndex = 0 }
} catch { /* partial / non-json line — ignore */ }
}
+ if (stream === 'stdout') spawnOpts.onStdoutLine?.(cleaned)
onLog(cleaned)
}
}
@@ -2514,13 +2516,21 @@ async function spawnOpenCodeStream(
prompt: opts.prompt,
env: opts.env,
onLog: (line) => {
- const event = parseOpenCodeLine(line)
- if (event) tracker.observe(event)
opts.onLog?.(line)
},
signal: opts.signal,
},
- { shell: opts.shell, stdinText: opts.prompt },
+ {
+ shell: opts.shell,
+ stdinText: opts.prompt,
+ // OpenCode's JSONL protocol is stdout-only. Stderr remains visible in
+ // logs and process-failure previews, but must never contribute usage,
+ // session state, or a stream-level provider error.
+ onStdoutLine: (line) => {
+ const event = parseOpenCodeLine(line)
+ if (event) tracker.observe(event)
+ },
+ },
)
} catch (err) {
return {
diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.ts
index 9574f22..0e76c74 100644
--- a/server/src/agents/computer/registry.ts
+++ b/server/src/agents/computer/registry.ts
@@ -357,40 +357,50 @@ export async function heartbeatComputer(
): Promise<void> {
const v = typeof version === 'string' && version ? version.slice(0, 32) : null
const sup = typeof supervised === 'boolean' ? supervised : null
- // Keep the advertised engine list current WITHOUT a re-pair. The daemon is
- // already online and re-scans PATH, so installing another supported CLI shows
- // up here instead of requiring the user to mint a new pairing token. Only for
- // paired computers: a cloud computer advertises 'managed' and has no PATH.
- if (detectedEngines) {
- const { rows } = await pool.query<{ available_engines: string[]; kind: ComputerKind }>(
- `SELECT available_engines, kind FROM computers WHERE id = $1 AND revoked_at IS NULL`,
- [computerId],
- )
- const row = rows[0]
- if (row && row.kind !== 'cloud') {
- const next = mergeDetectedEngines(row.available_engines ?? [], detectedEngines)
- if (next) {
- await pool.query(
- `UPDATE computers SET available_engines = $2::jsonb WHERE id = $1 AND revoked_at IS NULL`,
- [computerId, JSON.stringify(next)],
- )
- }
- }
- }
+ // Liveness is the primary heartbeat contract. Refreshing the optional PATH
+ // inventory must not run first: one transient read failure used to reject the
+ // whole request, so a healthy daemon could be swept offline even though its
+ // heartbeat reached the server.
const bumped = await pool.query(
`UPDATE computers SET last_seen_at = NOW(), daemon_version = COALESCE($2, daemon_version),
daemon_supervised = COALESCE($3, daemon_supervised)
WHERE id = $1 AND revoked_at IS NULL AND status = 'online' RETURNING 1`,
[computerId, v, sup],
)
- if (bumped.rowCount) return // already online — quiet bump
- const { rows } = await pool.query<{ company_id: string }>(
- `UPDATE computers SET status = 'online', last_seen_at = NOW(), daemon_version = COALESCE($2, daemon_version),
- daemon_supervised = COALESCE($3, daemon_supervised)
- WHERE id = $1 AND revoked_at IS NULL RETURNING company_id`,
- [computerId, v, sup],
- )
- if (rows[0]) await broadcastComputerStatus(computerId, rows[0].company_id, 'online')
+ if (!bumped.rowCount) {
+ const { rows } = await pool.query<{ company_id: string }>(
+ `UPDATE computers SET status = 'online', last_seen_at = NOW(), daemon_version = COALESCE($2, daemon_version),
+ daemon_supervised = COALESCE($3, daemon_supervised)
+ WHERE id = $1 AND revoked_at IS NULL RETURNING company_id`,
+ [computerId, v, sup],
+ )
+ if (rows[0]) await broadcastComputerStatus(computerId, rows[0].company_id, 'online')
+ }
+
+ // Keep the advertised engine list current WITHOUT a re-pair. This secondary
+ // refresh is best-effort: a database hiccup here must not turn a successful
+ // liveness update into an HTTP 500. Only paired computers participate; a
+ // cloud computer advertises 'managed' and has no PATH inventory.
+ if (detectedEngines) {
+ try {
+ const { rows } = await pool.query<{ available_engines: string[]; kind: ComputerKind }>(
+ `SELECT available_engines, kind FROM computers WHERE id = $1 AND revoked_at IS NULL`,
+ [computerId],
+ )
+ const row = rows[0]
+ if (row && row.kind !== 'cloud') {
+ const next = mergeDetectedEngines(row.available_engines ?? [], detectedEngines)
+ if (next) {
+ await pool.query(
+ `UPDATE computers SET available_engines = $2::jsonb WHERE id = $1 AND revoked_at IS NULL`,
+ [computerId, JSON.stringify(next)],
+ )
+ }
+ }
+ } catch (err) {
+ console.warn('[computers] heartbeat engine refresh failed:', err instanceof Error ? err.message : err)
+ }
+ }
}
/** Mark paired computers offline once their heartbeat goes stale, and
diff --git a/server/src/agents/kanban-wake.ts b/server/src/agents/kanban-wake.ts
index d48049d..4e1dc16 100644
--- a/server/src/agents/kanban-wake.ts
+++ b/server/src/agents/kanban-wake.ts
@@ -8,6 +8,31 @@ export interface KanbanWakeCard {
what: string
}
+export interface KanbanAssigneeChange {
+ nextAssigneeId: string | null
+ changed: boolean
+}
+
+/** Normalize the PATCH assignee field and distinguish a real reassignment
+ * from clients that echo the card's existing controlled value on every edit.
+ * Only a real transition should produce an assignment wake. */
+export function resolveKanbanAssigneeChange(
+ currentAssigneeId: string | null,
+ requestedAssigneeId: unknown,
+): KanbanAssigneeChange {
+ const specified = typeof requestedAssigneeId === 'string' || requestedAssigneeId === null
+ if (!specified) {
+ return { nextAssigneeId: currentAssigneeId, changed: false }
+ }
+ const nextAssigneeId = requestedAssigneeId === null
+ ? null
+ : requestedAssigneeId.trim() || null
+ return {
+ nextAssigneeId,
+ changed: nextAssigneeId !== currentAssigneeId,
+ }
+}
+
export function buildKanbanWakeBrief(card: KanbanWakeCard): WakeBackgroundBrief {
const title = card.title?.slice(0, 200) || null
return {
diff --git a/server/src/agents/runtime/byoa-source.ts b/server/src/agents/runtime/byoa-source.ts
new file mode 100644
index 0000000..b564395
--- /dev/null
+++ b/server/src/agents/runtime/byoa-source.ts
@@ -0,0 +1,21 @@
+/** Sources a BYOA daemon is allowed to attribute to local model calls. Keep
+ * this one whitelist shared by the triage and per-hop ledger endpoints. */
+export const BYOA_SOURCES = [
+ 'byoa-claude',
+ 'byoa-codex',
+ 'byoa-grok',
+ 'byoa-cursor',
+ 'byoa-opencode',
+ 'byoa-pi',
+ 'byoa-gemini',
+] as const
+
+export type ByoaSource = typeof BYOA_SOURCES[number]
+
+const BYOA_SOURCE_SET = new Set<string>(BYOA_SOURCES)
+
+export function normalizeByoaSource(value: unknown): ByoaSource {
+ return typeof value === 'string' && BYOA_SOURCE_SET.has(value)
+ ? value as ByoaSource
+ : 'byoa-claude'
+}
diff --git a/server/src/agents/runtime/server.ts b/server/src/agents/runtime/server.ts
index a26a685..ba41963 100644
--- a/server/src/agents/runtime/server.ts
+++ b/server/src/agents/runtime/server.ts
@@ -21,7 +21,8 @@ import { buildTriageRequest, gatherClaimsByConvo } from '../inbox-triage.js'
import { buildTeamRosterText, getPersona } from '../personas.js'
import { gatherAgentAgenda, classifyAgendaActionable, renderAgendaBrief, claimStallNudge, AGENDA_CLASSIFIER_ERROR } from '../agenda.js'
import { consumeAgentTurnToken } from '../scheduler.js'
-import { touchAgentRun, recordTriage, type TriageSource } from '../observability.js'
+import { touchAgentRun, recordTriage } from '../observability.js'
+import { normalizeByoaSource } from './byoa-source.js'
import { buildRuntimeArgv } from './cli-argv.js'
import { attachFsEndpoints } from './fs-endpoints.js'
import { inprocClient } from './inproc-client.js'
@@ -153,6 +154,14 @@ runtimeRouter.get('/inbox-triage/payload', withAgent(async (c, _req, res) => {
if (!c.companyId) { res.status(403).json({ error: 'companyId claim required' }); return }
const persona = await inprocClient.loadPersona(c.sub)
if (!persona) { res.status(404).json({ error: 'agent not found' }); return }
+ // A still-valid token can outlive an administrative tenant reassignment.
+ // Pin the subject's current tenant before loading its inbox; otherwise an old
+ // tenant's daemon can ask this route to assemble prompt content from the new
+ // tenant while loadContext alone remains correctly scoped to the JWT claim.
+ if (persona.companyId !== c.companyId) {
+ res.status(403).json({ error: 'agent does not belong to token tenant' })
+ return
+ }
const inbox = await inprocClient.loadInbox(c.sub)
const convoIds = [...new Set(inbox.map((m) => m.conversation_id))]
// Content-blind cost floor (NOT a loop decision). The daemon self-polls every
@@ -382,7 +391,7 @@ runtimeRouter.post('/triage', withAgent(async (c, req, res) => {
daemonVersion?: string
} | undefined
const daemonVersion = typeof body?.daemonVersion === 'string' && body.daemonVersion.trim() ? body.daemonVersion.trim().slice(0, 32) : null
- const source: TriageSource = (body?.source as TriageSource) ?? 'byoa-claude'
+ const source = normalizeByoaSource(body?.source)
void recordTriage({
agentId: c.sub,
companyId: c.companyId,
@@ -445,12 +454,7 @@ runtimeRouter.post('/llm-calls', withAgent(async (c, req, res) => {
extras?: Record<string, unknown>
}>
} | undefined
- const source = (
- body?.source === 'byoa-claude' || body?.source === 'byoa-codex' ||
- body?.source === 'byoa-grok' || body?.source === 'byoa-cursor' ||
- body?.source === 'byoa-opencode' || body?.source === 'byoa-pi' ||
- body?.source === 'byoa-gemini'
- ) ? body.source : 'byoa-claude'
+ const source = normalizeByoaSource(body?.source)
const daemonVersion = typeof body?.daemonVersion === 'string' && body.daemonVersion.trim() ? body.daemonVersion.trim().slice(0, 32) : null
const hops = Array.isArray(body?.hops) ? body!.hops : []
if (hops.length === 0) { res.json({ ok: true, inserted: 0 }); return }
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index 134547f..83fff09 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -10,7 +10,7 @@ import { env } from '../env.js'
import { startConvene, getActiveConvene } from '../agents/convene.js'
import { fetchImageBytes } from '../agents/image-fetcher.js'
import { getTriageEconomics, getWakeEconomics } from '../agents/observability.js'
-import { wakeKanbanAgents } from '../agents/kanban-wake.js'
+import { resolveKanbanAssigneeChange, wakeKanbanAgents } from '../agents/kanban-wake.js'
import { BUSY_STATUS_LEASE_MS } from '../status.js'
import { notifyMessage, computeMessageRecipients } from '../push.js'
import { randomUUID, randomBytes, createHash, timingSafeEqual } from 'node:crypto'
@@ -5326,9 +5326,9 @@ api.patch('/boards/:bid/cards/:cid', async (req, res) => {
// against the existing title/description and decide which broadcast kind
// to publish (card.moved vs card.updated).
const { rows: cur } = await pool.query<{
- title: string; description: string | null; column_id: string
+ title: string; description: string | null; column_id: string; assignee_id: string | null
}>(
- `SELECT title, description, column_id FROM board_cards
+ `SELECT title, description, column_id, assignee_id FROM board_cards
WHERE id = $1 AND board_id = $2 LIMIT 1`,
[cardId, boardId],
)
@@ -5339,6 +5339,7 @@ api.patch('/boards/:bid/cards/:cid', async (req, res) => {
let nextDesc = cur[0].description
let nextColumnId = cur[0].column_id
let columnChanged = false
+ const assigneeChange = resolveKanbanAssigneeChange(cur[0].assignee_id, req.body?.assigneeId)
if (typeof req.body?.title === 'string') {
nextTitle = req.body.title.trim().slice(0, 200)
params.push(nextTitle); sets.push(`title = $${params.length}`)
@@ -5350,9 +5351,8 @@ api.patch('/boards/:bid/cards/:cid', async (req, res) => {
if (typeof req.body?.position === 'number') {
params.push(req.body.position); sets.push(`position = $${params.length}`)
}
- if (typeof req.body?.assigneeId === 'string' || req.body?.assigneeId === null) {
- const a = req.body.assigneeId == null ? null : String(req.body.assigneeId).trim() || null
- params.push(a); sets.push(`assignee_id = $${params.length}`)
+ if (assigneeChange.changed) {
+ params.push(assigneeChange.nextAssigneeId); sets.push(`assignee_id = $${params.length}`)
}
if (typeof req.body?.columnId === 'string') {
const newCol = req.body.columnId.trim()
@@ -5395,8 +5395,8 @@ api.patch('/boards/:bid/cards/:cid', async (req, res) => {
},
})
// A re-assignment also wakes the new assignee.
- if (typeof req.body?.assigneeId === 'string') {
- const newAssignee = String(req.body.assigneeId).trim()
+ if (assigneeChange.changed) {
+ const newAssignee = assigneeChange.nextAssigneeId
if (newAssignee && newAssignee !== me) {
void wakeKanbanAgents({
companyId, mentions: [newAssignee], actorId: me,
diff --git a/src/components/Select.tsx b/src/components/Select.tsx
index 98edffd..4221c06 100644
--- a/src/components/Select.tsx
+++ b/src/components/Select.tsx
@@ -48,8 +48,8 @@ export function Select<T extends string = string>({
const rootRef = useRef<HTMLDivElement>(null)
const [open, setOpen] = useState(false)
const [animateMenu, setAnimateMenu] = useState(false)
- const selectedIndex = Math.max(0, options.findIndex((option) => option.value === value))
- const selected = options[selectedIndex]
+ const selectedIndex = options.findIndex((option) => option.value === value)
+ const selected = selectedIndex >= 0 ? options[selectedIndex] : undefined
const [activeIndex, setActiveIndex] = useState(selectedIndex)
useEffect(() => {
@@ -156,7 +156,7 @@ export function Select<T extends string = string>({
backgroundImage: 'var(--select-face)',
}}
>
- <span className="min-w-0 flex-1 truncate">{selected?.label ?? 'Select'}</span>
+ <span className="min-w-0 flex-1 truncate">{(selected?.label ?? value) || 'Select'}</span>
<span
aria-hidden="true"
className={cn(