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.

Let the reserve run on another account of the same harness (#72)

Eduardo Machado7636e2f9e6f8
diff --git a/src/core/db.ts b/src/core/db.ts
index 7af8cb9..d3946c1 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -227,6 +227,9 @@ const MIGRATIONS = [
`,
`
ALTER TABLE agents ADD COLUMN account TEXT;
+ `,
+ `
+ ALTER TABLE agents ADD COLUMN fallback_account TEXT;
`
]
@@ -312,6 +315,7 @@ export class Db {
modelId: str(r['model']),
...(str(r['account']) ? { accountId: str(r['account']) } : {}),
...(str(r['fallback_model']) ? { fallbackModelId: str(r['fallback_model']) } : {}),
+ ...(str(r['fallback_account']) ? { fallbackAccountId: str(r['fallback_account']) } : {}),
effort: str(r['effort']) as Effort,
limit: Number(r['limit_tokens']),
used: this.usedThisMonth(str(r['id'])),
@@ -341,14 +345,14 @@ export class Db {
saveAgent(a: Agent): void {
this.db
.prepare(
- `INSERT INTO agents (id, name, handle, role, color, instructions, model, fallback_model, account, effort, limit_tokens, grants, memory_mode, computer, computer_kind, web, browser, apps, auto_approve, archived, kind, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `INSERT INTO agents (id, name, handle, role, color, instructions, model, fallback_model, fallback_account, account, effort, limit_tokens, grants, memory_mode, computer, computer_kind, web, browser, apps, auto_approve, archived, kind, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (id) DO UPDATE SET name = excluded.name, handle = excluded.handle, role = excluded.role,
- color = excluded.color, instructions = excluded.instructions, model = excluded.model, fallback_model = excluded.fallback_model, account = excluded.account, effort = excluded.effort,
+ color = excluded.color, instructions = excluded.instructions, model = excluded.model, fallback_model = excluded.fallback_model, fallback_account = excluded.fallback_account, account = excluded.account, effort = excluded.effort,
limit_tokens = excluded.limit_tokens, grants = excluded.grants, memory_mode = excluded.memory_mode,
computer = excluded.computer, computer_kind = excluded.computer_kind, web = excluded.web, browser = excluded.browser, apps = excluded.apps, auto_approve = excluded.auto_approve, archived = excluded.archived, kind = COALESCE(excluded.kind, agents.kind)`
)
- .run(a.id, a.name, a.handle, a.role, a.color, a.instructions, a.modelId, a.fallbackModelId || null, a.accountId || null, a.effort, a.limit, JSON.stringify(a.grants), a.memory ?? 'auto', a.computer ? 1 : 0, a.computerKind === 'mac' ? 'mac' : 'linux', a.web === false ? 0 : 1, a.browser ? 1 : 0, JSON.stringify(a.apps ?? []), JSON.stringify(a.autoApprove ?? []), a.archived ? 1 : 0, a.kind ?? null, Date.now())
+ .run(a.id, a.name, a.handle, a.role, a.color, a.instructions, a.modelId, a.fallbackModelId || null, a.fallbackAccountId || null, a.accountId || null, a.effort, a.limit, JSON.stringify(a.grants), a.memory ?? 'auto', a.computer ? 1 : 0, a.computerKind === 'mac' ? 'mac' : 'linux', a.web === false ? 0 : 1, a.browser ? 1 : 0, JSON.stringify(a.apps ?? []), JSON.stringify(a.autoApprove ?? []), a.archived ? 1 : 0, a.kind ?? null, Date.now())
}
// Kept apart from saveAgent: folders change only after the core checks them.
diff --git a/src/core/engines/fake.ts b/src/core/engines/fake.ts
index ad3cc17..aedc07e 100644
--- a/src/core/engines/fake.ts
+++ b/src/core/engines/fake.ts
@@ -14,8 +14,9 @@ export function fakeEngine(id: Engine['id'], opts: { delayMs?: number; reply?: (
id,
async *run(turn): AsyncIterable<EngineEvent> {
const last = lastMessage(turn.prompt)
- // "acabou o limite": Claude's subscription is out, to see an agent's reserve model take over.
- if (id === 'claude' && /acabou o limite|out of quota/i.test(last) && turn.system !== routerSystem() && turn.system !== memorySystem()) {
+ // "acabou o limite": Claude's usual login is out, to see an agent's reserve take over (another
+ // harness, or another account of Claude, whose limit is still there).
+ if (id === 'claude' && !turn.account && /acabou o limite|out of quota/i.test(last) && turn.system !== routerSystem() && turn.system !== memorySystem()) {
yield { type: 'error', message: "You've hit your limit · resets 5pm" }
return
}
diff --git a/src/core/index.ts b/src/core/index.ts
index 87831cd..29a5dfe 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -931,8 +931,10 @@ const api: Api = {
removeAccount: ({ id }) => {
db.setSettings({ accounts: savedAccounts().filter((a) => a.id !== id) })
accountLogins.delete(id)
- for (const agent of db.agents().filter((x) => x.accountId === id)) {
- const { accountId: _gone, ...rest } = agent
+ for (const agent of db.agents().filter((x) => x.accountId === id || x.fallbackAccountId === id)) {
+ const rest = { ...agent }
+ if (rest.accountId === id) delete rest.accountId
+ if (rest.fallbackAccountId === id) delete rest.fallbackAccountId
db.saveAgent(rest)
emit({ type: 'agent', agent: db.agent(agent.id)! })
}
diff --git a/src/core/runs.ts b/src/core/runs.ts
index b641ba3..9e1c688 100644
--- a/src/core/runs.ts
+++ b/src/core/runs.ts
@@ -4,7 +4,7 @@ import { randomUUID } from 'node:crypto'
import { L, locale } from '../shared/lang'
import type { CoreEvent } from '../shared/rpc'
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
-import { ACCESS_REQUEST, CACHE_READ_WEIGHT, describeSchedule, workIn, ENGINES, ERRORS_STOP, usable, modelInfo, REPEAT_STOP, REPEAT_WARN, RUN_BUDGET_PCT, RUN_STALL_MINUTES, IMAGE_MIMES, MAX_IMAGE_BYTES, MAX_IMAGES_PER_MESSAGE, type Agent, type Approval, type Artifact, type ImageUpload, type Connector, type ConnectorTool, type Conversation, type EngineId, type Message, type Quota, type Receipt, type Routine, type Run, type RunStatus, type Settings, type Step } from '../shared/types'
+import { ACCESS_REQUEST, CACHE_READ_WEIGHT, describeSchedule, workIn, ENGINES, ERRORS_STOP, usable, modelInfo, REPEAT_STOP, REPEAT_WARN, RUN_BUDGET_PCT, RUN_STALL_MINUTES, IMAGE_MIMES, MAX_IMAGE_BYTES, MAX_IMAGES_PER_MESSAGE, type Account, type Agent, type Approval, type Artifact, type ImageUpload, type Connector, type ConnectorTool, type Conversation, type EngineId, type Message, type Quota, type Receipt, type Routine, type Run, type RunStatus, type Settings, type Step } from '../shared/types'
import { HISTORY_LIMIT, mentioned, systemPrompt, transcriptBlocks } from './context'
import { BUSCAR_MEMORIAS, LEMBRAR, type Memories } from './memory'
import { BROWSER_TOOL_NAMES, browserStep, browserTools, NAVEGADOR, type Browser } from './browser'
@@ -426,10 +426,17 @@ export class Runner {
}
// The agent's reserve model, when it has one that can run now: another model, on a harness that's ready.
- private reserveFor(agent: Agent, settings: Settings): ReturnType<typeof modelInfo> {
- const reserve = agent.fallbackModelId && agent.fallbackModelId !== agent.modelId ? modelInfo(agent.fallbackModelId) : undefined
- const status = reserve?.id ? settings.engines[reserve.engine] : undefined
- return reserve && status?.installed && status.loggedIn ? reserve : undefined
+ // The agent's reserve, when it can take the reply: its model, and the account it runs on (unset: its harness's
+ // usual login). None when it's the very login and model that just ran out, or when its login isn't ready.
+ private reserveFor(agent: Agent, settings: Settings, from: Account | undefined): { model: NonNullable<ReturnType<typeof modelInfo>>; account?: Account } | undefined {
+ const model = agent.fallbackModelId ? modelInfo(agent.fallbackModelId) : undefined
+ if (!model?.id) return undefined
+ // An account of another harness (the reserve's model changed since) means the usual login, like the agent's own.
+ const account = agent.fallbackAccountId ? settings.accounts?.find((a) => a.id === agent.fallbackAccountId && a.engine === model.engine) : undefined
+ if (agent.fallbackModelId === agent.modelId && account?.id === from?.id) return undefined
+ const status = settings.engines[model.engine]
+ if (!status?.installed || (account ? !account.loggedIn : !status.loggedIn)) return undefined
+ return { model, account }
}
private async execute(agent: Agent, conv: Conversation, opts: { depth: number; existing?: Message; task?: string; work?: string; routine?: boolean }): Promise<Message> {
@@ -439,6 +446,7 @@ export class Runner {
const model = modelInfo(agent.modelId)
// The model this reply runs on: the agent's, or its reserve once the main one's subscription is out.
let modelId = agent.modelId
+ let onReserve = false // the reserve takes a reply once
let modelName = model?.id ?? agent.modelId
let engineId: EngineId = model?.engine ?? 'claude'
let engineLabel = `${ENGINES[engineId].label} · ${model?.label ?? agent.modelId}`
@@ -1146,17 +1154,19 @@ export class Runner {
}
// The main model's subscription is out before it did anything: the same reply goes to the reserve, once.
// After a tool call it doesn't, since that would run the call again; the next reply starts on the main model.
- const reserve = modelId === agent.modelId && !result && error && !control.reason && !acted && !question && !approval && (!msg.text.trim() || outOfQuota(msg.text)) && outOfQuota(error) ? this.reserveFor(agent, settings) : undefined
+ const reserve = !onReserve && !result && error && !control.reason && !acted && !question && !approval && (!msg.text.trim() || outOfQuota(msg.text)) && outOfQuota(error) ? this.reserveFor(agent, settings, account) : undefined
if (!reserve) break
- const from = engineLabel
+ const from = `${engineLabel}${account ? ` (${account.name})` : ''}`
flush()
msg.text = '' // the CLI's own "you've hit your limit", when it wrote it as text
+ onReserve = true
modelId = agent.fallbackModelId!
- modelName = reserve.id
- engineId = reserve.engine
- engineLabel = `${ENGINES[engineId].label} · ${reserve.label}`
- account = undefined // the agent's account is a login of its main harness; the reserve runs on its harness's usual one
- addSteps({ id: randomUUID(), label: L('Foi pro modelo reserva', 'Moved to the reserve model'), detail: L(`${from} está sem limite agora; segue no ${engineLabel}`, `${from} is out of quota for now; going on with ${engineLabel}`), status: 'done' })
+ modelName = reserve.model.id
+ engineId = reserve.model.engine
+ engineLabel = `${ENGINES[engineId].label} · ${reserve.model.label}`
+ account = reserve.account
+ const to = `${engineLabel}${account ? ` (${account.name})` : ''}`
+ addSteps({ id: randomUUID(), label: L('Foi pro modelo reserva', 'Moved to the reserve model'), detail: L(`${from} está sem limite agora; segue no ${to}`, `${from} is out of quota for now; going on with ${to}`), status: 'done' })
error = null
progress = { tokens: 0, cacheRead: 0 }
}
diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsx
index 4c4133e..a3fa0fe 100644
--- a/src/renderer/src/components/Pages.tsx
+++ b/src/renderer/src/components/Pages.tsx
@@ -1248,16 +1248,25 @@ function Tabs({ page, tabs }: { page: string; tabs: TabList }): ReactNode {
// A model to run with, from what each harness in use offers, or another by name.
// Where the agent's replies go when its model's subscription is out (a 5-hour or weekly limit, a 429).
-// Off by default; turned on, it starts on another harness, since the same subscription is out for both.
+// Off by default. Turned on, it starts on another login of the same harness when there is one (the
+// limit is the account's), else on another harness, since the same subscription is out for both.
function ReserveModel({ draft, patch }: { draft: Agent; patch: (p: Partial<Agent>) => void }): ReactNode {
const usable = useStore((s) => usableEngines(s.settings))
+ const accounts = useStore((s) => s.settings.accounts) ?? []
const main = modelInfo(draft.modelId)?.engine
+ const mainAccount = accounts.find((a) => a.id === draft.accountId && a.engine === main)
const on = !!draft.fallbackModelId
- const first = (): string => {
- const other = usable.find((e) => e !== main) ?? usable[0]
- return MODELS.find((m) => m.engine === other)?.id ?? draft.modelId
+ const first = (): Partial<Agent> => {
+ const other = accounts.find((a) => a.engine === main && a.id !== mainAccount?.id)
+ if (other) return { fallbackModelId: draft.modelId, fallbackAccountId: other.id }
+ if (mainAccount) return { fallbackModelId: draft.modelId, fallbackAccountId: undefined } // the harness's usual login
+ const engine = usable.find((e) => e !== main) ?? usable[0]
+ return { fallbackModelId: MODELS.find((m) => m.engine === engine)?.id ?? draft.modelId, fallbackAccountId: undefined }
}
const reserve = draft.fallbackModelId ? modelInfo(draft.fallbackModelId) : undefined
+ const reserveAccounts = accounts.filter((a) => a.engine === reserve?.engine)
+ const reserveAccount = reserveAccounts.find((a) => a.id === draft.fallbackAccountId)
+ const sameLogin = !!reserve && reserve.engine === main && reserveAccount?.id === mainAccount?.id
return (
<div className="reserve">
<div className="key-row">
@@ -1266,16 +1275,41 @@ function ReserveModel({ draft, patch }: { draft: Agent; patch: (p: Partial<Agent
<strong>{L('Modelo reserva', 'Reserve model')}</strong>
<p className="muted small">
{L(
- `Quando a assinatura do modelo principal chega no limite (o de 5 horas ou o semanal), a resposta segue no reserva. Na resposta seguinte, ${draft.name || 'o agente'} tenta o principal de novo.`,
- `When the main model’s subscription hits its limit (the 5-hour or the weekly one), the reply goes on with the reserve. On the next reply, ${draft.name || 'the agent'} tries the main one again.`
+ `Quando a assinatura do modelo principal chega no limite (o de 5 horas ou o semanal), a resposta segue no reserva, que pode ser outro harness ou outra conta. Na resposta seguinte, ${draft.name || 'o agente'} tenta o principal de novo.`,
+ `When the main model’s subscription hits its limit (the 5-hour or the weekly one), the reply goes on with the reserve, which can be another harness or another account. On the next reply, ${draft.name || 'the agent'} tries the main one again.`
)}
</p>
</div>
- <Toggle on={on} onChange={(v) => patch({ fallbackModelId: v ? first() : undefined })} />
+ <Toggle on={on} onChange={(v) => patch(v ? first() : { fallbackModelId: undefined, fallbackAccountId: undefined })} />
</div>
- {on && <ModelPicker value={draft.fallbackModelId!} onChange={(fallbackModelId) => patch({ fallbackModelId })} />}
- {on && reserve && reserve.engine === main && (
- <p className="hint hint--warn">{L('É o mesmo harness do principal: se o limite for da assinatura, ele também vai estar sem.', 'It’s the same harness as the main one: if the limit is the subscription’s, it’ll be out too.')}</p>
+ {on && (
+ <ModelPicker
+ value={draft.fallbackModelId!}
+ onChange={(fallbackModelId) => patch({ fallbackModelId, ...(modelInfo(fallbackModelId)?.engine !== reserve?.engine ? { fallbackAccountId: undefined } : {}) })}
+ />
+ )}
+ {on && reserve && reserveAccounts.length > 0 && (
+ <label className="field">
+ <span className="field__label">{L('Conta da reserva', 'Reserve account')}</span>
+ <select value={reserveAccount?.id ?? ''} onChange={(e) => patch({ fallbackAccountId: e.target.value || undefined })}>
+ <option value="">{L(`A de sempre do ${ENGINES[reserve.engine].label}`, `${ENGINES[reserve.engine].label}’s usual one`)}</option>
+ {reserveAccounts.map((a) => (
+ <option key={a.id} value={a.id}>
+ {a.name}
+ {a.loggedIn ? '' : L(' (falta entrar)', ' (not signed in)')}
+ </option>
+ ))}
+ </select>
+ {reserveAccount && !reserveAccount.loggedIn && <span className="hint hint--warn">{L('Essa conta ainda não entrou: a reserva só funciona depois que você entrar nela em Configurações › Modelos.', 'This account isn’t signed in yet: the reserve only works once you sign in under Settings › Models.')}</span>}
+ </label>
+ )}
+ {on && sameLogin && (
+ <p className="hint hint--warn">
+ {draft.fallbackModelId === draft.modelId
+ ? L('É o mesmo modelo, na mesma conta do principal: a reserva não vai ser usada.', 'It’s the same model, on the same account as the main one: the reserve won’t be used.')
+ : L('É o mesmo harness, na mesma conta do principal: se o limite for da assinatura, ele também vai estar sem.', 'It’s the same harness, on the same account as the main one: if the limit is the subscription’s, it’ll be out too.')}
+ {reserveAccounts.length > 0 ? L(' Escolha outra conta em “Conta da reserva”.', ' Pick another one under “Reserve account”.') : ''}
+ </p>
)}
</div>
)
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 59157a4..6ee8b1f 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -60,6 +60,9 @@ export interface Agent {
// Where a reply goes when modelId's subscription is out (its 5-hour or weekly limit, a 429): tried
// only when the main model failed before doing anything, and the next reply tries the main one again.
fallbackModelId?: string
+ // The login the reserve runs on: one of settings.accounts, of the reserve's harness; unset: that harness's usual login.
+ // With it, the reserve can be the same model on another account, when the main account's limit is out.
+ fallbackAccountId?: string
accountId?: string // one of settings.accounts, for its harness; unset: the harness's own login
effort: Effort
limit: number // tokens per month
diff --git a/test/reserve-account.test.ts b/test/reserve-account.test.ts
new file mode 100644
index 0000000..2e82056
--- /dev/null
+++ b/test/reserve-account.test.ts
@@ -0,0 +1,146 @@
+import { mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { beforeEach, describe, expect, it } from 'vitest'
+import type { Account, Agent, EngineId, Message, Settings } from '../src/shared/types'
+import { Db } from '../src/core/db'
+import { accountDir } from '../src/core/engines/detect'
+import { fakeEngine } from '../src/core/engines/fake'
+import type { Engine, EngineEvent, Turn } from '../src/core/engines/types'
+import { Runner } from '../src/core/runs'
+
+const ready = { installed: true, loggedIn: true }
+const agent = (extra: Partial<Agent> = {}): Agent => ({ id: 'a1', name: 'lia', handle: 'lia', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'auto', computer: false, archived: false, ...extra })
+
+// Claude, whose limit is out on some logins (by their folder; undefined: the usual login) and not on others.
+const claudeOutOn = (out: (string | undefined)[]): Engine & { turns: Turn[] } => {
+ const turns: Turn[] = []
+ const ok = fakeEngine('claude', { delayMs: 1 })
+ return {
+ id: 'claude',
+ turns,
+ run: (t) => {
+ turns.push(t)
+ if (!out.includes(t.account)) return ok.run(t)
+ return (async function* (): AsyncIterable<EngineEvent> {
+ yield { type: 'error', message: "You've hit your limit · resets 5pm" }
+ })()
+ }
+ }
+}
+
+let db: Db
+let data: string
+let settings: Settings
+let codexTurns: Turn[]
+const work: Account = { id: 'w1', engine: 'claude', name: 'Trabalho', loggedIn: true }
+const personal: Account = { id: 'p1', engine: 'claude', name: 'Pessoal', loggedIn: true }
+
+function runner(claude: Engine): Runner {
+ codexTurns = []
+ const codex = fakeEngine('codex', { delayMs: 1 })
+ const engines: Record<EngineId, Engine> = { claude, codex: { id: 'codex', run: (t) => (codexTurns.push(t), codex.run(t)) }, opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini') }
+ return new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-work-')), dataDir: data })
+}
+const reply = (): Message => db.messages().filter((m) => m.author.kind === 'agent').at(-1)!
+
+beforeEach(() => {
+ data = mkdtempSync(join(tmpdir(), 'ad-data-'))
+ db = new Db(join(data, 'test.db'))
+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt', accounts: [work, personal] }
+ db.saveAgent(agent())
+ db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })
+})
+
+describe('the reserve on another account', () => {
+ it('is kept with the agent, and cleared', () => {
+ db.saveAgent(agent({ fallbackModelId: 'sonnet', fallbackAccountId: 'p1' }))
+ expect(db.agent('a1')).toMatchObject({ fallbackModelId: 'sonnet', fallbackAccountId: 'p1' })
+ db.saveAgent(agent())
+ expect(db.agent('a1')!.fallbackAccountId).toBeUndefined()
+ })
+
+ it('takes the reply on the same model, from the usual login to another account', async () => {
+ db.saveAgent(agent({ fallbackModelId: 'sonnet', fallbackAccountId: 'p1' }))
+ const claude = claudeOutOn([undefined])
+ const r = runner(claude)
+ await r.send('d1', 'oi')
+ await r.idle()
+ const m = reply()
+ expect(m.run?.status).toBe('done')
+ expect(claude.turns.map((t) => t.account)).toEqual([undefined, accountDir(data, 'p1')])
+ expect(claude.turns[1]!.model).toBe(claude.turns[0]!.model)
+ expect(m.run?.steps.find((s) => s.label === 'Foi pro modelo reserva')?.detail).toBe('Claude Code · Sonnet está sem limite agora; segue no Claude Code · Sonnet (Pessoal)')
+ expect(codexTurns).toHaveLength(0)
+ })
+
+ it('goes from one account to another, and from an account to the usual login', async () => {
+ db.saveAgent(agent({ accountId: 'w1', fallbackModelId: 'sonnet', fallbackAccountId: 'p1' }))
+ let claude = claudeOutOn([accountDir(data, 'w1')])
+ let r = runner(claude)
+ await r.send('d1', 'oi')
+ await r.idle()
+ expect(reply().run?.status).toBe('done')
+ expect(claude.turns.map((t) => t.account)).toEqual([accountDir(data, 'w1'), accountDir(data, 'p1')])
+ expect(reply().run?.steps.find((s) => s.label === 'Foi pro modelo reserva')?.detail).toContain('(Trabalho) está sem limite')
+
+ db.saveAgent(agent({ accountId: 'w1', fallbackModelId: 'sonnet' }))
+ claude = claudeOutOn([accountDir(data, 'w1')])
+ r = runner(claude)
+ await r.send('d1', 'de novo')
+ await r.idle()
+ expect(reply().run?.status).toBe('done')
+ expect(claude.turns.map((t) => t.account)).toEqual([accountDir(data, 'w1'), undefined])
+ })
+
+ it('is tried once: when the reserve account is out too, the reply fails', async () => {
+ db.saveAgent(agent({ fallbackModelId: 'sonnet', fallbackAccountId: 'p1' }))
+ const claude = claudeOutOn([undefined, accountDir(data, 'p1')])
+ const r = runner(claude)
+ await r.send('d1', 'oi')
+ await r.idle()
+ expect(reply().run?.status).toBe('failed')
+ expect(claude.turns).toHaveLength(2)
+ })
+
+ it('starts on the main account again on the next reply', async () => {
+ db.saveAgent(agent({ fallbackModelId: 'sonnet', fallbackAccountId: 'p1' }))
+ const claude = claudeOutOn([undefined])
+ const r = runner(claude)
+ await r.send('d1', 'oi')
+ await r.idle()
+ await r.send('d1', 'e agora?')
+ await r.idle()
+ expect(claude.turns.map((t) => t.account)).toEqual([undefined, accountDir(data, 'p1'), undefined, accountDir(data, 'p1')])
+ })
+
+ it('isn’t used when it’s the same model on the same login, nor when its account isn’t signed in', async () => {
+ for (const setup of [
+ () => db.saveAgent(agent({ fallbackModelId: 'sonnet' })),
+ () => db.saveAgent(agent({ accountId: 'p1', fallbackModelId: 'sonnet', fallbackAccountId: 'p1' })),
+ () => {
+ db.saveAgent(agent({ fallbackModelId: 'sonnet', fallbackAccountId: 'p1' }))
+ settings = { ...settings, accounts: [work, { ...personal, loggedIn: false }] }
+ }
+ ]) {
+ db = new Db(join(mkdtempSync(join(tmpdir(), 'ad-db-')), 'test.db'))
+ setup()
+ db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })
+ const claude = claudeOutOn([undefined, accountDir(data, 'p1')])
+ const r = runner(claude)
+ await r.send('d1', 'oi')
+ await r.idle()
+ expect(reply().run).toMatchObject({ status: 'failed' })
+ expect(claude.turns).toHaveLength(1)
+ }
+ })
+
+ it('runs on the usual login when its account belongs to another harness', async () => {
+ db.saveAgent(agent({ fallbackModelId: 'gpt-5.6-luna', fallbackAccountId: 'p1' }))
+ const r = runner(claudeOutOn([undefined]))
+ await r.send('d1', 'oi')
+ await r.idle()
+ expect(reply().run?.status).toBe('done')
+ expect(codexTurns.map((t) => t.account)).toEqual([undefined])
+ })
+})