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(agent): "No result was produced" has to be true where it is posted (#266)

Xialie Zhuang8e80f3cf368a
diff --git a/server/src/__integration__/agent-anti-duplicate.test.ts b/server/src/__integration__/agent-anti-duplicate.test.ts
index f2339b9..1499178 100644
--- a/server/src/__integration__/agent-anti-duplicate.test.ts
+++ b/server/src/__integration__/agent-anti-duplicate.test.ts
@@ -481,3 +481,37 @@ test('[integration] with no run id the gate behaves exactly as before', async ()
assert.match(second.text, /you already posted in/)
})
})
+
+// ─── exit 2 means HELD, and only that ──────────────────────────────
+//
+// turn.ts now reads the exit code to tell a deliberate stand-down apart from a
+// crash: a HELD relay ends the turn as `skipped` instead of posting "Agent run
+// failed … No result was produced" into a room where a peer just delivered.
+// That only works while 2 means exactly one thing.
+
+test('[integration] a HELD reply exits 2, an ordinary refusal exits 1', async () => {
+ const { agentA, agentB, convoId } = await seedGroupWithTwoAgents()
+
+ await runCli(['--as', agentB, 'reply', convoId, 'The answer is 42.'])
+ const held = await runCli(['--as', agentA, 'reply', convoId, 'The answer is 42.'])
+ assert.equal(held.ok, false)
+ assert.match(held.text, /HELD/)
+ assert.equal(held.exitCode, 2, 'HELD must be distinguishable from a crash by exit code alone')
+
+ // A refusal that is not a stand-down: nothing was deliberately declined, the
+ // caller simply asked for something impossible.
+ const usage = await runCli(['--as', agentA, 'reply'])
+ assert.equal(usage.ok, false)
+ assert.equal(usage.exitCode, 1, 'an ordinary error must not masquerade as HELD')
+})
+
+test('[unit] the top-level catch-all does not claim to be a hold', async () => {
+ // An unexpected exception is not "your write was declined, re-decide and
+ // retry" — and it used to exit 2, which is what made the code ambiguous.
+ const { readFile } = await import('node:fs/promises')
+ const source = await readFile(new URL('../agents/cli.ts', import.meta.url), 'utf8')
+ const tail = source.slice(source.lastIndexOf('} catch (e) {'))
+
+ assert.match(tail, /err\(`error: \$\{e instanceof Error \? e\.message : String\(e\)\}`, 1\)/,
+ 'the catch-all exits 2 again, so turn.ts can no longer tell a deliberate stand-down from a crash')
+})
diff --git a/server/src/__integration__/agent-turn.test.ts b/server/src/__integration__/agent-turn.test.ts
index 5afef26..b5ee653 100644
--- a/server/src/__integration__/agent-turn.test.ts
+++ b/server/src/__integration__/agent-turn.test.ts
@@ -1650,3 +1650,215 @@ test('[integration] MAX_HOPS: model that keeps requesting tools is capped withou
// direct one we seeded.
assert.match(conversationId, /^direct-/)
})
+
+// ─── "No result was produced" has to be true ───────────────────────
+//
+// postTurnFailureNotices posted that line into every conversation in the
+// inbox whenever finalStatus was 'failed', without asking whether the turn had
+// in fact produced something there. A turn can answer in hop 3 and then die at
+// MAX_HOPS, the token ceiling, or a turn-status protocol violation in hop 40 —
+// the room has the reply, and the red line lands directly under it saying the
+// opposite of what the user can see.
+//
+// The other half: a HELD relay. cmdReply exits 2 to say "declined on purpose,
+// a peer already delivered this". Treating that as a failed run reported the
+// coordination system working as a crash.
+
+test('[integration] a failure notice under a delivered answer drops the false clause', async () => {
+ const { companyId, agentId, humanId, conversationId } = await seedConvo({ kind: 'direct' })
+ await postHumanMessage({ conversationId, companyId, humanId, body: 'what is the answer?' })
+
+ const answer = 'The answer is 42.'
+ // Answer in hop 1, then the provider dies on the next call — the stub throws
+ // once its scripted streams run out. A missing turn status alone would NOT
+ // do: a user-visible reply infers `done`, which is correct and deliberate.
+ // This is the shape that genuinely fails after an answer has landed, the same
+ // as MAX_HOPS or the hard token ceiling further into a long turn.
+ const llm = makeLlmStub([
+ streamWithToolCall({
+ fcId: 'fc_reply', callId: 'call_reply', name: 'bash',
+ argsJson: JSON.stringify({ command: `cumora reply ${conversationId} '${answer}'` }),
+ }),
+ ])
+ llm.install()
+ makeToolStub({
+ bash: async () => {
+ const messageId = `m-${randomUUID()}`
+ await pool.query(
+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id)
+ VALUES ($1, $2, $3, 'text', $4, 2, $5)`,
+ [messageId, conversationId, agentId, answer, companyId],
+ )
+ return {
+ ok: true,
+ output: bashReplyOutput({ stdout: `sent (${messageId}, seq 2)`, conversationId, messageId }),
+ durationMs: 1,
+ display: { name: 'bash', arg: 'reply', status: 'ok', detail: '' },
+ }
+ },
+ set_turn_status: turnStatusToolResult,
+ }).install()
+
+ await assert.rejects(runAgentTurn(agentId))
+
+ const { rows: runs } = await pool.query<{ status: string }>(
+ `SELECT status FROM agent_runs WHERE agent_id = $1`, [agentId],
+ )
+ assert.equal(runs[0].status, 'failed', 'the run still genuinely failed — that is not what changed')
+
+ const posted = await messagesFromAgent(conversationId, agentId)
+ assert.equal(posted.length, 1)
+ assert.equal(posted[0].body, answer, 'the answer is in the room')
+
+ const { rows: notices } = await pool.query<{ body: string }>(
+ `SELECT body FROM messages WHERE conversation_id = $1 AND kind = 'system'`,
+ [conversationId],
+ )
+ // The notice still goes out — it is the only thing telling the user the run
+ // died and the work may be incomplete. What changes is the sentence: it must
+ // not claim the opposite of what the room can see one line above it.
+ assert.equal(notices.length, 1, 'the run failed, so the room must still be told')
+ assert.match(notices[0].body, /Agent run failed before it could finish/)
+ assert.doesNotMatch(
+ notices[0].body, /No result was produced/,
+ `a room that already has the answer was told "No result was produced": ${notices[0].body}`,
+ )
+})
+
+test('[integration] a rename is not an answer — the full sentence stays', async () => {
+ // The predicate has to be `message.posted`, not "any visible side effect".
+ // leave / invite / kick / topic_updated / renamed all report visibleToUser
+ // too, and an agent that renamed the room and then died has answered nobody:
+ // trimming the clause there would quietly drop the only prompt to re-ask.
+ const { companyId, agentId, humanId, conversationId } = await seedConvo({ kind: 'direct' })
+ await postHumanMessage({ conversationId, companyId, humanId, body: 'what is the answer?' })
+
+ const llm = makeLlmStub([
+ streamWithToolCall({
+ fcId: 'fc_rename', callId: 'call_rename', name: 'bash',
+ argsJson: JSON.stringify({ command: `cumora rename ${conversationId} 'Q3 launch'` }),
+ }),
+ ])
+ llm.install()
+ makeToolStub({
+ bash: async () => ({
+ ok: true,
+ output: {
+ stdout: 'renamed',
+ stderr: '',
+ exitCode: 0,
+ sideEffects: [{
+ event: 'conversation.renamed',
+ command: 'rename',
+ conversationId,
+ visibleToUser: true,
+ }],
+ },
+ durationMs: 1,
+ display: { name: 'bash', arg: 'rename', status: 'ok', detail: '' },
+ }),
+ set_turn_status: turnStatusToolResult,
+ }).install()
+
+ await assert.rejects(runAgentTurn(agentId))
+
+ const { rows: notices } = await pool.query<{ body: string }>(
+ `SELECT body FROM messages WHERE conversation_id = $1 AND kind = 'system'`,
+ [conversationId],
+ )
+ assert.equal(notices.length, 1)
+ assert.match(
+ notices[0].body, /No result was produced/,
+ 'a rename was mistaken for a delivered answer, so the user was never told to re-ask',
+ )
+})
+
+test('[integration] a HELD relay is a stand-down, not a failed run', async () => {
+ const { companyId, agentId, humanId, conversationId } = await seedConvo({ kind: 'direct' })
+ await postHumanMessage({ conversationId, companyId, humanId, body: 'count please' })
+ void companyId
+
+ const llm = makeLlmStub([
+ streamWithJustText('The answer is 42.'),
+ streamWithToolCall({
+ fcId: 'fc_status', callId: 'call_status', name: 'set_turn_status',
+ argsJson: JSON.stringify({
+ status: 'done', reason: 'relay the draft', next_step: '',
+ assistant_text: 'reply', reply_conversation_id: conversationId,
+ }),
+ }),
+ ])
+ llm.install()
+ makeToolStub({
+ // Exactly what tBash returns when cmdReply exits 2: a peer already posted
+ // this, so the write was declined on purpose.
+ bash: async () => ({
+ ok: false,
+ output: { stdout: 'HELD — verbatim duplicate of the immediately-prior peer post', stderr: '', exitCode: 2 },
+ error: 'exit 2',
+ durationMs: 1,
+ display: { name: 'bash', arg: 'reply', status: 'held', detail: '' },
+ }),
+ set_turn_status: turnStatusToolResult,
+ }).install()
+
+ await runAgentTurn(agentId)
+
+ const { rows: runs } = await pool.query<{ status: string }>(
+ `SELECT status FROM agent_runs WHERE agent_id = $1`, [agentId],
+ )
+ assert.equal(runs[0].status, 'skipped', 'a deliberate decline is not a failed run')
+
+ const { rows: notices } = await pool.query<{ body: string }>(
+ `SELECT body FROM messages WHERE conversation_id = $1 AND kind = 'system'`,
+ [conversationId],
+ )
+ assert.equal(notices.length, 0, 'the coordination system working must not read as a crash')
+
+ const ev = await eventsForAgent(agentId)
+ assert.equal(ev.filter((e) => e.kind === 'turn.auto_relay_held').length, 1, 'the stand-down is still observable')
+ assert.equal(ev.filter((e) => e.kind === 'turn.auto_relay_failed').length, 0)
+})
+
+test('[integration] a relay that genuinely failed is still a failed run', async () => {
+ // The guard rail: only exit 2 means "held". Anything else is a real failure
+ // and must keep its notice, or this fix would swallow lost answers.
+ const { companyId, agentId, humanId, conversationId } = await seedConvo({ kind: 'direct' })
+ await postHumanMessage({ conversationId, companyId, humanId, body: 'count please' })
+ void companyId
+
+ const llm = makeLlmStub([
+ streamWithJustText('The answer is 42.'),
+ streamWithToolCall({
+ fcId: 'fc_status', callId: 'call_status', name: 'set_turn_status',
+ argsJson: JSON.stringify({
+ status: 'done', reason: 'relay the draft', next_step: '',
+ assistant_text: 'reply', reply_conversation_id: conversationId,
+ }),
+ }),
+ ])
+ llm.install()
+ makeToolStub({
+ bash: async () => ({
+ ok: false,
+ output: { stdout: '', stderr: 'boom', exitCode: 1 },
+ error: 'exit 1',
+ durationMs: 1,
+ display: { name: 'bash', arg: 'reply', status: 'error', detail: '' },
+ }),
+ set_turn_status: turnStatusToolResult,
+ }).install()
+
+ await runAgentTurn(agentId)
+
+ const { rows: runs } = await pool.query<{ status: string }>(
+ `SELECT status FROM agent_runs WHERE agent_id = $1`, [agentId],
+ )
+ assert.equal(runs[0].status, 'failed')
+
+ const { rows: notices } = await pool.query<{ body: string }>(
+ `SELECT body FROM messages WHERE conversation_id = $1 AND kind = 'system'`,
+ [conversationId],
+ )
+ assert.equal(notices.length, 1, 'a genuinely lost answer must still tell the room')
+})
diff --git a/server/src/agents/cli.ts b/server/src/agents/cli.ts
index 03be578..3af23b9 100644
--- a/server/src/agents/cli.ts
+++ b/server/src/agents/cli.ts
@@ -6662,7 +6662,11 @@ export async function runCli(argv: string[]): Promise<CliResult> {
return err(`unknown subcommand: ${sub}\nrun "cumora help" for usage`)
}
} catch (e) {
- return err(`error: ${e instanceof Error ? e.message : String(e)}`, 2)
+ // 1, not 2. Exit 2 means HELD — "your write was deliberately declined,
+ // re-decide and retry" — and five call sites use it that way. An
+ // unexpected exception is not that, and turn.ts now reads the code to tell
+ // a stand-down apart from a crash.
+ return err(`error: ${e instanceof Error ? e.message : String(e)}`, 1)
}
}
diff --git a/server/src/agents/turn.ts b/server/src/agents/turn.ts
index 23366c4..b27c6b5 100644
--- a/server/src/agents/turn.ts
+++ b/server/src/agents/turn.ts
@@ -1723,8 +1723,36 @@ export async function runAgentTurn(agentId: string, options: AgentTurnOptions =
if (failureNoticePosted || inbox.length === 0) return
failureNoticePosted = true
const uniqueConvoIds = [...new Set(inbox.map((m) => m.conversation_id))]
+ // "No result was produced" has to be true where it is posted. A turn can
+ // answer in hop 3 and then die at MAX_HOPS or the token ceiling in hop 40;
+ // the room already has the reply, and a red failure line directly under it
+ // says the opposite of what the user can see.
+ //
+ // Fix the SENTENCE, not the notice. Suppressing it outright would silence
+ // the announce-then-die case, which is drawn from the same population: the
+ // rules mandate an intent message before long work (see the operating rules
+ // below), and long multi-hop turns are exactly the ones that reach MAX_HOPS
+ // or the token ceiling. There the room would get "Drafting the summary now."
+ // and then nothing — and nothing wakes an agent on an unread inbox alone,
+ // so no one retries it either. The failure line is the only thing telling
+ // the user to re-ask.
+ //
+ // `message.posted` specifically, not "any visible side effect": leave,
+ // invite, kick, topic_updated and renamed all report visibleToUser too, and
+ // an agent that renamed the room in hop 2 has not answered anybody.
+ // Per conversation, because one turn can span several and only some of them
+ // may have been answered.
+ const deliveredConvoIds = new Set(
+ cliSideEffectsThisTurn
+ .filter((e) => e.event === 'message.posted' && e.visibleToUser !== false)
+ .map((e) => e.conversationId)
+ .filter((id): id is string => typeof id === 'string'),
+ )
const reason = agentTurnFailureNoticeReason(summary, err)
- const noticeText = `Agent run failed before it could finish (${reason}). No result was produced.`
+ const failedText = `Agent run failed before it could finish (${reason}).`
+ const noticeTextFor = (convoId: string): string => (
+ deliveredConvoIds.has(convoId) ? failedText : `${failedText} No result was produced.`
+ )
const withNoticeTimeout = async <T>(promise: Promise<T>, label: string): Promise<T> => {
const timeoutMs = 5_000
let timer: ReturnType<typeof setTimeout> | null = null
@@ -1798,7 +1826,7 @@ export async function runAgentTurn(agentId: string, options: AgentTurnOptions =
companyId: convoCompanyId,
agentId,
noticeKind: 'agent_turn_failed',
- text: noticeText,
+ text: noticeTextFor(convoId),
dedupeKey: `agent_turn_failed:${convoId}:${inputKey}`,
dedupeTtlSec: 6 * 3600,
}), `postSystemNotice(${convoId})`)
@@ -1812,6 +1840,7 @@ export async function runAgentTurn(agentId: string, options: AgentTurnOptions =
reason,
inputMessageIds: convoInbox.map((m) => m.id),
noticePosted: res.posted,
+ resultDelivered: deliveredConvoIds.has(convoId),
},
stage: 'failed',
}).catch(() => { /* observability best-effort */ })
@@ -3260,7 +3289,26 @@ Mechanics:
argsJson: JSON.stringify({ command: `cumora reply ${target.conversationId} ${escaped} --continue` }),
ns: namespace,
})
- if (!relay.ok) {
+ // Exit 2 is HELD: cmdReply deliberately declined the write because a peer
+ // already delivered this. Nothing failed — the coordination system did
+ // its job and the room already has the answer. Reporting that as a failed
+ // run puts "Agent run failed … No result was produced" under a result
+ // that a teammate produced seconds earlier. `skipped` is the status this
+ // file already uses for a turn that intentionally does nothing.
+ const relayExit = (relay.output as { exitCode?: unknown } | null)?.exitCode
+ const relayHeld = !relay.ok && relayExit === 2
+ if (relayHeld) {
+ finalStatus = 'skipped'
+ finalSummary ||= 'Auto-relay held — a peer already delivered this'
+ await runtime.recordEvent({
+ runId, agentId, companyId: convoCompanyId,
+ kind: 'turn.auto_relay_held',
+ level: 'info',
+ title: 'Auto-relay held by a peer delivery',
+ data: { conversationId: target.conversationId, output: relay.output },
+ stage: 'auto_relay_held',
+ })
+ } else if (!relay.ok) {
finalStatus = 'failed'
finalError = `Auto-relay reply failed: ${relay.error ?? 'unknown error'}`
await runtime.recordEvent({