@nxxxsooo/opencode-annotate 0.14.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/README.md +34 -82
- package/agy/receiver.test.mjs +2 -2
- package/agy/skills/annotate/SKILL.md +3 -3
- package/bridge/native-host.mjs +5 -2
- package/bridge/receiver.mjs +38 -12
- package/browser/UPSTREAM.md +3 -1
- package/browser/manifest.json +1 -1
- package/browser/panel.css +25 -8
- package/browser/panel.html +9 -5
- package/browser/panel.mjs +206 -86
- package/browser/protocol.mjs +22 -7
- package/browser/worker.mjs +148 -40
- package/package.json +1 -8
- package/review.mjs +28 -42
- package/scripts/install-bridge.mjs +27 -6
- package/scripts/migrate-page-context.mjs +3 -3
- package/server.ts +0 -2
- package/targets.mjs +1 -2
- package/tui/bin/darwin-arm64/annotate-tui +0 -0
- package/tui/bin/darwin-x64/annotate-tui +0 -0
- package/tui/bin/linux-arm64/annotate-tui +0 -0
- package/tui/bin/linux-x64/annotate-tui +0 -0
- package/tui/bin/win32-x64/annotate-tui.exe +0 -0
- package/tui.ts +8 -35
- package/web-review.mjs +88 -30
- package/reference-command.mjs +0 -207
- package/reference-comment.tsx +0 -65
- package/server-history.mjs +0 -58
- package/session-reference.mjs +0 -119
- package/session-tools.mjs +0 -55
package/browser/worker.mjs
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import { HOST, PROTOCOL, pageTitle, safeUrl, validateReview } from "./protocol.mjs"
|
|
1
|
+
import { HOST, PROTOCOL, orderedNotes, pageTitle, safeUrl, validateReview } from "./protocol.mjs"
|
|
2
2
|
import { openPanel, reconnectHint, resolveTargetTab, sameExtensionURL, sessionDelivery } from "./env.mjs"
|
|
3
3
|
|
|
4
4
|
const DELIVERY = sessionDelivery()
|
|
5
5
|
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("")
|
|
6
|
-
let writes = Promise.resolve()
|
|
6
|
+
let writes = Promise.resolve(), connectionGeneration = 0
|
|
7
7
|
const serial = fn => { const next = writes.then(fn); writes = next.catch(() => {}); return next }
|
|
8
8
|
const RECONNECT = reconnectHint()
|
|
9
|
+
// Safari's app extension is sandboxed and cannot reach the local bridge, so the only
|
|
10
|
+
// delivery path there is copying the round out.
|
|
9
11
|
const native = message => {
|
|
10
12
|
if (!DELIVERY) throw new Error("Session delivery is off in Safari. Copy the round instead.")
|
|
11
13
|
return chrome.runtime.sendNativeMessage(HOST, message)
|
|
@@ -18,6 +20,7 @@ async function activate(tab) {
|
|
|
18
20
|
await chrome.storage.session.set({ [`tab:${tab.id}`]: { page: { url: safeUrl(tab.url), title: pageTitle(tab.title || "") }, anchor: null } })
|
|
19
21
|
}
|
|
20
22
|
// A reload or navigation removes the page tools; reinject them while activeTab still grants this tab.
|
|
23
|
+
// The receiver-missing wording differs per engine, so detect it by asking the tab instead.
|
|
21
24
|
async function tabMessage(tabId, message) {
|
|
22
25
|
try { return await chrome.tabs.sendMessage(tabId, message) }
|
|
23
26
|
catch (error) {
|
|
@@ -28,21 +31,32 @@ async function tabMessage(tabId, message) {
|
|
|
28
31
|
return chrome.tabs.sendMessage(tabId, message)
|
|
29
32
|
}
|
|
30
33
|
}
|
|
34
|
+
// Chrome reports a missing content script with a fixed string; Safari does not. Probe
|
|
35
|
+
// the tab with a message only the content script answers.
|
|
31
36
|
async function receiverMissing(tabId) {
|
|
32
37
|
try { await chrome.tabs.sendMessage(tabId, { action: "annotate-ping" }); return false }
|
|
33
38
|
catch { return true }
|
|
34
39
|
}
|
|
40
|
+
async function waitLoaded(tabID) {
|
|
41
|
+
await new Promise((resolve, reject) => {
|
|
42
|
+
const finish = error => { clearTimeout(timer); chrome.tabs.onUpdated.removeListener(updated); error ? reject(error) : resolve() }
|
|
43
|
+
const updated = (id, change) => { if (id === tabID && change.status === "complete") finish() }
|
|
44
|
+
const timer = setTimeout(() => finish(new Error("Page did not finish loading; try again")), 15000)
|
|
45
|
+
chrome.tabs.onUpdated.addListener(updated)
|
|
46
|
+
chrome.tabs.get(tabID).then(tab => { if (tab.status === "complete") finish() }, finish)
|
|
47
|
+
})
|
|
48
|
+
}
|
|
35
49
|
const delivered = note => !note.deleted && note.sentRevision === note.revision
|
|
36
|
-
async function closeRound(
|
|
50
|
+
async function closeRound(annotations, details) {
|
|
37
51
|
const storage = await chrome.storage.local.get(null), sentAt = new Date().toISOString(), updates = {}
|
|
38
52
|
for (const sent of annotations) {
|
|
39
|
-
const key = `note:${
|
|
53
|
+
const key = `note:${await pageKey(sent.page.url)}:${sent.id}`, note = storage[key]
|
|
40
54
|
if (note && !note.deleted && note.revision === sent.revision) updates[key] = { ...note, sentRevision: sent.revision, sentAt, ...details }
|
|
41
55
|
}
|
|
42
56
|
await chrome.storage.local.set(updates)
|
|
43
57
|
const rounds = new Map()
|
|
44
58
|
for (const [key, note] of Object.entries({ ...storage, ...updates })) {
|
|
45
|
-
if (!key.startsWith(
|
|
59
|
+
if (!key.startsWith("note:") || !delivered(note)) continue
|
|
46
60
|
const id = note.sentRound || "legacy"
|
|
47
61
|
if (!rounds.has(id)) rounds.set(id, { at: note.sentAt || "", keys: [] })
|
|
48
62
|
rounds.get(id).keys.push(key)
|
|
@@ -71,17 +85,19 @@ async function current(message) {
|
|
|
71
85
|
if (!state?.page) throw new Error(state?.error || "Click the extension icon on this page to grant access")
|
|
72
86
|
const hash = await pageKey(state.page.url)
|
|
73
87
|
const storage = await chrome.storage.local.get(null)
|
|
74
|
-
const entries = Object.entries(storage).filter(([key]) => key.startsWith(
|
|
88
|
+
const entries = Object.entries(storage).filter(([key]) => key.startsWith("note:")).map(([, value]) => value)
|
|
75
89
|
// Delivered notes leave the working list; the latest rounds stay restorable.
|
|
76
|
-
const notes = entries.filter(note => !note.deleted && !delivered(note))
|
|
90
|
+
const notes = orderedNotes(entries.filter(note => !note.deleted && !delivered(note)))
|
|
77
91
|
const draft = storage[`draft:${hash}`] || { revision: 0, value: null }
|
|
78
|
-
const outbox = storage
|
|
79
|
-
|
|
92
|
+
const outbox = storage.outbox
|
|
93
|
+
const localNotes = notes.filter(note => note.page.url === state.page.url)
|
|
94
|
+
let anchorStates = notes.map(note => note.page.url === state.page.url ? "unavailable" : "elsewhere"), draftAnchorState = draft.value ? "unavailable" : undefined, detached = null
|
|
80
95
|
try {
|
|
81
|
-
const anchors =
|
|
96
|
+
const anchors = localNotes.map(note => note.anchor).concat(draft.value ? [draft.value.anchor] : [])
|
|
82
97
|
const { states } = await tabMessage(tab.id, { action: "locate", anchors })
|
|
83
|
-
|
|
84
|
-
|
|
98
|
+
let index = 0
|
|
99
|
+
anchorStates = notes.map(note => note.page.url === state.page.url ? states[index++] : "elsewhere")
|
|
100
|
+
if (draft.value) draftAnchorState = states[localNotes.length]
|
|
85
101
|
} catch (error) { if (error.message === RECONNECT) detached = RECONNECT /* otherwise visibly unavailable while navigating */ }
|
|
86
102
|
return { protocol: PROTOCOL, tabID: tab.id, ...state, notes, anchorStates, hash, draft, draftAnchorState, detached, lastRound: lastRound(entries),
|
|
87
103
|
outbox: outbox ? { targetID: outbox.targetID, count: outbox.review.annotations.length } : null }
|
|
@@ -92,9 +108,9 @@ function draftConflict(draft) {
|
|
|
92
108
|
function validateDraft(page, draft) {
|
|
93
109
|
if (draft === null) return
|
|
94
110
|
if (!draft || typeof draft.comment !== "string" || draft.comment.length > 8000 || !["comment", "ask"].includes(draft.kind)) throw new Error("Invalid draft")
|
|
95
|
-
validateReview({ version:
|
|
111
|
+
validateReview({ version: 2, annotations: [{ page, id: "draft", revision: 1, createdAt: new Date().toISOString(),
|
|
96
112
|
kind: draft.kind, comment: draft.comment.trim() || "Draft", anchor: draft.anchor }] })
|
|
97
|
-
if (draft.editing) validateReview({ version:
|
|
113
|
+
if (draft.editing) validateReview({ version: 2, annotations: [draft.editing] })
|
|
98
114
|
consumedCaptures({}, draft.captures)
|
|
99
115
|
}
|
|
100
116
|
function consumedCaptures(previous, captures) {
|
|
@@ -107,6 +123,44 @@ function consumedCaptures(previous, captures) {
|
|
|
107
123
|
}
|
|
108
124
|
return result
|
|
109
125
|
}
|
|
126
|
+
const sameSession = (a, b) => a?.sessionID && b?.sessionID && a.sessionID === b.sessionID && (a.provider || "opencode") === (b.provider || "opencode")
|
|
127
|
+
// Called within serial(): receiver IDs may change, but retries belong to a session.
|
|
128
|
+
async function rememberTarget(target, storage = undefined) {
|
|
129
|
+
storage ??= await chrome.storage.local.get(null)
|
|
130
|
+
const paired = storage.paired, updates = { paired: target, disconnected: false }
|
|
131
|
+
if (paired?.id !== target.id && sameSession(paired, target)) {
|
|
132
|
+
updates.retiredTargetIDs = [...new Set([...(storage.retiredTargetIDs || []), paired.id])].slice(-50)
|
|
133
|
+
for (const [key, batch] of Object.entries(storage)) {
|
|
134
|
+
if (key === "outbox" && batch.targetID === paired.id) updates[key] = { ...batch, targetID: target.id }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
await chrome.storage.local.set(updates)
|
|
138
|
+
return target
|
|
139
|
+
}
|
|
140
|
+
async function liveTarget(paired, targets, current) {
|
|
141
|
+
if (!paired) return targets.length === 1 && targets[0].connected !== false ? targets[0] : null
|
|
142
|
+
const { retiredTargetIDs = [] } = await chrome.storage.local.get("retiredTargetIDs")
|
|
143
|
+
const viable = targets.filter(target => target.connected !== false && !retiredTargetIDs.includes(target.id))
|
|
144
|
+
const exact = viable.find(target => target.id === paired.id)
|
|
145
|
+
if (exact) {
|
|
146
|
+
// Backfill the stable identity on older pairings before their receiver restarts.
|
|
147
|
+
if (!paired.sessionID) await chrome.storage.local.set({ paired: exact })
|
|
148
|
+
return exact
|
|
149
|
+
}
|
|
150
|
+
const candidate = viable.find(target => sameSession(paired, target))
|
|
151
|
+
if (!candidate || !current()) return null
|
|
152
|
+
// A discovery response can be stale after a receiver restart; confirm the replacement now.
|
|
153
|
+
const probe = await native({ action: "info", targetID: candidate.id })
|
|
154
|
+
if (!probe.ok || !sameSession(paired, probe.target) || !current()) return null
|
|
155
|
+
const replacement = probe.target
|
|
156
|
+
return serial(async () => {
|
|
157
|
+
const storage = await chrome.storage.local.get(null)
|
|
158
|
+
// Another panel or a newer discovery may have changed the destination in flight.
|
|
159
|
+
if (!current()) return viable.find(target => target.id === storage.paired?.id) || null
|
|
160
|
+
if (storage.paired?.id !== paired.id) return viable.find(target => target.id === storage.paired?.id) || null
|
|
161
|
+
return rememberTarget(replacement, storage)
|
|
162
|
+
})
|
|
163
|
+
}
|
|
110
164
|
async function handle(message, sender) {
|
|
111
165
|
if (message.action === "capture") {
|
|
112
166
|
if (!sender.tab || !sender.url || new URL(message.page.url).origin !== new URL(sender.url).origin) throw new Error("Invalid page source")
|
|
@@ -136,47 +190,99 @@ async function handle(message, sender) {
|
|
|
136
190
|
})
|
|
137
191
|
if (message.action === "targets") return native({ action: "targets" })
|
|
138
192
|
if (message.action === "connection") {
|
|
139
|
-
|
|
140
|
-
const
|
|
193
|
+
const generation = ++connectionGeneration
|
|
194
|
+
const current = () => generation === connectionGeneration
|
|
195
|
+
if (!DELIVERY) return { targets: [], workspaces: [], target: null, destination: null, disconnected: false, stale: false, delivery: false }
|
|
196
|
+
const { paired, disconnected } = await chrome.storage.local.get(["paired", "disconnected"])
|
|
141
197
|
let result
|
|
142
198
|
try {
|
|
143
199
|
result = await native({ action: "targets" })
|
|
144
200
|
if (!result.ok) throw new Error(result.error)
|
|
145
201
|
} catch (error) {
|
|
146
|
-
return { targets: [], target: null, destination: paired || null, stale: !!paired, error: error.message }
|
|
202
|
+
return { targets: [], workspaces: [], target: null, destination: paired || null, disconnected: !!disconnected, stale: !!paired, delivery: true, error: error.message }
|
|
147
203
|
}
|
|
148
|
-
const
|
|
149
|
-
|
|
204
|
+
const targets = result.targets.filter(target => target.kind !== "workspace")
|
|
205
|
+
const workspaces = result.targets.filter(target => target.kind === "workspace" && target.canCreate)
|
|
206
|
+
const target = disconnected ? null : await liveTarget(paired, targets, current)
|
|
207
|
+
return { targets, workspaces, target: target || null, destination: target || paired || null, disconnected: !!disconnected, stale: !!paired && !target, delivery: true }
|
|
150
208
|
}
|
|
151
|
-
if (message.action === "pair") {
|
|
152
|
-
|
|
209
|
+
if (message.action === "pair") return serial(async () => {
|
|
210
|
+
connectionGeneration++
|
|
211
|
+
const result = await native({ action: "connect", targetID: message.target.id })
|
|
153
212
|
if (!result.ok) throw new Error(result.error)
|
|
154
|
-
|
|
155
|
-
}
|
|
213
|
+
return { target: await rememberTarget(result.target) }
|
|
214
|
+
})
|
|
156
215
|
if (message.action === "pairing") return { target: (await chrome.storage.local.get("paired")).paired || null }
|
|
157
|
-
if (message.action === "
|
|
216
|
+
if (message.action === "disconnect") return serial(async () => {
|
|
217
|
+
connectionGeneration++
|
|
218
|
+
const { paired } = await chrome.storage.local.get("paired")
|
|
219
|
+
if (paired && paired.id !== message.targetID) throw new Error("The destination changed in another panel; choose it again")
|
|
220
|
+
const result = await native({ action: "disconnect", targetID: message.targetID })
|
|
221
|
+
if (!result.ok) throw new Error(result.error)
|
|
222
|
+
await chrome.storage.local.set({ paired: result.target, disconnected: true })
|
|
223
|
+
return { target: result.target }
|
|
224
|
+
})
|
|
225
|
+
if (message.action === "create-session") return serial(async () => {
|
|
226
|
+
connectionGeneration++
|
|
227
|
+
let { pendingCreation } = await chrome.storage.local.get("pendingCreation")
|
|
228
|
+
if (!pendingCreation || pendingCreation.targetID !== message.targetID) {
|
|
229
|
+
pendingCreation = { action: "create-session", targetID: message.targetID, requestID: crypto.randomUUID() }
|
|
230
|
+
await chrome.storage.local.set({ pendingCreation })
|
|
231
|
+
}
|
|
232
|
+
const result = await native(pendingCreation)
|
|
233
|
+
if (!result.ok) throw new Error(result.error)
|
|
234
|
+
await rememberTarget(result.target)
|
|
235
|
+
await chrome.storage.local.remove("pendingCreation")
|
|
236
|
+
return { target: result.target }
|
|
237
|
+
})
|
|
158
238
|
const state = await current(message)
|
|
159
|
-
if (message.url && message.url !== state.page.url) throw new Error("The active page changed; retry on the original page")
|
|
239
|
+
if (["save", "pick"].includes(message.action) && message.url && message.url !== state.page.url) throw new Error("The active page changed; retry on the original page")
|
|
160
240
|
if (message.action === "pick") return tabMessage(state.tabID, { action: "pick" })
|
|
161
241
|
if (message.action === "reveal") {
|
|
162
242
|
const note = state.notes.find(note => note.id === message.noteID)
|
|
163
243
|
if (!note) throw new Error("This note is no longer on the page")
|
|
164
|
-
|
|
244
|
+
let tabID = state.tabID
|
|
245
|
+
if (note.page.url !== state.page.url) {
|
|
246
|
+
const tabs = (await chrome.tabs.query({})).filter(tab => tab.url === note.page.url || tab.pendingUrl === note.page.url)
|
|
247
|
+
const currentTab = await chrome.tabs.get(state.tabID)
|
|
248
|
+
const existing = tabs.find(tab => tab.windowId === currentTab.windowId) || tabs[0]
|
|
249
|
+
if (existing) {
|
|
250
|
+
tabID = existing.id
|
|
251
|
+
await chrome.tabs.update(tabID, { active: true })
|
|
252
|
+
await chrome.windows.update(existing.windowId, { focused: true })
|
|
253
|
+
await waitLoaded(tabID)
|
|
254
|
+
} else {
|
|
255
|
+
await new Promise((resolve, reject) => {
|
|
256
|
+
const done = (id, change) => { if (id === tabID && change.status === "complete") { clearTimeout(timer); chrome.tabs.onUpdated.removeListener(done); resolve() } }
|
|
257
|
+
const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(done); reject(new Error("Page did not finish loading; try again")) }, 15000)
|
|
258
|
+
chrome.tabs.onUpdated.addListener(done)
|
|
259
|
+
chrome.tabs.update(tabID, { url: note.page.url }).catch(error => { clearTimeout(timer); chrome.tabs.onUpdated.removeListener(done); reject(error) })
|
|
260
|
+
})
|
|
261
|
+
}
|
|
262
|
+
try { await activate(await chrome.tabs.get(tabID)) }
|
|
263
|
+
catch { throw new Error(RECONNECT) }
|
|
264
|
+
}
|
|
265
|
+
const result = await tabMessage(tabID, { action: "reveal", anchor: note.anchor })
|
|
165
266
|
if (!result.ok) throw new Error(result.error)
|
|
166
267
|
return result
|
|
167
268
|
}
|
|
168
269
|
if (["save", "delete", "restore"].includes(message.action)) return serial(async () => {
|
|
169
|
-
const
|
|
270
|
+
const page = message.note.page || state.page
|
|
271
|
+
const key = `note:${await pageKey(page.url)}:${message.note.id}`
|
|
170
272
|
const old = (await chrome.storage.local.get(key))[key]
|
|
171
273
|
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 })
|
|
172
274
|
if (message.action !== "save" && !old) throw new Error("This note no longer exists")
|
|
173
275
|
if (message.action === "restore" && !old.deleted) throw new Error("This note has already been restored")
|
|
174
276
|
if (old && delivered(old)) throw new Error("This note was already delivered; restore its round first")
|
|
175
|
-
const note = { ...(message.action === "save" ? message.note : old), page:
|
|
277
|
+
const note = { ...(message.action === "save" ? message.note : old), page: old?.page || page,
|
|
176
278
|
revision: (old?.revision || 0) + 1, deleted: message.action === "delete" }
|
|
177
279
|
if (message.action === "save") note.sentRevision = old?.sentRevision
|
|
178
|
-
validateReview({ version:
|
|
179
|
-
|
|
280
|
+
validateReview({ version: 2, annotations: [note] })
|
|
281
|
+
const round = (await current(message)).notes.filter(item => item.id !== note.id)
|
|
282
|
+
if (!note.deleted) {
|
|
283
|
+
if (round.length >= 200) throw new Error("This round has 200 notes; send or remove some first")
|
|
284
|
+
validateReview({ version: 2, annotations: [...round, note] })
|
|
285
|
+
}
|
|
180
286
|
const updates = { [key]: note }
|
|
181
287
|
let draft
|
|
182
288
|
if (message.draftRevision !== undefined) {
|
|
@@ -189,31 +295,33 @@ async function handle(message, sender) {
|
|
|
189
295
|
}
|
|
190
296
|
await chrome.storage.local.set(updates); return { note, draft }
|
|
191
297
|
})
|
|
192
|
-
if (message.action === "markers") return tabMessage(state.tabID, { action: "markers", notes: state.notes.map(note => ({ anchor: note.anchor })) })
|
|
298
|
+
if (message.action === "markers") return tabMessage(state.tabID, { action: "markers", notes: state.notes.map(note => ({ anchor: note.page.url === state.page.url ? note.anchor : null })) })
|
|
193
299
|
if (message.action === "copied") return serial(async () => {
|
|
194
300
|
if (!Array.isArray(message.notes) || !message.notes.length) throw new Error("No copied feedback to record")
|
|
195
|
-
const count = await closeRound(
|
|
301
|
+
const count = await closeRound(message.notes, { sentRound: crypto.randomUUID(), sentVia: "clipboard", sentTo: null })
|
|
196
302
|
// Copied feedback supersedes a batch that could not reach its session.
|
|
197
|
-
await chrome.storage.local.remove(
|
|
303
|
+
await chrome.storage.local.remove("outbox")
|
|
198
304
|
return { count }
|
|
199
305
|
})
|
|
200
306
|
if (message.action === "restore-round") return serial(async () => {
|
|
201
307
|
const storage = await chrome.storage.local.get(null), updates = {}
|
|
308
|
+
const latest = await current(message)
|
|
202
309
|
for (const [key, note] of Object.entries(storage)) {
|
|
203
|
-
if (!key.startsWith(
|
|
310
|
+
if (!key.startsWith("note:") || !delivered(note) || note.sentRound !== message.roundID) continue
|
|
204
311
|
const { sentRevision, sentRound, sentAt, sentVia, sentTo, ...rest } = note
|
|
205
312
|
updates[key] = { ...rest, revision: note.revision + 1 }
|
|
206
313
|
}
|
|
207
314
|
if (!Object.keys(updates).length) throw new Error("This round is no longer available")
|
|
208
|
-
if (
|
|
315
|
+
if (latest.notes.length + Object.keys(updates).length > 200) throw new Error("This round would exceed 200 notes; send or remove some first")
|
|
316
|
+
validateReview({ version: 2, annotations: [...latest.notes, ...Object.values(updates)] })
|
|
209
317
|
await chrome.storage.local.set(updates)
|
|
210
318
|
return { count: Object.keys(updates).length }
|
|
211
319
|
})
|
|
212
320
|
if (message.action === "send") return serial(async () => {
|
|
213
321
|
const latest = await current(message)
|
|
214
|
-
if (latest.page.url !== state.page.url) throw new Error("The active page changed; return to the original page to send")
|
|
215
322
|
if (typeof message.targetID !== "string" || !message.targetID) throw new Error("Choose a destination session before sending")
|
|
216
|
-
let { paired } = await chrome.storage.local.get("paired")
|
|
323
|
+
let { paired, disconnected } = await chrome.storage.local.get(["paired", "disconnected"])
|
|
324
|
+
if (disconnected) throw new Error("Session disconnected; select it in Annotate to reconnect")
|
|
217
325
|
if (paired && paired.id !== message.targetID) throw new Error("The destination changed in another panel; choose it again")
|
|
218
326
|
if (!paired) {
|
|
219
327
|
// A sole target is only preselected. The user's Send click authorizes this binding.
|
|
@@ -222,19 +330,19 @@ async function handle(message, sender) {
|
|
|
222
330
|
paired = result.target
|
|
223
331
|
await chrome.storage.local.set({ paired })
|
|
224
332
|
}
|
|
225
|
-
const outboxKey =
|
|
333
|
+
const outboxKey = "outbox"
|
|
226
334
|
let batch = (await chrome.storage.local.get(outboxKey))[outboxKey]
|
|
227
335
|
if (batch && batch.targetID !== paired.id) throw new Error("An unsent batch belongs to the previous pairing; restore that pairing or export your notes")
|
|
228
336
|
if (!batch) {
|
|
229
337
|
const pending = latest.notes.filter(note => note.sentRevision !== note.revision)
|
|
230
338
|
if (!pending.length) throw new Error("No new feedback to send")
|
|
231
|
-
const review = validateReview({ version:
|
|
339
|
+
const review = validateReview({ version: 2, annotations: pending })
|
|
232
340
|
batch = { action: "send", batchID: crypto.randomUUID(), targetID: paired.id, review }
|
|
233
341
|
await chrome.storage.local.set({ [outboxKey]: batch })
|
|
234
342
|
}
|
|
235
343
|
const response = await native(batch)
|
|
236
344
|
if (!response.ok) throw new Error(response.error)
|
|
237
|
-
const count = await closeRound(
|
|
345
|
+
const count = await closeRound(batch.review.annotations, { sentRound: batch.batchID, sentVia: "session", sentTo: paired.title })
|
|
238
346
|
await chrome.storage.local.remove(outboxKey)
|
|
239
347
|
return { ...response, count }
|
|
240
348
|
})
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nxxxsooo/opencode-annotate",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0",
|
|
4
4
|
"description": "Unofficial OpenCode annotation plugin: review AI replies and Markdown with a bundled terminal reviewer; annotate webpages with the browser companion.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -22,7 +22,6 @@
|
|
|
22
22
|
"install:bridge": "node scripts/install-bridge.mjs",
|
|
23
23
|
"install:plugin": "node scripts/install-plugin.mjs",
|
|
24
24
|
"test:smoke": "python3 smoke.py",
|
|
25
|
-
"test:references": "python3 tests/references-smoke.py",
|
|
26
25
|
"check": "node scripts/verify-tui.mjs && node --check review.mjs && npm test && npm pack --dry-run",
|
|
27
26
|
"prepack": "node scripts/verify-tui.mjs",
|
|
28
27
|
"prepublishOnly": "node scripts/verify-tui.mjs --all && npm run check"
|
|
@@ -35,12 +34,7 @@
|
|
|
35
34
|
"tui/LICENSE",
|
|
36
35
|
"tui/README.md",
|
|
37
36
|
"server.ts",
|
|
38
|
-
"session-tools.mjs",
|
|
39
|
-
"server-history.mjs",
|
|
40
|
-
"session-reference.mjs",
|
|
41
|
-
"reference-command.mjs",
|
|
42
37
|
"delivery.mjs",
|
|
43
|
-
"reference-comment.tsx",
|
|
44
38
|
"review.mjs",
|
|
45
39
|
"auto-review.mjs",
|
|
46
40
|
"configuration.mjs",
|
|
@@ -108,7 +102,6 @@
|
|
|
108
102
|
"browser-extension",
|
|
109
103
|
"chrome-extension",
|
|
110
104
|
"feedback",
|
|
111
|
-
"conversation-reference",
|
|
112
105
|
"antigravity",
|
|
113
106
|
"plannotator",
|
|
114
107
|
"review"
|
package/review.mjs
CHANGED
|
@@ -5,11 +5,11 @@ import os from "node:os"
|
|
|
5
5
|
import path from "node:path"
|
|
6
6
|
import { promisify } from "node:util"
|
|
7
7
|
import { createWebReview } from "./web-review.mjs"
|
|
8
|
+
import { feedbackInput } from "./delivery.mjs"
|
|
8
9
|
import { wantsBrowser } from "./targets.mjs"
|
|
9
10
|
import { prepareTheme } from "./theme.mjs"
|
|
10
11
|
import { createInputSource } from "./input-source.mjs"
|
|
11
12
|
import { resolveTuiBinary } from "./tui/binary.mjs"
|
|
12
|
-
import { finishedAssistant } from "./session-reference.mjs"
|
|
13
13
|
|
|
14
14
|
const execute = promisify(execFile)
|
|
15
15
|
const documentExtensions = new Set([".md", ".mdx", ".markdown", ".txt"])
|
|
@@ -53,6 +53,13 @@ async function documentSource(input, client, sessionID, signal) {
|
|
|
53
53
|
}
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
+
// Interrupted turns retain the completed text visible in the transcript.
|
|
57
|
+
export function finishedAssistant(message) {
|
|
58
|
+
if (message.type !== "assistant" || message.time.completed === undefined) return false
|
|
59
|
+
if (message.error?.type === "aborted") return true
|
|
60
|
+
return !message.error && message.finish !== "error"
|
|
61
|
+
}
|
|
62
|
+
|
|
56
63
|
export function selectReply(messages) {
|
|
57
64
|
return eligibleReplies(messages)[0]
|
|
58
65
|
}
|
|
@@ -188,15 +195,14 @@ export function createReviewCommand(context, options = {}) {
|
|
|
188
195
|
// run, so keep the last one per session.
|
|
189
196
|
context.renderer.on("selection", remember)
|
|
190
197
|
|
|
191
|
-
async function start(resolve, { automatic, home = false, sessionID: capturedSessionID
|
|
198
|
+
async function start(resolve, { automatic, home = false, sessionID: capturedSessionID } = {}) {
|
|
192
199
|
if (disposed) return
|
|
193
200
|
if (automatic && (active || !automatic())) return
|
|
194
201
|
if (active) return notice("An annotation is already in progress.")
|
|
195
202
|
// Capture before the first await: changing tabs must never redirect a review.
|
|
196
203
|
const route = context.ui.router.current()
|
|
197
204
|
if (capturedSessionID === undefined && route.type !== "session" && !(home && route.type === "home")) return notice("Open a session first.")
|
|
198
|
-
|
|
199
|
-
const sessionID = capturedSessionID === undefined ? (route.type === "session" ? route.sessionID : undefined) : capturedSessionID ?? undefined
|
|
205
|
+
const sessionID = capturedSessionID ?? (route.type === "session" ? route.sessionID : undefined)
|
|
200
206
|
const controller = new AbortController()
|
|
201
207
|
active = controller
|
|
202
208
|
let directory
|
|
@@ -205,7 +211,7 @@ export function createReviewCommand(context, options = {}) {
|
|
|
205
211
|
const source = await resolve({ sessionID, signal: controller.signal })
|
|
206
212
|
if (controller.signal.aborted || !source) return
|
|
207
213
|
if (automatic && !automatic()) return
|
|
208
|
-
const title =
|
|
214
|
+
const title = context.data.session.get(sessionID)?.title ?? sessionID
|
|
209
215
|
|
|
210
216
|
directory = await mkdtemp(path.join(options.tempRoot ?? os.tmpdir(), "opencode-annotate-"))
|
|
211
217
|
keepDraft = true
|
|
@@ -285,17 +291,17 @@ export function createReviewCommand(context, options = {}) {
|
|
|
285
291
|
: source.selection
|
|
286
292
|
? "Here are my annotations on text I selected in this session. Please address the feedback."
|
|
287
293
|
: `Here are my annotations on your ${source.progress ? "progress update" : "reply"} ${source.id}. Please address the feedback.`
|
|
288
|
-
const text =
|
|
294
|
+
const text = `${subject}\n\n${feedback}`
|
|
289
295
|
const feedbackPath = path.join(directory, "feedback.md")
|
|
290
296
|
await writeFile(feedbackPath, text, { mode: 0o600 })
|
|
291
297
|
const count = (feedback.match(/^## Annotation /gm) ?? []).length
|
|
292
|
-
const skills =
|
|
298
|
+
const skills = await whatSkills(context.client, context.options.whatSkill, feedback, sessionID, controller.signal)
|
|
293
299
|
const intent = await readFile(intentPath, "utf8").catch(error => {
|
|
294
300
|
if (error.code === "ENOENT") return ""
|
|
295
301
|
throw error
|
|
296
302
|
})
|
|
297
303
|
// Pressing send in the TUI is the explicit confirmation; quitting asks here.
|
|
298
|
-
const confirmed = intent.trim() === "send" || await context.ui.dialog.confirm(
|
|
304
|
+
const confirmed = intent.trim() === "send" || await context.ui.dialog.confirm({
|
|
299
305
|
title: "Send annotations?",
|
|
300
306
|
message: `${source.filePath ? `Document: ${source.filePath}\n` : ""}Send ${count} ${count === 1 ? "annotation" : "annotations"} to "${title}" and let the assistant continue?`,
|
|
301
307
|
label: { confirm: "Send and continue", cancel: "Cancel" },
|
|
@@ -305,19 +311,9 @@ export function createReviewCommand(context, options = {}) {
|
|
|
305
311
|
keepDraft = archived > 0
|
|
306
312
|
return notice(`Sending cancelled.${retainedArchive}`)
|
|
307
313
|
}
|
|
308
|
-
|
|
309
|
-
else {
|
|
310
|
-
// An idle session starts queued input at once, but OpenCode's prompt can still list it
|
|
311
|
-
// as queued; an empty Enter then tries to steer it and fails with a 409. Steering an
|
|
312
|
-
// idle session is equivalent and never listed as queued. A busy turn keeps the queue.
|
|
313
|
-
const busy = (context.data.session.status?.(sessionID) ?? "running") !== "idle"
|
|
314
|
-
await context.client.session.prompt({
|
|
315
|
-
sessionID, id: promptID, text, delivery: busy ? "queue" : "steer", resume: true,
|
|
316
|
-
...(skills.length ? { skills } : {}),
|
|
317
|
-
})
|
|
318
|
-
}
|
|
314
|
+
await context.client.session.prompt(feedbackInput({ sessionID, id: promptID, text, ...(skills.length ? { skills } : {}) }))
|
|
319
315
|
keepDraft = archived > 0
|
|
320
|
-
const delivered =
|
|
316
|
+
const delivered = `Sent ${count} ${count === 1 ? "annotation" : "annotations"}.`
|
|
321
317
|
notice(`${delivered}${retainedArchive}`, "success")
|
|
322
318
|
} catch (error) {
|
|
323
319
|
if (!disposed) {
|
|
@@ -337,15 +333,17 @@ export function createReviewCommand(context, options = {}) {
|
|
|
337
333
|
}
|
|
338
334
|
}
|
|
339
335
|
|
|
340
|
-
const run = (input = "") =>
|
|
341
|
-
const target = input.trim()
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
336
|
+
const run = (input = "") => {
|
|
337
|
+
const target = input.trim(), browser = wantsBrowser(target)
|
|
338
|
+
return start(async ({ sessionID, signal }) => {
|
|
339
|
+
if (/^\d+$/.test(target)) throw new Error("Numbered replies are retired. Use /annotate-pick to choose earlier text.")
|
|
340
|
+
if (browser) { await web.run(target, sessionID, signal); return }
|
|
341
|
+
if (target) return documentSource(target, context.client, sessionID, signal)
|
|
342
|
+
const reply = await latestReply(context.client, sessionID, signal)
|
|
343
|
+
if (!reply) notice("This session has no completed assistant reply yet.")
|
|
344
|
+
return reply
|
|
345
|
+
}, { home: browser })
|
|
346
|
+
}
|
|
349
347
|
|
|
350
348
|
const auto = (sessionID, messageID, threshold, current = () => true) => start(async ({ signal }) => {
|
|
351
349
|
const message = await context.client.session.message.get({ sessionID, messageID }, { signal, headers: uncompressed })
|
|
@@ -386,20 +384,8 @@ export function createReviewCommand(context, options = {}) {
|
|
|
386
384
|
return texts.find(text => compact(text.text).includes(needle)) ?? { text: selected, selection: true }
|
|
387
385
|
})
|
|
388
386
|
|
|
389
|
-
const webReview = (input = "") => {
|
|
390
|
-
const value = input.trim()
|
|
391
|
-
const target = value === "" ? "web" : value === "off" ? "web off" : value
|
|
392
|
-
return start(async ({ sessionID, signal }) => {
|
|
393
|
-
if (!(await web.run(target, sessionID, signal))) {
|
|
394
|
-
throw new Error("Use a webpage URL, an HTML file, or off.")
|
|
395
|
-
}
|
|
396
|
-
}, { home: target !== "web off" })
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
const snapshot = (sessionID, source, submission) => start(async () => source, { sessionID, submission })
|
|
400
|
-
|
|
401
387
|
return {
|
|
402
|
-
run, auto, pick,
|
|
388
|
+
run, auto, pick, selection: annotateSelection, webReady: web.ready,
|
|
403
389
|
dispose() {
|
|
404
390
|
context.renderer.off("selection", remember)
|
|
405
391
|
disposed = true
|
|
@@ -1,24 +1,45 @@
|
|
|
1
|
-
import { readFile, mkdir, writeFile, chmod, copyFile } from "node:fs/promises"
|
|
1
|
+
import { readFile, mkdir, writeFile, chmod, copyFile, access } from "node:fs/promises"
|
|
2
|
+
import { constants } from "node:fs"
|
|
2
3
|
import { createHash } from "node:crypto"
|
|
3
4
|
import { fileURLToPath } from "node:url"
|
|
4
5
|
import os from "node:os"
|
|
5
6
|
import path from "node:path"
|
|
6
7
|
import { registryRoot } from "../bridge/receiver.mjs"
|
|
7
8
|
const root = fileURLToPath(new URL("../", import.meta.url))
|
|
8
|
-
|
|
9
|
+
const matches = async (file, contents) => {
|
|
10
|
+
try { return await readFile(file, "utf8") === contents } catch (error) { if (error.code === "ENOENT") return false; throw error }
|
|
11
|
+
}
|
|
12
|
+
export async function resolveNode({ execPath = process.execPath, pathEnv = process.env.PATH, platform = process.platform } = {}) {
|
|
13
|
+
if (/^node(?:\.exe)?$/.test(path.basename(execPath))) return execPath
|
|
14
|
+
const executable = platform === "win32" ? "node.exe" : "node"
|
|
15
|
+
const directories = (pathEnv || "").split(path.delimiter).filter(Boolean)
|
|
16
|
+
if (platform === "darwin") directories.push("/opt/homebrew/bin", "/usr/local/bin")
|
|
17
|
+
for (const directory of new Set(directories)) {
|
|
18
|
+
const candidate = path.join(directory, executable)
|
|
19
|
+
try { await access(candidate, constants.X_OK); return candidate } catch { /* try the next installation */ }
|
|
20
|
+
}
|
|
21
|
+
throw new Error("Can't find Node.js 22+ for the browser native host; run npm run install:bridge with Node.js")
|
|
22
|
+
}
|
|
23
|
+
export async function installBridge({ profileDirectory = path.join(os.homedir(), "Library/Application Support/Google/Chrome"), installRoot = path.join(os.homedir(), ".local/share/opencode-annotate/native"), node, targetsDirectory = registryRoot() } = {}) {
|
|
24
|
+
node ??= await resolveNode()
|
|
9
25
|
const manifest = JSON.parse(await readFile(path.join(root, "browser/manifest.json"), "utf8"))
|
|
10
26
|
const extensionID = [...createHash("sha256").update(Buffer.from(manifest.key, "base64")).digest().subarray(0, 16)].flatMap(byte => [String.fromCharCode(97 + (byte >> 4)), String.fromCharCode(97 + (byte & 15))]).join("")
|
|
11
27
|
await mkdir(installRoot, { recursive: true, mode: 0o700 })
|
|
12
28
|
const launcher = path.join(installRoot, "host"), config = path.join(installRoot, "config.json")
|
|
13
29
|
const quote = value => `'${value.replaceAll("'", "'\\''")}'`
|
|
14
|
-
|
|
15
|
-
|
|
30
|
+
const configText = JSON.stringify({ extensionID, targetsDirectory })
|
|
31
|
+
const launcherText = `#!/bin/sh\nexec ${quote(node)} ${quote(path.join(root, "bridge/native-host.mjs"))} ${quote(config)} "$@"\n`
|
|
32
|
+
if (!await matches(config, configText)) await writeFile(config, configText, { mode: 0o600 })
|
|
33
|
+
if (!await matches(launcher, launcherText)) await writeFile(launcher, launcherText, { mode: 0o700 })
|
|
16
34
|
await chmod(launcher, 0o700)
|
|
17
35
|
const directory = path.join(profileDirectory, "NativeMessagingHosts")
|
|
18
36
|
await mkdir(directory, { recursive: true })
|
|
19
37
|
const hostManifest = path.join(directory, "fun.mjshao.annotate.json")
|
|
20
|
-
|
|
21
|
-
await
|
|
38
|
+
const manifestText = JSON.stringify({ name: "fun.mjshao.annotate", description: "Paired OpenCode annotation delivery", path: launcher, type: "stdio", allowed_origins: [`chrome-extension://${extensionID}/`] }, null, 2)
|
|
39
|
+
if (!await matches(hostManifest, manifestText)) {
|
|
40
|
+
try { await copyFile(hostManifest, `${hostManifest}.backup-${Date.now()}`) } catch (error) { if (error.code !== "ENOENT") throw error }
|
|
41
|
+
await writeFile(hostManifest, manifestText, { mode: 0o600 })
|
|
42
|
+
}
|
|
22
43
|
return { extensionID, extensionDirectory: path.join(root, "browser"), hostManifest, launcher }
|
|
23
44
|
}
|
|
24
45
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
import { createHash } from "node:crypto"
|
|
2
2
|
import { readFile, writeFile } from "node:fs/promises"
|
|
3
3
|
import { fileURLToPath } from "node:url"
|
|
4
|
-
import { safeUrl, validateReview } from "../browser/protocol.mjs"
|
|
4
|
+
import { pageTitle, safeUrl, validateReview } from "../browser/protocol.mjs"
|
|
5
5
|
|
|
6
6
|
export function migratePageContext(storage) {
|
|
7
7
|
const result = {}
|
|
8
8
|
for (const [key, page] of Object.entries(storage)) {
|
|
9
9
|
if (!key.startsWith("page:")) continue
|
|
10
10
|
if (!page?.page?.url || !Array.isArray(page.notes)) throw new Error(`Unrecognized old draft: ${key}`)
|
|
11
|
-
const source = { url: safeUrl(page.page.url), title: page.page.title || "Page" }
|
|
11
|
+
const source = { url: safeUrl(page.page.url), title: pageTitle(page.page.title || "Page") }
|
|
12
12
|
const hash = createHash("sha256").update(source.url).digest("hex")
|
|
13
13
|
for (const old of page.notes) {
|
|
14
14
|
const note = { id: old.id, revision: 1, kind: old.kind, comment: old.body,
|
|
15
15
|
createdAt: old.createdAt, updatedAt: old.updatedAt || old.createdAt,
|
|
16
16
|
anchor: { ...old.target, element: old.target.label || old.target.role || old.target.type,
|
|
17
17
|
styles: old.target.styles || "", accessibility: old.target.accessibility || "", fullPath: old.target.selector }, page: source }
|
|
18
|
-
validateReview({ version:
|
|
18
|
+
validateReview({ version: 2, annotations: [note] })
|
|
19
19
|
const destination = `note:${hash}:${note.id}`
|
|
20
20
|
if (result[destination]) throw new Error("Duplicate note during migration")
|
|
21
21
|
result[destination] = note
|
package/server.ts
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import { Plugin } from "@opencode/plugin"
|
|
2
|
-
import { registerSessionTools } from "./session-tools.mjs"
|
|
3
2
|
import { registerConfiguration } from "./configuration.mjs"
|
|
4
3
|
|
|
5
4
|
export default Plugin.define({
|
|
6
5
|
id: "opencode-annotate",
|
|
7
6
|
async setup(context) {
|
|
8
7
|
await registerConfiguration(context)
|
|
9
|
-
await registerSessionTools(context)
|
|
10
8
|
},
|
|
11
9
|
})
|
package/targets.mjs
CHANGED
|
@@ -7,11 +7,10 @@ const unquote = input => {
|
|
|
7
7
|
const value = input.trim()
|
|
8
8
|
return ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) ? value.slice(1, -1) : value
|
|
9
9
|
}
|
|
10
|
-
export const wantsBrowser = input =>
|
|
10
|
+
export const wantsBrowser = input => /\.html?$/i.test(unquote(input)) || /^[a-z][a-z0-9+.-]*:/i.test(unquote(input))
|
|
11
11
|
|
|
12
12
|
export async function browserTarget(input, directory) {
|
|
13
13
|
let value = unquote(input)
|
|
14
|
-
if (value === "web") return { type: "browser" }
|
|
15
14
|
if (/^[a-z][a-z0-9+.-]*:/i.test(value)) {
|
|
16
15
|
const url = new URL(value)
|
|
17
16
|
if (["http:", "https:"].includes(url.protocol)) {
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|