@nxxxsooo/opencode-annotate 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/README.md +75 -24
- package/browser/capture.js +23 -3
- package/browser/manifest.json +1 -1
- package/browser/panel.css +114 -3
- package/browser/panel.html +50 -17
- package/browser/panel.mjs +385 -105
- package/browser/worker.mjs +88 -10
- package/package.json +3 -2
- package/review.mjs +111 -36
- package/theme.mjs +115 -0
- package/tui.ts +26 -2
package/browser/worker.mjs
CHANGED
|
@@ -23,7 +23,36 @@ async function current() {
|
|
|
23
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
24
|
let anchorStates = notes.map(() => "unavailable")
|
|
25
25
|
try { anchorStates = (await chrome.tabs.sendMessage(tab.id, { action: "locate", anchors: notes.map(note => note.anchor) })).states } catch { /* visibly unavailable while navigating */ }
|
|
26
|
-
|
|
26
|
+
const draft = storage[`draft:${hash}`] || { revision: 0, value: null }
|
|
27
|
+
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,
|
|
34
|
+
outbox: outbox ? { targetID: outbox.targetID, count: outbox.review.annotations.length } : null }
|
|
35
|
+
}
|
|
36
|
+
function draftConflict(draft) {
|
|
37
|
+
return Object.assign(new Error("This draft changed in another panel. Choose which version to keep."), { code: "draft-conflict", draft })
|
|
38
|
+
}
|
|
39
|
+
function validateDraft(page, draft) {
|
|
40
|
+
if (draft === null) return
|
|
41
|
+
if (!draft || typeof draft.comment !== "string" || draft.comment.length > 8000 || !["comment", "ask"].includes(draft.kind)) throw new Error("Invalid draft")
|
|
42
|
+
validateReview({ version: 1, page, annotations: [{ id: "draft", revision: 1, createdAt: new Date().toISOString(),
|
|
43
|
+
kind: draft.kind, comment: draft.comment.trim() || "Draft", anchor: draft.anchor }] })
|
|
44
|
+
if (draft.editing) validateReview({ version: 1, page, annotations: [draft.editing] })
|
|
45
|
+
consumedCaptures({}, draft.captures)
|
|
46
|
+
}
|
|
47
|
+
function consumedCaptures(previous, captures) {
|
|
48
|
+
const result = { ...previous }
|
|
49
|
+
if (!captures) return result
|
|
50
|
+
if (typeof captures !== "object" || Array.isArray(captures)) throw new Error("Invalid capture acknowledgement")
|
|
51
|
+
for (const [tab, id] of Object.entries(captures)) {
|
|
52
|
+
if (!Number.isSafeInteger(Number(tab)) || Number(tab) < 0 || String(Number(tab)) !== tab || typeof id !== "string" || !id) throw new Error("Invalid capture acknowledgement")
|
|
53
|
+
result[tab] = id
|
|
54
|
+
}
|
|
55
|
+
return result
|
|
27
56
|
}
|
|
28
57
|
async function handle(message, sender) {
|
|
29
58
|
if (message.action === "capture") {
|
|
@@ -31,18 +60,39 @@ async function handle(message, sender) {
|
|
|
31
60
|
const key = `tab:${sender.tab.id}`
|
|
32
61
|
const previous = (await chrome.storage.session.get(key))[key] || {}
|
|
33
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,
|
|
34
|
-
...(!message.modeOnly ? { anchor: message.anchor, error: message.error } : {}) } })
|
|
63
|
+
...(!message.modeOnly ? { anchor: message.anchor, error: message.error, captureID: crypto.randomUUID() } : {}) } })
|
|
35
64
|
return {}
|
|
36
65
|
}
|
|
37
66
|
if (sender.url && !sender.url.startsWith(chrome.runtime.getURL(""))) throw new Error("Only the extension panel can manage feedback")
|
|
38
67
|
if (message.action === "current") return current()
|
|
68
|
+
if (message.action === "draft") return serial(async () => {
|
|
69
|
+
// A route change must still be able to persist the previous page's draft.
|
|
70
|
+
if (!message.page || safeUrl(message.page.url) !== message.page.url || typeof message.page.title !== "string" ||
|
|
71
|
+
typeof message.writerID !== "string" || !message.writerID || !Number.isSafeInteger(message.sequence) || message.sequence < 1 ||
|
|
72
|
+
!Number.isSafeInteger(message.baseRevision) || message.baseRevision < 0) throw new Error("Invalid draft update")
|
|
73
|
+
validateDraft(message.page, message.value)
|
|
74
|
+
const key = `draft:${await pageKey(message.page.url)}`
|
|
75
|
+
const old = (await chrome.storage.local.get(key))[key] || { revision: 0, value: null }
|
|
76
|
+
if (old.writerID === message.writerID && old.sequence >= message.sequence) return { draft: old }
|
|
77
|
+
if (old.revision !== message.baseRevision && old.writerID !== message.writerID) throw draftConflict(old)
|
|
78
|
+
const draft = { revision: old.revision + 1, value: message.value, writerID: message.writerID,
|
|
79
|
+
consumedCaptures: consumedCaptures(old.consumedCaptures, message.value === null ? message.captures : null),
|
|
80
|
+
sequence: message.sequence, updatedAt: new Date().toISOString() }
|
|
81
|
+
await chrome.storage.local.set({ [key]: draft })
|
|
82
|
+
return { draft }
|
|
83
|
+
})
|
|
39
84
|
if (message.action === "targets") return chrome.runtime.sendNativeMessage(HOST, { action: "targets" })
|
|
40
85
|
if (message.action === "connection") {
|
|
41
|
-
const result = await chrome.runtime.sendNativeMessage(HOST, { action: "targets" })
|
|
42
|
-
if (!result.ok) throw new Error(result.error)
|
|
43
86
|
const { paired } = await chrome.storage.local.get("paired")
|
|
87
|
+
let result
|
|
88
|
+
try {
|
|
89
|
+
result = await chrome.runtime.sendNativeMessage(HOST, { action: "targets" })
|
|
90
|
+
if (!result.ok) throw new Error(result.error)
|
|
91
|
+
} catch (error) {
|
|
92
|
+
return { targets: [], target: null, destination: paired || null, stale: !!paired, error: error.message }
|
|
93
|
+
}
|
|
44
94
|
const target = paired ? result.targets.find(target => target.id === paired.id) : result.targets.length === 1 ? result.targets[0] : null
|
|
45
|
-
return { targets: result.targets, target: target || null, stale: !!paired && !target }
|
|
95
|
+
return { targets: result.targets, target: target || null, destination: target || paired || null, stale: !!paired && !target }
|
|
46
96
|
}
|
|
47
97
|
if (message.action === "pair") {
|
|
48
98
|
const result = await chrome.runtime.sendNativeMessage(HOST, { action: "info", targetID: message.target.id })
|
|
@@ -54,14 +104,42 @@ async function handle(message, sender) {
|
|
|
54
104
|
const state = await current()
|
|
55
105
|
if (message.url && message.url !== state.page.url) throw new Error("The active page changed; retry on the original page")
|
|
56
106
|
if (message.action === "pick") return chrome.tabs.sendMessage(state.tabID, { action: "pick" })
|
|
57
|
-
if (message.action === "
|
|
107
|
+
if (message.action === "reveal") {
|
|
108
|
+
const note = state.notes.find(note => note.id === message.noteID)
|
|
109
|
+
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 })
|
|
111
|
+
if (!result.ok) throw new Error(result.error)
|
|
112
|
+
return result
|
|
113
|
+
}
|
|
114
|
+
if (["save", "delete", "restore"].includes(message.action)) return serial(async () => {
|
|
58
115
|
const key = `note:${state.hash}:${message.note.id}`
|
|
59
116
|
const old = (await chrome.storage.local.get(key))[key]
|
|
60
|
-
if ((old?.revision || 0) !== message.baseRevision) throw new Error("This note changed in another tab
|
|
61
|
-
|
|
117
|
+
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
|
+
if (message.action !== "save" && !old) throw new Error("This note no longer exists")
|
|
119
|
+
if (message.action === "restore" && !old.deleted) throw new Error("This note has already been restored")
|
|
120
|
+
const note = { ...(message.action === "save" ? message.note : old), page: state.page,
|
|
121
|
+
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
|
+
}
|
|
62
130
|
validateReview({ version: 1, page: state.page, annotations: [note] })
|
|
63
131
|
if (!old && state.notes.length >= 200) throw new Error("This page has 200 notes; export and remove some first")
|
|
64
|
-
|
|
132
|
+
const updates = { [key]: note }
|
|
133
|
+
let draft
|
|
134
|
+
if (message.draftRevision !== undefined) {
|
|
135
|
+
const draftKey = `draft:${state.hash}`
|
|
136
|
+
const previous = (await chrome.storage.local.get(draftKey))[draftKey] || { revision: 0, value: null }
|
|
137
|
+
if (previous.revision !== message.draftRevision) throw draftConflict(previous)
|
|
138
|
+
draft = { ...previous, revision: previous.revision + 1, value: null,
|
|
139
|
+
consumedCaptures: consumedCaptures(previous.consumedCaptures, message.captures), updatedAt: new Date().toISOString() }
|
|
140
|
+
updates[draftKey] = draft
|
|
141
|
+
}
|
|
142
|
+
await chrome.storage.local.set(updates); return { note, draft }
|
|
65
143
|
})
|
|
66
144
|
if (message.action === "markers") return chrome.tabs.sendMessage(state.tabID, { action: "markers", notes: state.notes.map(note => ({ anchor: note.anchor })) })
|
|
67
145
|
if (message.action === "send") return serial(async () => {
|
|
@@ -100,6 +178,6 @@ async function handle(message, sender) {
|
|
|
100
178
|
throw new Error("Unknown annotation action")
|
|
101
179
|
}
|
|
102
180
|
chrome.runtime.onMessage.addListener((message, sender, respond) => {
|
|
103
|
-
handle(message, sender).then(result => respond({ ok: true, ...result }), error => respond({ ok: false, error: error.message }))
|
|
181
|
+
handle(message, sender).then(result => respond({ ok: true, ...result }), error => respond({ ok: false, error: error.message, code: error.code, draft: error.draft, note: error.note }))
|
|
104
182
|
return true
|
|
105
183
|
})
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nxxxsooo/opencode-annotate",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
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",
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"./tui": "./tui.ts"
|
|
9
9
|
},
|
|
10
10
|
"scripts": {
|
|
11
|
-
"test": "node --test
|
|
11
|
+
"test": "node --test *.test.mjs bridge/*.test.mjs",
|
|
12
12
|
"test:browser": "node tests/browser.mjs",
|
|
13
13
|
"install:bridge": "node scripts/install-bridge.mjs",
|
|
14
14
|
"install:plugin": "node scripts/install-plugin.mjs",
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
"files": [
|
|
20
20
|
"tui.ts",
|
|
21
21
|
"review.mjs",
|
|
22
|
+
"theme.mjs",
|
|
22
23
|
"targets.mjs",
|
|
23
24
|
"web-review.mjs",
|
|
24
25
|
"browser",
|
package/review.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import path from "node:path"
|
|
|
6
6
|
import { promisify } from "node:util"
|
|
7
7
|
import { createWebReview } from "./web-review.mjs"
|
|
8
8
|
import { wantsBrowser } from "./targets.mjs"
|
|
9
|
+
import { prepareTheme } from "./theme.mjs"
|
|
9
10
|
|
|
10
11
|
const execute = promisify(execFile)
|
|
11
12
|
const documentExtensions = new Set([".md", ".mdx", ".markdown", ".txt"])
|
|
@@ -53,23 +54,31 @@ export function selectReply(messages) {
|
|
|
53
54
|
return eligibleReplies(messages)[0]
|
|
54
55
|
}
|
|
55
56
|
|
|
56
|
-
|
|
57
|
-
|
|
57
|
+
// Completed assistant text, newest first. Mid-turn progress updates (finish "tool-calls")
|
|
58
|
+
// are text the user can read in the transcript, so pick and selection include them.
|
|
59
|
+
function textMessages(messages) {
|
|
60
|
+
const texts = []
|
|
58
61
|
const newest = [...messages].sort((a, b) =>
|
|
59
62
|
b.time.created - a.time.created || b.id.localeCompare(a.id),
|
|
60
63
|
)
|
|
61
64
|
for (const message of newest) {
|
|
62
65
|
if (message.type !== "assistant" || message.time.completed === undefined || message.error) continue
|
|
63
|
-
if (["
|
|
66
|
+
if (["error", "content-filter"].includes(message.finish)) continue
|
|
64
67
|
const text = message.content.filter(part => part.type === "text").map(part => part.text).join("\n\n")
|
|
65
|
-
if (text.trim())
|
|
68
|
+
if (text.trim()) {
|
|
69
|
+
texts.push({ id: message.id, text, progress: message.finish === "tool-calls", created: message.time.created })
|
|
70
|
+
}
|
|
66
71
|
}
|
|
67
|
-
return
|
|
72
|
+
return texts
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function eligibleReplies(messages) {
|
|
76
|
+
return textMessages(messages).filter(message => !message.progress).map(({ id, text }) => ({ id, text }))
|
|
68
77
|
}
|
|
69
78
|
|
|
70
|
-
|
|
79
|
+
// Walk the session-scoped history newest first; the UI cache holds only a recent page.
|
|
80
|
+
async function* history(client, sessionID, signal) {
|
|
71
81
|
const seen = new Set()
|
|
72
|
-
const messages = new Set()
|
|
73
82
|
let cursor
|
|
74
83
|
do {
|
|
75
84
|
signal.throwIfAborted()
|
|
@@ -77,17 +86,39 @@ async function latestReply(client, sessionID, signal, position = 1) {
|
|
|
77
86
|
sessionID, type: "assistant", limit: 50,
|
|
78
87
|
...(cursor ? { cursor } : { order: "desc" }),
|
|
79
88
|
}, { signal })
|
|
80
|
-
|
|
81
|
-
if (messages.has(reply.id)) continue
|
|
82
|
-
messages.add(reply.id)
|
|
83
|
-
if (--position === 0) return reply
|
|
84
|
-
}
|
|
89
|
+
yield page.data
|
|
85
90
|
cursor = page.cursor?.next
|
|
86
91
|
if (cursor && seen.has(cursor)) throw new Error("Session history returned a repeated page cursor.")
|
|
87
92
|
seen.add(cursor)
|
|
88
93
|
} while (cursor)
|
|
89
94
|
}
|
|
90
95
|
|
|
96
|
+
async function latestReply(client, sessionID, signal) {
|
|
97
|
+
for await (const page of history(client, sessionID, signal)) {
|
|
98
|
+
const [reply] = eligibleReplies(page)
|
|
99
|
+
if (reply) return reply
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function recentTexts(client, sessionID, signal, limit) {
|
|
104
|
+
const texts = new Map()
|
|
105
|
+
for await (const page of history(client, sessionID, signal)) {
|
|
106
|
+
for (const message of textMessages(page)) {
|
|
107
|
+
texts.set(message.id, message)
|
|
108
|
+
if (texts.size >= limit) return [...texts.values()]
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return [...texts.values()]
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Rendered transcript text drops Markdown markers and rewraps lines, so compare letters
|
|
115
|
+
// and digits only.
|
|
116
|
+
const compact = text => text.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "")
|
|
117
|
+
const preview = (text, length) => {
|
|
118
|
+
const line = text.replace(/[#*_`>]+/g, "").replace(/\s+/g, " ").trim()
|
|
119
|
+
return line.length > length ? `${line.slice(0, length - 1)}…` : line
|
|
120
|
+
}
|
|
121
|
+
|
|
91
122
|
async function archivedNotes(data) {
|
|
92
123
|
let count = 0
|
|
93
124
|
for (const name of await readdir(data, { recursive: true })) {
|
|
@@ -122,7 +153,17 @@ export function createReviewCommand(context, options = {}) {
|
|
|
122
153
|
title: "Annotate", message, variant, duration: variant === "error" ? 15000 : 5000,
|
|
123
154
|
})
|
|
124
155
|
|
|
125
|
-
|
|
156
|
+
let selection
|
|
157
|
+
const remember = current => {
|
|
158
|
+
const text = current?.getSelectedText?.() ?? ""
|
|
159
|
+
const route = context.ui.router.current()
|
|
160
|
+
if (text.trim() && route.type === "session") selection = { text, sessionID: route.sessionID }
|
|
161
|
+
}
|
|
162
|
+
// OpenCode copies a mouse selection and clears it on release, before any command can
|
|
163
|
+
// run, so keep the last one per session.
|
|
164
|
+
context.renderer.on("selection", remember)
|
|
165
|
+
|
|
166
|
+
async function start(resolve) {
|
|
126
167
|
if (disposed) return
|
|
127
168
|
if (active) return notice("An annotation is already in progress.")
|
|
128
169
|
// Capture before the first await: changing tabs must never redirect a review.
|
|
@@ -135,29 +176,12 @@ export function createReviewCommand(context, options = {}) {
|
|
|
135
176
|
let directory
|
|
136
177
|
let keepDraft = false
|
|
137
178
|
try {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
const target = input.trim()
|
|
141
|
-
if (wantsBrowser(target)) {
|
|
142
|
-
await web.run(target, sessionID)
|
|
143
|
-
return
|
|
144
|
-
}
|
|
145
|
-
const numeric = target !== "" && /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(target)
|
|
146
|
-
const position = numeric ? Number(target) : 1
|
|
147
|
-
if (numeric && (!/^\d+$/.test(target) || !Number.isSafeInteger(position) || position < 1)) {
|
|
148
|
-
throw new Error("Choose a positive integer reply number (1 = latest, 2 = previous).")
|
|
149
|
-
}
|
|
150
|
-
const source = target && !numeric
|
|
151
|
-
? await documentSource(target, context.client, sessionID, controller.signal)
|
|
152
|
-
: await latestReply(context.client, sessionID, controller.signal, position)
|
|
153
|
-
if (controller.signal.aborted) return
|
|
154
|
-
if (!source) return notice(position === 1
|
|
155
|
-
? "This session has no completed assistant reply yet."
|
|
156
|
-
: `Can't find reply ${position}: this session has fewer completed assistant text replies.`)
|
|
179
|
+
const source = await resolve({ sessionID, signal: controller.signal })
|
|
180
|
+
if (controller.signal.aborted || !source) return
|
|
157
181
|
|
|
158
182
|
directory = await mkdtemp(path.join(options.tempRoot ?? os.tmpdir(), "opencode-annotate-"))
|
|
159
183
|
keepDraft = true
|
|
160
|
-
const snapshot = source.snapshot ?? "last-reply.md"
|
|
184
|
+
const snapshot = source.snapshot ?? (source.selection ? "selection.md" : source.progress ? "progress-update.md" : "last-reply.md")
|
|
161
185
|
const file = path.join(directory, snapshot)
|
|
162
186
|
const data = path.join(directory, "data")
|
|
163
187
|
const promptID = `msg_${randomUUID().replaceAll("-", "")}`
|
|
@@ -171,7 +195,7 @@ export function createReviewCommand(context, options = {}) {
|
|
|
171
195
|
|
|
172
196
|
// Use a fresh store per invocation, and disable any inherited pane delivery.
|
|
173
197
|
// The OpenCode confirmation is the sole authority for sending feedback.
|
|
174
|
-
|
|
198
|
+
let env = Object.fromEntries(Object.entries(process.env).filter(([key]) =>
|
|
175
199
|
!key.startsWith("HERDR_") && !key.startsWith("PLANNOTATOR_TUI_"),
|
|
176
200
|
))
|
|
177
201
|
Object.assign(env, {
|
|
@@ -179,6 +203,9 @@ export function createReviewCommand(context, options = {}) {
|
|
|
179
203
|
PLANNOTATOR_FEEDBACK_HISTORY: "0",
|
|
180
204
|
PLANNOTATOR_TUI_THEME: context.themeMode === "light" ? "light" : "dark",
|
|
181
205
|
})
|
|
206
|
+
if ((options.inheritTheme ?? context.options.inheritTheme) === true) {
|
|
207
|
+
env = await prepareTheme({ binary, theme: context.theme, directory, env, signal: controller.signal })
|
|
208
|
+
}
|
|
182
209
|
context.ui.dialog.clear()
|
|
183
210
|
// OpenCode 2.1.1+ suspends and resumes asynchronously; resume forces a full repaint.
|
|
184
211
|
await context.renderer.suspend()
|
|
@@ -203,7 +230,9 @@ export function createReviewCommand(context, options = {}) {
|
|
|
203
230
|
if (!feedback.startsWith("# Annotations on ")) throw new Error("Can't recognize the TUI annotation export format.")
|
|
204
231
|
const subject = source.filePath
|
|
205
232
|
? `Here are my annotations on the document ${JSON.stringify(source.filePath)}. Please apply the feedback to that file.\nThe annotations are based on a snapshot taken when the document was opened (SHA-256: ${source.sourceHash}). Re-read the file and check the quoted text before editing.`
|
|
206
|
-
:
|
|
233
|
+
: source.selection
|
|
234
|
+
? "Here are my annotations on text I selected in this session. Please address the feedback."
|
|
235
|
+
: `Here are my annotations on your ${source.progress ? "progress update" : "reply"} ${source.id}. Please address the feedback.`
|
|
207
236
|
const text = `${subject}\n\n${feedback}`
|
|
208
237
|
const feedbackPath = path.join(directory, "feedback.md")
|
|
209
238
|
await writeFile(feedbackPath, text, { mode: 0o600 })
|
|
@@ -241,9 +270,55 @@ export function createReviewCommand(context, options = {}) {
|
|
|
241
270
|
}
|
|
242
271
|
}
|
|
243
272
|
|
|
273
|
+
const run = (input = "") => start(async ({ sessionID, signal }) => {
|
|
274
|
+
const target = input.trim()
|
|
275
|
+
if (/^\d+$/.test(target)) throw new Error("Numbered replies are retired. Use /annotate-pick to choose earlier text.")
|
|
276
|
+
if (wantsBrowser(target)) throw new Error("Use /annotate-web for webpages and browser pairing.")
|
|
277
|
+
if (target) return documentSource(target, context.client, sessionID, signal)
|
|
278
|
+
const reply = await latestReply(context.client, sessionID, signal)
|
|
279
|
+
if (!reply) notice("This session has no completed assistant reply yet.")
|
|
280
|
+
return reply
|
|
281
|
+
})
|
|
282
|
+
|
|
283
|
+
const pick = () => start(async ({ sessionID, signal }) => {
|
|
284
|
+
const texts = await recentTexts(context.client, sessionID, signal, 30)
|
|
285
|
+
if (!texts.length) {
|
|
286
|
+
notice("This session has no completed assistant text yet.")
|
|
287
|
+
return
|
|
288
|
+
}
|
|
289
|
+
const time = new Intl.DateTimeFormat(undefined, { hour: "2-digit", minute: "2-digit" })
|
|
290
|
+
const chosen = await context.ui.dialog.select({
|
|
291
|
+
title: "Annotate text",
|
|
292
|
+
options: texts.map(text => ({
|
|
293
|
+
title: preview(text.text, 60), value: text.id,
|
|
294
|
+
description: `${text.progress ? "Progress update" : "Reply"} · ${time.format(text.created)}`,
|
|
295
|
+
})),
|
|
296
|
+
})
|
|
297
|
+
return texts.find(text => text.id === chosen)
|
|
298
|
+
})
|
|
299
|
+
|
|
300
|
+
const annotateSelection = () => start(async ({ sessionID, signal }) => {
|
|
301
|
+
const selected = selection?.sessionID === sessionID ? selection.text : ""
|
|
302
|
+
const needle = compact(selected)
|
|
303
|
+
if (!needle) {
|
|
304
|
+
notice("Select text in this session first, then run /annotate-selection.")
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
const texts = await recentTexts(context.client, sessionID, signal, 200)
|
|
308
|
+
return texts.find(text => compact(text.text).includes(needle)) ?? { text: selected, selection: true }
|
|
309
|
+
})
|
|
310
|
+
|
|
311
|
+
const webReview = (input = "") => start(async ({ sessionID }) => {
|
|
312
|
+
const target = input.trim()
|
|
313
|
+
if (!(await web.run(target === "" ? "web" : target === "off" ? "web off" : target, sessionID))) {
|
|
314
|
+
throw new Error("Use a webpage URL, an HTML file, or off.")
|
|
315
|
+
}
|
|
316
|
+
})
|
|
317
|
+
|
|
244
318
|
return {
|
|
245
|
-
run,
|
|
319
|
+
run, pick, selection: annotateSelection, web: webReview,
|
|
246
320
|
dispose() {
|
|
321
|
+
context.renderer.off("selection", remember)
|
|
247
322
|
disposed = true
|
|
248
323
|
active?.abort()
|
|
249
324
|
return web.dispose()
|
package/theme.mjs
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { execFile } from "node:child_process"
|
|
2
|
+
import { writeFile } from "node:fs/promises"
|
|
3
|
+
import path from "node:path"
|
|
4
|
+
import { promisify } from "node:util"
|
|
5
|
+
|
|
6
|
+
const execute = promisify(execFile)
|
|
7
|
+
|
|
8
|
+
export function themeColors(theme) {
|
|
9
|
+
const roles = {
|
|
10
|
+
foreground: "text.base",
|
|
11
|
+
background: "background.base",
|
|
12
|
+
muted: "text.muted",
|
|
13
|
+
border: "border.base",
|
|
14
|
+
accent: "text.action.primary.selected",
|
|
15
|
+
heading: "markdown.heading",
|
|
16
|
+
code: "markdown.code",
|
|
17
|
+
link: "markdown.link",
|
|
18
|
+
"link-text": "markdown.linkText",
|
|
19
|
+
quote: "markdown.blockQuote",
|
|
20
|
+
strong: "markdown.strong",
|
|
21
|
+
emphasis: "markdown.emphasis",
|
|
22
|
+
"list-item": "markdown.listItem",
|
|
23
|
+
// OpenTUI styles ordered and unordered markers alike with markup.list.
|
|
24
|
+
"list-number": "markdown.listItem",
|
|
25
|
+
rule: "markdown.horizontalRule",
|
|
26
|
+
// Many themes leave action and feedback backgrounds transparent or equal to the
|
|
27
|
+
// page, so the send button uses the visible accent and feedback text colors.
|
|
28
|
+
send: "background.action.primary.focused",
|
|
29
|
+
sent: "text.feedback.success.base",
|
|
30
|
+
blocked: "text.feedback.warning.base",
|
|
31
|
+
comment: "text.feedback.warning.base",
|
|
32
|
+
"looks-good": "text.feedback.success.base",
|
|
33
|
+
delete: "text.feedback.error.base",
|
|
34
|
+
"comment-bg": "background.raised.high",
|
|
35
|
+
"looks-good-bg": "diff.background.added",
|
|
36
|
+
block: "background.raised.base",
|
|
37
|
+
toolbar: "background.raised.high",
|
|
38
|
+
cursor: "background.action.primary.focused",
|
|
39
|
+
"cursor-fg": "text.action.primary.focused",
|
|
40
|
+
selection: "background.action.primary.focused",
|
|
41
|
+
"selection-fg": "text.action.primary.focused",
|
|
42
|
+
}
|
|
43
|
+
const token = name => {
|
|
44
|
+
const color = name.split(".").reduce((value, key) => value?.[key], theme)
|
|
45
|
+
if (!color || [color.r, color.g, color.b, color.a].some(value =>
|
|
46
|
+
!Number.isFinite(value) || value < 0 || value > 1,
|
|
47
|
+
)) throw new Error(`OpenCode theme token ${name} is not a resolved RGBA color.`)
|
|
48
|
+
return color
|
|
49
|
+
}
|
|
50
|
+
const base = token("background.base")
|
|
51
|
+
const colors = Object.fromEntries(Object.entries(roles).map(([role, name]) => {
|
|
52
|
+
const color = token(name)
|
|
53
|
+
if (color.a === 0) return [role, "reset"]
|
|
54
|
+
if (color.a < 1 && base.a !== 1) {
|
|
55
|
+
throw new Error(`Can't resolve translucent theme token ${name} over a transparent terminal.`)
|
|
56
|
+
}
|
|
57
|
+
const hex = ["r", "g", "b"].map(channel =>
|
|
58
|
+
Math.round(255 * (color[channel] * color.a + base[channel] * (1 - color.a)))
|
|
59
|
+
.toString(16).padStart(2, "0"),
|
|
60
|
+
).join("")
|
|
61
|
+
return [role, `#${hex}`]
|
|
62
|
+
}))
|
|
63
|
+
const luminance = color => color.slice(1).match(/../g).map(value => {
|
|
64
|
+
const channel = Number.parseInt(value, 16) / 255
|
|
65
|
+
return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4
|
|
66
|
+
}).reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index], 0)
|
|
67
|
+
const contrast = (one, two) => {
|
|
68
|
+
const [a, b] = [luminance(one), luminance(two)].sort((x, y) => x - y)
|
|
69
|
+
return (b + 0.05) / (a + 0.05)
|
|
70
|
+
}
|
|
71
|
+
const hex = (...items) => items.every(color => color.startsWith("#"))
|
|
72
|
+
// Some host themes use a pale focused label even on a pale accent. Keep their
|
|
73
|
+
// palette, but use the body foreground when it makes selected text more legible.
|
|
74
|
+
if (hex(colors.selection, colors["selection-fg"], colors.foreground)) {
|
|
75
|
+
const focused = contrast(colors.selection, colors["selection-fg"])
|
|
76
|
+
if (focused < 4.5 && contrast(colors.selection, colors.foreground) > focused) {
|
|
77
|
+
colors["selection-fg"] = colors.foreground
|
|
78
|
+
colors["cursor-fg"] = colors.foreground
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
// One label colour serves the send, sent and blocked buttons: take whichever of
|
|
82
|
+
// the host's page or body colour stays most legible on all three.
|
|
83
|
+
const buttons = [colors.send, colors.sent, colors.blocked]
|
|
84
|
+
const labels = [colors.background, colors.foreground].filter(color => color.startsWith("#"))
|
|
85
|
+
if (hex(...buttons) && labels.length) {
|
|
86
|
+
colors["send-fg"] = labels.reduce((best, color) =>
|
|
87
|
+
Math.min(...buttons.map(button => contrast(button, color)))
|
|
88
|
+
> Math.min(...buttons.map(button => contrast(button, best))) ? color : best)
|
|
89
|
+
}
|
|
90
|
+
return colors
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function prepareTheme({ binary, theme, directory, env, signal }) {
|
|
94
|
+
const colors = themeColors(theme)
|
|
95
|
+
const config = async environment => execute(binary, ["config"], {
|
|
96
|
+
cwd: directory, env: environment, signal, timeout: 15000, maxBuffer: 1024 * 1024,
|
|
97
|
+
})
|
|
98
|
+
const { stdout } = await config(env)
|
|
99
|
+
// The fork's `config` command serializes its strict schema with [colors] last.
|
|
100
|
+
// Work on that normalized output, never try to parse or rewrite the user's TOML.
|
|
101
|
+
const marker = stdout.lastIndexOf("\n[colors]\n")
|
|
102
|
+
if (marker < 0) throw new Error("OpenCode colors require the color-capable Plannotator fork. Check the plugin's binary option.")
|
|
103
|
+
const filename = path.join(directory, "theme.toml")
|
|
104
|
+
const palette = Object.entries(colors).map(([role, value]) => `${role} = "${value}"`).join("\n")
|
|
105
|
+
await writeFile(filename, `${stdout.slice(0, marker)}\n\n[colors]\n${palette}\n`, { mode: 0o600 })
|
|
106
|
+
const themed = { ...env, PLANNOTATOR_TUI_CONFIG: filename }
|
|
107
|
+
const effective = await config(themed)
|
|
108
|
+
// Also catches launchers that overwrite PLANNOTATOR_TUI_CONFIG instead of honoring it.
|
|
109
|
+
for (const [role, value] of Object.entries(colors)) {
|
|
110
|
+
if (!new RegExp(`^${role} = "${value}"$`, "mi").test(effective.stdout)) {
|
|
111
|
+
throw new Error(`Plannotator did not apply ${role}. Its launcher must honor PLANNOTATOR_TUI_CONFIG.`)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return themed
|
|
115
|
+
}
|
package/tui.ts
CHANGED
|
@@ -13,8 +13,8 @@ export default Plugin.define({
|
|
|
13
13
|
mode: "global",
|
|
14
14
|
commands: [{
|
|
15
15
|
id: "opencode-annotate.annotate",
|
|
16
|
-
title: "Annotate reply
|
|
17
|
-
description: "
|
|
16
|
+
title: "Annotate reply or document",
|
|
17
|
+
description: "The latest completed reply, or a Markdown/text file path",
|
|
18
18
|
group: "Annotate",
|
|
19
19
|
palette: true,
|
|
20
20
|
slash: { name: "annotate", arguments: true },
|
|
@@ -29,6 +29,30 @@ export default Plugin.define({
|
|
|
29
29
|
// Any supplied argument is deliberately ignored: this always means latest.
|
|
30
30
|
slash: { name: "annotate-last", arguments: true },
|
|
31
31
|
run: () => review.run(),
|
|
32
|
+
}, {
|
|
33
|
+
id: "opencode-annotate.annotate-pick",
|
|
34
|
+
title: "Annotate earlier text (TUI)",
|
|
35
|
+
description: "Choose a recent reply or progress update to annotate",
|
|
36
|
+
group: "Annotate",
|
|
37
|
+
palette: true,
|
|
38
|
+
slash: { name: "annotate-pick", arguments: true },
|
|
39
|
+
run: () => review.pick(),
|
|
40
|
+
}, {
|
|
41
|
+
id: "opencode-annotate.annotate-selection",
|
|
42
|
+
title: "Annotate selected text (TUI)",
|
|
43
|
+
description: "Open the message containing your last selection in this session",
|
|
44
|
+
group: "Annotate",
|
|
45
|
+
palette: true,
|
|
46
|
+
slash: { name: "annotate-selection", arguments: true },
|
|
47
|
+
run: () => review.selection(),
|
|
48
|
+
}, {
|
|
49
|
+
id: "opencode-annotate.annotate-web",
|
|
50
|
+
title: "Annotate webpage (browser)",
|
|
51
|
+
description: "Pair Chrome with this session, open a URL or HTML file, or off",
|
|
52
|
+
group: "Annotate",
|
|
53
|
+
palette: true,
|
|
54
|
+
slash: { name: "annotate-web", arguments: true },
|
|
55
|
+
run: review.web,
|
|
32
56
|
}],
|
|
33
57
|
}))
|
|
34
58
|
return null
|