OpenTalon / app / native / runtime / task-activity.cjs
| 1 | const { randomUUID } = require('node:crypto') |
| 2 | const { AppError } = require('./contracts.cjs') |
| 3 | const { agentNames } = require('./agent-models.cjs') |
| 4 | const { imageBytes } = require('./comments.cjs') |
| 5 | |
| 6 | function record( |
| 7 | store, |
| 8 | taskId, |
| 9 | { |
| 10 | id = randomUUID(), |
| 11 | at = new Date().toISOString(), |
| 12 | actor = 'OpenTalon', |
| 13 | kind = 'update', |
| 14 | summary, |
| 15 | detail = '', |
| 16 | legacyCommentID = null, |
| 17 | data = {} |
| 18 | }, |
| 19 | images = [] |
| 20 | ) { |
| 21 | const normalized = images.map((image) => ({ ...image, bytes: imageBytes(image) })) |
| 22 | const inserted = store.db |
| 23 | .prepare( |
| 24 | `INSERT OR IGNORE INTO task_activity |
| 25 | (id,task_id,saved_at,actor,kind,summary,detail,legacy_comment_id,data) VALUES (?,?,?,?,?,?,?,?,?)` |
| 26 | ) |
| 27 | .run(id, taskId, at, actor, kind, summary, detail, legacyCommentID, JSON.stringify(data)) |
| 28 | if (inserted.changes) |
| 29 | for (const image of normalized) |
| 30 | store.db |
| 31 | .prepare('INSERT INTO activity_images VALUES (?,?,?,?,?)') |
| 32 | .run(image.id || randomUUID(), id, image.name, image.mimeType, image.bytes) |
| 33 | return entry(store, store.db.prepare('SELECT * FROM task_activity WHERE id=?').get(id)) |
| 34 | } |
| 35 | |
| 36 | function entry(store, row) { |
| 37 | const images = store.db |
| 38 | .prepare('SELECT id,name,mime_type FROM activity_images WHERE activity_id=?') |
| 39 | .all(row.id) |
| 40 | if (row.legacy_comment_id) |
| 41 | images.push( |
| 42 | ...store.db |
| 43 | .prepare('SELECT id,name,mime_type FROM comment_images WHERE comment_id=?') |
| 44 | .all(row.legacy_comment_id) |
| 45 | ) |
| 46 | return { |
| 47 | ...JSON.parse(row.data), |
| 48 | id: row.id, |
| 49 | taskId: row.task_id, |
| 50 | sequence: row.sequence, |
| 51 | createdAt: row.saved_at, |
| 52 | actor: row.actor, |
| 53 | kind: row.kind, |
| 54 | summary: row.summary, |
| 55 | detail: row.detail, |
| 56 | text: row.detail, |
| 57 | images: images.map((image) => ({ id: image.id, name: image.name, mimeType: image.mime_type })) |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | function page(store, id, beforeSequence, limit = 20, commentID) { |
| 62 | const task = store.task(id) |
| 63 | let filter = '', |
| 64 | parameters = [] |
| 65 | if (commentID) { |
| 66 | const comment = store |
| 67 | .comments(task.id) |
| 68 | .find((item) => item.id === commentID && item.source === 'user') |
| 69 | if (!comment) throw new AppError('NOT_FOUND', 'This revision request is no longer available.') |
| 70 | // Only the comment's own assigned run and explicit responses belong in this drill-down. |
| 71 | filter = " AND (json_extract(data,'$.commentID')=? OR EXISTS (SELECT 1 FROM json_each(data,'$.commentIDs') WHERE value=?) OR json_extract(data,'$.runId')=? OR id=?)" |
| 72 | parameters = [commentID, commentID, comment.runId || '', comment.activityID || ''] |
| 73 | } |
| 74 | const rows = store.db |
| 75 | .prepare( |
| 76 | 'SELECT * FROM task_activity WHERE task_id=? AND sequence<?' + |
| 77 | filter + |
| 78 | ' ORDER BY sequence DESC LIMIT ?' |
| 79 | ) |
| 80 | .all(task.id, beforeSequence ?? Number.MAX_SAFE_INTEGER, ...parameters, limit + 1) |
| 81 | return { |
| 82 | taskID: task.id, |
| 83 | revision: store.revision(), |
| 84 | ...(commentID ? { commentID } : {}), |
| 85 | entries: rows.slice(0, limit).map((row) => entry(store, row)), |
| 86 | nextBefore: rows.length > limit ? rows[limit - 1].sequence : null |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | function recordHistory(store, taskId, row, value, previous, changes) { |
| 91 | const labels = { |
| 92 | title: 'Title', |
| 93 | notes: 'Notes', |
| 94 | definitionOfDone: 'Definition of done', |
| 95 | planMarkdown: 'Plan', |
| 96 | issueType: 'Issue type', |
| 97 | projectName: 'Project', |
| 98 | status: 'Status', |
| 99 | priority: 'Priority', |
| 100 | dueDate: 'Due date', |
| 101 | position: 'Order', |
| 102 | archived: 'Archive', |
| 103 | trashed: 'Trash' |
| 104 | } |
| 105 | let summary |
| 106 | if (row.action === 'history_started') summary = 'Task history started' |
| 107 | else if (!previous) summary = 'Task created' |
| 108 | else if (row.action === 'rename_board') summary = 'Project renamed' |
| 109 | else if (row.action === 'restore_task_revision') summary = 'Restored a previous revision' |
| 110 | else if (changes.includes('trashed')) |
| 111 | summary = value.trashed ? 'Moved task to Trash' : 'Restored task from Trash' |
| 112 | else if (changes.includes('archived')) |
| 113 | summary = value.archived ? 'Archived task' : 'Restored task from Archive' |
| 114 | else if (changes.includes('projectID')) |
| 115 | summary = `Moved from ${previous.projectName} to ${value.projectName}` |
| 116 | else if (changes.includes('status')) summary = `Moved from ${previous.status} to ${value.status}` |
| 117 | else |
| 118 | summary = |
| 119 | changes |
| 120 | .filter((key) => labels[key]) |
| 121 | .map((key) => labels[key]) |
| 122 | .join(', ') + ' updated' |
| 123 | const details = changes |
| 124 | .filter((key) => labels[key]) |
| 125 | .map((key) => { |
| 126 | if (['notes', 'definitionOfDone', 'planMarkdown'].includes(key)) |
| 127 | return labels[key] + ' edited. Previous versions remain in revision history.' |
| 128 | if (key === 'position') |
| 129 | return `Order: ${(previous?.position ?? 0) + 1} → ${value.position + 1}` |
| 130 | const display = (v) => (v === null || v === undefined ? 'None' : String(v).slice(0, 500)) |
| 131 | return previous |
| 132 | ? `${labels[key]}: ${display(previous[key])} → ${display(value[key])}` |
| 133 | : `${labels[key]}: ${display(value[key])}` |
| 134 | }) |
| 135 | .join('\n') |
| 136 | record(store, taskId, { |
| 137 | id: 'history:' + row.id, |
| 138 | at: row.savedAt, |
| 139 | actor: row.origin || 'OpenTalon', |
| 140 | kind: 'change', |
| 141 | summary, |
| 142 | detail: details, |
| 143 | data: {historyID: row.id, ...(row.runId ? {runId:row.runId} : {})} |
| 144 | }) |
| 145 | } |
| 146 | |
| 147 | function migrateMessages(store) { |
| 148 | for (const row of store.db.prepare('SELECT * FROM task_comments ORDER BY rowid').all()) { |
| 149 | const comment = JSON.parse(row.data) |
| 150 | if (comment.agent && comment.source !== 'user') { |
| 151 | const images = store.db |
| 152 | .prepare('SELECT * FROM comment_images WHERE comment_id=?') |
| 153 | .all(row.id) |
| 154 | .map((image) => ({ |
| 155 | id: image.id, |
| 156 | name: image.name, |
| 157 | mimeType: image.mime_type, |
| 158 | data: Buffer.from(image.bytes).toString('base64') |
| 159 | })) |
| 160 | record( |
| 161 | store, |
| 162 | row.task_id, |
| 163 | { |
| 164 | id: 'message:' + row.id, |
| 165 | at: comment.createdAt, |
| 166 | actor: agentNames[comment.agent] ?? 'Claude', |
| 167 | kind: 'agent', |
| 168 | summary: 'Earlier agent report', |
| 169 | detail: comment.text, |
| 170 | data: { agent: comment.agent, runId: comment.runId } |
| 171 | }, |
| 172 | images |
| 173 | ) |
| 174 | store.db.prepare('DELETE FROM task_comments WHERE id=?').run(row.id) |
| 175 | } else if (comment.source !== 'user') { |
| 176 | record(store, row.task_id, { |
| 177 | id: 'message:' + row.id, |
| 178 | at: comment.createdAt, |
| 179 | actor: 'Earlier message', |
| 180 | kind: 'legacy', |
| 181 | summary: 'Earlier task message', |
| 182 | detail: comment.text, |
| 183 | legacyCommentID: row.id |
| 184 | }) |
| 185 | store.db |
| 186 | .prepare('UPDATE task_comments SET data=? WHERE id=?') |
| 187 | .run(JSON.stringify({ ...comment, source: 'legacy' }), row.id) |
| 188 | } |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | function backfillHistory(store) { |
| 193 | const previous = new Map() |
| 194 | for (const row of store.db |
| 195 | .prepare('SELECT * FROM task_history ORDER BY saved_at,task_id,version') |
| 196 | .all()) { |
| 197 | const value = JSON.parse(row.state_json) |
| 198 | recordHistory( |
| 199 | store, |
| 200 | row.task_id, |
| 201 | { id: row.id, savedAt: row.saved_at, origin: row.origin, action: row.action }, |
| 202 | value, |
| 203 | previous.get(row.task_id), |
| 204 | JSON.parse(row.changes_json) |
| 205 | ) |
| 206 | previous.set(row.task_id, value) |
| 207 | } |
| 208 | } |
| 209 | function chronologicalOrder(store) { |
| 210 | const rows = store.db.prepare('SELECT id FROM task_activity ORDER BY saved_at,sequence').all() |
| 211 | store.db.exec('UPDATE task_activity SET sequence=-sequence') |
| 212 | rows.forEach((row, index) => |
| 213 | store.db.prepare('UPDATE task_activity SET sequence=? WHERE id=?').run(index + 1, row.id) |
| 214 | ) |
| 215 | } |
| 216 | |
| 217 | function migrate(store) { |
| 218 | store.db.exec('BEGIN IMMEDIATE') |
| 219 | try { |
| 220 | store.db.exec(`CREATE TABLE task_activity ( |
| 221 | sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, |
| 222 | task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE, saved_at TEXT NOT NULL, |
| 223 | actor TEXT NOT NULL,kind TEXT NOT NULL,summary TEXT NOT NULL,detail TEXT NOT NULL, |
| 224 | legacy_comment_id TEXT REFERENCES task_comments(id) ON DELETE SET NULL,data TEXT NOT NULL) STRICT; |
| 225 | CREATE INDEX activity_task ON task_activity(task_id,sequence); |
| 226 | CREATE TABLE activity_images(id TEXT PRIMARY KEY,activity_id TEXT NOT NULL REFERENCES task_activity(id) ON DELETE CASCADE,name TEXT NOT NULL,mime_type TEXT NOT NULL,bytes BLOB NOT NULL) STRICT; |
| 227 | PRAGMA user_version=11;`) |
| 228 | backfillHistory(store) |
| 229 | migrateMessages(store) |
| 230 | chronologicalOrder(store) |
| 231 | store.db.prepare('INSERT INTO schema_migrations VALUES (?,?)').run(11, new Date().toISOString()) |
| 232 | store.db.exec('COMMIT') |
| 233 | } catch (error) { |
| 234 | store.db.exec('ROLLBACK') |
| 235 | throw error |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | function exportRows(store) { |
| 240 | return { |
| 241 | activity: store.db.prepare('SELECT * FROM task_activity ORDER BY sequence').all(), |
| 242 | activityImages: store.db |
| 243 | .prepare('SELECT * FROM activity_images ORDER BY rowid') |
| 244 | .all() |
| 245 | .map((row) => ({ ...row, data: Buffer.from(row.bytes).toString('base64'), bytes: undefined })) |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | function validateRows(rows, images, tasks, comments) { |
| 250 | const bad = () => { |
| 251 | throw new AppError('INVALID_BACKUP', 'This backup contains invalid task activity.') |
| 252 | } |
| 253 | if (!Array.isArray(rows) || !Array.isArray(images)) bad() |
| 254 | const taskIDs = new Set(tasks.map((task) => task.id)), |
| 255 | commentIDs = new Map(comments.map((comment) => [comment.id, comment.taskId])), |
| 256 | ids = new Set(), |
| 257 | sequences = new Set(), |
| 258 | imageIDs = new Set() |
| 259 | const text = (v, max) => |
| 260 | typeof v === 'string' && v.length <= max && v.isWellFormed() && !v.includes('\0') |
| 261 | for (const row of rows) { |
| 262 | if ( |
| 263 | !row || |
| 264 | !text(row.id, 200) || |
| 265 | !row.id || |
| 266 | ids.has(row.id) || |
| 267 | !taskIDs.has(row.task_id) || |
| 268 | !Number.isSafeInteger(row.sequence) || |
| 269 | row.sequence < 1 || |
| 270 | sequences.has(row.sequence) || |
| 271 | !Number.isFinite(Date.parse(row.saved_at)) || |
| 272 | !text(row.actor, 100) || |
| 273 | !text(row.kind, 50) || |
| 274 | !text(row.summary, 1000) || |
| 275 | !text(row.detail, 10000) || |
| 276 | !(row.legacy_comment_id === null || commentIDs.get(row.legacy_comment_id) === row.task_id) || |
| 277 | !text(row.data, 20000) |
| 278 | ) |
| 279 | bad() |
| 280 | let data |
| 281 | try { |
| 282 | data = JSON.parse(row.data) |
| 283 | } catch { |
| 284 | bad() |
| 285 | } |
| 286 | if ( |
| 287 | !data || |
| 288 | Array.isArray(data) || |
| 289 | typeof data !== 'object' || |
| 290 | Object.entries(data).some( |
| 291 | ([key, value]) => key === 'commentIDs' |
| 292 | ? !Array.isArray(value) || value.length < 1 || value.length > 50 || |
| 293 | new Set(value).size !== value.length || |
| 294 | value.some((id) => !text(id, 200) || commentIDs.get(id) !== row.task_id) |
| 295 | : !['agent', 'runId', 'historyID', 'commentID'].includes(key) || |
| 296 | !(value === null || text(value, 200)) |
| 297 | ) |
| 298 | ) |
| 299 | bad() |
| 300 | if (data.commentID != null && commentIDs.get(data.commentID) !== row.task_id) bad() |
| 301 | ids.add(row.id) |
| 302 | sequences.add(row.sequence) |
| 303 | } |
| 304 | for (const image of images) { |
| 305 | if ( |
| 306 | !image || |
| 307 | !ids.has(image.activity_id) || |
| 308 | !text(image.id, 150) || |
| 309 | !image.id || |
| 310 | imageIDs.has(image.id) |
| 311 | ) |
| 312 | bad() |
| 313 | imageBytes({ name: image.name, mimeType: image.mime_type, data: image.data }) |
| 314 | imageIDs.add(image.id) |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | function restoreRows(store, rows, images) { |
| 319 | for (const row of rows) |
| 320 | store.db |
| 321 | .prepare('INSERT INTO task_activity VALUES (?,?,?,?,?,?,?,?,?,?)') |
| 322 | .run( |
| 323 | row.sequence, |
| 324 | row.id, |
| 325 | row.task_id, |
| 326 | row.saved_at, |
| 327 | row.actor, |
| 328 | row.kind, |
| 329 | row.summary, |
| 330 | row.detail, |
| 331 | row.legacy_comment_id, |
| 332 | row.data |
| 333 | ) |
| 334 | for (const image of images) |
| 335 | store.db |
| 336 | .prepare('INSERT INTO activity_images VALUES (?,?,?,?,?)') |
| 337 | .run( |
| 338 | image.id, |
| 339 | image.activity_id, |
| 340 | image.name, |
| 341 | image.mime_type, |
| 342 | imageBytes({ name: image.name, mimeType: image.mime_type, data: image.data }) |
| 343 | ) |
| 344 | backfillHistory(store) |
| 345 | migrateMessages(store) |
| 346 | chronologicalOrder(store) |
| 347 | } |
| 348 | module.exports = { |
| 349 | record, |
| 350 | recordHistory, |
| 351 | page, |
| 352 | migrate, |
| 353 | exportRows, |
| 354 | validateRows, |
| 355 | restoreRows, |
| 356 | migrateMessages |
| 357 | } |