Branchwell

OpenTalon / app · opentalon.ai / native / runtime / gemini-agent.test.cjs

1const test = require('node:test')
2const assert = require('node:assert/strict')
3const fs = require('node:fs')
4const path = require('node:path')
5const { randomUUID } = require('node:crypto')
6const { Store } = require('./store.cjs')
7const { AgentRunner, JsonProcess, askAgent, draftTask, executable } = require('./agent-runner.cjs')
8const { agentModels, agentIds, validateModelOverrides } = require('./agent-models.cjs')
9const { tools, validateAction } = require('./contracts.cjs')
10const { assertAgentReady } = require('./agent-readiness.cjs')
11const gemini = require('./gemini-agent.cjs')
12const base = process.env.OPENTALON_TEST_ROOT || '/Volumes/Expand/Projects/OpenTalon/native-app/tests'
13fs.mkdirSync(base, { recursive: true })
14
15// Captured from Google's signed agy 1.5.15 on November 23, 2026, in an empty home folder.
16const captured = (name) =>
17 JSON.parse(fs.readFileSync(path.join(__dirname, 'fixtures', `agy-1.5.15-${name}.json`), 'utf8'))
18const initialized = captured('initialize').result
19const signedOut = captured('signed-out').error
20const flash = 'gemini-3.8-flash-high'
21const hydrogen = 'gemini-4-hydrogen-high'
22const carbon = 'gemini-4-carbon-high'
23const sessionId = '0b9f3f0e-5a55-4d5f-9a39-2d5d7e5c1a10'
24const modes = (currentModeId = 'default', ids = ['default', 'accept-edits', 'auto', 'plan']) =>
25 ({ currentModeId, availableModes: ids.map((id) => ({ id, name: id })) })
26const models = (currentModelId = 'gemini-4-neon-medium', ids = [flash, hydrogen, carbon, 'gemini-4-neon-medium']) =>
27 ({ currentModelId, availableModels: ids.map((modelId) => ({ modelId, name: modelId })) })
28const rejection = (error) => Object.assign(new Error(error.message), { code: error.code })
29
30// A scripted `agy acp` peer. Replies default to a signed-in session with every model.
31function fakeAgy(replies = {}) {
32 const launched = []
33 const spawnTransport = (file, args, cwd, message, exit, options) => {
34 const entry = {
35 file, args, cwd, message, exit, options, written: [], closed: false, turn: null,
36 async request(method, params, claude, timeout) {
37 entry.written.push({ method, params, timeout })
38 if (replies[method]) return replies[method](params, entry)
39 if (method === 'initialize') return initialized
40 if (method === 'session/new') return { sessionId, modes: modes(), models: models() }
41 if (method === 'session/resume' || method === 'session/load') return { modes: modes(), models: models() }
42 if (method === 'session/prompt') return new Promise((resolve, reject) => { entry.turn = { resolve, reject } })
43 return {}
44 },
45 write(line) { entry.written.push(line) },
46 close() { entry.closed = true },
47 sent: (method) => entry.written.filter((line) => line.method === method),
48 }
49 launched.push(entry)
50 return entry
51 }
52 return { launched, spawnTransport }
53}
54
55function fixture(t, replies, { installed = true } = {}) {
56 const folder = fs.mkdtempSync(path.join(base, 'gemini-'))
57 const store = new Store(folder)
58 const agy = fakeAgy(replies)
59 const opened = []
60 const runner = new AgentRunner({
61 store,
62 connector: {
63 status: () => ({ running: true }),
64 configuration: () => ({
65 mcpServers: { opentalon: { command: '/safe/app', args: ['/bridge.cjs'], env: { OPENTALON_MCP_CONFIG: '/run/config.json' } } },
66 }),
67 },
68 openExternal: (url) => opened.push(url),
69 resolveExecutable: (agent) => (agent === 'gemini' && !installed ? null : '/safe/' + agent),
70 spawnTransport: agy.spawnTransport,
71 home: folder,
72 })
73 t.after(async () => {
74 await runner.close()
75 store.close()
76 fs.rmSync(folder, { recursive: true, force: true })
77 })
78 const write = (name, input) => store.dispatch(name, { ...input, requestKey: randomUUID() }, 'You · test')
79 const settings = (permissionMode) =>
80 write('set_agent_settings', { defaultAgent: 'gemini', workingFolder: folder, ...(permissionMode ? { permissionMode } : {}) })
81 const send = async (title, extra = {}) => {
82 const { task } = await write('create_task', { boardId: store.boards()[0].id, title })
83 await write('move_task', { id: task.id, expectedRevision: task.revision, status: 'Sent to agent', ...extra })
84 await runner.tick()
85 return { task, job: store.agentJobs().find((job) => job.taskId === task.id), transport: agy.launched.at(-1) }
86 }
87 const update = (transport, body, session = sessionId) =>
88 transport.message({ method: 'session/update', params: { sessionId: session, update: body } })
89 const said = (transport, text, messageId = 'm1') =>
90 update(transport, { sessionUpdate: 'agent_message_chunk', messageId, content: { type: 'text', text } })
91 return { folder, store, runner, opened, write, settings, send, update, said, ...agy }
92}
93
94test('Gemini ships as its own agent with Flash first and explicit Antigravity model slugs', () => {
95 assert.deepEqual(agentIds, ['claude-code', 'codex', 'gemini'])
96 assert.deepEqual(agentModels.filter(({ agent }) => agent === 'gemini').map(({ id, title }) => [id, title]), [
97 [flash, 'Gemini 3.8 Flash'], [hydrogen, 'Gemini 4 Hydrogen'], [carbon, 'Gemini 4 Carbon'],
98 ['gemini-4-neon-high', 'Gemini 4 Neon'], ['gemini-4-argon-high', 'Gemini 4 Argon'],
99 ])
100 assert.ok(!agentModels.some(({ id }) => /^gemini-(2|3\.[0-7])/.test(id)), 'Deprecated Gemini models are not offered')
101 assert.equal(validateModelOverrides([{ agent: 'gemini', id: 'gemini-4-neon-xhigh', title: 'Neon XHigh' }])[0].agent, 'gemini')
102 for (const [name, input] of [
103 ['set_agent_settings', { requestKey: 'k', defaultAgent: 'gemini', workingFolder: '/tmp' }],
104 ['open_agent_install_guide', { agent: 'gemini' }],
105 ['create_task', { requestKey: 'k', boardId: 'b', title: 'T', agent: 'gemini', model: hydrogen }],
106 ]) validateAction(name, input, true)
107 assert.throws(() => validateAction('set_agent_settings', { requestKey: 'k', defaultAgent: 'bard', workingFolder: '' }, true),
108 { code: 'INVALID_ARGUMENT' })
109 const overrides = tools.find(({ name }) => name === 'set_agent_models').inputSchema.properties.overrides
110 assert.ok(overrides.items.properties.agent.enum.includes('gemini'))
111})
112
113test('the Gemini launcher is agy; the retired gemini CLI is never picked up', (t) => {
114 const bin = fs.mkdtempSync(path.join(base, 'gemini-bin-'))
115 const previous = process.env.PATH
116 t.after(() => { process.env.PATH = previous; fs.rmSync(bin, { recursive: true, force: true }) })
117 fs.writeFileSync(path.join(bin, 'gemini'), '#!/bin/sh\n', { mode: 0o755 })
118 process.env.PATH = bin
119 assert.notEqual(executable('gemini'), path.join(bin, 'gemini'))
120 assert.equal(executable('bard'), null)
121 fs.writeFileSync(path.join(bin, 'agy'), '#!/bin/sh\n', { mode: 0o755 })
122 assert.equal(path.basename(executable('gemini')), 'agy')
123})
124
125test('a Gemini task launches agy acp with only the OpenTalon server, the default model, and reports status', async (t) => {
126 const f = fixture(t)
127 await f.settings()
128 assert.deepEqual(f.runner.status().gemini, { installed: true, name: 'Gemini' })
129 const { task, job, transport } = await f.send('Write the launch notes')
130 assert.equal(job.agent, 'gemini')
131 assert.equal(job.model, flash, 'Agent default names Gemini 3.8 Flash')
132 assert.equal(transport.file, '/safe/gemini')
133 assert.deepEqual(transport.args, ['acp', '--sandbox'])
134 assert.equal(transport.cwd, fs.realpathSync(f.folder))
135 assert.deepEqual(transport.options, {
136 jsonrpc: true, withoutEnvironment: ['GEMINI_API_KEY', 'AGY_ADC_AUTH', 'GOOGLE_GEMINI_BASE_URL'],
137 })
138 assert.deepEqual(transport.written.map(({ method }) => method),
139 ['initialize', 'session/new', 'session/set_model', 'session/set_mode', 'session/prompt'])
140 const [initialize, created, model, mode, prompt] = transport.written
141 assert.equal(initialize.params.protocolVersion, 1)
142 assert.deepEqual(initialize.params.clientCapabilities, { fs: { readTextFile: false, writeTextFile: false }, terminal: false })
143 assert.deepEqual(created.params, {
144 cwd: fs.realpathSync(f.folder),
145 mcpServers: [{
146 name: 'opentalon', command: '/safe/app', args: ['/bridge.cjs'],
147 env: [{ name: 'OPENTALON_MCP_CONFIG', value: '/run/config.json' }],
148 }],
149 })
150 assert.deepEqual(model.params, { sessionId, modelId: flash })
151 assert.deepEqual(mode.params, { sessionId, modeId: 'auto' })
152 assert.equal(prompt.timeout, 0, 'The turn is not cut off by the request timeout')
153 assert.equal(prompt.params.sessionId, sessionId)
154 assert.match(prompt.params.prompt[0].text, /Write the launch notes/)
155 assert.ok(prompt.params.prompt[0].text.includes(job.id))
156 assert.equal(f.store.agentJob(job.id).state, 'starting')
157 assert.equal(f.store.agentJob(job.id).threadId, sessionId)
158
159 await f.said(transport, 'Reading the task. ')
160 assert.equal(f.store.agentJob(job.id).state, 'working')
161 assert.equal(f.store.task(task.id).status, 'In progress')
162 await f.said(transport, 'Notes are saved.', 'm2')
163 await f.said(transport, ' Review them.', 'm2')
164 transport.turn.resolve({ stopReason: 'end_turn' })
165 await new Promise(setImmediate)
166 const finished = f.store.agentJob(job.id)
167 assert.equal(finished.state, 'review')
168 assert.equal(finished.summary, 'Notes are saved. Review them.')
169 assert.ok(transport.closed)
170 assert.equal(transport.sent('session/cancel').length, 0)
171 const activity = (await f.store.dispatch('list_task_activity', { taskId: task.id })).entries
172 assert.ok(activity.some((entry) => entry.summary === 'Gemini picked up the task'))
173 assert.ok(!activity.some((entry) => /Claude|Codex/.test(entry.summary)))
174})
175
176test('the chosen Gemini model is the one sent; a model for another agent is refused', async (t) => {
177 const f = fixture(t)
178 await f.settings()
179 const { task } = await f.write('create_task', { boardId: f.store.boards()[0].id, title: 'Reason through the plan' })
180 const move = { id: task.id, expectedRevision: task.revision, status: 'Sent to agent', agent: 'gemini' }
181 await assert.rejects(f.write('move_task', { ...move, model: 'gpt-6.2-sol' }), { code: 'INVALID_ARGUMENT' })
182 await assert.rejects(f.write('move_task', { ...move, agent: 'codex', model: carbon }), { code: 'INVALID_ARGUMENT' })
183 await f.write('move_task', { ...move, model: carbon })
184 await f.runner.tick()
185 assert.deepEqual(f.launched[0].sent('session/set_model').map(({ params }) => params.modelId), [carbon])
186})
187
188test('Agent default names Gemini 3.8 Flash; chosen models and the owner’s model list are kept exactly', async (t) => {
189 const f = fixture(t, { 'session/new': () => ({ sessionId, modes: modes(), models: models(flash, [flash]) }) })
190 await f.settings()
191 const unconfigured = await f.send('Agent default')
192 assert.equal(unconfigured.job.model, flash)
193 assert.equal(unconfigured.transport.sent('session/prompt').length, 1)
194 await f.runner.stop(unconfigured.job.id)
195
196 // A chosen model this account lacks stops the run. Flash is on offer and is not used instead.
197 const chosen = await f.send('Chosen model', { agent: 'gemini', model: hydrogen })
198 assert.equal(chosen.job.model, hydrogen)
199 assert.equal(f.store.agentJob(chosen.job.id).state, 'failed')
200 assert.match(f.store.agentJob(chosen.job.id).summary, /does not offer gemini-4-hydrogen-high.*did not switch models/)
201 assert.equal(chosen.transport.sent('session/set_model').length, 0)
202 assert.equal(chosen.transport.sent('session/prompt').length, 0)
203 assert.equal(f.store.agentJob(unconfigured.job.id).model, flash, 'An earlier run keeps the model it was sent with')
204
205 // The owner's own list decides Agent default once they change it.
206 const saveModels = async (overrides) => f.write('set_agent_models', {
207 overrides, expectedCatalogRevision: (await f.store.dispatch('get_agent_models')).catalogRevision,
208 })
209 await saveModels([{ agent: 'gemini', id: flash, title: 'Gemini 3.8 Flash', hidden: true }])
210 const preferred = await f.send('Owner hid Flash')
211 assert.equal(preferred.job.model, hydrogen)
212 await f.runner.stop(preferred.job.id)
213 await assert.rejects(f.write('create_task', {
214 boardId: f.store.boards()[0].id, title: 'Hidden model', status: 'Sent to agent', agent: 'gemini', model: flash,
215 }), { code: 'INVALID_ARGUMENT' })
216
217 await saveModels(agentModels.filter(({ agent }) => agent === 'gemini').map((model) => ({ ...model, hidden: true })))
218 await assert.rejects(f.write('create_task', {
219 boardId: f.store.boards()[0].id, title: 'No Gemini models', status: 'Sent to agent',
220 }), { code: 'INVALID_ARGUMENT', message: 'Add a Gemini model in Settings before sending this task.' })
221})
222
223test('model slugs resolve against config options with a separate thinking level, or not at all', async () => {
224 const session = () => ({
225 sessionId,
226 configOptions: [
227 { id: 'model', category: 'model', currentValue: 'gemini-4-neon', options: [
228 { group: 'gemini', name: 'Gemini', options: [{ value: 'gemini-4-neon', name: 'Neon' }, { value: 'gemini-4-carbon', name: 'Carbon' }] }] },
229 { id: 'thinking', category: 'thought_level', currentValue: 'medium', options: [
230 { value: 'medium', name: 'Medium' }, { value: 'high', name: 'High' }, { value: 'xhigh', name: 'Extra' }] },
231 ],
232 })
233 const sent = []
234 const transport = { request: async (method, params) => { sent.push([method, params]); return {} } }
235 assert.deepEqual(await gemini.selectGeminiModel(transport, session(), carbon), { model: 'gemini-4-carbon', thinking: 'high' })
236 assert.deepEqual(sent, [
237 ['session/set_config_option', { sessionId, configId: 'model', value: 'gemini-4-carbon' }],
238 ['session/set_config_option', { sessionId, configId: 'thinking', value: 'high' }],
239 ])
240 sent.length = 0
241 for (const model of ['gemini-4-hydrogen-high', 'gemini-4-carbon-max', 'gemini-4-carbon-', undefined])
242 await assert.rejects(gemini.selectGeminiModel(transport, session(), model), /Gemini/)
243 await assert.rejects(gemini.selectGeminiModel(transport, session(), 'gemini-4-hydrogen-high'), { code: 'AGENT_MODEL_UNAVAILABLE' })
244 await assert.rejects(gemini.selectGeminiModel(transport, { sessionId }, carbon), { code: 'AGENT_MODEL_UNAVAILABLE' })
245 assert.ok(!sent.some(([, params]) => params.configId === 'thinking'), 'No partial model is left selected as a success')
246 // A reply that reports a different model than the one requested is a failure, not a fallback.
247 const stubborn = { request: async () => ({ configOptions: session().configOptions }) }
248 await assert.rejects(gemini.selectGeminiModel(stubborn, session(), carbon), { code: 'AGENT_MODEL_UNAVAILABLE' })
249})
250
251test('agent default reflects the Google account list while explicit task choices stay fixed', async (t) => {
252 const f = fixture(t)
253 await f.settings()
254 const defaultId = () => f.store.agentModelCatalog().models.find(model => model.agent === 'gemini').id
255 assert.equal(defaultId(), 'gemini-3.8-flash-high', 'New offline or signed-out account')
256 f.store.googleAccountModels = ['gemini-3.8-flash-high']
257 assert.equal(defaultId(), 'gemini-3.8-flash-high', 'Free account')
258 f.store.googleAccountModels = ['gemini-4-neon-xhigh', 'gemini-4-neon-high', hydrogen, 'gemini-3.8-flash-high']
259 assert.equal(defaultId(), 'gemini-4-neon-high', 'Paid account')
260 const { job } = await f.send('Use my explicit choice', { agent: 'gemini', model: hydrogen })
261 assert.equal(job.model, hydrogen)
262})
263
264test('withdrawing a shared Gemini request cancels the current prompt and continues the other work in the same session', async (t) => {
265 const f = fixture(t)
266 await f.settings()
267 const { job, transport } = await f.send('Review a synthetic checklist', { agent: 'gemini', model: hydrogen })
268 const withdrawn = { id: randomUUID(), text: 'Skip the old title.' }
269 assert.deepEqual(await f.runner.notifyWithdrawal(randomUUID(), withdrawn), { notified: false })
270 assert.deepEqual(await f.runner.notifyWithdrawal(job.id, withdrawn), { notified: true })
271 assert.deepEqual(await f.runner.notifyWithdrawal(job.id, withdrawn), { notified: true })
272 assert.equal(transport.sent('session/cancel').length, 1)
273 transport.turn.resolve({ stopReason: 'cancelled' })
274 await new Promise(setImmediate)
275 const prompts = transport.sent('session/prompt')
276 assert.equal(prompts.length, 2)
277 assert.equal(prompts[1].params.sessionId, sessionId)
278 assert.ok(prompts[1].params.prompt[0].text.includes(withdrawn.id))
279 transport.turn.resolve({ stopReason: 'end_turn' })
280 await new Promise(setImmediate)
281 assert.equal(f.store.agentJob(job.id).state, 'review')
282})
283
284test('a signed-out agy fails closed with the captured error and never starts a sign-in or a turn', async (t) => {
285 const f = fixture(t, { 'session/new': () => { throw rejection(signedOut) } })
286 await f.settings()
287 const { task, job, transport } = await f.send('Needs an account')
288 const failed = f.store.agentJob(job.id)
289 assert.equal(failed.state, 'failed')
290 assert.match(failed.summary, /Gemini needs you to sign in\. Run agy in Terminal/)
291 assert.deepEqual(transport.written.map(({ method }) => method), ['initialize', 'session/new'])
292 assert.equal(transport.sent('authenticate').length, 0)
293 assert.ok(transport.closed)
294 assert.equal(f.store.task(task.id).status, 'To do', 'The task returns to To do, not to another agent')
295 assert.equal(f.launched.length, 1, 'No other agent ran in its place')
296})
297
298test('an unavailable model, an incompatible CLI or a CLI without Google sign-in fails closed', async (t) => {
299 for (const [replies, pattern, last] of [
300 [{ 'session/new': () => ({ sessionId, modes: modes(), models: models(carbon, [carbon]) }) },
301 /does not offer gemini-3\.8-flash-high.*did not switch models/, 'session/new'],
302 [{ 'session/set_model': () => { throw new Error('quota') } }, /does not offer gemini-3\.8-flash-high/, 'session/set_model'],
303 [{ initialize: () => ({ ...initialized, protocolVersion: 2 }) }, /not compatible with OpenTalon/, 'initialize'],
304 [{ initialize: () => ({ ...initialized, authMethods: initialized.authMethods.slice(2) }) }, /does not offer Google sign-in/, 'initialize'],
305 [{ 'session/new': () => ({ sessionId: '../escape' }) }, /did not return a conversation/, 'session/new'],
306 [{ 'session/new': () => ({ sessionId, models: models(), modes: modes('plan', ['plan']) }) }, /approval mode OpenTalon can enforce/, 'session/set_model'],
307 ]) {
308 const f = fixture(t, replies)
309 await f.settings()
310 const { job, transport } = await f.send('Fail closed')
311 assert.equal(f.store.agentJob(job.id).state, 'failed')
312 assert.match(f.store.agentJob(job.id).summary, pattern)
313 assert.equal(transport.written.at(-1).method, last)
314 assert.equal(transport.sent('session/prompt').length, 0)
315 assert.ok(transport.closed)
316 }
317})
318
319test('a missing agy launcher blocks dispatch and reports Gemini as not installed', async (t) => {
320 const f = fixture(t, {}, { installed: false })
321 assert.deepEqual(f.runner.status().gemini, { installed: false, name: 'Gemini' })
322 assert.throws(() => assertAgentReady({ defaultAgent: 'gemini', workingFolder: f.folder }, f.runner.status(), { running: true }),
323 { code: 'AGENT_NOT_INSTALLED' })
324 await f.settings()
325 const { job } = await f.send('No launcher')
326 assert.equal(f.store.agentJob(job.id).state, 'failed')
327 assert.match(f.store.agentJob(job.id).summary, /Gemini’s local launcher is not installed/)
328 assert.equal(f.launched.length, 0)
329})
330
331test('a Google task restricts its own MCP access without changing global servers or saved permissions', (t) => {
332 const f = fixture(t)
333 const config = path.join(f.folder, '.gemini', 'config')
334 const cli = path.join(f.folder, '.gemini', 'antigravity-cli')
335 fs.mkdirSync(config, { recursive: true })
336 fs.mkdirSync(cli, { recursive: true })
337 const registration = JSON.stringify({ mcpServers: { peer: { command: 'peer' }, off: { disabled: true } } })
338 const original = JSON.stringify({ permissions: { allow: ['mcp(peer/*)'], ask: ['command(*)'], deny: ['read_file(secrets)'] } })
339 fs.writeFileSync(path.join(config, 'mcp_config.json'), registration)
340 fs.writeFileSync(path.join(cli, 'settings.json'), original)
341 const [flag, session] = gemini.geminiScopedSettings(f.folder, f.folder)
342 assert.equal(flag, '--settings')
343 assert.deepEqual(JSON.parse(session).permissions, { allow: ['mcp(peer/*)'], ask: ['command(*)'], deny: ['read_file(secrets)', 'mcp(peer/*)'] })
344 assert.equal(fs.readFileSync(path.join(cli, 'settings.json'), 'utf8'), original)
345 assert.equal(fs.readFileSync(path.join(config, 'mcp_config.json'), 'utf8'), registration)
346})
347
348test('tool servers saved in Antigravity stop the run before agy starts', async (t) => {
349 const f = fixture(t)
350 await f.settings()
351 const config = path.join(f.folder, '.gemini', 'config')
352 fs.mkdirSync(path.join(config, 'plugins', 'drive'), { recursive: true })
353 fs.writeFileSync(path.join(config, 'mcp_config.json'), JSON.stringify({ mcpServers: {
354 opentalon: { command: 'old-bridge' }, paused: { command: 'x', disabled: true } } }))
355 fs.writeFileSync(path.join(config, 'plugins', 'drive', 'mcp_config.json'), JSON.stringify({ mcpServers: { drive: { url: 'https://example.test' } } }))
356 const blocked = await f.send('Scoped only')
357 assert.equal(f.store.agentJob(blocked.job.id).state, 'failed')
358 assert.match(f.store.agentJob(blocked.job.id).summary, /conflicts with the scoped OpenTalon/)
359 assert.equal(f.launched.length, 0)
360
361 fs.rmSync(path.join(f.folder, '.gemini'), { recursive: true })
362 fs.mkdirSync(path.join(f.folder, '.agents'))
363 fs.writeFileSync(path.join(f.folder, '.agents', 'mcp_config.json'), '{ not json')
364 const unreadable = await f.send('Unreadable settings')
365 assert.match(f.store.agentJob(unreadable.job.id).summary, /tool server settings could not be read/)
366 assert.equal(f.launched.length, 0)
367
368 fs.writeFileSync(path.join(f.folder, '.agents', 'mcp_config.json'), JSON.stringify({ mcpServers: { paused: { command: 'x', disabled: true } } }))
369 const allowed = await f.send('Nothing else enabled')
370 assert.equal(f.store.agentJob(allowed.job.id).state, 'starting')
371 assert.equal(f.launched.length, 1)
372})
373
374test('the saved access mode decides the agy flags and session mode', async (t) => {
375 const manual = fixture(t, { 'session/new': () => ({ sessionId, models: models(flash), modes: modes('auto') }) })
376 await manual.settings('manual')
377 const asked = (await manual.send('Manual')).transport
378 assert.deepEqual(asked.args, ['acp', '--sandbox'])
379 assert.deepEqual(asked.sent('session/set_mode').map(({ params }) => params.modeId), ['default'])
380 assert.equal(asked.sent('session/set_model').length, 0, 'The model is already the requested one')
381
382 const full = fixture(t)
383 await full.settings('full-access')
384 const open = (await full.send('Full access')).transport
385 assert.deepEqual(open.args, ['acp', '--dangerously-skip-permissions'])
386 assert.equal(open.sent('session/set_mode').length, 0)
387
388 const noAuto = fixture(t, { 'session/new': () => ({ sessionId, models: models(flash), modes: modes('default', ['default', 'plan']) }) })
389 await noAuto.settings('auto')
390 const fallback = (await noAuto.send('Automatic without auto mode')).transport
391 assert.deepEqual(fallback.args, ['acp', '--sandbox'])
392 assert.equal(fallback.sent('session/set_mode').length, 0, 'Stays in the mode that asks the owner')
393})
394
395test('Gemini approvals reach the owner, answer once with the offered option, and other requests are refused', async (t) => {
396 const f = fixture(t)
397 await f.settings('manual')
398 const { job, transport } = await f.send('Needs approval')
399 const options = [
400 { optionId: 'always', name: 'Always allow', kind: 'allow_always' },
401 { optionId: 'once', name: 'Allow', kind: 'allow_once' },
402 { optionId: 'no', name: 'Reject', kind: 'reject_once' },
403 ]
404 const ask = (id, extra = {}) => transport.message({
405 id, method: 'session/request_permission',
406 params: { sessionId, toolCall: { toolCallId: 'call-' + id, title: 'Run npm test', kind: 'execute', rawInput: { command: 'npm test' } }, options, ...extra },
407 })
408 await ask(7)
409 const waiting = f.store.agentJob(job.id)
410 assert.equal(waiting.state, 'needs-input')
411 assert.deepEqual([waiting.approval.id, waiting.approval.title, waiting.approval.canApprove], ['7', 'Run npm test', true])
412 assert.match(waiting.approval.details, /npm test/)
413 await f.runner.answer(job.id, '7', true)
414 assert.deepEqual(transport.written.at(-1), { id: 7, result: { outcome: { outcome: 'selected', optionId: 'once' } } })
415 assert.equal(f.store.agentJob(job.id).state, 'working')
416
417 await ask(8)
418 await f.runner.answer(job.id, '8', false)
419 assert.deepEqual(transport.written.at(-1), { id: 8, result: { outcome: { outcome: 'selected', optionId: 'no' } } })
420
421 await ask(9, { options: [options[0]] })
422 assert.equal(f.store.agentJob(job.id).approval.canApprove, false, 'A standing grant is never given on the owner’s behalf')
423 await assert.rejects(f.runner.answer(job.id, '9', true), { code: 'STALE_APPROVAL' })
424 await f.runner.answer(job.id, '9', false)
425 assert.deepEqual(transport.written.at(-1), { id: 9, result: { outcome: { outcome: 'cancelled' } } })
426
427 await transport.message({ id: 10, method: 'fs/write_text_file', params: { sessionId, path: '/etc/hosts', content: '' } })
428 assert.equal(transport.written.at(-1).error.code, -32601)
429 await ask(11, { sessionId: 'another-session' })
430 assert.equal(transport.written.at(-1).error.code, -32601)
431 assert.equal(f.store.agentJob(job.id).approval, null)
432})
433
434test('stopping a Gemini run cancels the turn, then closes agy; late replies change nothing', async (t) => {
435 const f = fixture(t)
436 await f.settings()
437 const { job, transport } = await f.send('Stop me')
438 await f.said(transport, 'Working')
439 await f.runner.stop(job.id)
440 assert.equal(f.store.agentJob(job.id).state, 'canceled')
441 assert.deepEqual(transport.written.at(-1), { method: 'session/cancel', params: { sessionId } })
442 assert.equal(f.runner.current, null)
443 await new Promise((resolve) => setTimeout(resolve, 450))
444 assert.ok(transport.closed)
445 transport.turn.resolve({ stopReason: 'cancelled' })
446 await f.said(transport, 'Late text')
447 await transport.exit(new Error('Late exit'))
448 assert.equal(f.store.agentJob(job.id).state, 'canceled')
449})
450
451test('turn endings and a mid-run model switch are terminal, with Gemini named in the reason', async (t) => {
452 for (const [result, state, pattern] of [
453 [{ stopReason: 'refusal' }, 'failed', /Gemini declined this request/],
454 [{ stopReason: 'max_turn_requests' }, 'failed', /stopped before finishing \(max turn requests\)/],
455 [{ stopReason: 'cancelled' }, 'canceled', /Gemini stopped this turn/],
456 [{}, 'failed', /stopped before finishing\./],
457 ]) {
458 const f = fixture(t)
459 await f.settings()
460 const { job, transport } = await f.send('Ends')
461 transport.turn.resolve(result)
462 await new Promise(setImmediate)
463 assert.equal(f.store.agentJob(job.id).state, state)
464 assert.match(f.store.agentJob(job.id).summary, pattern)
465 }
466 const signedOutLater = fixture(t)
467 await signedOutLater.settings()
468 const expired = await signedOutLater.send('Token expired')
469 expired.transport.turn.reject(rejection(signedOut))
470 await new Promise(setImmediate)
471 assert.match(signedOutLater.store.agentJob(expired.job.id).summary, /Gemini needs you to sign in/)
472
473 const f = fixture(t, { 'session/new': () => ({ sessionId, modes: modes('auto'), configOptions: [
474 { id: 'model', category: 'model', currentValue: hydrogen, options: [{ value: hydrogen, name: 'Hydrogen' }, { value: flash, name: 'Flash' }] }] }) })
475 await f.settings()
476 const { job, transport } = await f.send('Stay on Hydrogen', { agent: 'gemini', model: hydrogen })
477 const option = (currentValue) => ({ sessionUpdate: 'config_option_update', configOptions: [{ id: 'model', category: 'model', currentValue }] })
478 await f.update(transport, option(hydrogen))
479 assert.equal(f.store.agentJob(job.id).state, 'working')
480 await f.update(transport, option(flash))
481 assert.equal(f.store.agentJob(job.id).state, 'failed')
482 assert.match(f.store.agentJob(job.id).summary, /switched away from gemini-4-hydrogen-high/)
483})
484
485test('a Gemini run continues the same conversation, ignores replayed history, and refuses a different one', async (t) => {
486 const f = fixture(t)
487 await f.settings()
488 const { task, job, transport } = await f.send('Continue me')
489 await f.said(transport, 'Which fixture?')
490 await f.write('report_agent_progress', { runId: job.id, state: 'needs-input', summary: 'Which fixture should I use?' })
491 transport.turn.resolve({ stopReason: 'end_turn' })
492 await new Promise(setImmediate)
493 const read = await f.store.dispatch('get_task_agent_run', { taskId: task.id })
494 assert.equal(read.run.state, 'waiting-input')
495 assert.equal(read.run.threadId, sessionId)
496 const recovered = await f.write('recover_agent_run', {
497 taskId: task.id, expectedRunId: job.id, expectedRevision: read.task.revision, mode: 'queue', message: 'Use the local fixture.',
498 })
499 await f.runner.tick()
500 const resumed = f.launched[1]
501 assert.deepEqual(resumed.written.map(({ method }) => method),
502 ['initialize', 'session/resume', 'session/set_model', 'session/set_mode', 'session/prompt'])
503 assert.equal(resumed.sent('session/resume')[0].params.sessionId, sessionId)
504 assert.equal(resumed.sent('session/resume')[0].params.mcpServers[0].name, 'opentalon')
505 assert.equal(resumed.cwd, job.workingFolder)
506 assert.equal(resumed.sent('session/set_model')[0].params.modelId, flash, 'The continuation keeps the run’s model')
507 assert.match(resumed.sent('session/prompt')[0].params.prompt[0].text, /Use the local fixture/)
508 assert.equal(f.store.agentJob(recovered.run.id).threadId, sessionId)
509 await f.runner.stop(recovered.run.id)
510
511 const replay = fixture(t, {
512 initialize: () => ({ ...initialized, agentCapabilities: { loadSession: true, promptCapabilities: {} } }),
513 'session/load': async (params, entry) => {
514 await entry.message({ method: 'session/update', params: { sessionId, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'Old reply' } } } })
515 return { modes: modes(), models: models() }
516 },
517 })
518 await replay.settings()
519 const first = await replay.send('Replay')
520 first.transport.turn.resolve({ stopReason: 'end_turn' })
521 await new Promise(setImmediate)
522 await replay.write('move_task', { id: first.task.id, expectedRevision: replay.store.task(first.task.id).revision, status: 'In progress' }).catch(() => {})
523 const again = replay.store.agentJob(first.job.id)
524 replay.store.saveAgentJob({ ...again, id: randomUUID(), state: 'queued', resumeThread: true, threadId: sessionId, pickedUpAt: undefined })
525 const queued = replay.store.agentJobs().find((entry) => entry.state === 'queued')
526 replay.store.assignAgent(first.task.id, queued.id)
527 await replay.runner.tick()
528 const loaded = replay.launched[1]
529 assert.ok(loaded.sent('session/load').length === 1 && loaded.sent('session/resume').length === 0)
530 assert.equal(replay.store.agentJob(queued.id).state, 'starting', 'Replayed history is not a pickup')
531 assert.equal(replay.runner.current.lastText, '')
532 await replay.runner.stop(queued.id)
533
534 for (const [replies, pattern] of [
535 [{ 'session/resume': () => ({ sessionId: 'someone-else' }) }, /did not resume the original conversation/],
536 [{ initialize: () => ({ ...initialized, agentCapabilities: {} }) }, /cannot reopen a saved conversation/],
537 ]) {
538 const wrong = fixture(t, replies)
539 await wrong.settings()
540 const { task: other } = await wrong.write('create_task', { boardId: wrong.store.boards()[0].id, title: 'Wrong thread', status: 'In progress' })
541 const stale = wrong.store.saveAgentJob({
542 id: randomUUID(), taskId: other.id, agent: 'gemini', model: hydrogen, workingFolder: wrong.folder,
543 state: 'queued', resumeThread: true, threadId: sessionId, summary: 'Waiting', createdAt: new Date().toISOString(),
544 })
545 wrong.store.assignAgent(other.id, stale.id)
546 await wrong.runner.tick()
547 assert.equal(wrong.store.agentJob(stale.id).state, 'failed')
548 assert.match(wrong.store.agentJob(stale.id).summary, pattern)
549 assert.equal(wrong.launched[0].sent('session/prompt').length, 0)
550 }
551})
552
553test('Gemini conversations are not opened in another app', async (t) => {
554 const f = fixture(t)
555 await f.settings()
556 const { job, transport } = await f.send('Stay here')
557 transport.turn.resolve({ stopReason: 'end_turn' })
558 await new Promise(setImmediate)
559 await assert.rejects(f.runner.openThread(job.id), { code: 'THREAD_OPEN_UNSUPPORTED' })
560 assert.deepEqual(f.opened, [])
561})
562
563test('revision screenshots go to Gemini as images only when agy accepts them', () => {
564 const images = [{ data: 'AAAA', mimeType: 'image/png', name: 'shot.png' }]
565 assert.deepEqual(gemini.geminiPrompt('Fix it', images, initialized.agentCapabilities), [
566 { type: 'text', text: 'Fix it' }, { type: 'image', data: 'AAAA', mimeType: 'image/png' },
567 ])
568 assert.deepEqual(gemini.geminiPrompt('Fix it', images, {}), [{ type: 'text', text: 'Fix it' }])
569})
570
571test('Gemini settings, runs and comments survive JSON and SQLite backups', async (t) => {
572 const f = fixture(t)
573 await f.settings('manual')
574 const { job, transport } = await f.send('Back me up', { model: carbon, agent: 'gemini' })
575 transport.turn.resolve({ stopReason: 'end_turn' })
576 await new Promise(setImmediate)
577 for (const format of ['json', 'sqlite']) {
578 const backup = await f.write('create_backup', { format })
579 const inspected = await f.store.dispatch('inspect_backup', { path: backup.path })
580 assert.equal(inspected.tasks, 1)
581 const folder = fs.mkdtempSync(path.join(base, 'gemini-restore-'))
582 const target = new Store(folder)
583 t.after(() => { target.close(); fs.rmSync(folder, { recursive: true, force: true }) })
584 const preview = await target.dispatch('preview_destructive_action', { action: 'restore_backup', path: backup.path })
585 await target.dispatch('confirm_destructive_action', { token: preview.token, requestKey: randomUUID() })
586 assert.equal(target.agentSettings().defaultAgent, 'gemini')
587 assert.equal(target.agentSettings().permissionMode, 'manual')
588 const restored = target.agentJob(job.id)
589 assert.deepEqual([restored.agent, restored.model, restored.threadId], ['gemini', carbon, sessionId])
590 }
591 const exported = await f.write('create_backup', { format: 'json' })
592 const tampered = path.join(f.folder, 'tampered.json')
593 fs.writeFileSync(tampered, fs.readFileSync(exported.path, 'utf8').replace(/"defaultAgent":\s*"gemini"/, '"defaultAgent":"bard"'))
594 await assert.rejects(f.store.dispatch('inspect_backup', { path: tampered }), { code: 'INVALID_BACKUP' })
595})
596
597// The remaining tests run a real child process through the production transport.
598function fakeAgyBinary(t, script) {
599 const folder = fs.mkdtempSync(path.join(base, 'gemini-agy-'))
600 t.after(() => fs.rmSync(folder, { recursive: true, force: true }))
601 const file = path.join(folder, 'agy')
602 const log = path.join(folder, 'calls.jsonl')
603 fs.writeFileSync(file, `#!/usr/bin/env node
604const fs = require('node:fs')
605const log = (entry) => fs.appendFileSync(${JSON.stringify(log)}, JSON.stringify(entry) + '\\n')
606log({ argv: process.argv.slice(2), cwd: process.cwd(), env: Object.fromEntries(
607 ['GEMINI_API_KEY', 'AGY_ADC_AUTH', 'GOOGLE_GEMINI_BASE_URL', 'ELECTRON_RUN_AS_NODE'].map((key) => [key, process.env[key] ?? null])) })
608const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...message }) + '\\n')
609${script}
610`, { mode: 0o755 })
611 return { folder, file, calls: () => fs.readFileSync(log, 'utf8').trim().split('\n').map((line) => JSON.parse(line)) }
612}
613const acpServer = (sessionNew) => `
614const initialized = ${JSON.stringify(initialized)}
615require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => {
616 const message = JSON.parse(line)
617 log({ line: message })
618 if (message.method === 'initialize') send({ id: message.id, result: initialized })
619 else if (message.method === 'session/new') ${sessionNew}
620 else if (message.method === 'session/prompt') {
621 send({ method: 'session/update', params: { sessionId: 's-1', update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'Created VOX-001.' } } } })
622 send({ id: message.id, result: { stopReason: 'end_turn' } })
623 } else if (message.id !== undefined) send({ id: message.id, result: {} })
624})`
625const sessionReply = `send({ id: message.id, result: { sessionId: 's-1', modes: ${JSON.stringify(modes())}, models: ${JSON.stringify(models())} } })`
626const chatConfig = { command: '/safe/node', args: ['/chat-bridge.cjs'], env: { OPENTALON_MCP_CONFIG: '/chat/config.json', OPENTALON_MCP_NO_LAUNCH: '1' } }
627
628test('Ask my agent talks to a real agy process: JSON-RPC lines, model, scoped server, clean environment', async (t) => {
629 const agy = fakeAgyBinary(t, acpServer(sessionReply))
630 for (const key of gemini.unsupportedAuthEnvironment) process.env[key] = 'leak'
631 t.after(() => { for (const key of gemini.unsupportedAuthEnvironment) delete process.env[key] })
632 const reply = await askAgent('gemini', {
633 resolveExecutable: () => agy.file, home: agy.folder, workingFolder: agy.folder, config: chatConfig, model: hydrogen,
634 message: 'Add a task', history: [], project: 'Voxa', permissionMode: 'auto',
635 })
636 assert.deepEqual(reply, { text: 'Created VOX-001.' })
637 const [start, ...lines] = agy.calls()
638 assert.deepEqual(start.argv, ['acp', '--sandbox'])
639 assert.equal(start.cwd, fs.realpathSync(agy.folder))
640 assert.deepEqual(start.env, { GEMINI_API_KEY: null, AGY_ADC_AUTH: null, GOOGLE_GEMINI_BASE_URL: null, ELECTRON_RUN_AS_NODE: null })
641 const sent = lines.map(({ line }) => line)
642 assert.ok(sent.every((line) => line.jsonrpc === '2.0'))
643 assert.deepEqual(sent.map(({ method }) => method),
644 ['initialize', 'session/new', 'session/set_model', 'session/set_mode', 'session/prompt'])
645 assert.deepEqual(sent[1].params.mcpServers, [{
646 name: 'opentalon', command: '/safe/node', args: ['/chat-bridge.cjs'],
647 env: [{ name: 'OPENTALON_MCP_CONFIG', value: '/chat/config.json' }, { name: 'OPENTALON_MCP_NO_LAUNCH', value: '1' }],
648 }])
649 assert.deepEqual(sent[2].params, { sessionId: 's-1', modelId: hydrogen })
650 assert.match(sent[4].params.prompt[0].text, /"latestMessage":"Add a task"/)
651})
652
653test('Ask my agent fails closed for a signed-out agy, a missing model, a declined approval and a missing launcher', async (t) => {
654 const options = (file, extra = {}) => ({
655 resolveExecutable: () => file, home: path.dirname(file ?? base), workingFolder: path.dirname(file ?? base),
656 config: chatConfig, model: hydrogen, message: 'Hi', history: [], ...extra,
657 })
658 const signedOutAgy = fakeAgyBinary(t, acpServer(`send({ id: message.id, error: ${JSON.stringify(signedOut)} })`))
659 await assert.rejects(askAgent('gemini', options(signedOutAgy.file)), (error) =>
660 error.code === 'CHAT_AUTH_REQUIRED' && /Gemini needs you to sign in again\. Run agy in Terminal/.test(error.message))
661 assert.ok(!signedOutAgy.calls().some(({ line }) => ['authenticate', 'session/prompt'].includes(line?.method)))
662
663 const ready = fakeAgyBinary(t, acpServer(sessionReply))
664 await assert.rejects(askAgent('gemini', options(ready.file, { model: undefined })), { code: 'AGENT_MODEL_REQUIRED' })
665 await assert.rejects(askAgent('gemini', options(ready.file, { model: 'gemini-4-argon-high' })), { code: 'AGENT_MODEL_UNAVAILABLE' })
666 await assert.rejects(askAgent('gemini', options(null)), { code: 'AGENT_MISSING' })
667
668 const asks = fakeAgyBinary(t, acpServer(sessionReply).replace(
669 "send({ id: message.id, result: { stopReason: 'end_turn' } })",
670 `send({ id: 'p1', method: 'session/request_permission', params: { sessionId: 's-1', toolCall: { toolCallId: 'c1', title: 'Run rm' }, options: [{ optionId: 'y', kind: 'allow_once' }, { optionId: 'n', kind: 'reject_once' }] } })
671 pending = message.id`).replace("log({ line: message })", `log({ line: message })
672 if (message.id === 'p1') return send({ id: pending, result: { stopReason: 'end_turn' } })`).replace('const initialized', 'let pending\nconst initialized'))
673 await assert.rejects(askAgent('gemini', options(asks.file, { permissionMode: 'manual' })), { code: 'CHAT_PERMISSION_REQUIRED' })
674 const answer = asks.calls().find(({ line }) => line?.id === 'p1').line
675 assert.deepEqual(answer.result, { outcome: { outcome: 'selected', optionId: 'n' } })
676
677 const full = fakeAgyBinary(t, acpServer(sessionReply))
678 await askAgent('gemini', options(full.file, { permissionMode: 'full-access' }))
679 assert.deepEqual(full.calls()[0].argv, ['acp', '--dangerously-skip-permissions'])
680 assert.ok(!full.calls().some(({ line }) => line?.method === 'session/set_mode'))
681})
682
683test('the production transport ends a turn request when agy exits and frames requests as JSON-RPC', async (t) => {
684 const agy = fakeAgyBinary(t, `
685require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => {
686 const message = JSON.parse(line)
687 log({ line: message })
688 if (message.method === 'initialize') send({ id: message.id, result: ${JSON.stringify(initialized)} })
689 else process.exit(3)
690})`)
691 const exits = []
692 const transport = new JsonProcess(agy.file, ['acp', '--sandbox'], agy.folder, () => {}, (error) => exits.push(error.message), gemini.transportOptions)
693 assert.equal((await gemini.geminiInitialize(transport)).loadSession, true)
694 await assert.rejects(transport.request('session/prompt', { sessionId: 's-1', prompt: [] }, false, 0), /agent process ended \(exit 3\)/)
695 assert.equal(exits.length, 1)
696 assert.deepEqual(agy.calls().slice(1).map(({ line }) => [line.jsonrpc, line.method]), [['2.0', 'initialize'], ['2.0', 'session/prompt']])
697})
698
699test('Gemini drafting runs agy print mode with the named model in read-only plan mode', async (t) => {
700 const envelope = (body) => `process.stdout.write(JSON.stringify(${JSON.stringify(body)}))`
701 const draft = { title: 'Ship notes', notes: 'Write them', definitionOfDone: 'Published', project: 1, newProjectName: '', priority: 'High' }
702 const agy = fakeAgyBinary(t, envelope({ conversation_id: 'c-1', status: 'SUCCESS', response: '', structured_output: draft }))
703 process.env.GEMINI_API_KEY = 'leak'
704 t.after(() => delete process.env.GEMINI_API_KEY)
705 const options = (file, extra = {}) => ({
706 resolveExecutable: () => file, home: path.dirname(file), workingFolder: path.dirname(file), model: hydrogen,
707 projects: [{ id: 'board-1', name: 'Voxa' }], priorities: ['High', 'None'], ...extra,
708 })
709 const result = await draftTask('gemini', 'Ship the release notes for Voxa', options(agy.file, { permissionMode: 'full-access' }))
710 assert.deepEqual([result.title, result.projectId, result.priority], ['Ship notes', 'board-1', 'High'])
711 const { argv, env, cwd } = agy.calls()[0]
712 assert.equal(cwd, fs.realpathSync(agy.folder))
713 assert.equal(env.GEMINI_API_KEY, null)
714 const value = (flag) => argv[argv.indexOf(flag) + 1]
715 assert.deepEqual([value('--model'), value('--mode'), value('--output-format'), value('--print-timeout')], [hydrogen, 'plan', 'json', '40s'])
716 assert.ok(argv.includes('--sandbox') && argv.includes('--disable-slash-commands'))
717 assert.ok(!argv.includes('--dangerously-skip-permissions'), 'Drafting never needs more than read-only access')
718 assert.deepEqual(JSON.parse(value('--json-schema')).required, ['title', 'notes', 'definitionOfDone', 'project', 'newProjectName', 'priority'])
719 assert.match(value('--print'), /Ship the release notes for Voxa/)
720 assert.equal(argv.at(-2), '--print')
721
722 // The envelope and exit code agy 1.5.15 really prints when nobody is signed in.
723 const signedOutAgy = fakeAgyBinary(t, envelope(captured('print-signed-out')) + '; process.exitCode = 1')
724 await assert.rejects(draftTask('gemini', 'Idea', options(signedOutAgy.file)), { code: 'AGENT_AUTH_REQUIRED' })
725 const wrongModel = fakeAgyBinary(t, envelope({ status: 'ERROR', error: 'invalid model selection (--model gemini-4-hydrogen-high). Available models: gemini-3.8-flash-high' }) + '; process.exitCode = 1')
726 await assert.rejects(draftTask('gemini', 'Idea', options(wrongModel.file)), { code: 'DRAFT_FAILED', message: 'Gemini couldn’t draft task details.' })
727 await assert.rejects(draftTask('gemini', 'Idea', options(agy.file, { model: undefined })), { code: 'AGENT_MODEL_REQUIRED' })
728 fs.mkdirSync(path.join(agy.folder, '.agents'))
729 fs.writeFileSync(path.join(agy.folder, '.agents', 'mcp_config.json'), JSON.stringify({ mcpServers: { github: { command: 'gh-mcp' } } }))
730 await draftTask('gemini', 'Idea', options(agy.file))
731 const latest = agy.calls().at(-1)
732 assert.ok(JSON.stringify(latest).includes('mcp('))
733})