@nxxxsooo/opencode-annotate 0.17.0 → 0.18.0

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.18.0 — Select page areas
4
+
5
+ - Choose **Select area** in the browser panel and drag a rectangle. Feedback
6
+ includes page coordinates, visible text and element selectors when available.
7
+ No screenshot is captured.
8
+ - Unsent areas keep their numbered outlines when you scroll, reload or return
9
+ to the page. Select an outline to move or resize it and refresh its evidence
10
+ without changing the note number.
11
+ - Reload the Chrome extension and restart OpenCode after updating for browser
12
+ protocol 10.
13
+
14
+ ## 0.17.1 — picking inside modal drawers
15
+
16
+ - Keep element highlights, saved-note markers and reveal outlines visible above
17
+ modal dialogs and drawers, including nested dialogs and same-origin frames.
18
+ - Restore the overlay as dialogs open, close or reopen without intercepting page
19
+ clicks. Saved notes and browser protocol 8 are unchanged.
20
+ - Reload the Chrome extension and refresh pages already using annotation tools
21
+ after updating. Saved notes remain available.
22
+
3
23
  ## 0.17.0 — clear the round
4
24
 
5
25
  - **Clear** in the notes header removes every unsent note in the round; each page
package/README.md CHANGED
@@ -107,6 +107,27 @@ Browser setup is separate from the plugin install. Safari supports local notes a
107
107
 
108
108
  Numbered `/annotate N`, `/annotate-last` and `/annotate-web` are retired. Use `/annotate-pick` for earlier text, `/annotate` for the latest reply, and `/annotate <url-or-html>` for a page. Browser connection controls live in the extension's destination menu.
109
109
 
