@plannotator/ui 0.50.0 → 0.51.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.
Files changed (53) hide show
  1. package/HANDOFF.md +144 -11
  2. package/components/AISettingsTab.tsx +32 -0
  3. package/components/AgentToolAnnouncementDialog.tsx +347 -0
  4. package/components/AgentsTab.tsx +9 -9
  5. package/components/AskSessionAnnouncementDialog.tsx +329 -0
  6. package/components/CommentPopover.tsx +32 -18
  7. package/components/DecisionControl.tsx +2 -7
  8. package/components/DiagramBlock.tsx +46 -4
  9. package/components/DocBadges.tsx +12 -8
  10. package/components/PlanHeaderMenu.tsx +1 -1
  11. package/components/Settings.tsx +73 -1
  12. package/components/TerminalToolsAnnouncementDialog.tsx +1 -1
  13. package/components/Viewer.tsx +4 -0
  14. package/components/ai/AIProviderBar.tsx +18 -1
  15. package/components/ai/DocumentAIChatPanel.tsx +4 -9
  16. package/components/ai/SessionAskNotice.tsx +33 -21
  17. package/components/blocks/QuestionBlock.tsx +24 -19
  18. package/components/blocks/QuestionContext.tsx +81 -0
  19. package/components/diagram/DiagramComposer.tsx +54 -3
  20. package/components/diagram/DiagramViewer.tsx +31 -2
  21. package/components/diagram/index.ts +1 -1
  22. package/components/html-viewer/HtmlViewer.tsx +13 -3
  23. package/components/html-viewer/bridge-script.asset.js +124 -8
  24. package/components/html-viewer/bridge-script.ts +124 -8
  25. package/components/html-viewer/useHtmlAnnotation.ts +36 -55
  26. package/hooks/useAIChat.ts +26 -5
  27. package/hooks/useAIProviderActivation.ts +13 -0
  28. package/hooks/useAIProviderConfig.ts +3 -3
  29. package/hooks/useActiveSection.ts +3 -2
  30. package/hooks/useAgentToolSetting.ts +33 -0
  31. package/hooks/useAnnotationDraft.ts +53 -7
  32. package/hooks/useAnnotationHighlighter.ts +101 -5
  33. package/hooks/useExternalAnnotations.ts +21 -1
  34. package/hooks/useFirstRunAnnouncementWindow.ts +114 -0
  35. package/hooks/useLatchedTrue.ts +15 -0
  36. package/hooks/useLinkedDoc.ts +64 -4
  37. package/hooks/useModelCatalogs.ts +9 -2
  38. package/package.json +2 -2
  39. package/styles.css +1 -1
  40. package/themes/gruvbox.css +6 -0
  41. package/types.ts +13 -0
  42. package/utils/agentClosed.ts +33 -0
  43. package/utils/agentToolAnnouncement.ts +109 -0
  44. package/utils/agentToolSetting.ts +108 -0
  45. package/utils/aiProvider.ts +13 -40
  46. package/utils/annotationOwnsHighlight.ts +27 -0
  47. package/utils/annotationScope.ts +15 -0
  48. package/utils/askSessionAnnouncement.ts +107 -0
  49. package/utils/blockTargeting.ts +61 -2
  50. package/utils/diagramAskAI.ts +161 -0
  51. package/utils/parser.ts +236 -110
  52. package/utils/questionAnswers.ts +3 -1
  53. package/utils/quickLabels.ts +2 -2
package/HANDOFF.md CHANGED
@@ -95,7 +95,7 @@ Pass any subset of these to `configurePlannotatorUI({ ... })`. Anything omitted
95
95
  | `mathRendererLoader` | `() => Promise<MathRenderer>` | How KaTeX is loaded when no renderer is registered before the first math node renders (see "Lazy renderers and eager entries"). Once registered, the package default is never called, not even as a fallback after a rejected load, and `resetMathRenderer()` keeps the registration (0.34.0); a default load already in flight at registration still fills the slot (pre-existing, see `setMathRendererLoader`), so register before the first math render | `utils/math-default-loader`'s `import('katex')`, JS only; CSS stays yours |
96
96
  | `identityGenerator` | `() => string` | The synchronous generator behind the default "tater" display name when no `identityProvider` is installed | A built-in 16 x 16 word pool of the same `adjective-noun-tater` shape; Plannotator registers the full dictionary via `utils/identity-tater` |
97
97
  | `alertIconRenderer` | `(name: string) => ReactNode | null` | The icon rendered for a GitHub alert whose title line carries `<!-- icon: name -->` (0.38.0; grammar in `utils/alertTitle`). Called only for a title line with an icon comment and no leading emoji; a null return falls back to the type icon | `null` for every name: the type's own icon, the package bundles no icon set |
98
- | `fenceTheme` | `(colorTheme: string, mode: 'light' \| 'dark') => string \| undefined` | The Shiki theme every fence-style surface renders in (Viewer fences, `CodeBlock`, the code-file hover preview, the plan diff view, code review suggestion snippets: everything that reads `useFenceTheme` / `resolveFenceTheme`). Return a theme name to use it, `undefined` to keep the default for that (palette, mode); a throw or an empty string also falls through, and a name Shiki does not know renders the block as plain text. Install it before the first render; it is read on every render, so a later change applies the next time a fence re-renders. The code-review diff pane's dark/light pair (`resolveSyntaxTheme`) is not affected. Also `setFenceThemeResolver` / `resetFenceThemeResolver` on `utils/syntaxTheme` (unreleased) | The palette's `SHIKI_THEME_MAP` entry, else `pierre-dark` / `pierre-light`. Replaces mutating the exported `SHIKI_THEME_MAP`, which keeps working but is not a supported seam |
98
+ | `fenceTheme` | `(colorTheme: string, mode: 'light' \| 'dark') => string \| undefined` | The Shiki theme every fence-style surface renders in (Viewer fences, `CodeBlock`, the code-file hover preview, the plan diff view, code review suggestion snippets: everything that reads `useFenceTheme` / `resolveFenceTheme`). Return a theme name to use it, `undefined` to keep the default for that (palette, mode); a throw or an empty string also falls through, and a name Shiki does not know renders the block as plain text. Install it before the first render; it is read on every render, so a later change applies the next time a fence re-renders. The code-review diff pane's dark/light pair (`resolveSyntaxTheme`) is not affected. Also `setFenceThemeResolver` / `resetFenceThemeResolver` on `utils/syntaxTheme` (0.50.0) | The palette's `SHIKI_THEME_MAP` entry, else `pierre-dark` / `pierre-light`. Replaces mutating the exported `SHIKI_THEME_MAP`, which keeps working but is not a supported seam |
99
99
 
100
100
  ### Interface details worth knowing
101
101
 
@@ -109,7 +109,7 @@ Pass any subset of these to `configurePlannotatorUI({ ... })`. Anything omitted
109
109
 
110
110
  **`UploadTransport`** — `upload(file: File): Promise<{ path: string; originalName? }>`. The default does Plannotator's `POST /api/upload` and returns the server path. For Workspaces, send the bytes to your asset API (`PUT /v1/workspaces/:wsId/assets/:assetPath`) and return the content-addressed URL (or an opaque ref) in `path`. Notes from the Workspaces asset layer: your API makes the **caller choose the asset path** and 409s if a document owns it, so your adapter — not the UI — owns path selection (namespace uploads, e.g. an `assets/` prefix); it enforces a **10 MiB cap + content-type allowlist**, so surface upload failures; and because asset URLs need **no signing** (content-addressed, served from the cookieless `tot.page` origin), `imageSrcResolver` can be a pass-through — returning a full URL in `path` renders directly (the default resolver passes http(s) URLs through).
