@nxxxsooo/opencode-annotate 0.5.0 → 0.6.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,435 @@
1
1
  import { 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
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?.ok) throw Object.assign(new Error(result?.error || "Extension disconnected; reopen the panel"), { code: result?.code, draft: result?.draft, note: result?.note })
11
20
  return result
12
21
  }
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
- })
22
+ function status(text, error = false, page = state?.page.url) { notice = text ? { text, error, page } : null; renderDelivery() }
23
+ function focusWhenReady(selector, scroll = true) {
24
+ pendingFocus = { selector, scroll, page: state?.page.url }
25
+ flushFocus()
26
+ }
27
+ function flushFocus() {
28
+ if (!pendingFocus) return false
29
+ const request = pendingFocus, node = document.querySelector(request.selector)
30
+ if (request.page !== state?.page.url || !node || !node.getClientRects().length) { pendingFocus = null; return false }
31
+ if (node.disabled && busy.size) return false
32
+ pendingFocus = null
33
+ if (node.disabled) return false
34
+ node.focus({ preventScroll: true })
35
+ if (request.scroll) node.scrollIntoView({ block: "nearest" })
36
+ return true
37
+ }
38
+ async function run(id, fn) {
39
+ if (busy.has(id)) return
40
+ const previousFocus = document.activeElement, page = state?.page.url
41
+ busy.add(id); controls()
42
+ try { await fn() }
43
+ catch (error) {
44
+ if (model && ["draft-conflict", "note-conflict"].includes(error.code)) {
45
+ model.conflict = error; model.error = error
46
+ renderComposer()
47
+ }
48
+ status(error.message, true)
49
+ } finally {
50
+ busy.delete(id); if ($(id)) $(id).disabled = false; controls()
51
+ if (!flushFocus() && !pendingFocus && document.activeElement === document.body && page === state?.page.url &&
52
+ previousFocus?.isConnected && !previousFocus.disabled && previousFocus.getClientRects().length) previousFocus.focus({ preventScroll: true })
53
+ }
54
+ }
55
+ const task = (id, fn) => $(id).addEventListener("click", () => run(id, fn))
56
+ function dirty(m = model) {
57
+ const value = m?.value
58
+ if (!value) return false
59
+ return value.editing ? value.comment.trim() !== value.editing.comment || value.kind !== value.editing.kind ||
60
+ anchorIdentity(value.anchor) !== anchorIdentity(value.editing.anchor) : !!value.comment.trim()
18
61
  }
62
+ const validDraft = () => !!model?.value?.comment.trim() && dirty()
63
+ const anchorIdentity = anchor => anchor ? JSON.stringify([anchor.type, anchor.selector, anchor.quote, anchor.prefix, anchor.suffix]) : ""
64
+ function pendingCount() {
65
+ const pending = state?.notes.filter(note => note.sentRevision !== note.revision) || []
66
+ return pending.length + (validDraft() && !pending.some(note => note.id === model.value.editing?.id) ? 1 : 0)
67
+ }
68
+ function locked() { return ["save", "send", "cancel", "save-switch", "discard-switch", "delete", "undo", "reload-draft", "keep-draft"].some(id => busy.has(id)) }
19
69
  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
