@nxxxsooo/opencode-annotate 0.6.0 → 0.8.1

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.
@@ -1,12 +1,54 @@
1
- import { HOST, safeUrl, validateReview } from "./protocol.mjs"
1
+ import { HOST, PROTOCOL, pageTitle, safeUrl, validateReview } from "./protocol.mjs"
2
2
 
3
3
  const pageKey = async url => [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(url)))].map(v => v.toString(16).padStart(2, "0")).join("")
4
4
  let writes = Promise.resolve()
5
5
  const serial = fn => { const next = writes.then(fn); writes = next.catch(() => {}); return next }
6
+ const RECONNECT = "This page reloaded. Click the Annotate icon (Alt+Shift+A) once to reconnect it; your notes are kept."
7
+ const KEPT_ROUNDS = 10
8
+ const inject = tabId => chrome.scripting.executeScript({ target: { tabId }, files: ["inspector.js", "capture.js"] })
6
9
  async function activate(tab) {
7
10
  if (!tab?.id || !/^(https?|file):/.test(tab.url || "")) throw new Error("Open an ordinary webpage or authorized local HTML")
8
- await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ["inspector.js", "capture.js"] })
9
- await chrome.storage.session.set({ [`tab:${tab.id}`]: { page: { url: safeUrl(tab.url), title: tab.title || "Page" }, anchor: null } })
11
+ await inject(tab.id)
12
+ await chrome.storage.session.set({ [`tab:${tab.id}`]: { page: { url: safeUrl(tab.url), title: pageTitle(tab.title || "") }, anchor: null } })
13
+ }
14
+ // A reload or navigation removes the page tools; reinject them while activeTab still grants this tab.
15
+ async function tabMessage(tabId, message) {
16
+ try { return await chrome.tabs.sendMessage(tabId, message) }
17
+ catch (error) {
18
+ if (!String(error.message).includes("Receiving end does not exist")) throw error
19
+ try { await inject(tabId) } catch (injectError) {
20
+ throw new Error(String(injectError.message).includes("HTML") ? injectError.message : RECONNECT)
21
+ }
22
+ return chrome.tabs.sendMessage(tabId, message)
23
+ }
24
+ }
25
+ const delivered = note => !note.deleted && note.sentRevision === note.revision
26
+ async function closeRound(hash, annotations, details) {
27
+ const storage = await chrome.storage.local.get(null), sentAt = new Date().toISOString(), updates = {}
28
+ for (const sent of annotations) {
29
+ const key = `note:${hash}:${sent.id}`, note = storage[key]
30
+ if (note && !note.deleted && note.revision === sent.revision) updates[key] = { ...note, sentRevision: sent.revision, sentAt, ...details }
31
+ }
32
+ await chrome.storage.local.set(updates)
33
+ const rounds = new Map()
34
+ for (const [key, note] of Object.entries({ ...storage, ...updates })) {
35
+ if (!key.startsWith(`note:${hash}:`) || !delivered(note)) continue
36
+ const id = note.sentRound || "legacy"
37
+ if (!rounds.has(id)) rounds.set(id, { at: note.sentAt || "", keys: [] })
38
+ rounds.get(id).keys.push(key)
39
+ }
40
+ const expired = [...rounds.values()].sort((a, b) => b.at.localeCompare(a.at)).slice(KEPT_ROUNDS).flatMap(round => round.keys)
41
+ if (expired.length) await chrome.storage.local.remove(expired)
42
+ return Object.keys(updates).length
43
+ }
44
+ function lastRound(entries) {
45
+ const rounds = new Map()
46
+ for (const note of entries) {
47
+ if (!delivered(note) || !note.sentRound) continue
48
+ const round = rounds.get(note.sentRound) || { id: note.sentRound, count: 0, at: note.sentAt, via: note.sentVia, to: note.sentTo }
49
+ round.count++; rounds.set(note.sentRound, round)
50
+ }
51
+ return [...rounds.values()].sort((a, b) => b.at.localeCompare(a.at))[0] || null
10
52
  }
