@nxxxsooo/opencode-annotate 0.13.1 → 0.14.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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.14.0 — references as prompts
4
+
5
+ - Submit the referenced conversation, optional comment and inline annotations together
6
+ as one ordinary user prompt, instead of a compact reference item.
7
+ - Press **Ctrl+T** in the reference picker, or use `/ref --tui`, to mark passages in
8
+ the bundled reviewer. Confirmation preserves the originally selected destination.
9
+ - Confirmed references continue an existing conversation. Before its first message,
10
+ references wait without starting the assistant; `/ref` also works from OpenCode home
11
+ and creates the destination only after confirmation.
12
+ - Keep existing annotation/browser commands, delivery behavior and Safari's copy-only
13
+ boundary unchanged. This release does not include cross-agent hc review.
14
+
3
15
  ## 0.13.1 — README and search discoverability
4
16
 
5
17
  - Bring the install command and a three-step first review near the top of the README,
package/README.md CHANGED
@@ -1,12 +1,20 @@
1
- # OpenCode Annotate — review AI replies, documents, and webpages
1
+ # OpenCode Annotate
2
+
3
+ **Review OpenCode AI replies, Markdown documents, and webpages — send annotated feedback to the originating session.**
2
4
 
3
5
  [![npm](https://img.shields.io/npm/v/@nxxxsooo/opencode-annotate)](https://www.npmjs.com/package/@nxxxsooo/opencode-annotate)
4
6
  [![CI](https://github.com/nxxxsooo/opencode-annotate/actions/workflows/ci.yml/badge.svg)](https://github.com/nxxxsooo/opencode-annotate/actions/workflows/ci.yml)
5
7
  [![MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
6
8
 
7
- **Annotate AI replies and Markdown documents in your terminal, or review webpages in your browser.** Select a passage or element, add feedback, and send it to the originating OpenCode conversation.
9
+ [Website](https://mjshao.fun/opencode-annotate/) · [Install](#install) · [Workflows](#workflows) · [Browser review](#browser-review-optional) · [References](#reference-previous-conversations) · [Configuration](#configuration)
10
+
11
+ This **unofficial OpenCode plugin** bundles the native [terminal reviewer](tui/README.md) — no separate reviewer install is required. The optional [browser companion](#browser-review-optional) adds Chrome delivery and Safari copy-only review. Published on npm as `@nxxxsooo/opencode-annotate`.
8
12
 
9
- This **unofficial OpenCode plugin** includes the native [terminal reviewer](tui/README.md): **no separate reviewer install is required**. The optional [browser companion](#browser-review-optional) adds Chrome delivery and Safari's copy-only review. Published on npm as `@nxxxsooo/opencode-annotate`.
13
+ | Surface | Reviews | Entry point |
14
+ |---|---|---|
15
+ | Terminal (bundled TUI) | AI replies, Markdown, plain text | `/annotate` |
16
+ | Chrome (optional) | Webpages, local HTML | `/annotate-web` |
17
+ | Safari (optional, copy-only) | Webpages | `/annotate-web` |
10
18
 
11
19
  ## Install
12
20
 
@@ -45,6 +53,8 @@ Empty and cancelled reviews submit nothing. Opening a review makes no model call
45
53
 
46
54
  **`Ctrl+S`** saves the current comment and sends in one step. The header's **Send N back (q)** button does the same as `q`. **`Ctrl+C`** returns without sending, and OpenCode asks whether to send. `E` and `S` send as well, following any `[keys]` rebinding.
47
55
 
56
+ <a id="what-it-reviews"></a>
57
+
48
58
  ## Workflows
49
59
 
50
60
  ### Annotate AI responses
@@ -86,12 +96,13 @@ Browser setup is separate from the plugin install. Safari supports local notes a
86
96
 
87
97
  ### Reference previous conversations
88
98
 
89
- Run `/ref` to search and attach a past conversation as context. The source is attached to the session where you invoked `/ref`, queued with `resume: false` so an idle assistant stays idle until your next prompt.
99
+ Run `/ref` to search and attach a past conversation with optional comments and inline annotations as one ordinary user prompt. Confirmation continues an established conversation; before your first message, references wait with `resume: false` for your next prompt.
90
100
 
91
101
  ```text
92
102
  /ref # Choose a conversation from this project
93
103
  /ref authentication # Search titles in this project
94
104
  /ref --all authentication # Search titles across projects
105
+ /ref --tui authentication # Annotate the reference snapshot in the TUI
95
106
  /ref ses_… # Attach a specific conversation
96
107
  ```
97
108
 
@@ -114,6 +125,7 @@ Two Code Mode tools are registered for agent use: `annotate.session_search` and
114
125
  /ref Choose a conversation from this project
115
126
  /ref authentication Search conversation titles in this project
116
127
  /ref --all authentication Search titles across projects
128
+ /ref --tui authentication Annotate the reference snapshot in the TUI
117
129
  /ref ses_… Attach a specific conversation
118
130
  ```
119
131
 
@@ -127,20 +139,13 @@ Move its entry from `cli.json` to `opencode.json(c)`, retaining the whole entry
127
139
 
128
140
  ## Reference another conversation
129
141
 
130
- Run `/ref` or `/ref <title words>`, select the source, add an optional comment, then choose
131
- **Attach reference**. The comment field grows as you type or paste, wraps long lines, and
132
- scrolls at a screen-aware height limit. **Shift+Enter** adds a line, **Enter** continues to
133
- confirmation, and **Esc** cancels without attaching anything.
134
- The confirmation names both conversations and shows whether the text is an excerpt.
135
- The source is attached to the session where you invoked `/ref`, even if you switch tabs.
136
- It is queued as historical context with `resume: false`: an idle assistant stays idle
137
- until your next prompt. An already-running session can consume it at a later queue boundary.
138
- Escape cancels without attaching anything.
139
-
140
- Search defaults to the current session's project, including its worktrees. `/ref --all`
141
- searches every project on the connected server. Titles can be ambiguous, so title searches
142
- always show a chooser with directory, time and session ID. An exact `ses_…` ID selects
143
- that source directly, including a source in another project.
142
+ Run `/ref` or `/ref <title words>`, select the source, add an optional whole-reference comment, then choose **Attach and continue**. For inline marks, press **Ctrl+T** in the source chooser (or run `/ref --tui <title words>`) to annotate the snapshot in the existing TUI. The source snapshot, comment and annotations are submitted together as one ordinary user prompt, not a compact reference item. The confirmation names both conversations and shows whether the text is an excerpt. The source is attached to the session where you invoked `/ref`, even if you switch tabs.
143
+
144
+ The comment field grows as you type or paste, wraps long lines, and scrolls at a screen-aware height limit. **Shift+Enter** adds a line, **Enter** continues to confirmation, and **Esc** cancels without attaching anything. Confirming continues the conversation automatically (`delivery: "steer"`, `resume: true`): an idle assistant starts immediately, while a running assistant receives the reference and feedback at its next processing boundary. The quoted conversation remains historical source material.
145
+
146
+ Before your first message, **Attach** adds the reference with `resume: false`, and the assistant reads it with the message you write next. Run `/ref` again to add more. On OpenCode home, `/ref` searches the home directory's project and creates the new session (same directory and model) only after you confirm, then opens it. Cancelling leaves no empty session.
147
+
148
+ Search defaults to the current session's project, including its worktrees. `/ref --all` searches every project on the connected server. In the chooser, **Ctrl+A** switches between this project and all projects and reruns the same title query. The wide chooser gives titles the remaining space beside right-aligned, shortened directory tails; the confirmation retains the full directory. An exact `ses_…` ID selects that source directly, including a source in another project.
144
149
 
145
150
  The server part adds two Code Mode tools:
146
151
 
@@ -151,35 +156,19 @@ The server part adds two Code Mode tools:
151
156
  older history. For a shortened message, pass its `messageID` and `nextOffset` as
152
157
  `offset` to retrieve the rest.
153
158
 
154
- References include user text and completed assistant text, source IDs and timestamps.
155
- Tool payloads, reasoning, binary attachments and unfinished output are excluded. Each
156
- page contains at most 24,000 characters of message text, distributed across the messages;
157
- truncation and continuation are explicit. Historical claims may no longer match the code.
158
- Search matches titles, not words inside messages.
159
+ References include user text and completed assistant text, source IDs and timestamps. Tool payloads, reasoning, binary attachments and unfinished output are excluded. Each page contains at most 24,000 characters of message text, distributed across the messages; truncation and continuation are explicit. Historical claims may no longer match the code. Search matches titles, not words inside messages.
159
160
 
160
- **Server requirement:** the full-history read tool currently uses the official `opencode api`
161
- command because OpenCode 2.2's plugin context exposes only post-compaction context. The
162
- server must run as the managed OpenCode service with `opencode` on PATH. A process-ID
163
- check rejects a different discovered server; standalone and embedded servers are not
164
- supported by this tool. `/ref` uses the TUI's connected client directly. No separate
165
- transcript index or database access is needed.
161
+ **Server requirement:** the full-history read tool uses the official `opencode api` command because OpenCode 2.2's plugin context exposes only post-compaction context. The server must run as the managed OpenCode service with `opencode` on PATH. A process-ID check rejects a different discovered server. `/ref` uses the TUI's connected client directly.
166
162
 
167
- Permission actions are `annotate_session_search` (project ID, or `*` for cross-project
168
- search) and `annotate_session_read` (source session ID).
163
+ Permission actions are `annotate_session_search` (project ID, or `*` for cross-project search) and `annotate_session_read` (source session ID).
169
164
 
170
- ### Reference verification
165
+ <details>
166
+ <summary id="reference-verification">Reference verification</summary>
171
167
 
172
- `npm run test:references` exercises the server tools and `/ref` against source or an
173
- extracted npm package. The checks cover pre-compaction history, API responses larger than 256 KiB,
174
- pagination, long-message continuation, attachment and cancellation without a model
175
- turn. Unit checks also cover tab changes, permission denial and private-file cleanup.
168
+ `npm run test:references` exercises the server tools and `/ref` against source or an extracted npm package. The checks cover pre-compaction history, API responses larger than 256 KiB, pagination, long-message continuation, attachment and cancellation. The fixture records the production `steer`/`resume` request, then forces `resume: false` to avoid a model turn. Unit checks also cover tab changes, permission denial and private-file cleanup.
176
169
 
177
- Recovery starts in `reference-command.mjs` for `/ref`, `session-tools.mjs` for agent
178
- tools, and `session-reference.mjs` for bounded history. `server-history.mjs` captures
179
- CLI output in private temporary files to avoid v2.2.0 pipe truncation, then removes
180
- them. Regression entrypoints are `session-reference.test.mjs`,
181
- `server-history.test.mjs` and `tests/references-smoke.py`; release ownership remains in
182
- [docs/releasing.md](docs/releasing.md).
170
+ Recovery starts in `reference-command.mjs` for `/ref`, `session-tools.mjs` for agent tools, and `session-reference.mjs` for bounded history. `server-history.mjs` captures CLI output in private temporary files to avoid v2.2.0 pipe truncation, then removes them. Regression entrypoints are `session-reference.test.mjs`, `server-history.test.mjs` and `tests/references-smoke.py`; release ownership remains in [docs/releasing.md](docs/releasing.md).
171
+ </details>
183
172
 
184
173
  ## Antigravity (AGY) support
185
174
 
@@ -198,15 +187,9 @@ them. Regression entrypoints are `session-reference.test.mjs`,
198
187
 
199
188
  ### Match OpenCode's colors
200
189
 
201
- Set `"inheritTheme": true` in the plugin's `options`. The bundled reviewer supports the
202
- full palette and `[ui].doc_width` for a readable text column on wide terminals.
203
- See [TUI theme integration](docs/tui-theme.md).
190
+ Set `"inheritTheme": true` in the plugin's `options`. The bundled reviewer supports the full palette and `[ui].doc_width` for a readable text column on wide terminals. See [TUI theme integration](docs/tui-theme.md).
204
191
 
205
- Each review uses OpenCode's current resolved colors for the canvas, text, Markdown,
206
- borders, highlights, cursor and selection. The plugin asks the chosen binary for its
207
- effective configuration, copies it into that review's private directory, and validates
208
- the themed copy before taking over the terminal. Your original settings stay intact.
209
- Launchers must honor an existing `PLANNOTATOR_TUI_CONFIG`.
192
+ Each review uses OpenCode's current resolved colors for the canvas, text, Markdown, borders, highlights, cursor and selection. The plugin asks the chosen binary for its effective configuration, copies it into that review's private directory, and validates the themed copy before taking over the terminal. Your original settings stay intact. Launchers must honor an existing `PLANNOTATOR_TUI_CONFIG`.
210
193
 
211
194
  ## Browser review (optional)
212
195
 
@@ -222,189 +205,78 @@ ANNOTATE_DEVELOPMENT_TEAM="TEAMID" npm run build:safari
222
205
  npm run install:safari
223
206
  ```
224
207
 
225
- The installer replaces `/Applications/annotate.app` and refreshes its registration.
226
- Open that app once, then enable Annotate in Safari > Settings > Extensions. Without
227
- signing environment variables the build uses an ad-hoc signature, which Safari may
228
- refuse to register. Allow access to the pages you want to review.
208
+ The installer replaces `/Applications/annotate.app` and refreshes its registration. Open that app once, then enable Annotate in Safari > Settings > Extensions. Without signing environment variables the build uses an ad-hoc signature, which Safari may refuse to register. Allow access to the pages you want to review.
229
209
 
230
- Click the Annotate toolbar button, or use Option+Shift+A where Safari supports the
231
- extension command, to open its standalone panel. Select text or pick an element,
232
- write notes, then **Copy notes** to paste the round into any agent. Notes and drafts
233
- stay local; copying closes the round and **Restore last round** recovers it.
210
+ Click the Annotate toolbar button, or use Option+Shift+A where Safari supports the extension command, to open its standalone panel. Select text or pick an element, write notes, then **Copy notes** to paste the round into any agent. Notes and drafts stay local; copying closes the round and **Restore last round** recovers it.
234
211
 
235
- Safari requires an App-Sandboxed app extension, so it cannot start the Node bridge or
236
- read the session registry. It has no direct session delivery or session chooser;
237
- Chrome retains both. Safari also has no docked side panel: its separate window stays
238
- bound to the reviewed browser window and keeps polling while you work on the page.
212
+ Safari requires an App-Sandboxed app extension, so it cannot start the Node bridge or read the session registry. It has no direct session delivery or session chooser; Chrome retains both. Safari also has no docked side panel: its separate window stays bound to the reviewed browser window and keeps polling while you work on the page.
239
213
 
240
- Set the plugin option `"browser": "Safari"` so `/annotate-web <url-or-html-file>` opens
241
- the page in Safari. The only public values are `"Chrome"` (default) and `"Safari"`;
242
- Chrome maps to the macOS app Google Chrome. AGY supports the same choice with
243
- `agy-annotate web <url> --browser Safari`. Restart the client after changing the option.
244
- `/annotate-web` keeps its existing pairing lifecycle; Safari ignores that pairing
245
- and copies notes instead. `/annotate` remains the text/TUI command.
214
+ Set the plugin option `"browser": "Safari"` so `/annotate-web <url-or-html-file>` opens the page in Safari. The only public values are `"Chrome"` (default) and `"Safari"`; Chrome maps to the macOS app Google Chrome. AGY supports the same choice with `agy-annotate web <url> --browser Safari`. Restart the client after changing the option. `/annotate-web` keeps its existing pairing lifecycle; Safari ignores that pairing and copies notes instead. `/annotate` remains the text/TUI command.
246
215
 
247
- After updates, run `npm run build:safari` with the signing variables again, then
248
- `npm run install:safari`. Reopen the app and re-enable the extension if needed. An
249
- unpacked Chrome reload does not update the installed Safari app.
216
+ After updates, run `npm run build:safari` with the signing variables again, then `npm run install:safari`. Reopen the app and re-enable the extension if needed. An unpacked Chrome reload does not update the installed Safari app.
250
217
 
251
218
  ### Chrome (direct delivery)
252
219
 
253
- 1. Clone this repository and load its `browser/` directory as an unpacked extension in
254
- `chrome://extensions`. Allow file URL access if reviewing local HTML.
255
- 2. Run `npm run install:bridge` in the clone to register the native host. It allows only this
256
- companion's fixed extension ID and resolves Node absolutely. The host starts on demand and
257
- opens no HTTP port.
220
+ 1. Clone this repository and load its `browser/` directory as an unpacked extension in `chrome://extensions`. Allow file URL access if reviewing local HTML.
221
+ 2. Run `npm run install:bridge` in the clone to register the native host. It allows only this companion's fixed extension ID and resolves Node absolutely. The host starts on demand and opens no HTTP port.
258
222
  3. Reopen the OpenCode terminal client; the shared service needs no restart.
259
223
 
260
- Run `/annotate-web`, then open the Chrome extension. From the blank home screen, it
261
- creates an empty session in the current directory using the selected model; no first
262
- prompt is needed. In an existing session, it pairs that session. A sole live
263
- session is shown automatically; with several sessions, choose one once. Click the
264
- destination beside **To** to change or refresh it. Its title stays visible beside Send,
265
- including while disconnected, with its directory available on hover and in the chooser.
266
- A sole target is only preselected: no binding or model turn occurs until
267
- the user clicks **Send & continue**. A disconnected destination never silently switches to another session.
268
-
269
- Choose **Pick element** or select text, then write a comment or question. The composer
270
- appears for that selection. **Send N notes & continue** saves the current feedback and
271
- sends pending notes in one action; **Add note** collects feedback locally for a batch.
272
- Cmd/Ctrl+Enter adds a note or saves an edit. This sends pending notes to that captured
273
- session and starts a normal model turn; pairing and saving notes make no model call.
274
- Switching terminal tabs never changes the paired target. Revoke with `/annotate-web off`.
275
-
276
- The numbered queue matches the page markers. Click a note's quoted target to show it
277
- on the page without activating the element; **Edit** changes the feedback, and **Undo**
278
- restores a deleted note. The delivery bar shows the round's note count and destination.
279
-
280
- Each send closes a review round: delivered notes leave the list and the panel is ready
281
- for the next round. **Restore last round** returns the most recent delivered notes to the
282
- list; the last ten rounds per page are kept.
283
-
284
- Delivery has two modes, shown beside the destination. With a **Live** session the primary
285
- button is **Send N notes**, and the copy icon beside it copies the round instead. When the
286
- session is **Offline**, or none is connected, the button is **Copy N notes**: it copies the
287
- round as Markdown for any agent and closes it the same way. Run `/annotate-web` in a
288
- session to switch back to Send. If a session drops during Send, the notes are kept and the
289
- panel switches to Copy.
290
- **More review options** contains a non-closing Markdown copy, JSON export, and a preview
291
- of the current round.
292
-
293
- After a page reload or same-site navigation, the panel reconnects its page tools
294
- automatically. If Chrome has withdrawn access (for example after moving to another site),
295
- the panel asks you to click the extension icon once; saved notes are kept.
224
+ Run `/annotate-web`, then open the Chrome extension. From the blank home screen, it creates an empty session in the current directory using the selected model; no first prompt is needed. In an existing session, it pairs that session. A sole live session is shown automatically; with several sessions, choose one once. Click the destination beside **To** to change or refresh it. Its title stays visible beside Send, including while disconnected, with its directory available on hover and in the chooser. A sole target is only preselected: no binding or model turn occurs until the user clicks **Send & continue**. A disconnected destination never silently switches to another session.
225
+
226
+ Choose **Pick element** or select text, then write a comment or question. The composer appears for that selection. **Send N notes & continue** saves the current feedback and sends pending notes in one action; **Add note** collects feedback locally for a batch. Cmd/Ctrl+Enter adds a note or saves an edit. This sends pending notes to that captured session and starts a normal model turn; pairing and saving notes make no model call. Switching terminal tabs never changes the paired target. Revoke with `/annotate-web off`.
227
+
228
+ The numbered queue matches the page markers. Click a note's quoted target to show it on the page without activating the element; **Edit** changes the feedback, and **Undo** restores a deleted note. The delivery bar shows the round's note count and destination.
229
+
230
+ Each send closes a review round: delivered notes leave the list and the panel is ready for the next round. **Restore last round** returns the most recent delivered notes to the list; the last ten rounds per page are kept.
231
+
232
+ Delivery has two modes, shown beside the destination. With a **Live** session the primary button is **Send N notes**, and the copy icon beside it copies the round instead. When the session is **Offline**, or none is connected, the button is **Copy N notes**: it copies the round as Markdown for any agent and closes it the same way. Run `/annotate-web` in a session to switch back to Send. If a session drops during Send, the notes are kept and the panel switches to Copy. **More review options** contains a non-closing Markdown copy, JSON export, and a preview of the current round.
233
+
234
+ After a page reload or same-site navigation, the panel reconnects its page tools automatically. If Chrome has withdrawn access (for example after moving to another site), the panel asks you to click the extension icon once; saved notes are kept.
296
235
 
297
236
  ### Explicit routing
298
237
 
299
- `/annotate`, `/annotate-pick` and `/annotate-selection` always use the TUI; Markdown and
300
- plain-text files do too. Only `/annotate-web` enters the browser workflow; passing a URL or
301
- HTML file to `/annotate` points you there. A reply containing HTML links or code fences does
302
- not change the default.
238
+ `/annotate`, `/annotate-pick` and `/annotate-selection` always use the TUI; Markdown and plain-text files do too. Only `/annotate-web` enters the browser workflow; passing a URL or HTML file to `/annotate` points you there. A reply containing HTML links or code fences does not change the default.
303
239
 
304
240
  ### Browser safeguards and limitations
305
241
 
306
- Written drafts autosave locally and restore after panel reload or a return to the same URL,
307
- including SPA routes. Selecting another target with unfinished feedback offers **Add/Save
308
- & switch**, **Keep editing**, or **Discard & switch**. Storage failures keep the input and
309
- offer a retry; competing panels require an explicit choice of draft. Saved-note revision
310
- checks likewise prevent stale tabs overwriting newer feedback. Full JSON/Markdown exports include
311
- redacted URLs, exact selected text/context, verified selector hints, styles and accessibility.
312
- Missing/changed/ambiguous targets are labeled in the sidebar instead of silently rebound.
313
- Comments and drafts live in extension-owned UI/storage; the page receives only selection
314
- metadata and numbered markers, not your written feedback.
315
-
316
- Native delivery requires an open, paired local TUI. If the receiver closes, feedback stays
317
- pending. A failed batch retains its original target and ID for safe retry; if that target
318
- is permanently gone, export the notes before starting a new review. **Retry N notes &
319
- continue** retries that original batch; newly composed feedback stays local for the next
320
- send. Copying a round instead supersedes a failed batch.
321
- Clipboard failures expose a selectable preview and keep the round open. Browser-internal pages, PDF,
322
- cross-origin iframes, Canvas and remote SSH TUI clients are outside this version's scope.
323
- Page Context is retired only after exporting its drafts and verifying this replacement.
324
-
325
- See [implementation plan](docs/annotate-html-integration-plan.md) and
326
- [shipped-artifact evaluation](docs/annotate-html-evaluation.md), plus
327
- [browser provenance](browser/UPSTREAM.md). `npm test`, `npm run test:smoke`, and
328
- `npm run test:browser` verify each layer; the browser test uses an existing Playwright installation
329
- (`PLAYWRIGHT_MODULE`) and browser executable (`CHROMIUM_PATH`) in an isolated profile.
242
+ Written drafts autosave locally and restore after panel reload or a return to the same URL, including SPA routes. Selecting another target with unfinished feedback offers **Add/Save & switch**, **Keep editing**, or **Discard & switch**. Storage failures keep the input and offer a retry; competing panels require an explicit choice of draft. Saved-note revision checks likewise prevent stale tabs overwriting newer feedback. Full JSON/Markdown exports include redacted URLs, exact selected text/context, verified selector hints, styles and accessibility. Missing/changed/ambiguous targets are labeled in the sidebar instead of silently rebound. Comments and drafts live in extension-owned UI/storage; the page receives only selection metadata and numbered markers, not your written feedback.
243
+
244
+ Native delivery requires an open, paired local TUI. If the receiver closes, feedback stays pending. A failed batch retains its original target and ID for safe retry; if that target is permanently gone, export the notes before starting a new review. **Retry N notes & continue** retries that original batch; newly composed feedback stays local for the next send. Copying a round instead supersedes a failed batch. Clipboard failures expose a selectable preview and keep the round open. Browser-internal pages, PDF, cross-origin iframes, Canvas and remote SSH TUI clients are outside this version's scope. Page Context is retired only after exporting its drafts and verifying this replacement.
245
+
246
+ See [implementation plan](docs/annotate-html-integration-plan.md) and [shipped-artifact evaluation](docs/annotate-html-evaluation.md), plus [browser provenance](browser/UPSTREAM.md). `npm test`, `npm run test:smoke`, and `npm run test:browser` verify each layer; the browser test uses an existing Playwright installation (`PLAYWRIGHT_MODULE`) and browser executable (`CHROMIUM_PATH`) in an isolated profile.
330
247
 
331
248
  ### Reload after browser companion updates
332
249
 
333
- After updating the unpacked `browser/` files, open `chrome://extensions` and click
334
- **Reload** for **OpenCode Annotate**. Return to the target webpage and open Annotate
335
- using its extension icon or **Alt+Shift+A**.
250
+ After updating the unpacked `browser/` files, open `chrome://extensions` and click **Reload** for **OpenCode Annotate**. Return to the target webpage and open Annotate using its extension icon or **Alt+Shift+A**.
336
251
 
337
- A newly opened sidebar can load the updated `panel.mjs` while Chrome still runs an
338
- older `worker.mjs`. The panel detects this protocol mismatch and shows **Annotate was
339
- updated** with a **Reload Annotate** button; reopen the panel afterwards.
340
- Saved extension-local data survives an extension reload.
252
+ A newly opened sidebar can load the updated `panel.mjs` while Chrome still runs an older `worker.mjs`. The panel detects this protocol mismatch and shows **Annotate was updated** with a **Reload Annotate** button; reopen the panel afterwards. Saved extension-local data survives an extension reload.
341
253
 
342
- For diagnosis, compare the running worker's source (DevTools/CDP
343
- `Debugger.getScriptSource`) with `browser/worker.mjs` in the loaded checkout.
344
- The manifest version alone cannot identify edits to an unpacked extension.
254
+ For diagnosis, compare the running worker's source (DevTools/CDP `Debugger.getScriptSource`) with `browser/worker.mjs` in the loaded checkout. The manifest version alone cannot identify edits to an unpacked extension.
345
255
 
346
256
  ## Review and send
347
257
 
348
- 1. Run `/annotate` or `/annotate path/to/file.md` in a session.
349
- 2. Select text by dragging, or press `v` and use movement keys.
350
- 3. Press `c` to comment, `w` for **what?**, `a` for “looks good,” or `d` to request deletion.
351
- **what?** marks a passage you don't understand with a short `what?` note
352
- ([what? notes](#what-notes)). Without a selection, `c` comments on the current block.
353
- Enter saves a comment. With a selection waiting, Enter records **Done** (the requested
354
- work is finished), and `g` records **Get** (understood). Esc dismisses without a note.
355
- The compact toolbar shows approve, comment, Done and Get; `w`, `d` and `y` are keyboard-only.
356
- Selecting never touches the clipboard; press `y` to copy the selected source and keep
357
- the selection for annotating.
258
+ 1. Run `/annotate` or `/annotate path/to/file.md`.
259
+ 2. Select text by dragging, or press `v` and move.
260
+ 3. Press `c` to comment, `w` for **what?** ([what? notes](#what-notes)), `a` for "looks good," or `d` to request deletion. Without a selection, `c` comments on the current block. Enter saves a comment; with a selection waiting, Enter records **Done**, `g` records **Get**. Esc dismisses. The compact toolbar shows approve, comment, Done and Get; `w`, `d` and `y` are keyboard-only. Press `y` to copy the selected source.
358
261
  4. Press **`q`** to send your notes and return to OpenCode.
359
262
 
360
- For real PNG toolbar artwork in a verified Kitty-graphics terminal, see the
361
- [local image-toolbar configuration](tui/README.md#local-image-toolbar-trial).
362
- Artwork is user-supplied and not included; unconfigured terminals keep Unicode icons.
263
+ For PNG toolbar artwork in a verified Kitty-graphics terminal, see the [local image-toolbar configuration](tui/README.md#local-image-toolbar-trial). Artwork is user-supplied; unconfigured terminals keep Unicode icons.
363
264
 
364
265
  ### Chinese and other input methods
365
266
 
366
- An input method holds plain letters while it composes, so review keys such as `e`, `q`
367
- and `s`, and OpenCode's permission shortcuts, do nothing. With
368
- [Slash Saver](https://github.com/nxxxsooo/slash-saver) 1.1+ installed in `/Applications`,
369
- the plugin selects its configured ASCII source while you browse a review or answer a
370
- permission prompt, and restores your source afterwards. The comment and edit
371
- boxes switch back to your writing source while open. Set `"inputSource": false` in the
372
- plugin's `options` to turn this off, or a path to another helper with the same
373
- `input-source current|select|ascii` commands. The reviewer also binds **`Ctrl+E`** to edit,
374
- which an input method passes through.
375
-
376
- Opening a review makes no model call. Confirming sends a normal user prompt and
377
- resumes the **original session**, even if the active tab changes. Empty and
378
- cancelled reviews submit nothing.
379
-
380
- ## What it reviews
381
-
382
- **Replies:** the latest completed text reply, with paginated history lookup.
383
- Reasoning, in-progress messages and tool-call commentary are excluded.
384
- Use `/annotate-pick` for an earlier reply or progress update, or `/annotate-selection`
385
- for selected transcript text. Numbered reply arguments are retired.
386
-
387
- **Documents:** local UTF-8 `.md`, `.mdx`, `.markdown` and `.txt` files up to 2 MiB.
388
- Relative paths resolve against the captured session's working directory, not the
389
- directory from which the terminal client happened to start. Absolute and `~/`
390
- paths work too. The file must exist on the machine running the terminal client.
391
-
392
- The TUI reads a fixed snapshot and does not edit the original document. Feedback
393
- includes the original path and snapshot hash, with instructions to re-read the
394
- current file before applying suggestions. Document review works even before the
395
- session has an assistant reply.
267
+ An input method holds plain letters while it composes, so review keys such as `e`, `q` and `s`, and OpenCode's permission shortcuts, do nothing. With [Slash Saver](https://github.com/nxxxsooo/slash-saver) 1.1+ installed in `/Applications`, the plugin selects its configured ASCII source while you browse a review or answer a permission prompt, and restores your source afterwards. The comment and edit boxes switch back to your writing source while open. Set `"inputSource": false` in the plugin's `options` to turn this off, or a path to another helper with the same `input-source current|select|ascii` commands. The reviewer also binds **`Ctrl+E`** to edit, which an input method passes through.
268
+
269
+ Opening a review makes no model call. Confirming sends a normal user prompt and resumes the **original session**, even if the active tab changes. Empty and cancelled reviews submit nothing.
396
270
 
397
271
  ## Updates and uninstall
398
272
 
399
- `@latest` selects the npm release channel. OpenCode caches installed packages;
400
- it does not follow this repository's commits. Update just this plugin with:
273
+ `@latest` selects the npm release channel. OpenCode caches installed packages; it does not follow this repository's commits. Update just this plugin with:
401
274
 
402
275
  ```sh
403
276
  opencode plugin update @nxxxsooo/opencode-annotate@latest
404
277
  ```
405
278
 
406
- Run `/reload` if the command list has not refreshed. Check the installed version with
407
- `opencode plugin list`.
279
+ Run `/reload` if the command list has not refreshed. Check the installed version with `opencode plugin list`.
408
280
 
409
281
  To remove it:
410
282
 
@@ -433,47 +305,30 @@ Enable auto-annotation in the plugin entry in **`opencode.jsonc`** (or `opencode
433
305
  }
434
306
  ```
435
307
 
436
- Add these options to your existing entry, keeping any other options. Auto-annotation
437
- is **off by default**; set `autoAnnotate` to `false` to disable it. The threshold defaults
438
- to **2,000 characters** and accepts a non-negative integer; `0` reviews every non-empty
439
- reply. It counts Unicode characters in the trimmed reply text, including Markdown and
440
- code, excluding reasoning and tool output. A reply exactly at the threshold does not open.
308
+ Add these options to your existing entry, keeping any other options. Auto-annotation is **off by default**; set `autoAnnotate` to `false` to disable it. The threshold defaults to **2,000 characters** and accepts a non-negative integer; `0` reviews every non-empty reply. It counts Unicode characters in the trimmed reply text, including Markdown and code, excluding reasoning and tool output. A reply exactly at the threshold does not open.
441
309
 
442
- After a successful turn, a new qualifying reply in the active session opens the normal
443
- reviewer once. Progress updates, failed or interrupted turns, historical replies and
444
- background sessions do not trigger it. A reply is skipped if another review is open,
445
- you switch sessions before it opens, or a new turn starts. Dismissing the reviewer or
446
- reloading the plugin does not reopen that reply. Sending remains your explicit action.
447
- OpenCode reloads saved configuration automatically; use `/reload` if needed.
310
+ After a successful turn, a new qualifying reply in the active session opens the normal reviewer once. Progress updates, failed or interrupted turns, historical replies and background sessions do not trigger it. A reply is skipped if another review is open, you switch sessions before it opens, or a new turn starts. Dismissing the reviewer or reloading the plugin does not reopen that reply. Sending remains your explicit action. OpenCode reloads saved configuration automatically; use `/reload` if needed.
448
311
 
449
312
  ### What? notes
450
313
 
451
- A `what?` note stays short in the review. When you send, the feedback adds one
452
- instruction after all the notes: explain each marked passage in plain language with more
453
- detail and a concrete example where it helps, relate it to the current task, and hold any
454
- pending action until you confirm. Change or remove that instruction in
455
- `~/.config/opencode-annotate/tui.toml`; an empty string sends the notes alone:
314
+ A `what?` note stays short in the review. When you send, the feedback adds one instruction after all the notes: explain each marked passage in plain language with more detail and a concrete example where it helps, relate it to the current task, and hold any pending action until you confirm. Change or remove that instruction in `~/.config/opencode-annotate/tui.toml`; an empty string sends the notes alone:
456
315
 
457
316
  ```toml
458
317
  [prompts]
459
318
  what = "Explain each passage marked what? in two sentences, then stop."
460
319
  ```
461
320
 
462
- If OpenCode has a skill with ID `what`, the plugin attaches it to the sent feedback, the
463
- same as mentioning `@what`. That skill can then hold pending work and ask whether to
464
- continue. Choose another skill or turn this off with the `whatSkill` plugin option:
321
+ If OpenCode has a skill with ID `what`, the plugin attaches it to the sent feedback, the same as mentioning `@what`. That skill can then hold pending work and ask whether to continue. Choose another skill or turn this off with the `whatSkill` plugin option:
465
322
 
466
323
  ```jsonc
467
324
  "options": { "whatSkill": "explain" } // or false
468
325
  ```
469
326
 
470
- A missing default `what` skill is skipped. A missing skill that you set yourself stops the
471
- send with an error and keeps the draft and `feedback.md`.
327
+ A missing default `what` skill is skipped. A missing skill that you set yourself stops the send with an error and keeps the draft and `feedback.md`.
472
328
 
473
329
  ### Reviewer binary and layout
474
330
 
475
- The bundled reviewer is selected automatically. Use `binary` only to override it with
476
- another locally built Annotate TUI executable:
331
+ The bundled reviewer is selected automatically. Use `binary` only to override it with another locally built Annotate TUI executable:
477
332
 
478
333
  ```json
479
334
  {
@@ -486,31 +341,25 @@ another locally built Annotate TUI executable:
486
341
  }
487
342
  ```
488
343
 
489
- The adapter launches Annotate TUI in the current terminal. Layout and key settings live
490
- in `~/.config/opencode-annotate/tui.toml`; font family and size belong to the terminal.
491
- The adapter supplies `PLANNOTATOR_TUI_THEME` to follow OpenCode's light/dark mode.
492
- The existing environment and annotation-field names are local protocol identifiers;
493
- they do not connect to or install another project.
344
+ The adapter launches Annotate TUI in the current terminal. Layout and key settings live in `~/.config/opencode-annotate/tui.toml`; font family and size belong to the terminal. The adapter supplies `PLANNOTATOR_TUI_THEME` to follow OpenCode's light/dark mode. The existing environment and annotation-field names are local protocol identifiers; they do not connect to or install another project.
494
345
 
495
- ## Draft recovery
346
+ <details>
347
+ <summary id="draft-recovery">Draft recovery</summary>
496
348
 
497
- Each review has its own private temporary source and annotation store. Successful,
498
- empty and cancelled reviews are cleaned up. Failures and archived notes retain the
499
- store, and a status message gives its directory.
349
+ Each review has its own private temporary source and annotation store. Successful, empty and cancelled reviews are cleaned up. Failures and archived notes retain the store, and a status message gives its directory.
500
350
 
501
- `review.json` records the session, original source and relative `snapshot` path.
502
- `feedback.md` holds exported feedback when available. To recover a retained review:
351
+ `review.json` records the session, original source and relative `snapshot` path. `feedback.md` holds exported feedback when available. To recover a retained review:
503
352
 
504
353
  ```sh
505
354
  PLANNOTATOR_DATA_DIR="<retained-directory>/data" \
506
355
  npx --package @nxxxsooo/opencode-annotate annotate-tui "<retained-directory>/<snapshot>"
507
356
  ```
508
357
 
509
- Use the `snapshot` value from `review.json`. Press `H` to restore archived notes,
510
- then `E` to copy them for pasting into OpenCode. An **E → F** archive is
511
- preserved even when `--export` reports “No annotations.”
358
+ Use the `snapshot` value from `review.json`. Press `H` to restore archived notes, then `E` to copy them for pasting into OpenCode. An **E → F** archive is preserved even when `--export` reports "No annotations."
359
+ </details>
512
360
 
513
- ## Development
361
+ <details>
362
+ <summary id="development">Development</summary>
514
363
 
515
364
  ```sh
516
365
  npm ci
@@ -521,24 +370,14 @@ npm run test:smoke
521
370
  npm run test:references
522
371
  ```
523
372
 
524
- Rust 1.96+ is needed to build from source. Unit tests use the bundled annotation/export
525
- binary, including theme inheritance tests. The optional smoke test
526
- also requires Python 3, tmux and OpenCode. It runs a detached terminal, verifies
527
- commands and feedback through the actual API, then removes its test session.
528
- Its submission uses `resume: false`, so it makes no model call or visible window.
373
+ Rust 1.96+ is needed to build from source. Unit tests use the bundled annotation/export binary, including theme inheritance tests. The optional smoke test also requires Python 3, tmux and OpenCode. It runs a detached terminal, verifies commands and feedback through the actual API, then removes its test session. Its submission uses `resume: false`, so it makes no model call or visible window.
529
374
 
530
- Set `ANNOTATE_TUI_BINARY` to test a custom binary or launcher through the plugin's
531
- real configuration path. For a build with a centered 120-column viewport, also
532
- set `ANNOTATE_EXPECT_MARGIN=10` to assert blank margins in the 140-column smoke
533
- terminal. These variables configure the test, not the shipped plugin.
375
+ Set `ANNOTATE_TUI_BINARY` to test a custom binary or launcher through the plugin's real configuration path. For a build with a centered 120-column viewport, also set `ANNOTATE_EXPECT_MARGIN=10` to assert blank margins in the 140-column smoke terminal. These variables configure the test, not the shipped plugin.
534
376
 
535
- For development loading, set the plugin entry in `opencode.json(c)` to this checkout's
536
- absolute directory, preserving its `options`, and run `/reload`. Remove any duplicate
537
- entry in `cli.json`. The older `npm run install:plugin` helper switches **only the TUI**
538
- entry in `cli.json`; use it only for TUI-only development. The reference smoke test loads
539
- both entrypoints in its own temporary location without changing your global configuration.
377
+ For development loading, set the plugin entry in `opencode.json(c)` to this checkout's absolute directory, preserving its `options`, and run `/reload`. Remove any duplicate entry in `cli.json`. The older `npm run install:plugin` helper switches **only the TUI** entry in `cli.json`; use it only for TUI-only development.
540
378
 
541
379
  See [release instructions](docs/releasing.md) and [changelog](CHANGELOG.md).
380
+ </details>
542
381
 
543
382
  ## 中文速用
544
383
 
@@ -549,7 +388,7 @@ See [release instructions](docs/releasing.md) and [changelog](CHANGELOG.md).
549
388
  - `/annotate-pick`:从最近的回复和运行中的进度说明里选一条批注。
550
389
  - `/annotate-selection`:先在会话里拖选文字,再批注包含这段文字的消息。
551
390
  - `/annotate-last`:固定批注最新一条完整回复,忽略附带参数。
552
- - `/ref`:选择并引用同项目的历史会话,可附留言;留言框随内容自动增高、换行,超长时滚动。Shift+Enter 换行,Enter 进入确认,Esc 取消。`/ref --all 关键词` 跨项目搜索;`/ref ses_…` 直接指定。确认后附加上下文,不启动空闲助手。
391
+ - `/ref`:选择并引用同项目的历史会话,可附整段评论;选择器中按 `Ctrl+A` 切换项目范围,按 `Ctrl+T` 打开 TUI 添加逐段批注;`/ref --all 关键词` 跨项目搜索;`/ref --tui 关键词` 直接进入 TUI 流程;`/ref ses_…` 直接指定。快照、评论和批注合并为一条普通用户提示,确认后继续对话;在首条消息之前(包括 OpenCode 首页,确认后才新建会话),只附加不启动助手,可多次引用后再开口。
553
392
  - `/annotate-web`:配对 Chrome;空白首页会先创建空会话,无需先发提示词。`/annotate-web 页面.html`、`/annotate-web https://…` 批注网页;`/annotate-web off` 撤销配对。
554
393
  - 选中文字 → `c` 写批注 → Enter 保存 → `q` 发送并返回。
555
394
  - 写批注中途按 `Ctrl+S`,一步保存、返回并发送(中文输入法开着也有效);`Ctrl+C` 返回后由 OpenCode 询问。
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "OpenCode Annotate",
4
- "version": "0.13.1",
4
+ "version": "0.14.0",
5
5
  "description": "Annotate HTML-based page feedback, private drafts, and paired OpenCode delivery.",
6
6
  "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp7TG2yzekNKpQvHBtj4jqkOxtoeDIBhNIjPi37Os/ksuhzPp1pHnrJPV4WV2ToatUaD5x5/SpLP8qZKLBD+wuraEE/TeclEZ8HvEs1yhlnx/S7piTG/s0eV5umuTEx2w66Hi0w3dhTC7ZZfJXCLyqs1feBtWzQx6ClgaHNYly4iJ03pV7RfguqpIaG9LV8Oa8ELA+7Ubr0BAujXrSlvqLF5oAKGoXXcpvTL5rgMRIH4Q/85tnvrk0pRVg+1z9IGNzSfjN82iveC/JAriyWABp8YuswtvKfI2Wb+KspaisBh39Y3BRqlyo8I2Cr+01uE6G5pWiJIWMLhe0glrMr5I2wIDAQAB",
7
7
  "permissions": ["activeTab", "scripting", "storage", "sidePanel", "nativeMessaging", "clipboardWrite"],
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.13.1",
3
+ "version": "0.14.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",
@@ -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
- export function createReferenceCommand(context, { promptComment }) {
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
- description: `${session.directory} · ${new Date(session.updated).toLocaleString()} · ${session.sessionID}`,
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
- const chosen = await context.ui.dialog.select({ title: "Reference a conversation", options })
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
- const allProjects = /^--all(?:\s|$)/.test(query)
48
- if (allProjects) query = query.replace(/^--all\s*/, "")
49
- const current = await context.client.session.get({ sessionID }, { signal })
50
- const sourceID = /^ses_\S+$/.test(query) ? query : await choose(current, query, allProjects, signal)
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 (!sourceID) return
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: ${current.title ?? sessionID}\n${reference.messages.length} text messages${shortened ? " (excerpt; more history available)" : ""}. Available to the next prompt; this does not start a model turn.`,
67
- label: { confirm: "Attach reference", cancel: "Cancel" },
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 context.client.session.synthetic({
72
- sessionID, id: `msg_${randomUUID().replaceAll("-", "")}`,
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 {
package/review.mjs CHANGED
@@ -188,14 +188,15 @@ export function createReviewCommand(context, options = {}) {
188
188
  // run, so keep the last one per session.
189
189
  context.renderer.on("selection", remember)
190
190
 
191
- async function start(resolve, { automatic, home = false } = {}) {
191
+ async function start(resolve, { automatic, home = false, sessionID: capturedSessionID, submission } = {}) {
192
192
  if (disposed) return
193
193
  if (automatic && (active || !automatic())) return
194
194
  if (active) return notice("An annotation is already in progress.")
195
195
  // Capture before the first await: changing tabs must never redirect a review.
196
196
  const route = context.ui.router.current()
197
- if (route.type !== "session" && !(home && route.type === "home")) return notice("Open a session first.")
198
- const sessionID = route.type === "session" ? route.sessionID : undefined
197
+ if (capturedSessionID === undefined && route.type !== "session" && !(home && route.type === "home")) return notice("Open a session first.")
198
+ // null: the submission creates its destination only after confirmation.
199
+ const sessionID = capturedSessionID === undefined ? (route.type === "session" ? route.sessionID : undefined) : capturedSessionID ?? undefined
199
200
  const controller = new AbortController()
200
201
  active = controller
201
202
  let directory
@@ -204,7 +205,7 @@ export function createReviewCommand(context, options = {}) {
204
205
  const source = await resolve({ sessionID, signal: controller.signal })
205
206
  if (controller.signal.aborted || !source) return
206
207
  if (automatic && !automatic()) return
207
- const title = context.data.session.get(sessionID)?.title ?? sessionID
208
+ const title = submission?.title ?? context.data.session.get(sessionID)?.title ?? sessionID
208
209
 
209
210
  directory = await mkdtemp(path.join(options.tempRoot ?? os.tmpdir(), "opencode-annotate-"))
210
211
  keepDraft = true
@@ -284,17 +285,17 @@ export function createReviewCommand(context, options = {}) {
284
285
  : source.selection
285
286
  ? "Here are my annotations on text I selected in this session. Please address the feedback."
286
287
  : `Here are my annotations on your ${source.progress ? "progress update" : "reply"} ${source.id}. Please address the feedback.`
287
- const text = `${subject}\n\n${feedback}`
288
+ const text = submission ? submission.text(feedback) : `${subject}\n\n${feedback}`
288
289
  const feedbackPath = path.join(directory, "feedback.md")
289
290
  await writeFile(feedbackPath, text, { mode: 0o600 })
290
291
  const count = (feedback.match(/^## Annotation /gm) ?? []).length
291
- const skills = await whatSkills(context.client, context.options.whatSkill, feedback, sessionID, controller.signal)
292
+ const skills = submission ? [] : await whatSkills(context.client, context.options.whatSkill, feedback, sessionID, controller.signal)
292
293
  const intent = await readFile(intentPath, "utf8").catch(error => {
293
294
  if (error.code === "ENOENT") return ""
294
295
  throw error
295
296
  })
296
297
  // Pressing send in the TUI is the explicit confirmation; quitting asks here.
297
- const confirmed = intent.trim() === "send" || await context.ui.dialog.confirm({
298
+ const confirmed = intent.trim() === "send" || await context.ui.dialog.confirm(submission?.confirm({ count, title }) ?? {
298
299
  title: "Send annotations?",
299
300
  message: `${source.filePath ? `Document: ${source.filePath}\n` : ""}Send ${count} ${count === 1 ? "annotation" : "annotations"} to "${title}" and let the assistant continue?`,
300
301
  label: { confirm: "Send and continue", cancel: "Cancel" },
@@ -304,16 +305,20 @@ export function createReviewCommand(context, options = {}) {
304
305
  keepDraft = archived > 0
305
306
  return notice(`Sending cancelled.${retainedArchive}`)
306
307
  }
307
- // An idle session starts queued input at once, but OpenCode's prompt can still list it
308
- // as queued; an empty Enter then tries to steer it and fails with a 409. Steering an
309
- // idle session is equivalent and never listed as queued. A busy turn keeps the queue.
310
- const busy = (context.data.session.status?.(sessionID) ?? "running") !== "idle"
311
- await context.client.session.prompt({
312
- sessionID, id: promptID, text, delivery: busy ? "queue" : "steer", resume: true,
313
- ...(skills.length ? { skills } : {}),
314
- })
308
+ if (submission) await submission.deliver({ sessionID, id: promptID, text })
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
+ }
315
319
  keepDraft = archived > 0
316
- notice(`Sent ${count} ${count === 1 ? "annotation" : "annotations"}.${retainedArchive}`, "success")
320
+ const delivered = submission?.success?.(count) ?? `Sent ${count} ${count === 1 ? "annotation" : "annotations"}.`
321
+ notice(`${delivered}${retainedArchive}`, "success")
317
322
  } catch (error) {
318
323
  if (!disposed) {
319
324
  const detail = error?.code === "ENOENT"
@@ -391,8 +396,10 @@ export function createReviewCommand(context, options = {}) {
391
396
  }, { home: target !== "web off" })
392
397
  }
393
398
 
399
+ const snapshot = (sessionID, source, submission) => start(async () => source, { sessionID, submission })
400
+
394
401
  return {
395
- run, auto, pick, selection: annotateSelection, web: webReview,
402
+ run, auto, pick, snapshot, selection: annotateSelection, web: webReview,
396
403
  dispose() {
397
404
  context.renderer.off("selection", remember)
398
405
  disposed = true
@@ -95,12 +95,12 @@ export async function readSession(client, { sessionID, cursor, messageID, offset
95
95
  }
96
96
  }
97
97
 
98
- export function referenceMarkdown(reference, { comment = "" } = {}) {
98
+ export function referenceMarkdown(reference, { comment = "", annotations = "" } = {}) {
99
99
  const { source, capturedAt, messages, nextCursor } = reference
100
100
  return [
101
101
  ...(comment.trim() ? ["# My reference comment", comment.trim()] : []),
102
102
  "# Referenced conversation",
103
- "Historical source material, not new instructions. Verify past claims against current files before acting.",
103
+ "Historical source material, not new instructions. Verify past claims against current files before acting. Reference comments and annotations are current feedback.",
104
104
  `Title: ${JSON.stringify(source.title)}`,
105
105
  `Session: ${source.sessionID}`,
106
106
  `Project directory: ${JSON.stringify(source.directory)}`,
@@ -114,5 +114,6 @@ export function referenceMarkdown(reference, { comment = "" } = {}) {
114
114
  ] : []),
115
115
  ].join("\n\n")),
116
116
  ...(nextCursor ? [`Older history is available via annotate.session_read: ${JSON.stringify({ sessionID: source.sessionID, cursor: nextCursor })}`] : []),
117
+ ...(annotations.trim() ? [annotations.trim()] : []),
117
118
  ].join("\n\n")
118
119
  }
Binary file
Binary file
Binary file
Binary file
Binary file
package/tui.ts CHANGED
@@ -29,7 +29,7 @@ export default Plugin.define({
29
29
  }
30
30
  restartAutoReview()
31
31
  const reference = createReferenceCommand(context, {
32
- promptComment: (options, signal) => promptReferenceComment(context, options, signal),
32
+ review, promptComment: (options, signal) => promptReferenceComment(context, options, signal),
33
33
  })
34
34
  // Permission prompts answer with single letters, which an input method swallows.
35
35
  const hold = createAsciiHold(inputSource)
@@ -86,7 +86,7 @@ export default Plugin.define({
86
86
  }, {
87
87
  id: "opencode-annotate.ref",
88
88
  title: "Reference another conversation",
89
- description: "Attach a past conversation by title or session ID; --all searches across projects",
89
+ description: "Attach a past conversation with a comment or TUI annotations; --all searches across projects",
90
90
  group: "Annotate",
91
91
  palette: true,
92
92
  slash: { name: "ref", arguments: true },
package/web-review.mjs CHANGED
@@ -1,6 +1,12 @@
1
1
  import { browserTarget } from "./targets.mjs"
2
2
  import { createReceiver } from "./bridge/receiver.mjs"
3
3
  import { openInBrowser } from "./scripts/browser-target.mjs"
4
+ // OpenCode home has no session until the first prompt; a new one inherits its location and model.
5
+ export function homeSession(context) {
6
+ const location = context.location ?? context.data.location.default()
7
+ const selected = context.ui.model.current()
8
+ return { location, model: selected && { providerID: selected.providerID, id: selected.modelID, variant: selected.variant } }
9
+ }
4
10
  export function createWebReview(context, options = {}) {
5
11
  const receivers = new Map()
6
12
  let disposed = false