70
+ const lock = locked()
71
+ $("comment").disabled = lock
72
+ for (const button of $("kind").querySelectorAll("button")) button.disabled = lock
73
+ $("save").disabled = lock || !state || !validDraft() || !!model?.conflict
74
+ $("save-switch").disabled = lock || !validDraft() || !!model?.conflict
75
+ $("pick").disabled = !state || lock
76
+ $("cancel").disabled = lock
77
+ for (const id of ["discard-switch", "keep-editing", "retry-draft", "reload-draft", "keep-draft", "copy-draft", "undo", "targets", "change-target", "refresh-targets"]) $(id).disabled = lock
25
78
  $("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
79
+ for (const button of $("notes").querySelectorAll("button")) button.disabled = lock
80
+ for (const id of busy) if ($(id)) $(id).disabled = true
81
+ renderDelivery()
82
+ }
83
+
84
+ function modelFor(next) {
85
+ let m = models.get(next.page.url)
86
+ if (!m) {
87
+ m = { page: next.page, hash: next.hash, record: next.draft, value: clone(next.draft.value), sequence: 0,
88
+ acknowledged: 0, touched: false, pending: new Set(), captureID: null, error: null, conflict: null }
89
+ models.set(next.page.url, m)
90
+ } else mergeDraft(m, next.draft)
91
+ return m
92
+ }
93
+ function mergeDraft(m, record) {
94
+ if (record.revision <= m.record.revision) return
95
+ if (record.writerID !== writerID && (m.touched || m.pending.size)) {
96
+ m.conflict = Object.assign(new Error("This draft changed in another panel. Choose which version to keep."), { code: "draft-conflict", draft: record })
97
+ m.error = m.conflict
98
+ return
99
+ }
100
+ m.record = record
101
+ if (!m.touched && !m.pending.size) m.value = clone(record.value)
102
+ }
103
+ function persistDraft(m, value = m.value) {
104
+ if (m.conflict) return Promise.reject(m.conflict)
105
+ const sequence = ++m.sequence, snapshot = clone(value)
106
+ m.touched = true
107
+ const promise = call({ action: "draft", page: m.page, value: snapshot, writerID, sequence, baseRevision: m.record.revision,
108
+ ...(value === null ? { captures: m.value?.captures } : {}) })
109
+ .then(result => {
110
+ if (result.draft.revision > m.record.revision) m.record = result.draft
111
+ if (sequence === m.sequence && !m.conflict) { m.acknowledged = sequence; m.error = null }
112
+ return result.draft
113
+ }, error => {
114
+ if (error.code === "draft-conflict") m.conflict = error
115
+ if (sequence === m.sequence || m.conflict) m.error = error
116
+ throw error
117
+ }).finally(() => {
118
+ m.pending.delete(promise)
119
+ if (m === model) { renderComposer(); controls() }
120
+ })
121
+ m.pending.add(promise)
122
+ if (m === model) renderComposer()
123
+ return promise
124
+ }
125
+ async function flushDraft(m) {
126
+ await Promise.allSettled([...m.pending])
127
+ if (m.error || m.conflict) throw m.conflict || m.error
128
+ }
129
+ function openComposer(value) {
130
+ model.value = clone(value); model.error = null; model.conflict = null; model.touched = false
131
+ selectedNoteID = value.editing?.id || null; pendingAction = null; notice = null
132
+ // Selection is broadcast to every open panel. Only user edits claim a draft.
133
+ render(); focusWhenReady("#comment")
134
+ }
135
+ async function discardDraft() {
136
+ const m = model
137
+ await persistDraft(m, null)
138
+ m.value = null; m.touched = false; m.error = null
139
+ if (model === m) { pendingAction = null; selectedNoteID = null; notice = null; render() }
140
+ }
141
+ async function saveCurrent() {
142
+ const m = model
143
+ if (!validDraft()) return
144
+ await flushDraft(m)
145
+ const value = clone(m.value), now = new Date().toISOString()
146
+ const note = { id: value.editing?.id || crypto.randomUUID(), revision: (value.editing?.revision || 0) + 1,
147
+ createdAt: value.editing?.createdAt || now, updatedAt: now, kind: value.kind, comment: value.comment.trim(), anchor: value.anchor }
148
+ const result = await call({ action: "save", url: m.page.url, note, baseRevision: value.editing?.revision || 0,
149
+ draftRevision: m.record.revision, captures: value.captures })
150
+ m.record = result.draft; m.value = null; m.touched = false; m.error = null; m.conflict = null
151
+ if (model === m) { pendingAction = null; selectedNoteID = result.note.id }
152
+ await refresh(); status("Saved locally", false, m.page.url)
153
+ }
154
+ async function performAction(action) {
155
+ pendingAction = null
156
+ if (action.type === "select") openComposer({ anchor: action.anchor, captures: { [action.capture.tabID]: action.capture.id }, kind: "comment", comment: "", editing: null })
157
+ else if (action.type === "edit") {
158
+ const note = state.notes.find(note => note.id === action.id)
159
+ if (!note) throw new Error("This note has been removed; choose another note")
160
+ openComposer({ anchor: note.anchor, kind: note.kind, comment: note.comment, editing: note })
161
+ } else if (action.type === "delete") await deleteNote(action.id)
162
+ }
163
+ async function requestAction(action) {
164
+ if (dirty()) {
165
+ pendingAction = action; renderComposer(); controls()
166
+ $("switch-notice").scrollIntoView({ block: "nearest" })
167
+ } else await performAction(action)
168
+ }
169
+ async function deleteNote(id) {
170
+ const note = state.notes.find(note => note.id === id), m = model
171
+ if (!note) throw new Error("This note has already been removed")
172
+ const clearDraft = m.value?.editing?.id === id
173
+ if (clearDraft) await flushDraft(m)
174
+ const result = await call({ action: "delete", url: state.page.url, note, baseRevision: note.revision,
175
+ ...(clearDraft ? { draftRevision: m.record.revision, captures: m.value.captures } : {}) })
176
+ if (clearDraft) { m.record = result.draft; m.value = null; m.touched = false }
177
+ undoRecord = { note: result.note, url: state.page.url }
178
+ await refresh(); focusWhenReady("#undo")
179
+ }
180
+
181
+ function renderComposer() {
182
+ const value = model?.value
183
+ $("composer").hidden = !value
184
+ $("empty-state").hidden = !!value || !!state?.notes.length
185
+ if (!value) return
186
+ $("composer-title").textContent = value.editing ? "Edit note" : "New note"
187
+ $("quote").textContent = value.anchor.quote
188
+ if ($("comment").value !== value.comment) $("comment").value = value.comment
189
+ for (const button of $("kind").querySelectorAll("button")) {
190
+ const selected = button.dataset.kind === value.kind
191
+ button.setAttribute("aria-checked", String(selected)); button.tabIndex = selected ? 0 : -1
192
+ }
193
+ $("save-label").textContent = value.editing ? "Save changes" : "Add note"
194
+ $("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"
195
+ $("switch-notice").hidden = !pendingAction
196
+ $("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."
197
+ $("save-switch").textContent = `${value.editing ? "Save" : "Add"} & ${pendingAction?.type === "delete" ? "continue" : "switch"}`
198
+ $("discard-switch").textContent = `Discard & ${pendingAction?.type === "delete" ? "continue" : "switch"}`
199
+ $("draft-error").hidden = !model.error
200
+ $("draft-error-text").textContent = model.error?.message || ""
201
+ $("retry-draft").hidden = !!model.conflict
202
+ $("reload-draft").hidden = $("keep-draft").hidden = !model.conflict
203
+ $("reload-draft").textContent = model.conflict?.code === "note-conflict" ? "Load saved note" : "Load saved draft"
204
+ const anchorState = state?.draftAnchorState
205
+ const sameStoredAnchor = anchorIdentity(state?.draft.value?.anchor) === anchorIdentity(value.anchor)
206
+ $("anchor-warning").hidden = !sameStoredAnchor || !anchorState || anchorState === "located"
207
+ $("anchor-warning").textContent = `Element ${anchorState}. Your draft is kept.`
29
208
  }
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
209
  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)
210
+ const notes = state?.notes || [], pending = notes.filter(note => note.sentRevision !== note.revision).length
211
+ $("notes-section").hidden = !notes.length
212
+ $("count").textContent = pending ? `${pending} pending` : `${notes.length} sent`
213
+ const key = JSON.stringify([notes, state?.anchorStates, selectedNoteID])
214
+ if (key === noteRenderKey) return
215
+ noteRenderKey = key; $("notes").replaceChildren()
216
+ for (const [index, note] of notes.entries()) {
217
+ const item = make("li"), number = make("span", index + 1), content = make("div"), target = make("button"), bottom = make("div"), meta = make("span")
218
+ item.className = `note${selectedNoteID === note.id ? " is-current" : ""}`; item.dataset.noteId = note.id
219
+ number.className = "note-number"; number.setAttribute("aria-label", `Note ${index + 1}`)
220
+ target.className = "note-target"; target.setAttribute("aria-label", `Show note ${index + 1} on page`)
221
+ target.append(make("span", note.anchor.quote.slice(0, 200)), icon("reveal"))
222
+ target.onclick = () => run("reveal", async () => {
223
+ await call({ action: "reveal", url: state.page.url, noteID: note.id }); selectedNoteID = note.id
224
+ status("Element highlighted on the page"); renderNotes()
225
+ $("notes").querySelector(`[data-note-id="${CSS.escape(note.id)}"] .note-target`)?.focus({ preventScroll: true })
226
+ })
227
+ const comment = make("p", note.comment); comment.className = "note-comment"
228
+ content.append(target, comment)
229
+ const anchorState = state.anchorStates[index]
230
+ if (anchorState !== "located") { const warning = make("p", `Element ${anchorState}. Your feedback is kept.`); warning.className = "warning"; content.append(warning) }
231
+ bottom.className = "note-bottom"; meta.className = "note-meta"
232
+ if (note.kind === "ask") meta.append(make("span", "Question"))
233
+ if (note.sentRevision === note.revision) { const sent = make("span"); sent.className = "sent-mark"; sent.append(icon("check"), make("span", "Sent")); meta.append(sent) }
234
+ else meta.append(make("span", "Pending"))
235
+ const edit = make("button", "Edit"), remove = make("button")
236
+ edit.className = "text-button"; edit.setAttribute("aria-label", `Edit note ${index + 1}`)
237
+ edit.onclick = () => run("edit", () => requestAction({ type: "edit", id: note.id }))
238
+ remove.className = "icon-button"; remove.title = "Delete note"; remove.setAttribute("aria-label", `Delete note ${index + 1}`); remove.append(icon("trash"))
239
+ remove.onclick = () => run("delete", () => model?.value?.editing?.id === note.id ? requestAction({ type: "delete", id: note.id }) : deleteNote(note.id))
240
+ bottom.append(meta, edit, remove); content.append(bottom); item.append(number, content); $("notes").append(item)
46
241
  }
47
- $("preview").textContent = state.notes.length ? markdown(review()) : "No saved notes"
242
+ $("preview").textContent = notes.length ? markdown(review()) : "Add a note to preview the feedback."
48
243
  call({ action: "markers" }).catch(() => {})
244
+ }
245
+ function renderDelivery() {
246
+ const retry = state?.outbox, count = retry?.count ?? pendingCount(), connected = !!available, sending = busy.has("send") && connected
247
+ const wrongDestination = retry && retry.targetID !== destination?.id
248
+ const allSent = !!state?.notes.length && !count && !model?.value && !retry
249
+ $("paired").textContent = destination?.title || (connectionLoading ? "Looking for your session…" : "Choose a session")
250
+ $("change-target").title = destination ? `${destination.title}\n${destination.directory}` : "Choose where to send feedback"
251
+ $("send-label").textContent = sending ? "Sending…" : !connected ? destination ? "Reconnect session" : "Connect a session" : !state ? "Open a page to send" : wrongDestination ? "Choose original session" : count ? `${retry ? "Retry" : "Send"} ${count} note${count === 1 ? "" : "s"} & continue` : allSent ? "All notes sent" : "Send & continue"
252
+ $("send").disabled = locked() || connectionLoading || (connected && (!state || !count || (!retry && !!model?.conflict)))
253
+ $("send-arrow").toggleAttribute("hidden", !connected || !count || sending)
254
+ $("send-check").toggleAttribute("hidden", !connected || !allSent)
255
+ const currentNotice = notice && (!notice.page || notice.page === state?.page.url) ? notice : null
256
+ $("status").classList.toggle("error", !!currentNotice?.error)
257
+ $("status").classList.toggle("success", !currentNotice?.error && allSent && connected)
258
+ $("status").textContent = currentNotice?.text || (connectionLoading ? "Looking for your OpenCode session…" : sending ? "Queuing feedback for the selected session…" :
259
+ !connected ? connectionError ? "Connection unavailable · open session options." : destination ? "Disconnected · your notes stay saved." : "Choose where to send your feedback." :
260
+ allSent ? "Feedback delivered · continue in OpenCode" : wrongDestination ? "This batch belongs to the previous session." : retry ? "Retry the previous batch. New feedback stays local." : validDraft() ? "Includes your current feedback." : count ? "Only pending notes will be sent." : "Feedback stays local until you send.")
261
+ }
262
+ function render() {
263
+ renderComposer(); renderNotes()
264
+ $("undo-notice").hidden = !undoRecord || undoRecord.url !== state?.page.url
49
265
  controls()
50
266
  }
