agent-canvas 0.9.0-dev.1 → 0.9.0-dev.10

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 (94) hide show
  1. package/README.md +10 -0
  2. package/bin/lib/commands/review-remote.ts +186 -0
  3. package/bin/lib/commands/review.ts +88 -25
  4. package/bin/lib/instructions/app-review.md +31 -0
  5. package/daemon/build.ts +2 -0
  6. package/daemon/client/App.tsx +1 -1
  7. package/daemon/client/FileViewer.tsx +1 -1
  8. package/daemon/dist/client.css +2 -2
  9. package/daemon/dist/review.js +33 -3
  10. package/daemon/review-widget/anchor.ts +21 -4
  11. package/daemon/review-widget/browser.ts +46 -0
  12. package/daemon/review-widget/client.ts +23 -1
  13. package/daemon/review-widget/index.tsx +69 -11
  14. package/daemon/review-widget/remote-client.ts +117 -0
  15. package/daemon/review-widget/source.ts +43 -7
  16. package/daemon/review-widget/style.ts +51 -0
  17. package/daemon/review-widget/styles.css +30 -0
  18. package/daemon/review-widget/tsconfig.json +2 -1
  19. package/daemon/review-widget/widget.tsx +115 -17
  20. package/daemon/src/review/markdown.ts +6 -1
  21. package/daemon/src/review/model.ts +13 -1
  22. package/daemon/src/review/proxy.ts +30 -3
  23. package/daemon/src/review/remote.ts +112 -0
  24. package/daemon/src/review/sealing.ts +35 -0
  25. package/daemon/src/review/server.ts +16 -1
  26. package/daemon/src/review/store.ts +20 -28
  27. package/daemon/src/review/threads.ts +63 -0
  28. package/daemon/src/server.ts +1 -1
  29. package/daemon/tsconfig.json +1 -1
  30. package/package.json +23 -6
  31. package/skills/canvas/SKILL.md +2 -1
  32. package/types/bin/agent-canvas.d.ts +2 -0
  33. package/types/bin/lib/commands/daemon.d.ts +1 -0
  34. package/types/bin/lib/commands/exec.d.ts +7 -0
  35. package/types/bin/lib/commands/fetch.d.ts +1 -0
  36. package/types/bin/lib/commands/install.d.ts +1 -0
  37. package/types/bin/lib/commands/instructions.d.ts +1 -0
  38. package/types/bin/lib/commands/push.d.ts +1 -0
  39. package/types/bin/lib/commands/review-remote.d.ts +52 -0
  40. package/types/bin/lib/commands/review.d.ts +1 -0
  41. package/types/bin/lib/commands/watch.d.ts +1 -0
  42. package/types/bin/lib/config.d.ts +9 -0
  43. package/types/bin/lib/daemon-lifecycle.d.ts +4 -0
  44. package/types/bin/lib/helpers.d.ts +13 -0
  45. package/types/daemon/build.d.ts +1 -0
  46. package/types/daemon/client/App.d.ts +1 -0
  47. package/types/daemon/client/CompareView.d.ts +17 -0
  48. package/types/daemon/client/FileBrowser.d.ts +4 -0
  49. package/types/daemon/client/FileViewer.d.ts +6 -0
  50. package/types/daemon/client/OverviewView.d.ts +18 -0
  51. package/types/daemon/client/ReviewerIdentityDialog.d.ts +17 -0
  52. package/types/daemon/client/RevisionSelect.d.ts +10 -0
  53. package/types/daemon/client/SessionSwitcher.d.ts +6 -0
  54. package/types/daemon/client/ShareDialog.d.ts +30 -0
  55. package/types/daemon/client/apiSchemas.d.ts +1311 -0
  56. package/types/daemon/client/canvas-runtime.d.ts +1 -0
  57. package/types/daemon/client/clientApi.d.ts +112 -0
  58. package/types/daemon/client/components/SecretInput.d.ts +10 -0
  59. package/types/daemon/client/components/index.d.ts +2 -0
  60. package/types/daemon/client/domDiff.d.ts +37 -0
  61. package/types/daemon/client/errorMessage.d.ts +1 -0
  62. package/types/daemon/client/exportMarkdown.d.ts +1 -0
  63. package/types/daemon/client/lcs.d.ts +2 -0
  64. package/types/daemon/client/shareCrypto.d.ts +40 -0
  65. package/types/daemon/client/unifiedDiff.d.ts +26 -0
  66. package/types/daemon/langMap.d.ts +2 -0
  67. package/types/daemon/review-widget/anchor.d.ts +18 -0
  68. package/types/daemon/review-widget/browser.d.ts +6 -0
  69. package/types/daemon/review-widget/client.d.ts +38 -0
  70. package/types/daemon/review-widget/index.d.ts +1 -0
  71. package/types/daemon/review-widget/markup.d.ts +4 -0
  72. package/types/daemon/review-widget/remote-client.d.ts +29 -0
  73. package/types/daemon/review-widget/screenshot.d.ts +8 -0
  74. package/types/daemon/review-widget/source.d.ts +17 -0
  75. package/types/daemon/review-widget/style.d.ts +7 -0
  76. package/types/daemon/review-widget/widget.d.ts +7 -0
  77. package/types/daemon/src/components.d.ts +10 -0
  78. package/types/daemon/src/handlers/api.d.ts +11 -0
  79. package/types/daemon/src/handlers/files.d.ts +3 -0
  80. package/types/daemon/src/handlers/static.d.ts +2 -0
  81. package/types/daemon/src/handlers/uploads.d.ts +3 -0
  82. package/types/daemon/src/paths.d.ts +12 -0
  83. package/types/daemon/src/remote-feedback.d.ts +4 -0
  84. package/types/daemon/src/review/markdown.d.ts +3 -0
  85. package/types/daemon/src/review/model.d.ts +1089 -0
  86. package/types/daemon/src/review/proxy.d.ts +30 -0
  87. package/types/daemon/src/review/remote.d.ts +258 -0
  88. package/types/daemon/src/review/sealing.d.ts +11 -0
  89. package/types/daemon/src/review/server.d.ts +24 -0
  90. package/types/daemon/src/review/store.d.ts +34 -0
  91. package/types/daemon/src/review/threads.d.ts +35 -0
  92. package/types/daemon/src/server.d.ts +7 -0
  93. package/types/daemon/src/share.d.ts +98 -0
  94. package/types/daemon/src/stubFetch.d.ts +2 -0
