Branchwell

OpenTalon / app / native / runtime / comments.cjs

1const { AppError } = require('./contracts.cjs')
2const { agentIds } = require('./agent-models.cjs')
3const { randomUUID } = require('node:crypto')
4const MAX_IMAGE_BYTES = 2 * 1024 * 1024
5function imageBytes(image) {
6 if (
7 !image ||
8 typeof image.name !== 'string' ||
9 image.name.length > 200 ||
10 !['image/png', 'image/jpeg'].includes(image.mimeType) ||
11 typeof image.data !== 'string' ||
12 !/^[A-Za-z0-9+/]*={0,2}$/.test(image.data)
13 )
14 throw new AppError('INVALID_IMAGE', 'Attach a PNG or JPEG screenshot.')
15 const bytes = Buffer.from(image.data, 'base64')
16 const png = bytes.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'))
17 const jpeg = bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff
18 if (
19 !bytes.length ||
20 bytes.length > MAX_IMAGE_BYTES ||
21 !(image.mimeType === 'image/png' ? png : jpeg)
22 )
23 throw new AppError('INVALID_IMAGE', 'Each screenshot must be a valid PNG or JPEG under 2 MB.')
24 return bytes
25}
26function comments(store, taskId) {
27 return store.db
28 .prepare('SELECT * FROM task_comments WHERE task_id=? ORDER BY rowid')
29 .all(taskId)
30 .map((row) => ({
31 id: row.id,
32 taskId: row.task_id,
33 ...JSON.parse(row.data),
34 ...commentActivity(store, row),
35 images: store.db
36 .prepare('SELECT id,name,mime_type FROM comment_images WHERE comment_id=? ORDER BY rowid')
37 .all(row.id)
38 .map((image) => ({ id: image.id, name: image.name, mimeType: image.mime_type }))
39 }))
40}
41function commentActivity(store, row) {
42 const comment = JSON.parse(row.data)
43 if (!store.activityReady || comment.source !== 'user') return {}
44 let activity =
45 comment.actedOnActivityID &&
46 store.db
47 .prepare(
48 "SELECT id,saved_at FROM task_activity WHERE id=? AND task_id=? AND (json_extract(data,'$.commentID')=? OR EXISTS (SELECT 1 FROM json_each(data,'$.commentIDs') WHERE value=?))"
49 )
50 .get(comment.actedOnActivityID, row.task_id, row.id, row.id)
51 const jobRow =
52 comment.runId &&
53 store.db
54 .prepare('SELECT data FROM agent_jobs WHERE id=? AND task_id=?')
55 .get(comment.runId, row.task_id)
56 const job = jobRow ? JSON.parse(jobRow.data) : null
57 if (
58 !activity &&
59 job?.requiresRevisionReceipts !== true &&
60 comment.delivery === 'delivered' &&
61 ['done', 'review'].includes(job?.state) &&
62 job.summary?.trim() &&
63 !/^The agent (ended its turn|finished its response)/.test(job.summary)
64 )
65 activity = store.db
66 .prepare(
67 "SELECT id,saved_at FROM task_activity WHERE task_id=? AND kind='agent' AND json_extract(data,'$.runId')=? ORDER BY sequence DESC LIMIT 1"
68 )
69 .get(row.task_id, comment.runId)
70 return {
71 activityState: job?.state || null,
72 activityID: activity?.id || null,
73 actedOnAt: activity?.saved_at || null
74 }
75}
76
77function insertComment(store, taskId, text, images = [], notifyAgent = false, author = {}) {
78 const task = store.task(taskId)
79 if (task.deleted) throw new AppError('IN_TRASH', 'Restore the task before sending a revision request.')
80 if (!text.trim() && !images.length)
81 throw new AppError('EMPTY_COMMENT', 'Describe the change you want or attach a screenshot.')
82 const normalized = images.map((image) => ({ ...image, bytes: imageBytes(image) }))
83 const id = author.clientId === undefined ? randomUUID() : clientRevisionId(store, taskId, author.clientId)
84 store.db.prepare('INSERT INTO task_comments VALUES (?,?,?)').run(
85 id,
86 taskId,
87 JSON.stringify({
88 text,
89 source: 'user',
90 createdAt: new Date().toISOString(),
91 delivery: notifyAgent && !task.archivedAt && store.assignedRun(taskId) ? 'pending' : 'local',
92 runId: author.runId || null,
93 agent: author.agent || null
94 })
95 )
96 for (const image of normalized)
97 store.db
98 .prepare('INSERT INTO comment_images VALUES (?,?,?,?,?)')
99 .run(randomUUID(), id, image.name, image.mimeType, image.bytes)
100 if (store.activityReady)
101 require('./task-activity.cjs').record(store, taskId, {
102 actor: author.actor || 'You',
103 kind: 'comment',
104 summary: 'Saved a revision request'
105 })
106 return comments(store, taskId).find((comment) => comment.id === id)
107}
108const revisionIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
109// A device names its own request, so the ID must be a fresh UUID that was not withdrawn in transit.
110function clientRevisionId(store, taskId, value) {
111 const id = String(value).toLowerCase()
112 if (!revisionIdPattern.test(id))
113 throw new AppError('INVALID_ARGUMENT', 'Use a UUID for the revision request ID.')
114 if (store.withdrawnRevision(id)?.taskId === taskId)
115 throw new AppError('WITHDRAWN', 'This revision request was withdrawn before it reached your Mac.')
116 if (store.db.prepare('SELECT 1 FROM task_comments WHERE id=?').get(id))
117 throw new AppError('CONFLICT', 'This revision request is already saved.')
118 return id
119}
120function exportComments(store) {
121 return {
122 comments: store.db
123 .prepare('SELECT * FROM task_comments ORDER BY rowid')
124 .all()
125 .map((row) => ({ id: row.id, taskId: row.task_id, ...JSON.parse(row.data) })),
126 commentImages: store.db
127 .prepare('SELECT * FROM comment_images ORDER BY rowid')
128 .all()
129 .map((row) => ({
130 id: row.id,
131 commentId: row.comment_id,
132 name: row.name,
133 mimeType: row.mime_type,
134 data: Buffer.from(row.bytes).toString('base64')
135 }))
136 }
137}
138function validateComments(records, images, tasks) {
139 if (
140 !Array.isArray(records) ||
141 !Array.isArray(images) ||
142 new Set(records.map((row) => row?.id)).size !== records.length ||
143 new Set(images.map((row) => row?.id)).size !== images.length
144 )
145 throw new AppError('INVALID_BACKUP', 'Invalid revision request or screenshot records.')
146 const taskIds = new Set(tasks.map((task) => task.id))
147 const ids = new Set()
148 for (const row of records) {
149 if (
150 !row ||
151 typeof row.id !== 'string' ||
152 !row.id.length ||
153 row.id.length > 150 ||
154 !taskIds.has(row.taskId) ||
155 typeof row.text !== 'string' ||
156 row.text.length > 10000 ||
157 !Number.isFinite(Date.parse(row.createdAt)) ||
158 !(row.source === undefined || ['user', 'legacy'].includes(row.source)) ||
159 !(
160 row.actedOnActivityID === undefined ||
161 (typeof row.actedOnActivityID === 'string' && row.actedOnActivityID.length <= 200)
162 ) ||
163 !['pending', 'queued', 'delivered', 'needs-review', 'local'].includes(row.delivery) ||
164 !(row.runId === null || typeof row.runId === 'string') ||
165 !(row.agent === null || agentIds.includes(row.agent))
166 )
167 throw new AppError('INVALID_BACKUP', 'Invalid revision request data.')
168 ids.add(row.id)
169 }
170 const counts = new Map()
171 for (const image of images) {
172 if (
173 !image ||
174 typeof image.id !== 'string' ||
175 !image.id.length ||
176 image.id.length > 150 ||
177 !ids.has(image.commentId)
178 )
179 throw new AppError('INVALID_BACKUP', 'A screenshot has no matching revision request.')
180 imageBytes(image)
181 counts.set(image.commentId, (counts.get(image.commentId) || 0) + 1)
182 if (counts.get(image.commentId) > 3)
183 throw new AppError('INVALID_BACKUP', 'A revision request has too many screenshots.')
184 }
185}
186function restoreComments(store, records, images) {
187 for (const row of records)
188 store.db.prepare('INSERT INTO task_comments VALUES (?,?,?)').run(
189 row.id,
190 row.taskId,
191 JSON.stringify({
192 text: row.text,
193 source: row.source,
194 actedOnActivityID: row.actedOnActivityID,
195 createdAt: row.createdAt,
196 delivery: ['pending', 'queued'].includes(row.delivery) ? 'needs-review' : row.delivery,
197 runId: row.runId,
198 agent: row.agent
199 })
200 )
201 for (const image of images)
202 store.db
203 .prepare('INSERT INTO comment_images VALUES (?,?,?,?,?)')
204 .run(image.id, image.commentId, image.name, image.mimeType, imageBytes(image))
205}
206module.exports = {
207 comments,
208 insertComment,
209 exportComments,
210 validateComments,
211 restoreComments,
212 imageBytes,
213 revisionIdPattern,
214 MAX_IMAGE_BYTES
215}