267
+ function scheduleRefresh() { clearTimeout(scheduledRefresh); scheduledRefresh = setTimeout(() => refresh(), 30) }
51
268
  async function refresh() {
52
- const requestID = ++refreshID
269
+ const request = ++refreshID
53
270
  try {
54
271
  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.")
272
+ if (request !== refreshID) return
273
+ if (state?.page.url !== next.page.url) { pendingAction = null; selectedNoteID = null; notice = null }
274
+ state = next; model = modelFor(next)
275
+ $("page-title").textContent = next.page.title; $("page-title").title = next.page.title
276
+ const url = new URL(next.page.url)
277
+ $("page-url").textContent = url.protocol === "file:" ? decodeURIComponent(url.pathname.split("/").pop()) : `${url.host}${url.pathname === "/" ? "" : url.pathname}`
278
+ $("page-url").title = next.page.url
279
+ $("page-error").hidden = !next.error; $("page-error").textContent = next.error || ""
280
+ $("pick-label").textContent = next.picking ? "Cancel pick (Esc)" : "Pick element"
281
+ $("pick").setAttribute("aria-pressed", String(!!next.picking)); $("pick-hint").hidden = !!next.picking
282
+ if (next.captureID && next.captureID !== model.captureID) {
283
+ model.captureID = next.captureID
284
+ if (next.anchor && next.draft.consumedCaptures?.[next.tabID] !== next.captureID) {
285
+ notice = null
286
+ if (anchorIdentity(next.anchor) !== anchorIdentity(model.value?.anchor)) await requestAction({ type: "select", anchor: next.anchor,
287
+ capture: { id: next.captureID, tabID: next.tabID } })
288
+ else model.value.captures = { ...model.value.captures, [next.tabID]: next.captureID }
289
+ } else if (next.error) status(next.error, true)
64
290
  }
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()
71
- 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()
291
+ render()
292
+ } catch (error) {
293
+ if (request !== refreshID) return
294
+ state = null; $("page-error").hidden = false; $("page-error").textContent = error.message
295
+ controls(); status(error.message, true)
296
+ }
297
+ }
298
+ function showSessionOptions(show = true, focus = true) {
299
+ $("session-options").hidden = !show; $("change-target").setAttribute("aria-expanded", String(show))
300
+ if (show && focus) { notice = null; $("panel-body").scrollTop = 0; focusWhenReady("#targets", false) }
92
301
  }
