Skip to content

Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.

Keep an approval decided while the agent is still replying (#122)

Alan Jones Rios80c84d0b432e
diff --git a/src/core/runs.ts b/src/core/runs.ts
index 5b275a6..9976189 100644
--- a/src/core/runs.ts
+++ b/src/core/runs.ts
@@ -124,7 +124,8 @@ export interface RoutineEvent {
body: string // the item itself, clipped
}
-type Control = { ctl: AbortController; reason?: 'stopped' | 'limit' | 'budget' | 'loop' | 'errors' | 'stall' }
+// msg is the live reply: a decision taken mid-run must land on it, or the run's last save overwrites it.
+type Control = { ctl: AbortController; msg: Message; reason?: 'stopped' | 'limit' | 'budget' | 'loop' | 'errors' | 'stall' }
export class Runner {
private queue: (() => Promise<unknown>)[] = []
@@ -568,7 +569,7 @@ export class Runner {
// The wiki: for agents that may read it, once it has a page.
const wiki = this.deps.gateway && this.deps.wiki && wikiAccess(agent) !== 'none' && this.deps.wiki.count() > 0 ? this.deps.wiki : undefined
- const control: Control = { ctl: new AbortController() }
+ const control: Control = { ctl: new AbortController(), msg }
this.controllers.set(msg.id, control)
const halt = (reason: NonNullable<Control['reason']>): void => {
if (control.reason) return
@@ -1302,10 +1303,12 @@ export class Runner {
run: { ...base, ...again, status: 'limit_reached', steps: closeThinking('error', L('Parou no limite de tokens', 'Stopped at the token limit')), error: L('Cheguei no meu limite de tokens deste mês no meio da resposta.', 'I hit my token limit for this month in the middle of the reply.') }
})
} else if (result) {
+ // Approved or refused before the run ended: nothing is left to wait for.
+ const waiting = approval && db.approval(approval.id)?.state === 'pending'
// Streamed text keeps every model call of the turn; the final result may hold only the last one.
save({
text: msg.text.trim() ? msg.text.trim() : result.text.trim() ? result.text : (narration ?? ''), // said it all before its last tool
- run: { ...base, status: question ? 'waiting_input' : approval ? 'waiting_approval' : 'done', steps: closeThinking('done', L('Respondeu', 'Replied')) }
+ run: { ...base, status: question ? 'waiting_input' : waiting ? 'waiting_approval' : 'done', steps: closeThinking('done', L('Respondeu', 'Replied')) }
})
// The Mac tells you when it's your turn: a question, or the end of the work (once, when no other agent takes it on).
if (question) this.deps.notify?.(L(`${agent.name} te perguntou`, `${agent.name} asked you`), question, conv.id, 'question', msg.threadId)
@@ -1481,10 +1484,15 @@ export class Runner {
db.setApprovalOutcome(id, outcome)
emit({ type: 'approval', approval: db.approval(id)! })
- const msg = db.message(ap.messageId)
+ // Approved while the agent is still replying: add the step to the live reply, which saves it when it ends.
+ const live = this.controllers.get(ap.messageId)?.msg
+ const msg = live ?? db.message(ap.messageId)
if (msg?.run) {
const label = decision === 'approved' ? L('Aprovado', 'Approved') : decision === 'refused' ? L('Recusado', 'Refused') : L('Expirou', 'Expired')
- this.update(msg, {
+ if (live) {
+ live.run!.steps.push({ id: randomUUID(), label, detail: outcome, status: decision === 'approved' && ok ? 'done' : 'error' })
+ this.update(live, {})
+ } else this.update(msg, {
run: {
...msg.run,
status: msg.run.status === 'waiting_approval' ? 'done' : msg.run.status,
diff --git a/test/governance.test.ts b/test/governance.test.ts
index f992ed3..953d8b9 100644
--- a/test/governance.test.ts
+++ b/test/governance.test.ts
@@ -254,6 +254,45 @@ describe('approvals', () => {
expect(db.approvals()[0]).toMatchObject({ state: 'expired', outcome: 'Expirou sem decisão.' })
expect(seen.turns.at(-1)?.prompt).toContain('expirou sem decisão')
})
+
+ it("approved while the reply is still being written: the reply's last save keeps the decision (#121)", async () => {
+ db.saveAgent(agent('read_write'))
+ // A "model" that asks, then goes on writing; I approve before it ends.
+ let r!: Runner
+ let asked = false
+ const engine: Engine = {
+ id: 'claude',
+ async *run(turn) {
+ seen.turns.push(turn)
+ if (turn.mcpUrl && !asked) {
+ asked = true
+ const client = new Client({ name: 'scripted', version: '0' })
+ await client.connect(new StreamableHTTPClientTransport(new URL(turn.mcpUrl)))
+ await client.callTool({ name: 'tarefas__delete_task', arguments: { id: 2, _motivo: 'duplicada' } })
+ await client.close()
+ await r.decide(db.approvals()[0]!.id, 'approved')
+ }
+ yield { type: 'text', delta: 'pedi pra apagar e sigo escrevendo' }
+ yield { type: 'done', text: 'pedi pra apagar e sigo escrevendo', usage: { inputTokens: 10, cacheReadTokens: 0, outputTokens: 2 } }
+ }
+ }
+ r = new Runner({
+ db,
+ engines: { claude: engine, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') },
+ settings: async () => settings,
+ emit: (e) => events.push(e),
+ workDir: join(dir, 'work'),
+ gateway,
+ connectors
+ })
+ await r.send('d1', 'apaga a tarefa 2')
+ await r.idle()
+
+ expect(db.approvals()[0]).toMatchObject({ state: 'approved', outcome: 'Executou.' })
+ const reply = agentMessages()[0]!
+ expect(reply.run?.status).toBe('done') // not waiting for an approval that was given
+ expect(reply.run?.steps.map((s) => s.label)).toEqual(expect.arrayContaining(['Pediu aprovação', 'Aprovado']))
+ })
})
describe('always allow and asking for access', () => {