11
53
  chrome.action.onClicked.addListener(tab => {
12
54
  // open() must retain the browser's action user gesture, before asynchronous injection.
@@ -20,17 +62,19 @@ async function current() {
20
62
  if (!state?.page) throw new Error(state?.error || "Click the extension icon on this page to grant access")
21
63
  const hash = await pageKey(state.page.url)
22
64
  const storage = await chrome.storage.local.get(null)
23
- const notes = Object.entries(storage).filter(([key, value]) => key.startsWith(`note:${hash}:`) && !value.deleted).map(([, value]) => value).sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id))
24
- let anchorStates = notes.map(() => "unavailable")
25
- try { anchorStates = (await chrome.tabs.sendMessage(tab.id, { action: "locate", anchors: notes.map(note => note.anchor) })).states } catch { /* visibly unavailable while navigating */ }
65
+ const entries = Object.entries(storage).filter(([key]) => key.startsWith(`note:${hash}:`)).map(([, value]) => value)
66
+ // Delivered notes leave the working list; the latest rounds stay restorable.
67
+ const notes = entries.filter(note => !note.deleted && !delivered(note)).sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id))
26
68
  const draft = storage[`draft:${hash}`] || { revision: 0, value: null }
27
69
  const outbox = storage[`outbox:${hash}`]
28
- let draftAnchorState
29
- if (draft.value) {
30
- try { draftAnchorState = (await chrome.tabs.sendMessage(tab.id, { action: "locate", anchors: [draft.value.anchor] })).states[0] }
31
- catch { draftAnchorState = "unavailable" }
32
- }
33
- return { tabID: tab.id, ...state, notes, anchorStates, hash, draft, draftAnchorState,
70
+ let anchorStates = notes.map(() => "unavailable"), draftAnchorState = draft.value ? "unavailable" : undefined, detached = null
71
+ try {
72
+ const anchors = notes.map(note => note.anchor).concat(draft.value ? [draft.value.anchor] : [])
73
+ const { states } = await tabMessage(tab.id, { action: "locate", anchors })
74
+ anchorStates = states.slice(0, notes.length)
75
+ if (draft.value) draftAnchorState = states[notes.length]
76
+ } catch (error) { if (error.message === RECONNECT) detached = RECONNECT /* otherwise visibly unavailable while navigating */ }
77
+ return { protocol: PROTOCOL, tabID: tab.id, ...state, notes, anchorStates, hash, draft, draftAnchorState, detached, lastRound: lastRound(entries),
34
78
  outbox: outbox ? { targetID: outbox.targetID, count: outbox.review.annotations.length } : null }
35
79
  }