93
302
  async function refreshConnection() {
94
303
  if (connectionBusy) return
95
304
  connectionBusy = true
96
305
  const revision = connectionRevision
97
306
  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."
307
+ const result = await call({ action: "connection" })
308
+ if (revision !== connectionRevision) return
309
+ if (available?.id !== result.target?.id || destination?.id !== result.destination?.id) notice = null
310
+ targets = result.targets; available = result.target; destination = result.destination; connectionError = result.error || ""
311
+ const optionsKey = JSON.stringify([targets.map(target => [target.id, target.title, target.directory]), destination?.id, !!available])
312
+ if (optionsKey !== connectionOptionsKey) {
313
+ connectionOptionsKey = optionsKey
314
+ $("targets").replaceChildren(make("option", "Choose a session…")); $("targets").firstChild.value = ""
315
+ if (destination && !targets.some(target => target.id === destination.id)) {
316
+ const option = make("option", `${destination.title} — disconnected`); option.value = destination.id; option.disabled = true; $("targets").append(option)
317
+ }
318
+ for (const target of targets) { const option = make("option", `${target.title} — ${target.directory}`); option.value = target.id; $("targets").append(option) }
319
+ $("targets").value = destination?.id || ""
320
+ }
321
+ $("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."
322
+ if (!destination && targets.length > 1) showSessionOptions(true, false)
107
323
  } catch (error) {
108
- if (revision === connectionRevision) { paired = null; showConnection(); $("connection-hint").textContent = `Session unavailable: ${error.message}` }
109
- } finally { connectionBusy = false; controls() }
324
+ available = null; connectionError = error.message; $("connection-hint").textContent = `Session unavailable: ${error.message}`
325
+ } finally { connectionBusy = false; connectionLoading = false; controls() }
110
326
  }
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()
327
+ function review() { return validateReview({ version: 1, page: state.page, annotations: state.notes }) }
328
+
329
+ $("comment").addEventListener("input", () => {
330
+ model.value.comment = $("comment").value; notice = null
331
+ persistDraft(model).catch(() => {}); controls()
332
+ })
333
+ $("comment").addEventListener("keydown", event => {
334
+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey) && !$("save").disabled) { event.preventDefault(); $("save").click() }
335
+ })
336
+ for (const button of $("kind").querySelectorAll("button")) {
337
+ button.addEventListener("click", () => { model.value.kind = button.dataset.kind; persistDraft(model).catch(() => {}); renderComposer(); controls(); button.focus() })
338
+ button.addEventListener("keydown", event => {
339
+ if (!["ArrowLeft", "ArrowRight"].includes(event.key)) return
340
+ event.preventDefault(); $(model.value.kind === "comment" ? "kind-ask" : "kind-comment").click()
341
+ })
342
+ }
343
+ $("save-shortcut").textContent = navigator.platform.includes("Mac") ? "⌘↵" : "Ctrl↵"
344
+ task("pick", async () => { notice = null; await call({ action: "pick" }); await refresh() })
345
+ task("save", async () => { await saveCurrent(); focusWhenReady("#pick") })
346
+ task("cancel", async () => { await discardDraft(); focusWhenReady("#pick") })
347
+ task("save-switch", async () => { const action = pendingAction; await saveCurrent(); await performAction(action) })
348
+ task("discard-switch", async () => { const action = pendingAction; await discardDraft(); await performAction(action) })
349
+ task("keep-editing", () => { pendingAction = null; renderComposer(); focusWhenReady("#comment") })
350
+ task("retry-draft", async () => { await persistDraft(model); status("Draft saved locally"); focusWhenReady("#comment") })
351
+ task("reload-draft", async () => {
352
+ const conflict = model.conflict
353
+ if (conflict.code === "draft-conflict") { model.record = conflict.draft; model.value = clone(conflict.draft.value); model.touched = false; model.error = null; model.conflict = null }
354
+ else {
355
+ const note = conflict.note
356
+ model.error = null; model.conflict = null
357
+ if (!note || note.deleted) await discardDraft()
358
+ else openComposer({ anchor: note.anchor, kind: note.kind, comment: note.comment, editing: note })
359
+ }
360
+ pendingAction = null; notice = null; render(); focusWhenReady(model.value ? "#comment" : "#pick")
361
+ })
362
+ task("keep-draft", async () => {
363
+ const conflict = model.conflict
364
+ if (conflict.code === "draft-conflict") model.record = conflict.draft
365
+ else model.value.editing = conflict.note?.deleted ? null : conflict.note
366
+ model.error = null; model.conflict = null
367
+ await persistDraft(model); status("Your draft is saved locally"); focusWhenReady("#comment")
116
368
  })