110
+ ## Herdr
111
+
112
+ Run the bundled `annotate-tui` directly from a Herdr pane. Herdr needs an enabled
113
+ `annotate` plugin with a `doc` pane entrypoint; see the [TUI setup](tui/README.md#herdr).
114
+ OpenCode's `/annotate` keeps its own session delivery, even when OpenCode runs in Herdr.
115
+
116
+ ```sh
117
+ annotate-tui herdr open docs/plan.md --placement split --deliver-to w1:p2
118
+ annotate-tui herdr open docs/ --deliver-to w1:p2
119
+ annotate-tui herdr last --deliver-to w1:p2
120
+ annotate-tui herdr terminal --lines 20 --deliver-to w1:p2
121
+ annotate-tui herdr terminal --lines 5 --print
122
+ ```
123
+
124
+ - `open`, `last` and `terminal` accept `--placement overlay|split|tab|zoomed`. The default is `overlay`.
125
+ - `last` opens a reply picker; add `--newest` to open the newest reply directly. With `--deliver-to`, it reads that pane's agent session.
126
+ - `terminal` reviews recent output from the calling pane, even if feedback goes to a different pane. `--print` writes a fenced Markdown block to stdout instead of opening a reviewer.
127
+ - Replace `w1:p2` with the receiving agent's pane ID. **Send** submits the feedback as a prompt, including Enter. If Herdr reports the agent is blocked at a dialog, no prompt is sent. Annotate keeps the notes pending and tries to copy the feedback to the terminal clipboard; resolve the dialog and retry when ready.
128
+
129
+ Outside Herdr, use `annotate-tui docs/plan.md` to copy feedback via a terminal that supports OSC 52. `herdr open` requires a Herdr pane.
130
+
110
131
  ## Upgrading from the TUI-only package
111
132
 
112
133
  `opencode-annotate` replaces `opencode-plannotator-tui` (0.4.2 and earlier). To switch, run `opencode plugin remove opencode-plannotator-tui@latest` and then install this package as shown above.
@@ -176,7 +197,7 @@ After updates, run `npm run build:safari` with the signing variables again, then
176
197
 
177
198
  Click the destination beside **To** to filter sessions by title or directory and sort by recent activity, creation or title. The picker refreshes automatically and shows current session titles. **New session** creates an empty session with the chosen session's location/model, or the blank OpenCode home's current selection, without starting a model turn. **Disconnect** keeps the destination named and notes local; choosing that session again reconnects. A disconnected destination never silently switches to another session. Restarted receivers reconnect by stable provider/session identity, carrying any retry batch to the replacement.
178
199
 
179
- Choose **Pick element** or select text, then write a comment or question. The composer appears for that selection. **Send N notes & continue** saves current feedback and sends all pending notes across pages; **Add note** collects feedback locally. Cmd/Ctrl+Enter adds a note or saves an edit. Confirmed sends use `steer` / `resume: true`: idle sessions start immediately and running turns receive feedback at their next processing boundary. Registering, creating sessions and saving notes make no model call. Switching terminal tabs never changes the captured destination.
200
+ Choose **Pick element**, drag a rectangle with **Select area**, or select text directly, then write a comment or question. Unsent areas stay marked: click a dashed outline or badge to activate it, drag the rectangle to move it, or drag a handle to resize. Esc cancels an adjustment. Area notes include the rectangle's position, visible text, and element hints, without a screenshot. **Send N notes & continue** saves current feedback and sends all pending notes across pages; **Add note** collects feedback locally. Cmd/Ctrl+Enter adds a note or saves an edit. Confirmed sends use `steer` / `resume: true`: idle sessions start immediately and running turns receive feedback at their next processing boundary. Registering, creating sessions and saving notes make no model call. Switching terminal tabs never changes the captured destination.
180
201
 
181
202
  The queue groups notes by page, with contiguous numbers matching page markers and delivered Markdown. Click a note's quoted target to show it on its page without activating the element; off-page notes can open their page. **Edit** changes the feedback, and **Undo** restores a deleted note. The delivery bar shows the whole round's count and destination; drafts remain page-local.
182
203
 
@@ -1,36 +1,209 @@
1
1
  (() => {
2
2
  if (globalThis.__opencodeAnnotate === true) throw new Error("Refresh this page once to update annotation tools. Saved notes will remain.")
3
- if (globalThis.__opencodeAnnotate?.version === 7) return
3
+ if (globalThis.__opencodeAnnotate?.version === 10) return
4
4
  globalThis.__opencodeAnnotate?.dispose()
5
5
  if (!["text/html", "application/xhtml+xml"].includes(document.contentType)) throw new Error("Only HTML pages are supported")
6
6
  const listeners = new AbortController()
7
7
  const on = (target, event, handler, options = {}) => target.addEventListener(event, handler, { ...options, signal: listeners.signal })
8
8
  const host = document.createElement("div")
9
9
  host.setAttribute("data-opencode-annotate", "")
10
+ host.setAttribute("aria-hidden", "true")
11
+ // A manual popover keeps viewport coordinates even under a transformed dialog.
12
+ host.setAttribute("popover", "manual")
10
13
  host.style.cssText = "all:initial!important;position:fixed!important;inset:0!important;pointer-events:none!important;z-index:2147483647!important"
11
14
  const root = host.attachShadow({ mode: "closed" })
12
15
  const style = document.createElement("style")
13
- style.textContent = '.box{position:fixed;pointer-events:none;border:2px solid #c96442;background:#c9644210}.pin{position:fixed;display:grid;place-items:center;background:#c96442;color:#fff;border:2px solid #fff;border-radius:50%;font:600 12px/1 system-ui;width:26px;height:26px;pointer-events:none}'
16
+ style.textContent = `
17
+ .box{position:fixed;pointer-events:none;border:2px solid #c96442;background:#c9644210}
18
+ .area{box-sizing:border-box}
19
+ .pin{position:fixed;display:grid;place-items:center;background:#c96442;color:#fff;border:2px solid #fff;border-radius:50%;font:600 12px/1 system-ui;width:26px;height:26px;pointer-events:none}
20
+ .area-mark{border-style:dashed}
21
+ .area-mark.is-active{border-style:solid;z-index:1}
22
+ .area-mark .pin,.edge,.handle{position:absolute;touch-action:none}
23
+ .area-mark .pin{left:-12px;top:-12px}
24
+ .edge[data-side="n"],.edge[data-side="s"]{left:0;right:0;height:4px}
25
+ .edge[data-side="w"],.edge[data-side="e"]{top:0;bottom:0;width:4px}
26
+ .edge[data-side="n"]{top:-3px}.edge[data-side="s"]{bottom:-3px}
27
+ .edge[data-side="w"]{left:-3px}.edge[data-side="e"]{right:-3px}
28
+ .handle{width:8px;height:8px;border:1px solid #c96442;background:#fff;transform:translate(-50%,-50%)}
29
+ .area-layer:not(.passive) .area-mark.is-active,.area-layer:not(.passive) :is(.edge,.pin,.handle){pointer-events:auto;cursor:move;touch-action:none}
30
+ `
14
31
  root.append(style); document.documentElement.append(host)
32
+ const areaLayer = document.createElement("div"); areaLayer.className = "area-layer"; root.append(areaLayer)
15
33
  const box = document.createElement("div"); box.className = "box"
16
34
  const highlight = document.createElement("div"); highlight.className = "box"
35
+ const shield = document.createElement("div")
36
+ shield.style.cssText = "position:fixed;inset:0;pointer-events:auto;cursor:crosshair;touch-action:none"
17
37
  let highlighted, highlightTimer
18
- let picking = false, url = location.href, timer, markers = [], active = true
38
+ const MIN_AREA = 5
39
+ let mode = null, areaEvents, drag, areaDrag, url = location.href, timer, markers = [], active = true
40
+ let draftMarker, markerFocus, markerKey
41
+ let modals = []
42
+ function syncLayer(force = false) {
43
+ const next = [...document.querySelectorAll("dialog:modal")]
44
+ // Hit testing through the backdrop finds the top modal even when another
45
+ // modal follows it in DOM order. The active modal's subtree is the only
46
+ // place where top-layer area controls can receive pointer events.
47
+ const modal = next.length > 1 ? document.elementFromPoint(0, 0)?.closest("dialog:modal") || next.at(-1) : next[0]
48
+ const parent = modal || document.documentElement
49
+ const move = host.parentElement !== parent
50
+ const changed = move || force || next.length !== modals.length || next.some((node, index) => node !== modals[index])
51
+ if (changed && mode === "element") box.remove()
52
+ if (changed && host.matches(":popover-open")) host.hidePopover()
53
+ if (move) parent.append(host)
54
+ if (!host.matches(":popover-open")) host.showPopover()
55
+ modals = next
56
+ }
57
+ syncLayer()
19
58
  function send(anchor = null, error = null, modeOnly = false, ready = false) {
20
59
  if (!active) return
21
60
  try {
22
- chrome.runtime.sendMessage({ action: "capture", page: { url: location.href, title: document.title }, frame: AnnotateInspector.frame(), anchor, error, picking, modeOnly, ready }).catch(dispose)
61
+ chrome.runtime.sendMessage({ action: "capture", page: { url: location.href, title: document.title }, frame: AnnotateInspector.frame(), anchor, error, mode, modeOnly, ready }).catch(dispose)
23
62
  } catch { dispose() }
24
63
  }
25
- function setPicking(value, notify = true) {
26
- picking = value
27
- // Only a hover over a real element adds the box. Reapplying frame-wide
28
- // picker state must not resurrect a box hidden at an iframe boundary.
29
- if (!picking) box.remove()
64
+ function setMode(value, notify = true) {
65
+ if (mode === value) return
66
+ areaEvents?.abort(); areaEvents = null
67
+ clearDrag(); shield.remove(); box.remove()
68
+ cancelAdjust()
69
+ mode = value
70
+ areaLayer.classList.toggle("passive", !!mode)
71
+ box.classList.toggle("area", mode === "area")
72
+ if (mode === "area") startArea()
30
73
  if (notify) send(null, null, true)
31
74
  }
75
+ const point = event => ({ x: event.clientX, y: event.clientY })
76
+ function documentRect() {
77
+ const x = drag.end.x + scrollX, y = drag.end.y + scrollY
78
+ return { x: Math.round(Math.min(drag.start.x, x)), y: Math.round(Math.min(drag.start.y, y)),
79
+ width: Math.round(Math.abs(drag.start.x - x)), height: Math.round(Math.abs(drag.start.y - y)) }
80
+ }
81
+ const areaRect = ({ rect }) => new DOMRect(rect.x - scrollX, rect.y - scrollY, rect.width, rect.height)
82
+ function paint(node, rect) {
83
+ node.style.cssText = `left:${rect.x}px;top:${rect.y}px;width:${rect.width}px;height:${rect.height}px`
84
+ }
85
+ function clearDrag() {
86
+ if (!drag) return
87
+ const { target, id } = drag
88
+ drag = null
89
+ if (target.hasPointerCapture(id)) target.releasePointerCapture(id)
90
+ box.remove()
91
+ }
92
+ function startArea() {
93
+ areaEvents = new AbortController()
94
+ const listen = (event, handler) => window.addEventListener(event, handler, { capture: true, signal: areaEvents.signal })
95
+ const block = event => { event.preventDefault(); event.stopImmediatePropagation() }
96
+ root.prepend(shield)
97
+ listen("pointerdown", event => {
98
+ block(event)
99
+ if (event.button !== 0 || drag) return
100
+ const target = event.target === host ? shield : event.target
101
+ drag = { id: event.pointerId, target, start: { x: event.clientX + scrollX, y: event.clientY + scrollY }, end: point(event) }
102
+ target.setPointerCapture(drag.id)
103
+ })
104
+ listen("pointermove", event => {
105
+ if (drag?.id !== event.pointerId) return
106
+ block(event)
107
+ drag.end = point(event); drawArea()
108
+ })
109
+ let finishTimer, completed
110
+ const finish = () => {
111
+ clearTimeout(finishTimer)
112
+ if (!completed) return
113
+ const rect = completed; completed = null
114
+ setMode(null, false)
115
+ try { send(captureArea(rect)) } catch (error) { send(null, error.message) }
116
+ }
117
+ listen("pointerup", event => {
118
+ block(event)
119
+ if (drag?.id !== event.pointerId) return
120
+ drag.end = point(event)
121
+ const rect = documentRect()
122
+ clearDrag()
123
+ if (rect.width < MIN_AREA || rect.height < MIN_AREA) return
124
+ completed = rect; finishTimer = setTimeout(finish, 0)
125
+ })
126
+ listen("click", event => { block(event); finish() })
127
+ const cancelDrag = event => { if (drag?.id === event.pointerId) clearDrag() }
128
+ listen("pointercancel", cancelDrag)
129
+ listen("lostpointercapture", cancelDrag)
130
+ listen("keydown", event => { if (event.key === "Escape") { block(event); setMode(null) } })
131
+ areaEvents.signal.addEventListener("abort", () => clearTimeout(finishTimer), { once: true })
132
+ }
133
+ function drawArea() {
134
+ if (!drag) return
135
+ root.append(box)
136
+ paint(box, areaRect({ rect: documentRect() }))
137
+ }
138
+ const captureArea = rect => AnnotateInspector.captureArea(rect, host.closest("dialog:modal") || document.body)
139
+ const directions = ["n", "ne", "e", "se", "s", "sw", "w", "nw"]
140
+ const block = event => { event.preventDefault(); event.stopImmediatePropagation() }
141
+ const docPoint = event => ({ x: event.clientX + scrollX, y: event.clientY + scrollY })
142
+ function adjustRect({ marker, side, start, end }) {
143
+ const { x, y, width, height } = marker.anchor.rect
144
+ const dx = Math.round(end.x + scrollX - start.x), dy = Math.round(end.y + scrollY - start.y)
145
+ if (!side) return { x: x + dx, y: y + dy, width, height }
146
+ const left = side.includes("w") ? Math.min(x + dx, x + width - MIN_AREA) : x
147
+ const right = side.includes("e") ? Math.max(left + MIN_AREA, x + width + dx) : x + width
148
+ const top = side.includes("n") ? Math.min(y + dy, y + height - MIN_AREA) : y
149
+ const bottom = side.includes("s") ? Math.max(top + MIN_AREA, y + height + dy) : y + height
150
+ return { x: left, y: top, width: right - left, height: bottom - top }
151
+ }
152
+ function cancelAdjust(repaint = true) {
153
+ if (!areaDrag) return
154
+ const { id } = areaDrag
155
+ areaDrag = null
156
+ if (areaLayer.hasPointerCapture(id)) areaLayer.releasePointerCapture(id)
157
+ if (repaint) drawAreaMarkers()
158
+ }
159
+ async function areaGesture(action, marker, anchor) {
160
+ try {
161
+ const result = await chrome.runtime.sendMessage({ action, page: { url: location.href }, frame: AnnotateInspector.frame(),
162
+ id: marker.id, revision: marker.revision, baseRect: marker.anchor.rect, anchor })
163
+ if (!result.ok) throw new Error(result.error)
164
+ } catch (error) {
165
+ send(null, error.message, true)
166
+ }
167
+ }
168
+ on(areaLayer, "pointerdown", event => {
169
+ const id = event.target.closest(".area-mark")?.dataset.markerId
170
+ if (mode || !id) return
171
+ block(event)
172
+ if (event.button !== 0 || areaDrag) return
173
+ const marker = id === draftMarker?.id ? draftMarker : markers.find(note => note.id === id)
174
+ if (!marker) return
175
+ const adjustable = event.target.closest(".area-mark").classList.contains("is-active")
176
+ areaDrag = { id: event.pointerId, marker, adjustable, side: event.target.dataset.handle,
177
+ start: docPoint(event), end: point(event) }
178
+ areaLayer.setPointerCapture(event.pointerId)
179
+ })
180
+ on(window, "pointermove", event => {
181
+ if (!areaDrag || areaDrag.id !== event.pointerId) return
182
+ block(event)
183
+ areaDrag.end = point(event)
184
+ if (areaDrag.adjustable) drawAreaMarkers()
185
+ }, { capture: true })
186
+ on(window, "pointerup", event => {
187
+ if (!areaDrag || areaDrag.id !== event.pointerId) return
188
+ block(event)
189
+ const { adjustable, marker } = areaDrag
190
+ areaDrag.end = point(event)
191
+ const rect = adjustRect(areaDrag)
192
+ cancelAdjust()
193
+ if (adjustable && Object.keys(rect).some(key => rect[key] !== marker.anchor.rect[key])) {
194
+ try { void areaGesture("area-adjust", marker, captureArea(rect)) }
195
+ catch (error) { send(null, error.message, true) }
196
+ } else void areaGesture("area-focus", marker)
197
+ }, { capture: true })
198
+ on(window, "click", event => { if (event.target === host && !mode) block(event) }, { capture: true })
199
+ on(window, "keydown", event => {
200
+ if (event.key === "Escape" && areaDrag) { block(event); cancelAdjust() }
201
+ }, { capture: true })
202
+ for (const name of ["pointercancel", "lostpointercapture"]) on(window, name, event => {
203
+ if (areaDrag?.id === event.pointerId) cancelAdjust()
204
+ }, { capture: true })
32
205
  function selection() {
33
- if (picking || !active) return
206
+ if (mode || !active) return
34
207
  const selected = getSelection()
35
208
  if (!selected?.rangeCount || selected.isCollapsed || selected.anchorNode?.getRootNode() !== document) return
36
209
  const range = selected.getRangeAt(0).cloneRange()
@@ -41,7 +214,8 @@
41
214
  on(document, "selectionchange", () => { clearTimeout(timer); timer = setTimeout(selection, 160) })
42
215
  on(document, "pointerup", selection)
43
216
  const hover = event => {
44
- if (!picking) return
217
+ if (mode !== "element") return
218
+ syncLayer()
45
219
  if (["iframe", "frame", "frameset"].includes(event.target.localName)) {
46
220
  box.remove()
47
221
  if (event.target.localName !== "frameset") {
@@ -52,37 +226,51 @@
52
226
  }
53
227
  root.append(box)
54
228
  const rect = event.target.getBoundingClientRect()
55
- box.style.cssText = `left:${rect.x}px;top:${rect.y}px;width:${rect.width}px;height:${rect.height}px`
229
+ paint(box, rect)
56
230
  }
57
231
  on(document, "mousemove", hover, { capture: true })
58
232
  on(document, "pointerover", hover, { capture: true })
59
- on(document, "pointerdown", event => { if (picking) { event.preventDefault(); event.stopImmediatePropagation() } }, { capture: true })
233
+ on(document, "pointerdown", event => { if (mode === "element") { event.preventDefault(); event.stopImmediatePropagation() } }, { capture: true })
60
234
  on(document, "click", event => {
61
- if (!picking) return
235
+ if (mode !== "element") return
62
236
  if (event.target.localName === "frameset") return
63
237
  if (["iframe", "frame"].includes(event.target.localName)) {
64
238
  try { if (event.target.contentDocument) { box.remove(); return } } catch { /* inaccessible frame: explain below */ }
65
239
  }
66
240
  event.preventDefault(); event.stopImmediatePropagation()
67
241
  // A failed pick must never leave the page trapped in interception mode.
68
- setPicking(false, false)
242
+ setMode(null, false)
69
243
  try { send(AnnotateInspector.capture(event.target)) } catch (error) { send(null, error.message) }
70
244
  }, { capture: true })
71
- on(document, "keydown", event => { if (picking && event.key === "Escape") setPicking(false) })
245
+ on(document, "keydown", event => { if (mode === "element" && event.key === "Escape") setMode(null) })
72
246
  const onMessage = (message, _sender, respond) => {
73
247
  if (message.action === "annotate-ping") { respond({ ok: true }); return }
74
- if (message.action === "pick") { setPicking(message.picking, false); respond({ ok: true, picking }) }
75
- if (message.action === "markers") { markers = message.notes || []; draw(); respond({ ok: true }) }
248
+ if (message.action === "pick") { setMode(message.mode, false); respond({ ok: true, mode }) }
249
+ if (message.action === "markers") {
250
+ const key = JSON.stringify([message.notes, message.draft, message.focus])
251
+ if (key !== markerKey) {
252
+ markerKey = key; markers = message.notes || []; draftMarker = message.draft; markerFocus = message.focus
253
+ draw()
254
+ }
255
+ respond({ ok: true })
256
+ }
76
257
  if (message.action === "locate") respond({ states: message.anchors.map(locate) })
77
258
  if (message.action === "reveal") {
78
259
  const state = locate(message.anchor)
79
260
  if (state !== "located") {
80
- respond({ ok: false, error: `This element is ${state}. Your feedback is kept.` })
261
+ respond({ ok: false, error: `This target is ${state}. Your feedback is kept.` })
81
262
  return
82
263
  }
83
- setPicking(false, false)
84
- highlighted = document.querySelector(message.anchor.selector)
85
- highlighted.scrollIntoView({ block: "center", inline: "nearest", behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "instant" : "smooth" })
264
+ setMode(null, false)
265
+ const behavior = matchMedia("(prefers-reduced-motion: reduce)").matches ? "instant" : "smooth"
266
+ if (message.anchor.type === "area") {
267
+ const { x, y, width, height } = message.anchor.rect
268
+ window.scrollTo({ left: x + (width - innerWidth) / 2, top: y + (height - innerHeight) / 2, behavior })
269
+ respond({ ok: true }); return
270
+ } else {
271
+ highlighted = document.querySelector(message.anchor.selector)
272
+ highlighted.scrollIntoView({ block: "center", inline: "nearest", behavior })
273
+ }
86
274
  root.append(highlight); draw()
87
275
  clearTimeout(highlightTimer)
88
276
  highlightTimer = setTimeout(() => { highlighted = null; highlight.remove() }, 1600)
@@ -91,6 +279,7 @@
91
279
  }
92
280
  chrome.runtime.onMessage.addListener(onMessage)
93
281
  function locate(anchor) {
282
+ if (anchor.type === "area") return "located"
94
283
  try {
95
284
  const matches = document.querySelectorAll(anchor.selector)
96
285
  if (matches.length !== 1) return matches.length ? "ambiguous" : "missing"
@@ -102,37 +291,76 @@
102
291
  return "located"
103
292
  } catch { return "invalid selector" }
104
293
  }
294
+ function drawAreaMarkers() {
295
+ const draws = []
296
+ for (const [index, marker] of [...markers, ...(draftMarker ? [draftMarker] : [])].entries()) {
297
+ if (marker.anchor?.type !== "area") continue
298
+ const isDraft = marker === draftMarker
299
+ const selected = marker.id && (markerFocus ? marker.id === markerFocus : isDraft)
300
+ const rect = areaDrag?.adjustable && areaDrag.marker.id === marker.id ? adjustRect(areaDrag) : marker.anchor.rect
301
+ const mark = document.createElement("div")
302
+ mark.className = `box area area-mark${selected ? " is-active" : ""}`
303
+ if (marker.id) mark.dataset.markerId = marker.id
304
+ paint(mark, areaRect({ rect }))
305
+ if (selected) {
306
+ for (const side of directions) {
307
+ const handle = document.createElement("span"); handle.className = "handle"; handle.dataset.handle = side
308
+ handle.style.cssText = `left:${side.includes("w") ? "0" : side.includes("e") ? "100%" : "50%"};top:${side.includes("n") ? "0" : side.includes("s") ? "100%" : "50%"};cursor:${side}-resize`
309
+ mark.append(handle)
310
+ }
311
+ } else if (marker.id) {
312
+ for (const side of ["n", "e", "s", "w"]) {
313
+ const edge = document.createElement("span"); edge.className = "edge"; edge.dataset.side = side; mark.append(edge)
314
+ }
315
+ }
316
+ if (!isDraft) {
317
+ const pin = document.createElement("span"); pin.className = "pin"; pin.textContent = String(marker.number ?? index + 1)
318
+ mark.append(pin)
319
+ }
320
+ draws.push(mark)
321
+ }
322
+ areaLayer.replaceChildren(...draws)
323
+ }
105
324
  function draw() {
106
- if (highlighted?.isConnected) {
107
- const rect = highlighted.getBoundingClientRect()
108
- highlight.style.cssText = `left:${rect.left}px;top:${rect.top}px;width:${rect.width}px;height:${rect.height}px`
109
- } else highlight.remove()
110
- root.querySelectorAll(".pin").forEach(node => node.remove())
325
+ syncLayer()
326
+ drawArea()
327
+ drawAreaMarkers()
328
+ if (highlighted?.isConnected) paint(highlight, highlighted.getBoundingClientRect())
329
+ else highlight.remove()
330
+ for (const child of [...root.children]) if (child.classList.contains("pin")) child.remove()
111
331
  for (const [index, note] of markers.entries()) {
332
+ if (!note.anchor || note.anchor.type === "area") continue
112
333
  let matches
113
334
  try { matches = document.querySelectorAll(note.anchor.selector) } catch { continue }
114
- if (matches.length !== 1) continue
115
- const element = matches[0]
116
- // A changed or removed quote is an orphan, not another equally named element.
117
- if (!AnnotateInspector.text(element).includes(note.anchor.quote)) continue
118
- const rect = element.getBoundingClientRect()
119
- const pin = document.createElement("span"); pin.className = "pin"; pin.textContent = String(index + 1)
335
+ if (matches.length !== 1 || !AnnotateInspector.text(matches[0]).includes(note.anchor.quote)) continue
336
+ const rect = matches[0].getBoundingClientRect()
337
+ const pin = document.createElement("span"); pin.className = "pin"; pin.textContent = String(note.number ?? index + 1)
120
338
  pin.style.cssText = `left:${rect.left - 10}px;top:${rect.top - 10}px`; root.append(pin)
121
339
  }
122
340
  }
123
341
  on(document, "scroll", draw, { capture: true, passive: true }); on(window, "resize", draw)
124
- const observer = new MutationObserver(() => { clearTimeout(timer); timer = setTimeout(draw, 160) })
125
- observer.observe(document.documentElement, { childList: true, subtree: true, characterData: true })
342
+ const observer = new MutationObserver(records => {
343
+ // showModal/close mutate `open`; observe it as well as removed dialogs.
344
+ // Force a raise even if a dialog closes and reopens in one mutation batch.
345
+ syncLayer(records.some(record => record.type === "attributes" && record.target.localName === "dialog"))
346
+ clearTimeout(timer); timer = setTimeout(draw, 160)
347
+ })
348
+ observer.observe(document.documentElement, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ["open"] })
126
349
  on(document, "load", event => {
127
350
  if (["iframe", "frame"].includes(event.target.localName)) chrome.runtime.sendMessage({ action: "frames-changed" }).catch(() => {})
128
351
  }, { capture: true })
129
- const routeTimer = setInterval(() => { if (!active) { observer.disconnect(); return } if (url !== location.href) { url = location.href; markers = []; draw(); send() } }, 700)
352
+ const routeTimer = setInterval(() => {
353
+ if (!active) { observer.disconnect(); return }
354
+ if (url !== location.href) {
355
+ url = location.href; setMode(null, false); cancelAdjust(false); markers = []; draftMarker = markerFocus = markerKey = null; draw(); send()
356
+ }
357
+ }, 700)
130
358
  function dispose() {
131
359
  if (!active) return
132
- active = false; listeners.abort(); clearInterval(routeTimer); clearTimeout(timer); clearTimeout(highlightTimer); observer.disconnect(); host.remove()
360
+ active = false; setMode(null, false); cancelAdjust(false); listeners.abort(); clearInterval(routeTimer); clearTimeout(timer); clearTimeout(highlightTimer); observer.disconnect(); host.remove()
133
361
  try { chrome.runtime.onMessage.removeListener(onMessage) } catch { /* previous extension context may already be invalidated */ }
134
362
  delete globalThis.__opencodeAnnotate
135
363
  }
136
- globalThis.__opencodeAnnotate = { dispose, version: 7 }
364
+ globalThis.__opencodeAnnotate = { dispose, version: 10 }
137
365
  send(null, null, true, true)
138
366
  })();
@@ -123,6 +123,71 @@
123
123
  rect: Object.fromEntries(["x", "y", "width", "height"].map(key => [key, Math.round(rect[key])])),
124
124
  viewport: { width: innerWidth, height: innerHeight, scrollX, scrollY } }
125
125
  }
126
+ const intersection = (a, b) => {
127
+ const left = Math.max(a.left, b.left), top = Math.max(a.top, b.top)
128
+ const right = Math.min(a.right, b.right), bottom = Math.min(a.bottom, b.bottom)
129
+ return right > left && bottom > top ? { left, top, right, bottom } : null
130
+ }
131
+ const size = rect => (rect.right - rect.left) * (rect.bottom - rect.top)
132
+ const contains = (outer, inner) => outer.left <= inner.left && outer.top <= inner.top && outer.right >= inner.right && outer.bottom >= inner.bottom
133
+ function captureArea(rect, container) {
134
+ const viewport = { width: innerWidth, height: innerHeight, scrollX, scrollY }
135
+ const region = intersection(new DOMRect(rect.x - scrollX, rect.y - scrollY, rect.width, rect.height), new DOMRect(0, 0, innerWidth, innerHeight))
136
+ if (!region || !container) return { type: "area", rect, viewport, quote: "", selectors: [] }
137
+ const omitted = textFilter(), clips = new WeakMap(), range = document.createRange(), candidates = []
138
+ function clip(element) {
139
+ if (!element) return region
140
+ if (clips.has(element)) return clips.get(element)
141
+ let bounds = clip(element.parentElement)
142
+ const style = getComputedStyle(element)
143
+ if (bounds && element.clientWidth && element.clientHeight && (style.overflowX !== "visible" || style.overflowY !== "visible")) {
144
+ const box = element.getBoundingClientRect()
145
+ bounds = intersection(bounds, {
146
+ left: style.overflowX === "visible" ? bounds.left : box.left,
147
+ right: style.overflowX === "visible" ? bounds.right : box.right,
148
+ top: style.overflowY === "visible" ? bounds.top : box.top,
149
+ bottom: style.overflowY === "visible" ? bounds.bottom : box.bottom,
150
+ })
151
+ }
152
+ clips.set(element, bounds)
153
+ return bounds
154
+ }
155
+ function textIn(node, bounds, start, end) {
156
+ range.setStart(node, start); range.setEnd(node, end)
157
+ const boxes = [...range.getClientRects()].filter(box => size(box) > 0)
158
+ if (!boxes.some(box => intersection(bounds, box))) return ""
159
+ if (end - start <= 1 || boxes.every(box => contains(bounds, box))) return node.data.slice(start, end)
160
+ const middle = Math.floor((start + end) / 2)
161
+ return textIn(node, bounds, start, middle) + textIn(node, bounds, middle, end)
162
+ }
163
+ let quote = ""
164
+ const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT)
165
+ for (let node; (node = walker.nextNode());) {
166
+ const element = node.nodeType === Node.TEXT_NODE ? node.parentElement : node
167
+ if (omitted(element)) continue
168
+ const bounds = clip(element.parentElement)
169
+ if (!bounds) continue
170
+ if (node === element) {
171
+ const box = element.getBoundingClientRect()
172
+ const overlap = intersection(bounds, box)
173
+ if (overlap) candidates.push({ element, score: size(overlap) / (size(region) + size(box) - size(overlap)) })
174
+ } else if (quote.length < 4000 && node.data.trim()) {
175
+ const clipped = clip(element)
176
+ if (!clipped) continue
177
+ const text = textIn(node, clipped, 0, node.length).replace(/\s+/g, " ").trim()
178
+ if (text) quote = `${quote}${quote ? " " : ""}${text}`.slice(0, 4000)
179
+ }
180
+ }
181
+ const selectors = []
182
+ for (const { element } of candidates.sort((a, b) => b.score - a.score)) {
183
+ try {
184
+ const hint = selector(element)
185
+ if (hint.length <= 1000) selectors.push(hint)
186
+ } catch { /* A selector is evidence, not the area anchor. */ }
187
+ if (selectors.length === 5) break
188
+ }
189
+ return { type: "area", rect, viewport, quote, selectors }
190
+ }
126
191
  function frame() {
127
192
  const selectors = []
128
193
  for (let current = window; current !== current.top; current = current.parent) {
@@ -131,5 +196,5 @@
131
196
  }
132
197
  return selectors.length ? { selectors, url: location.href } : null
133
198
  }
134
- globalThis.AnnotateInspector = { capture, text: elementText, frame }
199
+ globalThis.AnnotateInspector = { capture, captureArea, text: elementText, frame }
135
200
  })();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "OpenCode Annotate",
