OpenTalon / app · opentalon.ai / native / runtime / revision-withdrawal.test.cjs
| 1 | const test = require('node:test') |
| 2 | const assert = require('node:assert/strict') |
| 3 | const fs = require('node:fs') |
| 4 | const path = require('node:path') |
| 5 | const os = require('node:os') |
| 6 | const readline = require('node:readline') |
| 7 | const { randomUUID } = require('node:crypto') |
| 8 | const { spawn } = require('node:child_process') |
| 9 | const { once } = require('node:events') |
| 10 | const { Store } = require('./store.cjs') |
| 11 | const { AgentRunner } = require('./agent-runner.cjs') |
| 12 | const { Connector } = require('./mcp.cjs') |
| 13 | const { tools } = require('./contracts.cjs') |
| 14 | |
| 15 | const base = process.env.OPENTALON_TEST_ROOT || '/Volumes/Expand/Projects/OpenTalon/native-app/tests' |
| 16 | fs.mkdirSync(base, { recursive: true }) |
| 17 | const image = { |
| 18 | name: 'Screenshot.png', |
| 19 | mimeType: 'image/png', |
| 20 | data: fs.readFileSync(path.resolve(__dirname, '../assets/opentalon-logo-1024.png')).toString('base64'), |
| 21 | } |
| 22 | |
| 23 | // The store, runner and withdrawal handler are wired the way the native service wires them. |
| 24 | function fixture(t) { |
| 25 | const folder = fs.mkdtempSync(path.join(base, 'withdraw-')) |
| 26 | const store = new Store(folder) |
| 27 | const launched = [] |
| 28 | const runner = new AgentRunner({ |
| 29 | store, |
| 30 | connector: { |
| 31 | status: () => ({ enabled: true, running: true }), |
| 32 | configuration: () => ({ mcpServers: { opentalon: { command: '/app', args: [], env: {} } } }), |
| 33 | }, |
| 34 | openExternal: () => {}, |
| 35 | resolveExecutable: (agent) => '/safe/' + agent, |
| 36 | spawnTransport(file, args, cwd, message, exit) { |
| 37 | const entry = { |
| 38 | file, args, message, exit, written: [], closed: false, hold: null, |
| 39 | async request(method, params) { |
| 40 | entry.written.push({ method, params }) |
| 41 | if (entry.hold?.method === method) await entry.hold.until |
| 42 | if (method === 'thread/start') return { thread: { id: randomUUID() } } |
| 43 | if (method === 'thread/resume') return { thread: { id: params.threadId } } |
| 44 | if (method === 'turn/start') return { turn: { id: 'turn-1' } } |
| 45 | return {} |
| 46 | }, |
| 47 | write: (value) => entry.written.push(value), |
| 48 | close() { entry.closed = true }, |
| 49 | } |
| 50 | launched.push(entry) |
| 51 | return entry |
| 52 | }, |
| 53 | }) |
| 54 | runner.interruptTimeout = 40 |
| 55 | const cleanup = [] |
| 56 | t.after(async () => { |
| 57 | for (const close of cleanup.reverse()) await close() |
| 58 | await runner.close() |
| 59 | store.close() |
| 60 | fs.rmSync(folder, { recursive: true, force: true }) |
| 61 | }) |
| 62 | const write = (name, input, origin = 'You · mobile') => |
| 63 | store.dispatch(name, { requestKey: randomUUID(), ...input }, origin) |
| 64 | const task = (title, status = 'In progress') => |
| 65 | write('create_task', { boardId: store.boards()[0].id, title, status }).then((result) => result.task) |
| 66 | const previous = (task, agent = 'claude-code', state = 'review') => { |
| 67 | const job = store.saveAgentJob({ |
| 68 | id: randomUUID(), taskId: task.id, agent, workingFolder: folder, threadId: randomUUID(), |
| 69 | state, summary: 'First response', createdAt: new Date().toISOString(), |
| 70 | }) |
| 71 | store.assignAgent(task.id, job.id) |
| 72 | return job |
| 73 | } |
| 74 | const comment = (task, text, extra = {}) => |
| 75 | write('add_user_comment', { taskId: task.id, text, notifyAgent: true, ...extra }).then((result) => result.comment) |
| 76 | // Mirrors native/service.cjs: the store decides, then only the named turn is ended. |
| 77 | const withdraw = async (task, id, extra = {}) => { |
| 78 | const result = await write('withdraw_revision_request', { taskId: task.id, id, ...extra }) |
| 79 | if (result.run?.stop) await runner.stopWithdrawnTurn(result.run.id) |
| 80 | else if (result.run?.notify) await runner.notifyWithdrawal(result.run.id, result.run.notify) |
| 81 | return result |
| 82 | } |
| 83 | const texts = (taskId) => store.comments(taskId).map(({ text }) => text) |
| 84 | const turnText = (entry) => { |
| 85 | const claude = entry.written.find(({ type }) => type === 'user') |
| 86 | const codex = entry.written.find(({ method }) => method === 'turn/start') |
| 87 | return claude ? claude.message.content[0].text : codex?.params.input[0].text |
| 88 | } |
| 89 | return { folder, store, runner, launched, cleanup, write, task, previous, comment, withdraw, texts, turnText } |
| 90 | } |
| 91 | |
| 92 | test('withdrawal is a private native action and is never offered to connected agents', async (t) => { |
| 93 | const f = fixture(t) |
| 94 | assert.ok(!tools.some(({ name }) => name === 'withdraw_revision_request')) |
| 95 | const task = await f.task('Private action') |
| 96 | const saved = await f.comment(task, 'Only the user can withdraw this.') |
| 97 | const connector = new Connector({ folder: f.folder, call: (name, args) => f.store.dispatch(name, args) }) |
| 98 | await connector.enable(true) |
| 99 | f.cleanup.push(() => connector.stop()) |
| 100 | const response = await fetch(connector.status().endpoint, { |
| 101 | method: 'POST', |
| 102 | headers: { Authorization: `Bearer ${connector.config.token}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' }, |
| 103 | body: JSON.stringify({ |
| 104 | jsonrpc: '2.0', id: 1, method: 'tools/call', |
| 105 | params: { name: 'withdraw_revision_request', arguments: { taskId: task.id, id: saved.id, requestKey: randomUUID() } }, |
| 106 | }), |
| 107 | }) |
| 108 | const reply = await response.json() |
| 109 | assert.equal(reply.result.isError, true, 'An agent must not be able to withdraw the user’s request') |
| 110 | assert.equal(reply.result.structuredContent.code, 'UNKNOWN_ACTION') |
| 111 | assert.deepEqual(f.texts(task.id), ['Only the user can withdraw this.']) |
| 112 | }) |
| 113 | |
| 114 | test('a saved request is withdrawn once, recorded in Activity, and leaves its neighbours untouched', async (t) => { |
| 115 | const f = fixture(t) |
| 116 | const task = await f.task('Manual task') |
| 117 | const keep = await f.comment(task, 'Keep this request.', { images: [image] }) |
| 118 | const drop = await f.comment(task, 'Withdraw this request.', { images: [image] }) |
| 119 | assert.equal(drop.delivery, 'local') |
| 120 | const input = { taskId: task.id, id: drop.id, requestKey: randomUUID() } |
| 121 | const first = await f.store.dispatch('withdraw_revision_request', input, 'You · mobile') |
| 122 | assert.deepEqual(await f.store.dispatch('withdraw_revision_request', input, 'You · mobile'), first, 'A retried request replays its receipt') |
| 123 | assert.equal(first.withdrawn, true) |
| 124 | assert.equal(first.run, undefined) |
| 125 | assert.deepEqual(f.texts(task.id), ['Keep this request.']) |
| 126 | assert.equal(f.store.task(task.id).commentCount, 1) |
| 127 | assert.equal(f.store.commentImage(keep.images[0].id).data, image.data) |
| 128 | assert.throws(() => f.store.commentImage(drop.images[0].id), { code: 'NOT_FOUND' }) |
| 129 | const activity = await f.store.dispatch('list_task_activity', { taskId: task.id }) |
| 130 | const entry = activity.entries.find(({ summary }) => summary === 'Withdrew a revision request') |
| 131 | assert.equal(entry.actor, 'You · mobile') |
| 132 | assert.equal(entry.detail, 'Withdraw this request.') |
| 133 | assert.equal(activity.entries.filter(({ summary }) => summary === 'Withdrew a revision request').length, 1) |
| 134 | // A second, separate withdrawal of the same request is harmless. |
| 135 | assert.equal((await f.withdraw(task, drop.id)).withdrawn, true) |
| 136 | assert.deepEqual(f.texts(task.id), ['Keep this request.']) |
| 137 | }) |
| 138 | |
| 139 | test('a request can only be withdrawn from its own task, and only if the user wrote it', async (t) => { |
| 140 | const f = fixture(t) |
| 141 | const mine = await f.task('Owning task') |
| 142 | const other = await f.task('Another task') |
| 143 | const saved = await f.comment(mine, 'Belongs to the owning task.') |
| 144 | await assert.rejects(f.withdraw(other, saved.id), { code: 'NOT_FOUND' }) |
| 145 | await assert.rejects(f.withdraw({ id: randomUUID() }, saved.id), { code: 'NOT_FOUND' }) |
| 146 | await assert.rejects(f.withdraw(mine, 'not-a-revision-id'), { code: 'NOT_FOUND' }) |
| 147 | f.store.db.prepare('INSERT INTO task_comments VALUES (?,?,?)').run('legacy-1', mine.id, |
| 148 | JSON.stringify({ text: 'Earlier agent message', source: 'legacy', createdAt: new Date().toISOString(), delivery: 'local', runId: null, agent: null })) |
| 149 | await assert.rejects(f.withdraw(mine, 'legacy-1'), { code: 'NOT_FOUND' }) |
| 150 | assert.equal(f.store.comments(mine.id).length, 2) |
| 151 | assert.equal(f.store.comments(other.id).length, 0) |
| 152 | // A withdrawal recorded for one task never blocks the same device ID on another task. |
| 153 | const traveling = randomUUID() |
| 154 | await f.withdraw(other, traveling) |
| 155 | await assert.rejects(f.withdraw(mine, traveling), { code: 'NOT_FOUND' }) |
| 156 | const arrived = await f.comment(mine, 'Sent to the owning task.', { clientId: traveling }) |
| 157 | assert.equal(arrived.id, traveling) |
| 158 | }) |
| 159 | |
| 160 | test('a withdrawal that reaches the Mac first keeps the late request from ever being saved or delivered', async (t) => { |
| 161 | const f = fixture(t) |
| 162 | const task = await f.task('Offline race', 'Done') |
| 163 | const run = f.previous(task) |
| 164 | const stable = randomUUID().toUpperCase() |
| 165 | const early = await f.withdraw(task, stable) |
| 166 | assert.deepEqual({ withdrawn: early.withdrawn, received: early.received }, { withdrawn: true, received: false }) |
| 167 | const late = { taskId: task.id, text: 'Queued while offline.', notifyAgent: true, clientId: stable, requestKey: 'phone:' + stable } |
| 168 | await assert.rejects(f.store.dispatch('add_user_comment', late, 'You · mobile'), { code: 'WITHDRAWN' }) |
| 169 | await assert.rejects(f.store.dispatch('add_user_comment', late, 'You · mobile'), { code: 'WITHDRAWN' }, 'Retries stay withdrawn') |
| 170 | assert.equal(f.store.comments(task.id).length, 0) |
| 171 | assert.equal((await f.store.queueCommentFollowups()).queued, 0) |
| 172 | await f.runner.tick() |
| 173 | assert.equal(f.launched.length, 0) |
| 174 | assert.equal(f.store.assignedRun(task.id), run.id) |
| 175 | assert.equal(f.store.task(task.id).status, 'Done') |
| 176 | assert.equal((await f.withdraw(task, stable)).withdrawn, true) |
| 177 | }) |
| 178 | |
| 179 | test('a phone request keeps its device ID, so the phone can withdraw it without knowing the Mac’s copy', async (t) => { |
| 180 | const f = fixture(t) |
| 181 | const task = await f.task('Stable identity') |
| 182 | const stable = randomUUID().toUpperCase() |
| 183 | const saved = await f.comment(task, 'Named by the phone.', { clientId: stable, requestKey: 'phone:' + stable }) |
| 184 | assert.equal(saved.id, stable.toLowerCase()) |
| 185 | await assert.rejects(f.comment(task, 'A second request with the same ID.', { clientId: stable }), { code: 'CONFLICT' }) |
| 186 | await assert.rejects(f.comment(task, 'Bad ID', { clientId: 'request-1' }), { code: 'INVALID_ARGUMENT' }) |
| 187 | await f.withdraw(task, stable) |
| 188 | assert.equal(f.store.comments(task.id).length, 0) |
| 189 | |
| 190 | // A request saved by an earlier Mac version has the Mac's own ID. Its receipt still names the phone request. |
| 191 | const older = randomUUID().toUpperCase() |
| 192 | const legacy = await f.comment(task, 'Saved before stable IDs.', { requestKey: 'phone:' + older }) |
| 193 | assert.notEqual(legacy.id, older.toLowerCase()) |
| 194 | // If its acknowledgement was lost, the updated Mac replays that receipt instead of failing or saving a copy. |
| 195 | const replayed = await f.comment(task, 'Saved before stable IDs.', { requestKey: 'phone:' + older, clientId: older.toLowerCase() }) |
| 196 | assert.equal(replayed.id, legacy.id) |
| 197 | assert.equal(f.store.comments(task.id).length, 1) |
| 198 | await assert.rejects(f.comment(task, 'Different text.', { requestKey: 'phone:' + older, clientId: older.toLowerCase() }), |
| 199 | { code: 'REQUEST_KEY_REUSED' }) |
| 200 | await f.withdraw(task, older.toLowerCase()) |
| 201 | assert.equal(f.store.comments(task.id).length, 0) |
| 202 | }) |
| 203 | |
| 204 | test('withdrawing the only request in a queued follow-up cancels that follow-up and nothing else', async (t) => { |
| 205 | const f = fixture(t) |
| 206 | const task = await f.task('Follow-up', 'Done') |
| 207 | const other = await f.task('Unrelated', 'Done') |
| 208 | const run = f.previous(task) |
| 209 | const otherRun = f.previous(other, 'codex') |
| 210 | const drop = await f.comment(task, 'Changed my mind.') |
| 211 | const unrelated = await f.comment(other, 'Still wanted.') |
| 212 | assert.equal((await f.store.queueCommentFollowups()).queued, 2) |
| 213 | const followup = f.store.agentJobs().find((job) => job.taskId === task.id) |
| 214 | const otherFollowup = f.store.agentJobs().find((job) => job.taskId === other.id) |
| 215 | assert.equal(followup.previousRunId, run.id) |
| 216 | assert.equal(f.store.comments(task.id)[0].delivery, 'queued') |
| 217 | |
| 218 | const result = await f.withdraw(task, drop.id) |
| 219 | assert.equal(result.run, undefined, 'Nothing was running, so there is no turn to stop') |
| 220 | assert.deepEqual( |
| 221 | { state: f.store.agentJob(followup.id).state, summary: f.store.agentJob(followup.id).summary }, |
| 222 | { state: 'canceled', summary: 'Revision request withdrawn before delivery.' }) |
| 223 | assert.equal(f.store.assignedRun(task.id), run.id, 'The task returns to the run it had') |
| 224 | assert.equal(f.store.agentJob(run.id).state, 'review') |
| 225 | assert.equal(f.store.task(task.id).status, 'Done') |
| 226 | assert.equal(f.store.agentJob(otherFollowup.id).state, 'queued') |
| 227 | assert.equal(f.store.assignedRun(other.id), otherFollowup.id) |
| 228 | assert.equal(f.store.comments(other.id)[0].delivery, 'queued') |
| 229 | |
| 230 | await f.runner.tick() |
| 231 | assert.equal(f.launched.length, 1, 'Only the unrelated follow-up launches') |
| 232 | assert.ok(f.turnText(f.launched[0]).includes(unrelated.text)) |
| 233 | assert.equal(f.store.agentJob(followup.id).state, 'canceled', 'The runner never revives the canceled follow-up') |
| 234 | assert.equal(f.store.agentJob(otherRun.id).state, 'review') |
| 235 | }) |
| 236 | |
| 237 | test('withdrawing one of several queued requests delivers the rest; a dispatch still sends its task', async (t) => { |
| 238 | const f = fixture(t) |
| 239 | await f.write('set_agent_settings', { defaultAgent: 'claude-code', workingFolder: f.folder }) |
| 240 | const task = await f.task('Shared follow-up', 'Done') |
| 241 | f.previous(task) |
| 242 | const keep = await f.comment(task, 'Deliver this one.') |
| 243 | const drop = await f.comment(task, 'Withdraw this one.') |
| 244 | await f.store.queueCommentFollowups() |
| 245 | const followup = f.store.agentJobs()[0] |
| 246 | await f.withdraw(task, drop.id) |
| 247 | assert.equal(f.store.agentJob(followup.id).state, 'queued') |
| 248 | assert.deepEqual(f.store.agentJob(followup.id).commentIds, [keep.id]) |
| 249 | await f.runner.tick() |
| 250 | assert.ok(f.turnText(f.launched[0]).includes('Deliver this one.')) |
| 251 | assert.ok(!f.turnText(f.launched[0]).includes('Withdraw this one.')) |
| 252 | await f.runner.finish(followup.id, 'review', 'Done') |
| 253 | |
| 254 | const fresh = await f.task('New dispatch', 'To do') |
| 255 | const sent = await f.write('move_task', { |
| 256 | id: fresh.id, expectedRevision: fresh.revision, status: 'Sent to agent', dispatchComment: 'Skip the dispatch note.', |
| 257 | }) |
| 258 | const dispatchNote = f.store.comments(fresh.id)[0] |
| 259 | const dispatch = f.store.agentJobs()[0] |
| 260 | assert.equal(dispatch.dispatchCommentId, dispatchNote.id) |
| 261 | await f.withdraw(fresh, dispatchNote.id) |
| 262 | assert.equal(f.store.agentJob(dispatch.id).state, 'queued', 'The user still sent the task itself') |
| 263 | assert.equal(f.store.agentJob(dispatch.id).dispatchCommentId, undefined) |
| 264 | assert.equal(f.store.task(sent.task.id).status, 'Sent to agent') |
| 265 | await f.runner.tick() |
| 266 | assert.equal(f.launched.length, 2) |
| 267 | assert.ok(f.turnText(f.launched[1]).includes('New dispatch')) |
| 268 | assert.ok(!f.turnText(f.launched[1]).includes('Skip the dispatch note.')) |
| 269 | }) |
| 270 | |
| 271 | for (const agent of ['claude-code', 'codex']) |
| 272 | test(`${agent}: a withdrawal during launch ends the turn before any request is written`, async (t) => { |
| 273 | const f = fixture(t) |
| 274 | const task = await f.task('In flight', 'Done') |
| 275 | const run = f.previous(task, agent) |
| 276 | const drop = await f.comment(task, 'Withdrawn while the agent was starting.') |
| 277 | await f.store.queueCommentFollowups() |
| 278 | const followup = f.store.agentJobs()[0] |
| 279 | let release |
| 280 | const until = new Promise((resolve) => { release = resolve }) |
| 281 | const original = f.runner.spawnTransport |
| 282 | f.runner.spawnTransport = (...args) => Object.assign(original(...args), { hold: { method: 'initialize', until } }) |
| 283 | const launching = f.runner.tick() |
| 284 | while (!f.launched.length) await new Promise((resolve) => setImmediate(resolve)) |
| 285 | assert.equal(f.store.agentJob(followup.id).state, 'starting') |
| 286 | assert.equal(f.runner.turnState(followup.id), 'unsent') |
| 287 | |
| 288 | const result = await f.withdraw(task, drop.id) |
| 289 | assert.deepEqual(result.run, { id: followup.id, stop: true }) |
| 290 | release() |
| 291 | await launching |
| 292 | const entry = f.launched[0] |
| 293 | assert.equal(f.turnText(entry), undefined, 'The withdrawn request never reached the agent') |
| 294 | assert.ok(!entry.written.some(({ method }) => method === 'interrupt' || method === 'turn/interrupt')) |
| 295 | assert.equal(entry.closed, true) |
| 296 | assert.equal(f.runner.current, null) |
| 297 | const ended = f.store.agentJob(followup.id) |
| 298 | assert.deepEqual({ state: ended.state, summary: ended.summary }, |
| 299 | { state: 'canceled', summary: 'Revision request withdrawn before delivery.' }) |
| 300 | assert.equal(f.store.assignedRun(task.id), run.id) |
| 301 | assert.equal(f.store.task(task.id).status, 'Done') |
| 302 | assert.equal(f.store.comments(task.id).length, 0) |
| 303 | await entry.exit(new Error('Late exit')) |
| 304 | assert.equal(f.store.agentJob(followup.id).state, 'canceled') |
| 305 | }) |
| 306 | |
| 307 | for (const agent of ['claude-code', 'codex']) |
| 308 | test(`${agent}: a request already handed to its own turn stops that turn by asking the agent, never another run`, async (t) => { |
| 309 | const f = fixture(t) |
| 310 | const task = await f.task('Delivered', 'Done') |
| 311 | const run = f.previous(task, agent) |
| 312 | const drop = await f.comment(task, 'Already with the agent.') |
| 313 | await f.store.queueCommentFollowups() |
| 314 | const followup = f.store.agentJobs()[0] |
| 315 | await f.runner.tick() |
| 316 | const entry = f.launched[0] |
| 317 | assert.ok(f.turnText(entry).includes('Already with the agent.')) |
| 318 | assert.equal(f.runner.turnState(followup.id), 'sent') |
| 319 | await entry.message(agent === 'claude-code' |
| 320 | ? { type: 'system', subtype: 'init', session_id: run.threadId } |
| 321 | : { method: 'turn/started', params: { turn: { id: 'turn-9' } } }) |
| 322 | assert.equal(f.store.comments(task.id)[0].delivery, 'delivered') |
| 323 | // A second task waits in the queue behind the running turn. |
| 324 | const waiting = await f.task('Queued behind', 'Done') |
| 325 | f.previous(waiting, agent) |
| 326 | await f.comment(waiting, 'Wait your turn.') |
| 327 | await f.store.queueCommentFollowups() |
| 328 | const queued = f.store.agentJobs()[0] |
| 329 | |
| 330 | const result = await f.withdraw(task, drop.id) |
| 331 | assert.deepEqual(result.run, { id: followup.id, stop: true }) |
| 332 | const interrupt = entry.written.find(({ method }) => method === 'interrupt' || method === 'turn/interrupt') |
| 333 | assert.ok(interrupt, 'The agent is asked to end its turn') |
| 334 | if (agent === 'codex') assert.deepEqual(interrupt.params, { threadId: run.threadId, turnId: 'turn-9' }) |
| 335 | assert.equal(entry.closed, true) |
| 336 | const ended = f.store.agentJob(followup.id) |
| 337 | assert.equal(ended.state, 'canceled') |
| 338 | assert.match(ended.summary, /revision request was withdrawn/) |
| 339 | assert.equal(f.store.assignedRun(task.id), run.id) |
| 340 | assert.equal(f.store.comments(task.id).length, 0) |
| 341 | assert.equal(f.store.agentJob(queued.id).state, 'queued', 'The waiting run is untouched') |
| 342 | assert.equal(f.store.comments(waiting.id)[0].delivery, 'queued') |
| 343 | // The same withdrawal replayed after the turn ended stops nothing new. |
| 344 | await f.runner.stopWithdrawnTurn(followup.id) |
| 345 | await f.runner.tick() |
| 346 | assert.equal(f.launched.length, 2) |
| 347 | assert.ok(f.turnText(f.launched[1]).includes('Wait your turn.')) |
| 348 | }) |
| 349 | |
| 350 | test('work the agent already applied is never marked stopped or withdrawn', async (t) => { |
| 351 | const f = fixture(t) |
| 352 | const task = await f.task('Applied work', 'Done') |
| 353 | const run = f.previous(task) |
| 354 | const applied = await f.comment(task, 'Apply this first.') |
| 355 | const second = await f.comment(task, 'Then this.') |
| 356 | await f.store.queueCommentFollowups() |
| 357 | const followup = f.store.agentJobs()[0] |
| 358 | await f.runner.tick() |
| 359 | const entry = f.launched[0] |
| 360 | await entry.message({ type: 'system', subtype: 'init', session_id: run.threadId }) |
| 361 | await f.write('add_task_activity', { taskId: task.id, text: 'Applied the first request.', commentIds: [applied.id] }, 'Claude') |
| 362 | |
| 363 | await assert.rejects(f.withdraw(task, applied.id), { code: 'INVALID_STATE', message: /already acted on/ }) |
| 364 | assert.equal(entry.closed, false) |
| 365 | assert.equal(f.store.agentJob(followup.id).state, 'working') |
| 366 | assert.equal(f.store.comments(task.id).find(({ id }) => id === applied.id).delivery, 'delivered') |
| 367 | |
| 368 | // With the first request applied, the second is the turn's only remaining work, so the turn ends. |
| 369 | const result = await f.withdraw(task, second.id) |
| 370 | assert.deepEqual(result.run, { id: followup.id, stop: true }) |
| 371 | const ended = f.store.agentJob(followup.id) |
| 372 | assert.equal(ended.state, 'review', 'Applied work is left for review') |
| 373 | assert.match(ended.summary, /Completed revision work is ready for review/) |
| 374 | assert.equal(f.store.assignedRun(task.id), followup.id) |
| 375 | const kept = f.store.comments(task.id) |
| 376 | assert.deepEqual(kept.map(({ id }) => id), [applied.id]) |
| 377 | assert.ok(kept[0].actedOnAt) |
| 378 | assert.equal(kept[0].activityState, 'review') |
| 379 | await assert.rejects(f.write('report_agent_progress', { runId: followup.id, state: 'working', summary: 'Late report' }, 'Claude'), |
| 380 | { code: 'INACTIVE_RUN' }) |
| 381 | }) |
| 382 | |
| 383 | for (const agent of ['claude-code', 'codex']) |
| 384 | test(`${agent}: a request sharing an active turn is invalidated and its run is told to skip it while the rest continues`, async (t) => { |
| 385 | const f = fixture(t) |
| 386 | const task = await f.task('Shared turn', 'Done') |
| 387 | const other = await f.task('Other running context', 'Done') |
| 388 | const run = f.previous(task, agent) |
| 389 | const keep = await f.comment(task, 'Keep working on this.') |
| 390 | const drop = await f.comment(task, 'Skip this after all.') |
| 391 | const elsewhere = await f.comment(other, 'Unrelated request.') |
| 392 | f.previous(other, agent) |
| 393 | await f.store.queueCommentFollowups() |
| 394 | const followup = f.store.agentJobs().find((job) => job.taskId === task.id) |
| 395 | const otherFollowup = f.store.agentJobs().find((job) => job.taskId === other.id) |
| 396 | // The runner launches the newest queued job last, so cancel order does not matter here. |
| 397 | while (f.runner.current?.job.id !== followup.id) { |
| 398 | if (f.runner.current) await f.runner.finish(f.runner.current.job.id, 'review', 'Finished') |
| 399 | await f.runner.tick() |
| 400 | } |
| 401 | const entry = f.launched.at(-1) |
| 402 | assert.ok(f.turnText(entry).includes('Skip this after all.')) |
| 403 | await entry.message(agent === 'claude-code' |
| 404 | ? { type: 'system', subtype: 'init', session_id: run.threadId } |
| 405 | : { method: 'turn/started', params: { turn: { id: 'turn-4' } } }) |
| 406 | const before = entry.written.length |
| 407 | |
| 408 | const input = { taskId: task.id, id: drop.id, requestKey: randomUUID() } |
| 409 | const result = await f.store.dispatch('withdraw_revision_request', input, 'You · mobile') |
| 410 | assert.deepEqual(result.run, { id: followup.id, notify: { id: drop.id, text: 'Skip this after all.' } }) |
| 411 | await f.runner.notifyWithdrawal(result.run.id, result.run.notify) |
| 412 | // A retried request replays its receipt and must not message the agent twice. |
| 413 | const replay = await f.store.dispatch('withdraw_revision_request', input, 'You · mobile') |
| 414 | await f.runner.notifyWithdrawal(replay.run.id, replay.run.notify) |
| 415 | const sent = entry.written.slice(before) |
| 416 | assert.equal(sent.length, 1) |
| 417 | const note = agent === 'claude-code' ? sent[0].message.content[0].text : sent[0].params.input[0].text |
| 418 | if (agent === 'codex') { |
| 419 | assert.equal(sent[0].method, 'turn/steer') |
| 420 | assert.equal(sent[0].params.expectedTurnId, 'turn-4') |
| 421 | } |
| 422 | assert.ok(note.includes(drop.id) && note.includes('Skip this after all.')) |
| 423 | assert.ok(!entry.written.some(({ method }) => method === 'interrupt' || method === 'turn/interrupt'), 'The shared turn is not interrupted') |
| 424 | assert.equal(entry.closed, false) |
| 425 | |
| 426 | const job = f.store.agentJob(followup.id) |
| 427 | assert.equal(job.state, 'working') |
| 428 | assert.deepEqual(job.commentIds, [keep.id]) |
| 429 | assert.deepEqual(f.store.comments(task.id).map(({ id }) => id), [keep.id]) |
| 430 | assert.equal(f.store.comments(task.id)[0].delivery, 'delivered') |
| 431 | assert.equal(f.store.comments(other.id)[0].id, elsewhere.id) |
| 432 | assert.notEqual(f.store.agentJob(otherFollowup.id).state, 'canceled') |
| 433 | |
| 434 | // The run's own tool calls repeat the withdrawal. The user's and other tasks' reads do not. |
| 435 | const asAgent = (name, fields) => f.store.dispatch(name, fields, 'Connected agent') |
| 436 | const listed = await asAgent('list_task_comments', { taskId: task.id }) |
| 437 | assert.deepEqual(listed.withdrawnRevisionRequests.map(({ id }) => id), [drop.id]) |
| 438 | assert.match(listed.withdrawalNotice, /Do not start or continue work on them/) |
| 439 | assert.ok((await asAgent('get_task', { id: task.id })).withdrawalNotice) |
| 440 | assert.equal((await asAgent('get_task', { id: other.id })).withdrawalNotice, undefined) |
| 441 | assert.equal((await f.store.dispatch('list_task_comments', { taskId: task.id }, 'You · Mac')).withdrawalNotice, undefined) |
| 442 | |
| 443 | // The withdrawn request can no longer be claimed, and no receipt is owed for it. |
| 444 | await assert.rejects(f.write('add_task_activity', { taskId: task.id, text: 'Did both.', commentIds: [keep.id, drop.id] }, 'Claude'), |
| 445 | { code: 'WITHDRAWN' }) |
| 446 | const done = await f.write('report_agent_progress', { |
| 447 | runId: followup.id, state: 'done', summary: 'Finished the remaining request.', |
| 448 | proof: 'Ran the focused checks for the remaining request and all of them passed.', |
| 449 | definitionOfDoneMet: true, actedOnCommentIds: [keep.id], |
| 450 | }, 'Claude') |
| 451 | assert.equal(done.run.state, 'done') |
| 452 | assert.equal(f.store.task(task.id).status, 'Done') |
| 453 | assert.ok(f.store.comments(task.id)[0].actedOnAt) |
| 454 | assert.equal((await asAgent('get_task', { id: task.id })).withdrawalNotice, undefined, 'A finished run is no longer notified') |
| 455 | }) |
| 456 | |
| 457 | test('a request sent with a task’s first dispatch is withdrawn without stopping the task', async (t) => { |
| 458 | const f = fixture(t) |
| 459 | await f.write('set_agent_settings', { defaultAgent: 'claude-code', workingFolder: f.folder }) |
| 460 | const fresh = await f.task('First dispatch', 'To do') |
| 461 | await f.write('move_task', { id: fresh.id, expectedRevision: fresh.revision, status: 'Sent to agent', dispatchComment: 'Sent with the task.' }) |
| 462 | const dispatch = f.store.agentJobs()[0] |
| 463 | await f.runner.tick() |
| 464 | const entry = f.launched[0] |
| 465 | await entry.message({ type: 'system', subtype: 'init', session_id: f.store.agentJob(dispatch.id).threadId }) |
| 466 | const note = f.store.comments(fresh.id)[0] |
| 467 | assert.ok(note.pickedUpAt) |
| 468 | const result = await f.withdraw(fresh, note.id) |
| 469 | assert.equal(result.run.notify.id, note.id) |
| 470 | assert.equal(entry.closed, false) |
| 471 | assert.equal(f.store.agentJob(dispatch.id).state, 'working') |
| 472 | assert.equal(f.store.task(fresh.id).status, 'In progress') |
| 473 | assert.equal(f.store.comments(fresh.id).length, 0) |
| 474 | assert.ok(entry.written.at(-1).message.content[0].text.includes('withdrew revision request')) |
| 475 | |
| 476 | // A received request whose run already ended without acting on it is simply removed. |
| 477 | const again = await f.task('Ended run', 'To do') |
| 478 | await f.write('move_task', { id: again.id, expectedRevision: again.revision, status: 'Sent to agent', dispatchComment: 'Never acted on.' }) |
| 479 | const second = f.store.agentJobs()[0] |
| 480 | await f.runner.finish(dispatch.id, 'review', 'Finished') |
| 481 | await f.runner.tick() |
| 482 | await f.launched[1].message({ type: 'system', subtype: 'init', session_id: f.store.agentJob(second.id).threadId }) |
| 483 | await f.runner.finish(second.id, 'review', 'Ended without a receipt') |
| 484 | const stale = f.store.comments(again.id)[0] |
| 485 | assert.equal(stale.delivery, 'needs-review') |
| 486 | const ended = await f.withdraw(again, stale.id) |
| 487 | assert.equal(ended.run, undefined) |
| 488 | assert.equal(f.store.comments(again.id).length, 0) |
| 489 | assert.equal(f.store.agentJob(second.id).state, 'review') |
| 490 | assert.equal(f.store.assignedRun(again.id), second.id) |
| 491 | }) |
| 492 | |
| 493 | test('an undelivered request that needs review can be withdrawn and is not retried', async (t) => { |
| 494 | const f = fixture(t) |
| 495 | const task = await f.task('Needs review', 'Done') |
| 496 | const run = f.previous(task) |
| 497 | const drop = await f.comment(task, 'Never reached the agent.') |
| 498 | await f.store.queueCommentFollowups() |
| 499 | const followup = f.store.agentJobs()[0] |
| 500 | await f.store.updateAgentJob(followup.id, { state: 'failed', summary: 'Launch failed' }) |
| 501 | assert.equal(f.store.comments(task.id)[0].delivery, 'needs-review') |
| 502 | await f.withdraw(task, drop.id) |
| 503 | assert.equal(f.store.comments(task.id).length, 0) |
| 504 | assert.equal(f.store.agentJob(followup.id).state, 'failed', 'A finished run keeps its recorded outcome') |
| 505 | await assert.rejects(f.write('retry_task_comment', { id: drop.id }), { code: 'NOT_FOUND' }) |
| 506 | assert.equal((await f.store.queueCommentFollowups()).queued, 0) |
| 507 | assert.equal(f.store.agentJob(run.id).state, 'review') |
| 508 | }) |
| 509 | |
| 510 | test('backups made after a withdrawal restore without the withdrawn request', async (t) => { |
| 511 | const f = fixture(t) |
| 512 | const target = fixture(t) |
| 513 | const task = await f.task('Portable') |
| 514 | const keep = await f.comment(task, 'Kept across restore.') |
| 515 | const drop = await f.comment(task, 'Withdrawn before backup.') |
| 516 | await f.withdraw(task, drop.id) |
| 517 | for (const format of ['json', 'sqlite']) { |
| 518 | const backup = await f.write('create_backup', { format }) |
| 519 | const preview = await target.store.dispatch('preview_destructive_action', { action: 'restore_backup', path: backup.path }) |
| 520 | await target.write('confirm_destructive_action', { token: preview.token }) |
| 521 | assert.deepEqual(target.store.comments(task.id).map(({ id }) => id), [keep.id]) |
| 522 | const activity = await target.store.dispatch('list_task_activity', { taskId: task.id }) |
| 523 | assert.ok(activity.entries.some(({ summary }) => summary === 'Withdrew a revision request')) |
| 524 | } |
| 525 | }) |
| 526 | |
| 527 | // Runs the real native service process the Mac app talks to, over its JSON-line transport. |
| 528 | function nativeService(t) { |
| 529 | const staged = fs.mkdtempSync(path.join(base, 'withdraw-service-')) |
| 530 | const data = fs.mkdtempSync(path.join(base, 'withdraw-data-')) |
| 531 | for (const file of fs.readdirSync(__dirname)) |
| 532 | if (file.endsWith('.cjs') && !file.endsWith('.test.cjs')) fs.copyFileSync(path.join(__dirname, file), path.join(staged, file)) |
| 533 | for (const file of ['service.cjs', 'daily-backup.cjs']) |
| 534 | fs.copyFileSync(path.resolve(__dirname, '..', file), path.join(staged, file)) |
| 535 | const child = spawn(process.execPath, [path.join(staged, 'service.cjs'), data, process.execPath, '0.1.0'], { |
| 536 | stdio: ['pipe', 'pipe', 'inherit'], |
| 537 | env: { ...process.env, HOME: data, PATH: '/usr/bin:/bin', CODEX_APP_RUNTIME_CLI_PATH: '' }, |
| 538 | }) |
| 539 | const closed = once(child, 'close') |
| 540 | const requests = new Map() |
| 541 | let ready |
| 542 | const started = new Promise((resolve, reject) => { ready = resolve; child.on('close', () => reject(new Error('Service exited.'))) }) |
| 543 | started.catch(() => {}) |
| 544 | readline.createInterface({ input: child.stdout }).on('line', (line) => { |
| 545 | const response = JSON.parse(line) |
| 546 | if (response.event === 'ready') ready() |
| 547 | const pending = requests.get(response.id) |
| 548 | if (!pending) return |
| 549 | requests.delete(response.id) |
| 550 | if (response.error) pending.reject(Object.assign(new Error(response.error.message), response.error)) |
| 551 | else pending.resolve(response.data) |
| 552 | }) |
| 553 | t.after(async () => { |
| 554 | child.stdin.end() |
| 555 | await closed |
| 556 | fs.rmSync(staged, { recursive: true, force: true }) |
| 557 | fs.rmSync(data, { recursive: true, force: true }) |
| 558 | }) |
| 559 | return async (name, input = {}) => { |
| 560 | await started |
| 561 | return new Promise((resolve, reject) => { |
| 562 | const id = randomUUID() |
| 563 | requests.set(id, { resolve, reject }) |
| 564 | child.stdin.write(JSON.stringify({ id, name, input }) + '\n') |
| 565 | }) |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | test('the native service applies phone withdrawals end to end and reports them in the phone snapshot', { timeout: 30000 }, async (t) => { |
| 570 | const call = nativeService(t) |
| 571 | const phone = (name, input) => { |
| 572 | const request = randomUUID().toUpperCase() |
| 573 | return call(name, { requestKey: 'phone:' + request, ...input }).then((result) => ({ request, result })) |
| 574 | } |
| 575 | const { boards } = await call('snapshot') |
| 576 | const { result: created } = await phone('create_task', { boardId: boards[0].id, title: 'Phone revisions' }) |
| 577 | const task = created.task |
| 578 | const { result: other } = await phone('create_task', { boardId: boards[0].id, title: 'Other task' }) |
| 579 | |
| 580 | // The Mac saves the phone's request under the phone's own request ID. |
| 581 | const sent = randomUUID().toUpperCase() |
| 582 | const saved = await call('add_user_comment', { |
| 583 | requestKey: 'phone:' + sent, taskId: task.id, text: 'From the phone.', notifyAgent: false, clientId: sent.toLowerCase(), |
| 584 | }) |
| 585 | assert.equal(saved.comment.id, sent.toLowerCase()) |
| 586 | await phone('add_user_comment', { taskId: task.id, text: 'Stays on the task.', notifyAgent: false }) |
| 587 | let snapshot = await call('native_phone_snapshot') |
| 588 | assert.deepEqual(snapshot.commentsByTask[task.id].map(({ text, delivery }) => [text, delivery]), |
| 589 | [['From the phone.', 'local'], ['Stays on the task.', 'local']]) |
| 590 | |
| 591 | await assert.rejects(phone('withdraw_revision_request', { taskId: other.task.id, id: sent.toLowerCase() }), { code: 'NOT_FOUND' }) |
| 592 | await assert.rejects(call('withdraw_revision_request', { taskId: task.id, id: sent.toLowerCase() }), { code: 'INVALID_ARGUMENT' }, |
| 593 | 'A request key is required so retries replay') |
| 594 | const { request, result } = await phone('withdraw_revision_request', { taskId: task.id, id: sent.toLowerCase() }) |
| 595 | assert.equal(result.withdrawn, true) |
| 596 | const replay = await call('withdraw_revision_request', { requestKey: 'phone:' + request, taskId: task.id, id: sent.toLowerCase() }) |
| 597 | assert.deepEqual(replay, result) |
| 598 | snapshot = await call('native_phone_snapshot') |
| 599 | assert.deepEqual(snapshot.commentsByTask[task.id].map(({ text }) => text), ['Stays on the task.']) |
| 600 | assert.ok(snapshot.workspace.revision >= result.revision) |
| 601 | const activity = await call('list_task_activity', { taskId: task.id }) |
| 602 | const entry = activity.entries.find(({ summary }) => summary === 'Withdrew a revision request') |
| 603 | assert.equal(entry.actor, 'You · mobile') |
| 604 | |
| 605 | // Withdrawn while still in transit: the late request is refused when it arrives. |
| 606 | const late = randomUUID().toUpperCase() |
| 607 | await phone('withdraw_revision_request', { taskId: task.id, id: late.toLowerCase() }) |
| 608 | await assert.rejects(call('add_user_comment', { |
| 609 | requestKey: 'phone:' + late, taskId: task.id, text: 'Arrived after its withdrawal.', notifyAgent: false, clientId: late.toLowerCase(), |
| 610 | }), { code: 'WITHDRAWN' }) |
| 611 | snapshot = await call('native_phone_snapshot') |
| 612 | assert.deepEqual(snapshot.commentsByTask[task.id].map(({ text }) => text), ['Stays on the task.']) |
| 613 | assert.equal(snapshot.commentsByTask[other.task.id], undefined) |
| 614 | }) |