@nxxxsooo/opencode-annotate 0.5.0 → 0.7.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/browser/panel.mjs CHANGED
@@ -1,155 +1,515 @@
1
- import { markdown, validateReview } from "./protocol.mjs"
1
+ import { PROTOCOL, markdown, validateReview } from "./protocol.mjs"
2
+
2
3
  const $ = id => document.getElementById(id)
3
- let state, anchor, editing, targets = [], paired, pageURL, capturedIdentity, lastPageError, connectionBusy = false
4
- let refreshID = 0, connectionRevision = 0
5
- const busy = new Set()
6
4
  const make = (tag, text = "") => { const node = document.createElement(tag); node.textContent = text; return node }
7
- function status(text, error = false) { $("status").textContent = text; $("status").classList.toggle("error", error) }
5
+ const clone = value => structuredClone(value)
6
+ const writerID = crypto.randomUUID(), models = new Map(), busy = new Set()
7
+ let state, model, destination, available, targets = [], connectionError = "", connectionLoading = true
8
+ let refreshID = 0, connectionRevision = 0, connectionBusy = false, scheduledRefresh
9
+ let pendingAction, pendingFocus, undoRecord, selectedNoteID, noteRenderKey, connectionOptionsKey, notice, outdated = false
10
+
11
+ function icon(name) {
12
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg")
13
+ svg.setAttribute("class", "icon"); svg.setAttribute("aria-hidden", "true")
14
+ const use = document.createElementNS(svg.namespaceURI, "use"); use.setAttribute("href", `#icon-${name}`)
15
+ svg.append(use); return svg
16
+ }
8
17
  async function call(data) {
9
18
  const result = await chrome.runtime.sendMessage(data)
10
- if (!result?.ok) throw new Error(result?.error || "Extension disconnected; reopen the panel")
19
+ if (result?.error === "Unknown annotation action") throw markOutdated()
20
+ if (!result?.ok) throw Object.assign(new Error(result?.error || "Extension disconnected; reopen the panel"), { code: result?.code, draft: result?.draft, note: result?.note })
11
21
  return result
12
22
  }