4
- "version": "0.17.0",
4
+ "version": "0.18.0",
5
5
  "description": "Annotate HTML-based page feedback, private drafts, and paired OpenCode delivery.",
6
6
  "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp7TG2yzekNKpQvHBtj4jqkOxtoeDIBhNIjPi37Os/ksuhzPp1pHnrJPV4WV2ToatUaD5x5/SpLP8qZKLBD+wuraEE/TeclEZ8HvEs1yhlnx/S7piTG/s0eV5umuTEx2w66Hi0w3dhTC7ZZfJXCLyqs1feBtWzQx6ClgaHNYly4iJ03pV7RfguqpIaG9LV8Oa8ELA+7Ubr0BAujXrSlvqLF5oAKGoXXcpvTL5rgMRIH4Q/85tnvrk0pRVg+1z9IGNzSfjN82iveC/JAriyWABp8YuswtvKfI2Wb+KspaisBh39Y3BRqlyo8I2Cr+01uE6G5pWiJIWMLhe0glrMr5I2wIDAQAB",
7
7
  "permissions": ["activeTab", "scripting", "storage", "sidePanel", "nativeMessaging", "clipboardWrite"],
package/browser/panel.css CHANGED
@@ -37,9 +37,9 @@ textarea { caret-color: var(--accent); }
37
37
  #page-url { min-width: 0; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