36
80
  function draftConflict(draft) {
@@ -59,7 +103,7 @@ async function handle(message, sender) {
59
103
  if (!sender.tab || !sender.url || new URL(message.page.url).origin !== new URL(sender.url).origin) throw new Error("Invalid page source")
60
104
  const key = `tab:${sender.tab.id}`
61
105
  const previous = (await chrome.storage.session.get(key))[key] || {}
62
- await chrome.storage.session.set({ [key]: { ...previous, page: { url: safeUrl(message.page.url), title: String(message.page.title).slice(0, 500) }, picking: !!message.picking,
106
+ await chrome.storage.session.set({ [key]: { ...previous, page: { url: safeUrl(message.page.url), title: pageTitle(message.page.title) }, picking: !!message.picking,
63
107
  ...(!message.modeOnly ? { anchor: message.anchor, error: message.error, captureID: crypto.randomUUID() } : {}) } })
64
108
  return {}
65
109
  }
@@ -103,11 +147,11 @@ async function handle(message, sender) {
103
147
  if (message.action === "unpair") { await chrome.storage.local.remove("paired"); return {} }
104
148
  const state = await current()
105
149
  if (message.url && message.url !== state.page.url) throw new Error("The active page changed; retry on the original page")
106
- if (message.action === "pick") return chrome.tabs.sendMessage(state.tabID, { action: "pick" })
150
+ if (message.action === "pick") return tabMessage(state.tabID, { action: "pick" })
107
151
  if (message.action === "reveal") {
108
152
  const note = state.notes.find(note => note.id === message.noteID)
109
153
  if (!note) throw new Error("This note is no longer on the page")
110
- const result = await chrome.tabs.sendMessage(state.tabID, { action: "reveal", anchor: note.anchor })
154
+ const result = await tabMessage(state.tabID, { action: "reveal", anchor: note.anchor })
111
155
  if (!result.ok) throw new Error(result.error)
112
156
  return result
113
157
  }
@@ -117,16 +161,10 @@ async function handle(message, sender) {
117
161
  if ((old?.revision || 0) !== message.baseRevision) throw Object.assign(new Error("This note changed in another tab. Choose which version to keep."), { code: "note-conflict", note: old || null })
118
162
  if (message.action !== "save" && !old) throw new Error("This note no longer exists")
119
163
  if (message.action === "restore" && !old.deleted) throw new Error("This note has already been restored")
164
+ if (old && delivered(old)) throw new Error("This note was already delivered; restore its round first")
120
165
  const note = { ...(message.action === "save" ? message.note : old), page: state.page,
121
166
  revision: (old?.revision || 0) + 1, deleted: message.action === "delete" }
122
- if (message.action === "delete") note.wasSent = old.sentRevision === old.revision
123
- else if (message.action === "restore") {
124
- if (old.wasSent) note.sentRevision = note.revision
125
- delete note.wasSent
126
- } else {
127
- note.sentRevision = old?.sentRevision
128
- delete note.wasSent
129
- }
167
+ if (message.action === "save") note.sentRevision = old?.sentRevision
130
168
  validateReview({ version: 1, page: state.page, annotations: [note] })
131
169
  if (!old && state.notes.length >= 200) throw new Error("This page has 200 notes; export and remove some first")
132
170
  const updates = { [key]: note }
@@ -141,7 +179,26 @@ async function handle(message, sender) {
141
179
  }
142
180
  await chrome.storage.local.set(updates); return { note, draft }
143
181
  })
144
- if (message.action === "markers") return chrome.tabs.sendMessage(state.tabID, { action: "markers", notes: state.notes.map(note => ({ anchor: note.anchor })) })
182
+ if (message.action === "markers") return tabMessage(state.tabID, { action: "markers", notes: state.notes.map(note => ({ anchor: note.anchor })) })
183
+ if (message.action === "copied") return serial(async () => {
184
+ if (!Array.isArray(message.notes) || !message.notes.length) throw new Error("No copied feedback to record")
185
+ const count = await closeRound(state.hash, message.notes, { sentRound: crypto.randomUUID(), sentVia: "clipboard", sentTo: null })
186
+ // Copied feedback supersedes a batch that could not reach its session.
187
+ await chrome.storage.local.remove(`outbox:${state.hash}`)
188
+ return { count }
189
+ })
190
+ if (message.action === "restore-round") return serial(async () => {
191
+ const storage = await chrome.storage.local.get(null), updates = {}
192
+ for (const [key, note] of Object.entries(storage)) {
193
+ if (!key.startsWith(`note:${state.hash}:`) || !delivered(note) || note.sentRound !== message.roundID) continue
194
+ const { sentRevision, sentRound, sentAt, sentVia, sentTo, ...rest } = note
195
+ updates[key] = { ...rest, revision: note.revision + 1 }
196
+ }
197
+ if (!Object.keys(updates).length) throw new Error("This round is no longer available")
198
+ if (state.notes.length + Object.keys(updates).length > 200) throw new Error("This page would exceed 200 notes; send or remove some first")
199
+ await chrome.storage.local.set(updates)
200
+ return { count: Object.keys(updates).length }
201
+ })
145
202
  if (message.action === "send") return serial(async () => {
146
203
  const latest = await current()
147
204
  if (latest.page.url !== state.page.url) throw new Error("The active page changed; return to the original page to send")
@@ -167,13 +224,9 @@ async function handle(message, sender) {
167
224
  }
168
225
  const response = await chrome.runtime.sendNativeMessage(HOST, batch)
169
226
  if (!response.ok) throw new Error(response.error)
170
- for (const sent of batch.review.annotations) {
171
- const key = `note:${state.hash}:${sent.id}`
172
- const note = (await chrome.storage.local.get(key))[key]
173
- if (note && note.revision === sent.revision) await chrome.storage.local.set({ [key]: { ...note, sentRevision: sent.revision } })
174
- }
227
+ const count = await closeRound(state.hash, batch.review.annotations, { sentRound: batch.batchID, sentVia: "session", sentTo: paired.title })
175
228
  await chrome.storage.local.remove(outboxKey)
176
- return response
229
+ return { ...response, count }
177
230
  })
178
231
  throw new Error("Unknown annotation action")
179
232
  }
package/package.json CHANGED
@@ -1,14 +1,17 @@
1
1
  {
2
2
  "name": "@nxxxsooo/opencode-annotate",
3
- "version": "0.6.0",
3
+ "version": "0.8.1",
4
4
  "description": "Unofficial OpenCode plugin: annotate replies, documents and webpages, then send the feedback to the originating session.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "exports": {
8
8
  "./tui": "./tui.ts"
9
9
  },
10
+ "bin": {
11
+ "agy-annotate": "./agy/cli.mjs"
12
+ },
10
13
  "scripts": {
11
- "test": "node --test *.test.mjs bridge/*.test.mjs",
14
+ "test": "node --test *.test.mjs bridge/*.test.mjs agy/*.test.mjs",
12
15
  "test:browser": "node tests/browser.mjs",
13
16
  "install:bridge": "node scripts/install-bridge.mjs",
14
17
  "install:plugin": "node scripts/install-plugin.mjs",
@@ -26,6 +29,7 @@
26
29
  "bridge/native-host.mjs",
27
30
  "bridge/receiver.mjs",
28
31
  "bridge/wire.mjs",
32
+ "agy",
29
33
  "scripts/install-bridge.mjs",
30
34
  "scripts/install-plugin.mjs",
31
35
  "scripts/migrate-page-context.mjs",
package/review.mjs CHANGED
@@ -76,6 +76,10 @@ function eligibleReplies(messages) {
76
76
  return textMessages(messages).filter(message => !message.progress).map(({ id, text }) => ({ id, text }))
77
77
  }
78
78
 
79
+ // OpenCode 2.2.0 compresses API responses at roughly 80 KB/s, so a page of long
80
+ // replies took 10–30 s; uncompressed, the same local page arrives in milliseconds.
81
+ const uncompressed = { "accept-encoding": "identity" }
82
+
79
83
  // Walk the session-scoped history newest first; the UI cache holds only a recent page.
80
84
  async function* history(client, sessionID, signal) {
81
85
  const seen = new Set()
@@ -85,7 +89,7 @@ async function* history(client, sessionID, signal) {
85
89
  const page = await client.message.list({
86
90
  sessionID, type: "assistant", limit: 50,
87
91
  ...(cursor ? { cursor } : { order: "desc" }),
88
- }, { signal })
92
+ }, { signal, headers: uncompressed })
89
93
  yield page.data
90
94
  cursor = page.cursor?.next
91
95
  if (cursor && seen.has(cursor)) throw new Error("Session history returned a repeated page cursor.")
@@ -206,6 +210,9 @@ export function createReviewCommand(context, options = {}) {
206
210
  if ((options.inheritTheme ?? context.options.inheritTheme) === true) {
207
211
  env = await prepareTheme({ binary, theme: context.theme, directory, env, signal: controller.signal })
208
212
  }
213
+ // A capable binary writes "send" here when q or Ctrl+S quits with notes; upstream ignores it.
214
+ const intentPath = path.join(directory, "send-intent")
215
+ env.PLANNOTATOR_TUI_SEND_INTENT = intentPath
209
216
  context.ui.dialog.clear()
210
217
  // OpenCode 2.1.1+ suspends and resumes asynchronously; resume forces a full repaint.
211
218
  await context.renderer.suspend()
@@ -237,7 +244,12 @@ export function createReviewCommand(context, options = {}) {
237
244
  const feedbackPath = path.join(directory, "feedback.md")
238
245
  await writeFile(feedbackPath, text, { mode: 0o600 })
239
246
  const count = (feedback.match(/^## Annotation /gm) ?? []).length
240
- const confirmed = await context.ui.dialog.confirm({
247
+ const intent = await readFile(intentPath, "utf8").catch(error => {
248
+ if (error.code === "ENOENT") return ""
249
+ throw error
250
+ })
251
+ // Pressing send in the TUI is the explicit confirmation; quitting asks here.
252
+ const confirmed = intent.trim() === "send" || await context.ui.dialog.confirm({
241
253
  title: "Send annotations?",
242
254
  message: `${source.filePath ? `Document: ${source.filePath}\n` : ""}Send ${count} ${count === 1 ? "annotation" : "annotations"} to "${title}" and let the assistant continue?`,
243
255
  label: { confirm: "Send and continue", cancel: "Cancel" },
package/tui.ts CHANGED
@@ -22,7 +22,7 @@ export default Plugin.define({
22
22
  }, {
23
23
  id: "opencode-annotate.annotate-last",
24
24
  title: "Annotate last reply (TUI)",
25
- description: "Annotate the latest completed reply; press q, then confirm to send",
25
+ description: "Annotate the latest completed reply; q sends (fork), or q then confirm",
26
26
  group: "Annotate",
27
27
  palette: true,
28
28
  // Keep slash submission with a trailing space local to the command.