111
111
 
112
- **`DraftTransport`** — `load()`, `save(body, { keepalive })`, `remove(generation, { keepalive })`. The generation-gated tombstone and keepalive retry logic stay inside the hook; you only provide the three transport calls. `keepalive: true` means "best-effort deliver this even though the page is closing" (maps to `fetch(..., { keepalive: true })` or `navigator.sendBeacon`). One non-obvious contract on `load()`: it returns `{ data, generation }`, where `generation` is the **deletion tombstone counter** for the no-draft case — Plannotator's server encodes it in the 404 body so a stale tab can't resurrect a deleted draft. If your backend tracks draft deletions, return the tombstone generation with `data: null`; if it doesn't, return `{ data, generation: null }` and the hook still works (you just lose stale-tab deletion protection).
112
+ **`DraftTransport`** — `load()`, `save(body, { keepalive })`, `remove(generation, { keepalive })`. The generation-gated tombstone and keepalive retry logic stay inside the hook; you only provide the three transport calls. `keepalive: true` means "best-effort deliver this even though the page is closing" (maps to `fetch(..., { keepalive: true })` or `navigator.sendBeacon`). One non-obvious contract on `load()`: it returns `{ data, generation }`, where `generation` is the **deletion tombstone counter** for the no-draft case — Plannotator's server encodes it in the 404 body so a stale tab can't resurrect a deleted draft. If your backend tracks draft deletions, return the tombstone generation with `data: null`; if it doesn't, return `{ data, generation: null }` and the hook still works (you just lose stale-tab deletion protection). Optionally, `save()` may resolve `{ staleGeneration }` when your store refused the body as stale (Plannotator's server answers `409 { draftGeneration }`); the hook then raises its counter above that generation and saves once more. Resolving nothing (the old `Promise<void>`) keeps the previous behavior.
113
113
 
114
114
  **`ExternalAnnotationTransport<T>`** — `subscribe(onEvent, onError) => unsubscribe`, `getSnapshot(since) => { annotations, version } | null` (return `null` for "no changes", i.e. the 304 case), plus `add/remove/update/clear`. For Workspaces this is your realtime layer — a Durable Object WebSocket or SSE fanning out comment events. `T` extends `{ id: string; source?: string }`; if your annotation type adds fields, call `setExternalAnnotationTransport<YourType>()` directly for full type safety (the `configure` front door pins the base type for ergonomics).
115
115
 