38
38
  main { min-height: 0; min-width: 0; overflow: auto; padding: 14px 16px 20px; scrollbar-width: thin; scrollbar-color: var(--input) transparent; scroll-padding: 16px; }
39
39
  .picker-row { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }
40
- #pick { flex: none; }
40
+ #pick, #area { flex: none; }
41
41
  #pick-hint { font-size: 13px; color: var(--muted); }
42
- #pick[aria-pressed="true"] { width: 100%; background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
42
+ .picker-row button[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
43
43
  .composer { margin-top: 18px; padding-bottom: 18px; border-bottom: 1px solid var(--line); }
44
44
  .section-heading { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 10px; }
45
45
  .section-heading h2 { font-size: 14px; font-weight: 650; }
@@ -27,7 +27,7 @@
27
27
  </section>
28
28
  <div id="update-notice" class="update-notice" role="status" hidden><strong>Annotate was updated</strong><p>Reload once to finish. Notes and drafts are kept; reopen the panel with the icon or Alt+Shift+A afterwards.</p><button id="reload-extension" class="primary">Reload Annotate</button></div>
29
29
  <p id="page-error" class="error" role="alert" hidden></p>
30
- <div class="picker-row"><button id="pick" aria-pressed="false"><svg class="icon" aria-hidden="true"><use href="#icon-pick"/></svg><span id="pick-label">Pick element</span></button><span id="pick-hint">or select text</span></div>
30
+ <div class="picker-row"><button id="pick" aria-pressed="false"><svg class="icon" aria-hidden="true"><use href="#icon-pick"/></svg><span id="pick-label">Pick element</span></button><button id="area" aria-pressed="false">Select area</button><span id="pick-hint">or select text</span></div>
31
31
  <section id="composer" class="composer" aria-label="Current annotation" hidden>
32
32
  <div class="section-heading"><h2 id="composer-title">New note</h2><span id="draft-state" aria-live="polite"></span></div>
33
33
  <blockquote class="selected-quote"><svg class="icon" aria-hidden="true"><use href="#icon-pick"/></svg><p id="quote"></p></blockquote>
package/browser/panel.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { PROTOCOL, markdown, validateReview } from "./protocol.mjs"
1
+ import { PROTOCOL, areaLabel, markdown, validateReview } from "./protocol.mjs"
2
2
  import { panelPolling, panelWindowID } from "./env.mjs"
3
3
 
4
4
  const $ = id => document.getElementById(id)
@@ -13,6 +13,7 @@ let state, model, destination, available, targets = [], workspaces = [], disconn
13
13
  let deliverySupported = true
14
14
  let refreshID = 0, connectionRevision = 0, connectionRefresh, connectionRefreshRevision, connectionTimer, scheduledRefresh
15
15
  let pendingAction, pendingFocus, undoRecord, clearBatchID, selectedNoteID, noteRenderKey, notice, outdated = false
16
+ let areaViewKey
16
17
  let sessionSort = localStorage.getItem("sessionSort") || "updated", showAllSessions = false
17
18
 
18
19
  function icon(name) {
@@ -74,7 +75,47 @@ function dirty(m = model) {
74
75
  anchorIdentity(value.anchor) !== anchorIdentity(value.editing.anchor) : !!value.comment.trim()
75
76
  }
76
77
  const validDraft = () => !!model?.value?.comment.trim() && dirty()
77
- const anchorIdentity = anchor => anchor ? JSON.stringify([anchor.frame, anchor.type, anchor.selector, anchor.quote, anchor.prefix, anchor.suffix]) : ""
78
+ const anchorIdentity = anchor => anchor ? JSON.stringify([anchor.frame, anchor.type, anchor.type === "area" ? anchor.rect : anchor.selector, anchor.quote, anchor.prefix, anchor.suffix]) : ""
79
+ const targetLabel = anchor => anchor.type === "area" ? `${areaLabel(anchor)}${anchor.quote ? `: ${anchor.quote}` : ""}` : anchor.quote
80
+ function areaDraft() {
81
+ const value = model?.value
82
+ if (value?.anchor.type !== "area" || value.editing) return null
83
+ const captureID = value.captures?.[state.tabID] || Object.values(value.captures || {})[0]
84
+ return captureID ? { id: `draft:${captureID}`, anchor: value.anchor } : null
85
+ }
86
+ function syncAreaView() {
87
+ if (!state || outdated) return
88
+ const focus = state.notes.some(note => note.id === selectedNoteID && note.page.url === state.page.url && note.anchor.type === "area") ? selectedNoteID : null
89
+ const view = { tabID: state.tabID, url: state.page.url, focus, draft: areaDraft(), eventID: state.areaEvent?.token }
90
+ const key = JSON.stringify(view)
91
+ if (key === areaViewKey) return
92
+ // Leave a tab's last marker view intact when its panel switches away.
93
+ areaViewKey = key
94
+ call({ action: "area-view", ...view }).catch(error => {
95
+ if (areaViewKey === key) areaViewKey = null
96
+ if (error.code !== "outdated" && state?.tabID === view.tabID) status(error.message, "error")
97
+ })
98
+ }
99
+ function applyAreaEvent(event) {
100
+ if (!event || model.areaEvent === event.token) return
101
+ model.areaEvent = event.token
102
+ if (event.draft) {
103
+ if (areaDraft()?.id !== event.id) return
104
+ selectedNoteID = null
105
+ if (event.anchor && anchorIdentity(model.value.anchor) !== anchorIdentity(event.anchor)) {
106
+ model.value.anchor = event.anchor
107
+ persistDraft(model).catch(() => {})
108
+ }
109
+ } else {
110
+ const note = state.notes.find(note => note.id === event.id)
111
+ if (!note) return
112
+ selectedNoteID = note.id
113
+ if (model.value?.editing?.id === note.id && event.revision === note.revision && model.value.editing.revision + 1 === note.revision) {
114
+ model.value.anchor = note.anchor; model.value.editing = clone(note)
115
+ persistDraft(model).catch(() => {})
116
+ }
117
+ }
118
+ }
78
119
  function pendingCount() {
79
120
  const pending = state?.notes.filter(note => note.sentRevision !== note.revision) || []
80
121
  return pending.length + (validDraft() && !pending.some(note => note.id === model.value.editing?.id) ? 1 : 0)
@@ -86,7 +127,7 @@ function controls() {
86
127
  for (const button of $("kind").querySelectorAll("button")) button.disabled = lock
87
128
  $("save").disabled = lock || !state || !validDraft() || !!model?.conflict
88
129
  $("save-switch").disabled = lock || !validDraft() || !!model?.conflict
89
- $("pick").disabled = !state || lock
130
+ $("pick").disabled = $("area").disabled = !state || lock
90
131
  $("cancel").disabled = lock
91
132
  for (const id of ["discard-switch", "keep-editing", "retry-draft", "reload-draft", "keep-draft", "copy-draft", "undo", "restore-round", "change-target"]) $(id).disabled = lock
92
133
  for (const row of $("targets").querySelectorAll(".session-row")) row.disabled = lock || !targets.some(target => target.id === row.dataset.targetId)
@@ -99,7 +140,7 @@ function controls() {
99
140
  $("disconnect").hidden = !available
100
141
  $("disconnect").disabled = lock || !available
101
142
  $("copy").disabled = $("export").disabled = !state?.notes.length
102
- for (const button of $("notes").querySelectorAll("button")) button.disabled = lock
143
+ for (const button of $("notes").querySelectorAll("button")) button.disabled = lock || !state
103
144
  for (const id of ["clear", "confirm-clear", "cancel-clear"]) $(id).disabled = lock || !state?.notes.length
104
145
  for (const id of busy) if ($(id)) $(id).disabled = true
105
146
  if (outdated) for (const button of document.querySelectorAll("button:not(#reload-extension)")) button.disabled = true
@@ -229,7 +270,7 @@ function renderComposer() {
229
270
  renderEmpty()
230
271
  if (!value) return
231
272
  $("composer-title").textContent = value.editing ? "Edit note" : "New note"
232
- $("quote").textContent = value.anchor.quote
273
+ $("quote").textContent = targetLabel(value.anchor)
233
274
  if ($("comment").value !== value.comment) $("comment").value = value.comment
234
275
  for (const button of $("kind").querySelectorAll("button")) {
235
276
  const selected = button.dataset.kind === value.kind
@@ -264,8 +305,12 @@ function renderNotes() {
264
305
  $("notes-section").hidden = !notes.length
265
306
  const pageCount = new Set(notes.map(note => note.page.url)).size
266
307
  $("count").textContent = `${plural(notes.length)} in this round${pageCount > 1 ? ` · ${pageCount} pages` : ""}`
267
- const key = JSON.stringify([notes, state?.page.url, state?.anchorStates, selectedNoteID])
268
- if (key === noteRenderKey) return
308
+ const key = JSON.stringify([notes, state?.page.url, state?.anchorStates])
309
+ if (key === noteRenderKey) {
310
+ for (const item of $("notes").querySelectorAll("[data-note-id]")) item.classList.toggle("is-current", item.dataset.noteId === selectedNoteID)
311
+ return
312
+ }
313
+ const focused = document.activeElement?.classList.contains("note-target") ? document.activeElement.closest("[data-note-id]").dataset.noteId : null
269
314
  noteRenderKey = key; $("notes").replaceChildren()
270
315
  let pageURL
271
316
  for (const [index, note] of notes.entries()) {
@@ -285,10 +330,15 @@ function renderNotes() {
285
330
  item.className = `note${selectedNoteID === note.id ? " is-current" : ""}`; item.dataset.noteId = note.id
286
331
  number.className = "note-number"; number.setAttribute("aria-label", `Note ${index + 1}`)
287
332
  target.className = "note-target"; target.setAttribute("aria-label", `Show note ${index + 1} on page`)
288
- target.append(make("span", note.anchor.quote.slice(0, 200)), icon("reveal"))
333
+ target.append(make("span", targetLabel(note.anchor).slice(0, 200)), icon("reveal"))
334
+ target.onfocus = () => {
335
+ if (note.anchor.type === "area" && note.page.url === state.page.url && selectedNoteID !== note.id) {
336
+ selectedNoteID = note.id; renderNotes(); syncAreaView()
337
+ }
338
+ }
289
339
  target.onclick = () => run("reveal", async () => {
290
340
  await call({ action: "reveal", url: state.page.url, noteID: note.id }); selectedNoteID = note.id
291
- await refresh(); status("Element highlighted on the page"); renderNotes()
341
+ await refresh(); status(`${note.anchor.type === "area" ? "Area" : "Element"} highlighted on the page`); renderNotes()
292
342
  $("notes").querySelector(`[data-note-id="${CSS.escape(note.id)}"] .note-target`)?.focus({ preventScroll: true })
293
343
  })
294
344
  const comment = make("p", note.comment); comment.className = "note-comment"
@@ -305,7 +355,9 @@ function renderNotes() {
305
355
  bottom.append(meta, edit, remove); content.append(bottom); item.append(number, content); $("notes").append(item)
306
356
  }
307
357
  $("preview").textContent = notes.length ? markdown(review()) : "Add a note to preview the feedback."
308
- call({ action: "markers" }).catch(() => {})
358
+ if (focused && (focused === selectedNoteID || notes.find(note => note.id === focused)?.anchor.type !== "area")) {
359
+ $("notes").querySelector(`[data-note-id="${CSS.escape(focused)}"] .note-target`)?.focus({ preventScroll: true })
360
+ }
309
361
  }
310
362
  // Send always means session delivery; Copy instead is a separate, stable action.
311
363
  function renderDelivery() {
@@ -356,6 +408,7 @@ function renderDelivery() {
356
408
  }
357
409
  function render() {
358
410
  renderComposer(); renderNotes()
411
+ syncAreaView()
359
412
  $("undo-notice").hidden = !undoRecord
360
413
  $("undo-text").textContent = undoRecord ? `${plural(undoRecord.notes.length)} removed.` : ""
361
414
  controls()
@@ -367,7 +420,9 @@ async function refresh() {
367
420
  const next = await call({ action: "current" })
368
421
  if (request !== refreshID) return
369
422
  if (next.protocol !== PROTOCOL) { markOutdated(); return }
370
- if (state?.page.url !== next.page.url) { pendingAction = null; selectedNoteID = null; pendingFocus = null; if (notice?.page) notice = null }
423
+ if (state?.tabID !== next.tabID || state?.page.url !== next.page.url) {
424
+ pendingAction = null; selectedNoteID = null; pendingFocus = null; if (notice?.page) notice = null
425
+ }
371
426
  state = next; model = modelFor(next)
372
427
  $("page-title").textContent = next.page.title; $("page-title").title = next.page.title
373
428
  const url = new URL(next.page.url)
@@ -375,17 +430,21 @@ async function refresh() {
375
430
  $("page-url").title = next.page.url
376
431
  const pageError = next.detached || next.error
377
432
  $("page-error").hidden = !pageError; $("page-error").textContent = pageError || ""
378
- $("pick-label").textContent = next.picking ? "Cancel pick (Esc)" : "Pick element"
379
- $("pick").setAttribute("aria-pressed", String(!!next.picking)); $("pick-hint").hidden = !!next.picking
433
+ $("pick-label").textContent = next.mode === "element" ? "Cancel pick (Esc)" : "Pick element"
434
+ $("pick").setAttribute("aria-pressed", String(next.mode === "element"))
435
+ $("area").setAttribute("aria-pressed", String(next.mode === "area"))
436
+ $("pick-hint").hidden = next.mode === "element"
437
+ $("pick-hint").textContent = next.mode === "area" ? "Drag on page · Esc to cancel" : "or select text"
380
438
  if (next.captureID && next.captureID !== model.captureID) {
381
439
  model.captureID = next.captureID
382
- if (next.anchor && next.draft.consumedCaptures?.[next.tabID] !== next.captureID) {
440
+ if (next.anchor && next.draft.consumedCaptures?.[next.tabID] !== next.captureID && model.value?.captures?.[next.tabID] !== next.captureID) {
383
441
  notice = null
384
442
  if (anchorIdentity(next.anchor) !== anchorIdentity(model.value?.anchor)) await requestAction({ type: "select", anchor: next.anchor,
385
443
  capture: { id: next.captureID, tabID: next.tabID } })
386
444
  else model.value.captures = { ...model.value.captures, [next.tabID]: next.captureID }
387
445
  } else if (next.error) status(next.error, "error")
388
446
  }
447
+ applyAreaEvent(next.areaEvent)
389
448
  render()
390
449
  } catch (error) {
391
450
  if (request !== refreshID || error.code === "outdated") return
@@ -497,6 +556,11 @@ $("comment").addEventListener("input", () => {
497
556
  model.value.comment = $("comment").value; notice = null
498
557
  persistDraft(model).catch(() => {}); controls()
499
558
  })
559
+ $("comment").addEventListener("focus", () => {
560
+ if (!model?.value || model.value.anchor.type !== "area") return
561
+ selectedNoteID = model.value.editing?.id || null
562
+ renderNotes(); syncAreaView()
563
+ })
500
564
  $("comment").addEventListener("keydown", event => {
501
565
  if (event.key === "Enter" && (event.metaKey || event.ctrlKey) && !$("save").disabled) { event.preventDefault(); $("save").click() }
502
566
  })
@@ -508,7 +572,9 @@ for (const button of $("kind").querySelectorAll("button")) {
508
572
  })
509
573
  }
510
574
  $("save-shortcut").textContent = navigator.platform.includes("Mac") ? "⌘↵" : "Ctrl↵"
511
- task("pick", async () => { notice = null; await call({ action: "pick" }); await refresh() })
575
+ for (const [button, mode] of [["pick", "element"], ["area", "area"]]) {
576
+ task(button, async () => { notice = null; await call({ action: "pick", mode: state.mode === mode ? null : mode }); await refresh() })
577
+ }
512
578
  task("save", async () => { await saveCurrent(); focusWhenReady("#pick") })
513
579
  task("cancel", async () => { await discardDraft(); focusWhenReady("#pick") })
514
580
  task("save-switch", async () => { const action = pendingAction; await saveCurrent(); await performAction(action) })
@@ -671,7 +737,7 @@ document.addEventListener("click", event => {
671
737
  })
672
738
  document.addEventListener("keydown", event => {
673
739
  if (event.key !== "Escape") return
674
- if (state?.picking) $("pick").click()
740
+ if (state?.mode) $(state.mode === "area" ? "area" : "pick").click()
675
741
  pendingAction = null; $("utilities").hidden = true; $("more").setAttribute("aria-expanded", "false"); showSessionOptions(false); renderComposer()
676
742
  })
677
743
  chrome.storage.onChanged.addListener((changes, area) => {
@@ -1,7 +1,22 @@
1
1
  export const MAX_BYTES = 512 * 1024
2
2
  export const HOST = "fun.mjshao.annotate"
3
3
  // Bump when panel ↔ worker actions change. Chrome can keep an older worker running beside a newer panel.
4
- export const PROTOCOL = 8
4
+ export const PROTOCOL = 10
5
+ const finiteFields = (value, keys) => value && keys.every(key => Number.isFinite(value[key]))
6
+ export function validateAnchor(anchor) {
7
+ if (typeof anchor?.quote !== "string" || anchor.quote.length > 4000 ||
8
+ !["text", "element", "area"].includes(anchor.type) ||
9
+ (anchor.type !== "area" && typeof anchor.selector !== "string")) throw new Error("Invalid annotation anchor")
10
+ for (const key of ["prefix", "suffix", "styles", "accessibility", "element", "fullPath", "frame"]) {
11
+ if (anchor[key] !== undefined && typeof anchor[key] !== "string") throw new Error("Invalid anchor field")
12
+ }
13
+ if (anchor.type === "area" && (
14
+ !finiteFields(anchor.rect, ["x", "y", "width", "height"]) || anchor.rect.width <= 0 || anchor.rect.height <= 0 ||
15
+ !finiteFields(anchor.viewport, ["width", "height", "scrollX", "scrollY"]) || anchor.viewport.width <= 0 || anchor.viewport.height <= 0 ||
16
+ !Array.isArray(anchor.selectors) || anchor.selectors.length > 5 ||
17
+ Array.from(anchor.selectors).some(value => typeof value !== "string" || !value.trim() || value.length > 1000)
18
+ )) throw new Error("Invalid area anchor")
19
+ }
5
20
  export function safeUrl(input) {
6
21
  const url = new URL(input)
7
22
  if (!["http:", "https:", "file:"].includes(url.protocol)) throw new Error("Unsupported page URL")
@@ -20,12 +35,8 @@ export function validateReview(review) {
20
35
  if (!note || typeof note.page?.title !== "string" || pageTitle(note.page.title) !== note.page.title ||
21
36
  typeof note.page?.url !== "string" || safeUrl(note.page.url) !== note.page.url ||
22
37
  typeof note.id !== "string" || ids.has(note.id) || !Number.isSafeInteger(note.revision) || note.revision < 1 ||
23
- !["comment", "ask"].includes(note.kind) || typeof note.comment !== "string" || !note.comment.trim() || note.comment.length > 8000 ||
24
- typeof note.anchor?.quote !== "string" || note.anchor.quote.length > 4000 || typeof note.anchor.selector !== "string" ||
25
- !["text", "element"].includes(note.anchor.type)) throw new Error("Invalid annotation")
26
- for (const key of ["prefix", "suffix", "styles", "accessibility", "element", "fullPath", "frame"]) {
27
- if (note.anchor[key] !== undefined && typeof note.anchor[key] !== "string") throw new Error("Invalid anchor field")
28
- }
38
+ !["comment", "ask"].includes(note.kind) || typeof note.comment !== "string" || !note.comment.trim() || note.comment.length > 8000) throw new Error("Invalid annotation")
39
+ validateAnchor(note.anchor)
29
40
  if (typeof note.createdAt !== "string" || Number.isNaN(Date.parse(note.createdAt))) throw new Error("Invalid annotation timestamp")
30
41
  ids.add(note.id)
31
42
  }
@@ -41,6 +52,9 @@ export function orderedNotes(notes) {
41
52
  }
42
53
  return [...groups.values()].flat()
43
54
  }
55
+ export function areaLabel({ rect: { x, y, width, height } }) {
56
+ return `Area (${x},${y} ${width}×${height})`
57
+ }
44
58
  export function markdown(review) {
45
59
  validateReview(review)
46
60
  const lines = ["# Web annotations", "",
@@ -52,7 +66,12 @@ export function markdown(review) {
52
66
  lines.push(`## ${note.page.title}`, `URL: ${pageURL}`, "")
53
67
  }
54
68
  const a = note.anchor
55
- lines.push(`### Annotation ${index + 1} (${note.kind})`, `Captured: ${note.createdAt}`, `Selector hint: ${a.selector}`, `Element: ${a.element || a.type}`, "", "Page evidence:")
69
+ lines.push(`### Annotation ${index + 1} (${note.kind})`, `Captured: ${note.createdAt}`)
70
+ if (a.type === "area") {
71
+ lines.push(`${areaLabel(a)} on ${note.page.title}`)
72
+ if (a.selectors.length) lines.push("Selector hints:", ...a.selectors.map(selector => `- ${selector}`))
73
+ } else lines.push(`Selector hint: ${a.selector}`, `Element: ${a.element || a.type}`)
74
+ lines.push("", "Page evidence:")
56
75
  lines.push(...`${a.prefix || ""}【${a.quote}】${a.suffix || ""}`.split("\n").map(line => `> ${line}`))
57
76
  if (a.fullPath) lines.push(`DOM path: ${a.fullPath}`)
58
77
  if (a.frame) lines.push(`Frame: ${a.frame}`)
@@ -1,4 +1,4 @@
1
- import { HOST, PROTOCOL, orderedNotes, pageTitle, safeUrl, validateReview } from "./protocol.mjs"
1
+ import { HOST, PROTOCOL, orderedNotes, pageTitle, safeUrl, validateAnchor, validateReview } from "./protocol.mjs"
2
2
  import { openPanel, reconnectHint, resolveTargetTab, sameExtensionURL, sessionDelivery } from "./env.mjs"
3
3
 
4
4
  const DELIVERY = sessionDelivery()
@@ -23,10 +23,10 @@ async function inject(tabId) {
23
23
  } })
24
24
  return frames.filter(item => item.result).map(item => ({ frameId: item.frameId, frame: frameLocator(item.result.frame) }))
25
25
  }
26
- async function pickFrames(tabId, picking, frames = undefined) {
26
+ async function pickFrames(tabId, mode, frames = undefined) {
27
27
  frames ??= await inject(tabId)
28
- await Promise.all(frames.map(({ frameId }) => chrome.tabs.sendMessage(tabId, { action: "pick", picking }, { frameId })))
29
- return { picking }
28
+ await Promise.all(frames.map(({ frameId }) => chrome.tabs.sendMessage(tabId, { action: "pick", mode }, { frameId })))
29
+ return { mode }
30
30
  }
31
31
  async function anchorMessage(tabId, message, frames = undefined) {
32
32
  frames ??= await inject(tabId)
@@ -49,15 +49,32 @@ async function waitLoaded(tabID) {
49
49
  })
50
50
  }
51
51
  const delivered = note => !note.deleted && note.sentRevision === note.revision
52
- async function updateMarkers(notes) {
52
+ const pendingNotes = storage => orderedNotes(Object.entries(storage).filter(([key, note]) =>
53
+ key.startsWith("note:") && !note.deleted && !delivered(note)).map(([, note]) => note))
54
+ async function paintMarkers(tabID, frames, notes, page, view) {
55
+ await Promise.all(frames.map(({ frameId, frame }) => chrome.tabs.sendMessage(tabID, {
56
+ action: "markers",
57
+ notes: notes.map(note => note.page.url === page.url && note.anchor.frame === frame
58
+ ? { id: note.id, revision: note.revision, anchor: note.anchor } : { anchor: null }),
59
+ draft: view?.draft && view.draft.anchor.frame === frame ? view.draft : undefined,
60
+ focus: view?.focus,
61
+ }, { frameId })))
62
+ }
63
+ async function syncMarkers(tabID, frames = undefined) {
64
+ frames ??= await inject(tabID)
65
+ const keys = [`tab:${tabID}`, `area:${tabID}`]
66
+ const [session, storage] = await Promise.all([readSession(keys), chrome.storage.local.get(null)])
67
+ const page = session[keys[0]]?.page, view = session[keys[1]]
68
+ if (page) await paintMarkers(tabID, frames, pendingNotes(storage), page, view?.url === page.url ? view : null)
69
+ }
70
+ async function readSession(keys) {
71
+ return Object.assign({}, ...await Promise.all(keys.map(key => chrome.storage.session.get(key))))
72
+ }
73
+ async function updateMarkers() {
53
74
  const session = await chrome.storage.session.get(null)
54
75
  await Promise.all((await chrome.tabs.query({})).map(async tab => {
55
- const page = session[`tab:${tab.id}`]?.page
56
- if (!page) return
57
- try {
58
- const frames = await inject(tab.id)
59
- await Promise.all(frames.map(({ frameId, frame }) => chrome.tabs.sendMessage(tab.id, { action: "markers", notes: notes.map(note => ({ anchor: note.page.url === page.url && note.anchor.frame === frame ? note.anchor : null })) }, { frameId })))
60
- } catch { /* Closed or navigated tabs are refreshed when reopened. */ }
76
+ if (!session[`tab:${tab.id}`]?.page) return
77
+ try { await syncMarkers(tab.id) } catch { /* Closed or navigated tabs are refreshed when reopened. */ }
61
78
  }))
62
79
  }
63
80
  async function closeRound(annotations, details) {
@@ -76,6 +93,7 @@ async function closeRound(annotations, details) {
76
93
  }
77
94
  const expired = [...rounds.values()].sort((a, b) => b.at.localeCompare(a.at)).slice(KEPT_ROUNDS).flatMap(round => round.keys)
78
95
  if (expired.length) await chrome.storage.local.remove(expired)
96
+ await updateMarkers()
79
97
  return Object.keys(updates).length
80
98
  }
81
99
  function lastRound(entries) {
@@ -94,13 +112,14 @@ chrome.action.onClicked.addListener(tab => {
94
112
  })
95
113
  async function current(message) {
96
114
  const tab = await resolveTargetTab(message)
97
- const state = (await chrome.storage.session.get(`tab:${tab.id}`))[`tab:${tab.id}`]
115
+ const keys = [`tab:${tab.id}`, `area:${tab.id}`], session = await readSession(keys)
116
+ const state = session[keys[0]], view = session[keys[1]]
98
117
  if (!state?.page) throw new Error(state?.error || "Click the extension icon on this page to grant access")
99
118
  const hash = await pageKey(state.page.url)
100
119
  const storage = await chrome.storage.local.get(null)
101
120
  const entries = Object.entries(storage).filter(([key]) => key.startsWith("note:")).map(([, value]) => value)
102
121
  // Delivered notes leave the working list; the latest rounds stay restorable.
103
- const notes = orderedNotes(entries.filter(note => !note.deleted && !delivered(note)))
122
+ const notes = pendingNotes(storage)
104
123
  const draft = storage[`draft:${hash}`] || { revision: 0, value: null }
105
124
  const outbox = storage.outbox
106
125
  const localNotes = notes.filter(note => note.page.url === state.page.url)
@@ -109,7 +128,8 @@ async function current(message) {
109
128
  const anchors = localNotes.map(note => note.anchor).concat(draft.value ? [draft.value.anchor] : [])
110
129
  const frames = await inject(tab.id)
111
130
  const latest = (await chrome.storage.session.get(`tab:${tab.id}`))[`tab:${tab.id}`]
112
- await pickFrames(tab.id, !!latest?.picking, frames)
131
+ await pickFrames(tab.id, latest?.mode ?? null, frames)
132
+ await syncMarkers(tab.id, frames)
113
133
  const states = await Promise.all(anchors.map(async anchor => {
114
134
  const result = await anchorMessage(tab.id, { action: "locate", anchor, anchors: [anchor] }, frames)
115
135
  return result.states?.[0] || "missing frame"
@@ -118,7 +138,8 @@ async function current(message) {
118
138
  anchorStates = notes.map(note => note.page.url === state.page.url ? states[index++] : "elsewhere")
119
139
  if (draft.value) draftAnchorState = states[localNotes.length]
120
140
  } catch (error) { if (error.message === RECONNECT) detached = RECONNECT /* otherwise visibly unavailable while navigating */ }
121
- return { protocol: PROTOCOL, tabID: tab.id, ...state, notes, anchorStates, hash, draft, draftAnchorState, detached, lastRound: lastRound(entries),
141
+ return { protocol: PROTOCOL, tabID: tab.id, ...state, areaEvent: view?.url === state.page.url ? view.event : undefined,
142
+ notes, anchorStates, hash, draft, draftAnchorState, detached, lastRound: lastRound(entries),
122
143
  outbox: outbox ? { batchID: outbox.batchID, targetID: outbox.targetID, count: outbox.review.annotations.length } : null }
123
144
  }
124
145
  function draftConflict(draft) {
@@ -142,6 +163,51 @@ function consumedCaptures(previous, captures) {
142
163
  }
143
164
  return result
144
165
  }
166
+ async function pageSource(message, sender) {
167
+ if (!sender.tab || !sender.url || new URL(message.page.url).origin !== new URL(sender.url).origin) throw new Error("Invalid page source")
168
+ const tab = await chrome.tabs.get(sender.tab.id)
169
+ if ((sender.origin || new URL(sender.url).origin) !== new URL(tab.url).origin) throw new Error("Invalid frame source")
170
+ const frame = sender.frameId ? frameLocator(message.frame) : undefined
171
+ if (sender.frameId && !frame) throw new Error("Missing frame locator")
172
+ return { tab, frame, page: { url: safeUrl(tab.url), title: pageTitle(tab.title || "") } }
173
+ }
174
+ async function areaGesture(message, sender) {
175
+ const { tab, frame, page } = await pageSource(message, sender)
176
+ const key = `area:${tab.id}`, tabKey = `tab:${tab.id}`
177
+ const session = await readSession([key, tabKey])
178
+ if (session[tabKey]?.page.url !== page.url || (!frame && safeUrl(message.page.url) !== page.url)) throw new Error("The page changed")
179
+ const view = session[key]?.url === page.url ? session[key] : { url: page.url }
180
+ const { id } = message
181
+ if (typeof id !== "string" || !id) throw new Error("Invalid area marker")
182
+ const event = { token: crypto.randomUUID(), id, draft: id === view.draft?.id }
183
+ const adjust = message.action === "area-adjust"
184
+ if (adjust) {
185
+ validateAnchor(message.anchor)
186
+ if (message.anchor.type !== "area") throw new Error("Invalid area marker")
187
+ event.anchor = { ...message.anchor, frame }
188
+ }
189
+ if (event.draft) {
190
+ if (view.draft.anchor.frame !== frame) throw new Error("The area draft changed")
191
+ if (adjust) {
192
+ if (JSON.stringify(view.draft.anchor.rect) !== JSON.stringify(message.baseRect)) throw new Error("The area draft changed")
193
+ view.draft = { ...view.draft, anchor: event.anchor }
194
+ }
195
+ } else {
196
+ const storage = await chrome.storage.local.get(null)
197
+ const noteKey = `note:${await pageKey(page.url)}:${id}`, old = storage[noteKey]
198
+ if (!old || old.deleted || delivered(old) || old.anchor.type !== "area" || old.anchor.frame !== frame) throw new Error("This area note is no longer adjustable")
199
+ if (adjust) {
200
+ if (old.revision !== message.revision) throw new Error("The area note changed; try again")
201
+ const note = { ...old, anchor: event.anchor, revision: old.revision + 1, updatedAt: new Date().toISOString() }
202
+ validateReview({ version: 2, annotations: pendingNotes({ ...storage, [noteKey]: note }) })
203
+ await chrome.storage.local.set({ [noteKey]: note })
204
+ event.revision = note.revision
205
+ }
206
+ }
207
+ await chrome.storage.session.set({ [key]: { ...view, focus: event.draft ? null : id, event } })
208
+ await syncMarkers(tab.id)
209
+ return {}
210
+ }
145
211
  const sameSession = (a, b) => a?.sessionID && b?.sessionID && a.sessionID === b.sessionID && (a.provider || "opencode") === (b.provider || "opencode")
146
212
  // Called within serial(): receiver IDs may change, but retries belong to a session.
147
213
  async function rememberTarget(target, storage = undefined) {
@@ -184,28 +250,47 @@ async function handle(message, sender) {
184
250
  if (message.action === "frames-changed") {
185
251
  if (!sender.tab) throw new Error("Invalid page source")
186
252
  const state = (await chrome.storage.session.get(`tab:${sender.tab.id}`))[`tab:${sender.tab.id}`]
187
- if (state?.page) await pickFrames(sender.tab.id, !!state.picking)
253
+ if (state?.page) {
254
+ const frames = await inject(sender.tab.id)
255
+ await pickFrames(sender.tab.id, state.mode ?? null, frames)
256
+ await syncMarkers(sender.tab.id, frames)
257
+ }
188
258
  return {}
189
259
  }
260
+ if (["area-focus", "area-adjust"].includes(message.action)) return serial(() => areaGesture(message, sender))
190
261
  if (message.action === "capture") {
191
- if (!sender.tab || !sender.url || new URL(message.page.url).origin !== new URL(sender.url).origin) throw new Error("Invalid page source")
192
- const key = `tab:${sender.tab.id}`
262
+ const { tab, frame, page } = await pageSource(message, sender)
263
+ const key = `tab:${tab.id}`
193
264
  const previous = (await chrome.storage.session.get(key))[key] || {}
194
- const tab = await chrome.tabs.get(sender.tab.id)
195
- if ((sender.origin || new URL(sender.url).origin) !== new URL(tab.url).origin) throw new Error("Invalid frame source")
196
- const frame = sender.frameId ? frameLocator(message.frame) : undefined
197
- if (sender.frameId && !frame) throw new Error("Missing frame locator")
198
265
  const captured = !message.modeOnly
199
- const changedPage = previous.page?.url !== safeUrl(tab.url)
200
- const picking = changedPage || captured ? false : message.ready ? !!previous.picking : !!message.picking
201
- await chrome.storage.session.set({ [key]: { ...previous, page: { url: safeUrl(tab.url), title: pageTitle(tab.title || "") }, picking,
266
+ if (captured && message.anchor) validateAnchor(message.anchor)
267
+ const changedPage = previous.page?.url !== page.url
268
+ const mode = changedPage || captured || !message.ready && !message.error ? null : previous.mode ?? null
269
+ await chrome.storage.session.set({ [key]: { ...previous, page, mode,
202
270
  ...(captured ? { anchor: message.anchor ? { ...message.anchor, ...(frame ? { frame } : {}) } : null, error: message.error, captureID: crypto.randomUUID() } : changedPage ? { anchor: null, error: null } : message.error ? { error: message.error } : {}) } })
203
- if (message.ready) await chrome.tabs.sendMessage(sender.tab.id, { action: "pick", picking }, { frameId: sender.frameId || 0 })
204
- if (!picking && previous.picking) await pickFrames(sender.tab.id, false)
271
+ if (message.ready) await chrome.tabs.sendMessage(sender.tab.id, { action: "pick", mode }, { frameId: sender.frameId || 0 })
272
+ if (!mode && previous.mode) await pickFrames(sender.tab.id, null)
273
+ if (message.ready) await syncMarkers(tab.id, [{ frameId: sender.frameId || 0, frame }])
274
+ else if (changedPage) await syncMarkers(tab.id)
205
275
  return {}
206
276
  }
207
277
  if (sender.url && !sameExtensionURL(sender.url)) throw new Error("Only the extension panel can manage feedback")
208
278
  if (message.action === "current") return current(message)
279
+ if (message.action === "area-view") return serial(async () => {
280
+ const { tabID, url, focus, draft, eventID } = message
281
+ if (!Number.isInteger(tabID) || (focus !== null && typeof focus !== "string")) throw new Error("Invalid marker view")
282
+ if (draft) {
283
+ validateAnchor(draft.anchor)
284
+ if (draft.anchor.type !== "area" || typeof draft.id !== "string" || !draft.id.startsWith("draft:")) throw new Error("Invalid area draft")
285
+ }
286
+ const key = `area:${tabID}`, tabKey = `tab:${tabID}`, session = await readSession([key, tabKey])
287
+ if (session[tabKey]?.page.url !== url) return {}
288
+ const view = session[key]?.url === url ? session[key] : null
289
+ if (view?.event?.token !== eventID) return {}
290
+ await chrome.storage.session.set({ [key]: { url, focus, draft, event: view?.event } })
291
+ await syncMarkers(tabID)
292
+ return {}
293
+ })
209
294
  if (message.action === "draft") return serial(async () => {
210
295
  // A route change must still be able to persist the previous page's draft.
211
296
  if (!message.page || safeUrl(message.page.url) !== message.page.url || typeof message.page.title !== "string" ||
@@ -272,10 +357,10 @@ async function handle(message, sender) {
272
357
  const state = await current(message)
273
358
  if (["save", "pick"].includes(message.action) && message.url && message.url !== state.page.url) throw new Error("The active page changed; retry on the original page")
274
359
  if (message.action === "pick") {
275
- const picking = !state.picking
360
+ if (![null, "element", "area"].includes(message.mode)) throw new Error("Invalid capture mode")
276
361
  const key = `tab:${state.tabID}`, previous = (await chrome.storage.session.get(key))[key]
277
- await chrome.storage.session.set({ [key]: { ...previous, picking } })
278
- return pickFrames(state.tabID, picking)
362
+ await chrome.storage.session.set({ [key]: { ...previous, mode: message.mode } })
363
+ return pickFrames(state.tabID, message.mode)
279
364
  }
280
365
  if (message.action === "reveal") {
281
366
  const note = state.notes.find(note => note.id === message.noteID)
@@ -302,8 +387,8 @@ async function handle(message, sender) {
302
387
  catch { throw new Error(RECONNECT) }
303
388
  }
304
389
  const key = `tab:${tabID}`, previous = (await chrome.storage.session.get(key))[key]
305
- await chrome.storage.session.set({ [key]: { ...previous, picking: false } })
306
- await pickFrames(tabID, false)
390
+ await chrome.storage.session.set({ [key]: { ...previous, mode: null } })
391
+ await pickFrames(tabID, null)
307
392
  const result = await anchorMessage(tabID, { action: "reveal", anchor: note.anchor })
308
393
  if (!result.ok) throw new Error(result.error)
309
394
  return result
@@ -329,7 +414,7 @@ async function handle(message, sender) {
329
414
  updates.outbox = null
330
415
  }
331
416
  await chrome.storage.local.set(updates)
332
- await updateMarkers(orderedNotes(Object.entries({ ...storage, ...updates }).filter(([key, note]) => key.startsWith("note:") && !note.deleted && !delivered(note)).map(([, note]) => note)))
417
+ await updateMarkers()
333
418
  return { notes }
334
419
  })
335
420
  if (["save", "delete", "restore"].includes(message.action)) return serial(async () => {
@@ -359,11 +444,12 @@ async function handle(message, sender) {
359
444
  consumedCaptures: consumedCaptures(previous.consumedCaptures, message.captures), updatedAt: new Date().toISOString() }
360
445
  updates[draftKey] = draft
361
446
  }
362
- await chrome.storage.local.set(updates); return { note, draft }
447
+ await chrome.storage.local.set(updates)
448
+ await updateMarkers()
449
+ return { note, draft }
363
450
  })
364
451
  if (message.action === "markers") {
365
- const frames = await inject(state.tabID)
366
- await Promise.all(frames.map(({ frameId, frame }) => chrome.tabs.sendMessage(state.tabID, { action: "markers", notes: state.notes.map(note => ({ anchor: note.page.url === state.page.url && note.anchor.frame === frame ? note.anchor : null })) }, { frameId })))
452
+ await syncMarkers(state.tabID)
367
453
  return {}
368
454
  }
369
455
  if (message.action === "copied") return serial(async () => {
@@ -385,6 +471,7 @@ async function handle(message, sender) {
385
471
  if (latest.notes.length + Object.keys(updates).length > 200) throw new Error("This round would exceed 200 notes; send or remove some first")
386
472
  validateReview({ version: 2, annotations: [...latest.notes, ...Object.values(updates)] })
387
473
  await chrome.storage.local.set(updates)
474
+ await updateMarkers()
388
475
  return { count: Object.keys(updates).length }
389
476
  })
390
477
  if (message.action === "send") return serial(async () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nxxxsooo/opencode-annotate",
3
- "version": "0.17.0",
3
+ "version": "0.18.0",
4
4
  "description": "Unofficial OpenCode annotation plugin: review AI replies and Markdown with a bundled terminal reviewer; annotate webpages with the browser companion.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/tui/README.md CHANGED
@@ -55,6 +55,38 @@ Standalone annotation data defaults to `~/.local/share/opencode-annotate/tui`
55
55
  (`%LOCALAPPDATA%/opencode-annotate/tui` on Windows). Hosted reviews use their own private
56
56
  snapshot stores. An explicit `PLANNOTATOR_DATA_DIR` can still open a retained older draft.
57
57
 
58
+ ## Herdr
59
+
60
+ The [Herdr commands](../README.md#herdr) use an enabled plugin with ID `annotate`.
61
+ For a local setup on macOS (tested with Herdr 0.9.5), save this as `herdr-plugin.toml`
62
+ and run `herdr plugin link /absolute/path/to/plugin-directory`:
63
+
64
+ ```toml
65
+ id = "annotate"
66
+ name = "Annotate"
67
+ version = "0.1.0"
68
+ min_herdr_version = "0.9.5"
69
+ platforms = ["macos"]
70
+
71
+ [[panes]]
72
+ id = "doc"
73
+ title = "Annotate"
74
+ placement = "overlay"
75
+ command = ["/absolute/path/to/annotate-tui", "herdr", "pane"]
76
+ ```
77
+
78
+ `herdr pane` is the plugin entrypoint: it reads the file, reply or terminal source
79
+ passed by the launcher. Set `--placement overlay|split|tab|zoomed` on `herdr open`,
80
+ `herdr last` or `herdr terminal`; the default is `overlay`. Remove any old
81
+ `popup_width` and `popup_height` settings and replace `placement = "popup"` with
82
+ one of the supported values. Agent delivery uses `herdr agent prompt`; a blocked send
83
+ leaves notes pending for a manual retry and attempts an OSC 52 clipboard copy.
84
+ OpenCode's `/annotate` clears the inherited `HERDR_*` variables before launching
85
+ the reviewer, so it does not use this route.
86
+
87
+ Runtime checks used fixture panes and a local transcript. Real model turns and
88
+ OS clipboard integration were not tested.
89
+
58
90
  ## Local image-toolbar trial
59
91
 
60
92
  The default toolbar remains Unicode. To opt in, add to the TUI config selected by
Binary file
Binary file
Binary file
Binary file
Binary file