117
- $("targets").addEventListener("change", async () => {
369
+ task("copy-draft", async () => {
370
+ try { await navigator.clipboard.writeText(model.value.comment); status("Draft copied") }
371
+ catch { $("comment").focus(); $("comment").select(); status("Automatic copy was blocked. Press Cmd/Ctrl+C to copy your draft.", true) }
372
+ })
373
+ task("undo", async () => {
374
+ const { note, url } = undoRecord
375
+ await call({ action: "restore", url, note, baseRevision: note.revision }); undoRecord = null
376
+ await refresh(); status("Note restored"); focusWhenReady(`[data-note-id="${CSS.escape(note.id)}"] .note-target`)
377
+ })
378
+ task("more", () => { const show = $("utilities").hidden; $("utilities").hidden = !show; $("more").setAttribute("aria-expanded", String(show)); if (show) $("panel-body").scrollTop = 0 })
379
+ task("refresh-targets", refreshConnection)
380
+ task("change-target", async () => { showSessionOptions($("session-options").hidden); if (!$("session-options").hidden) await refreshConnection() })
381
+ $("targets").addEventListener("change", () => run("targets", async () => {
118
382
  const target = targets.find(target => target.id === $("targets").value)
119
383
  if (!target) return
120
384
  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) }
125
- })
385
+ destination = (await call({ action: "pair", target })).target; available = destination; connectionError = ""; notice = null
386
+ showSessionOptions(false); renderDelivery(); focusWhenReady("#change-target", false)
387
+ }))
126
388
  task("send", async () => {
127
- const destination = paired
128
- if (!destination) throw new Error("Choose an OpenCode session before sending")
389
+ if (!available) { showSessionOptions(); await refreshConnection(); return }
390
+ if (state.outbox && state.outbox.targetID !== destination.id) { showSessionOptions(); status("Choose the original session to retry this batch, or export your notes.", true); return }
391
+ const target = destination, page = state.page
392
+ if (!state.outbox) {
393
+ if (model.error || model.conflict) throw model.conflict || model.error
394
+ if (validDraft()) await saveCurrent()
395
+ }
129
396
  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.")
397
+ const result = await call({ action: "send", url: page.url, targetID: target.id })
398
+ await refresh(); $("status").title = result.messageID
399
+ status("Feedback queued. Continue in the selected session.", false, page.url)
400
+ focusWhenReady(model.value ? "#comment" : "#pick")
134
401
  })
