Branchwell

OpenTalon / app / native / runtime / agent-runner.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 { DatabaseSync } = require('node:sqlite')
7const { Store, FORMAT } = require('./store.cjs')
8const { AgentRunner } = require('./agent-runner.cjs')
9const base = process.env.OPENTALON_TEST_ROOT || '/Volumes/Expand/Projects/OpenTalon/native-app/tests'
10fs.mkdirSync(base, { recursive: true })
11test('stopping a queued task leaves the active task connected; late process exits are harmless', async (t) => {
12 const f = fixture(t)
13 await f.settings('codex')
14 const first = await f.task('Keep running'),
15 second = await f.task('Cancel queued')
16 await f.send(first)
17 await f.runner.tick()
18 const current = f.runner.current
19 await f.send(second)
20 const queued = f.store.agentJobs()[0]
21 await f.runner.stop(queued.id)
22 assert.equal(f.runner.current, current)
23 assert.equal(f.launched[0].closed, false)
24 const completed = f.store.agentJob(current.job.id)
25 await f.runner.finish(completed.id, 'review', 'Finished')
26 await f.launched[0].exit(new Error('Late exit'))
27 assert.equal(f.store.agentJob(completed.id).state, 'review')
28})
29function fixture(t, { projectApiUnavailable = false, nameApiUnavailable = false, projectPageSize = 100 } = {}) {
30 const folder = fs.mkdtempSync(path.join(base, 'agent-'))
31 const store = new Store(folder)
32 const launched = []
33 const opened = []
34 const projects = []
35 const runner = new AgentRunner({
36 store,
37 connector: {
38 status: () => ({ running: true }),
39 configuration: () => ({
40 mcpServers: {
41 opentalon: {
42 command: '/safe/app',
43 args: ['/bridge.cjs'],
44 env: { ELECTRON_RUN_AS_NODE: '1' },
45 },
46 },
47 }),
48 },
49 openExternal: (url) => opened.push(url),
50 resolveExecutable: (agent) => '/safe/' + agent,
51 spawnTransport(file, args, cwd, message, exit) {
52 const entry = {
53 file,
54 args,
55 cwd,
56 message,
57 exit,
58 written: [],
59 closed: false,
60 async request(method, params) {
61 entry.written.push({ method, params })
62 if (method === 'project/list') {
63 if (projectApiUnavailable)
64 throw Object.assign(new Error('Method not found'), { code: -32601 })
65 const start = Number(params.cursor ?? 0)
66 const end = start + projectPageSize
67 return { data: projects.slice(start, end), nextCursor: end < projects.length ? String(end) : null }
68 }
69 if (method === 'project/create') {
70 const project = { id: randomUUID(), roots: params.roots }
71 projects.push(project)
72 return { project }
73 }
74 if (method === 'thread/start') {
75 return { thread: { id: randomUUID(), projectId: params.projectId } }
76 }
77 if (method === 'thread/resume') return { thread: { id: params.threadId } }
78 if (method === 'thread/name/set' && nameApiUnavailable)
79 throw Object.assign(new Error('Method not found'), { code: -32601 })
80 return {}
81 },
82 write(message) {
83 entry.written.push(message)
84 },
85 close() {
86 entry.closed = true
87 },
88 }
89 launched.push(entry)
90 return entry
91 },
92 })
93 t.after(async () => {
94 await runner.close()
95 store.close()
96 fs.rmSync(folder, { recursive: true, force: true })
97 })
98 const write = (name, input) => store.dispatch(name, { ...input, requestKey: randomUUID() }, 'You · test')
99 const settings = (defaultAgent, permissionMode) =>
100 write('set_agent_settings', {
101 defaultAgent,
102 workingFolder: folder,
103 ...(permissionMode === undefined ? {} : { permissionMode }),
104 })
105 const task = (title) =>
106 write('create_task', { boardId: store.boards()[0].id, title }).then((result) => result.task)
107 const send = (task) =>
108 write('move_task', {
109 id: task.id,
110 expectedRevision: store.task(task.id).revision,
111 status: 'Sent to agent',
112 })
113 return { folder, store, runner, launched, opened, projects, write, settings, task, send }
114}
115for (const agent of ['claude-code', 'codex']) {
116 test(`${agent} closes a waiting turn and recovers the same conversation once`, async (t) => {
117 const f = fixture(t)
118 await f.settings(agent)
119 const projectFolder = path.join(f.folder, 'Project work')
120 fs.mkdirSync(projectFolder)
121 const board = f.store.boards()[0]
122 await f.write('set_project_folder', { id: board.id, expectedRevision: board.revision, workingFolder: projectFolder })
123 const task = await f.task('Recover this task')
124 await f.write('add_user_comment', { taskId: task.id, text: 'Verify the saved result.' })
125 await f.send(task)
126 await f.runner.tick()
127 const original = f.runner.current.job
128 const transport = f.launched[0]
129 assert.equal(transport.cwd, fs.realpathSync(projectFolder))
130 if (agent === 'claude-code')
131 await transport.message({ type: 'system', subtype: 'init', session_id: original.threadId })
132 else await transport.message({ method: 'turn/started' })
133 await f.write('report_agent_progress', { runId: original.id, state: 'needs-input', summary: 'Which fixture should I use?' })
134 if (agent === 'claude-code')
135 await transport.message({ type: 'result', result: 'I will wait.' })
136 else await transport.message({ method: 'turn/completed', params: { turn: { status: 'completed' } } })
137 const read = await f.store.dispatch('get_task_agent_run', { taskId: task.id })
138 assert.equal(f.runner.current, null)
139 assert(transport.closed)
140 assert.equal(read.run.state, 'waiting-input')
141 assert.equal(read.run.summary, 'Which fixture should I use?')
142 assert.equal(read.task.status, 'In progress')
143 await assert.rejects(f.write('report_agent_progress', {
144 runId: original.id, state: 'working', summary: 'The old run is closed.'
145 }), { code: 'INACTIVE_RUN' })
146 const input = {
147 taskId: task.id, expectedRunId: original.id, expectedRevision: read.task.revision,
148 requestKey: randomUUID(), mode: 'queue', message: 'Use the local fixture.',
149 }
150 await f.write('set_project_folder', { id: board.id, expectedRevision: f.store.board(board.id).revision, workingFolder: '' })
151 const [first, duplicate] = await Promise.all([
152 f.store.dispatch('recover_agent_run', input),
153 f.store.dispatch('recover_agent_run', input),
154 ])
155 assert.deepEqual(duplicate, first)
156 assert.equal(first.run.state, 'queued')
157 assert.equal(first.run.workingFolder, original.workingFolder)
158 assert.equal(first.run.threadId, read.run.threadId)
159 assert.deepEqual(first.run.commentIds, original.commentIds)
160 await assert.rejects(f.store.dispatch('recover_agent_run', { ...input, requestKey: randomUUID() }),
161 { code: 'STALE_RUN' })
162 await f.runner.tick()
163 assert.equal(f.launched.length, 2)
164 const resumed = f.launched[1]
165 assert.equal(resumed.cwd, original.workingFolder)
166 const prompt = agent === 'claude-code'
167 ? resumed.written.at(-1).message.content[0].text
168 : resumed.written.at(-1).params.input[0].text
169 assert.match(prompt, /Use the local fixture/)
170 assert.match(prompt, /Verify the saved result/)
171 assert(prompt.includes(first.run.id))
172 })
173}
174
175test('owner recovery can attach once to a reopened turn, and can explicitly reopen an archived task', async (t) => {
176 const f = fixture(t)
177 await f.settings('codex')
178 const task = await f.task('Continue from the saved chat')
179 await f.send(task)
180 await f.runner.tick()
181 const original = f.runner.current.job
182 await f.launched[0].message({ method: 'turn/started' })
183 await f.runner.finish(original.id, 'review', 'I need your input.')
184 const current = await f.store.dispatch('get_task_agent_run', { taskId: task.id })
185 const input = { taskId: task.id, expectedRevision: current.task.revision, expectedRunId: original.id, mode: 'attach' }
186 await assert.rejects(f.write('recover_agent_run', { ...input, threadId: 'other-thread' }), { code: 'THREAD_MISMATCH' })
187 const attached = await f.write('recover_agent_run', { ...input, threadId: current.run.threadId })
188 await f.runner.tick()
189 assert.equal(f.launched.length, 1)
190 assert.equal(attached.run.state, 'working')
191 assert.equal(attached.run.previousRunId, original.id)
192 await assert.rejects(f.write('report_agent_progress', {
193 runId: attached.run.id, state: 'done', summary: 'Done.'
194 }), { code: 'COMPLETION_PROOF_REQUIRED' })
195 await f.write('force_complete_task', { id: task.id })
196 await f.write('companion_organize_task', { id: task.id, destination: 'archive' })
197 const archived = await f.store.dispatch('get_task_agent_run', { taskId: task.id })
198 const queue = {
199 taskId: task.id, expectedRunId: attached.run.id, expectedRevision: archived.task.revision,
200 mode: 'queue', message: 'Please run one more check.',
201 }
202 assert.equal(archived.recovery.requiresReopen, true)
203 await assert.rejects(f.write('recover_agent_run', queue), { code: 'REOPEN_REQUIRED' })
204 const reopened = await f.write('recover_agent_run', { ...queue, reopenClosed: true })
205 assert.equal(reopened.task.status, 'In progress')
206 assert.equal(reopened.task.archivedAt, null)
207 assert.equal(f.store.agentJob(attached.run.id).state, 'canceled')
208 await f.runner.stop(reopened.run.id)
209 const canceled = await f.store.dispatch('get_task_agent_run', { taskId: task.id })
210 assert.deepEqual(canceled.recovery.actions, [])
211})
212
213test('new agent chats use the same short title and receive the full task', async (t) => {
214 const f = fixture(t)
215 const title = 'Add PulseCanvas MCP for agent-controlled music video creation'
216 const name = 'Add PulseCanvas MCP'
217 for (const agent of ['claude-code', 'codex']) {
218 await f.settings(agent)
219 await f.send(await f.task(title))
220 await f.runner.tick()
221 const { args, written } = f.launched.at(-1)
222 let prompt
223 if (agent === 'claude-code') {
224 assert.equal(args[args.indexOf('--name') + 1], name)
225 prompt = written.at(-1).message.content[0].text
226 } else {
227 assert.equal(written.at(-2).method, 'thread/name/set')
228 assert.deepEqual(written.at(-2).params, { name, threadId: f.runner.current.job.threadId })
229 assert.equal(written.at(-1).method, 'turn/start')
230 prompt = written.at(-1).params.input[0].text
231 }
232 assert.equal(prompt.split('\n')[0], name)
233 assert.ok(prompt.includes(`Title: ${title}`))
234 await f.runner.stop(f.runner.current.job.id)
235 }
236})
237test('new Codex tasks share the local project for their selected folder across launches', async (t) => {
238 const f = fixture(t, { projectPageSize: 1 })
239 f.projects.push({ id: randomUUID(), roots: [{ path: path.dirname(f.folder) }] })
240 await f.settings('codex')
241
242 async function launch(title) {
243 await f.send(await f.task(title))
244 await f.runner.tick()
245 const calls = f.launched.at(-1).written
246 const { threadId } = f.runner.current.job
247 await f.runner.stop(f.runner.current.job.id)
248 return { calls, threadId, start: calls.find(({ method }) => method === 'thread/start').params }
249 }
250
251 const first = await launch('First task in the shared project')
252 const second = await launch('Another task in the shared project')
253 assert.notEqual(first.threadId, second.threadId)
254 const creation = first.calls.find(({ method }) => method === 'project/create')
255 assert.equal(creation.params.name, 'OpenTalon')
256 assert.match(creation.params.idempotencyKey, /^opentalon:[a-f0-9]{64}$/)
257 assert.equal(second.calls.filter(({ method }) => method === 'project/list').length, 2)
258 assert.ok(!second.calls.some(({ method }) => method === 'project/create'))
259 for (const launch of [first, second]) {
260 assert.equal(launch.start.projectId, f.projects[1].id)
261 assert.equal(launch.start.cwd, fs.realpathSync(f.folder))
262 assert.deepEqual(launch.start.runtimeWorkspaceRoots, [launch.start.cwd])
263 assert.equal(launch.start.ephemeral, false)
264 }
265})
266test('older Codex launchers still start saved tasks with a short first line', async (t) => {
267 const f = fixture(t, { projectApiUnavailable: true, nameApiUnavailable: true })
268 await f.settings('codex')
269 await f.send(await f.task('Open a saved chat with an older launcher'))
270 await f.runner.tick()
271 const start = f.launched[0].written.find(({ method }) => method === 'thread/start').params
272 assert.equal(start.cwd, fs.realpathSync(f.folder))
273 assert.equal(start.ephemeral, false)
274 assert.equal(start.projectId, undefined)
275 const turn = f.launched[0].written.at(-1)
276 assert.equal(turn.method, 'turn/start')
277 assert.equal(turn.params.input[0].text.split('\n')[0], 'Open a saved chat')
278})
279test('Codex reuses an existing project through a folder alias and creates one only after a folder change', async (t) => {
280 const f = fixture(t)
281 const alias = path.join(f.folder, 'alias')
282 fs.symlinkSync(f.folder, alias)
283 const existing = { id: randomUUID(), roots: [{ path: alias }] }
284 f.projects.push(existing)
285 await f.settings('codex')
286 await f.send(await f.task('First board task'))
287 await f.runner.tick()
288 let calls = f.launched.at(-1).written
289 assert.equal(calls.find(({ method }) => method === 'thread/start').params.projectId, existing.id)
290 assert.ok(!calls.some(({ method }) => method === 'project/create'))
291 await f.runner.stop(f.runner.current.job.id)
292
293 const nextFolder = path.join(f.folder, 'Changed OpenTalon folder')
294 fs.mkdirSync(nextFolder)
295 await f.write('set_agent_settings', { defaultAgent: 'codex', workingFolder: nextFolder })
296 await f.send(await f.task('Task after an intentional folder change'))
297 await f.runner.tick()
298 calls = f.launched.at(-1).written
299 assert.equal(calls.filter(({ method }) => method === 'project/create').length, 1)
300 assert.equal(calls.find(({ method }) => method === 'project/create').params.name, 'OpenTalon')
301 assert.equal(calls.find(({ method }) => method === 'thread/start').params.cwd, nextFolder)
302})
303test('Codex project matching never probes unrelated project folders', async (t) => {
304 const cwd = '/chosen/OpenTalon'
305 const unrelated = ['/unselected/Desktop/Project', '/unselected/Documents/Project', '/Volumes/OtherDrive/Project']
306 const probes = []
307 for (const method of ['realpathSync', 'readlinkSync']) {
308 t.mock.method(fs, method, (file) => {
309 probes.push(file)
310 throw Object.assign(new Error('Folder access was not requested'), { code: 'EPERM' })
311 })
312 }
313 const runner = new AgentRunner({})
314 const requests = []
315 const transport = {
316 async request(method, input) {
317 requests.push(method)
318 assert.equal(method, 'project/list')
319 return input.cursor
320 ? { data: [{ id: 'selected', roots: [{ path: cwd }] }], nextCursor: null }
321 : { data: unrelated.map((folder, index) => ({ id: String(index), roots: [{ path: folder }] })), nextCursor: 'next' }
322 },
323 }
324 assert.equal(await runner.codexProject(transport, cwd, '/chosen/Alias'), 'selected')
325 assert.deepEqual(requests, ['project/list', 'project/list'])
326 assert.deepEqual(probes, [], 'Matching saved project metadata must not touch other folders')
327})
328test('Claude tasks from different boards use the same configured OpenTalon folder', async (t) => {
329 const f = fixture(t)
330 await f.settings('claude-code')
331 const board = (await f.write('create_board', { name: 'A different product' })).board
332 for (const boardId of [f.store.boards()[0].id, board.id]) {
333 const task = (await f.write('create_task', { boardId, title: 'Use the shared workspace' })).task
334 await f.send(task)
335 await f.runner.tick()
336 assert.equal(f.launched.at(-1).cwd, fs.realpathSync(f.folder))
337 await f.runner.stop(f.runner.current.job.id)
338 }
339 assert.equal(f.launched.length, 2)
340})
341test('mobile sends use the Mac working folder for either agent and cannot supply a different cwd', async (t) => {
342 const f = fixture(t)
343 for (const agent of ['codex', 'claude-code']) {
344 await f.settings(agent)
345 const task = await f.task(`Mobile request for ${agent}`)
346 await f.write('companion_set_task_field', {
347 id: task.id, field: 'status', expectedValue: 'To do', value: 'Sent to agent', agent,
348 })
349 const job = f.store.agentJobs()[0]
350 assert.equal(job.workingFolder, f.folder)
351 await f.runner.tick()
352 assert.equal(f.launched.at(-1).cwd, fs.realpathSync(f.folder))
353 await f.runner.stop(f.runner.current.job.id)
354 }
355})
356test('explicit models are bound to the chosen agent and passed to both runtimes', async (t) => {
357 const f = fixture(t)
358 await f.settings('codex')
359 const claudeTask = await f.task('Use a chosen Claude model')
360 const move = { id: claudeTask.id, expectedRevision: claudeTask.revision, status: 'Sent to agent' }
361 await assert.rejects(f.write('move_task', { ...move, agent: 'codex', model: 'claude-fable-5-2' }), {
362 code: 'INVALID_ARGUMENT',
363 })
364 assert.equal(f.store.task(claudeTask.id).status, 'To do')
365 await f.write('move_task', { ...move, agent: 'claude-code', model: 'claude-fable-5-2' })
366 assert.equal(f.store.agentJobs()[0].model, 'claude-fable-5-2')
367 await f.runner.tick()
368 const args = f.launched[0].args
369 assert.equal(args[args.indexOf('--model') + 1], 'claude-fable-5-2')
370 await f.runner.finish(f.store.agentJobs()[0].id, 'review', 'Finished')
371
372 await f.write('create_task', {
373 boardId: f.store.boards()[0].id,
374 title: 'Use a chosen Codex model',
375 status: 'Sent to agent',
376 agent: 'codex',
377 model: 'gpt-6.2-sol',
378 })
379 assert.equal(f.store.agentJobs()[0].model, 'gpt-6.2-sol')
380 await f.runner.tick()
381 assert.equal(f.launched[1].written.find(({ method }) => method === 'turn/start').params.model, 'gpt-6.2-sol')
382})
383test('dispatch saves the initial comment once and passes it to the chosen agent', async (t) => {
384 const f = fixture(t)
385 assert.equal(f.store.agentSettings().defaultAgent, 'codex')
386 await f.settings('codex')
387 const task = await f.task('Review the sync screenshots')
388 const input = {
389 id: task.id,
390 expectedRevision: task.revision,
391 status: 'Sent to agent',
392 agent: 'claude-code',
393 model: 'claude-sonnet-5-5',
394 dispatchComment: 'Compare timestamps on both devices.',
395 requestKey: randomUUID(),
396 }
397 await assert.rejects(f.store.dispatch('move_task', { ...input, status: 'In progress' }), {
398 code: 'INVALID_ARGUMENT',
399 })
400 assert.equal(f.store.comments(task.id).length, 0)
401 const sent = await f.store.dispatch('move_task', input, 'You · test')
402 assert.deepEqual(await f.store.dispatch('move_task', input, 'You · test'), sent)
403 assert.equal(f.store.comments(task.id).length, 1)
404 assert.equal(f.store.agentJobs().length, 1)
405 await f.runner.tick()
406 const claude = f.launched[0]
407 assert.ok(!claude.args.includes('--no-session-persistence'))
408 const message = claude.written.find(({ type }) => type === 'user')
409 assert.ok(message.message.content[0].text.includes(input.dispatchComment))
410 const firstJob = f.store.agentJobs()[0]
411 assert.equal(f.store.comments(task.id)[0].delivery, 'queued')
412 await claude.message({ type: 'system', subtype: 'init', session_id: firstJob.threadId })
413 assert.equal(f.store.comments(task.id)[0].pickedUpAt, f.store.agentJob(firstJob.id).pickedUpAt)
414 assert.equal(f.store.task(task.id).status, 'In progress')
415 await f.runner.finish(f.store.agentJobs()[0].id, 'review', 'Finished')
416
417 const created = await f.write('create_task', {
418 boardId: f.store.boards()[0].id,
419 title: 'Check the date picker',
420 status: 'Sent to agent',
421 dispatchComment: 'Check the unset date as well.',
422 })
423 assert.equal(f.store.comments(created.task.id)[0].text, 'Check the unset date as well.')
424 await f.runner.tick()
425 const codex = f.launched[1]
426 assert.equal(codex.written.find(({ method }) => method === 'thread/start').params.ephemeral, false)
427 assert.ok(codex.written.find(({ method }) => method === 'turn/start').params.input[0].text.includes('Check the unset date as well.'))
428})
429test('To do, In progress and Done are manual by default; only Sent to agent opts in', async (t) => {
430 const f = fixture(t)
431 for (const status of ['To do', 'In progress', 'Done']) {
432 let task = (
433 await f.write('create_task', {
434 boardId: f.store.boards()[0].id,
435 title: `Manual ${status}`,
436 status,
437 })
438 ).task
439 assert.equal(f.store.assignedRun(task.id), null)
440 for (const next of ['In progress', 'Done', 'To do']) {
441 task = (
442 await f.write('move_task', { id: task.id, expectedRevision: task.revision, status: next })
443 ).task
444 assert.equal(f.store.assignedRun(task.id), null)
445 }
446 await f.write('add_user_comment', {
447 taskId: task.id,
448 text: 'A note for myself.',
449 notifyAgent: true,
450 })
451 }
452 await f.settings('codex')
453 await f.store.queueCommentFollowups()
454 await f.runner.tick()
455 assert.equal(f.launched.length, 0)
456 assert.equal(f.store.agentJobs().length, 0)
457 const task = await f.task('Agent help only when I request it')
458 await f.send(task)
459 const job = f.store.agentJobs()[0]
460 assert.equal(f.store.assignedRun(task.id), job.id)
461 await f.runner.tick()
462 await f.launched[0].message({ method: 'turn/started', params: { threadId: job.threadId } })
463 assert.equal(f.store.task(task.id).status, 'In progress')
464 assert.equal(f.store.assignedRun(task.id), job.id)
465 const saved = f.store.task(task.id)
466 await f.write('move_task', { id: task.id, expectedRevision: saved.revision, status: 'To do' })
467 await f.write('move_task', {
468 id: task.id,
469 expectedRevision: f.store.task(task.id).revision,
470 status: 'In progress',
471 })
472 assert.equal(f.store.assignedRun(task.id), null)
473 await assert.rejects(
474 f.write('report_agent_progress', {
475 runId: job.id,
476 state: 'done',
477 summary: 'Stale agent update',
478 }),
479 { code: 'TASK_MANUAL' }
480 )
481 await f.runner.tick()
482 assert.equal(f.launched[0].closed, true)
483 assert.equal(f.store.task(task.id).status, 'In progress')
484 await f.write('add_user_comment', {
485 taskId: task.id,
486 text: 'Still a manual task.',
487 notifyAgent: true,
488 })
489 assert.equal((await f.store.queueCommentFollowups()).queued, 0)
490})
491for (const agent of ['claude-code', 'codex']) {
492 test(`${agent} pickup moves the task automatically and ignores duplicate or stale start events`, async (t) => {
493 const f = fixture(t)
494 await f.settings(agent)
495 const task = await f.task('Automatic pickup')
496 const existing = (
497 await f.write('create_task', {
498 boardId: task.boardId,
499 title: 'Already in progress',
500 status: 'In progress',
501 })
502 ).task
503 await f.send(task)
504 await f.runner.tick()
505 assert.equal(f.store.task(task.id).status, 'Sent to agent', 'Launching alone is not pickup')
506 const job = f.store.agentJobs()[0]
507 const pickup =
508 agent === 'claude-code'
509 ? { type: 'system', subtype: 'init', session_id: job.threadId }
510 : {
511 method: 'turn/started',
512 params: { threadId: job.threadId, turn: { id: 'test-turn', status: 'inProgress' } },
513 }
514 await f.launched[0].message(pickup)
515 const saved = f.store.task(task.id)
516 assert.equal(saved.status, 'In progress', 'No MCP progress report is needed')
517 assert.equal(saved.position, existing.position + 1)
518 assert.equal(f.store.agentJob(job.id).state, 'working')
519 assert.equal(saved.revision, f.store.revision(), 'Task and run commit together')
520 const revision = f.store.revision()
521 await f.launched[0].message(pickup)
522 assert.equal(
523 f.store.revision(),
524 revision,
525 'Duplicate start must not reorder or revise the task'
526 )
527 await f.write('move_task', { id: task.id, expectedRevision: saved.revision, status: 'To do' })
528 await f.launched[0].message(pickup)
529 assert.equal(f.store.task(task.id).status, 'To do', 'A late event cannot undo a user move')
530 await f.runner.stop(job.id)
531 await f.store.updateAgentJob(job.id, { state: 'working' }, { pickedUp: true })
532 assert.equal(f.store.agentJob(job.id).state, 'canceled')
533 })
534}
535test('both defaults route correctly, persist per run, launch once and keep In progress', async (t) => {
536 const f = fixture(t)
537 const task = await f.task('First Claude task')
538 await assert.rejects(f.send(task), { code: 'AGENT_SETUP_REQUIRED' })
539 assert.equal(f.store.task(task.id).status, 'To do')
540 await f.settings('claude-code')
541 const request = {
542 id: task.id,
543 expectedRevision: task.revision,
544 status: 'Sent to agent',
545 requestKey: randomUUID(),
546 }
547 await f.store.dispatch('move_task', request)
548 await f.store.dispatch('move_task', request)
549 assert.equal(f.store.agentJobs().length, 1)
550 await f.runner.tick()
551 await f.runner.tick()
552 assert.equal(f.launched.length, 1)
553 assert.equal(f.launched[0].file, '/safe/claude-code')
554 assert.ok(f.launched[0].args.includes('--session-id'))
555 assert.ok(!f.launched[0].args.some((arg) => /dangerously|bypassPermissions/.test(arg)))
556 await f.settings('codex')
557 assert.equal(f.store.agentJobs()[0].agent, 'claude-code')
558 const firstJob = f.store.agentJobs()[0]
559 await f.write('report_agent_progress', {
560 runId: firstJob.id,
561 state: 'working',
562 summary: 'Started',
563 })
564 assert.equal(f.store.task(task.id).status, 'In progress')
565 await f.launched[0].message({ type: 'result', is_error: false, result: 'I have a question.' })
566 assert.equal(f.store.agentJob(firstJob.id).state, 'review')
567 assert.equal(
568 f.store.task(task.id).status,
569 'In progress',
570 'A successful turn does not mark a task done'
571 )
572 const second = await f.task('Next Codex task')
573 await f.send(second)
574 await f.runner.tick()
575 assert.equal(f.launched.length, 2)
576 assert.equal(f.launched[1].file, '/safe/codex')
577 assert.equal(f.launched[1].written[1].method, 'initialized')
578 assert.ok(f.launched[1].written.some(({ method }) => method === 'thread/start'))
579 assert.equal(f.launched[1].written.at(-1).method, 'turn/start')
580 const secondJob = f.store.agentJobs()[0]
581 await f.write('report_agent_progress', {
582 runId: secondJob.id,
583 state: 'done',
584 summary: 'Completed and verified.',
585 proof:
586 'The disposable task was read through MCP and its requested outcome was verified in the test fixture.',
587 definitionOfDoneMet: true,
588 })
589 assert.equal(f.store.task(second.id).status, 'Done')
590 await f.launched[1].message({
591 method: 'turn/completed',
592 params: { turn: { status: 'completed' } },
593 })
594 assert.equal(f.store.agentJob(secondJob.id).state, 'done')
595 await f.runner.openThread(secondJob.id)
596 assert.equal(f.opened[0], `codex://threads/${secondJob.threadId}`)
597 assert.deepEqual(f.store.agentSettings(), {
598 defaultAgent: 'codex', workingFolder: f.folder, permissionMode: 'auto',
599 })
600})
601test('the saved permission mode controls future Claude and Codex launches', async (t) => {
602 const f = fixture(t)
603 for (const [mode, claudeMode, reviewer, policy, sandbox] of [
604 [undefined, 'auto', 'auto_review', 'on-request', 'workspace-write'],
605 ['auto', 'auto', 'auto_review', 'on-request', 'workspace-write'],
606 ['manual', 'manual', 'user', 'on-request', 'workspace-write'],
607 ['full-access', 'bypassPermissions', 'user', 'never', 'danger-full-access'],
608 ]) {
609 await f.settings('claude-code', mode)
610 await f.send(await f.task('Claude permissions'))
611 await f.runner.tick()
612 const claude = f.launched.at(-1)
613 assert.equal(claude.args[claude.args.indexOf('--permission-mode') + 1], claudeMode)
614 await f.runner.stop(f.runner.current.job.id)
615
616 await f.settings('codex')
617 await f.send(await f.task('Codex permissions'))
618 await f.runner.tick()
619 const codex = f.launched.at(-1).written.find((message) => message.method === 'thread/start')
620 assert.equal(codex.params.approvalsReviewer, reviewer)
621 assert.equal(codex.params.approvalPolicy, policy)
622 assert.equal(codex.params.sandbox, sandbox)
623 await f.runner.stop(f.runner.current.job.id)
624 }
625})
626test('Claude opens the saved session through Desktop after the run stops', async (t) => {
627 const f = fixture(t)
628 await f.settings('claude-code')
629 await f.send(await f.task('Conversation handoff'))
630 await f.runner.tick()
631 const job = f.runner.current.job
632 await assert.rejects(f.runner.openThread(job.id), { code: 'RUNNING_THREAD' })
633 await f.runner.stop(job.id)
634
635 const launcher = path.join(f.folder, 'claude')
636 const requireTerminal = process.platform === 'darwin' ? '[ -t 1 ] || exit 47\n' : ''
637 fs.writeFileSync(launcher, '#!/bin/sh\n' + requireTerminal + 'printf "%s\\n" "$PWD" "$@" > handoff.log\n', { mode: 0o700 })
638 f.runner.resolveExecutable = () => launcher
639 assert.deepEqual(await f.runner.openThread(job.id), { opened: true })
640 const args = fs.readFileSync(path.join(f.folder, 'handoff.log'), 'utf8').trimEnd().split('\n')
641 assert.deepEqual(args, [fs.realpathSync(f.folder), '--desktop', '--resume', job.threadId])
642
643 fs.writeFileSync(launcher, '#!/bin/sh\nexit 47\n')
644 await assert.rejects(f.runner.openThread(job.id), {
645 code: 'THREAD_OPEN_FAILED',
646 message: 'Claude Desktop could not open this conversation. Open the Claude CLI in the original working folder and paste /resume ' + job.threadId,
647 })
648
649 fs.writeFileSync(launcher, "#!/bin/sh\necho 'Session is open in another terminal. Run /desktop there instead.'\nexit 1\n")
650 await assert.rejects(f.runner.openThread(job.id), { code: 'THREAD_IN_USE' })
651})
652test('approval requests retain their scope, concurrent prompts and declines; canceled jobs ignore callbacks', async (t) => {
653 const f = fixture(t)
654 await f.settings('claude-code')
655 const task = await f.task('Permission test')
656 await f.send(task)
657 await f.runner.tick()
658 const job = f.store.agentJobs()[0],
659 transport = f.launched[0]
660 const permission = (id, input) =>
661 transport.message({
662 type: 'control_request',
663 request_id: id,
664 request: { subtype: 'can_use_tool', tool_name: 'Bash', input },
665 })
666 await permission('first', { command: 'echo one' })
667 await permission('second', { command: 'echo two' })
668 assert.equal(f.store.agentJob(job.id).approval.id, 'first')
669 await f.runner.answer(job.id, 'first', false)
670 assert.equal(transport.written.at(-1).response.response.behavior, 'deny')
671 assert.equal(f.store.agentJob(job.id).approval.id, 'second')
672 await f.runner.answer(job.id, 'second', true)
673 assert.deepEqual(transport.written.at(-1).response.response.updatedInput, { command: 'echo two' })
674 assert.equal(f.store.agentJob(job.id).approval, null)
675 await transport.message({
676 type: 'control_request',
677 request_id: 'own',
678 request: {
679 subtype: 'can_use_tool',
680 tool_name: 'mcp__opentalon__report_agent_progress',
681 input: { runId: job.id, state: 'working', summary: 'ok' },
682 },
683 })
684 assert.equal(transport.written.at(-1).response.response.behavior, 'allow')
685 for (const tool of ['list_task_activity','add_task_activity']) {
686 await transport.message({type:'control_request',request_id:tool,request:{subtype:'can_use_tool',tool_name:'mcp__opentalon__'+tool,input:{taskId:task.id,text:'Progress'}}})
687 assert.equal(transport.written.at(-1).response.response.behavior,'allow')
688 }
689 await transport.message({type:'control_request',request_id:'foreign-activity',request:{subtype:'can_use_tool',tool_name:'mcp__opentalon__add_task_activity',input:{taskId:'another-task',text:'Wrong task'}}})
690 assert.equal(f.store.agentJob(job.id).approval.id,'foreign-activity')
691 await f.runner.answer(job.id,'foreign-activity',false)
692 await transport.message({
693 type: 'control_request',
694 request_id: 'other',
695 request: {
696 subtype: 'can_use_tool',
697 tool_name: 'mcp__opentalon__report_agent_progress',
698 input: { runId: 'other' },
699 },
700 })
701 assert.equal(f.store.agentJob(job.id).state, 'needs-input')
702 await f.runner.stop(job.id)
703 await transport.exit(new Error('Stopped'))
704 assert.equal(f.store.agentJob(job.id).state, 'canceled')
705 await assert.rejects(
706 f.write('report_agent_progress', { runId: job.id, state: 'done', summary: 'Too late' }),
707 { code: 'INACTIVE_RUN' }
708 )
709})
710test('queued moves cancel, restarts never replay uncertain work and restored jobs do not run', async (t) => {
711 const f = fixture(t)
712 await f.settings('codex')
713 const task = await f.task('Persistent queue')
714 await f.send(task)
715 let saved = f.store.task(task.id)
716 await f.write('move_task', { id: task.id, expectedRevision: saved.revision, status: 'To do' })
717 assert.equal(f.store.agentJobs()[0].state, 'canceled')
718 await f.send(task)
719 const job = f.store.agentJobs()[0]
720 await f.store.updateAgentJob(job.id, { state: 'starting', threadId: randomUUID() })
721 await f.runner.start()
722 assert.equal(f.store.agentJob(job.id).state, 'interrupted')
723 assert.equal(f.launched.length, 0)
724 saved = f.store.task(task.id)
725 assert.equal(saved.status, 'To do')
726 await f.write('move_task', {
727 id: task.id,
728 expectedRevision: saved.revision,
729 status: 'Sent to agent',
730 })
731 const retry = f.store.agentJobs()[0]
732 saved = f.store.task(task.id)
733 await f.write('move_task', { id: task.id, expectedRevision: saved.revision, status: 'Sent to agent' })
734 assert.equal(f.store.agentJobs().length, 3, 'Only the explicit resend creates a run')
735 for (const format of ['json', 'sqlite']) {
736 const backup = await f.write('create_backup', { format })
737 const preview = await f.store.dispatch('preview_destructive_action', {
738 action: 'restore_backup',
739 path: backup.path,
740 })
741 await f.write('confirm_destructive_action', { token: preview.token })
742 assert.equal(f.store.agentJob(retry.id).state, 'interrupted')
743 await f.runner.tick()
744 assert.equal(f.launched.length, 0)
745 assert.equal(f.store.task(task.id).status, 'To do')
746 }
747})
748test('completion requires proof and definition of done confirmation; report is atomic and idempotent', async (t) => {
749 const f = fixture(t)
750 await f.settings('codex')
751 const task = (
752 await f.write('create_task', {
753 boardId: f.store.boards()[0].id,
754 title: 'Deliver a reviewed document',
755 definitionOfDone: 'Save the document and verify that it opens with the requested content.',
756 priority: 'High',
757 })
758 ).task
759 await f.send(task)
760 await f.runner.tick()
761 const job = f.store.agentJobs()[0]
762 await f.write('report_agent_progress', {
763 runId: job.id,
764 state: 'working',
765 summary: 'Reading requirements',
766 })
767 for (const input of [
768 {},
769 { proof: 'Done', definitionOfDoneMet: true },
770 { proof: 'Saved the document and opened it for review.', definitionOfDoneMet: false },
771 ]) {
772 await assert.rejects(
773 f.write('report_agent_progress', {
774 runId: job.id,
775 state: 'done',
776 summary: 'Finished',
777 ...input,
778 }),
779 { code: 'COMPLETION_PROOF_REQUIRED' }
780 )
781 assert.equal(f.store.task(task.id).status, 'In progress')
782 assert.equal(f.store.comments(task.id).length, 0)
783 }
784 for (const name of ['move_task', 'update_task'])
785 await assert.rejects(
786 f.write(name, {
787 id: task.id,
788 expectedRevision: f.store.task(task.id).revision,
789 status: 'Done',
790 }),
791 { code: 'COMPLETION_PROOF_REQUIRED' }
792 )
793 const input = {
794 runId: job.id,
795 state: 'done',
796 summary: 'Document ready.',
797 proof:
798 'Saved /test/output.md, reopened it, and checked all requested sections against the definition of done.',
799 definitionOfDoneMet: true,
800 requestKey: randomUUID(),
801 }
802 const result = await f.store.dispatch('report_agent_progress', input)
803 assert.deepEqual(await f.store.dispatch('report_agent_progress', input), result)
804 assert.equal(f.store.task(task.id).status, 'Done')
805 assert.equal(f.store.comments(task.id).length, 0)
806 assert.match(result.completionReport.text, /Save the document and verify/)
807 assert.match(result.completionReport.text, /\/test\/output.md/)
808 assert.equal(result.completionReport.agent, 'codex')
809 assert.equal(result.completionReport.kind, 'agent')
810 assert.equal(f.store.task(task.id).commentCount, 0)
811 const backup = await f.write('create_backup', { format: 'json' })
812 assert.ok((await f.store.inspect(backup.path)).activity.some(row=>row.detail.includes('Proof and verification')))
813})
814
815test('failed starts recover and explicit local completion survives late pickup', async (t) => {
816 const f = fixture(t)
817 await f.settings('codex')
818 const task = await f.task('Recover from a failed agent launch')
819 await f.send(task)
820 await f.runner.tick()
821 let run = f.store.agentJobs()[0]
822 await f.runner.finish(run.id, 'failed', 'The agent did not respond.')
823 assert.equal(f.store.task(task.id).status, 'To do')
824 assert.equal(f.store.agentJob(run.id).state, 'failed')
825
826 await f.send(task)
827 await f.runner.tick()
828 run = f.store.agentJobs()[0]
829 await f.write('force_complete_task', { id: task.id })
830 assert.equal(f.store.task(task.id).status, 'Done')
831 assert.equal(f.store.assignedRun(task.id), null)
832 assert.equal(f.store.agentJob(run.id).state, 'canceled')
833 await f.store.updateAgentJob(run.id, { state: 'working' }, { pickedUp: true })
834 assert.equal(f.store.task(task.id).status, 'Done')
835 await f.runner.tick()
836 assert.equal(f.launched.at(-1).closed, true)
837})
838test('v1 database migration preserves records and v1 JSON/SQLite backups remain importable', async (t) => {
839 const f = fixture(t)
840 await f.task('Original data')
841 const jsonBackup = await f.write('create_backup', { format: 'json' })
842 const legacy = JSON.parse(fs.readFileSync(jsonBackup.path, 'utf8'))
843 legacy.formatVersion = 1
844 legacy.columns = ['To do', 'In progress', 'Done']
845 delete legacy.agentSettings
846 delete legacy.agentRuns
847 const json = path.join(f.folder, 'legacy.json')
848 fs.writeFileSync(json, JSON.stringify(legacy))
849 assert.equal((await f.store.inspect(json)).summary.tasks, 1)
850 const sqlite = await f.write('create_backup', {})
851 const db = new DatabaseSync(sqlite.path)
852 db.exec(
853 'DROP TRIGGER tasks_record_completion_on_insert; DROP TRIGGER tasks_record_completion_on_move; DROP TABLE activity_images; DROP TABLE task_activity; DROP TABLE task_history; DROP TABLE task_files; ALTER TABLE tasks DROP COLUMN issue_type; ALTER TABLE tasks DROP COLUMN plan_markdown; ALTER TABLE tasks DROP COLUMN completed_at; ALTER TABLE tasks DROP COLUMN archived_at; DROP INDEX tasks_task_key; DROP INDEX boards_project_key; ALTER TABLE tasks DROP COLUMN task_key; ALTER TABLE boards DROP COLUMN project_key; ALTER TABLE boards DROP COLUMN next_task_number; ALTER TABLE tasks DROP COLUMN due_date; ALTER TABLE tasks DROP COLUMN priority; ALTER TABLE tasks DROP COLUMN definition_of_done; DROP TABLE comment_images; DROP TABLE task_comments; DROP TABLE agent_jobs; DELETE FROM schema_migrations WHERE version>=2; PRAGMA user_version=1;'
854 )
855 db.close()
856 assert.equal((await f.store.inspect(sqlite.path)).summary.tasks, 1)
857 const folder = path.join(f.folder, 'legacy-profile')
858 fs.mkdirSync(folder)
859 fs.copyFileSync(sqlite.path, path.join(folder, 'opentalon.sqlite'))
860 const migrated = new Store(folder)
861 try {
862 assert.equal(migrated.snapshot().tasks[0].title, 'Original data')
863 assert.equal(migrated.db.prepare('PRAGMA user_version').get().user_version, FORMAT)
864 assert.deepEqual(migrated.db.prepare('PRAGMA foreign_key_check').all(), [])
865 } finally {
866 migrated.close()
867 }
868})