13
- function task(id, fn) {
14
- $(id).addEventListener("click", async () => {
15
- busy.add(id); $(id).disabled = true; controls()
16
- try { await fn() } catch (error) { status(error.message, true) } finally { busy.delete(id); $(id).disabled = false; controls() }
17
- })
23
+ function markOutdated() {
24
+ outdated = true; $("update-notice").hidden = false; controls()
25
+ return Object.assign(new Error("Annotate was updated"), { code: "outdated" })
26
+ }
27
+ const plural = count => `${count} note${count === 1 ? "" : "s"}`
28
+ function status(text, tone = "", page = state?.page.url) { notice = text ? { text, tone, page } : null; renderDelivery() }
29
+ function focusWhenReady(selector, scroll = true) {
30
+ pendingFocus = { selector, scroll, page: state?.page.url }
31
+ flushFocus()
32
+ }
33
+ function flushFocus() {
34
+ if (!pendingFocus) return false
35
+ const request = pendingFocus, node = document.querySelector(request.selector)
36
+ if (request.page !== state?.page.url || !node || !node.getClientRects().length) { pendingFocus = null; return false }
37
+ if (node.disabled && busy.size) return false
38
+ pendingFocus = null
39
+ if (node.disabled) return false
40
+ node.focus({ preventScroll: true })
41
+ if (request.scroll) node.scrollIntoView({ block: "nearest" })
42
+ return true
43
+ }
44
+ async function run(id, fn) {
45
+ if (busy.has(id)) return
46
+ const previousFocus = document.activeElement, page = state?.page.url
47
+ busy.add(id); controls()
48
+ try { await fn() }
49
+ catch (error) {
50
+ if (error.code === "outdated") return
51
+ if (model && ["draft-conflict", "note-conflict"].includes(error.code)) {
52
+ model.conflict = error; model.error = error
53
+ renderComposer()
54
+ }
55
+ status(error.message, "error")
56
+ } finally {
57
+ busy.delete(id); if ($(id)) $(id).disabled = false; controls()
58
+ if (!flushFocus() && !pendingFocus && document.activeElement === document.body && page === state?.page.url &&
59
+ previousFocus?.isConnected && !previousFocus.disabled && previousFocus.getClientRects().length) previousFocus.focus({ preventScroll: true })
60
+ }
61
+ }
62
+ const task = (id, fn) => $(id).addEventListener("click", () => run(id, fn))
63
+ function dirty(m = model) {
64
+ const value = m?.value
65
+ if (!value) return false
66
+ return value.editing ? value.comment.trim() !== value.editing.comment || value.kind !== value.editing.kind ||
67
+ anchorIdentity(value.anchor) !== anchorIdentity(value.editing.anchor) : !!value.comment.trim()
18
68
  }
69
+ const validDraft = () => !!model?.value?.comment.trim() && dirty()
70
+ const anchorIdentity = anchor => anchor ? JSON.stringify([anchor.type, anchor.selector, anchor.quote, anchor.prefix, anchor.suffix]) : ""
71
+ function pendingCount() {
72
+ const pending = state?.notes.filter(note => note.sentRevision !== note.revision) || []
73
+ return pending.length + (validDraft() && !pending.some(note => note.id === model.value.editing?.id) ? 1 : 0)
74
+ }
75
+ function locked() { return ["save", "send", "copy-round", "restore-round", "cancel", "save-switch", "discard-switch", "delete", "undo", "reload-draft", "keep-draft"].some(id => busy.has(id)) }
19
76
  function controls() {
20
- const saving = busy.has("save") || busy.has("send")
21
- $("comment").disabled = $("kind").disabled = saving
22
- $("save").disabled = !state || !anchor || !$("comment").value.trim()
23
- $("send").disabled = !paired || !state || (!state.notes.some(n => n.sentRevision !== n.revision) && $("save").disabled)
24
- if (saving) $("save").disabled = true
77
+ const lock = locked() || outdated
78
+ $("comment").disabled = lock
79
+ for (const button of $("kind").querySelectorAll("button")) button.disabled = lock
80
+ $("save").disabled = lock || !state || !validDraft() || !!model?.conflict
81
+ $("save-switch").disabled = lock || !validDraft() || !!model?.conflict
82
+ $("pick").disabled = !state || lock
83
+ $("cancel").disabled = lock
84
+ for (const id of ["discard-switch", "keep-editing", "retry-draft", "reload-draft", "keep-draft", "copy-draft", "undo", "restore-round", "targets", "change-target", "refresh-targets"]) $(id).disabled = lock
25
85
  $("copy").disabled = $("export").disabled = !state?.notes.length
26
- $("pick").disabled = !state
27
- $("cancel").hidden = !editing && !anchor
28
- for (const id of busy) $(id).disabled = true
86
+ for (const button of $("notes").querySelectorAll("button")) button.disabled = lock
87
+ for (const id of busy) if ($(id)) $(id).disabled = true
88
+ if (outdated) for (const button of document.querySelectorAll("button:not(#reload-extension)")) button.disabled = true
89
+ renderDelivery()
90
+ }
91
+
92
+ function modelFor(next) {
93
+ let m = models.get(next.page.url)
94
+ if (!m) {
95
+ m = { page: next.page, hash: next.hash, record: next.draft, value: clone(next.draft.value), sequence: 0,
96
+ acknowledged: 0, touched: false, pending: new Set(), captureID: null, error: null, conflict: null }
97
+ models.set(next.page.url, m)
98
+ } else mergeDraft(m, next.draft)
99
+ return m
100
+ }
101
+ function mergeDraft(m, record) {
102
+ if (record.revision <= m.record.revision) return
103
+ if (record.writerID !== writerID && (m.touched || m.pending.size)) {
104
+ m.conflict = Object.assign(new Error("This draft changed in another panel. Choose which version to keep."), { code: "draft-conflict", draft: record })
105
+ m.error = m.conflict
106
+ return
107
+ }
108
+ m.record = record
109
+ if (!m.touched && !m.pending.size) m.value = clone(record.value)
110
+ }
111
+ function persistDraft(m, value = m.value) {
112
+ if (m.conflict) return Promise.reject(m.conflict)
113
+ const sequence = ++m.sequence, snapshot = clone(value)
114
+ m.touched = true
115
+ const promise = call({ action: "draft", page: m.page, value: snapshot, writerID, sequence, baseRevision: m.record.revision,
116
+ ...(value === null ? { captures: m.value?.captures } : {}) })
117
+ .then(result => {
118
+ if (result.draft.revision > m.record.revision) m.record = result.draft
119
+ if (sequence === m.sequence && !m.conflict) { m.acknowledged = sequence; m.error = null }
120
+ return result.draft
121
+ }, error => {
122
+ if (error.code === "draft-conflict") m.conflict = error
123
+ if (sequence === m.sequence || m.conflict) m.error = error
124
+ throw error
125
+ }).finally(() => {
126
+ m.pending.delete(promise)
127
+ if (m === model) { renderComposer(); controls() }
128
+ })
129
+ m.pending.add(promise)
130
+ if (m === model) renderComposer()
131
+ return promise
132
+ }
133
+ async function flushDraft(m) {
134
+ await Promise.allSettled([...m.pending])
135
+ if (m.error || m.conflict) throw m.conflict || m.error
136
+ }
137
+ function openComposer(value) {
138
+ model.value = clone(value); model.error = null; model.conflict = null; model.touched = false
139
+ selectedNoteID = value.editing?.id || null; pendingAction = null; notice = null
140
+ // Selection is broadcast to every open panel. Only user edits claim a draft.
141
+ render(); focusWhenReady("#comment")
142
+ }
143
+ async function discardDraft() {
144
+ const m = model
145
+ await persistDraft(m, null)
146
+ m.value = null; m.touched = false; m.error = null
147
+ if (model === m) { pendingAction = null; selectedNoteID = null; notice = null; render() }
148
+ }
149
+ function draftNote(value) {
150
+ const now = new Date().toISOString()
151
+ return { id: value.editing?.id || crypto.randomUUID(), revision: (value.editing?.revision || 0) + 1,
152
+ createdAt: value.editing?.createdAt || now, updatedAt: now, kind: value.kind, comment: value.comment.trim(), anchor: value.anchor }
153
+ }
154
+ async function saveCurrent(prepared) {
155
+ const m = model
156
+ if (!validDraft()) return
157
+ await flushDraft(m)
158
+ const value = clone(m.value), note = prepared || draftNote(value)
159
+ const result = await call({ action: "save", url: m.page.url, note, baseRevision: value.editing?.revision || 0,
160
+ draftRevision: m.record.revision, captures: value.captures })
161
+ m.record = result.draft; m.value = null; m.touched = false; m.error = null; m.conflict = null
162
+ if (model === m) { pendingAction = null; selectedNoteID = result.note.id }
163
+ await refresh(); status("Saved locally", "", m.page.url)
164
+ }
165
+ async function performAction(action) {
166
+ pendingAction = null
167
+ if (action.type === "select") openComposer({ anchor: action.anchor, captures: { [action.capture.tabID]: action.capture.id }, kind: "comment", comment: "", editing: null })
168
+ else if (action.type === "edit") {
169
+ const note = state.notes.find(note => note.id === action.id)
170
+ if (!note) throw new Error("This note has been removed; choose another note")
171
+ openComposer({ anchor: note.anchor, kind: note.kind, comment: note.comment, editing: note })
172
+ } else if (action.type === "delete") await deleteNote(action.id)
173
+ }
174
+ async function requestAction(action) {
175
+ if (dirty()) {
176
+ pendingAction = action; renderComposer(); controls()
177
+ $("switch-notice").scrollIntoView({ block: "nearest" })
178
+ } else await performAction(action)
179
+ }
180
+ async function deleteNote(id) {
181
+ const note = state.notes.find(note => note.id === id), m = model
182
+ if (!note) throw new Error("This note has already been removed")
183
+ const clearDraft = m.value?.editing?.id === id
184
+ if (clearDraft) await flushDraft(m)
185
+ const result = await call({ action: "delete", url: state.page.url, note, baseRevision: note.revision,
186
+ ...(clearDraft ? { draftRevision: m.record.revision, captures: m.value.captures } : {}) })
187
+ if (clearDraft) { m.record = result.draft; m.value = null; m.touched = false }
188
+ undoRecord = { note: result.note, url: state.page.url }
189
+ await refresh(); focusWhenReady("#undo")
190
+ }
191
+
192
+ function renderComposer() {
193
+ const value = model?.value
194
+ $("composer").hidden = !value
195
+ $("empty-state").hidden = !!value || !!state?.notes.length
196
+ renderEmpty()
197
+ if (!value) return
198
+ $("composer-title").textContent = value.editing ? "Edit note" : "New note"
199
+ $("quote").textContent = value.anchor.quote
200
+ if ($("comment").value !== value.comment) $("comment").value = value.comment
201
+ for (const button of $("kind").querySelectorAll("button")) {
202
+ const selected = button.dataset.kind === value.kind
203
+ button.setAttribute("aria-checked", String(selected)); button.tabIndex = selected ? 0 : -1
204
+ }
205
+ $("save-label").textContent = value.editing ? "Save changes" : "Add note"
206
+ $("draft-state").textContent = model.error ? "Draft not saved" : model.pending.size ? "Saving draft…" : value.editing && !dirty() ? "No changes yet" : value.comment.trim() ? "Draft saved locally" : "Only saved on your device"
207
+ $("switch-notice").hidden = !pendingAction
208
+ $("switch-description").textContent = pendingAction?.type === "delete" ? "Save your changes before removing this note, or keep editing." : "Add this feedback to your notes before switching, or keep editing."
209
+ $("save-switch").textContent = `${value.editing ? "Save" : "Add"} & ${pendingAction?.type === "delete" ? "continue" : "switch"}`
210
+ $("discard-switch").textContent = `Discard & ${pendingAction?.type === "delete" ? "continue" : "switch"}`
211
+ $("draft-error").hidden = !model.error
212
+ $("draft-error-text").textContent = model.error?.message || ""
213
+ $("retry-draft").hidden = !!model.conflict
214
+ $("reload-draft").hidden = $("keep-draft").hidden = !model.conflict
215
+ $("reload-draft").textContent = model.conflict?.code === "note-conflict" ? "Load saved note" : "Load saved draft"
216
+ const anchorState = state?.draftAnchorState
217
+ const sameStoredAnchor = anchorIdentity(state?.draft.value?.anchor) === anchorIdentity(value.anchor)
218
+ $("anchor-warning").hidden = !sameStoredAnchor || !anchorState || anchorState === "located"
219
+ $("anchor-warning").textContent = `Element ${anchorState}. Your draft is kept.`
220
+ }
221
+ function renderEmpty() {
222
+ const round = state?.lastRound
223
+ $("empty-title").textContent = round ? "Ready for the next round." : "Start with what you see."
224
+ $("empty-footnote").textContent = round
225
+ ? `Last round: ${plural(round.count)} ${round.via === "clipboard" ? "copied" : `sent to ${round.to || "your session"}`} at ${new Date(round.at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}.`
226
+ : "Send one note straight away, or collect a few first. Your feedback stays local until you send."
227
+ $("restore-round").hidden = !round
29
228
  }
30
- function reset() { anchor = null; editing = null; $("comment").value = ""; $("kind").value = "comment"; $("quote").textContent = "Select text or an element to begin."; $("save").textContent = "Save note"; controls() }
31
- function review() { return validateReview({ version: 1, page: state.page, annotations: state.notes }) }
32
229
  function renderNotes() {
33
- $("count").textContent = `${state.notes.length} notes`
34
- $("notes").replaceChildren()
35
- for (const [index, note] of state.notes.entries()) {
36
- const li = make("li"), actions = make("div"); actions.className = "actions"
37
- const edit = make("button", "Edit"), remove = make("button", "Delete")
38
- edit.onclick = () => { editing = note; anchor = note.anchor; $("quote").textContent = anchor.quote; $("comment").value = note.comment; $("kind").value = note.kind; $("save").textContent = "Save changes"; controls(); $("comment").focus() }
39
- remove.onclick = async () => {
40
- try { await call({ action: "delete", url: state.page.url, note, baseRevision: note.revision }); if (editing?.id === note.id) reset(); await refresh() }
41
- catch (error) { status(error.message, true) }
42
- }
43
- actions.append(edit, remove)
44
- li.append(make("small", `${note.kind} · ${note.sentRevision === note.revision ? "sent" : "pending"} · ${state.anchorStates?.[index] || "unavailable"} · ${note.anchor.quote.slice(0, 100)}`), make("p", note.comment), actions)
45
- $("notes").append(li)
230
+ const notes = state?.notes || []
231
+ $("notes-section").hidden = !notes.length
232
+ $("count").textContent = `${plural(notes.length)} in this round`
233
+ const key = JSON.stringify([notes, state?.anchorStates, selectedNoteID])
234
+ if (key === noteRenderKey) return
235
+ noteRenderKey = key; $("notes").replaceChildren()
236
+ for (const [index, note] of notes.entries()) {
237
+ const item = make("li"), number = make("span", index + 1), content = make("div"), target = make("button"), bottom = make("div"), meta = make("span")
238
+ item.className = `note${selectedNoteID === note.id ? " is-current" : ""}`; item.dataset.noteId = note.id
239
+ number.className = "note-number"; number.setAttribute("aria-label", `Note ${index + 1}`)
240
+ target.className = "note-target"; target.setAttribute("aria-label", `Show note ${index + 1} on page`)
241
+ target.append(make("span", note.anchor.quote.slice(0, 200)), icon("reveal"))
242
+ target.onclick = () => run("reveal", async () => {
243
+ await call({ action: "reveal", url: state.page.url, noteID: note.id }); selectedNoteID = note.id
244
+ status("Element highlighted on the page"); renderNotes()
245
+ $("notes").querySelector(`[data-note-id="${CSS.escape(note.id)}"] .note-target`)?.focus({ preventScroll: true })
246
+ })
247
+ const comment = make("p", note.comment); comment.className = "note-comment"
248
+ content.append(target, comment)
249
+ const anchorState = state.anchorStates[index]
250
+ if (anchorState !== "located") { const warning = make("p", `Element ${anchorState}. Your feedback is kept.`); warning.className = "warning"; content.append(warning) }
251
+ bottom.className = "note-bottom"; meta.className = "note-meta"
252
+ if (note.kind === "ask") meta.append(make("span", "Question"))
253
+ const edit = make("button", "Edit"), remove = make("button")
254
+ edit.className = "text-button"; edit.setAttribute("aria-label", `Edit note ${index + 1}`)
255
+ edit.onclick = () => run("edit", () => requestAction({ type: "edit", id: note.id }))
256
+ remove.className = "icon-button"; remove.title = "Delete note"; remove.setAttribute("aria-label", `Delete note ${index + 1}`); remove.append(icon("trash"))
257
+ remove.onclick = () => run("delete", () => model?.value?.editing?.id === note.id ? requestAction({ type: "delete", id: note.id }) : deleteNote(note.id))
258
+ bottom.append(meta, edit, remove); content.append(bottom); item.append(number, content); $("notes").append(item)
46
259
  }
47
- $("preview").textContent = state.notes.length ? markdown(review()) : "No saved notes"
260
+ $("preview").textContent = notes.length ? markdown(review()) : "Add a note to preview the feedback."
48
261
  call({ action: "markers" }).catch(() => {})
262
+ }
263
+ // Delivery has exactly two modes: a live session receives Send; otherwise the round is copied for any agent.
264
+ function deliveryMode() { return connectionLoading ? "loading" : available ? "send" : "copy" }
265
+ function renderDelivery() {
266
+ const mode = deliveryMode(), retry = mode === "send" ? state?.outbox : null, pending = pendingCount()
267
+ const count = retry?.count ?? pending, working = busy.has("send") || busy.has("copy-round")
268
+ const wrongDestination = retry && retry.targetID !== destination?.id
269
+ const choosing = !destination && targets.length > 0
270
+ $("paired").textContent = destination?.title || (connectionLoading ? "Looking for your session…" : choosing ? "Choose a session" : "No session")
271
+ $("change-target").title = destination ? `${destination.title}\n${destination.directory}` : "Choose where to send feedback"
272
+ $("link-state").textContent = mode === "send" ? "Live" : mode === "copy" && destination ? "Offline" : ""
273
+ $("link-state").className = `link-state ${mode === "send" ? "live" : "offline"}`
274
+ $("send-label").textContent = working ? busy.has("copy-round") || mode === "copy" ? "Copying…" : "Sending…" :
275
+ !state ? "Open a page to start" : mode === "loading" ? "Looking for your session…" :
276
+ mode === "copy" ? count ? `Copy ${plural(count)}` : destination ? "Reconnect session" : choosing ? "Choose a session" : "Connect a session" :
277
+ wrongDestination ? "Choose original session" : count ? `${retry ? "Retry" : "Send"} ${plural(count)}` : "Send notes"
278
+ $("send").disabled = locked() || outdated || !state || mode === "loading" ||
279
+ (mode === "send" && (!count || (!retry && !!model?.conflict))) || (mode === "copy" && !!count && !!model?.conflict)
280
+ $("send-arrow").toggleAttribute("hidden", mode !== "send" || !count || working)
281
+ $("send-copy").toggleAttribute("hidden", mode !== "copy" || !count || working)
282
+ $("copy-round").hidden = mode !== "send" || !state || !pending
283
+ $("copy-round").disabled = locked() || outdated || !!model?.conflict
284
+ const currentNotice = notice && (!notice.page || notice.page === state?.page.url) ? notice : null
285
+ for (const tone of ["error", "warning", "success"]) $("status").classList.toggle(tone, currentNotice?.tone === tone)
286
+ const where = destination ? "Session offline" : "No session"
287
+ $("status").textContent = currentNotice?.text || (mode === "loading" ? "Looking for your OpenCode session…" :
288
+ working ? busy.has("copy-round") || mode === "copy" ? "Copying to the clipboard…" : "Sending to the session…" :
289
+ mode === "copy" && choosing ? count ? "Choose a session above to send, or copy for any agent." : "Choose the session that should receive this review." :
290
+ mode === "copy" ? count ? `${where} · Copy works with any agent. Run /annotate-web in a session to send instead.` :
291
+ destination ? "Session offline · run /annotate-web in it to reconnect." : "No session · run /annotate-web in OpenCode, or add notes and copy them." :
292
+ wrongDestination ? "This batch belongs to the previous session." : retry ? "Retry the previous batch. New feedback stays local." :
293
+ count ? validDraft() ? "Sends to this session, including your current feedback." : "Sends to this session; the list starts fresh." : "Feedback stays local until you send.")
294
+ }
295
+ function render() {
296
+ renderComposer(); renderNotes()
297
+ $("undo-notice").hidden = !undoRecord || undoRecord.url !== state?.page.url
49
298
  controls()
50
299
  }
300
+ function scheduleRefresh() { clearTimeout(scheduledRefresh); scheduledRefresh = setTimeout(() => refresh(), 30) }
51
301
  async function refresh() {
52
- const requestID = ++refreshID
302
+ const request = ++refreshID
53
303
  try {
54
304
  const next = await call({ action: "current" })
55
- if (requestID !== refreshID) return
56
- if (pageURL !== next.page.url) { pageURL = next.page.url; reset(); capturedIdentity = null; lastPageError = null }
57
- const changed = JSON.stringify(state?.notes) !== JSON.stringify(next.notes) || JSON.stringify(state?.anchorStates) !== JSON.stringify(next.anchorStates)
58
- state = next
59
- $("page-title").textContent = state.page.title
60
- $("page-url").textContent = state.page.url
61
- if (state.anchor && JSON.stringify(state.anchor) !== capturedIdentity && !editing) {
62
- capturedIdentity = JSON.stringify(state.anchor); anchor = state.anchor; $("quote").textContent = anchor.quote
63
- status("Selected. Write feedback, then Send & continue.")
305
+ if (request !== refreshID) return
306
+ if (next.protocol !== PROTOCOL) { markOutdated(); return }
307
+ if (state?.page.url !== next.page.url) { pendingAction = null; selectedNoteID = null; notice = null }
308
+ state = next; model = modelFor(next)
309
+ $("page-title").textContent = next.page.title; $("page-title").title = next.page.title
310
+ const url = new URL(next.page.url)
311
+ $("page-url").textContent = url.protocol === "file:" ? decodeURIComponent(url.pathname.split("/").pop()) : `${url.host}${url.pathname === "/" ? "" : url.pathname}`
312
+ $("page-url").title = next.page.url
313
+ const pageError = next.detached || next.error
314
+ $("page-error").hidden = !pageError; $("page-error").textContent = pageError || ""
315
+ $("pick-label").textContent = next.picking ? "Cancel pick (Esc)" : "Pick element"
316
+ $("pick").setAttribute("aria-pressed", String(!!next.picking)); $("pick-hint").hidden = !!next.picking
317
+ if (next.captureID && next.captureID !== model.captureID) {
318
+ model.captureID = next.captureID
319
+ if (next.anchor && next.draft.consumedCaptures?.[next.tabID] !== next.captureID) {
320
+ notice = null
321
+ if (anchorIdentity(next.anchor) !== anchorIdentity(model.value?.anchor)) await requestAction({ type: "select", anchor: next.anchor,
322
+ capture: { id: next.captureID, tabID: next.tabID } })
323
+ else model.value.captures = { ...model.value.captures, [next.tabID]: next.captureID }
324
+ } else if (next.error) status(next.error, "error")
64
325
  }
65
- if (state.error && state.error !== lastPageError) status(state.error, true)
66
- lastPageError = state.error
67
- $("pick").textContent = state.picking ? "Cancel pick (Esc)" : "Pick an element"
68
- $("pick").setAttribute("aria-pressed", String(!!state.picking))
69
- $("pick-hint").textContent = state.picking ? "Click one page element. Picking ends after the click, or press Esc to cancel." : "Or select text on the page, write feedback, then send. Use Save note to collect several notes first."
70
- if (changed) renderNotes()
326
+ render()
327
+ } catch (error) {
328
+ if (request !== refreshID || error.code === "outdated") return
329
+ state = null; $("page-error").hidden = false; $("page-error").textContent = error.message
71
330
  controls()
72
- } catch (error) { if (requestID === refreshID) { state = null; controls(); status(error.message, true) } }
73
- }
74
- $("comment").addEventListener("input", controls)
75
- $("comment").addEventListener("keydown", event => { if (event.key === "Enter" && (event.metaKey || event.ctrlKey) && !$("save").disabled) { event.preventDefault(); $("save").click() } })
76
- task("pick", async () => { const result = await call({ action: "pick" }); await refresh(); status(result.picking ? "Click a page element; Esc cancels" : "Selection cancelled") })
77
- task("cancel", reset)
78
- async function saveCurrent() {
79
- status("Saving note…")
80
- const now = new Date().toISOString()
81
- const note = { id: editing?.id || crypto.randomUUID(), revision: (editing?.revision || 0) + 1,
82
- createdAt: editing?.createdAt || now, updatedAt: now, kind: $("kind").value, comment: $("comment").value.trim(), anchor }
83
- await call({ action: "save", url: state.page.url, note, baseRevision: editing?.revision || 0 })
84
- reset(); await refresh(); status("Saved locally")
85
- }
86
- task("save", saveCurrent)
87
- function showConnection() {
88
- $("paired").textContent = paired ? paired.title : targets.length > 1 ? "Choose where to send feedback" : "No connected session"
89
- $("paired").title = paired ? `${paired.title}\n${paired.directory}` : ""
90
- $("connection-hint").textContent = paired ? "Sending continues this session. Comments stay private until you send." : "Run /annotate web in the target OpenCode session."
91
- controls()
331
+ }
332
+ }
333
+ function showSessionOptions(show = true, focus = true) {
334
+ $("session-options").hidden = !show; $("change-target").setAttribute("aria-expanded", String(show))
335
+ if (show && focus) { notice = null; $("panel-body").scrollTop = 0; focusWhenReady("#targets", false) }
92
336
  }
93
337
  async function refreshConnection() {
94
338
  if (connectionBusy) return
95
339
  connectionBusy = true
96
340
  const revision = connectionRevision
97
341
  try {
98
- const result = await call({ action: "connection" })
99
- if (revision !== connectionRevision) return
100
- targets = result.targets; paired = result.target
101
- $("targets").replaceChildren(make("option", "Select a session…")); $("targets").firstChild.value = ""
102
- for (const target of targets) { const option = make("option", `${target.title} — ${target.directory}`); option.value = target.id; $("targets").append(option) }
103
- if (paired) $("targets").value = paired.id
104
- if (!paired && targets.length) { $("session-options").hidden = false; $("change-target").setAttribute("aria-expanded", "true") }
105
- showConnection()
106
- if (result.stale) $("connection-hint").textContent = "Previous session disconnected. Choose a session explicitly to switch."
342
+ const result = await call({ action: "connection" })
343
+ if (revision !== connectionRevision) return
344
+ if (available?.id !== result.target?.id || destination?.id !== result.destination?.id) notice = null
345
+ targets = result.targets; available = result.target; destination = result.destination; connectionError = result.error || ""
346
+ const optionsKey = JSON.stringify([targets.map(target => [target.id, target.title, target.directory]), destination?.id, !!available])
347
+ if (optionsKey !== connectionOptionsKey) {
348
+ connectionOptionsKey = optionsKey
349
+ $("targets").replaceChildren(make("option", "Choose a session…")); $("targets").firstChild.value = ""
350
+ if (destination && !targets.some(target => target.id === destination.id)) {
351
+ const option = make("option", `${destination.title} — disconnected`); option.value = destination.id; option.disabled = true; $("targets").append(option)
352
+ }
353
+ for (const target of targets) { const option = make("option", `${target.title} — ${target.directory}`); option.value = target.id; $("targets").append(option) }
354
+ $("targets").value = destination?.id || ""
355
+ }
356
+ $("connection-hint").textContent = connectionError ? `Session unavailable: ${connectionError}` : !available && destination ? "Reconnect the original OpenCode session, then refresh. Choose another session only to change the destination." : targets.length > 1 && !destination ? "Choose the session that should receive this review." : !available ? "Run /annotate-web in OpenCode, then refresh." : "Sending continues the selected session."
357
+ if (!destination && targets.length > 1) showSessionOptions(true, false)
107
358
  } catch (error) {
108
- if (revision === connectionRevision) { paired = null; showConnection(); $("connection-hint").textContent = `Session unavailable: ${error.message}` }
109
- } finally { connectionBusy = false; controls() }
359
+ available = null; connectionError = error.message; $("connection-hint").textContent = `Session unavailable: ${error.message}`
360
+ } finally { connectionBusy = false; connectionLoading = false; controls() }
110
361
  }
111
- task("refresh-targets", refreshConnection)
112
- task("change-target", async () => {
113
- const hidden = !$("session-options").hidden
114
- $("session-options").hidden = hidden; $("change-target").setAttribute("aria-expanded", String(!hidden))
115
- if (!hidden) await refreshConnection()
362
+ function review() { return validateReview({ version: 1, page: state.page, annotations: state.notes }) }
363
+
364
+ $("comment").addEventListener("input", () => {
365
+ model.value.comment = $("comment").value; notice = null
366
+ persistDraft(model).catch(() => {}); controls()
116
367
  })
117
- $("targets").addEventListener("change", async () => {
368
+ $("comment").addEventListener("keydown", event => {
369
+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey) && !$("save").disabled) { event.preventDefault(); $("save").click() }
370
+ })
371
+ for (const button of $("kind").querySelectorAll("button")) {
372
+ button.addEventListener("click", () => { model.value.kind = button.dataset.kind; persistDraft(model).catch(() => {}); renderComposer(); controls(); button.focus() })
373
+ button.addEventListener("keydown", event => {
374
+ if (!["ArrowLeft", "ArrowRight"].includes(event.key)) return
375
+ event.preventDefault(); $(model.value.kind === "comment" ? "kind-ask" : "kind-comment").click()
376
+ })
377
+ }
378
+ $("save-shortcut").textContent = navigator.platform.includes("Mac") ? "⌘↵" : "Ctrl↵"
379
+ task("pick", async () => { notice = null; await call({ action: "pick" }); await refresh() })
380
+ task("save", async () => { await saveCurrent(); focusWhenReady("#pick") })
381
+ task("cancel", async () => { await discardDraft(); focusWhenReady("#pick") })
382
+ task("save-switch", async () => { const action = pendingAction; await saveCurrent(); await performAction(action) })
383
+ task("discard-switch", async () => { const action = pendingAction; await discardDraft(); await performAction(action) })
384
+ task("keep-editing", () => { pendingAction = null; renderComposer(); focusWhenReady("#comment") })
385
+ task("retry-draft", async () => { await persistDraft(model); status("Draft saved locally"); focusWhenReady("#comment") })
386
+ task("reload-draft", async () => {
387
+ const conflict = model.conflict
388
+ if (conflict.code === "draft-conflict") { model.record = conflict.draft; model.value = clone(conflict.draft.value); model.touched = false; model.error = null; model.conflict = null }
389
+ else {
390
+ const note = conflict.note
391
+ model.error = null; model.conflict = null
392
+ if (!note || note.deleted) await discardDraft()
393
+ else openComposer({ anchor: note.anchor, kind: note.kind, comment: note.comment, editing: note })
394
+ }
395
+ pendingAction = null; notice = null; render(); focusWhenReady(model.value ? "#comment" : "#pick")
396
+ })
397
+ task("keep-draft", async () => {
398
+ const conflict = model.conflict
399
+ if (conflict.code === "draft-conflict") model.record = conflict.draft
400
+ else model.value.editing = conflict.note?.deleted ? null : conflict.note
401
+ model.error = null; model.conflict = null
402
+ await persistDraft(model); status("Your draft is saved locally"); focusWhenReady("#comment")
403
+ })
404
+ task("copy-draft", async () => {
405
+ try { await navigator.clipboard.writeText(model.value.comment); status("Draft copied") }
406
+ catch { $("comment").focus(); $("comment").select(); status("Automatic copy was blocked. Press Cmd/Ctrl+C to copy your draft.", "error") }
407
+ })
408
+ task("undo", async () => {
409
+ const { note, url } = undoRecord
410
+ await call({ action: "restore", url, note, baseRevision: note.revision }); undoRecord = null
411
+ await refresh(); status("Note restored"); focusWhenReady(`[data-note-id="${CSS.escape(note.id)}"] .note-target`)
412
+ })
413
+ task("more", () => { const show = $("utilities").hidden; $("utilities").hidden = !show; $("more").setAttribute("aria-expanded", String(show)); if (show) $("panel-body").scrollTop = 0 })
414
+ task("refresh-targets", refreshConnection)
415
+ task("change-target", async () => { showSessionOptions($("session-options").hidden); if (!$("session-options").hidden) await refreshConnection() })
416
+ $("targets").addEventListener("change", () => run("targets", async () => {
118
417
  const target = targets.find(target => target.id === $("targets").value)
119
418
  if (!target) return
120
419
  connectionRevision++
121
- try {
122
- paired = (await call({ action: "pair", target })).target
123
- $("session-options").hidden = true; $("change-target").setAttribute("aria-expanded", "false"); showConnection()
124
- } catch (error) { status(error.message, true) }
420
+ destination = (await call({ action: "pair", target })).target; available = destination; connectionError = ""; notice = null
421
+ showSessionOptions(false); renderDelivery(); focusWhenReady("#change-target", false)
422
+ }))
423
+ function showManualCopy(text) {
424
+ $("utilities").hidden = false; $("more").setAttribute("aria-expanded", "true"); $("context-details").open = true
425
+ $("preview").textContent = text
426
+ const range = document.createRange(); range.selectNodeContents($("preview")); getSelection().removeAllRanges(); getSelection().addRange(range)
427
+ $("preview").scrollIntoView({ block: "nearest" })
428
+ }
429
+ // Chrome only grants clipboard access during the click, so copy before any storage round trip.
430
+ function copyText(text) {
431
+ const legacy = () => {
432
+ const area = make("textarea"); area.value = text; area.readOnly = true; area.style.cssText = "position:fixed;opacity:0;pointer-events:none"
433
+ document.body.append(area); area.select()
434
+ try { return document.execCommand("copy") } finally { area.remove() }
435
+ }
436
+ return navigator.clipboard.writeText(text).catch(error => { if (!legacy()) throw error })
437
+ }
438
+ async function copyRound() {
439
+ const page = state.page
440
+ if (model.error || model.conflict) throw model.conflict || model.error
441
+ const prepared = validDraft() ? draftNote(clone(model.value)) : null
442
+ const notes = !prepared ? state.notes : state.notes.some(note => note.id === prepared.id)
443
+ ? state.notes.map(note => note.id === prepared.id ? prepared : note) : [...state.notes, prepared]
444
+ const text = markdown(validateReview({ version: 1, page, annotations: notes }))
445
+ try { await copyText(text) }
446
+ catch {
447
+ showManualCopy(text)
448
+ status("Automatic copy was blocked. The preview is selected; press Cmd/Ctrl+C. Notes stay in this round.", "error")
449
+ return
450
+ }
451
+ if (prepared) await saveCurrent(prepared)
452
+ const result = await call({ action: "copied", url: page.url, notes: notes.map(({ id, revision }) => ({ id, revision })) })
453
+ await refresh()
454
+ status(`Copied ${plural(result.count)} · paste into any agent. Ready for the next round.`, "success", page.url)
455
+ focusWhenReady(model.value ? "#comment" : "#pick")
456
+ }
457
+ task("copy-round", copyRound)
458
+ task("restore-round", async () => {
459
+ const result = await call({ action: "restore-round", url: state.page.url, roundID: state.lastRound.id })
460
+ await refresh(); status(`Restored ${plural(result.count)} to this round`); focusWhenReady("#notes .note-target")
125
461
  })
126
462
  task("send", async () => {
127
- const destination = paired
128
- if (!destination) throw new Error("Choose an OpenCode session before sending")
463
+ // The click follows the visible label: Copy without a live session, Send with one.
464
+ if (deliveryMode() === "copy") {
465
+ if (state && pendingCount()) return copyRound()
466
+ showSessionOptions(); await refreshConnection(); return
467
+ }
468
+ if (state.outbox && state.outbox.targetID !== destination.id) { showSessionOptions(); status("Choose the original session to retry this batch, or copy your notes.", "warning"); return }
469
+ const target = destination, page = state.page
470
+ if (!state.outbox) {
471
+ if (model.error || model.conflict) throw model.conflict || model.error
472
+ if (validDraft()) await saveCurrent()
473
+ }
129
474
  status("Sending feedback…")
130
- if (anchor && $("comment").value.trim()) await saveCurrent()
131
- const response = await call({ action: "send", url: state.page.url, targetID: destination.id })
132
- await refresh(); $("status").title = response.messageID
133
- status("Feedback queued. The agent will continue in the selected session.")
475
+ let result
476
+ try { result = await call({ action: "send", url: page.url, targetID: target.id }) }
477
+ catch (error) {
478
+ await Promise.all([refresh(), refreshConnection()])
479
+ if (available) throw error
480
+ status("The session went offline before receiving this round. Notes are kept; copy them, or run /annotate-web there and send again.", "warning", page.url)
481
+ return
482
+ }
483
+ await refresh(); $("status").title = result.messageID
484
+ status(`Sent ${plural(result.count)} to ${target.title}. Ready for the next round.`, "success", page.url)
485
+ focusWhenReady(model.value ? "#comment" : "#pick")
134
486
  })
487
+ $("reload-extension").addEventListener("click", () => chrome.runtime.reload())
135
488
  task("copy", async () => {
136
489
  const text = markdown(review())
137
- try { await navigator.clipboard.writeText(text); status("Context copied. Paste it into any agent.") }
138
- catch {
139
- $("preview").textContent = text; document.querySelector("details").open = true
140
- const range = document.createRange(); range.selectNodeContents($("preview")); getSelection().removeAllRanges(); getSelection().addRange(range)
141
- status("Automatic copy was blocked. The preview is selected; press Cmd/Ctrl+C.", true)
142
- }
490
+ try { await copyText(text); status("Context copied. Notes stay in this round.") }
491
+ catch { showManualCopy(text); status("Automatic copy was blocked. The preview is selected; press Cmd/Ctrl+C.", "error") }
143
492
  })
144
493
  task("export", () => {
145
494
  const url = URL.createObjectURL(new Blob([JSON.stringify(review(), null, 2)], { type: "application/json" }))
146
- const a = make("a"); a.href = url; a.download = "annotate-feedback.json"; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000)
495
+ const link = make("a"); link.href = url; link.download = "annotate-feedback.json"; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000)
147
496
  status("Complete review exported")
148
497
  })
149
- chrome.storage.onChanged.addListener((changes, area) => { if (area === "local" || area === "session") refresh(); if (changes.paired) refreshConnection() })
150
- chrome.tabs.onActivated.addListener(refresh)
151
- chrome.tabs.onUpdated.addListener((_id, change) => { if (change.status === "complete") refresh() })
498
+ document.addEventListener("keydown", event => {
499
+ if (event.key !== "Escape") return
500
+ if (state?.picking) $("pick").click()
501
+ pendingAction = null; $("utilities").hidden = true; $("more").setAttribute("aria-expanded", "false"); showSessionOptions(false); renderComposer()
502
+ })
503
+ chrome.storage.onChanged.addListener((changes, area) => {
504
+ if (area === "local" || area === "session") {
505
+ const ownDraftsOnly = Object.entries(changes).every(([key, value]) => key.startsWith("draft:") && value.newValue?.writerID === writerID)
506
+ if (!ownDraftsOnly) scheduleRefresh()
507
+ }
508
+ if (changes.paired) refreshConnection()
509
+ })
510
+ chrome.tabs.onActivated.addListener(scheduleRefresh)
511
+ chrome.tabs.onUpdated.addListener((_id, change) => { if (change.status === "complete") scheduleRefresh() })
152
512
  setInterval(() => { if (document.visibilityState === "visible") refresh() }, 1500)
153
- setInterval(() => { if (!paired && document.visibilityState === "visible") refreshConnection() }, 10000)
513
+ setInterval(() => { if (document.visibilityState === "visible") refreshConnection() }, 10000)
154
514
  window.addEventListener("focus", refreshConnection)
155
515
  await Promise.all([refreshConnection(), refresh()])