135
402
  task("copy", async () => {
136
403
  const text = markdown(review())
137
404
  try { await navigator.clipboard.writeText(text); status("Context copied. Paste it into any agent.") }
138
405
  catch {
139
- $("preview").textContent = text; document.querySelector("details").open = true
406
+ $("utilities").hidden = false; $("more").setAttribute("aria-expanded", "true"); $("context-details").open = true
407
+ $("preview").textContent = text
140
408
  const range = document.createRange(); range.selectNodeContents($("preview")); getSelection().removeAllRanges(); getSelection().addRange(range)
409
+ $("preview").scrollIntoView({ block: "nearest" })
141
410
  status("Automatic copy was blocked. The preview is selected; press Cmd/Ctrl+C.", true)
142
411
  }
143
412
  })
144
413
  task("export", () => {
145
414
  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)
415
+ const link = make("a"); link.href = url; link.download = "annotate-feedback.json"; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000)
147
416
  status("Complete review exported")
148
417
  })
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() })
418
+ document.addEventListener("keydown", event => {
419
+ if (event.key !== "Escape") return
420
+ if (state?.picking) $("pick").click()
421
+ pendingAction = null; $("utilities").hidden = true; $("more").setAttribute("aria-expanded", "false"); showSessionOptions(false); renderComposer()
422
+ })
423
+ chrome.storage.onChanged.addListener((changes, area) => {
424
+ if (area === "local" || area === "session") {
425
+ const ownDraftsOnly = Object.entries(changes).every(([key, value]) => key.startsWith("draft:") && value.newValue?.writerID === writerID)
426
+ if (!ownDraftsOnly) scheduleRefresh()
427
+ }
428
+ if (changes.paired) refreshConnection()
429
+ })
430
+ chrome.tabs.onActivated.addListener(scheduleRefresh)
431
+ chrome.tabs.onUpdated.addListener((_id, change) => { if (change.status === "complete") scheduleRefresh() })
152
432
  setInterval(() => { if (document.visibilityState === "visible") refresh() }, 1500)
153
- setInterval(() => { if (!paired && document.visibilityState === "visible") refreshConnection() }, 10000)
433
+ setInterval(() => { if (document.visibilityState === "visible") refreshConnection() }, 10000)
154
434
  window.addEventListener("focus", refreshConnection)
155
435
  await Promise.all([refreshConnection(), refresh()])