@nxxxsooo/opencode-annotate 0.13.1 → 0.15.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 +32 -0
- package/README.md +102 -269
- 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/delivery.mjs +6 -0
- package/package.json +2 -1
- package/reference-command.mjs +140 -19
- package/review.mjs +26 -35
- package/scripts/install-bridge.mjs +27 -6
- package/scripts/migrate-page-context.mjs +3 -3
- package/session-reference.mjs +3 -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 +10 -23
- package/web-review.mjs +94 -30
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/delivery.mjs
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Explicitly sent feedback starts an idle session or reaches a running turn's next
|
|
2
|
+
// processing boundary. Queueing based on cached status can leave it waiting for a
|
|
3
|
+
// later turn. Tests may suppress execution while exercising the real API.
|
|
4
|
+
export function feedbackInput(input) {
|
|
5
|
+
return { ...input, delivery: "steer", resume: input.resume ?? true }
|
|
6
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nxxxsooo/opencode-annotate",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.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",
|
|
@@ -39,6 +39,7 @@
|
|
|
39
39
|
"server-history.mjs",
|
|
40
40
|
"session-reference.mjs",
|
|
41
41
|
"reference-command.mjs",
|
|
42
|
+
"delivery.mjs",
|
|
42
43
|
"reference-comment.tsx",
|
|
43
44
|
"review.mjs",
|
|
44
45
|
"auto-review.mjs",
|
package/reference-command.mjs
CHANGED
|
@@ -1,7 +1,46 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto"
|
|
2
2
|
import { readSession, referenceMarkdown, searchSessions } from "./session-reference.mjs"
|
|
3
|
+
import { feedbackInput } from "./delivery.mjs"
|
|
4
|
+
import { homeSession } from "./web-review.mjs"
|
|
3
5
|
|
|
4
|
-
|
|
6
|
+
const DIRECTORY_CAP = 28
|
|
7
|
+
const TOGGLE_SCOPE = Symbol("toggle-scope")
|
|
8
|
+
const wide = /[\u1100-\u115F\u2E80-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE6F\uFF00-\uFF60\uFFE0-\uFFE6\u{1F300}-\u{1FAFF}\u{20000}-\u{3FFFD}]/u
|
|
9
|
+
const zeroWidth = /[\p{Mark}\u200D\uFE0F]/u
|
|
10
|
+
const characterWidth = character => zeroWidth.test(character) ? 0 : wide.test(character) ? 2 : 1
|
|
11
|
+
const textWidth = text => Array.from(text).reduce((width, character) => width + characterWidth(character), 0)
|
|
12
|
+
|
|
13
|
+
function truncateLeft(text, width) {
|
|
14
|
+
if (textWidth(text) <= width) return text
|
|
15
|
+
let result = "", used = 0
|
|
16
|
+
for (const character of Array.from(text).reverse()) {
|
|
17
|
+
const next = characterWidth(character)
|
|
18
|
+
if (used + next > width - 1) break
|
|
19
|
+
result = character + result
|
|
20
|
+
used += next
|
|
21
|
+
}
|
|
22
|
+
return `…${result}`
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The native footer owns a right-aligned directory column, leaving the title
|
|
26
|
+
// all remaining cells instead of reserving a fixed percentage in plugin code.
|
|
27
|
+
|
|
28
|
+
function directoryTail(directory, depth = 3) {
|
|
29
|
+
const separator = directory.includes("\\") && !directory.includes("/") ? "\\" : "/"
|
|
30
|
+
const parts = directory.split(/[\\/]/).filter(Boolean)
|
|
31
|
+
if (parts.length <= depth && textWidth(directory) <= DIRECTORY_CAP) return directory
|
|
32
|
+
const kept = parts.slice(-depth)
|
|
33
|
+
while (kept.length > 1 && textWidth(kept.join(separator)) > DIRECTORY_CAP) {
|
|
34
|
+
let widest = 0
|
|
35
|
+
for (let index = 1; index < kept.length - 1; index++) {
|
|
36
|
+
if (textWidth(kept[index]) > textWidth(kept[widest])) widest = index
|
|
37
|
+
}
|
|
38
|
+
kept.splice(widest, 1)
|
|
39
|
+
}
|
|
40
|
+
return truncateLeft(kept.join(separator), DIRECTORY_CAP)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function createReferenceCommand(context, { review, promptComment }) {
|
|
5
44
|
let active
|
|
6
45
|
let disposed = false
|
|
7
46
|
const notice = (message, variant = "info") => context.ui.toast.show({
|
|
@@ -16,15 +55,35 @@ export function createReferenceCommand(context, { promptComment }) {
|
|
|
16
55
|
signal.throwIfAborted()
|
|
17
56
|
const options = page.sessions.map(session => ({
|
|
18
57
|
title: session.title, value: session.sessionID,
|
|
19
|
-
|
|
58
|
+
footer: directoryTail(session.directory),
|
|
20
59
|
}))
|
|
21
60
|
if (page.nextCursor) options.push({ title: "More conversations…", value: "more", description: "Load the next page" })
|
|
22
61
|
if (!options.length) {
|
|
23
62
|
notice(allProjects ? "No matching conversations." : "No matching conversations in this project. Use /ref --all to search across projects.")
|
|
24
63
|
return
|
|
25
64
|
}
|
|
26
|
-
|
|
65
|
+
let toggle = false
|
|
66
|
+
let annotate
|
|
67
|
+
const selection = context.ui.dialog.select({
|
|
68
|
+
title: `Reference a conversation · ${allProjects ? "All projects" : "This project"}`,
|
|
69
|
+
options,
|
|
70
|
+
actions: [{
|
|
71
|
+
bind: "ctrl+a", title: allProjects ? "This project" : "All projects", selection: "none",
|
|
72
|
+
onTrigger: () => { toggle = true; context.ui.dialog.clear() },
|
|
73
|
+
}, ...(review ? [{
|
|
74
|
+
bind: "ctrl+t", title: "Annotate in TUI",
|
|
75
|
+
onTrigger: value => {
|
|
76
|
+
if (value === "more") return
|
|
77
|
+
annotate = value
|
|
78
|
+
context.ui.dialog.clear()
|
|
79
|
+
},
|
|
80
|
+
}] : [])],
|
|
81
|
+
})
|
|
82
|
+
context.ui.dialog.set({ size: "xlarge" })
|
|
83
|
+
const chosen = await selection
|
|
27
84
|
signal.throwIfAborted()
|
|
85
|
+
if (toggle) return TOGGLE_SCOPE
|
|
86
|
+
if (annotate) return { sessionID: annotate, tui: true }
|
|
28
87
|
if (chosen !== "more") return page.sessions.find(session => session.sessionID === chosen)?.sessionID
|
|
29
88
|
cursor = page.nextCursor
|
|
30
89
|
if (seen.has(cursor)) throw new Error("Session search returned a repeated page cursor.")
|
|
@@ -32,24 +91,72 @@ export function createReferenceCommand(context, { promptComment }) {
|
|
|
32
91
|
} while (cursor)
|
|
33
92
|
}
|
|
34
93
|
|
|
94
|
+
const attach = (sessionID, id, text, reference, resume, signal) => context.client.session.prompt(feedbackInput({
|
|
95
|
+
sessionID, id, resume,
|
|
96
|
+
text,
|
|
97
|
+
metadata: { annotateReference: { sessionID: reference.source.sessionID, capturedAt: reference.capturedAt } },
|
|
98
|
+
}), { signal })
|
|
99
|
+
|
|
100
|
+
// Before the first user message there is nothing to continue: references wait as
|
|
101
|
+
// context for that message, so several can be attached first.
|
|
102
|
+
async function destination(route, signal) {
|
|
103
|
+
if (route.type === "home") {
|
|
104
|
+
const initial = homeSession(context)
|
|
105
|
+
const directory = initial.location?.directory
|
|
106
|
+
if (!directory) throw new Error("Can't determine the working directory for a new session.")
|
|
107
|
+
const location = await context.client.location.get({ location: { directory } }, { signal })
|
|
108
|
+
return {
|
|
109
|
+
current: { projectID: location.project.id }, title: "New session", directory, fresh: true,
|
|
110
|
+
async open() {
|
|
111
|
+
const session = await context.client.session.create({ location: initial.location, ...(initial.model ? { model: initial.model } : {}) }, { signal })
|
|
112
|
+
if (context.ui.router.current().type === "home") context.ui.router.navigate({ type: "session", sessionID: session.id })
|
|
113
|
+
return session.id
|
|
114
|
+
},
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const sessionID = route.sessionID
|
|
118
|
+
const [current, spoken] = await Promise.all([
|
|
119
|
+
context.client.session.get({ sessionID }, { signal }),
|
|
120
|
+
context.client.message.list({ sessionID, type: "user", limit: 1, order: "desc" }, { signal, headers: { "accept-encoding": "identity" } }),
|
|
121
|
+
])
|
|
122
|
+
return { current, sessionID, title: current.title ?? sessionID, fresh: !spoken.data.length, open: async () => sessionID }
|
|
123
|
+
}
|
|
124
|
+
|
|
35
125
|
async function run(input = "") {
|
|
36
126
|
if (disposed) return
|
|
37
127
|
if (active) return notice("A reference is already being selected.")
|
|
38
128
|
// Capture before awaiting the search; a tab change must not redirect the attachment.
|
|
39
129
|
const route = context.ui.router.current()
|
|
40
|
-
if (route.type !== "session") return notice("Open a session first.")
|
|
41
|
-
const sessionID = route.sessionID
|
|
130
|
+
if (route.type !== "session" && route.type !== "home") return notice("Open a session first.")
|
|
131
|
+
const sessionID = route.type === "session" ? route.sessionID : undefined
|
|
42
132
|
const controller = new AbortController()
|
|
43
133
|
active = controller
|
|
44
134
|
const { signal } = controller
|
|
45
135
|
try {
|
|
46
136
|
let query = input.trim()
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
137
|
+
let allProjects = false
|
|
138
|
+
let tui = false
|
|
139
|
+
let flags = true
|
|
140
|
+
while (flags) {
|
|
141
|
+
if (/^--all(?:\s|$)/.test(query)) {
|
|
142
|
+
allProjects = true
|
|
143
|
+
query = query.replace(/^--all\s*/, "")
|
|
144
|
+
} else if (/^--tui(?:\s|$)/.test(query)) {
|
|
145
|
+
tui = true
|
|
146
|
+
query = query.replace(/^--tui\s*/, "")
|
|
147
|
+
} else flags = false
|
|
148
|
+
}
|
|
149
|
+
const target = await destination(route, signal)
|
|
150
|
+
const { current, fresh } = target
|
|
151
|
+
let picked
|
|
152
|
+
do {
|
|
153
|
+
picked = /^ses_\S+$/.test(query) ? query : await choose(current, query, allProjects, signal)
|
|
154
|
+
if (picked === TOGGLE_SCOPE) allProjects = !allProjects
|
|
155
|
+
} while (picked === TOGGLE_SCOPE)
|
|
51
156
|
signal.throwIfAborted()
|
|
52
|
-
if (!
|
|
157
|
+
if (!picked) return
|
|
158
|
+
const sourceID = typeof picked === "object" ? picked.sessionID : picked
|
|
159
|
+
tui ||= typeof picked === "object" && picked.tui
|
|
53
160
|
if (sourceID === sessionID) return notice("Choose a different conversation to reference.")
|
|
54
161
|
const reference = await readSession(context.client, { sessionID: sourceID }, signal)
|
|
55
162
|
signal.throwIfAborted()
|
|
@@ -60,21 +167,35 @@ export function createReferenceCommand(context, { promptComment }) {
|
|
|
60
167
|
}, signal)
|
|
61
168
|
signal.throwIfAborted()
|
|
62
169
|
if (comment == null) return
|
|
170
|
+
const outcome = fresh ? "Write your message to start the conversation." : "Continuing the conversation."
|
|
171
|
+
const label = { confirm: fresh ? "Attach" : "Attach and continue", cancel: "Cancel" }
|
|
172
|
+
const deliver = async (id, text) => attach(await target.open(), id, text, reference, !fresh, signal)
|
|
173
|
+
if (tui) {
|
|
174
|
+
if (!review) throw new Error("TUI annotation is unavailable.")
|
|
175
|
+
return await review.snapshot(sessionID ?? null, {
|
|
176
|
+
text: referenceMarkdown(reference, { comment }), snapshot: "referenced-conversation.md",
|
|
177
|
+
}, {
|
|
178
|
+
title: target.title,
|
|
179
|
+
text: annotations => referenceMarkdown(reference, { comment, annotations }),
|
|
180
|
+
confirm: ({ count, title }) => ({
|
|
181
|
+
title: "Attach annotated reference?",
|
|
182
|
+
message: `Attach ${count} ${count === 1 ? "annotation" : "annotations"} to "${title}"${fresh ? "? The assistant reads it with your first message." : " and let the assistant continue?"}`,
|
|
183
|
+
label,
|
|
184
|
+
}),
|
|
185
|
+
deliver: ({ id, text }) => deliver(id, text),
|
|
186
|
+
success: count => `Attached ${count} reference ${count === 1 ? "annotation" : "annotations"}. ${outcome}`,
|
|
187
|
+
})
|
|
188
|
+
}
|
|
63
189
|
const shortened = reference.nextCursor || reference.messages.some(message => message.nextOffset !== null)
|
|
64
190
|
const confirmed = await context.ui.dialog.confirm({
|
|
65
191
|
title: "Attach conversation reference?",
|
|
66
|
-
message: `From: ${reference.source.title}\n${reference.source.directory}\nTo: ${
|
|
67
|
-
label
|
|
192
|
+
message: `From: ${reference.source.title}\n${reference.source.directory}\nTo: ${target.title}${target.directory ? `\n${target.directory}` : ""}\n${reference.messages.length} text messages${shortened ? " (excerpt; more history available)" : ""}. ${fresh ? "Attach this reference? The assistant reads it with your first message." : "Attach this reference and let the assistant continue?"}`,
|
|
193
|
+
label,
|
|
68
194
|
})
|
|
69
195
|
signal.throwIfAborted()
|
|
70
196
|
if (confirmed !== true) return
|
|
71
|
-
await
|
|
72
|
-
|
|
73
|
-
text: referenceMarkdown(reference, { comment }), description: `Reference: ${reference.source.title}`,
|
|
74
|
-
metadata: { annotateReference: { sessionID: sourceID, capturedAt: reference.capturedAt } },
|
|
75
|
-
delivery: "queue", resume: false,
|
|
76
|
-
}, { signal })
|
|
77
|
-
if (!disposed) notice(`Attached “${reference.source.title}” to “${current.title ?? sessionID}” for the next prompt.`, "success")
|
|
197
|
+
await deliver(`msg_${randomUUID().replaceAll("-", "")}`, referenceMarkdown(reference, { comment }))
|
|
198
|
+
if (!disposed) notice(`Attached “${reference.source.title}” to “${target.title}”. ${outcome}`, "success")
|
|
78
199
|
} catch (error) {
|
|
79
200
|
if (!disposed) notice(error instanceof Error ? error.message : String(error), "error")
|
|
80
201
|
} finally {
|