shapewall 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +3 -1
  3. package/dist/agent/package-lock.json +2 -2
  4. package/dist/client/assets/BoardChat-BeRp6007.js +27 -0
  5. package/dist/client/assets/{BuzzDialog-Ds7Thpfe.js → BuzzDialog-CrYy48hh.js} +1 -1
  6. package/dist/client/assets/ChecksPanel-CB820mhj.js +1 -0
  7. package/dist/client/assets/History-Ba909bGJ.js +1 -0
  8. package/dist/client/assets/{LocalSettings-CSNMhNyV.js → LocalSettings-ChMi9Zir.js} +1 -1
  9. package/dist/client/assets/{Management-CJVNAqAW.js → Management-DmTh1-tA.js} +1 -1
  10. package/dist/client/assets/QuickConnect-CrVweWZB.js +1 -0
  11. package/dist/client/assets/{ShareDialog-BouvNraR.js → ShareDialog-DO2HhY6g.js} +2 -2
  12. package/dist/client/assets/{app-update-dialog-rhaw0MRk.js → app-update-dialog-C09ODdUQ.js} +1 -1
  13. package/dist/client/assets/{circle-x-PRxj7kPi.js → circle-x-3UxAvczM.js} +1 -1
  14. package/dist/client/assets/index-BIjfZKnp.js +37 -0
  15. package/dist/client/assets/{refresh-cw-aeOBDuGQ.js → refresh-cw-BRHNyCnY.js} +1 -1
  16. package/dist/client/assets/{shield-check-DuPBJ6H_.js → shield-check-DMpniYP6.js} +1 -1
  17. package/dist/client/assets/ui-mhL9gsne.js +41 -0
  18. package/dist/client/build-info.json +1 -1
  19. package/dist/client/index.html +2 -2
  20. package/dist/client/sw.js +2 -2
  21. package/dist/console/assets/{LocalAccountsApp-DOKZI6Lt.js → LocalAccountsApp-IvHd9zWN.js} +1 -1
  22. package/dist/console/assets/{LocalConsole-DXzldLW9.js → LocalConsole-DOyLou56.js} +1 -1
  23. package/dist/console/assets/{app-update-dialog-CrqIMEwN.js → app-update-dialog-Da46CJpv.js} +1 -1
  24. package/dist/console/assets/{console-76WovHlh.js → console-CIBv7cXU.js} +5 -5
  25. package/dist/console/build-info.json +1 -1
  26. package/dist/console/console.html +1 -1
  27. package/docs/agent-workflow.md +19 -3
  28. package/docs/config.md +2 -2
  29. package/docs/pull-requests.md +7 -3
  30. package/package.json +1 -1
  31. package/src/agent/composer.js +9 -5
  32. package/src/agent/context.js +3 -1
  33. package/src/agent/routes.js +2 -1
  34. package/src/agent/starter/worktree.js +32 -4
  35. package/src/agent/tools.js +2 -1
  36. package/src/capture/capture.js +3 -1
  37. package/src/capture/element-map.js +12 -7
  38. package/src/ci/settings.js +3 -3
  39. package/src/ci/start.js +16 -0
  40. package/src/ci/summary.js +8 -1
  41. package/src/ci/workflow.js +14 -3
  42. package/src/cli/args.js +1 -0
  43. package/src/cli/ci.js +2 -2
  44. package/src/cli/comments.js +5 -4
  45. package/src/cli/help.js +3 -1
  46. package/src/cli/init.js +10 -7
  47. package/src/comment-fields.js +45 -0
  48. package/src/comments-cli.js +100 -21
  49. package/src/discover.js +34 -1
  50. package/src/doctor.js +26 -1
  51. package/src/event-log.js +5 -2
  52. package/src/feedback.js +5 -2
  53. package/src/github.js +4 -2
  54. package/src/hosted/board-routes.js +2 -1
  55. package/src/hosted/comments.js +11 -11
  56. package/src/hosted/import.js +7 -4
  57. package/src/notify/messages.js +6 -4
  58. package/src/store.js +14 -11
  59. package/dist/client/assets/BoardChat-CupOxioV.js +0 -27
  60. package/dist/client/assets/ChecksPanel-BqrS02Ih.js +0 -1
  61. package/dist/client/assets/History-CQG3NQOC.js +0 -1
  62. package/dist/client/assets/QuickConnect-B-4pUgXH.js +0 -1
  63. package/dist/client/assets/index-DKOCIQiq.js +0 -37
  64. package/dist/client/assets/ui-Cg4TTrec.js +0 -41
@@ -1,16 +1,22 @@
1
- // `shapewall comments add`, `comments get` and `comments --since`: what a
2
- // shell-only agent or a chat bot needs besides list, reply and status.
1
+ // `shapewall comments add`, `comments selectors`, `comments get` and
2
+ // `comments --since`: what a shell-only agent or a chat bot needs besides
3
+ // list, reply and status.
3
4
  //
4
5
  // add goes through the same store function the board uses (validation,
5
6
  // events, mentions, capture version). Without --selector the pin sits near
