OpenTalon / app / native / integration.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, randomBytes } = require('node:crypto') |
| 8 | const { spawn, execFile } = require('node:child_process') |
| 9 | const { once } = require('node:events') |
| 10 | const { promisify } = require('node:util') |
| 11 | const { setTimeout: pause } = require('node:timers/promises') |
| 12 | const { Store } = require('./runtime/store.cjs') |
| 13 | const { tools } = require('./runtime/contracts.cjs') |
| 14 | const { DailyBackup } = require('./daily-backup.cjs') |
| 15 | |
| 16 | const root = process.env.OPENTALON_NATIVE_TEST_ROOT || os.tmpdir() |
| 17 | const bundle = process.env.OPENTALON_NATIVE_TEST_APP |
| 18 | const execute = promisify(execFile) |
| 19 | const pixel = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2uoAAAAASUVORK5CYII=' |
| 20 | function directory(t) { |
| 21 | const folder = fs.mkdtempSync(path.join(root, 'opentalon-native-test-')) |
| 22 | t.after(() => fs.rmSync(folder, { recursive: true, force: true })) |
| 23 | return folder |
| 24 | } |
| 25 | const request = (call, name, fields = {}) => call(name, { requestKey: randomUUID(), ...fields }) |
| 26 | |
| 27 | function mcpClient(config, messages) { |
| 28 | const contents = path.join(bundle, 'Contents') |
| 29 | return new Promise((resolve, reject) => { |
| 30 | const child = spawn(path.join(contents, 'Helpers', 'node'), [path.join(contents, 'Resources', 'service', 'mcp-bridge.cjs')], { |
| 31 | stdio: ['pipe', 'pipe', 'inherit'], env: { ...process.env, OPENTALON_MCP_CONFIG: config }, |
| 32 | }) |
| 33 | let output = '' |
| 34 | child.stdout.on('data', data => { output += data }) |
| 35 | child.on('error', reject) |
| 36 | child.on('close', code => { |
| 37 | try { |
| 38 | assert.equal(code, 0) |
| 39 | resolve(output.trim().split('\n').map(line => JSON.parse(line))) |
| 40 | } catch (error) { reject(error) } |
| 41 | }) |
| 42 | child.stdin.end(messages.map((message, index) => JSON.stringify({ jsonrpc: '2.0', id: index + 1, ...message })).join('\n') + '\n') |
| 43 | }) |
| 44 | } |
| 45 | |
| 46 | test('daily snapshots are dated, survive restart, can be restored, and recover after a destination reconnects', async (t) => { |
| 47 | const parent = directory(t) |
| 48 | const store = new Store(path.join(parent, 'native')) |
| 49 | t.after(() => store.close()) |
| 50 | const call = store.dispatch.bind(store) |
| 51 | const boardId = store.snapshot().boards[0].id |
| 52 | const { task } = await request(call, 'create_task', { boardId, title: 'Original task' }) |
| 53 | let date = new Date(2026, 10, 11, 3) |
| 54 | const schedule = new DailyBackup(store, { now: () => date }) |
| 55 | const first = await schedule.run() |
| 56 | const firstPath = path.join(first.folder, 'OpenTalon-2026-11-11.json') |
| 57 | assert.ok(fs.existsSync(firstPath)) |
| 58 | assert.equal(fs.statSync(firstPath).mode & 0o777, 0o600) |
| 59 | |
| 60 | await request(call, 'update_task', { id: task.id, expectedRevision: task.revision, title: 'Changed task' }) |
| 61 | const restarted = new DailyBackup(store, { now: () => date }) |
| 62 | await restarted.run() |
| 63 | assert.equal(fs.readdirSync(first.folder).length, 1) |
| 64 | assert.equal(JSON.parse(fs.readFileSync(firstPath)).tasks[0].title, 'Original task') |
| 65 | |
| 66 | date = new Date(2026, 10, 12, 3) |
| 67 | await restarted.run() |
| 68 | const secondPath = path.join(first.folder, 'OpenTalon-2026-11-12.json') |
| 69 | assert.equal(JSON.parse(fs.readFileSync(secondPath)).tasks[0].title, 'Changed task') |
| 70 | const preview = await call('preview_destructive_action', { action: 'restore_backup', path: firstPath }) |
| 71 | const restore = await request(call, 'confirm_destructive_action', { token: preview.token }) |
| 72 | assert.ok(fs.existsSync(restore.safetyBackup)) |
| 73 | assert.equal(store.snapshot().tasks[0].title, 'Original task') |
| 74 | |
| 75 | const separate = fs.mkdtempSync(path.join(parent, 'external-')) |
| 76 | await restarted.configure({ folder: separate }) |
| 77 | fs.rmdirSync(separate) |
| 78 | assert.match((await restarted.run()).lastError, /unavailable/) |
| 79 | assert.ok(!fs.existsSync(separate)) |
| 80 | fs.mkdirSync(separate) |
| 81 | assert.equal((await restarted.run()).lastError, '') |
| 82 | assert.equal(fs.readdirSync(separate).length, 1) |
| 83 | date = new Date(2026, 10, 13, 3) |
| 84 | await restarted.configure({ enabled: false }) |
| 85 | await restarted.run() |
| 86 | assert.equal(fs.readdirSync(separate).length, 1) |
| 87 | await restarted.run({ force: true }) |
| 88 | assert.equal(fs.readdirSync(separate).length, 2) |
| 89 | }) |
| 90 | |
| 91 | function localService(folder) { |
| 92 | const contents = path.join(bundle, 'Contents') |
| 93 | const executable = path.join(contents, 'MacOS', 'OpenTalon') |
| 94 | const child = spawn(path.join(contents, 'Helpers', 'node'), [ |
| 95 | path.join(contents, 'Resources', 'service', 'service.cjs'), folder, executable, '0.1.0', |
| 96 | ], { stdio: ['pipe', 'pipe', 'inherit'] }) |
| 97 | const closed = once(child, 'close') |
| 98 | const requests = new Map() |
| 99 | const lines = readline.createInterface({ input: child.stdout }) |
| 100 | let ready |
| 101 | let fail |
| 102 | const started = new Promise((resolve, reject) => { ready = resolve; fail = reject }) |
| 103 | lines.on('line', (line) => { |
| 104 | const response = JSON.parse(line) |
| 105 | if (response.event === 'ready') ready() |
| 106 | if (response.event === 'failed') fail(new Error(response.error.message)) |
| 107 | if (!requests.has(response.id)) return |
| 108 | const { resolve, reject } = requests.get(response.id) |
| 109 | requests.delete(response.id) |
| 110 | if (response.error) reject(Object.assign(new Error(response.error.message), response.error)) |
| 111 | else resolve(response.data) |
| 112 | }) |
| 113 | child.on('close', () => { |
| 114 | fail(new Error('Local service exited.')) |
| 115 | for (const { reject } of requests.values()) reject(new Error('Local service exited.')) |
| 116 | requests.clear() |
| 117 | }) |
| 118 | return { |
| 119 | async call(name, input = {}) { |
| 120 | await started |
| 121 | return new Promise((resolve, reject) => { |
| 122 | const id = randomUUID() |
| 123 | requests.set(id, { resolve, reject }) |
| 124 | child.stdin.write(JSON.stringify({ id, name, input }) + '\n') |
| 125 | }) |
| 126 | }, |
| 127 | async stop() { child.stdin.end(); await closed }, |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | test('MCP availability gates chat and dispatch and is projected to mobile without a task edit', { |
| 132 | skip: !bundle, timeout: 30000, |
| 133 | }, async (t) => { |
| 134 | const service = localService(directory(t)) |
| 135 | t.after(() => service.stop()) |
| 136 | await service.call('set_connection', { enabled: false }) |
| 137 | assert.equal((await service.call('get_agent_settings')).permissionMode, 'auto') |
| 138 | const before = await service.call('snapshot') |
| 139 | assert.equal(before.agentConnectionReady, false) |
| 140 | assert.equal((await service.call('native_phone_snapshot')).agentConnectionReady, false) |
| 141 | await assert.rejects(service.call('native_agent_chat', { message: 'Hello', history: [] }), { code: 'CONNECTION_DISABLED' }) |
| 142 | await assert.rejects(service.call('native_draft_task', { idea: 'Review the release' }), { code: 'MCP_DISABLED' }) |
| 143 | await assert.rejects(service.call('check_task_comments'), { code: 'MCP_DISABLED' }) |
| 144 | await service.call('set_connection', { enabled: true }) |
| 145 | assert.equal((await service.call('snapshot')).agentConnectionReady, true) |
| 146 | assert.equal((await service.call('native_phone_snapshot')).agentConnectionReady, true) |
| 147 | assert.equal((await service.call('snapshot')).revision, before.revision) |
| 148 | await service.call('set_connection', { enabled: false }) |
| 149 | assert.equal((await service.call('snapshot')).agentConnectionReady, false) |
| 150 | assert.equal((await service.call('native_phone_snapshot')).agentConnectionReady, false) |
| 151 | const { task } = await service.call('create_task', { requestKey: randomUUID(), boardId: before.boards[0].id, title: 'Manual task' }) |
| 152 | await assert.rejects(service.call('move_task', { requestKey: randomUUID(), id: task.id, expectedRevision: task.revision, |
| 153 | boardId: task.boardId, status: 'Sent to agent' }), { code: 'MCP_DISABLED' }) |
| 154 | const done = await service.call('move_task', { requestKey: randomUUID(), id: task.id, expectedRevision: task.revision, |
| 155 | boardId: task.boardId, status: 'Done' }) |
| 156 | assert.equal(done.task.status, 'Done') |
| 157 | }) |
| 158 | |
| 159 | test('packaged MCP model edits persist and reach the mobile snapshot without changing a task', { |
| 160 | skip: !bundle, timeout: 30000, |
| 161 | }, async t => { |
| 162 | const folder = fs.mkdtempSync(path.join(root, 'opentalon-native-models-')) |
| 163 | let service = localService(folder) |
| 164 | t.after(async () => { |
| 165 | await service.stop() |
| 166 | fs.rmSync(folder, { recursive: true, force: true }) |
| 167 | }) |
| 168 | await service.call('set_connection', { enabled: true }) |
| 169 | const before = await service.call('snapshot') |
| 170 | const config = path.join(folder, 'mcp.json') |
| 171 | const call = async (name, args = {}) => { |
| 172 | const [reply] = await mcpClient(config, [{ method: 'tools/call', params: { name, arguments: args } }]) |
| 173 | assert.ok(!reply.error && !reply.result.isError, JSON.stringify(reply)) |
| 174 | return reply.result.structuredContent |
| 175 | } |
| 176 | const catalog = await call('get_agent_models') |
| 177 | const overrides = [ |
| 178 | { agent: 'codex', id: 'gpt-6.2-sol', title: 'My Sol' }, |
| 179 | { agent: 'claude-code', id: 'claude-haiku-5-5', title: 'Haiku', hidden: true }, |
| 180 | { agent: 'codex', id: 'custom-model', title: 'My custom model' }, |
| 181 | ] |
| 182 | const saved = await call('set_agent_models', { |
| 183 | requestKey: randomUUID(), expectedCatalogRevision: catalog.catalogRevision, overrides, |
| 184 | }) |
| 185 | assert.equal(saved.catalogRevision, catalog.catalogRevision + 1) |
| 186 | const phone = await service.call('native_phone_snapshot') |
| 187 | assert.ok(phone.availableAgents.includes('codex'), 'This integration fixture requires the installed Codex runtime') |
| 188 | assert.equal(phone.agentModels.find(x => x.id === 'gpt-6.2-sol').title, 'My Sol') |
| 189 | assert.ok(phone.agentModels.some(x => x.id === 'custom-model')) |
| 190 | assert.ok(!phone.agentModels.some(x => x.id === 'claude-haiku-5-5')) |
| 191 | assert.deepEqual((await service.call('snapshot')).tasks, before.tasks) |
| 192 | const projectFolder = path.join(folder, 'Project work') |
| 193 | fs.mkdirSync(projectFolder) |
| 194 | const board = before.boards[0] |
| 195 | const selected = await call('set_project_folder', { |
| 196 | requestKey: randomUUID(), id: board.id, expectedRevision: board.revision, workingFolder: projectFolder, |
| 197 | }) |
| 198 | assert.equal(selected.effectiveFolder, projectFolder) |
| 199 | assert.equal((await service.call('native_agent_options', { boardId: board.id })).workingFolder, projectFolder) |
| 200 | await service.stop() |
| 201 | service = localService(folder) |
| 202 | const after = await service.call('native_phone_snapshot') |
| 203 | assert.deepEqual(after.agentModels, phone.agentModels) |
| 204 | assert.equal((await call('get_agent_models')).catalogRevision, saved.catalogRevision) |
| 205 | assert.equal((await call('get_project_folder', { id: board.id })).workingFolder, projectFolder) |
| 206 | }) |
| 207 | |
| 208 | test('packaged local service copies a live WAL database and restores portable JSON with screenshots and Trash', { |
| 209 | skip: !bundle, timeout: 30000, |
| 210 | }, async (t) => { |
| 211 | const parent = directory(t) |
| 212 | const previous = new Store(path.join(parent, 'OpenTalon Prototype')) |
| 213 | const old = previous.dispatch.bind(previous) |
| 214 | const boardId = previous.snapshot().boards[0].id |
| 215 | const { task } = await request(old, 'create_task', { |
| 216 | boardId, title: 'Legacy task', notes: 'Old notes', priority: 'Urgent', |
| 217 | definitionOfDone: 'Verify migration', dueDate: '2026-11-11', |
| 218 | }) |
| 219 | const { task: discarded } = await request(old, 'create_task', { boardId, title: 'Recoverable' }) |
| 220 | await request(old, 'trash_task', { id: discarded.id, expectedRevision: discarded.revision }) |
| 221 | await request(old, 'add_user_comment', { |
| 222 | taskId: task.id, text: 'Screenshot', images: [{ name: 'pixel.png', mimeType: 'image/png', data: pixel }], |
| 223 | }) |
| 224 | assert.ok(fs.existsSync(previous.file + '-wal')) |
| 225 | |
| 226 | const local = localService(path.join(parent, 'OpenTalon Native')) |
| 227 | t.after(async () => { await local.stop(); previous.close() }) |
| 228 | const call = local.call |
| 229 | const preview = await call('native_preview_electron') |
| 230 | assert.equal(preview.summary.tasks, 1) |
| 231 | assert.equal(preview.summary.trash, 1) |
| 232 | const restore = await request(call, 'confirm_destructive_action', { token: preview.token }) |
| 233 | assert.ok(fs.existsSync(restore.safetyBackup)) |
| 234 | assert.equal(previous.snapshot().tasks.length, 2) |
| 235 | const state = await call('snapshot') |
| 236 | assert.deepEqual(state.agentAssignments, {}) |
| 237 | assert.equal(state.tasks.find((item) => item.id === task.id).dueDate, '2026-11-11') |
| 238 | const { comments } = await call('list_task_comments', { taskId: task.id }) |
| 239 | const image = await call('read_comment_image', { imageId: comments[0].images[0].id }) |
| 240 | assert.equal(image.data, pixel) |
| 241 | const rejected = await call('get_task', { id: task.id }) |
| 242 | await assert.rejects(request(call, 'move_task', { |
| 243 | id: task.id, expectedRevision: rejected.task.revision, status: 'Sent to agent', |
| 244 | }), { code: 'MCP_DISABLED' }) |
| 245 | const file = path.join(parent, 'portable.json') |
| 246 | await request(call, 'create_backup', { destination: file, format: 'json' }) |
| 247 | assert.equal(JSON.parse(fs.readFileSync(file)).format, 'opentalon-backup') |
| 248 | const imported = await call('preview_destructive_action', { action: 'restore_backup', path: file }) |
| 249 | await request(call, 'confirm_destructive_action', { token: imported.token }) |
| 250 | const removal = await call('preview_destructive_action', { action: 'empty_trash' }) |
| 251 | assert.equal(removal.summary.tasks[0].title, 'Recoverable') |
| 252 | assert.equal((await call('snapshot')).tasks.length, 2) |
| 253 | }) |
| 254 | |
| 255 | test('Settings connection test uses the bundled MCP bridge and reports an unavailable configuration', { |
| 256 | skip: !bundle, timeout: 30000, |
| 257 | }, async (t) => { |
| 258 | const folder = fs.mkdtempSync(path.join(root, 'opentalon-native-test-')) |
| 259 | const service = localService(folder) |
| 260 | t.after(async () => { |
| 261 | try { await service.stop() } |
| 262 | finally { fs.rmSync(folder, { recursive: true, force: true }) } |
| 263 | }) |
| 264 | await assert.rejects(service.call('native_test_connection'), { code: 'CONNECTION_DISABLED' }) |
| 265 | await service.call('set_connection', { enabled: true }) |
| 266 | const status = await service.call('get_app_status') |
| 267 | assert.deepEqual(await service.call('native_test_connection'), {}) |
| 268 | assert.equal((await service.call('get_app_status')).revision, status.revision) |
| 269 | fs.renameSync(path.join(folder, 'mcp.json'), path.join(folder, 'mcp.saved.json')) |
| 270 | await assert.rejects(service.call('native_test_connection'), { code: 'CONNECTION_TEST_FAILED' }) |
| 271 | }) |
| 272 | |
| 273 | test('bundled stdio bridge starts the native application in the background and exposes the full tool contract', { |
| 274 | skip: !bundle, timeout: 30000, |
| 275 | }, async (t) => { |
| 276 | const folder = fs.mkdtempSync(path.join(root, 'opentalon-native-test-')) |
| 277 | let appPID |
| 278 | t.after(async () => { |
| 279 | try { |
| 280 | if (!appPID) return |
| 281 | try { process.kill(appPID, 'SIGTERM') } catch { return } |
| 282 | for (let attempt = 0; attempt < 40; attempt++) { |
| 283 | try { process.kill(appPID, 0) } catch { return } |
| 284 | await pause(50) |
| 285 | } |
| 286 | // Never leave an isolated app running if this test fails to shut it down. |
| 287 | try { process.kill(appPID, 'SIGKILL') } catch {} |
| 288 | assert.fail('The native background app did not shut down cleanly.') |
| 289 | } finally { |
| 290 | fs.rmSync(folder, { recursive: true, force: true }) |
| 291 | } |
| 292 | }) |
| 293 | const contents = path.join(bundle, 'Contents') |
| 294 | const executable = path.join(contents, 'MacOS', 'OpenTalon') |
| 295 | const bridge = path.join(contents, 'Resources', 'service', 'mcp-bridge.cjs') |
| 296 | const config = path.join(folder, 'mcp.json') |
| 297 | const runtime = path.join(contents, 'Helpers', 'node') |
| 298 | const store = new Store(folder) |
| 299 | store.close() |
| 300 | fs.writeFileSync(config, JSON.stringify({ |
| 301 | enabled: true, token: randomBytes(32).toString('hex'), port: 0, executable, launchArgs: [], profile: folder, |
| 302 | }), { mode: 0o600 }) |
| 303 | const client = (messages) => new Promise((resolve, reject) => { |
| 304 | const child = spawn(runtime, [bridge], { |
| 305 | stdio: ['pipe', 'pipe', 'inherit'], |
| 306 | env: { ...process.env, OPENTALON_MCP_CONFIG: config }, |
| 307 | }) |
| 308 | let output = '' |
| 309 | child.stdout.on('data', (data) => { output += data }) |
| 310 | child.on('error', reject) |
| 311 | child.on('close', (code) => { |
| 312 | try { |
| 313 | assert.equal(code, 0) |
| 314 | resolve(output.trim().split('\n').map((line) => JSON.parse(line))) |
| 315 | } catch (error) { reject(error) } |
| 316 | }) |
| 317 | child.stdin.end(messages.map((message, index) => JSON.stringify({ jsonrpc: '2.0', id: index + 1, ...message })).join('\n') + '\n') |
| 318 | }) |
| 319 | const [result, list] = await client([ |
| 320 | { method: 'tools/call', params: { name: 'get_app_status', arguments: {} } }, |
| 321 | { method: 'tools/list' }, |
| 322 | ]) |
| 323 | assert.ok(!result.error && !result.result.isError, JSON.stringify(result)) |
| 324 | const status = result.result.structuredContent |
| 325 | assert.equal(status.dataLocation, folder) |
| 326 | assert.ok(Number.isInteger(status.processId)) |
| 327 | appPID = status.processId |
| 328 | assert.deepEqual(list.result.tools.map(tool => tool.name), tools.map(tool => tool.name)) |
| 329 | assert.equal(status.windowOpen, false) |
| 330 | }) |
| 331 | |
| 332 | test('native backup-only executable writes a daily file without touching MCP config', { |
| 333 | skip: !bundle, timeout: 15000, |
| 334 | }, async (t) => { |
| 335 | const folder = directory(t) |
| 336 | const store = new Store(folder) |
| 337 | const boardId = store.snapshot().boards[0].id |
| 338 | await request(store.dispatch.bind(store), 'create_task', { boardId, title: 'Backup in the background' }) |
| 339 | store.close() |
| 340 | const executable = path.join(bundle, 'Contents', 'MacOS', 'OpenTalon') |
| 341 | await execute(executable, ['--daily-backup'], { |
| 342 | env: { ...process.env, OPENTALON_PROFILE: folder }, |
| 343 | }) |
| 344 | const files = fs.readdirSync(path.join(folder, 'Backups', 'Daily')) |
| 345 | assert.equal(files.length, 1) |
| 346 | const backup = JSON.parse(fs.readFileSync(path.join(folder, 'Backups', 'Daily', files[0]))) |
| 347 | assert.equal(backup.tasks[0].title, 'Backup in the background') |
| 348 | assert.equal(fs.existsSync(path.join(folder, 'mcp.json')), false) |
| 349 | }) |