@@ -1,5 +1,7 @@
1
1
  import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks'
2
- import type { ReviewAnchor, ReviewSource, ReviewThread, ReviewThreadState } from '../src/review/model'
2
+ import { z } from 'zod'
3
+ import { type ReviewAnchor, reviewAnchorSchema, type ReviewSource, type ReviewThread, type ReviewThreadState } from '../src/review/model'
4
+ import { isUnsentNote } from '../src/review/threads'
3
5
  import { describe, find } from './anchor'
4
6
  import type { ReviewClient } from './client'
5
7
  import { captureElement } from './screenshot'
@@ -19,6 +21,32 @@ interface Draft {
19
21
  element: Element
20
22
  /** Resolved while the reviewer writes: source maps can take a moment to load. */
21
23
  sources: Promise<ReviewSource[]>
24
+ body: string
25
+ screenshot: boolean
26
+ }
27
+
28
+ /** The comment being written, kept for the tab: a dev server reloads the page on many edits. */
29
+ const savedDraftSchema = z.object({ anchor: reviewAnchorSchema, body: z.string(), screenshot: z.boolean() })
30
+ type SavedDraft = z.infer<typeof savedDraftSchema>
31
+
32
+ const DRAFT_KEY = 'agent-canvas-review:draft'
33
+
34
+ function saveDraft(draft: SavedDraft | null): void {
35
+ try {
36
+ if (draft === null) sessionStorage.removeItem(DRAFT_KEY)
37
+ else sessionStorage.setItem(DRAFT_KEY, JSON.stringify(draft))
38
+ } catch {}
39
+ }
40
+
41
+ function loadDraft(): SavedDraft | null {
42
+ try {
43
+ const saved = sessionStorage.getItem(DRAFT_KEY)
44
+ if (saved === null) return null
45
+ const parsed = savedDraftSchema.safeParse(JSON.parse(saved))
46
+ return parsed.success ? parsed.data : null
47
+ } catch {
48
+ return null
49
+ }
22
50
  }
23
51
 
24
52
  const STATE_LABELS: Record<ReviewThreadState, string> = {
@@ -57,6 +85,13 @@ function takePendingReveal(): string | null {
57
85
  }
58
86
  }
59
87
 