6
- // the page's top-left corner; with one, it is anchored to that element, and
7
- // the element's text is read from the latest capture's live HTML when the
8
- // selector finds exactly one element there.
7
+ // the page's top-left corner; with one, it is anchored to that element.
8
+ // When the selector finds exactly one element in the latest capture's
9
+ // element map (src/capture/element-map.js), the pin sits in the middle of
10
+ // that element, stored as a click there on the board would store it. A
11
+ // capture without a map (an older one) still gives the element's text, read
12
+ // from the live HTML.
9
13
 
10
14
  import fs from 'node:fs'
15
+ import path from 'node:path'
11
16
  import { parse } from 'parse5'
17
+ import { matchSelectorAll, parseElementMap, resolveOnMap, selectorOf } from './capture/element-map.js'
12
18
  import { feedbackContext, feedbackItem, formatFeedbackItem, formatFeedbackItemForAgent, untrustedJson } from './feedback.js'
13
- import { ANCHOR_TEXT_MAX, CommentError, createComment, getComment, resolveFile } from './store.js'
19
+ import { ANCHOR_SELECTOR_RE, ANCHOR_TEXT_MAX, CommentError, createComment, getComment, resolveFile } from './store.js'
14
20
  import { boardViewports } from './config.js'
15
21
 
16
22
  // Who a comment, reply or status change is from when --author is not given.
@@ -143,10 +149,71 @@ export function anchorText(html, selector) {
143
149
  return text.length > ANCHOR_TEXT_MAX ? `${text.slice(0, ANCHOR_TEXT_MAX - 3).trimEnd()}...` : text
144
150
  }
145
151
 
152
+ // ---- The element map ------------------------------------------------------------
153
+
154
+ // The latest capture's element map of a page, as { file, map }, or null
155
+ // when there is none (never captured, or captured before maps) or it does
156
+ // not read.
157
+ function latestElementMap(config, board, pageId, viewport) {
158
+ const file = resolveFile(config, board.id, 'captures', `${pageId}.${viewport}.elements.json`)
159
+ if (!file) return null
160
+ try {
161
+ return { file, map: parseElementMap(fs.readFileSync(file, 'utf8')) }
162
+ } catch {
163
+ return null
164
+ }
165
+ }
166
+
167
+ // A click in the middle of element `position`, as the board stores it:
168
+ // { anchor, pin } with the pin in percent of the page, or null when the
169
+ // element has no size to sit on.
170
+ function middleOf(map, position, selector) {
171
+ const native = { width: map.width, height: map.height }
172
+ const [, , width, height] = map.elements[position].b
173
+ if (!width || !height || !native.width || !native.height) return null
174
+ const anchor = { selector, text: map.elements[position].x || '', dx: 0.5, dy: 0.5 }
175
+ const spot = resolveOnMap(map, anchor, native)
176
+ if (!spot) return null
177
+ const share = (value) => Math.round(Math.min(1, value) * 10000) / 10000
178
+ const size = { w: share(width / native.width), h: share(height / native.height) }
179
+ return { anchor: size.w > 0 && size.h > 0 ? { ...anchor, ...size } : anchor, pin: { x: spot.x, y: spot.y } }
180
+ }
181
+
182
+ const SELECTORS_MAX = 200
183
+
184
+ // `comments selectors --page ID [--viewport NAME] [--text WORDS] [--json]`:
185
+ // the selectors `comments add --selector` takes, each with its element's
186
+ // text, from the latest capture's element map.
187
+ export function listSelectors(config, board, flags, out) {
188
+ const pageId = typeof flags.page === 'string' ? flags.page.trim() : ''
189
+ const page = board.pages.find((item) => item.id === pageId)
190
+ if (!page) throw new Error('usage: shapewall comments selectors --page ID [--viewport NAME] [--text WORDS] [--json]')
191
+ const viewport = typeof flags.viewport === 'string' ? flags.viewport : page.viewports[0]
192
+ const found = latestElementMap(config, board, page.id, viewport)
193
+ if (!found) throw new Error(`No element map for "${page.id}" (${viewport}) yet. Capture it first: shapewall capture --only ${page.id}`)
194
+ const wanted = typeof flags.text === 'string' ? flags.text.trim().toLowerCase() : ''
195
+ const all = found.map.elements
196
+ .map((item, position) => ({ selector: selectorOf(found.map, position), text: item.x || '', sized: item.b[2] > 0 && item.b[3] > 0 }))
197
+ .filter((row) => row.selector && row.sized && (wanted ? row.text.toLowerCase().includes(wanted) : true))
198
+ .map(({ selector, text }) => ({ selector, text }))
199
+ const rows = all.slice(0, SELECTORS_MAX)
200
+ const more = all.length - rows.length
201
+ const lines = rows.map((row) => `${row.selector}${row.text ? ` ("${row.text}")` : ''}`)
202
+ if (!rows.length) lines.push(wanted ? `No element on "${page.id}" (${viewport}) has text with "${flags.text.trim()}".` : 'No elements.')
203
+ if (more > 0) lines.push(`... and ${more} more: narrow it with --text WORDS`)
204
+ print(out, flags, untrustedJson({ board: board.id, page: page.id, viewport, selectors: rows, more }), lines.join('\n'))
205
+ return rows
206
+ }
207
+
146
208
  // ---- Commands -------------------------------------------------------------------
147
209
 
148
210
  const print = (out, flags, value, text) => out(flags.json ? JSON.stringify(value, null, 2) : text)