@@ -1636,25 +1636,91 @@ Additive. What a host that keeps question answers ITSELF needs (Workspaces store
1636
1636
 
1637
1637
  Not here (dropped with the owner's Q2 answer): record lines inside the block (`Other:`, `Answer:`, `Note:`, `Answered:`) and a `writeQuestionAnswer` byte rewriter.
1638
1638
 
1639
- ## Fence theme seam and srcdoc frame height (unreleased)
1639
+ ## Fence theme seam and srcdoc frame height (0.50.0)
1640
1640
 
1641
1641
  Additive; Plannotator passes nothing, so its output is unchanged.
1642
1642
 
1643
1643
  - **`fenceTheme` on `configurePlannotatorUI`** (row in the seam catalog above; `FenceThemeResolver` type exported from `configure` and `utils/syntaxTheme`). Hosts that mutated `SHIKI_THEME_MAP` to pick their own code colors should move to it.
1644
1644
  - **`HtmlViewer` frame height.** The bridge measured `document.body.scrollHeight`, which leaves out a first child's top margin (and a last child's bottom margin) that collapses through a margin-less body, so a page like `body{margin:0}` + a card with `margin-top` was cut short by its margins. It now measures body's box in document coordinates plus the bottom margins that can collapse through it (`measureContentHeight` in `bridge-script.ts`). It deliberately does not use `documentElement.scrollHeight`: that never drops below the frame's own viewport (and an `html{height:100%}` root is the frame's height), so the frame could grow but never shrink. Content sized by the frame itself (`html,body{height:100%}`, `min-height:100vh`, a `100vh` section) plus a margin around it always measures taller than the frame, so a feedback guard (`nextResizeHeight`) stops growing when the first measure after a grow the parent applied still overflows by as much as before: such a page settles one or two grows above its old height (e.g. 600 → 640) instead of growing forever, and a later content change still resizes the frame. Absolutely positioned content whose containing block is the root (not body) is still not measured, as before. No `BRIDGE_PROTOCOL_VERSION` bump: the `resize` message shape is unchanged, only the value is more accurate, so a cached older asset keeps the old measure and nothing misreads.
1645
1645
 
1646
- ## Ask this session (unreleased)
1646
+ ## Ask this session (shipped in 0.50.0; bridge-only change in 0.51.0, BREAKING for 0.50.0 consumers)
1647
1647
 
1648
- Additive. Ask AI can be answered by the agent session that opened Plannotator ("Ask this session"), when the server registers a `session-bridge` provider (Pi review/annotate/last and plan review today). A host whose backend never advertises one sees the same provider list, default selection, requests and DOM as before, and has nothing to pass.
1648
+ Ask AI can be answered by the agent session that opened Plannotator ("Ask this session"), when the server registers a `session-bridge` provider. A host whose backend never advertises one sees the same provider list, default selection, requests and DOM as before, and has nothing to pass.
1649
1649
 
1650
- - **`utils/aiProvider`:** `AIProviderOption` gains optional `label` and `sessionBridge` (`{ host, status, modes }`), read from `/api/ai/capabilities`. `resolveAIProviderSelection` prefers a usable bridge (present, not `gone`, not `blocked` without a transient mode) after an explicit saved pick and before the origin's SDK provider; with no bridge in the list the order is unchanged. New exports: `SESSION_BRIDGE_PROVIDER_NAME`, `SESSION_ASK_ERROR_CODES`, `isSessionBridgeProvider`, `findUsableSessionBridge`, `resolveSessionBridgeFallback`.
1651
- - **`hooks/useAIChat`:** `AskAIParams.busyPolicy?: 'wait' | 'interrupt'` (sent on `/api/ai/query` only when set), `retry(questionId, AIRetryOptions)`, and `AIResponse.errorCode` / `status` (`'waiting' | 'interrupting'`).
1652
- - **`hooks/useAIProviderConfig`:** `applyConfigChange(config, { persist: false })` selects a provider for this page without writing the cookie.
1653
- - **`components/ai/SessionAskNotice`** (new): `SessionAskStatus`, `SessionAskActions`, `sessionAskErrorTone`. `DocumentAIChatPanel` takes optional `onSessionAskAction` and `sessionAskFallbackLabel`; without them it renders as before.
1654
- - **`components/ProviderIcons`:** `getProviderMeta(name, label?)`; a server-sent label overrides the name lookup.
1650
+ As shipped in 0.50.0 the bridge sat beside the SDK providers: an explicit saved pick won over it, and a gone or blocked session offered "Ask a separate AI instead". **ui 0.51.0 makes the bridge the ONLY Ask AI choice** (Plannotator's servers now register nothing else for Ask AI while a bridge is present):
1651
+
1652
+ - **`utils/aiProvider`:** `resolveAIProviderSelection` selects a bridge in the list in every status (ready, busy, blocked, gone), ahead of any saved pick; the saved cookies are not rewritten, and with no bridge in the list the order is unchanged. New export `findSessionBridge(providers)`. Kept from 0.50.0: `AIProviderOption.label` / `sessionBridge`, `SESSION_BRIDGE_PROVIDER_NAME`, `SESSION_ASK_ERROR_CODES`, `isSessionBridgeProvider`.
1653
+ - **`components/ai/SessionAskNotice`:** `SessionAskActions` keeps the busy actions ("Ask when it finishes" / "Interrupt and ask now", rendered only with `onAction`); for a gone or blocked session it renders a plain note (`[data-session-ask-unreachable]`, with or without `onAction`) instead of a fallback button.
1654
+ - **Pickers:** with a bridge in the list, `AIProviderBar` renders only the bridge label (`[data-ai-provider-session-bridge]`, no `<select>`), and `AISettingsTab` shows the bridge read-only and writes nothing.
1655
+ - **`hooks/useAIProviderActivation`:** additive. New optional `providers?: ReadonlyArray<{ id }>` option, the Ask AI providers the server currently lists: an id not in it is never activated (at page load a saved id such as `codex-sdk` can sit in the selection for one render before the resolver moves it to the bridge, and activating it would start model discovery Ask AI does not offer). Omitted keeps the old behavior.
1656
+ - **`hooks/useModelCatalogs`:** additive. The launchers' catalog loader also reads `catalogProviders` from `/api/ai/capabilities?activate=<id>`, which a bridged Plannotator server uses to report the Claude / Codex catalogs without listing those providers for Ask AI. A backend that never sends the field behaves as before.
1657
+
1658
+ **Removed (BREAKING for consumers of 0.50.0):**
1659
+
1660
+ | Removed | Use instead |
1661
+ | --- | --- |
1662
+ | `findUsableSessionBridge` (`utils/aiProvider`) | `findSessionBridge`; the bridge is selected whatever its status |
1663
+ | `resolveSessionBridgeFallback` (`utils/aiProvider`) | nothing: there is no other Ask AI provider while a bridge is present |
1664
+ | `'fallback'` member of `SessionAskAction` (`components/ai/SessionAskNotice`) | nothing: it is now `'wait' \| 'interrupt'` |
1665
+ | `fallbackLabel` prop of `SessionAskActions` | nothing: gone/blocked render the note |
1666
+ | `sessionAskFallbackLabel` prop of `DocumentAIChatPanel` | nothing |
1667
+
1668
+ Unchanged from 0.50.0: `hooks/useAIChat` (`AskAIParams.busyPolicy`, `retry(questionId, AIRetryOptions)`, `AIResponse.errorCode` / `status`; `AIRetryOptions.providerId` still exists for hosts that offer another provider), `hooks/useAIProviderConfig`'s `applyConfigChange(config, { persist: false })`, and `components/ProviderIcons`' `getProviderMeta(name, label?)`.
1669
+
1670
+ Also in 0.51.0 (#1703, additive): an answer the session stopped because another message took its turn over arrives as the error code `session_taken_over` (`SESSION_ASK_ERROR_CODES.takenOver`). `useAIChat` no longer treats it as an error: the streamed text stays, `AIResponse.notice` carries the server's note, `error` stays unset, and `DocumentAIChatPanel` renders the note under the answer through the new `SessionAskNote` (`components/ai/SessionAskNotice`, `[data-session-ask-note="taken-over"]`). A backend that never sends the code sees no change.
1671
+
1672
+ ## Questions, restore, drafts and the rest (ui 0.51.0, core 0.25.11)
1673
+
1674
+ Everything host-facing that changed between ui 0.50.0 / core 0.25.10 and this pair, apart from the three sections above (Ask this session, composer trim, diagram Ask AI). Plannotator's own app needs nothing; a host that passes nothing new gets the fixes below and the noted behavior changes.
1675
+
1676
+ **Question cards (#1683, #1699, #1702).**
1677
+
1678
+ - **Pinpoint inside a card targets what was clicked (#1683).** The card (`fieldset.question-block`) is now one block target whose prompt, context and each choice's text are child targets, marked `data-question-part="prompt" | "context" | "choice"`. Before, every pinpoint hover or click in a card resolved to the prompt. Clicking the radio/checkbox still answers.
1679
+ - **Plain-bullet choices keep their wrapped lines (#1699, core).** A `:::question` / `:::question-multi` with no task-list items reads each plain bullet the way CommonMark reads a list item (indented lines, lazy lines, an indented paragraph after a blank line), and those lines no longer leak into `context`. A bullet written `- **Name:** prose` (bold name set off by punctuation, `**` only) takes `Name` as its label and the prose as its description; a label longer than `MAX_QUESTION_CHOICE_LABEL_CHARS` (200) is cut at its first sentence, the rest leading the description; two bullets never end up with the same label. A `Recommended:` line continues onto the next line only when that line wraps the same sentence. **Task-list choices (`- [ ]`) parse exactly as before**, and `questionKey` does not change.
1680
+ - **Behavior change for hosts that store answers themselves:** the labels of PLAIN-BULLET choices can differ from what core 0.25.10 produced (the wrapped text joins the label, or a bold lead becomes the label). An answer stores the labels it picked, so core 0.25.11 adds **`QuestionChoice.aliases?: string[]`** (the older names of a plain-bullet choice: its full text, its first line, that line's earlier label) and **`canonicalQuestionAnswer(question, answer)`** (`@plannotator/core/question-block`), which maps a stored label that names exactly one choice by an alias to its current label and returns the same object when nothing maps; an ambiguous label stays as stored. `QuestionBlock`, the Questions panel rows (`utils/questionAnswers`), WebMCP `read_document` and `formatQuestionAnswersSection` all read answers through it, so a host that renders `QuestionBlock` with its stored answer sees the right pick without changes. **A host that reads stored answers on its own (turning an answer into a decision, its own export) should run them through `canonicalQuestionAnswer` too.** `QuestionExportItem` gains an optional `choices` (label + aliases) so the export prints current labels.
1681
+ - **Context renders with the document's block renderers (#1699).** A card's context goes through `parseMarkdownToBlocks` + `BlockRenderer` (new `components/blocks/QuestionContext`), so tables, lists, fences, quotes, headings and images look as they do in the document. Those blocks carry no `data-block-id`. Its styles are a `<style href="plannotator-question-context" precedence="default">` that React 19 hoists into `<head>` once, so a host needs no Tailwind change. `useActiveSection` observes only headings that have a block id, so a heading inside a card never stalls the table of contents.
1682
+
1683
+ **Restore after an edit (#1717).**
1684
+
1685
+ - **`AnnotationRestoreReport.moved?: RestoredAnchor[]`** (`hooks/useAnnotationHighlighter`, additive): when a restore re-anchors comments by their text after the document changed, each comment whose stored `blockId` no longer holds its text is listed with `{ id, blockId, startOffset?, positionsStale }`, where `blockId` is the block the highlight landed in or `''` when the text is gone, and `positionsStale` says the stored `startMeta`/`endMeta` should be dropped. An unchanged document reports nothing here. **A host that derives line numbers from `blockId` (an export, a gutter) should write these back**; Plannotator does so in `packages/editor/restoredAnchors.ts`. A restore that paints nothing is now reported unanchored even when there were no stored positions to try.
1686
+ - **`utils/annotationOwnsHighlight`** (new): `annotationOwnsHighlight(annotation)` is false for diff-view comments, general comments, checkbox toggles (`CHECKBOX_ANNOTATION_PREFIX`) and question answers, which the text highlighter never draws. The highlighter skips them itself; a host that re-applies a stored list through `ViewerHandle.applySharedAnnotations` should filter with it, as `useLinkedDoc` now does, or those rows come back unanchored.
1687
+
1688
+ **Drafts (#1710).** `DraftTransport.save` may now resolve `{ staleGeneration }` (`DraftSaveRefused`, `hooks/useAnnotationDraft`) when the store refused the body as stale; the hook raises its counter above that generation and saves once more. Resolving nothing (the old `Promise<void>`) keeps the old behavior, so a host transport needs no change. Also documented in the seam catalog above. The hook's return value gains `flushPendingSave()`, which sends a pending debounced save now. Plannotator's DEFAULT transport now reads a `409 { draftGeneration }` as that refusal (never when the body says `decided: true`).
1689
+
1690
+ **The agent closes a review (#1709).** `ExternalAnnotationEvent` (`@plannotator/core/external-annotation`) gains a member that is not an annotation change: `{ type: "session-closed"; by: "agent"; unsentAnnotations: number }`. `useExternalAnnotations` takes an optional `onSessionClosed({ unsentAnnotations })` and calls it when the stream delivers that event (the polling fallback never does). A host transport that never emits it is unaffected. **A host with an exhaustive `switch` over `ExternalAnnotationEvent['type']` (a `never` check) must add the case.** `utils/agentClosed` (new) holds the copy Plannotator shows (`AGENT_CLOSED_TITLE`, `agentClosedSubtitle(count, surface)`).
1691
+
1692
+ **HTML pinpoints and exports (#1694, #1700).**
1693
+
1694
+ - A text-less pinpoint's quote (`originalText`) now names the element, not just its kind: `[element: Image "Team photo" (team.jpg)]` instead of `[element: Image]` (hover label, accessible name, and for media the scrubbed file name). Restore never reads the quote, so older pins keep restoring.
1695
+ - `HtmlElementContext.sourceName?` (ui `types` and core `html-anchor`, additive, validated by `parseHtmlElementContext`): the file a media element shows, resolved by the bridge the same way the quote names it. The export heading reads it, falling back to the `src` attribute for older contexts. Core exports the shed order as `ELEMENT_CONTEXT_SHED_ORDER`; `sourceName` is shed last.
1696
+ - Ask AI from an HTML pinpoint composer sends the element's identity: `CommentAskAIContext.detail?` / `AIQuestion.scope.detail?` (additive), built by the new `elementIdentityForAskAI(targets)` (`utils/parser`), which `buildDefaultPrompt` appends under "Selected element:". It is not shown in the chat.
1697
+ - Export order: comments made in the plan/version diff view (`blockId` `diff-block-N`) now print AFTER the document's other comments, in diff order (they printed first). A list with no diff comments sorts exactly as before.
1698
+
1699
+ **Linked documents and several-file reviews (#1696, #1718).**
1700
+
1701
+ - `useLinkedDoc` gains `getFeedbackDocuments()` → `FeedbackDocuments { root, documents }`: the root once and every other document once. `getDocAnnotations()` also carries the active document's live state (for counts), so an export that used it beside the host's own live annotations printed the open document twice. Export from `getFeedbackDocuments()`.
1702
+ - `exportLinkedDocAnnotations(docAnnotations, heading?)` takes an optional heading (`LINKED_DOC_EXPORT_HEADING` default, `FOLDER_DOC_EXPORT_HEADING`, `BUNDLE_DOC_EXPORT_HEADING`) and renders every document through the same entry renderer as `exportAnnotations`: document order, `[In diff content]`, quick labels with their tip and Label Summary, threaded replies. Plain comment, deletion and global output is unchanged.
1703
+ - `groupAnnotationsByDocument` / `buildAnnotationDocumentGroups` (`utils/annotationScope`) take an optional fixed `order` of paths. `DocBadges`' `linkedDocInfo.onBack` is optional (absent: no Close pill). `PlanHeaderMenu` item ids gain `'bundle-previous' | 'bundle-next'`. Core: `AnnotateAgentTerminalMode` gains `"annotate-bundle"` (and `supportsAnnotateAgentTerminalMode` accepts it; the type already includes `string`, so no `never` switch over it can break); `AnnotateContext.bundlePosition?: { index, total }`.
1704
+
1705
+ **Agent tool switch and offer (#1725, ui only).** Additive; a host whose server never sends the fields sees no row and no offer.
1706
+
1707
+ - **`Settings`** takes optional `agentToolSetting?: AgentToolSetting` and `onAgentToolChange?: (enabled: boolean) => Promise<void>`. Only when BOTH are passed does General render the row `[data-agent-tool-setting="<host>"]` ("Let the agent open reviews (plannotator tool)"). A rejected `onAgentToolChange` shows its message in `[data-agent-tool-setting-error]`; the switch is disabled when `setting.env` is set (`PLANNOTATOR_AGENT_TOOL` decides).
1708
+ - **`utils/agentToolSetting`** (new): `AgentToolHost` (`'claude-code' | 'pi' | 'opencode'`), `AgentToolSetting` (`host`, `enabled`, `configured`, `env?`), `parseAgentToolSetting(serverConfig)`, `withSavedAgentTool(setting, value)`, `saveAgentToolSetting(value, fetchImpl?)` (POST `/api/config` `{ agentTool }`, rejects with a readable message unless the server confirms), and the copy helpers `agentToolHostName`, `agentToolAppliesWhen`, `agentToolCostNote`. `parseAgentToolSetting` returns `undefined` unless the server config carries `agentToolHost` and a boolean `agentToolEnabled`, so a Workspaces-style backend gets nothing to render.
1709
+ - **`hooks/useAgentToolSetting`** (new): `{ setting, adopt(serverConfig), save(enabled) }`, the shared state the Settings row and the offer read: `adopt` takes the fields from a `/api/plan` or `/api/diff` `serverConfig`, `save` calls `saveAgentToolSetting` and then `withSavedAgentTool`.
1710
+ - **`utils/agentToolAnnouncement`** (new, cookie gate for the one-time offer: `needsAgentToolAnnouncement`, `markAgentToolAnnouncementSeen`, `agentToolAnnouncementPendingThisLoad`, `agentToolOfferApplies`, `agentToolOfferHostOf`, `agentToolAnnouncementEligible`) and **`components/AgentToolAnnouncementDialog`** (new): the one-time offer to turn the tool on, shown on Pi and OpenCode 2. Nothing in the library mounts it; Plannotator's apps do.
1711
+
1712
+ **Internal exports, deliberately not supported.** `XMark` (`components/TerminalToolsAnnouncementDialog`, exported in #1690 so the announcement dialogs share one close icon) and `hooks/useLatchedTrue` (#1725, the apps' "an announcement was shown on this load" latch) are exported only so Plannotator's own components and apps can share them. They are not seams, carry no compatibility promise, and may change or move in any release; a host should not import them.
1713
+
1714
+ **Smaller changes.**
1715
+
1716
+ - **`DecisionControl` / `DecisionNoteDialog` (#1711):** the keyboard hint under the decision note composer is gone; keys unchanged.
1717
+ - **Pi thinking levels (#1704):** core `model-catalog` adds `PI_THINKING_LEVELS`, `PI_SESSION_SCOPED_THINKING_VERSION`, `piThinkingLevelsSupported`, `piSupportedThinkingLevels`, `piCatalogFromRpc`, `PiRpcModel`, and an `off` entry in `EFFORT_LABELS`. `AgentsTab`'s `PI_THINKING` is now derived from them (same values and labels as before).
1718
+ - **"Ask this session" announcement (#1690):** new `components/AskSessionAnnouncementDialog`, `utils/askSessionAnnouncement` (cookie `plannotator-announce-ask-session-seen`) and `hooks/useFirstRunAnnouncementWindow`. Plannotator's apps mount it; nothing in the library mounts it for a host.
1719
+ - **gruvbox palette (#1721):** sets `--diffs-addition-color-override` (dark `#b8bb26`, light `#79740e`), so added diff lines draw in gruvbox green instead of the text colour. This changed the guides.show viewer stylesheet (see "Publishing & versioning").
1655
1720
 
1656
1721
  ## Publishing & versioning
1657
1722
 
1723
+ - **core 0.25.11 / ui 0.51.0: both change. Order: guides.show deploy, then `core` 0.25.11, then `ui` 0.51.0.** ui imports `canonicalQuestionAnswer` and `PI_THINKING_LEVELS`, which no published core before 0.25.11 has, and pins core `0.25.11` exactly. core 0.25.11 pins a new guides.show viewer stylesheet (`viewer.DuqkfIUz.css`, from the gruvbox fix #1721; the viewer JS `viewer.BYGvfCcj.js` is unchanged), which guides.show serves only after a deploy, so run the deploy by hand first (next bullet). **ui 0.51.0 is BREAKING for 0.50.0 consumers of the "Ask this session" exports**: it removes `findUsableSessionBridge`, `resolveSessionBridgeFallback`, the `'fallback'` `SessionAskAction` member, `SessionAskActions`' `fallbackLabel` and `DocumentAIChatPanel`'s `sessionAskFallbackLabel`, and makes a listed bridge the only Ask AI selection. Release notes must say so. Everything else is additive or a fix (including #1725's agent tool switch and offer); see "Ask this session (shipped in 0.50.0; …)", "Comment composer trim (0.51.0; …)", "Ask AI from a diagram comment (0.51.0; …)" and "Questions, restore, drafts and the rest (ui 0.51.0, core 0.25.11)".
1658
1724
  - **guides.show before a core publish that moves the viewer pin.** guides.show deploys on Plannotator release tags only. When a core publish carries a new `guide-viewer-manifest` hash (any change to the shared CSS or the guide chain) and no release tag has shipped it yet, run the deploy by hand first (`gh workflow run guides-show-deploy.yml --ref main`), then check that `curl -I https://guides.show/v1/<css>` and `<js>` from the manifest answer 200. Otherwise every host's guide pages load without that asset (core 0.25.9 hit this; fixed by a manual deploy). The deploy is add-only.
1659
1725
  - **core 0.25.9 / ui 0.49.0 (question host seams): both change. Publish `core` first**: ui imports the new `@plannotator/core/markdown-structure` subpath and the new `findQuestionBlocks` / decision fields, so a ui on a published core 0.25.8 fails to compile in a consumer. See "Question host seams (ui 0.49.0, core 0.25.9)".
1660
1726
  - **core 0.25.8 / ui 0.48.0 (questions in documents): both change. Publish `core` 0.25.8 first, then `ui` 0.48.0**, which pins core `0.25.8` exactly and imports the new `@plannotator/core/question-block` subpath. Core is a patch bump because its change is additive and pre-1.0 caret ranges would not accept a minor. See "Questions in documents (0.48.0, core 0.25.8)".
@@ -1700,7 +1766,7 @@ unaffected by the prop. Purely additive: no export, share or archive change.
1700
1766
 
1701
1767
  ---
1702
1768
 
1703
- ## Diff file tree (next ui release; no core change)
1769
+ ## Diff file tree (0.50.0; no core change)
1704
1770
 
1705
1771
  Asked for by a host that shows a read-only per-file diff list (one Pierre
1706
1772
  `FileDiff` per file) and wants Plannotator's file tree beside it. The tree used
@@ -1745,6 +1811,73 @@ this branch with the same static patch (merged chains, A/D/R/M marks, nested
1745
1811
  folders), at rest, after two `j` presses and after collapsing a folder: the
1746
1812
  sidebar screenshots and its `outerHTML` were byte-identical.
1747
1813
 
1814
+ ## Comment composer trim (0.51.0; not breaking)
1815
+
1816
+ The visible submit hint added noise and is gone from `components/CommentPopover`.
1817
+ The composer's one-click thumbs-up was removed in the same change and then
1818
+ brought back before any release, so hosts see no API change for it.
1819
+
1820
+ - **Submit hint text removed** from both composer footers (popover and
1821
+ dialog): the `⌘↵` / `Ctrl+Enter` label no longer renders. The keyboard
1822
+ behavior is unchanged: `Mod+Enter` still saves.
1823
+ - **`onQuickLookGood` stays** on `CommentPopover` (published in 0.32.0), with
1824
+ the same contract: optional, absent renders nothing, the parent owns
1825
+ creation and closing, disabled once anything is typed or attached. Only its
1826
+ look changed: it is now an emoji-only 👍 button beside Save (no "Looks
1827
+ good" text), named "Looks good" through `aria-label` and its tooltip, marked
1828
+ `data-quick-look-good`. It takes no key; `Mod+Enter` still saves. Like
1829
+ Save, a click clears the `draftKey` draft and returns focus to the opener.
1830
+ Its classes are all ones the pinned guides.show viewer CSS already has (the
1831
+ disabled grey-out is an inline filter), so it does not change that bundle.
1832
+ Why it is
1833
+ needed: a pinpoint click on an HTML / live-app element opens this composer
1834
+ directly and never shows the selection toolbar, so without it an element
1835
+ cannot get a one-click thumbs-up.
1836
+ - **`handleCommentLooksGood` stays** on the `useHtmlAnnotation` return value
1837
+ (`components/html-viewer`), and `HtmlViewer` still passes it, so hosts that
1838
+ render `HtmlViewer` keep the button exactly as in 0.32.0 to 0.50.0. It now
1839
+ shares one commit path with `handleCommentSubmit` (`commitComposerDraft`),
1840
+ so the 👍 carries the same anchor, element context and shift-click extra
1841
+ targets as a typed comment.
1842
+
1843
+ `THUMBS_UP_LABEL` (`utils/quickLabels`) stays exported; the toolbar path,
1844
+ the composer path and `HtmlViewer`'s id filter use it. The trust-boundary
1845
+ clamp is untouched.
1846
+
1847
+ ---
1848
+
1849
+ ## Ask AI from a diagram comment (0.51.0; additive, no core change)
1850
+
1851
+ The diagram composer can offer the same "Ask AI" the markdown and HTML
1852
+ composers offer. All new props are optional; a host that passes none of them
1853
+ renders the composer it had (Cancel + Comment, no Ask AI).
1854
+
1855
+ - **`DiagramViewer` / `DiagramPopout` `onAskAI?: DiagramAskAI`** —
1856
+ `(question, anchor, additionalTargets) => boolean | void | Promise<boolean | void>`.
1857
+ `anchor` is the `DiagramAnchor` a comment on that part would carry
1858
+ (`sourceLine` already in document lines). Resolve `false` (or throw) to keep
1859
+ the draft open; anything else closes the composer. The button is disabled
1860
+ until text is typed and has no key binding: Enter stays Comment.
1861
+ - **`MermaidBlock` / `GraphvizBlock` (`DiagramBlockProps`) `onAskAI?: CommentAskAIHandler`**
1862
+ and **`askAISourcePath?: string`** — the same handler `Viewer` /
1863
+ `CommentPopover` take. The block builds the `CommentAskAIContext` with
1864
+ `utils/diagramAskAI`'s `diagramAskAIContext`: `kind: 'selection'`, label
1865
+ `"Mermaid diagram node D"`, `text` = the part's label, and `detail` = the
1866
+ export's location line (`diagramAnchorLocationLine`), the engine and family,
1867
+ and the diagram source (bounded to 40 lines / 4000 chars, grown outward
1868
+ from the part's line so the part is always in it; a single line over the
1869
+ budget is cut with `…`) in document lines. `detail` is the #1694 field that
1870
+ `buildDefaultPrompt` puts on the user message before the question. Ignored
1871
+ when `readOnly`. A question asked in the popout closes the popout, since it
1872
+ covers the panel the answer streams into.
1873
+ - **`Viewer`** forwards its existing `onAskAI` to its diagram fences (and the
1874
+ `sourcePath` it already sends from the markdown composer), so a host that
1875
+ passes `onAskAI` to `Viewer` gets Ask AI on diagram comments too. A host
1876
+ that wants Ask AI on text but not on diagrams has no switch for that yet.
1877
+
1878
+ Pinned by `components/DiagramBlock.askAI.test.tsx` and
1879
+ `utils/diagramAskAI.test.ts`.
1880
+
1748
1881
  ---
1749
1882
 
1750
1883
  ## The law (guardrails for anyone editing `@plannotator/ui`)
@@ -2,6 +2,7 @@ import type React from 'react';
2
2
  import { getProviderMeta } from './ProviderIcons';
3
3
  import { ModelSourceHint, modelSourceToolForProvider } from './ModelSourceHint';
4
4
  import {
5
+ findSessionBridge,
5
6
  getAIProviderSettings,
6
7
  resolveAIProviderSelection,
7
8
  saveAIProviderSelection,
@@ -65,6 +66,37 @@ export const AISettingsTab: React.FC<AISettingsTabProps> = ({
65
66
  );
66
67
  }
67
68
 
69
+ // "Ask this session": the session that opened Plannotator answers Ask AI and
70
+ // nothing else is offered. Nothing here writes a preference, so a saved
71
+ // provider still applies to sessions that have no attached session.
72
+ const sessionBridge = findSessionBridge(providers);
73
+ if (sessionBridge) {
74
+ const meta = getProviderMeta(sessionBridge.name, sessionBridge.label);
75
+ const Icon = meta.icon;
76
+ return (
77
+ <>
78
+ <div>
79
+ <div className="text-sm font-medium">AI Provider</div>
80
+ <div className="text-xs text-muted-foreground">
81
+ Ask AI is answered by the agent session that opened Plannotator.
82
+ </div>
83
+ </div>
84
+ <div
85
+ className="flex items-center gap-3 p-3 rounded-lg border border-primary bg-primary/5"
86
+ data-ai-settings-session-bridge
87
+ >
88
+ <div className="w-6 h-6 rounded-md bg-muted flex items-center justify-center text-muted-foreground">
89
+ <Icon className="w-4 h-4" />
90
+ </div>
91
+ <div className="text-sm font-medium">{meta.label}</div>
92
+ </div>
93
+ <div className="text-[10px] text-muted-foreground/70">
94
+ Your provider choice applies when Plannotator is opened without an attached session.
95
+ </div>
96
+ </>
97
+ );
98
+ }
99
+
68
100
  return (
69
101
  <>
70
102
  <div>
@@ -0,0 +1,347 @@
1
+ import React, { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { createPortal } from 'react-dom';
3
+ import { agentToolHostName } from '../utils/agentToolSetting';
4
+
5
+ /**
6
+ * One-time offer to turn on the `plannotator` agent tool on Pi and OpenCode 2,
7
+ * where it is off by default. Question first ("Do you use Plannotator as a
8
+ * skill?"), two example requests, one line of why, the cost, and two buttons,
9
+ * under a small diagram of the round trip (the agent opens a review right
10
+ * away, keeps working, your feedback comes back). Same shell as the other
11
+ * first-run announcements (portal, z-[100], hand-rolled Escape + Tab wrap +
12
+ * focus restore, backdrop dismiss, capture-phase keydown that swallows
13
+ * Mod+Enter so a keystroke aimed here cannot approve a plan or post a review
14
+ * behind it).
15
+ *
16
+ * Unlike those, it collects a decision, so it never dismisses itself while a
17
+ * save is in flight, and it reports the outcome in place: a failed save shows
18
+ * the server's reason and keeps both buttons; a successful one says when the
19
+ * tool arrives and offers Done.
20
+ *
21
+ * LAST in each app's first-run dialog chain; the Apps gate rendering through
22
+ * agentToolAnnouncementEligible and useFirstRunAnnouncementWindow.
23
+ */
24
+
25
+ export type AgentToolOfferHost = 'pi' | 'opencode';
26
+
27
+ interface AgentToolAnnouncementDialogProps {
28
+ readonly isOpen: boolean;
29
+ /** The session's host; names the agent and when the change applies. */
30
+ readonly host: AgentToolOfferHost;
31
+ /**
32
+ * "Yes, turn it on": writes the setting (POST /api/config `{ agentTool: true }`).
33
+ * Rejects with an Error whose message is shown. The App marks the offer
34
+ * seen when it resolves.
35
+ */
36
+ readonly onTurnOn: () => Promise<void>;
37
+ /** The decline button ("No, I’ll just use slash commands"), Escape, the backdrop and Done: marks the offer seen and closes it. */
38
+ readonly onDismiss: () => void;
39
+ }
40
+
41
+ type SaveState =
42
+ | { readonly kind: 'idle' }
43
+ | { readonly kind: 'saving' }
44
+ | { readonly kind: 'saved' }
45
+ | { readonly kind: 'failed'; readonly message: string };
46
+
47
+ const SECONDARY_BUTTON_CLASS =
48
+ 'inline-flex min-h-9 items-center gap-2 rounded-lg border border-border bg-surface-0/40 px-3 text-sm font-medium text-foreground outline-none transition-colors motion-reduce:transition-none hover:bg-surface-1/70 focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-card disabled:cursor-not-allowed disabled:opacity-50';
49
+
50
+ const PRIMARY_BUTTON_CLASS =
51
+ 'min-h-9 rounded-lg bg-primary px-5 text-sm font-medium text-primary-foreground outline-none transition-opacity motion-reduce:transition-none hover:opacity-90 focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-card disabled:cursor-not-allowed disabled:opacity-50';
52
+
53
+ export function AgentToolAnnouncementDialog({
54
+ isOpen,
55
+ host,
56
+ onTurnOn,
57
+ onDismiss,
58
+ }: AgentToolAnnouncementDialogProps) {
59
+ const notNowRef = useRef<HTMLButtonElement>(null);
60
+ const doneRef = useRef<HTMLButtonElement>(null);
61
+ const previousFocusRef = useRef<HTMLElement | null>(null);
62
+ const onDismissRef = useRef(onDismiss);
63
+ const [save, setSave] = useState<SaveState>({ kind: 'idle' });
64
+ const saveRef = useRef(save);
65
+ saveRef.current = save;
66
+ const mountedRef = useRef(true);
67
+ const agent = agentToolHostName(host);
68
+
69
+ useEffect(() => {
70
+ onDismissRef.current = onDismiss;
71
+ }, [onDismiss]);
72
+
73
+ useEffect(() => {
74
+ mountedRef.current = true;
75
+ return () => {
76
+ mountedRef.current = false;
77
+ };
78
+ }, []);
79
+
80
+ // Never closed mid-save: the outcome has to be shown.
81
+ const dismiss = useCallback(() => {
82
+ if (saveRef.current.kind === 'saving') return;
83
+ onDismissRef.current();
84
+ }, []);
85
+
86
+ const turnOn = useCallback(async () => {
87
+ if (saveRef.current.kind === 'saving' || saveRef.current.kind === 'saved') return;
88
+ setSave({ kind: 'saving' });
89
+ try {
90
+ await onTurnOn();
91
+ if (mountedRef.current) setSave({ kind: 'saved' });
92
+ } catch (error) {
93
+ if (!mountedRef.current) return;
94
+ setSave({
95
+ kind: 'failed',
96
+ message: error instanceof Error && error.message ? error.message : 'Could not save the setting.',
97
+ });
98
+ }
99
+ }, [onTurnOn]);
100
+
101
+ // Focus follows the outcome: Done once saved.
102
+ useEffect(() => {
103
+ if (save.kind === 'saved') doneRef.current?.focus();
104
+ }, [save.kind]);
105
+
106
+ useEffect(() => {
107
+ if (!isOpen) return;
108
+
109
+ previousFocusRef.current = document.activeElement instanceof HTMLElement
110
+ ? document.activeElement
111
+ : null;
112
+ // The decline button takes focus, so a stray Enter or Space never changes a setting.
113
+ notNowRef.current?.focus();
114
+
115
+ const handleKeyDown = (event: KeyboardEvent) => {
116
+ if (event.key === 'Escape') {
117
+ event.preventDefault();
118
+ event.stopPropagation();
119
+ dismiss();
120
+ return;
121
+ }
122
+ // Both apps submit their decision on Mod+Enter from a window-level
123
+ // handler; swallowing it here on the capture phase keeps a keystroke
124
+ // aimed at this dialog from approving a plan or posting a review.
125
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
126
+ event.preventDefault();
127
+ event.stopPropagation();
128
+ return;
129
+ }
130
+ if (event.key !== 'Tab') return;
131
+
132
+ const dialog = document.querySelector<HTMLElement>('[data-agent-tool-announcement-dialog]');
133
+ const focusable = Array.from(
134
+ dialog?.querySelectorAll<HTMLElement>('button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])')
135
+ ?? [],
136
+ ).filter((element) => element.getAttribute('tabindex') !== '-1');
137
+ if (focusable.length === 0) return;
138
+
139
+ const first = focusable[0];
140
+ const last = focusable[focusable.length - 1];
141
+ if (event.shiftKey && document.activeElement === first) {
142
+ event.preventDefault();
143
+ last.focus();
144
+ } else if (!event.shiftKey && document.activeElement === last) {
145
+ event.preventDefault();
146
+ first.focus();
147
+ }
148
+ };
149
+
150
+ document.addEventListener('keydown', handleKeyDown, true);
151
+ return () => {
152
+ document.removeEventListener('keydown', handleKeyDown, true);
153
+ previousFocusRef.current?.focus();
154
+ previousFocusRef.current = null;
155
+ };
156
+ }, [isOpen, dismiss]);
157
+
158
+ if (!isOpen) return null;
159
+
160
+ const saving = save.kind === 'saving';
161
+ return createPortal(
162
+ <div
163
+ className="fixed inset-0 z-[100] flex items-center justify-center bg-background/90 p-4 backdrop-blur-sm"
164
+ onMouseDown={(event) => {
165
+ if (event.target === event.currentTarget) dismiss();
166
+ }}
167
+ >
168
+ <div
169
+ data-agent-tool-announcement-dialog
170
+ data-agent-tool-host={host}
171
+ role="dialog"
172
+ aria-modal="true"
173
+ aria-labelledby="agent-tool-announcement-title"
174
+ aria-describedby="agent-tool-announcement-description"
175
+ className="flex max-h-[calc(100dvh-2rem)] w-full max-w-lg min-w-0 flex-col overflow-hidden rounded-xl border border-border bg-card shadow-2xl"
176
+ >
177
+ <style>{DIALOG_LAYOUT_CSS}</style>
178
+ <div className="pn-ato-graphic shrink-0 border-b border-border px-4 py-3" aria-hidden="true">
179
+ <RoundTripGraphic agent={agent} />
180
+ </div>
181
+ <div className="min-h-0 overflow-y-auto px-5 py-5 sm:px-7 sm:py-6">
182
+ <h2 id="agent-tool-announcement-title" className="text-balance text-xl font-semibold tracking-tight sm:text-2xl">
183
+ Do you use Plannotator as a skill?
184
+ </h2>
185
+ <div id="agent-tool-announcement-description">
186
+ <p className="mt-2 text-pretty text-sm leading-relaxed text-muted-foreground">
187
+ Like asking {agent} to &ldquo;use Plannotator to show me the HTML plan&rdquo; or &ldquo;open a
188
+ Plannotator code review&rdquo;.
189
+ </p>
190
+ <p className="mt-3 text-pretty text-sm leading-relaxed text-foreground">
191
+ If so, turn on the Plannotator tool. Those requests then open right away while {agent} keeps
192
+ working, and your feedback comes back as a message.
193
+ </p>
194
+ </div>
195
+ <p className="mt-3 text-pretty text-xs leading-relaxed text-muted-foreground" data-agent-tool-cost>
196
+ Adds about 780 tokens to each request.{save.kind === 'saved' ? '' : ` ${startsLine(host)}`}
197
+ </p>
198
+
199
+ <div className="mt-5 flex flex-col gap-3">
200
+ {save.kind === 'saved' ? (
201
+ <p
202
+ role="status"
203
+ data-agent-tool-status="saved"
204
+ className="inline-flex min-w-0 items-center gap-2 text-sm text-foreground"
205
+ >
206
+ <span className="size-2 shrink-0 rounded-full bg-success" aria-hidden="true" />
207
+ Turned on. {startsLine(host)}
208
+ </p>
209
+ ) : save.kind === 'failed' ? (
210
+ <p
211
+ role="alert"
212
+ data-agent-tool-status="failed"
213
+ className="inline-flex min-w-0 items-center gap-2 text-sm text-destructive"
214
+ >
215
+ <span className="size-2 shrink-0 rounded-full bg-destructive" aria-hidden="true" />
216
+ {save.message}
217
+ </p>
218
+ ) : null}
219
+
220
+ {/* Stacks full-width below sm (secondary first, so focus order matches reading order); one row from sm. */}
221
+ <div className="pn-ato-actions">
222
+ {save.kind === 'saved' ? (
223
+ <button
224
+ ref={doneRef}
225
+ type="button"
226
+ onClick={() => onDismissRef.current()}
227
+ className={`${PRIMARY_BUTTON_CLASS} w-full sm:w-auto`}
228
+ >
229
+ Done
230
+ </button>
231
+ ) : (
232
+ <>
233
+ <button
234
+ ref={notNowRef}
235
+ type="button"
236
+ onClick={dismiss}
237
+ disabled={saving}
238
+ data-agent-tool-not-now
239
+ className={`${SECONDARY_BUTTON_CLASS} w-full justify-center text-balance py-1.5 text-center sm:w-auto`}
240
+ >
241
+ No, I&rsquo;ll just use slash commands
242
+ </button>
243
+ <button
244
+ type="button"
245
+ onClick={() => void turnOn()}
246
+ disabled={saving}
247
+ aria-busy={saving}
248
+ data-agent-tool-turn-on
249
+ className={`${PRIMARY_BUTTON_CLASS} w-full sm:w-auto`}
250
+ >
251
+ {saving ? 'Turning on…' : save.kind === 'failed' ? 'Try again' : 'Yes, turn it on'}
252
+ </button>
253
+ </>
254
+ )}
255
+ </div>
256
+ </div>
257
+ </div>
258
+ </div>
259
+ </div>,
260
+ document.body,
261
+ );
262
+ }
263
+
264
+ /*
265
+ * Layout rules, the graphic band tint and the graphic colors are plain CSS (theme
266
+ * tokens through var()) rather than Tailwind utilities on purpose: this file
267
+ * is scanned by the review stylesheet, which the portable guides.show viewer
268
+ * shares, and utilities used nowhere else would change the pinned viewer CSS
269
+ * for a dialog the viewer never renders. Same result as the approved markup:
270
+ * the graphic hides below 420px; the buttons stack full-width below `sm`
271
+ * (40rem) and sit in one right-aligned row from it.
272
+ */
273
+ const DIALOG_LAYOUT_CSS = `
274
+ .pn-ato-graphic { display: none; background-color: color-mix(in oklab, var(--muted) 45%, transparent); }
275
+ @media (min-width: 420px) { .pn-ato-graphic { display: block; } }
276
+ .pn-ato-actions { display: flex; flex-direction: column; gap: 0.5rem; }
277
+ @media (min-width: 40rem) {
278
+ .pn-ato-actions { flex-direction: row; flex-wrap: wrap; align-items: center; justify-content: flex-end; }
279
+ }
280
+ `;
281
+
282
+ /** When the change applies on each host; part of the small print and the saved status. */
283
+ function startsLine(host: AgentToolOfferHost): string {
284
+ return host === 'opencode' ? 'Starts the next time OpenCode starts.' : 'Starts with your next Pi session.';
285
+ }
286
+
287
+ /*
288
+ * The round trip, as inline SVG painted only from theme tokens (var(--token)
289
+ * values from theme.css), so it follows every palette in light and dark.
290
+ * aria-hidden: the copy beside it carries the whole meaning.
291
+ *
292
+ * Motion, in one sentence: your feedback travelling back to the agent is what
293
+ * the tool adds, and drawing that one arrow once shows the direction the
294
+ * static picture only implies. Runs once on mount (900ms draw, then a 200ms
295
+ * fade of its head and label), never loops, and is off under
296
+ * prefers-reduced-motion, where the resting frame is the final one.
297
+ */
298
+ const ROUND_TRIP_MOTION_CSS = `
299
+ .pn-ato-return { stroke-dasharray: 1; stroke-dashoffset: 0; animation: pn-ato-draw 900ms cubic-bezier(0.23, 1, 0.32, 1) 300ms both; }
300
+ .pn-ato-return-head, .pn-ato-return-label { animation: pn-ato-fade 200ms ease-out 1050ms both; }
301
+ @keyframes pn-ato-draw { from { stroke-dashoffset: 1; } to { stroke-dashoffset: 0; } }
302
+ @keyframes pn-ato-fade { from { opacity: 0; } to { opacity: 1; } }
303
+ @media (prefers-reduced-motion: reduce) {
304
+ .pn-ato-return, .pn-ato-return-head, .pn-ato-return-label { animation: none; }
305
+ }
306
+ `;
307
+
308
+ function RoundTripGraphic({ agent }: { agent: string }) {
309
+ return (
310
+ <svg viewBox="0 0 480 176" className="mx-auto block h-auto w-full font-sans" style={{ maxWidth: 460 }} focusable="false">
311
+ <style>{ROUND_TRIP_MOTION_CSS}</style>
312
+
313
+ {/* The agent: a terminal tile */}
314
+ <g transform="translate(92 52)">
315
+ <rect x="0.75" y="0.75" width="54.5" height="54.5" rx="12" style={{ fill: 'var(--card)', stroke: 'var(--border)' }} strokeWidth="1.5" />
316
+ <path d="M17 21 L25 28 L17 35" style={{ fill: 'none', stroke: 'var(--primary)' }} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
317
+ <rect x="29" y="33" width="11" height="3" rx="1.5" style={{ fill: 'var(--primary)' }} />
318
+ </g>
319
+ <text x={120} y={140} textAnchor="middle" fontSize="13" fontWeight="600" style={{ fill: 'var(--foreground)' }}>
320
+ {agent} <tspan fontWeight="400" style={{ fill: 'var(--muted-foreground)' }}>keeps working</tspan>
321
+ </text>
322
+
323
+ {/* Plannotator: a document with one highlighted, commented line */}
324
+ <g transform="translate(318 38)">
325
+ <rect x="0.75" y="0.75" width="66.5" height="82.5" rx="10" style={{ fill: 'var(--card)', stroke: 'var(--border)' }} strokeWidth="1.5" />
326
+ <rect x="12" y="15" width="30.8" height="4" rx="2" style={{ fill: 'var(--foreground)' }} fillOpacity="0.55" />
327
+ <rect x="12" y="29" width="44" height="3" rx="1.5" style={{ fill: 'var(--muted-foreground)' }} fillOpacity="0.45" />
328
+ <rect x="9" y="38" width="50" height="11" rx="3" style={{ fill: 'var(--accent)' }} fillOpacity="0.28" />
329
+ <rect x="12" y="42" width="36.1" height="3" rx="1.5" style={{ fill: 'var(--foreground)' }} fillOpacity="0.6" />
330
+ <rect x="12" y="56" width="39.6" height="3" rx="1.5" style={{ fill: 'var(--muted-foreground)' }} fillOpacity="0.45" />
331
+ <rect x="12" y="66" width="24.2" height="3" rx="1.5" style={{ fill: 'var(--muted-foreground)' }} fillOpacity="0.45" />
332
+ <circle cx="64" cy="43" r="7" style={{ fill: 'var(--accent)', stroke: 'var(--card)' }} strokeWidth="2" />
333
+ </g>
334
+ <text x={352} y={140} textAnchor="middle" fontSize="13" fontWeight="600" style={{ fill: 'var(--foreground)' }}>Plannotator</text>
335
+
336
+ {/* opens right away */}
337
+ <path d="M152 64 Q 236 16 310 56" style={{ fill: 'none', stroke: 'var(--muted-foreground)' }} strokeWidth="1.75" strokeLinecap="round" />
338
+ <path d="M302.5 47.5 L311 56.5 L299 59" style={{ fill: 'none', stroke: 'var(--muted-foreground)' }} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" />
339
+ <text x={232} y={28} textAnchor="middle" fontSize="12" style={{ fill: 'var(--muted-foreground)' }}>opens right away</text>
340
+
341
+ {/* your feedback comes back */}
342
+ <path d="M310 106 Q 236 150 152 98" pathLength={1} className="pn-ato-return" style={{ fill: 'none', stroke: 'var(--primary)' }} strokeWidth="2.25" strokeLinecap="round" />
343
+ <path d="M153 112 L151.5 98.5 L164.5 100" className="pn-ato-return-head" style={{ fill: 'none', stroke: 'var(--primary)' }} strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round" />
344
+ <text x={236} y={166} textAnchor="middle" fontSize="12" fontWeight="600" className="pn-ato-return-label" style={{ fill: 'var(--primary)' }}>your feedback, as a message</text>
345
+ </svg>
346
+ );
347
+ }