88
+ /** Vite reloads every page for a module change, and for an HTML change only the page that file serves. */
89
+ function reloadsThisPage(path: string): boolean {
90
+ if (!path.endsWith('.html')) return true
91
+ const page = decodeURI(location.pathname)
92
+ return path === '/index.html' || page === path || (page.endsWith('/') && `${page}index.html` === path)
93
+ }
94
+
60
95
  function boxOf(element: Element): Box {
61
96
  const rect = element.getBoundingClientRect()
62
97
  return { top: rect.top, left: rect.left, width: rect.width, height: rect.height }
@@ -179,9 +214,17 @@ function popoverPosition(box: Box): { top: number; left: number } {
179
214
  return { top, left }
180
215
  }
181
216
 
182
- function Composer(props: { draft: Draft; onSubmit: (body: string, send: boolean, screenshot: boolean) => Promise<void>; onCancel: () => void }) {
183
- const [body, setBody] = useState('')
184
- const [screenshot, setScreenshot] = useState(false)
217
+ function Composer(props: {
218
+ draft: Draft
219
+ reloadPending: boolean
220
+ onChange: (body: string, screenshot: boolean) => void
221
+ onSubmit: (body: string, send: boolean, screenshot: boolean) => Promise<void>
222
+ onCancel: () => void
223
+ }) {
224
+ const [body, setBody] = useState(props.draft.body)
225
+ const [screenshot, setScreenshot] = useState(props.draft.screenshot)
226
+ const { onChange } = props
227
+ useEffect(() => onChange(body, screenshot), [onChange, body, screenshot])
185
228
  const [busy, setBusy] = useState(false)
186
229
  const [error, setError] = useState<string | null>(null)
187
230
  const textarea = useRef<HTMLTextAreaElement>(null)
@@ -217,6 +260,12 @@ function Composer(props: { draft: Draft; onSubmit: (body: string, send: boolean,
217
260
  <input type="checkbox" checked={screenshot} onChange={(event) => setScreenshot(event.currentTarget.checked)} />
218
261
  Attach a screenshot
219
262
  </label>
263
+ {props.reloadPending && (
264
+ <div class="reload-pending">
265
+ <span>The application changed. It reloads once you save or cancel this comment.</span>
266
+ <button type="button" class="ghost" onClick={() => location.reload()}>Reload now</button>
267
+ </div>
268
+ )}
220
269
  {error !== null && <div class="error">{error}</div>}
221
270
  <div class="actions">
222
271
  <button type="button" class="ghost" onClick={props.onCancel}>Cancel</button>
@@ -242,7 +291,7 @@ function ThreadCard(props: { thread: ReviewThread; number: number | null; client
242
291
  }
243
292
 
244
293
  return (
245
- <div class={`thread${props.number === null ? '' : ' current'}`}>
294
+ <div class={`thread${props.number === null ? '' : ' current'}${thread.state === 'resolved' ? ' resolved' : ''}`}>
246
295
  <div class="thread-head">
247
296
  <button type="button" class="ghost" title="Show in page" aria-label="Show in page" onClick={props.onReveal}>
248
297
  {props.number === null ? '↗' : `#${props.number}`}
@@ -299,16 +348,26 @@ export function ReviewWidget(props: { client: ReviewClient; host: HTMLElement })
299
348
  const [picking, setPicking] = useState(false)
300
349
  const [hovered, setHovered] = useState<Element | null>(null)
301
350
  const [draft, setDraft] = useState<Draft | null>(null)
351
+ const [unrestored, setUnrestored] = useState<SavedDraft | null>(loadDraft)
352
+ const [reloadPending, setReloadPending] = useState(false)
302
353
  const [panelOpen, setPanelOpen] = useState(false)
303
354
  const [showAll, setShowAll] = useState(false)
304
- const [showResolved, setShowResolved] = useState(false)
355
+ const [hideResolved, setHideResolved] = useState(false)
356
+ const [panelError, setPanelError] = useState<string | null>(null)
305
357
  const [revealId, setRevealId] = useState<string | null>(takePendingReveal)
306
358
  const [flash, setFlash] = useState<Box | null>(null)
307
359
  const href = useHref()
308
- useLayoutTick()
360
+ const tick = useLayoutTick()
309
361
 
310
362
  useEffect(() => {
311
- client.connect({ threads: setThreads, agentWatching: setWatching, connected: setConnected })
363
+ client.connect({
364
+ threads: setThreads,
365
+ agentWatching: setWatching,
366
+ connected: setConnected,
367
+ reload: (path) => {
368
+ if (reloadsThisPage(path)) setReloadPending(true)
369
+ },
370
+ })
312
371
  return () => client.close()
313
372
  }, [client])
314
373
 
@@ -320,24 +379,39 @@ export function ReviewWidget(props: { client: ReviewClient; host: HTMLElement })
320
379
  setPicking(false)
321
380
  setHovered(null)
322
381
  window.getSelection()?.removeAllRanges()
323
- setDraft({ anchor: describe(element, location.href, range), box: boxOf(element), element, sources: resolveSources(bundleFrames(element)) })
382
+ setUnrestored(null)
383
+ const anchor = describe(element, location.href, range)
384
+ setDraft({ anchor, box: boxOf(element), element, sources: resolveSources(bundleFrames(element)), body: '', screenshot: false })
324
385
  }, [])
386
+ const discardDraft = useCallback(() => {
387
+ setDraft(null)
388
+ saveDraft(null)
389
+ }, [])
390
+ const anchor = draft?.anchor
391
+ const keepDraft = useCallback((body: string, screenshot: boolean) => {
392
+ if (anchor !== undefined) saveDraft({ anchor, body, screenshot })
393
+ }, [anchor])
325
394
  usePicker(host, picking, setHovered, pick, cancelPicking)
326
395
  // The panel covers the right edge of the page, which the reviewer may want to pick from.
327
396
  const startPicking = () => {
328
397
  setPanelOpen(false)
329
- setDraft(null)
398
+ discardDraft()
330
399
  setPicking(true)
331
400
  }
332
401
 
333
402
  const page = pageKey(href)
334
403
  const onPage = useMemo(
335
- () => threads.filter((thread) => pageKey(thread.anchor.url) === page && (showResolved || thread.state !== 'resolved')),
336
- [threads, page, showResolved],
404
+ () => threads.filter((thread) => pageKey(thread.anchor.url) === page && (!hideResolved || thread.state !== 'resolved')),
405
+ [threads, page, hideResolved],
337
406
  )
338
- const listed = showAll ? threads.filter((thread) => showResolved || thread.state !== 'resolved') : onPage
407
+ const listed = showAll ? threads.filter((thread) => !hideResolved || thread.state !== 'resolved') : onPage
339
408
  const numbers = new Map(onPage.map((thread, index) => [thread.id, index + 1]))
340
409
  const pending = threads.filter((thread) => thread.state !== 'resolved').length
410
+ const notes = threads.filter(isUnsentNote).length
411
+ const sendNotes = () => {
412
+ setPanelError(null)
413
+ client.sendNotes().catch((failure: unknown) => setPanelError(failure instanceof Error ? failure.message : String(failure)))
414
+ }
341
415
 
342
416
  useEffect(() => {
343
417
  if (revealId === null) return
@@ -351,12 +425,26 @@ export function ReviewWidget(props: { client: ReviewClient; host: HTMLElement })
351
425
  setTimeout(() => setFlash(null), 1600)
352
426
  }, [revealId, threads, page])
353
427
 
428
+ // The draft survives the reload in sessionStorage; held back only so the reviewer can finish writing.
429
+ useEffect(() => {
430
+ if (reloadPending && draft === null) location.reload()
431
+ }, [reloadPending, draft])
432
+
433
+ // The application may render the element a moment after the reload.
434
+ useEffect(() => {
435
+ if (unrestored === null || draft !== null || pageKey(unrestored.anchor.url) !== page) return
436
+ const element = find(document, unrestored.anchor)
437
+ if (element === null) return
438
+ setUnrestored(null)
439
+ setDraft({ ...unrestored, box: boxOf(element), element, sources: resolveSources(bundleFrames(element)) })
440
+ }, [unrestored, draft, page, tick])
441
+
354
442
  const reveal = (thread: ReviewThread) => {
355
443
  setRevealId(thread.id)
356
444
  if (pageKey(thread.anchor.url) !== page) navigate(thread.anchor.url, thread.id)
357
445
  }
358
446
 
359
- const presence = !connected ? 'Daemon offline' : watching ? 'Claude is listening' : 'Claude is not listening'
447
+ const presence = !connected ? client.offlineLabel : watching ? 'Claude is listening' : 'Claude is not listening'
360
448
  const hoveredBox = hovered === null ? null : boxOf(hovered)
361
449
 
362
450
  return (
@@ -384,13 +472,15 @@ export function ReviewWidget(props: { client: ReviewClient; host: HTMLElement })
384
472
  {draft !== null && (
385
473
  <Composer
386
474
  draft={draft}
387
- onCancel={() => setDraft(null)}
475
+ reloadPending={reloadPending}
476
+ onChange={keepDraft}
477
+ onCancel={discardDraft}
388
478
  onSubmit={async (body, send, screenshot) => {
389
479
  // The capture asks for the tab, which the browser allows only while the click still counts as a gesture.
390
480
  const image = screenshot ? await captureElement(draft.element, host) : undefined
391
481
  const sources = await draft.sources
392
482
  await client.createThread(sources.length === 0 ? draft.anchor : { ...draft.anchor, sources }, body, send, image)
393
- setDraft(null)
483
+ discardDraft()
394
484
  }}
395
485
  />
396
486
  )}
@@ -403,8 +493,16 @@ export function ReviewWidget(props: { client: ReviewClient; host: HTMLElement })
403
493
  <div class="tabs">
404
494
  <button type="button" class={showAll ? '' : 'active'} onClick={() => setShowAll(false)}>This page</button>
405
495
  <button type="button" class={showAll ? 'active' : ''} onClick={() => setShowAll(true)}>All pages</button>
406
- <button type="button" class={showResolved ? 'active' : ''} onClick={() => setShowResolved(!showResolved)}>Resolved</button>
496
+ <button type="button" class={hideResolved ? 'active' : ''} onClick={() => setHideResolved(!hideResolved)}>Hide resolved</button>
407
497
  </div>
498
+ {notes > 0 && (
499
+ <div class="send-notes">
500
+ <button type="button" class="primary" onClick={sendNotes}>
501
+ Send {notes === 1 ? '1 note' : `${notes} notes`} to Claude
502
+ </button>
503
+ </div>
504
+ )}
505
+ {panelError !== null && <div class="error">{panelError}</div>}
408
506
  <div class="threads">
409
507
  {listed.length === 0 && <div class="empty">No comments yet. Click “Comment”, then an element or a text selection.</div>}
410
508
  {listed.map((thread) => (
@@ -19,9 +19,14 @@ function describeAnchor(anchor: ReviewAnchor, screenshot: string | undefined): s
19
19
  }
20
20
  if (anchor.quote !== undefined) {
21
21
  lines.push(`- Selected text: …${anchor.quote.before}**${anchor.quote.exact}**${anchor.quote.after}…`)
22
- } else if (anchor.text !== undefined && anchor.text !== '') {
22
+ } else if (anchor.text !== undefined && anchor.text !== '' && anchor.text !== anchor.name) {
23
23
  lines.push(`- Text: "${anchor.text}"`)
24
24
  }
25
+ if (anchor.browser !== undefined) {
26
+ const { name, viewport, colorScheme } = anchor.browser
27
+ lines.push(`- Browser: ${name}, viewport ${viewport.width}×${viewport.height} @${viewport.scale}x, ${colorScheme} color scheme`)
28
+ }
29
+ if (anchor.style !== undefined) lines.push(`- Computed style: \`${anchor.style}\``)
25
30
  if (screenshot !== undefined) lines.push(`- Screenshot, the element outlined in red: \`${screenshot}\` (read the file to see it)`)
26
31
  if (anchor.html !== undefined) lines.push('- Markup, trimmed:', '', fence('html', anchor.html))
27
32
  return lines
@@ -25,12 +25,14 @@ export function isLoopbackOrigin(origin: string): boolean {
25
25
  const shortText = z.string().max(500)
26
26
 
27
27
  export const MAX_HTML = 4000
28
+ export const MAX_SOURCE_FILE = 1000
29
+ export const MAX_STYLE = 1000
28
30
 
29
31
  /** A position in the application's source, resolved from a development stack through the page's source maps. */
30
32
  export const reviewSourceSchema = z.object({
31
33
  /** What was created there, e.g. `<a> in ProductListCell` or `<ProductListCell> in DataGrid`. */
32
34
  label: shortText,
33
- file: z.string().max(1000),
35
+ file: z.string().max(MAX_SOURCE_FILE),
34
36
  line: z.number().int().positive(),
35
37
  column: z.number().int().nonnegative(),
36
38
  })
@@ -53,6 +55,14 @@ export const reviewAnchorSchema = z.object({
53
55
  sources: z.array(reviewSourceSchema).max(10).optional(),
54
56
  /** The landmarks around the element: page heading, section, dialog. */
55
57
  context: shortText.optional(),
58
+ /** The reviewer's browser and operating system, e.g. `Chrome 141 · Linux`, viewport and colour scheme. */
59
+ browser: z.object({
60
+ name: shortText,
61
+ viewport: z.object({ width: z.number().int().nonnegative(), height: z.number().int().nonnegative(), scale: z.number().positive() }),
62
+ colorScheme: z.enum(['light', 'dark']),
63
+ }).optional(),
64
+ /** The element's computed box, layout and type as CSS declarations, initial values left out. */
65
+ style: z.string().max(MAX_STYLE).optional(),
56
66
  /** The element's markup, trimmed: deep subtrees, long lists and long texts are cut. */
57
67
  html: z.string().max(MAX_HTML).optional(),
58
68
  /** A text selection inside the element, with its surroundings. */
@@ -125,6 +135,8 @@ export type ReviewProxy = z.infer<typeof reviewProxySchema>
125
135
  export type ReviewBrowserFrame =
126
136
  | { type: 'threads'; threads: readonly ReviewThread[] }
127
137
  | { type: 'agent-status'; watching: boolean }
138
+ /** The application's dev server asked for a full reload; the widget holds it while the reviewer writes. */
139
+ | { type: 'reload'; path: string }
128
140
 
129
141
  /** The frame a waiting CLI receives when the person sends threads; it reads them back through the claim endpoint. */
130
142
  export interface ReviewWaitFrame {
@@ -1,5 +1,22 @@
1
+ import { z } from 'zod'
1
2
  import type { ReviewStore } from './store'
2
3
 
4
+ /** Vite's hot reload message that makes its client reload the page. */
5
+ const viteFullReloadSchema = z.object({ type: z.literal('full-reload'), path: z.string().default('*') })
6
+
7
+ /** The page path a Vite full reload names, or `undefined` for any other frame. */
8
+ export function viteFullReloadPath(frame: string): string | undefined {
9
+ if (!frame.includes('full-reload')) return undefined
10
+ let message: unknown
11
+ try {
12
+ message = JSON.parse(frame)
13
+ } catch {
14
+ return undefined
15
+ }
16
+ const parsed = viteFullReloadSchema.safeParse(message)
17
+ return parsed.success ? parsed.data.path : undefined
18
+ }
19
+
3
20
  /** One browser socket proxied to the application, e.g. its dev server's hot reload. */
4
21
  interface ProxySocketData {
5
22
  upstream: WebSocket
@@ -38,7 +55,15 @@ function connectUpstream(url: URL, protocols: string[]): Promise<WebSocket> {
38
55
  export class ReviewProxies {
39
56
  private readonly running = new Map<string, RunningProxy>()
40
57
 
41
- constructor(private readonly store: ReviewStore, private readonly widgetScript: string) {}
58
+ /**
59
+ * `onFullReload` receives the full reloads the application's dev server asks for: the proxy holds them back from
60
+ * the page, so a reload does not take the comment the reviewer is writing.
61
+ */
62
+ constructor(
63
+ private readonly store: ReviewStore,
64
+ private readonly widgetScript: string,
65
+ private readonly onFullReload: (project: string, path: string) => void,
66
+ ) {}
42
67
 
43
68
  /** Serves the project's application at `target` and returns where the reviewer opens it, `target`'s path kept. */
44
69
  open(project: string, target: string): string {
@@ -94,7 +119,7 @@ export class ReviewProxies {
94
119
  const upstreamUrl = new URL(`${url.pathname}${url.search}`, target)
95
120
  if (req.headers.get('Upgrade')?.toLowerCase() === 'websocket') {
96
121
  upstreamUrl.protocol = upstreamUrl.protocol === 'https:' ? 'wss:' : 'ws:'
97
- return await this.upgrade(req, server, upstreamUrl)
122
+ return await this.upgrade(project, req, server, upstreamUrl)
98
123
  }
99
124
  return await forward(req, upstreamUrl, url.origin, widgetTag)
100
125
  },
@@ -116,7 +141,7 @@ export class ReviewProxies {
116
141
  }
117
142
 
118
143
  /** Connects to the application first, so the browser gets the subprotocol the application chose. */
119
- private async upgrade(req: Request, server: ProxyServer, upstreamUrl: URL): Promise<Response | undefined> {
144
+ private async upgrade(project: string, req: Request, server: ProxyServer, upstreamUrl: URL): Promise<Response | undefined> {
120
145
  const protocols = (req.headers.get('Sec-WebSocket-Protocol') ?? '').split(',').map((protocol) => protocol.trim()).filter((protocol) =>
121
146
  protocol !== ''
122
147
  )
@@ -129,6 +154,8 @@ export class ReviewProxies {
129
154
  const data: ProxySocketData = { upstream, early: [], browser: null }
130
155
  upstream.onmessage = (event) => {
131
156
  if (typeof event.data !== 'string' && !(event.data instanceof ArrayBuffer)) return
157
+ const reloadPath = typeof event.data === 'string' ? viteFullReloadPath(event.data) : undefined
158
+ if (reloadPath !== undefined) return this.onFullReload(project, reloadPath)
132
159
  if (data.browser === null) data.early.push(event.data)
133
160
  else data.browser.send(event.data)
134
161
  }
@@ -0,0 +1,112 @@
1
+ import { z } from 'zod'
2
+ import { reviewAuthorSchema, reviewThreadStateSchema } from './model'
3
+
4
+ /**
5
+ * Remote review: the threads of an application deployed somewhere else, kept by the share worker. The reviewer's
6
+ * browser and the agent's CLI share a key the worker never sees, so the worker stores and relays ciphertext. It reads
7
+ * only what moves a thread through its lifecycle: ids, states, comment authors and timestamps.
8
+ */
9
+
10
+ /** The worker's name for a remote project: 12 random bytes, hex. Knowing it, from an allowed origin, lets a browser write. */
11
+ export const REMOTE_PROJECT_ID_RE = /^[a-f0-9]{24}$/
12
+
13
+ /** The fragment that hands a reviewer the project and its key: `#agent-canvas-review=<projectId>.<key>`. */
14
+ export const REVIEW_FRAGMENT_PARAM = 'agent-canvas-review'
15
+
16
+ export const MAX_ORIGINS = 5
17
+ export const MAX_THREADS = 1000
18
+ export const MAX_COMMENTS = 200
19
+ /** Ciphertext limits: base64 of AES-GCM over the plaintext limits in `model.ts`, with room for multi-byte UTF-8. */
20
+ export const MAX_SEALED_ANCHOR = 160_000
21
+ export const MAX_SEALED_BODY = 110_000
22
+ export const MAX_SEALED_SCREENSHOT = 11_000_000
23
+
24
+ /** `shareCrypto` packing: base64(IV || ciphertext || tag). */
25
+ function sealed(max: number) {
26
+ return z.string().min(1).max(max).regex(/^[A-Za-z0-9+/]+={0,2}$/, 'must be base64 ciphertext')
27
+ }
28
+
29
+ /** A deployed application's origin, or one on this machine for trying the setup out. */
30
+ export const reviewOriginSchema = z.string().refine((value) => {
31
+ let url: URL
32
+ try {
33
+ url = new URL(value)
34
+ } catch {
35
+ return false
36
+ }
37
+ if (url.origin !== value) return false
38
+ if (url.protocol === 'https:') return true
39
+ return url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname.endsWith('.localhost'))
40
+ }, 'must be an origin such as https://app.example.com')
41
+
42
+ export const sealedCommentSchema = z.object({
43
+ id: z.string().max(64),
44
+ author: reviewAuthorSchema,
45
+ body: sealed(MAX_SEALED_BODY),
46
+ createdAt: z.string().max(64),
47
+ })
48
+ export type SealedComment = z.infer<typeof sealedCommentSchema>
49
+
50
+ export const sealedThreadSchema = z.object({
51
+ id: z.string().max(64),
52
+ /** The `ReviewAnchor` as JSON, sealed. */
53
+ anchor: sealed(MAX_SEALED_ANCHOR),
54
+ state: reviewThreadStateSchema,
55
+ comments: z.array(sealedCommentSchema).min(1).max(MAX_COMMENTS),
56
+ /** Whether the reviewer attached a screenshot; the agent fetches it separately. */
57
+ screenshot: z.boolean(),
58
+ createdAt: z.string().max(64),
59
+ updatedAt: z.string().max(64),
60
+ })
61
+ export type SealedThread = z.infer<typeof sealedThreadSchema>
62
+
63
+ export const sealedThreadsSchema = z.object({ threads: z.array(sealedThreadSchema) })
64
+
65
+ export const createRemoteProjectBodySchema = z.object({ origins: z.array(reviewOriginSchema).min(1).max(MAX_ORIGINS) })
66
+ export const createRemoteProjectResponseSchema = z.object({ projectId: z.string().regex(REMOTE_PROJECT_ID_RE), agentToken: z.string().min(32) })
67
+
68
+ export const sealedCreateThreadBodySchema = z.object({
69
+ anchor: sealed(MAX_SEALED_ANCHOR),
70
+ body: sealed(MAX_SEALED_BODY),
71
+ send: z.boolean(),
72
+ /** The PNG data URL, sealed. */
73
+ screenshot: sealed(MAX_SEALED_SCREENSHOT).optional(),
74
+ })
75
+ export const sealedCommentBodySchema = z.object({ body: sealed(MAX_SEALED_BODY), send: z.boolean() })
76
+ export const sealedAgentReplyBodySchema = z.object({ body: sealed(MAX_SEALED_BODY), resolve: z.boolean() })
77
+ export const sealedScreenshotSchema = z.object({ screenshot: sealed(MAX_SEALED_SCREENSHOT) })
78
+
79
+ /** Frames the worker sends to a project's browsers. */
80
+ export type RemoteBrowserFrame =
81
+ | { type: 'threads'; threads: readonly SealedThread[] }
82
+ | { type: 'agent-status'; watching: boolean }
83
+
84
+ /** Sockets send this to keep an idle connection open; the worker answers `pong` without waking the project. */
85
+ export const KEEPALIVE_PING = 'ping'
86
+ export const KEEPALIVE_PONG = 'pong'
87
+
88
+ export interface ReviewCredentials {
89
+ projectId: string
90
+ /** The base64url AES-GCM key, as `exportShareKey` writes it. */
91
+ key: string
92
+ }
93
+
94
+ const KEY_RE = /^[A-Za-z0-9_-]{43}$/
95
+
96
+ /** `<projectId>.<key>`, the value of the fragment parameter. */
97
+ export function formatReviewCredentials(credentials: ReviewCredentials): string {
98
+ return `${credentials.projectId}.${credentials.key}`
99
+ }
100
+
101
+ export function parseReviewCredentials(value: string): ReviewCredentials | null {
102
+ const [projectId, key, ...rest] = value.split('.')
103
+ if (projectId === undefined || key === undefined || rest.length > 0) return null
104
+ if (!REMOTE_PROJECT_ID_RE.test(projectId) || !KEY_RE.test(key)) return null
105
+ return { projectId, key }
106
+ }
107
+
108
+ /**
109
+ * A WebSocket client cannot always set headers, so the agent's wait socket offers its token as a second subprotocol:
110
+ * `[AGENT_SOCKET_PROTOCOL, <agent token>]`. The worker answers with the first one only.
111
+ */
112
+ export const AGENT_SOCKET_PROTOCOL = 'agent-canvas-review'
@@ -0,0 +1,35 @@
1
+ import { decryptString, encryptString } from '../../client/shareCrypto'
2
+ import { type ReviewAnchor, reviewAnchorSchema, type ReviewThread, reviewThreadSchema } from './model'
3
+ import type { SealedThread } from './remote'
4
+
5
+ /** What the reviewer's browser and the agent's CLI seal before a remote project's worker sees it, and open after. */
6
+
7
+ export function sealAnchor(key: CryptoKey, anchor: ReviewAnchor): Promise<string> {
8
+ return encryptString(key, JSON.stringify(anchor))
9
+ }
10
+
11
+ export function sealText(key: CryptoKey, text: string): Promise<string> {
12
+ return encryptString(key, text)
13
+ }
14
+
15
+ export function openText(key: CryptoKey, sealed: string): Promise<string> {
16
+ return decryptString(key, sealed)
17
+ }
18
+
19
+ /**
20
+ * Opens a thread into the shape the widget and the agent read. A thread that does not decrypt with the key or does not
21
+ * parse once open was not sealed by this project's browser or CLI; it throws.
22
+ */
23
+ export async function openThread(key: CryptoKey, thread: SealedThread, screenshot?: string): Promise<ReviewThread> {
24
+ const anchor: unknown = JSON.parse(await decryptString(key, thread.anchor))
25
+ const comments = await Promise.all(thread.comments.map(async (comment) => ({ ...comment, body: await decryptString(key, comment.body) })))
26
+ return reviewThreadSchema.parse({
27
+ id: thread.id,
28
+ anchor: reviewAnchorSchema.parse(anchor),
29
+ state: thread.state,
30
+ comments,
31
+ ...(screenshot === undefined ? {} : { screenshot }),
32
+ createdAt: thread.createdAt,
33
+ updatedAt: thread.updatedAt,
34
+ })
35
+ }
@@ -12,7 +12,8 @@ import {
12
12
  type ReviewWaitFrame,
13
13
  } from './model'
14
14
  import type { ReviewProxies } from './proxy'
15
- import { ReviewError, type ReviewStore } from './store'
15
+ import type { ReviewStore } from './store'
16
+ import { ReviewError } from './threads'
16
17
 
17
18
  export interface ReviewSocketData {
18
19
  type: 'review'
@@ -130,6 +131,15 @@ export function createReviewServer(store: ReviewStore, proxies: ReviewProxies) {
130
131
  notifyAgent(project)
131
132
  return { thread }
132
133
  }),
134
+ route('POST', '/api/review/:project/notes/send', 'browser', async (_req, match) => {
135
+ const project = projectOf(match)
136
+ const threads = store.sendNotes(project)
137
+ if (threads.length > 0) {
138
+ publish(project)
139
+ notifyAgent(project)
140
+ }
141
+ return { threads }
142
+ }),
133
143
  route('POST', '/api/review/:project/threads/:thread/resolve', 'browser', async (_req, match) => {
134
144
  const project = projectOf(match)
135
145
  const thread = store.setResolved(project, threadIdOf(match), true)
@@ -170,6 +180,11 @@ export function createReviewServer(store: ReviewStore, proxies: ReviewProxies) {
170
180
 
171
181
  return {
172
182
  channel,
183
+ /** Hands a full reload the application asked for to the project's widgets, which reload unless the reviewer is writing. */
184
+ fullReload(project: string, path: string): void {
185
+ const frame: ReviewBrowserFrame = { type: 'reload', path }
186
+ channel.broadcast(project, frame)
187
+ },
173
188
  /** Answers the request when it is review mode's: CORS preflight, a route, or a WebSocket upgrade. */
174
189
  fetch(
175
190
  req: Request,
@@ -4,18 +4,13 @@ import {
4
4
  PROJECT_RE,
5
5
  type ReviewAnchor,
6
6
  type ReviewAuthor,
7
+ type ReviewComment,
7
8
  type ReviewProxy,
8
9
  reviewProxySchema,
9
10
  type ReviewThread,
10
11
  reviewThreadsFileSchema,
11
- type ReviewThreadState,
12
12
  } from './model'
13
-
14
- export class ReviewError extends Error {
15
- constructor(message: string, readonly status: 400 | 404 | 409) {
16
- super(message)
17
- }
18
- }
13
+ import { agentReplied, claimed, notesSent, openingState, resolvedAs, ReviewError, sent, userCommented } from './threads'
19
14
 
20
15
  /**
21
16
  * Review threads of each project: `<directory>/<project>/threads.json`, attached screenshots beside it, and the
@@ -36,7 +31,7 @@ export class ReviewStore {
36
31
  const thread: ReviewThread = {
37
32
  id,
38
33
  anchor,
39
- state: send ? 'queued' : 'open',
34
+ state: openingState(send),
40
35
  comments: [{ id: Bun.randomUUIDv7(), author: 'user', body, createdAt }],
41
36
  ...(screenshot === undefined ? {} : { screenshot: this.writeScreenshot(project, id, screenshot) }),
42
37
  createdAt,
@@ -48,21 +43,22 @@ export class ReviewStore {
48
43
 
49
44
  /** A comment from the person reopens a resolved thread; with `send` it goes to the agent. */
50
45
  addUserComment(project: string, threadId: string, body: string, send: boolean): ReviewThread {
51
- return this.update(project, threadId, (thread) => {
52
- const state: ReviewThreadState = send ? 'queued' : thread.state === 'resolved' ? 'open' : thread.state
53
- return { ...this.withComment(thread, 'user', body), state }
54
- })
46
+ return this.update(project, threadId, (thread) => userCommented(thread, this.comment('user', body), send))
55
47
  }
56
48
 
57
49
  send(project: string, threadId: string): ReviewThread {
58
- return this.update(project, threadId, (thread) => {
59
- if (thread.state === 'working') throw new ReviewError('The agent is already working on this thread', 409)
60
- return { ...thread, state: 'queued', updatedAt: this.timestamp() }
61
- })
50
+ return this.update(project, threadId, (thread) => sent(thread, this.timestamp()))
51
+ }
52
+
53
+ /** Sends every unsent note at once, so the agent picks them up as one batch. */
54
+ sendNotes(project: string): readonly ReviewThread[] {
55
+ const result = notesSent(this.list(project), this.timestamp())
56
+ this.save(project, result.threads)
57
+ return result.sent
62
58
  }
63
59
 
64
60
  setResolved(project: string, threadId: string, resolved: boolean): ReviewThread {
65
- return this.update(project, threadId, (thread) => ({ ...thread, state: resolved ? 'resolved' : 'open', updatedAt: this.timestamp() }))
61
+ return this.update(project, threadId, (thread) => resolvedAs(thread, resolved, this.timestamp()))
66
62
  }
67
63
 
68
64
  delete(project: string, threadId: string): void {
@@ -75,18 +71,15 @@ export class ReviewStore {
75
71
 
76
72
  /** Hands every queued thread to the agent: they become `working` and are returned in creation order. */
77
73
  claimQueued(project: string): readonly ReviewThread[] {
78
- const threads = this.list(project)
79
- const claimed = threads.filter((thread) => thread.state === 'queued')
80
- if (claimed.length === 0) return []
81
- const updatedAt = this.timestamp()
82
- const claimedIds = new Set(claimed.map((thread) => thread.id))
83
- this.save(project, threads.map((thread) => (claimedIds.has(thread.id) ? { ...thread, state: 'working', updatedAt } : thread)))
84
- return claimed.map((thread) => ({ ...thread, state: 'working', updatedAt }))
74
+ const result = claimed(this.list(project), this.timestamp())
75
+ if (result.claimed.length === 0) return []
76
+ this.save(project, result.threads)
77
+ return result.claimed
85
78
  }
86
79
 
87
80
  /** The agent's answer. Without `resolve` the thread goes back to the person as `open`. */
88
81
  agentReply(project: string, threadId: string, body: string, resolve: boolean): ReviewThread {
89
- return this.update(project, threadId, (thread) => ({ ...this.withComment(thread, 'agent', body), state: resolve ? 'resolved' : 'open' }))
82
+ return this.update(project, threadId, (thread) => agentReplied(thread, this.comment('agent', body), resolve))
90
83
  }
91
84
 
92
85
  proxyOf(project: string): ReviewProxy | undefined {
@@ -114,9 +107,8 @@ export class ReviewStore {
114
107
  return next
115
108
  }
116
109
 
117
- private withComment(thread: ReviewThread, author: ReviewAuthor, body: string): ReviewThread {
118
- const createdAt = this.timestamp()
119
- return { ...thread, comments: [...thread.comments, { id: Bun.randomUUIDv7(), author, body, createdAt }], updatedAt: createdAt }
110
+ private comment(author: ReviewAuthor, body: string): ReviewComment {
111
+ return { id: Bun.randomUUIDv7(), author, body, createdAt: this.timestamp() }
120
112
  }
121
113
 
122
114
  private writeScreenshot(project: string, threadId: string, png: Uint8Array): string {