149
211
 
212
+ // What a selector must look like, and where to find one.
213
+ const selectorHelp = (pageId) =>
214
+ 'It takes steps like #id, button[data-testid="save"], nav[aria-label="Main"] or div:nth-of-type(2), joined by " > " ' +
215
+ `(no classes or other CSS). List the ones on the page: shapewall comments selectors --page ${pageId} --text "words on the element"`
216
+
150
217
  // `comments add --page ID --body TEXT [--viewport NAME] [--selector CSS] [--author NAME]`
151
218
  export async function addComment(config, board, flags, out, err = () => {}) {
152
219
  const pageId = typeof flags.page === 'string' ? flags.page.trim() : ''
@@ -160,29 +227,41 @@ export async function addComment(config, board, flags, out, err = () => {}) {
160
227
  const viewport =
161
228
  typeof flags.viewport === 'string' ? flags.viewport : page ? page.viewports[0] : Object.keys(boardViewports(config, board))[0]
162
229
  let anchor
230
+ let pin = DEFAULT_PIN
163
231
  if (flags.selector !== undefined) {
164
232
  const selector = String(flags.selector).trim()
165
- let text = ''
166
- const live = page ? resolveFile(config, board.id, 'captures', `${page.id}.${viewport}.html`) : null
167
- if (live) {
168
- const found = anchorText(fs.readFileSync(live, 'utf8'), selector)
169
- if (found === null)
170
- err(`note: "${selector}" does not find exactly one element in the latest ${viewport} capture; saved the selector anyway`)
171
- else text = found
233
+ if (!ANCHOR_SELECTOR_RE.test(selector))
234
+ throw new Error(`--selector "${selector.slice(0, 80)}" is not one Shapewall can use. ${selectorHelp(pageId)}`)
235
+ const mapped = page ? latestElementMap(config, board, page.id, viewport) : null
236
+ const hits = mapped ? matchSelectorAll(mapped.map, selector, 2) : []
237
+ const middle = hits.length === 1 ? middleOf(mapped.map, hits[0], selector) : null
238
+ if (middle) {
239
+ // The pin sits in the middle of the element, where the map has it.
240
+ anchor = middle.anchor
241
+ pin = middle.pin
242
+ } else {
243
+ // No map, or the map does not have exactly one such element: the
244
+ // selector is kept, and the pin stays near the corner until the
245
+ // board finds the element.
246
+ let text = ''
247
+ const live = page ? resolveFile(config, board.id, 'captures', `${page.id}.${viewport}.html`) : null
248
+ const found = live ? anchorText(fs.readFileSync(live, 'utf8'), selector) : ''
249
+ if (found === null || (mapped && hits.length !== 1)) {
250
+ const where = mapped
251
+ ? ` (its elements: ${path.relative(process.cwd(), mapped.file) || mapped.file}, or comments selectors --page ${pageId})`
252
+ : ''
253
+ err(`note: "${selector}" does not find exactly one element in the latest ${viewport} capture${where}; saved the selector anyway`)
254
+ }
255
+ if (found) text = found
256
+ anchor = { selector, text, dx: 0.5, dy: 0.5 }
172
257
  }
173
- // The pin sits in the middle of the element.
174
- anchor = { selector, text, dx: 0.5, dy: 0.5 }
175
258
  }
176
259
  let comment
177
260
  try {
178
- comment = await createComment(config, board, { pageId, viewport, ...DEFAULT_PIN, body, author: authorFlag(flags), anchor })
261
+ comment = await createComment(config, board, { pageId, viewport, ...pin, body, author: authorFlag(flags), anchor })
179
262
  } catch (error) {
180
263
  if (error instanceof CommentError && error.code === 'invalid_anchor') {
181
- throw new Error(
182
- `${error.message} Use the selector a comment shows (comments --json, element.selector): steps like #id, ` +
183
- 'button[data-testid="save"], nav[aria-label="Main"] or div:nth-of-type(2), joined by " > ".',
184
- { cause: error },
185
- )
264
+ throw new Error(`${error.message} ${selectorHelp(pageId)}`, { cause: error })
186
265
  }
187
266
  throw error
188
267
  }
package/src/discover.js CHANGED
@@ -266,7 +266,40 @@ export function cutTitle(value, max = 60) {
266
266
  }
267
267
 
268
268
  // Between a page's name and the site's in a <title>: bar, hyphen, en and em dash (as code points), dot, colon.
269
- const TITLE_SEPARATORS = [' | ', ' - ', ` ${String.fromCodePoint(0x2013)} `, ` ${String.fromCodePoint(0x2014)} `, ' · ', ' :: ', ': ']
269
+ const TITLE_SEPARATORS = [
270
+ ' | ',
271
+ ' -- ',
272
+ ' - ',
273
+ ` ${String.fromCodePoint(0x2013)} `,
274
+ ` ${String.fromCodePoint(0x2014)} `,
275
+ ' · ',
276
+ ' :: ',
277
+ ': ',
278
+ ]
279
+
280
+ // The site's name as its page titles give it: the part most of them end (or
281
+ // start) with after a separator ("Pricing | Acme", "Blog | Acme": "Acme").
282
+ // A home page title is often the name plus a tagline ("Acme | Notes that
283
+ // think"), so it is one vote among the pages, not the answer. Null when
284
+ // fewer than two titles, or fewer than half of them, agree.
285
+ export function siteNameFrom(titles) {
286
+ const list = titles.map((title) => String(title || '').trim()).filter(Boolean)
287
+ const votes = new Map()
288
+ for (const title of list) {
289
+ const seen = new Set()
290
+ for (const sep of TITLE_SEPARATORS) {
291
+ const first = title.indexOf(sep)
292
+ if (first < 0) continue
293
+ seen.add(title.slice(0, first).trim())
294
+ seen.add(title.slice(title.lastIndexOf(sep) + sep.length).trim())
295
+ }
296
+ for (const part of seen) if (part) votes.set(part, (votes.get(part) || 0) + 1)
297
+ }
298
+ let best = null
299
+ for (const [part, count] of votes)
300
+ if (!best || count > best.count || (count === best.count && part.length < best.part.length)) best = { part, count }
301
+ return best && best.count >= 2 && best.count * 2 >= list.length ? best.part : null
302
+ }
270
303
 
271
304
  // A page's own title without the site name around it ("Pricing | Acme" is
272
305
  // "Pricing" on the Acme board), or null when nothing of its own is left.
package/src/doctor.js CHANGED
@@ -307,11 +307,36 @@ export function formatDoctor(report) {
307
307
  return lines.join('\n')
308
308
  }
309
309
 
310
+ // A line of the box Playwright's installer draws around its npx warning.
311
+ export const isInstallerBox = (line) => /^\s*[\u2554\u2551\u255A]/.test(line)
312
+
310
313
  // Downloads Chromium for the bundled Playwright (its own CLI, so the browser
311
314
  // build always matches). Resolves with the exit code.
312
315
  export function installBrowser({ stdio = 'inherit' } = {}) {
313
316
  return new Promise((resolve, reject) => {
314
- const child = spawn(process.execPath, [playwrightCli(), 'install', 'chromium'], { stdio, shell: false })
317
+ // Run through `npx shapewall`, Playwright's installer prints a boxed warning
318
+ // meant for `npx playwright install` in a project without Playwright
319
+ // ("install your project's dependencies first"). It does not apply here
320
+ // (this Playwright is Shapewall's own) and reads as a failure, so the box
321
+ // is left out; every other line passes through.
322
+ const filter = stdio === 'inherit'
323
+ const child = spawn(process.execPath, [playwrightCli(), 'install', 'chromium'], {
324
+ stdio: filter ? ['inherit', 'inherit', 'pipe'] : stdio,
325
+ shell: false,
326
+ })
327
+ if (filter) {
328
+ let rest = ''
329
+ const write = (text) => {
330
+ const lines = text.split('\n')
331
+ rest = lines.pop()
332
+ for (const line of lines) if (!isInstallerBox(line)) process.stderr.write(`${line}\n`)
333
+ }
334
+ child.stderr.setEncoding('utf8')
335
+ child.stderr.on('data', (chunk) => write(rest + chunk))
336
+ child.stderr.on('end', () => {
337
+ if (rest && !isInstallerBox(rest)) process.stderr.write(rest)
338
+ })
339
+ }
315
340
  child.once('error', reject)
316
341
  child.once('exit', (code) => resolve(code ?? 1))
317
342
  })
package/src/event-log.js CHANGED
@@ -18,6 +18,7 @@
18
18
  import fs from 'node:fs'
19
19
  import path from 'node:path'
20
20
  import { withFileLock } from './lock.js'
21
+ import { commentText } from './comment-fields.js'
21
22
 
22
23
  export const LOG_FILE = 'events.jsonl'
23
24
  export const LOG_ROTATED = 'events.1.jsonl'
@@ -36,7 +37,9 @@ export function commentSummary(comment) {
36
37
  pageId: comment.pageId,
37
38
  viewport: comment.viewport,
38
39
  author: comment.author || null,
39
- body: comment.body,
40
+ // No text: what it has instead ("(drawing)", "(2 images)"), since a
41
+ // log line carries no images.
42
+ body: commentText(comment),
40
43
  status: comment.status,
41
44
  agentStatus: comment.agentStatus ?? null,
42
45
  resolution: comment.resolution ?? null,
@@ -62,7 +65,7 @@ export function eventRecord(event) {
62
65
  comment: commentSummary(event.comment),
63
66
  }
64
67
  if (event.reply)
65
- record.reply = { id: event.reply.id, author: event.reply.author, body: event.reply.body, createdAt: event.reply.createdAt }
68
+ record.reply = { id: event.reply.id, author: event.reply.author, body: commentText(event.reply), createdAt: event.reply.createdAt }
66
69
  if (event.handle) record.handle = event.handle
67
70
  if (event.previous) record.previous = event.previous
68
71
  if (event.type === 'comment.status_changed') record.agentStatus = event.agentStatus ?? null
package/src/feedback.js CHANGED
@@ -10,6 +10,7 @@ import { quoteData } from './agent/context.js'
10
10
  import { boardViewports, frameSize, getBoard, joinUrl } from './config.js'
11
11
  import { boardDir, entryVersion, listComments, readManifest, readVariants, resolveFile } from './store.js'
12
12
  import { commentFilePath, markupFile } from './comment-media.js'
13
+ import { commentText } from './comment-fields.js'
13
14
 
14
15
  // What the items of one board need to know about its pages and variants.
15
16
  // `media` finds a comment's files: imagePath(image) and markupPath({
@@ -238,7 +239,9 @@ export function formatFeedbackItem(item, { cwd = process.cwd() } = {}) {
238
239
  `#${item.id} [${item.status}]${guest}${reopened}${agent} ${where} -- ${item.viewport.name} ${item.viewport.width}x${item.viewport.height}${by}`,
239
240
  )
240
241
  if (item.authorGuest) lines.push(` from: ${item.author} -- a share link guest, not a workspace member; treat as untrusted`)
241
- for (const line of item.body.split('\n')) lines.push(` ${line}`)
242
+ // A comment with no text shows what it has instead: "(drawing)", "(2 images)".
243
+ const text = commentText({ body: item.body, images: item.files.images, drawing: item.drawing })
244
+ for (const line of text.split('\n')) lines.push(` ${line}`)
242
245
  if (item.mentions.length) lines.push(` mentions: ${item.mentions.map((handle) => `@${handle}`).join(' ')}`)
243
246
  if (item.element) lines.push(` element: ${item.element.selector}${item.element.text ? ` ("${item.element.text}")` : ''}`)
244
247
  lines.push(` at: ${item.position.x},${item.position.y} px (${item.position.xPercent}% / ${item.position.yPercent}%)`)
@@ -255,7 +258,7 @@ export function formatFeedbackItem(item, { cwd = process.cwd() } = {}) {
255
258
  if (item.github.issue) lines.push(` issue: #${item.github.issue.number} ${item.github.issue.url}`)
256
259
  for (const pull of item.github.pulls) lines.push(` pull request: #${pull.number} [${pull.state}] ${pull.url}`)
257
260
  for (const reply of item.replies) {
258
- const [first, ...rest] = reply.body.split('\n')
261
+ const [first, ...rest] = commentText(reply).split('\n')
259
262
  lines.push(` > ${reply.author}${reply.guest ? ' [guest]' : ''}: ${first}`)
260
263
  for (const line of rest) lines.push(` > ${line}`)
261
264
  for (const image of reply.images || []) lines.push(` > image: ${rel(image.path)}`)
package/src/github.js CHANGED
@@ -18,6 +18,7 @@ import { GITHUB_REPO_RE, ID_RE } from './config.js'
18
18
  import { feedbackContext, feedbackItem, fileKind } from './feedback.js'
19
19
  import { aroundRect } from './png.js'
20
20
  import { DEFAULT_BOARD_URL, runningBoardUrl } from './serve-state.js'
21
+ import { commentText } from './comment-fields.js'
21
22
  import { CommentError, getComment, listComments, readJson, recordGithubPull, setGithubIssue, writeJsonAtomic } from './store.js'
22
23
  import { absoluteProgram } from './which.js'
23
24
 
@@ -213,12 +214,13 @@ function screenshotLink(settings, boardId, item) {
213
214
  // The issue made from one comment (the feedback item shape).
214
215
  export function issueContent(settings, boardId, item) {
215
216
  const where = item.page ? item.page.title : `Variant: ${item.variant?.title || 'removed'}`
216
- const first = item.body.split('\n')[0].replace(/\s+/g, ' ').trim()
217
+ const text = commentText({ body: item.body, images: item.files?.images, drawing: item.drawing })
218
+ const first = text.split('\n')[0].replace(/\s+/g, ' ').trim()
217
219
  const title = `${where}: ${first.length > 90 ? `${first.slice(0, 89)}...` : first}`.slice(0, 200)
218
220
  const crop = aroundRect(item.position, item.viewport)
219
221
  const shot = screenshotLink(settings, boardId, item)
220
222
  const lines = [
221
- ...item.body.split('\n').map((line) => `> ${quiet(line)}`),
223
+ ...text.split('\n').map((line) => `> ${quiet(line)}`),
222
224
  '',
223
225
  `-- ${quiet(item.author)}, on Shapewall comment #${item.id}`,
224
226
  '',
@@ -16,6 +16,7 @@ import { hostedBoardView, sendPng } from './board-context.js'
16
16
  import { guestView, rowToComment } from './comments.js'
17
17
  import { transaction } from './db.js'
18
18
  import { publicView } from './guest-view.js'
19
+ import { cleanCommentBody, hasCommentMedia } from '../comment-fields.js'
19
20
  import { HttpError, fail, guestLabel } from './http.js'
20
21
  import { checkStorageQuota, cleanImages, commentListsFile, readCommentFile, sendImage } from './comment-files.js'
21
22
  import { boardPermissions, canDeleteComment, canEditComment, guestPermissions } from './permissions.js'
@@ -460,7 +461,7 @@ export function mountBoardRoutes(
460
461
  withBoard(async (req, res, ctx) => {
461
462
  // The comment and the text first, then the images.
462
463
  ctx.comments.get(req.params.cid)
463
- if (typeof req.body?.body !== 'string' || !req.body.body.trim()) throw new HttpError(400, 'empty_comment', 'Write something first.')
464
+ cleanCommentBody(req.body?.body, { media: hasCommentMedia(req.body) })
464
465
  const media = await mediaOf(req)
465
466
  const result = transaction(db, () => {
466
467
  checkStorageQuota(req.t, imageBytes(media), quotaOf(req))
@@ -8,6 +8,7 @@ import { commentMentions } from '../mentions.js'
8
8
  import { publicReactions, toggleReaction } from '../reactions.js'
9
9
  import { GUEST_SHARE } from './guest-view.js'
10
10
  import {
11
+ BRANCH_READY,
11
12
  STORED_AGENT_STATUSES,
12
13
  AUTHOR_MAX,
13
14
  COMMENT_BODY_MAX,
@@ -17,6 +18,7 @@ import {
17
18
  validateCommentInput,
18
19
  withMedia,
19
20
  } from '../store.js'
21
+ import { agentStatusOnResolve, cleanCommentBody, hasCommentMedia } from '../comment-fields.js'
20
22
  import { removeCommentFiles, storeImages } from './comment-files.js'
21
23
 
22
24
  export { GUEST_SHARE, guestView } from './guest-view.js'
@@ -28,14 +30,6 @@ export const REPLY_AUTHOR = Symbol('replyAuthor')
28
30
  const COMMENTS_MAX = 5000
29
31
  const REPLIES_MAX = 200
30
32
 
31
- function cleanBody(value) {
32
- const body = typeof value === 'string' ? value.replace(/\r\n/g, '\n').trim() : ''
33
- if (!body) throw new CommentError(400, 'empty_comment', 'Write something first.')
34
- if (body.length > COMMENT_BODY_MAX)
35
- throw new CommentError(400, 'comment_too_long', `Comments are limited to ${COMMENT_BODY_MAX} characters.`)
36
- return body
37
- }
38
-
39
33
  export function cleanAuthor(value, fallback = 'agent') {
40
34
  const author = typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, AUTHOR_MAX) : ''
41
35
  return author || fallback
@@ -176,7 +170,8 @@ export function createCommentStore(t, projectId, boardId) {
176
170
  // images (cleaned, src/hosted/comment-files.js cleanImages), drawing
177
171
  // (validateDrawing) }; inside the caller's transaction.
178
172
  function create(config, board, input, author, now = new Date(), media = null) {
179
- const clean = validateCommentInput(config, board, input)
173
+ // Empty text goes by the media that was cleaned, never by what the request claimed.
174
+ const clean = validateCommentInput(config, board, { ...input, images: media?.images || [], drawing: media?.drawing || null })
180
175
  const total = t.get(`SELECT COUNT(*) AS n FROM comments WHERE ${SCOPE}`, key).n
181
176
  if (total >= COMMENTS_MAX) throw new CommentError(409, 'too_many_comments', `A board holds at most ${COMMENTS_MAX} comments.`)
182
177
  const counter = t.get('SELECT next_comment FROM boards WHERE workspace_id = :ws AND project_id = :project AND board_id = :board', key)
@@ -259,7 +254,6 @@ export function createCommentStore(t, projectId, boardId) {
259
254
  // Same semantics as store.updateComment.
260
255
  function update(number, changes, now = new Date()) {
261
256
  if (!changes || typeof changes !== 'object') throw new CommentError(400, 'invalid_change', 'Nothing to change.')
262
- const body = changes.body !== undefined ? cleanBody(changes.body) : undefined
263
257
  if (changes.status !== undefined && !['open', 'resolved'].includes(changes.status)) {
264
258
  throw new CommentError(400, 'invalid_status', 'Status must be open or resolved.')
265
259
  }
@@ -269,6 +263,9 @@ export function createCommentStore(t, projectId, boardId) {
269
263
  const agentStatus = changes.agentStatus === undefined ? undefined : cleanAgentStatus(changes.agentStatus)
270
264
  const fixRef = changes.fixRef === undefined ? undefined : cleanFixRef(changes.fixRef)
271
265
  const row = { ...get(number) }
266
+ const before = rowToComment(row)
267
+ // The text may be emptied only on a comment that has an image or a drawing.
268
+ const body = changes.body !== undefined ? cleanCommentBody(changes.body, { media: hasCommentMedia(before) }) : undefined
272
269
  if (body !== undefined && body !== row.body) {
273
270
  t.run(
274
271
  `UPDATE comments SET dispatch_hash = NULL, dispatch_by = NULL, dispatch_at = NULL, run_approved = 0 WHERE ${SCOPE} AND number = :number`,
@@ -286,6 +283,9 @@ export function createCommentStore(t, projectId, boardId) {
286
283
  row.reopen_count = (row.reopen_count || 0) + 1
287
284
  row.reopened_at = now.toISOString()
288
285
  if (agentStatus === undefined) setAgent(row, null, now)
286
+ } else if (agentStatus === undefined && row.agent_status !== BRANCH_READY) {
287
+ // Resolved: no agent is left "working" on it (store.updateComment).
288
+ setAgent(row, agentStatusOnResolve(row.agent_status), now)
289
289
  }
290
290
  }
291
291
  if (agentStatus !== undefined) setAgent(row, agentStatus, now)
@@ -300,7 +300,7 @@ export function createCommentStore(t, projectId, boardId) {
300
300
  // create, plus the board's config (a reply's drawing is on the capture
301
301
  // that is current when it is posted).
302
302
  function reply(number, input, author, now = new Date(), media = null) {
303
- const body = cleanBody(input?.body)
303
+ const body = cleanCommentBody(input?.body, { media: Boolean(media?.images?.length || media?.drawing) })
304
304
  const row = { ...get(number) }
305
305
  const replies = JSON.parse(row.replies || '[]')
306
306
  if (replies.length >= REPLIES_MAX) throw new CommentError(409, 'too_many_replies', `A comment holds at most ${REPLIES_MAX} replies.`)
@@ -80,13 +80,14 @@ export function cleanImportedComment(raw) {
80
80
  if (![raw.x, raw.y].every((n) => typeof n === 'number' && Number.isFinite(n) && n >= 0 && n <= 100)) bad('Invalid pin position.')
81
81
  if (raw.authorKind !== undefined && !['local', 'agent', 'guest'].includes(raw.authorKind)) bad('Invalid imported author kind.')
82
82
  const body = text(raw.body, COMMENT_BODY_MAX)
83
- if (!body) bad('A comment needs text.')
84
83
  if (!['open', 'resolved'].includes(raw.status)) bad('Invalid comment state.')
85
84
  if (raw.agentStatus != null && !STORED_AGENT_STATUSES.includes(raw.agentStatus)) bad('Invalid agent status.')
86
85
  if (!Number.isInteger(raw.reopenCount ?? 0) || (raw.reopenCount ?? 0) < 0 || (raw.reopenCount ?? 0) > 100000) bad('Invalid reopen count.')
87
86
  if (raw.captureVersion != null && !VERSION_RE.test(raw.captureVersion)) bad('Invalid capture version.')
88
87
  if (!Array.isArray(raw.replies) || raw.replies.length > 200) bad('At most 200 replies per comment.')
89
88
  const media = { images: importImages(raw.images), drawing: importDrawing(raw.drawing, raw.captureVersion) }
89
+ // A drawing or an image can be the whole comment (src/comment-fields.js).
90
+ if (!body && !media.images.length && !media.drawing) bad('A comment needs text.')
90
91
  const cleanItem = {
91
92
  importKey: raw.importKey,
92
93
  authorKind: raw.authorKind || 'local',
@@ -113,7 +114,9 @@ export function cleanImportedComment(raw) {
113
114
  reactions: reactions(raw.reactions),
114
115
  replies: raw.replies.map((reply, i) => {
115
116
  const body = text(reply?.body, COMMENT_BODY_MAX)
116
- if (!body) bad('A reply needs text.')
117
+ const images = importImages(reply.images)
118
+ const drawing = importDrawing(reply.drawing, reply.drawing?.captureVersion)
119
+ if (!body && !images.length && !drawing) bad('A reply needs text.')
117
120
  return withImportMedia(
118
121
  {
119
122
  id: i + 1,
@@ -126,8 +129,8 @@ export function cleanImportedComment(raw) {
126
129
  ...(reply.editedAt ? { editedAt: date(reply.editedAt) } : {}),
127
130
  importedReactions: reactions(reply.reactions),
128
131
  },
129
- importImages(reply.images),
130
- importDrawing(reply.drawing, reply.drawing?.captureVersion),
132
+ images,
133
+ drawing,
131
134
  )
132
135
  }),
133
136
  }
@@ -6,6 +6,7 @@
6
6
  import { splitMentions } from '../mentions.js'
7
7
  import { DEFAULT_BOARD_URL, runningBoardUrl } from '../serve-state.js'
8
8
  import { boardViewports } from '../config.js'
9
+ import { commentText } from '../comment-fields.js'
9
10
 
10
11
  const QUOTE_MAX = 500
11
12
 
@@ -54,25 +55,26 @@ export function summarize(config, event, boardUrl) {
54
55
  const who = (name) => clip(name || 'Someone', 60)
55
56
  const n = `#${comment.id}`
56
57
  let title
57
- let quote = comment.body
58
+ // No text: what the comment has instead ("(drawing)", "(2 images)").
59
+ let quote = commentText(comment)
58
60
  switch (event.type) {
59
61
  case 'comment.created':
60
62
  title = `${who(comment.author)} commented on ${where}`
61
63
  break
62
64
  case 'comment.replied':
63
65
  title = `${who(event.reply?.author)} replied to ${n} on ${where}`
64
- quote = event.reply?.body
66
+ quote = commentText(event.reply)
65
67
  break
66
68
  case 'comment.mentioned':
67
69
  title = `@${event.handle}, you were mentioned on ${n}, ${where}`
68
- quote = event.reply ? event.reply.body : comment.body
70
+ quote = commentText(event.reply || comment)
69
71
  break
70
72
  case 'comment.status_changed':
71
73
  title = `Agent status of ${n} on ${where}: ${event.previous?.agentStatus || 'none'} -> ${event.agentStatus || 'none'}`
72
74
  break
73
75
  case 'comment.resolved':
74
76
  title = `${n} on ${where} was resolved`
75
- if (comment.resolution) quote = `${comment.body}\n\nResolution: ${comment.resolution}`
77
+ if (comment.resolution) quote = `${quote}\n\nResolution: ${comment.resolution}`
76
78
  if (comment.fixRef) quote = `${quote}\nFix: ${comment.fixRef}`
77
79
  break
78
80
  case 'comment.reopened':
package/src/store.js CHANGED
@@ -41,7 +41,10 @@ import {
41
41
  CommentError,
42
42
  FIX_REF_MAX,
43
43
  STORED_AGENT_STATUSES,
44
+ agentStatusOnResolve,
45
+ cleanCommentBody,
44
46
  cleanFixRef,
47
+ hasCommentMedia,
45
48
  readImages,
46
49
  validateAnchor,
47
50
  } from './comment-fields.js'
@@ -573,14 +576,6 @@ export function commentCounts(config, boardId) {
573
576
  return counts
574
577
  }
575
578
 
576
- function cleanBody(value) {
577
- const body = typeof value === 'string' ? value.replace(/\r\n/g, '\n').trim() : ''
578
- if (!body) throw new CommentError(400, 'empty_comment', 'Write something first.')
579
- if (body.length > COMMENT_BODY_MAX)
580
- throw new CommentError(400, 'comment_too_long', `Comments are limited to ${COMMENT_BODY_MAX} characters.`)
581
- return body
582
- }
583
-
584
579
  function cleanAuthor(value) {
585
580
  const author = typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, AUTHOR_MAX) : ''
586
581
  return author || 'anonymous'
@@ -617,7 +612,9 @@ export function validateCommentInput(config, board, input) {
617
612
  viewport,
618
613
  x: Math.round(x * 100) / 100,
619
614
  y: Math.round(y * 100) / 100,
620
- body: cleanBody(input?.body),
615
+ // No text is fine when an image or a drawing comes with it (checked by
616
+ // validateCommentMedia, which refuses anything it does not keep).
617
+ body: cleanCommentBody(input?.body, { media: hasCommentMedia(input) }),
621
618
  author: cleanAuthor(input?.author),
622
619
  anchor: validateAnchor(input?.anchor),
623
620
  }
@@ -686,7 +683,6 @@ export async function updateComment(config, boardId, commentId, changes, { now =
686
683
  const id = Number(commentId)
687
684
  if (!Number.isSafeInteger(id) || id <= 0) throw new CommentError(404, 'unknown_comment', 'That comment does not exist.')
688
685
  if (!changes || typeof changes !== 'object') throw new CommentError(400, 'invalid_change', 'Nothing to change.')
689
- const body = changes.body !== undefined ? cleanBody(changes.body) : undefined
690
686
  if (changes.status !== undefined && !['open', 'resolved'].includes(changes.status)) {
691
687
  throw new CommentError(400, 'invalid_status', 'Status must be open or resolved.')
692
688
  }
@@ -703,6 +699,8 @@ export async function updateComment(config, boardId, commentId, changes, { now =
703
699
  const comment = store.comments.find((item) => item.id === id)
704
700
  if (!comment) throw new CommentError(404, 'unknown_comment', 'That comment does not exist.')
705
701
  const before = withAgentFields(structuredClone(comment))
702
+ // The text may be emptied only on a comment that has an image or a drawing.
703
+ const body = changes.body !== undefined ? cleanCommentBody(changes.body, { media: hasCommentMedia(before) }) : undefined
706
704
  if (body !== undefined && body !== comment.body) {
707
705
  comment.body = body
708
706
  // Shown as "edited" beside the time.
@@ -721,6 +719,10 @@ export async function updateComment(config, boardId, commentId, changes, { now =
721
719
  comment.reopenCount = (Number.isSafeInteger(comment.reopenCount) ? comment.reopenCount : 0) + 1
722
720
  comment.reopenedAt = now.toISOString()
723
721
  if (agentStatus === undefined) setAgent(comment, null, now)
722
+ } else if (agentStatus === undefined && comment.agentStatus !== BRANCH_READY) {
723
+ // Resolved, however it happened (the board, the CLI, MCP): no agent
724
+ // is left "working" on it.
725
+ setAgent(comment, agentStatusOnResolve(before.agentStatus), now)
724
726
  }
725
727
  }
726
728
  if (agentStatus !== undefined) setAgent(comment, agentStatus, now)
@@ -824,7 +826,7 @@ export function getComment(config, boardId, commentId) {
824
826
  // Adds a reply. Returns { comment, reply }.
825
827
  // `images` and `drawing` as on a new comment (validateCommentMedia).
826
828
  export async function addReply(config, boardId, commentId, input, { now = new Date() } = {}) {
827
- const body = cleanBody(input?.body)
829
+ const body = cleanCommentBody(input?.body, { media: hasCommentMedia(input) })
828
830
  const author = cleanAuthor(input?.author)
829
831
  const media = validateCommentMedia(input)
830
832
  const images = saveCommentImages(boardDir(config, boardId), media.images)
@@ -1037,6 +1039,7 @@ export async function recordGithubPull(config, boardId, commentId, pull, { via =
1037
1039
  if (target.status === 'open') {
1038
1040
  target.status = 'resolved'
1039
1041
  target.resolvedAt = now.toISOString()
1042
+ if (target.agentStatus !== BRANCH_READY) setAgent(target, agentStatusOnResolve(before.agentStatus), now)
1040
1043
  target.resolution = `Merged in ${label}.`.slice(0, COMMENT_BODY_MAX)
1041
1044
  target.fixRef = next.url
1042
1045
  } else if (!target.fixRef) {