OpenTalon / app / native / runtime / comments.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 { randomUUID } = require('node:crypto') |
| 6 | const { Store } = require('./store.cjs') |
| 7 | const { AgentRunner } = require('./agent-runner.cjs') |
| 8 | const { Connector } = require('./mcp.cjs') |
| 9 | const base = process.env.OPENTALON_TEST_ROOT || '/Volumes/Expand/Projects/OpenTalon/native-app/tests' |
| 10 | const image = { |
| 11 | name: 'Screenshot.png', |
| 12 | mimeType: 'image/png', |
| 13 | data: fs |
| 14 | .readFileSync(path.resolve(__dirname, '../assets/opentalon-logo-1024.png')) |
| 15 | .toString('base64'), |
| 16 | } |
| 17 | function fixture(t) { |
| 18 | fs.mkdirSync(base, { recursive: true }) |
| 19 | const folder = fs.mkdtempSync(path.join(base, 'comments-')) |
| 20 | const store = new Store(folder) |
| 21 | const cleanup = [] |
| 22 | t.after(async () => { |
| 23 | for (const close of cleanup.reverse()) await close() |
| 24 | store.close() |
| 25 | fs.rmSync(folder, { recursive: true, force: true }) |
| 26 | }) |
| 27 | const write = (name, input) => store.dispatch(name, { ...input, requestKey: randomUUID() }) |
| 28 | const task = (title) => |
| 29 | write('create_task', { boardId: store.boards()[0].id, title, status: 'In progress' }).then( |
| 30 | (result) => result.task |
| 31 | ) |
| 32 | const previous = (task, agent = 'claude-code') => { |
| 33 | const job = store.saveAgentJob({ |
| 34 | id: randomUUID(), |
| 35 | taskId: task.id, |
| 36 | agent, |
| 37 | workingFolder: folder, |
| 38 | threadId: randomUUID(), |
| 39 | state: 'review', |
| 40 | summary: 'First response', |
| 41 | createdAt: new Date().toISOString(), |
| 42 | }) |
| 43 | store.assignAgent(task.id, job.id) |
| 44 | return job |
| 45 | } |
| 46 | const comment = (task, text = 'Please update this.', images = []) => |
| 47 | write('add_user_comment', { taskId: task.id, text, images, notifyAgent: true }).then( |
| 48 | (result) => result.comment |
| 49 | ) |
| 50 | return { store, write, task, previous, comment, folder, cleanup } |
| 51 | } |
| 52 | for (const agent of ['claude-code', 'codex']) |
| 53 | test(`${agent} checks at five minutes, resumes the same conversation and passes screenshots`, async (t) => { |
| 54 | const f = fixture(t), |
| 55 | { task } = await f.write('create_task', { |
| 56 | boardId: f.store.boards()[0].id, title: 'Feedback', status: 'Done', |
| 57 | }) |
| 58 | const previous = f.previous(task, agent) |
| 59 | const comment = await f.comment(task, 'Use this screenshot.', [image]) |
| 60 | await f.write('set_agent_settings', { |
| 61 | defaultAgent: agent === 'codex' ? 'claude-code' : 'codex', |
| 62 | workingFolder: base, |
| 63 | }) |
| 64 | const launched = [] |
| 65 | let connected = true |
| 66 | const runner = new AgentRunner({ |
| 67 | store: f.store, |
| 68 | connector: { |
| 69 | status: () => ({ enabled: connected, running: connected }), |
| 70 | configuration: () => ({ |
| 71 | mcpServers: { opentalon: { command: '/app', args: [], env: {} } }, |
| 72 | }), |
| 73 | }, |
| 74 | openExternal: () => {}, |
| 75 | resolveExecutable: (agent) => agent, |
| 76 | spawnTransport(file, args, cwd, message) { |
| 77 | const transport = { |
| 78 | file, |
| 79 | args, |
| 80 | cwd, |
| 81 | message, |
| 82 | messages: [], |
| 83 | request: async (method, params) => { |
| 84 | transport.messages.push({ method, params }) |
| 85 | return method === 'thread/resume' ? { thread: { id: params.threadId } } : {} |
| 86 | }, |
| 87 | write: (value) => transport.messages.push(value), |
| 88 | close() {}, |
| 89 | } |
| 90 | launched.push(transport) |
| 91 | return transport |
| 92 | }, |
| 93 | }) |
| 94 | f.cleanup.push(() => runner.close()) |
| 95 | await runner.tick() |
| 96 | assert.equal(launched.length, 0, 'No early wake-up before five minutes') |
| 97 | runner.lastCommentCheck = Date.now() - 300001 |
| 98 | connected = false |
| 99 | await runner.tick() |
| 100 | assert.equal(launched.length, 0, 'MCP off must not queue or launch a comment follow-up') |
| 101 | assert.deepEqual(f.store.agentJobs().map(({ id }) => id), [previous.id]) |
| 102 | connected = true |
| 103 | await runner.tick() |
| 104 | assert.equal(launched.length, 1) |
| 105 | const job = f.store.agentJobs()[0] |
| 106 | assert.equal(job.agent, agent, 'Changing defaults must not switch an existing conversation') |
| 107 | assert.equal(job.threadId, previous.threadId) |
| 108 | assert.equal(job.workingFolder, previous.workingFolder) |
| 109 | assert.deepEqual(job.commentIds, [comment.id]) |
| 110 | assert.equal(f.store.comments(task.id)[0].delivery, 'queued') |
| 111 | assert.equal(f.store.task(task.id).status, 'Done', 'Queued does not mean the agent picked it up') |
| 112 | await runner.tick() |
| 113 | assert.equal(f.store.agentJob(job.id).state, 'starting') |
| 114 | const transport = launched[0] |
| 115 | if (agent === 'claude-code') { |
| 116 | assert.equal(transport.args[transport.args.indexOf('--resume') + 1], previous.threadId) |
| 117 | assert.ok(!transport.args.includes('--session-id')) |
| 118 | assert.equal(transport.messages.at(-1).message.content[1].source.data, image.data) |
| 119 | await transport.message({ type: 'system', subtype: 'init', session_id: previous.threadId }) |
| 120 | } else { |
| 121 | assert.ok(transport.messages.some((message) => message.method === 'thread/resume')) |
| 122 | assert.ok(!transport.messages.some((message) => message.method === 'thread/start')) |
| 123 | assert.equal( |
| 124 | transport.messages.at(-1).params.input[1].url, |
| 125 | `data:image/png;base64,${image.data}` |
| 126 | ) |
| 127 | await transport.message({ method: 'turn/started', params: { threadId: previous.threadId } }) |
| 128 | } |
| 129 | assert.equal(f.store.comments(task.id)[0].delivery, 'delivered') |
| 130 | const pickedUpAt = f.store.agentJob(job.id).pickedUpAt |
| 131 | assert.ok(Number.isFinite(Date.parse(pickedUpAt))) |
| 132 | assert.equal(f.store.comments(task.id)[0].pickedUpAt, pickedUpAt) |
| 133 | assert.equal(f.store.task(task.id).status, 'In progress') |
| 134 | await runner.finish(job.id, 'review', 'Comments addressed') |
| 135 | runner.lastCommentCheck = Date.now() - 300001 |
| 136 | await runner.tick() |
| 137 | assert.equal(launched.length, 1, 'A delivered comment must never be replayed') |
| 138 | }) |
| 139 | test('comments are idempotent, defer busy tasks, hold completion for unread feedback and never wake on agent notes', async (t) => { |
| 140 | const f = fixture(t), |
| 141 | task = await f.task('Working') |
| 142 | const job = f.previous(task) |
| 143 | await f.store.updateAgentJob(job.id, { state: 'working' }) |
| 144 | const args = { |
| 145 | taskId: task.id, |
| 146 | text: 'New direction', |
| 147 | images: [image], |
| 148 | notifyAgent: true, |
| 149 | requestKey: randomUUID(), |
| 150 | } |
| 151 | const saved = await f.store.dispatch('add_user_comment', args) |
| 152 | assert.deepEqual(await f.store.dispatch('add_user_comment', args), saved) |
| 153 | assert.equal(f.store.comments(task.id).length, 1) |
| 154 | assert.equal((await f.store.queueCommentFollowups()).queued, 0) |
| 155 | await f.write('report_agent_progress', { |
| 156 | runId: job.id, |
| 157 | state: 'done', |
| 158 | summary: 'Earlier work complete', |
| 159 | proof: |
| 160 | 'Earlier requested checks passed; newly pending feedback is still waiting and must keep this task open.', |
| 161 | definitionOfDoneMet: true, |
| 162 | }) |
| 163 | assert.equal(f.store.task(task.id).status, 'In progress', 'Unread feedback keeps the task open') |
| 164 | assert.equal((await f.store.queueCommentFollowups()).queued, 1) |
| 165 | const queued = f.store.agentJobs()[0] |
| 166 | assert.equal((await f.store.queueCommentFollowups()).queued, 0) |
| 167 | await f.store.updateAgentJob(queued.id, { state: 'failed' }) |
| 168 | assert.equal(f.store.comments(task.id)[0].delivery, 'needs-review') |
| 169 | await f.write('retry_task_comment', { id: saved.comment.id }) |
| 170 | assert.equal((await f.store.queueCommentFollowups()).queued, 1) |
| 171 | const agentNote = await f.write('add_task_activity', { taskId: task.id, text: 'Agent note' }) |
| 172 | assert.equal(agentNote.activity.kind, 'agent') |
| 173 | assert.equal(f.store.commentImage(saved.comment.images[0].id).data, image.data) |
| 174 | await assert.rejects(f.comment(task, '', []), { code: 'EMPTY_COMMENT' }) |
| 175 | await assert.rejects( |
| 176 | f.comment(task, 'Bad image', [ |
| 177 | { ...image, data: Buffer.from('not an image').toString('base64') }, |
| 178 | ]), |
| 179 | { code: 'INVALID_IMAGE' } |
| 180 | ) |
| 181 | await assert.rejects(f.comment(task, 'Too many', [image, image, image, image]), { |
| 182 | code: 'INVALID_ARGUMENT', |
| 183 | }) |
| 184 | assert.equal(f.store.comments(task.id).length, 1, 'Only the user note belongs in Comments') |
| 185 | }) |
| 186 | test('comments and screenshot bytes round-trip in JSON and SQLite; restored feedback is paused and legacy v2 imports', async (t) => { |
| 187 | const f = fixture(t), |
| 188 | target = fixture(t), |
| 189 | task = await f.task('Portable comments') |
| 190 | f.previous(task) |
| 191 | const comment = await f.comment(task, 'Image retained after restore', [image]) |
| 192 | const trash = await f.task('Trashed with comments') |
| 193 | await f.comment(trash, 'Keep this too') |
| 194 | await f.write('trash_task', { id: trash.id, expectedRevision: trash.revision }) |
| 195 | for (const format of ['json', 'sqlite']) { |
| 196 | const backup = await f.write('create_backup', { format }) |
| 197 | const preview = await target.store.dispatch('preview_destructive_action', { |
| 198 | action: 'restore_backup', |
| 199 | path: backup.path, |
| 200 | }) |
| 201 | await target.write('confirm_destructive_action', { token: preview.token }) |
| 202 | assert.equal(target.store.comments(task.id)[0].text, comment.text) |
| 203 | assert.equal(target.store.comments(task.id)[0].delivery, 'needs-review') |
| 204 | assert.equal(target.store.commentImage(comment.images[0].id).data, image.data) |
| 205 | assert.equal(target.store.comments(trash.id).length, 1) |
| 206 | assert.equal((await target.store.queueCommentFollowups()).queued, 0) |
| 207 | } |
| 208 | const backup = await f.write('create_backup', { format: 'json' }) |
| 209 | const json = JSON.parse(fs.readFileSync(backup.path, 'utf8')) |
| 210 | const legacy = path.join(f.folder, 'legacy-v2.json') |
| 211 | fs.writeFileSync( |
| 212 | legacy, |
| 213 | JSON.stringify({ ...json, formatVersion: 2, comments: undefined, commentImages: undefined }) |
| 214 | ) |
| 215 | assert.equal((await f.store.inspect(legacy)).comments.length, 0) |
| 216 | const invalid = path.join(f.folder, 'bad-comment.json') |
| 217 | fs.writeFileSync( |
| 218 | invalid, |
| 219 | JSON.stringify({ ...json, commentImages: [{ ...json.commentImages[0], commentId: 'missing' }] }) |
| 220 | ) |
| 221 | await assert.rejects(f.store.inspect(invalid), { code: 'INVALID_BACKUP' }) |
| 222 | }) |
| 223 | test('MCP returns screenshot image content without duplicating base64 in structured metadata', async (t) => { |
| 224 | const f = fixture(t), |
| 225 | task = await f.task('Image tool') |
| 226 | const comment = await f.comment(task, '', [image]) |
| 227 | const connector = new Connector({ |
| 228 | folder: f.folder, |
| 229 | call: (name, args) => f.store.dispatch(name, args), |
| 230 | }) |
| 231 | await connector.enable(true) |
| 232 | f.cleanup.push(() => connector.stop()) |
| 233 | const response = await fetch(connector.status().endpoint, { |
| 234 | method: 'POST', |
| 235 | headers: { |
| 236 | Authorization: `Bearer ${connector.config.token}`, |
| 237 | 'Content-Type': 'application/json', |
| 238 | Accept: 'application/json, text/event-stream', |
| 239 | }, |
| 240 | body: JSON.stringify({ |
| 241 | jsonrpc: '2.0', |
| 242 | id: 1, |
| 243 | method: 'tools/call', |
| 244 | params: { name: 'read_comment_image', arguments: { imageId: comment.images[0].id } }, |
| 245 | }), |
| 246 | }) |
| 247 | const data = await response.json() |
| 248 | assert.equal(data.result.content[0].type, 'image') |
| 249 | assert.equal(data.result.content[0].data, image.data) |
| 250 | assert.ok(!data.result.structuredContent.data) |
| 251 | }) |
| 252 | |
| 253 | test('comment Acted on links isolate the responding run and its task changes, never pickup alone', async t => { |
| 254 | const f=fixture(t),task=await f.task('Comment drill-down') |
| 255 | const old=f.previous(task,'codex') |
| 256 | const comment=await f.comment(task,'Please make this high priority.') |
| 257 | await f.store.queueCommentFollowups() |
| 258 | const run=f.store.agentJobs().find(job=>job.id!==old.id) |
| 259 | await f.store.updateAgentJob(run.id,{state:'starting'}) |
| 260 | await f.store.updateAgentJob(run.id,{state:'working',summary:'Reading feedback'},{pickedUp:true}) |
| 261 | let saved=f.store.comments(task.id).find(item=>item.id===comment.id) |
| 262 | assert.ok(saved.pickedUpAt);assert.equal(saved.actedOnAt,null) |
| 263 | await f.write('update_task',{id:task.id,expectedRevision:f.store.task(task.id).revision,priority:'High'}) |
| 264 | await f.write('add_task_activity',{taskId:task.id,commentId:comment.id,text:'Changed priority to High as requested.'}) |
| 265 | await f.store.updateAgentJob(run.id,{state:'review',summary:'Changed priority to High as requested.'}) |
| 266 | saved=f.store.comments(task.id).find(item=>item.id===comment.id) |
| 267 | assert.ok(saved.actedOnAt);assert.ok(saved.activityID) |
| 268 | const activity=await f.store.dispatch('list_task_activity',{taskId:task.id,commentId:comment.id,limit:50}) |
| 269 | assert.equal(activity.commentID,comment.id) |
| 270 | assert.ok(activity.entries.some(entry=>entry.detail.includes('Priority:'))) |
| 271 | assert.ok(activity.entries.some(entry=>entry.detail.includes('Changed priority to High'))) |
| 272 | assert.ok(activity.entries.every(entry=>entry.runId===run.id)) |
| 273 | assert.ok(!activity.entries.some(entry=>entry.runId===old.id)) |
| 274 | const foreign=await f.task('Foreign task') |
| 275 | await assert.rejects(f.store.dispatch('list_task_activity',{taskId:foreign.id,commentId:comment.id}),{code:'NOT_FOUND'}) |
| 276 | }) |
| 277 | |
| 278 | test('one verified response marks two revision requests and keeps later requests open', async t => { |
| 279 | const f = fixture(t), task = await f.task('Confirm two revision requests') |
| 280 | const previous = f.previous(task, 'codex') |
| 281 | const first = await f.comment(task, 'Make the priority High.') |
| 282 | const second = await f.comment(task, 'Describe the verification in Activity.') |
| 283 | await f.store.queueCommentFollowups() |
| 284 | const run = f.store.agentJobs().find(job => job.id !== previous.id) |
| 285 | assert.deepEqual(run.commentIds, [first.id, second.id]) |
| 286 | await f.store.updateAgentJob(run.id, {state:'starting'}) |
| 287 | await f.store.updateAgentJob(run.id, {state:'working'}, {pickedUp:true}) |
| 288 | const later = await f.comment(task, 'Check the release date separately.') |
| 289 | assert.ok(f.store.comments(task.id).every(request => !request.actedOnAt)) |
| 290 | const proof = { |
| 291 | runId:run.id, state:'done', summary:'Changed priority and recorded the checks.', |
| 292 | proof:'Verified the saved priority and documented the checks in Activity.', definitionOfDoneMet:true |
| 293 | } |
| 294 | await assert.rejects(f.write('report_agent_progress', {...proof, actedOnCommentIds:[first.id]}), |
| 295 | {code:'REVISION_PROOF_REQUIRED'}) |
| 296 | const report = await f.write('report_agent_progress', {...proof, actedOnCommentIds:[first.id,second.id]}) |
| 297 | const rows = f.store.comments(task.id) |
| 298 | assert.deepEqual(rows.map(row => row.activityID), [report.completionReport.id, report.completionReport.id, null]) |
| 299 | for (const id of [first.id, second.id]) { |
| 300 | const activity = await f.store.dispatch('list_task_activity', {taskId:task.id,commentId:id}) |
| 301 | assert.ok(activity.entries.some(entry => entry.id === report.completionReport.id)) |
| 302 | } |
| 303 | assert.equal(rows.find(row => row.id === later.id).delivery, 'pending') |
| 304 | const backup = await f.write('create_backup', {format:'json'}) |
| 305 | const preview = await f.store.dispatch('preview_destructive_action', {action:'restore_backup',path:backup.path}) |
| 306 | await f.write('confirm_destructive_action', {token:preview.token}) |
| 307 | assert.deepEqual(f.store.comments(task.id).map(row => row.activityID), [report.completionReport.id, report.completionReport.id, null]) |
| 308 | }) |
| 309 | |
| 310 | test('explicit external-agent responses link to user comments and survive backups without changing comments', async t => { |
| 311 | const f=fixture(t),task=await f.task('External feedback') |
| 312 | const {comment}=await f.write('add_user_comment',{taskId:task.id,text:'Please fix the date.'}) |
| 313 | const request={taskId:task.id,commentId:comment.id,text:'Changed the due date to November 30 and verified the saved task.',requestKey:randomUUID()} |
| 314 | const report=await f.store.dispatch('add_task_activity',request) |
| 315 | assert.deepEqual(await f.store.dispatch('add_task_activity',request),report) |
| 316 | assert.equal(f.store.comments(task.id).length,1) |
| 317 | assert.equal(f.store.comments(task.id)[0].activityID,report.activity.id) |
| 318 | assert.equal((await f.store.dispatch('list_task_activity',{taskId:task.id,commentId:comment.id})).entries[0].id,report.activity.id) |
| 319 | for(const format of ['json','sqlite']) { |
| 320 | const backup=await f.write('create_backup',{format}) |
| 321 | const preview=await f.store.dispatch('preview_destructive_action',{action:'restore_backup',path:backup.path}) |
| 322 | await f.write('confirm_destructive_action',{token:preview.token}) |
| 323 | assert.equal(f.store.comments(task.id)[0].activityID,report.activity.id) |
| 324 | } |
| 325 | await assert.rejects(f.write('add_task_activity',{taskId:task.id,commentId:'missing',text:'Invalid'}),{code:'NOT_FOUND'}) |
| 326 | }) |