From 48ed2d33852792c39a08975920bc2bd9120fe53c Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Mon, 5 Oct 2026 11:17:10 -0700 Subject: [PATCH 1/3] feat(annotate): several files in one review (0.29 PR 4, bundles) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit plannotator annotate spec.md mock.html notes.md (every argument an existing file named by its path) opens ONE review of the files, in the typed order, with one decision. No flag, no file-count limit. - Shared rule (annotate-target.ts, vendored to Pi): probeAnnotateBundlePath, the bundle selection, resolveAnnotateBundleFiles (type and 2MB checks that name the file). Prose, URLs, folders and searched names keep the #1483 tiers; the ambiguity error gains a hint on hosts that open bundles. Strict gates take only a single target or only file paths (else exit 2). - Server mode annotate-bundle in Bun and Pi: /api/plan carries bundle, /api/doc follows the single-file rule per file, history saved per text file at open, per-file draft copies (#1710), host status documents, archive surface annotate-bundle with target.documents. - CLI: host result record gains documents; the agent message names every file. - Editor: first file opens by itself, header switcher (2 of 3 · name), the Files tab and All files panel in bundle order, export one section per file in bundle order, Ask AI surface line names file N of M. - Tool contract: description line for lists, plannotatorBundleSubject, isOlderCliBundleRefusal; Bash take-over maps several file paths to a list. Mod launches bundles and maps an older CLI's refusal to an update message. - Pi and OpenCode (embedded and CLI bridge) slash commands open bundles too. Co-Authored-By: Claude --- .github/workflows/test.yml | 1 + AGENTS.md | 64 +++-- apps/hook/hooks/mod/controller.test.ts | 74 +++++- apps/hook/hooks/mod/controller.ts | 17 +- apps/hook/hooks/mod/launch.ts | 13 ++ apps/hook/hooks/mod/tool.ts | 79 ++++++- apps/hook/server/annotate-bundle-cli.test.ts | 180 ++++++++++++++ apps/hook/server/annotate-resolution.ts | 6 +- apps/hook/server/cli.ts | 2 + apps/hook/server/host-result.ts | 24 +- apps/hook/server/index.ts | 91 ++++++-- .../src/content/docs/commands/annotate.md | 12 + apps/opencode-plugin/cli-bridge.test.ts | 51 +++- apps/opencode-plugin/cli-bridge.ts | 57 ++++- apps/opencode-plugin/commands.test.ts | 32 +++ apps/opencode-plugin/commands.ts | 57 ++++- apps/pi-extension/index.ts | 61 ++++- apps/pi-extension/plannotator-browser.ts | 8 +- .../server/serverAnnotate-bundle.test.ts | 15 ++ apps/pi-extension/server/serverAnnotate.ts | 62 ++++- apps/pi-extension/vendor.sh | 2 +- apps/skills/core/plannotator/SKILL.md | 3 +- packages/ai/context.ts | 7 + packages/ai/session-bridge.test.ts | 14 ++ packages/ai/session-bridge.ts | 6 +- packages/core/agent-terminal.ts | 3 +- packages/core/ai-context.ts | 2 + packages/core/annotate-bundle.test.ts | 53 +++++ packages/core/annotate-bundle.ts | 142 +++++++++++ packages/core/package.json | 1 + packages/editor/App.bundle.test.tsx | 220 ++++++++++++++++++ packages/editor/App.tsx | 194 +++++++++++++-- packages/editor/agentTerminalIntegration.ts | 3 +- packages/editor/components/AppHeader.tsx | 11 +- packages/editor/components/BundleSwitcher.tsx | 55 +++++ packages/editor/feedbackDocuments.test.ts | 32 +++ packages/editor/feedbackDocuments.ts | 27 ++- packages/server/annotate-bundle.scenarios.ts | 218 +++++++++++++++++ packages/server/annotate-bundle.test.ts | 14 ++ packages/server/annotate.ts | 84 +++++-- packages/shared/annotate-bundle.ts | 1 + .../shared/annotate-reference-roots-node.ts | 11 + packages/shared/annotate-target.test.ts | 126 ++++++++++ packages/shared/annotate-target.ts | 162 ++++++++++++- packages/shared/feedback-archive.ts | 15 +- packages/shared/package.json | 1 + .../shared/plannotator-tool-command.test.ts | 12 +- packages/shared/plannotator-tool.test.ts | 20 ++ packages/shared/plannotator-tool.ts | 86 +++++-- packages/ui/components/PlanHeaderMenu.tsx | 2 +- packages/ui/utils/annotationScope.test.ts | 16 ++ packages/ui/utils/annotationScope.ts | 15 ++ packages/ui/utils/parser.ts | 5 + 53 files changed, 2303 insertions(+), 166 deletions(-) create mode 100644 apps/hook/server/annotate-bundle-cli.test.ts create mode 100644 apps/pi-extension/server/serverAnnotate-bundle.test.ts create mode 100644 packages/core/annotate-bundle.test.ts create mode 100644 packages/core/annotate-bundle.ts create mode 100644 packages/editor/App.bundle.test.tsx create mode 100644 packages/editor/components/BundleSwitcher.tsx create mode 100644 packages/server/annotate-bundle.scenarios.ts create mode 100644 packages/server/annotate-bundle.test.ts create mode 100644 packages/shared/annotate-bundle.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 715abf4444..af8fd504ee 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -239,6 +239,7 @@ jobs: packages/editor/App.editModeCrossBlockHighlights.test.tsx packages/editor/App.markdownUnanchored.test.tsx packages/editor/App.documentDrafts.test.tsx + packages/editor/App.bundle.test.tsx packages/editor/annotationDraftStaleRetry.test.tsx packages/ui/components/blocks/AlertBlock.title.test.tsx packages/ui/components/blocks/AlertBlock.seam.test.tsx diff --git a/AGENTS.md b/AGENTS.md index f734f399e9..3db916f23b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -155,7 +155,7 @@ claude --plugin-dir ./apps/hook | `PLANNOTATOR_MOD_DEBUG` | Set to `1` before starting Claude Code to have the Claude Code mod write `claude-code-mod/debug.log` in the data dir (launches, results, turns, bridge commands). Default: off. | | `PLANNOTATOR_ORIGIN` | Explicit agent-origin override at the top of the detection chain. Valid values: `claude-code`, `amp`, `droid`, `opencode`, `codex`, `copilot-cli`, `gemini-cli`, `kiro-cli`, `mistral-vibe`, `pi`, `oh-my-pi`. Invalid values silently fall through to env-based detection. Unset by default. | | `PLANNOTATOR_JINA` | Set to `0` / `false` to disable Jina Reader for URL annotation, or `1` / `true` to enable. Default: enabled. Can also be set via `~/.plannotator/config.json` (`{ "jina": false }`) or per-invocation via `--no-jina`. | -| `PLANNOTATOR_ANNOTATE_HISTORY` | Set to `0` / `false` to disable ALL annotate-session writes to the data dir: per-file version history (no copies of annotated files are written; the annotate version diff is unavailable) AND the durable submitted-feedback records (#678) that single-local-file annotate sessions otherwise write to `history/{project}/{slug}/submissions/` before deleting the draft on submit. Disabling it keeps annotate sessions fully stateless but also gives up that submit crash-recovery record. URL and annotate-last sessions never write either kind of data regardless of this flag. Folder sessions write no submitted-feedback records, but they do participate in per-file version history: the first time a session serves a file through /api/doc it snapshots that file (lazily, memoized per resolved path for the life of the server), which is what powers the per-file version diff when a folder file is reopened later; setting this flag to 0 disables those folder snapshots too. Setting it to 0 additionally suppresses **feedback archive** records for every annotate surface (single file, folder, URL, live app, annotate-last), so "fully stateless annotate session" stays literally true regardless of `PLANNOTATOR_FEEDBACK_HISTORY`, with one exception: annotation drafts (`drafts/`, including the path-keyed copies described under "Annotate drafts follow the file") are crash recovery and are still written; they are deleted when the review is decided. Raw-HTML and live-app pinpoints write their element context (selector, ancestor path, allowlisted attributes, visible text, a collapsed HTML skeleton, and the live route) into the submission records and drafts too; form values and inline handlers are never captured. Default: enabled. Can also be set via `~/.plannotator/config.json` (`{ "annotateHistory": false }`); the env var takes precedence. | +| `PLANNOTATOR_ANNOTATE_HISTORY` | Set to `0` / `false` to disable ALL annotate-session writes to the data dir: per-file version history (no copies of annotated files are written; the annotate version diff is unavailable) AND the durable submitted-feedback records (#678) that single-local-file annotate sessions otherwise write to `history/{project}/{slug}/submissions/` before deleting the draft on submit. Disabling it keeps annotate sessions fully stateless but also gives up that submit crash-recovery record. URL and annotate-last sessions never write either kind of data regardless of this flag. Folder sessions write no submitted-feedback records, but they do participate in per-file version history: the first time a session serves a file through /api/doc it snapshots that file (lazily, memoized per resolved path for the life of the server), which is what powers the per-file version diff when a folder file is reopened later; setting this flag to 0 disables those folder snapshots too. A review of several files (bundle) snapshots each of its text files when it opens, through the same pipeline, governed the same way. Setting it to 0 additionally suppresses **feedback archive** records for every annotate surface (single file, folder, URL, live app, annotate-last), so "fully stateless annotate session" stays literally true regardless of `PLANNOTATOR_FEEDBACK_HISTORY`, with one exception: annotation drafts (`drafts/`, including the path-keyed copies described under "Annotate drafts follow the file") are crash recovery and are still written; they are deleted when the review is decided. Raw-HTML and live-app pinpoints write their element context (selector, ancestor path, allowlisted attributes, visible text, a collapsed HTML skeleton, and the live route) into the submission records and drafts too; form values and inline handlers are never captured. Default: enabled. Can also be set via `~/.plannotator/config.json` (`{ "annotateHistory": false }`); the env var takes precedence. | | `PLANNOTATOR_FEEDBACK_HISTORY` | Set to `0` / `false` to stop archiving submitted feedback under `~/.plannotator/feedback/` (or `PLANNOTATOR_DATA_DIR`). Default: enabled, which appends one record per submission at decision-settlement time on all three surfaces and in both runtimes: plan approve/deny, code review Send Feedback / Approve (LGTM) / Close, and every annotate submit / approve / close. A review posted straight to GitHub, GitLab or Bitbucket with `POST /api/pr-action` is delivered to the platform and is not archived locally yet. **Note that this writes the user's own feedback text, the document and code excerpts it quotes, and per-annotation metadata to disk, and nothing prunes the directory** (same policy as `plans/`, `history/`, and `guides/`); delete `~/.plannotator/feedback/` or a project subdirectory to forget, or set this to 0 to never write. Code-review records carry diff IDENTITY only (vcsType, diffType, base, gitRef, snapshotId, cwd, PR metadata, changed-file count, patch byte count), never the patch bytes; plan records carry the decision text plus a reference to the `history/{project}/{slug}/NNN.md` version the decision was made on, never a second copy of the plan. Externally sourced annotations (linters, review agents, WebMCP browser agents) are included but keep their `source` / `author` tags, so `source == null` selects the reviewer's own comments; agent job outputs (guides, tours) are not archived. This knob governs only the new archive: the `planSave` decision snapshots in `plans/` and the #678 annotate submission records under `history/` are unaffected. Annotate surfaces honor `PLANNOTATOR_ANNOTATE_HISTORY` as well. Can also be set via `~/.plannotator/config.json` (`{ "feedbackHistory": false }`); the env var takes precedence. | | `PLANNOTATOR_GUIDE_VIEWER_URL` | Base URL of the portable Guided Review viewer that exported guides pin (default `https://guides.show/v1/`). Must be `https:` (or `http:` on localhost for local viewer builds — `bun run --cwd apps/guides-show serve:local`); anything else is ignored. Read by the export endpoints of both servers and by `plannotator guide export` (which also accepts `--viewer-url`). | | `PLANNOTATOR_GUIDE_SHARE_URL` | Base URL of the guide host that Guided Review share links are created on: the review UI's "Create share link", `plannotator guide share`, and `plannotator guide unshare` upload to and delete from it (default `https://guides.show`; the origin of your own deployment of its Cloudflare Worker otherwise, see the `apps/guides-show` README). Must be `http(s)`; credentials, query and fragment are dropped and a trailing slash is trimmed; an invalid value warns once on stderr and falls back to the default so a share setting can never break a server launch or CLI run. An empty-but-set env var counts as unset. Can also be set via `~/.plannotator/config.json` (`{ "guideShareUrl": "https://guides.example.com" }`); the env var takes precedence; there is no per-invocation flag. Resolved by `resolveGuideShareUrl` in `packages/shared/config.ts`. Whether sharing is allowed at all is `PLANNOTATOR_SHARE` (`disabled` turns guide share links off entirely). Removal always goes to the host a saved guide's record names, never merely the currently configured URL, so changing this after sharing does not strand a link. | @@ -359,7 +359,9 @@ review; verified live, `claude --continue` reattached and delivered it. like the bridge token: when a review, annotate, annotate-last or `claude-mod-plan` session settles, the CLI writes ONE JSON record there atomically (temp + rename): `{ v: 1, surface, decision, message, noop, -annotationCount?, platform?, withNotes?, approvedPlan?, permissionMode? }`. +annotationCount?, platform?, withNotes?, approvedPlan?, permissionMode?, +documents? }` (`documents`: a review of several files names each file with its +comment count, in review order). `message` is composed from the configured prompts exactly as other hosts do (review: the CLI's own output; annotate: the file/message feedback and approved-with-notes prompts OpenCode and Pi use; plan: `composePlanDeniedMessage` @@ -573,12 +575,22 @@ found". Against an older CLI the mod falls back to `TERM` under the checks described in "Version skew" above (`stopArgv`), which ends the server without a decision and never deletes a draft. The contract also accepts `target` as a list for annotate (validated, duplicates dropped, a -one-item list is the plain call) and reserves `action: "reply"` (`session`, -`comment`, `text`, `resolve`) for live comments; until bundles and live -comments ship the mod answers a list of several files with -`PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT` and `reply` with -`PLANNOTATOR_TOOL_REPLY_UNAVAILABLE_TEXT`, launching nothing. The tool -description does not advertise lists or `reply` yet. Design: +one-item list is the plain call): a review of several files (a bundle, see +"Several files in one review" under the Annotate Flow). `plannotatorToolArgs` +passes the paths as the CLI's arguments, one each, in order, and the session is +named `plannotatorBundleSubject` ("3 files: spec.md, mock.html, notes.md"), in +the opened text, the session list and the decision heading. The tool +description says "Pass a list as `target` to review several files together, in +the order you want them read." Version skew: a CLI that predates bundles answers +several paths with its ambiguity error WITHOUT the bundle hint line +(`isOlderCliBundleRefusal`, which compares against `PLANNOTATOR_BUNDLE_HINT_LINE`, +a copy of `ANNOTATE_BUNDLE_HINT` pinned equal by `annotate-target.test.ts`); the +mod then answers `PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT` ("update Plannotator +to open several files at once") for the tool, and for `/plannotator-annotate` +when every word reads as a file path (`isSeveralFilePaths`). `action: "reply"` +(`session`, `comment`, `text`, `resolve`) stays reserved for live comments: the +mod answers it with `PLANNOTATOR_TOOL_REPLY_UNAVAILABLE_TEXT`, launching nothing, +and the description does not advertise it yet. Design: `.product/drafts/agent-sessions-0.29/DESIGN.md`. **Agent-run CLI commands are taken over (Bash).** Because the tool is deferred @@ -601,14 +613,15 @@ its own cwd or worktree, while the mod launches in the session's cwd, so its quote; quoting follows `splitShellWords`, nothing is expanded) whose program is exactly `plannotator` (the binary on PATH; a path such as `./plannotator` or `/tmp/dev/plannotator` is a dev build and runs for real), subcommand -`annotate` (one target, `--gate`, `--markdown`), `review` (at most one target, `--base `), +`annotate` (one target, or several that all read as file paths, `looksLikeFilePath`: a separator, a leading `~` `.` `@`, or a file extension; they become `target: [...]`, a review of several files; plus `--gate`, `--markdown`), `review` (at most one target, `--base `), or `annotate-last` / `last` (no arguments); `--json` is accepted and dropped (the decision arrives as a message), and the result must pass `parsePlannotatorToolInput`. Everything else runs as written: other subcommands, every other flag (`--require-approval`, `--result-file`, `--hook`, `--tailscale`, `--static`, `--app`, `--no-jina`, `--render-html`, `--diff-type`, `--local`, `--patch-file`, `--stdin`, `--help`, ...), repeated -flags, several targets, environment prefixes, and any compound command +flags, several targets that are not all file paths (prose, which the CLI's +tolerant resolution reads) or several review targets, environment prefixes, and any compound command (`cd x && plannotator ...`, pipes, redirects, substitutions), so scripted strict gates keep the real CLI and its exit codes. With the mod off, in `-p`/SDK runs and on Windows nothing is taken over. The CLI the mod launches runs in the @@ -1196,6 +1209,9 @@ Input type detected: forces the classic conversion pipeline; --app forces live mode and fails loudly when it cannot apply. folder/ → file browser opened, files converted on demand + a.md b.html c.md (several existing file paths) + → ONE review of all of them, in that order (mode + "annotate-bundle"; see "Several files in one review" below) ↓ Annotate server starts (reuses plan editor HTML with mode:"annotate") ↓ @@ -1277,10 +1293,22 @@ were silent no-ops. Slash-command hosts forward raw user words to `plannotator annotate` verbatim (on Claude Code through a bash-substitution prefix that runs before the model sees anything), so non-strict invocations resolve their arguments in three tiers. The shared logic lives in `packages/shared/annotate-target.ts` (vendored to Pi) and is wired into the CLI's annotate branch plus the OpenCode and Pi command parsers: 1. A single-token invocation runs the classic pipeline unchanged: a bare correct path behaves exactly as before, and a lone typo'd path still fails with `File not found` and exit `1`. -2. With several tokens, each token is probed; exactly one naming an existing file, URL, or folder proceeds with it (`annotate look at notes.md please` opens `notes.md`). Two or more resolving tokens error naming every candidate rather than guessing, which also means `annotate a.md b.md` (previously: silently opened `a.md`, ignoring `b.md`) is now that error. Bare directory names only count as targets when they are the sole argument, so a stray word matching a directory (or `.`) cannot hijack the fast path; unrecognized dash-prefixed tokens disable the tolerance entirely so a typo'd flag (`--no-jna`) errors the way it always did instead of being silently skipped. +2. With several tokens, each token is probed; exactly one naming an existing file, URL, or folder proceeds with it (`annotate look at notes.md please` opens `notes.md`). **Bundle rule (0.29), checked first:** when EVERY token is an existing regular file named by its path (resolved from the cwd, `~` or an `@` prefix; `probeAnnotateBundlePath`, never a name found only by searching the project, never a URL or folder), they open as one review in the typed order with duplicates dropped (`selectAnnotateTokenTarget(..., { bundlePath })` → `{ kind: "bundle" }`); an existing file of an unsupported type or over the 2MB cap among them fails naming it (`resolveAnnotateBundleFiles`). Otherwise two or more resolving tokens (prose around them, a URL or folder among them, a searched name) error naming every candidate rather than guessing, and the error gains one hint line, `ANNOTATE_BUNDLE_HINT` ("To review several files together, pass only their paths: plannotator annotate a.md b.html"), on hosts that open bundles. A host that cannot open bundles passes no `bundlePath` and keeps the #1182 tiers exactly. Bare directory names only count as targets when they are the sole argument, so a stray word matching a directory (or `.`) cannot hijack the fast path; unrecognized dash-prefixed tokens disable the tolerance entirely so a typo'd flag (`--no-jna`) errors the way it always did instead of being silently skipped. 3. When nothing resolves, the CLI emits an agent-addressed handoff that echoes the words tried and asks the reading agent to re-run with a concrete target (content flags such as `--markdown` / `--no-jina` / `--render-html` are echoed for the re-run; transport flags are not). In plain mode the handoff goes to **stdout with exit `0`**, because a non-zero exit from a Claude Code bang-prefix skill aborts the prompt before the model sees any output; with `--json` / `--hook` it goes to stderr with exit `1` so machine-readable stdout stays reserved for decision records. OpenCode and Pi surface the same message as a host notification. -Strict invocations (`--require-approval` / `--result-file`) bypass all three tiers: `args[1]` is the target and a typo'd path stays a startup failure with exit `2`. +Strict invocations (`--require-approval` / `--result-file`) bypass all three tiers: `args[1]` is the target and a typo'd path stays a startup failure with exit `2`. With several arguments, a strict gate takes only the bundle rule: several existing file paths make one review (approve covers every file); anything else exits `2` (the first argument's own error when it has one, else "A strict annotate gate takes one target, or only existing file paths…"), where extra words used to be silently ignored. + +### Several files in one review (annotate bundles) + +`plannotator annotate spec.md mock.html notes.md`, the `plannotator` tool's `target: [...]`, a taken-over Bash command with several file paths, and `/plannotator-annotate a.md b.md` on Pi and OpenCode (embedded and CLI-bridge) open ONE review of the listed files, in the given order, with ONE decision (owner decisions: no flag, no file-count limit, per-file decisions later). Design: `.product/drafts/agent-sessions-0.29/DESIGN.md` section A. + +- **Server mode `annotate-bundle`** in both runtimes (`packages/server/annotate.ts`, mirrored in `apps/pi-extension/server/serverAnnotate.ts`): options `bundleFiles: AnnotateBundleFile[]` (`{ path, renderAs }`, from `packages/core/annotate-bundle.ts`, two or more or the server throws) and `filePath` = the bundle root (`annotateBundleRoot`, the deepest directory holding every file, compared by path segment). `/api/plan` adds `bundle` (the list, in order) and `projectRoot` = the bundle root. `/api/doc` serves the files and what they link to under the single-file rule: reference roots are the cwd plus each file's own directory (`bundlePaths` on `getAnnotateReferenceRootPaths`), so a document beside a bundle file opens as a linked document exactly as from that file alone, and anything outside is `403`. The editor never walks the bundle root. Each text file's version history is saved when the review opens (the folder pipeline's per-file memo, run eagerly; raw HTML keeps none, as in folders), and `/api/doc` returns its version fields. Source save (Edit Mode writes) is off in bundles. +- **Drafts:** the session draft is keyed by the ordered list (`bundle:\0`), and every file's comments are also saved under that file's path key (#1710's document copies), so they follow the file into a single-file, folder or other bundle session. Host status `documents` lists the files. +- **Decision record:** the host result record (`PLANNOTATOR_HOST_RESULT_FILE`) and the feedback archive gain `documents: [{ path, annotationCount }]` in bundle order (`annotateBundleDocumentCounts`, counted from each submitted annotation's `documentPath`). The archive record's surface is `annotate-bundle` with `target.documents` and no `filePath`. The agent message frames the feedback with `Files: , ` (`annotateBundleTargetText`) on every host. +- **Editor** (`packages/editor/App.tsx`): a folder session (`annotateSource` stays `'folder'`) with `bundleFiles` state. The first file opens by itself; the header's `BundleSwitcher` (`packages/editor/components/BundleSwitcher.tsx`, "2 of 3 · mock.html ‹ ›", desktop; the compact shell names the position in its title and offers Previous/Next file in its Options menu) and the Files tab follow the given order: the tab shows the bundle as a synthetic, never-fetched file-browser section (`bundleDirState`, merged into `navigatorFileBrowser` beside any configured directories; the filesystem root is the empty dir path so `${dir}/${node}` stays absolute). A link from one bundle file to another opens it as that bundle file, and an HTML bundle file gets no header Back control (there is no root to go back to). The export lists one section per file in bundle order under `BUNDLE_DOC_EXPORT_HEADING` ("File Feedback"; `resolveFeedbackSections({ bundleOrder })`, unlisted linked documents after), the All files panel follows the same order (`groupAnnotationsByDocument`'s `order`), and Ask AI's context carries `bundlePosition`, so the session-bridge surface line reads "annotating /…/mock.html, file 2 of 3". +- **Version skew:** an older CLI answers several paths with the ambiguity error lacking `ANNOTATE_BUNDLE_HINT`; the Claude Code mod and the OpenCode CLI bridge recognize that (`isOlderCliBundleRefusal`) and say to update Plannotator to open several files at once. An older host never sends a list. + +Tests: the selection table in `packages/shared/annotate-target.test.ts`; `packages/server/annotate-bundle.scenarios.ts` (both runtimes); `apps/hook/server/annotate-bundle-cli.test.ts` (the CLI as a process: order, one decision, the host record's `documents`, strict gates, the hint); `packages/core/annotate-bundle.test.ts`; the mod's `controller.test.ts` and `plannotator-tool*.test.ts`; OpenCode `commands.test.ts` and `cli-bridge.test.ts`; and the DOM test `packages/editor/App.bundle.test.tsx` (first file opens, switcher and file list in order, one section per file in bundle order). The bang prefix in the Claude Code skill is deliberate: #872 (commit `aac5aacb`, "restore `/plannotator-*` bash execution on Claude Code") put it back so the slash command never depends on the model choosing to run the binary. Argument-shape problems belong here in the CLI's resolution, not in the skill templates. @@ -1297,7 +1325,7 @@ Tests: `packages/server/annotate-draft.scenarios.ts` (run against both runtimes ### Strict direct annotate results -Direct `plannotator annotate` invocations may add `--require-approval` and/or `--result-file ` only with `--gate --json`; both reject `--hook` and are not shared with OpenCode/Pi slash-command parsing. When neither strict option is present, single-target invocations keep the legacy plaintext, JSON, hook, and exit behavior unchanged, with one additive JSON field: a non-gated Done with nothing to send prints `{"decision":"annotated","feedback":"User reviewed the document and has no feedback.","nothingToSend":true}` (the field appears only in that case and only on the non-strict `--json` record and the `opencode-annotate-last` record; decision values, the feedback text, plaintext, `--hook` output, the strict-gate record and every exit code are unchanged; the OpenCode CLI bridge, Amp and Droid read it; #1701). Multi-token invocations go through the tolerant tiers described under "Tolerant argument resolution" above. +Direct `plannotator annotate` invocations may add `--require-approval` and/or `--result-file ` only with `--gate --json`; both reject `--hook` and are not shared with OpenCode/Pi slash-command parsing. When neither strict option is present, single-target invocations keep the legacy plaintext, JSON, hook, and exit behavior unchanged, with one additive JSON field: a non-gated Done with nothing to send prints `{"decision":"annotated","feedback":"User reviewed the document and has no feedback.","nothingToSend":true}` (the field appears only in that case and only on the non-strict `--json` record and the `opencode-annotate-last` record; decision values, the feedback text, plaintext, `--hook` output, the strict-gate record and every exit code are unchanged; the OpenCode CLI bridge, Amp and Droid read it; #1701). Multi-token invocations go through the tolerant tiers described under "Tolerant argument resolution" above; several existing file paths open one review of all of them (strict gates included). Strict decisions use one newline-terminated JSON record on stdout and, when requested, identical bytes in the result file. Exit codes follow the grep convention: approval exits `0`; with `--require-approval`, annotated and dismissed decisions are published before exiting `1` (negative human outcome); usage/startup/validation failures — bad flag combinations, strict flags outside `annotate --gate --json`, a missing `--result-file` parent, a pre-existing or dangling-symlink destination, and every annotate startup failure (missing path, unreachable URL, empty folder, ambiguous name, missing file, oversized file) — exit `2` (the gate itself was misconfigured or could not start). Those startup sites exit `1` as before for non-strict invocations, with one deliberate exception: the multi-token zero-resolve handoff is not a startup failure, so in plain non-strict mode it prints on stdout and exits `0` (under `--json`/`--hook` it stays stderr + exit `1`). Under a strict flag `1` is reserved for "the reviewer did not approve", so a typo'd path must never masquerade as a rejection. Post-decision publication failures (destination appears between validation and publish, hard links unavailable) also exit `2`: the result *file* was not published, so they present as environment errors — "the gate could not publish its result" — never as a reviewer outcome, and never as approval (still fail-closed, since only `0` means approved). The stdout decision record is written **before** result-file publication and is still emitted whenever the decision itself completed; only a stdout write failure leaves no record anywhere. Signal deaths keep `128+n`. Result paths resolve from the invocation working directory, require an existing parent and absent destination, and publish via a flushed/closed `0600` same-directory temporary file plus an atomic no-clobber hard link—never copy or overwrite fallback (the `0600` mode is a no-op on Windows, and the atomic link/rename is not followed by a parent-directory fsync, so publication is atomic but not crash-durable). Keep reviewed sources at stable project paths; unique result and diagnostic log files may use a narrow temporary directory. Explicit Close emits `dismissed`; missing results or process/browser failures are recovery cases, never approval. @@ -1449,7 +1477,7 @@ During normal plan review, an Archive sidebar tab provides the same browsing via | Endpoint | Method | Purpose | | --------------------- | ------ | ------------------------------------------ | -| `/api/plan` | GET | Returns `{ plan, origin, mode: "annotate", filePath, sourceInfo?, gate, renderAs?, rawHtml?, previousPlan?, versionInfo?, diffCurrent?, diffHtml? }`. `renderAs` is `"markdown"`, `"html"`, or — for a whole-file diagram source (`.mmd`/`.mermaid`/`.dot`/`.gv`) — `"mermaid"` / `"graphviz"`, in which case `plan` is the file's RAW text and the editor renders it as one diagram block (see "Diagram files"). The decision is the pure, shared `annotateDiagramRenderKind` (`packages/core/annotatable.ts`), so a raw-HTML, converted, URL, folder, message or live-app session is never a diagram session in either runtime. The last four power the per-file version diff: `previousPlan`/`versionInfo`/`diffCurrent` for the markdown diff, `diffHtml` (the previous→current page rendered with inline ``/``) for `--render-html` files. A local rendered-HTML root is served from its CURRENT bytes on every read (`readRootHtml`), with the startup snapshot as the fallback when the file is missing, unreadable, or over the 2MB cap; when the served bytes differ from the snapshot, `previousPlan`/`versionInfo` still name the saved baseline and `diffCurrent`/`diffHtml` are recomputed against the served bytes (`htmlDiff` is pure; a GET never writes history), so a reload after an agent edit keeps the version diff. `/api/doc` carries the same recomputed `previousPlan`/`versionInfo`/`diffHtml` when it serves that root document (the in-app Refresh path, `rootHtmlVersionDiff`), and nothing extra for any other document. Live app sessions return `{ mode: "annotate-app", appUrl, targetUrl, liveToken, sharingEnabled: false, ... }` instead: no rawHtml, no version fields (see "Live app annotation"). | +| `/api/plan` | GET | Returns `{ plan, origin, mode: "annotate", filePath, sourceInfo?, gate, renderAs?, rawHtml?, previousPlan?, versionInfo?, diffCurrent?, diffHtml? }`. `renderAs` is `"markdown"`, `"html"`, or — for a whole-file diagram source (`.mmd`/`.mermaid`/`.dot`/`.gv`) — `"mermaid"` / `"graphviz"`, in which case `plan` is the file's RAW text and the editor renders it as one diagram block (see "Diagram files"). The decision is the pure, shared `annotateDiagramRenderKind` (`packages/core/annotatable.ts`), so a raw-HTML, converted, URL, folder, message or live-app session is never a diagram session in either runtime. The last four power the per-file version diff: `previousPlan`/`versionInfo`/`diffCurrent` for the markdown diff, `diffHtml` (the previous→current page rendered with inline ``/``) for `--render-html` files. A local rendered-HTML root is served from its CURRENT bytes on every read (`readRootHtml`), with the startup snapshot as the fallback when the file is missing, unreadable, or over the 2MB cap; when the served bytes differ from the snapshot, `previousPlan`/`versionInfo` still name the saved baseline and `diffCurrent`/`diffHtml` are recomputed against the served bytes (`htmlDiff` is pure; a GET never writes history), so a reload after an agent edit keeps the version diff. `/api/doc` carries the same recomputed `previousPlan`/`versionInfo`/`diffHtml` when it serves that root document (the in-app Refresh path, `rootHtmlVersionDiff`), and nothing extra for any other document. Live app sessions return `{ mode: "annotate-app", appUrl, targetUrl, liveToken, sharingEnabled: false, ... }` instead: no rawHtml, no version fields (see "Live app annotation"). A review of several files answers `{ mode: "annotate-bundle", plan: "", bundle: [{ path, renderAs }], projectRoot: , documentDrafts: true, ... }` (see "Several files in one review"). | | `/api/plan/version` | GET | Fetch a specific stored version of the annotated file (`?v=N`) | | `/api/plan/versions` | GET | List all stored versions of the annotated file | | `/api/feedback` | POST | Submit annotations (body: feedback, annotations) | @@ -1620,6 +1648,10 @@ Details that surprise people: on a document other than the session's own target carries the additive `documentPath` field naming that document (absent means the session's own target or message; distinct from `file`, a code annotation's file). +- **Records of a review of several files name every file.** Surface + `annotate-bundle` (additive), no `target.filePath`, and the additive + `target.documents: [{ path, annotationCount }]` in review order; every + comment on a file carries its `documentPath`. - **URL-session records store the full URL, query string included**, because that is the page that was reviewed. A URL carrying a token in its query is therefore written to disk; the opt-out is the control for that. @@ -1767,11 +1799,11 @@ Text highlighting uses `web-highlighter` library. Code blocks use manual ` **Annotation undo/redo:** each plan, annotate, or code-review app keeps one bounded 50-action stack for the active surface. `Mod+Z` undoes; `Mod+Shift+Z` and `Mod+Y` redo. Only local human annotation mutations are recorded, and a new mutation discards the redo branch. Native inputs, textareas, contenteditable regions, CodeMirror, dialogs/popovers, the Image Annotator, and an open Review Edit Mode session keep ownership of their own history shortcuts. External/agent writes do not enter annotation history; direct source changes, draft/share restore, refresh or diff replacement, identity changes, navigation to another document/message/review context, submission, and other baseline replacements clear it. The Image Annotator keeps a separate stroke undo/redo stack while its overlay is open. -**Cross-file annotations (multi-document annotate sessions).** A folder session — and any session whose linked documents carry feedback — spreads one body of feedback over many documents, so the annotations panel has a scope toggle in its header: **This file | All files**. It appears only when feedback exists outside the open document (`isMultiDocumentSession` in `packages/editor/App.tsx`); message multi-select keeps its own cross-message surface and is excluded. The toggle replaces the old `+N in M other files` flash affordance as the primary answer to "there are comments elsewhere"; the flash survives as a "Show in files" link at the foot of the All files view, and the header keeps a quiet `+N elsewhere` count while the scope is This file. +**Cross-file annotations (multi-document annotate sessions).** A folder session — a review of several files (bundle), and any session whose linked documents carry feedback — spreads one body of feedback over many documents, so the annotations panel has a scope toggle in its header: **This file | All files**. It appears only when feedback exists outside the open document (`isMultiDocumentSession` in `packages/editor/App.tsx`); message multi-select keeps its own cross-message surface and is excluded. The toggle replaces the old `+N in M other files` flash affordance as the primary answer to "there are comments elsewhere"; the flash survives as a "Show in files" link at the foot of the All files view, and the header keeps a quiet `+N elsewhere` count while the scope is This file. *Default rule* (`resolveInitialAnnotationScope`, `packages/ui/utils/annotationScope.ts`): the saved preference wins, except that a document with **no feedback of its own while other documents have some** opens on All files — that is the frustration the view exists for. It is re-resolved on every document change (keyed on the open document only, so a toggle is never yanked away mid-document), and the explicit choice persists per browser in the `plannotator-annotation-scope` cookie. One exception: arriving by clicking a card in the All files list keeps the All files scope, because that list is where the reviewer was. -*Grouping* is `groupAnnotationsByDocument` (pure, same file): one collapsible group per document that actually carries feedback, the open document first and the rest by path, labelled relative to the deepest session root the file browser knows. Cards are the same `AnnotationCard` the single-document timeline renders, so quote, comment, type, images, replies, Edit and Delete behave identically. +*Grouping* is `groupAnnotationsByDocument` (pure, same file): one collapsible group per document that actually carries feedback, the open document first and the rest by path (in a bundle: the bundle's own order, the open file in its place, anything else after), labelled relative to the deepest session root the file browser knows. Cards are the same `AnnotationCard` the single-document timeline renders, so quote, comment, type, images, replies, Edit and Delete behave identically. *Editing another document's comments* writes straight into that document's stored annotations through `useLinkedDoc`'s `updateStoredAnnotations` (the linked-doc cache, or the stashed source document); the active document is refused outright, since its annotations are host state. The export reads the same store, so a cross-file delete is reflected in what is submitted. *Export split:* `getDocAnnotations()` also carries the OPEN document's live state (for counts and the panel), so an export must never read it beside the host's live annotations — that printed the open document twice (every folder session, and any session submitted while a linked document was open). Every export goes through `useLinkedDoc.getFeedbackDocuments()` (`{ root, documents }`: the stashed root while a linked document is open, else null, and every other document once by path) and `resolveFeedbackSections` (`packages/editor/feedbackDocuments.ts`): the root (plan, file, or folder-level comments, plus SSE externals) under the session heading, every other document under its own path. A folder session titles that second section `Folder Document Feedback` ("files in the reviewed folder"), not the plan wording. Every document's entries are rendered by the ONE renderer `exportAnnotations` uses (`renderAnnotationEntries` in `packages/ui/utils/parser.ts`: document order, `[In diff content]`, quick labels + tip + Label Summary, threaded replies), so a document reads the same whichever section carries it. A cache entry under the root's own path (the root opened from itself, e.g. an HTML "Home" link) is a separate copy and is exported under its path, never dropped. **These cross-file mutations are deliberately not undoable:** the annotation history stack describes the open document's surface, and an entry that undid into a document the reviewer is not looking at would restore invisible state. `Mod+Z` still covers everything done in the open document. diff --git a/apps/hook/hooks/mod/controller.test.ts b/apps/hook/hooks/mod/controller.test.ts index 88ba24ca18..f719c5a876 100644 --- a/apps/hook/hooks/mod/controller.test.ts +++ b/apps/hook/hooks/mod/controller.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test' import { PlannotatorMod, STORE_LAUNCHES } from './controller' import { PLAN_APPROVAL_NEXT_STEP } from './delivery' import { CLASSIC_PLAN_REVIEW_TEXT } from './plan' +import { PLANNOTATOR_BUNDLE_HINT_LINE, PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT } from './tool' import { fakeHost, type FakeHost, type RunCall } from './testing/fake-host' const SESSION = { sessionId: 'session-1', dataDir: '/data', interactive: true } @@ -853,12 +854,11 @@ describe('the plannotator tool: list and close (contract v2)', () => { expect(host.submits[0]).toContain('fix line 3') }) - test('several files and reply answer with an error and launch nothing yet', async () => { + test('reply answers with an error and launches nothing yet', async () => { const host = fakeHost() serveOnLaunch(host) const mod = new PlannotatorMod(host, SESSION) - expect('deny' in (await mod.runTool({ action: 'annotate', target: ['a.md', 'b.md'] }))).toBe(true) expect('deny' in (await mod.runTool({ action: 'reply', session: 'pn-ababab', comment: 'c1', text: 'done' }))).toBe(true) expect(launches(host)).toHaveLength(0) @@ -867,3 +867,73 @@ describe('the plannotator tool: list and close (contract v2)', () => { expect(launches(host)[0]?.argv.slice(5)).toEqual(['plannotator', 'annotate', 'a.md']) }) }) + +// Reviews of several files (bundles). The failures: a list launched as +// something other than the CLI's bundle invocation (re-split, reordered), the +// decision heading naming one file of several, or an older CLI's "pick one" +// error shown to Claude as if its call were wrong. +describe('the plannotator tool: several files', () => { + test('a list launches one CLI with the files in order, and the result and decision name the bundle', async () => { + const host = fakeHost() + serveOnLaunch(host) + const mod = new PlannotatorMod(host, SESSION) + + const answer = await mod.runTool({ action: 'annotate', target: ['spec.md', 'ui/mock.html', 'notes.md'], gate: true }) + + expect('text' in answer && answer.text).toContain('Opened 3 files: spec.md, mock.html, notes.md in Plannotator') + const [launch] = launches(host) + expect(launch?.argv.slice(5)).toEqual(['plannotator', 'annotate', 'spec.md', 'ui/mock.html', 'notes.md', '--gate']) + + decide(host, launch!, { surface: 'annotate', decision: 'annotated', message: 'two notes', noop: false, annotationCount: 2 }) + await host.tick() + expect(host.submits[0]).toStartWith('Plannotator: 3 files: spec.md, mock.html, notes.md (pn-') + }) + + test('an older CLI refusing several paths reads as "update Plannotator", for the tool and the slash command', async () => { + const olderRefusal = [ + 'Ambiguous annotate arguments: 2 of them each resolve to an existing target.', + ' a.md -> /r/a.md', + ' b.md -> /r/b.md', + 'Re-run with exactly one target: plannotator annotate ', + ].join('\n') + const host = fakeHost() + host.onRun = (call) => { + if (isLaunch(call)) { + host.files.set(`${launchDirOf(call)}/stderr`, olderRefusal) + host.files.set(`${launchDirOf(call)}/exit`, '1') + } + } + const mod = new PlannotatorMod(host, SESSION) + + const answer = await mod.runTool({ action: 'annotate', target: ['a.md', 'b.md'] }) + expect('deny' in answer && answer.deny).toBe(PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT) + expect(await mod.runCommand('annotate', 'a.md b.md')).toBe(PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT) + // Prose around two paths is the user's own ambiguity, shown as the CLI said it. + expect(await mod.runCommand('annotate', 'compare a.md and b.md')).toContain('Ambiguous annotate arguments') + }) + + test("a current CLI's ambiguity error (a URL among the files) is shown as it is", async () => { + const host = fakeHost() + host.onRun = (call) => { + if (isLaunch(call)) { + host.files.set( + `${launchDirOf(call)}/stderr`, + `Ambiguous annotate arguments: 2 of them each resolve to an existing target.\n${PLANNOTATOR_BUNDLE_HINT_LINE}`, + ) + host.files.set(`${launchDirOf(call)}/exit`, '1') + } + } + const mod = new PlannotatorMod(host, SESSION) + const answer = await mod.runTool({ action: 'annotate', target: ['a.md', 'https://example.com'] }) + expect('deny' in answer && answer.deny).toContain(PLANNOTATOR_BUNDLE_HINT_LINE) + }) + + test('the slash command names several file paths as a bundle', async () => { + const host = fakeHost() + serveOnLaunch(host, 5555) + const mod = new PlannotatorMod(host, SESSION) + const text = await mod.runCommand('annotate', 'spec.md notes.md') + expect(text).toContain('2 files: spec.md, notes.md') + expect(launches(host)[0]?.argv.slice(5)).toEqual(['plannotator', 'annotate', 'spec.md', 'notes.md']) + }) +}) diff --git a/apps/hook/hooks/mod/controller.ts b/apps/hook/hooks/mod/controller.ts index 180e7cd36b..ad78f87b65 100644 --- a/apps/hook/hooks/mod/controller.ts +++ b/apps/hook/hooks/mod/controller.ts @@ -18,6 +18,7 @@ import { cliArgvFor, failedText, fileIn, + isSeveralFilePaths, launchArgv, launchDirOf, openedText, @@ -48,7 +49,9 @@ import { type PendingApproval, } from './plan' import { + isOlderCliBundleRefusal, parsePlannotatorToolInput, + plannotatorBundleSubject, plannotatorSessionId, plannotatorToolArgs, plannotatorToolCloseText, @@ -411,6 +414,11 @@ export class PlannotatorMod { const opened = await this.open(kind, rawArgs, subjectFor(kind, rawArgs)) switch (opened.state) { case 'error': + // Several file paths given to a CLI that predates reviews of several + // files: say to update instead of showing its "pick one" error. + if (kind === 'annotate' && isOlderCliBundleRefusal(opened.text) && isSeveralFilePaths(wordsOf(rawArgs))) { + return PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT + } return opened.text case 'starting': return `Starting Plannotator for ${opened.subject}… it opens in your browser when ready, and your feedback comes back here as a message.` @@ -442,14 +450,17 @@ export class PlannotatorMod { case 'last': break } - // Several files as one review need a CLI with bundles; none has them yet. - if (Array.isArray(call.target)) return { deny: PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT } const action = call.action const gate = call.gate === true - const subject = subjectFor(action, plannotatorToolTargets(call)) + const targets = plannotatorToolTargets(call) + // A list of files is one review of all of them (a bundle), named as such. + const bundle = Array.isArray(call.target) + const subject = bundle ? plannotatorBundleSubject(targets) : subjectFor(action, targets) const opened = await this.open(action, plannotatorToolArgs(call), subject, gate ? { deliverApproval: true } : {}) switch (opened.state) { case 'error': + // An older CLI answers several paths with its ambiguity error. + if (bundle && isOlderCliBundleRefusal(opened.text)) return { deny: PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT } return { deny: opened.text } case 'starting': return { text: plannotatorToolOpenedText(opened.subject, undefined, gate, opened.sessionId) } diff --git a/apps/hook/hooks/mod/launch.ts b/apps/hook/hooks/mod/launch.ts index 45b91c01fd..ecb67f353a 100644 --- a/apps/hook/hooks/mod/launch.ts +++ b/apps/hook/hooks/mod/launch.ts @@ -20,6 +20,7 @@ import type { SessionKind } from './delivery' import { splitShellWords } from './shell-words' +import { looksLikeFilePath, plannotatorBundleSubject } from './tool' /** The wrapper. `$1` is the launch directory; the CLI argv follows. */ export const LAUNCH_SCRIPT = [ @@ -238,6 +239,16 @@ function baseName(path: string): string { return trimmed.slice(trimmed.lastIndexOf('/') + 1) || trimmed } +/** + * Whether annotate's words (flags ignored) are several file paths, i.e. a + * review of several files (the CLI checks they exist; this only reads their + * shape, for naming the session and for reading an older CLI's refusal). + */ +export function isSeveralFilePaths(words: readonly string[]): boolean { + const targets = [...new Set(words.filter((word) => !word.startsWith('-')))] + return targets.length > 1 && targets.every(looksLikeFilePath) +} + /** How the status line, the command output and the plugin turn name a session. */ export function subjectFor(kind: SessionKind, args: string | readonly string[], version?: number): string { const words = wordsOf(args).filter((word) => !word.startsWith('-')) @@ -255,6 +266,8 @@ export function subjectFor(kind: SessionKind, args: string | readonly string[], return directory ? `changes in ${baseName(directory)}` : 'local changes' } case 'annotate': { + // Several file paths open as one review: name it as a bundle. + if (isSeveralFilePaths(words)) return plannotatorBundleSubject([...new Set(words)]) const target = words.find((word) => /^https?:\/\//i.test(word) || /[./]/.test(word)) ?? words[0] if (!target) return 'document' if (/^https?:\/\//i.test(target)) { diff --git a/apps/hook/hooks/mod/tool.ts b/apps/hook/hooks/mod/tool.ts index b8a0e92b7c..74e7b232d9 100644 --- a/apps/hook/hooks/mod/tool.ts +++ b/apps/hook/hooks/mod/tool.ts @@ -40,7 +40,7 @@ export interface PlannotatorToolInput { export const PLANNOTATOR_TOOL_DESCRIPTION = [ 'Open Plannotator, the browser review UI, for the user, and return at once. Also lists and closes the reviews opened in this conversation (by this tool or the user\'s /plannotator-* commands).', - '- action "annotate": annotate a file (markdown, text, config, HTML), a folder, or a URL; `target` is required. `gate: true` adds an Approve button for an explicit sign-off. `options.markdown: true` converts HTML or a URL to markdown first.', + '- action "annotate": annotate a file (markdown, text, config, HTML), a folder, or a URL; `target` is required. Pass a list as `target` to review several files together, in the order you want them read. `gate: true` adds an Approve button for an explicit sign-off. `options.markdown: true` converts HTML or a URL to markdown first.', '- action "review": review code changes; `target` is an optional repository directory or a GitHub/GitLab/Bitbucket pull request URL (default: the current repository). `options.base` sets the compare branch or ref (git only).', '- action "last": annotate your own last assistant message; no target.', '- action "list": the reviews opened in this conversation that are still open, one line each: session id, what it shows, url, age, state, and how many comments the reviewer has not sent yet.', @@ -61,7 +61,7 @@ export const PLANNOTATOR_TOOL_INPUT_SCHEMA = { { type: 'string' }, { type: 'array', items: { type: 'string' }, minItems: 1 }, ], - description: 'annotate: the file, folder or URL (required). review: a repository directory or PR URL (optional). Other actions: not used.', + description: 'annotate: the file, folder or URL (required), or a list of file paths to review together in that order. review: a repository directory or PR URL (optional). Other actions: not used.', }, gate: { type: 'boolean', @@ -308,9 +308,56 @@ export function plannotatorDecisionHeading(subject: string, sessionId: string | return `Plannotator: ${subject}${sessionId ? ` (${sessionId})` : ''} — ${outcome}.` } -/** What a host answers a list of several files with until it can open them as one review. */ +/** What a host answers a list of several files with when its Plannotator CLI is too old to open them as one review. */ export const PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT = - 'Plannotator did not open: opening several files in one review needs a newer Plannotator. Open them one at a time for now, or ask the user to update Plannotator.' + 'Plannotator did not open: the installed Plannotator is too old to open several files at once. Ask the user to update Plannotator to open several files at once, or open them one at a time for now.' + +/** + * The line a CLI that opens bundles adds to its "Ambiguous annotate + * arguments" error (`ANNOTATE_BUNDLE_HINT` in annotate-target.ts; copied here + * because this section must stay dependency-free). + */ +export const PLANNOTATOR_BUNDLE_HINT_LINE = + 'To review several files together, pass only their paths: plannotator annotate a.md b.html' + +/** + * Whether a CLI's startup error for several file paths is an OLDER CLI's + * refusal: its ambiguity error without the bundle hint a current CLI adds. A + * host that sent a list of paths answers `PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT` + * then, instead of showing an error that tells the agent to pick one file. + */ +export function isOlderCliBundleRefusal(errorText: string): boolean { + return errorText.includes('Ambiguous annotate arguments:') && !errorText.includes(PLANNOTATOR_BUNDLE_HINT_LINE) +} + +/** The file name of a path, for subjects (either separator). */ +function fileNameOf(path: string): string { + const trimmed = path.replace(/[\\/]+$/, '') + return trimmed.slice(Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\')) + 1) || trimmed +} + +/** + * What a review of several files is called wherever one line names it: the + * tool's result, the decision heading, the session list. Up to three file + * names, then a count of the rest: "3 files: spec.md, mock.html, notes.md", + * "5 files: a.md, b.md, c.md +2 more". + */ +export function plannotatorBundleSubject(paths: readonly string[]): string { + const names = paths.map(fileNameOf) + const rest = names.length - 3 + return `${names.length} files: ${names.slice(0, 3).join(', ')}${rest > 0 ? ` +${rest} more` : ''}` +} + +/** + * Whether a shell word reads as a file path rather than prose: it has a path + * separator, starts with `~`, `.` or `@`, or ends in a file extension. A URL + * is not a path. Pure: nothing is looked up on disk. + */ +export function looksLikeFilePath(word: string): boolean { + if (/^https?:\/\//i.test(word)) return false + if (/[\\/]/.test(word) || /^[~.@]/.test(word)) return true + return /\.[A-Za-z0-9]{1,12}$/.test(word) +} /** What a host answers `reply` with until it delivers single comments. */ export const PLANNOTATOR_TOOL_REPLY_UNAVAILABLE_TEXT = @@ -532,15 +579,18 @@ const COMMAND_ACTIONS: Record = { * word is exactly `plannotator` (the installed binary on PATH; a path such as * `./plannotator` is a dev build and runs for real), with subcommand * `annotate`, `review`, `annotate-last` or `last`, carrying only what the tool - * represents: annotate `` plus `--gate` and `--markdown`; review - * `[target]` plus `--base `; last with no arguments. `--json` is accepted - * and dropped (the decision arrives as a message, not on stdout). The result - * passes `parsePlannotatorToolInput`. + * represents: annotate `` (or several targets that all read as file + * paths, `looksLikeFilePath`, which become `target: [...]`, a review of + * several files) plus `--gate` and `--markdown`; review `[target]` plus + * `--base `; last with no arguments. `--json` is accepted and dropped + * (the decision arrives as a message, not on stdout). The result passes + * `parsePlannotatorToolInput`. * * Everything else is null and runs as written: other subcommands, any other * flag (`--require-approval`, `--result-file`, `--hook`, `--tailscale`, - * `--static`, `--app`, `--no-jina`, `--help`, ...), a repeated flag, more than - * one target, an environment prefix, and any shell syntax (`cd x && ...`, + * `--static`, `--app`, `--no-jina`, `--help`, ...), a repeated flag, several + * targets that are not all file paths (or for review), an environment prefix, + * and any shell syntax (`cd x && ...`, * pipes, redirects, substitutions), so scripted strict gates keep the CLI. */ export function plannotatorCommandToToolInput(command: string): PlannotatorToolInput | null { @@ -576,8 +626,13 @@ export function plannotatorCommandToToolInput(command: string): PlannotatorToolI } else return null } - if (targets.length > 1) return null - if (targets.length === 1) call.target = targets[0] + if (targets.length > 1) { + // Several targets are taken over only as a review of several files: + // annotate, and every word a file path. Anything else (prose around a + // path, which the CLI's tolerant resolution reads) runs as written. + if (action !== 'annotate' || !targets.every(looksLikeFilePath)) return null + call.target = targets + } else if (targets.length === 1) call.target = targets[0] if (Object.keys(options).length > 0) call.options = options const parsed = parsePlannotatorToolInput(call) return parsed.ok ? parsed.input : null diff --git a/apps/hook/server/annotate-bundle-cli.test.ts b/apps/hook/server/annotate-bundle-cli.test.ts new file mode 100644 index 0000000000..4f53e446bc --- /dev/null +++ b/apps/hook/server/annotate-bundle-cli.test.ts @@ -0,0 +1,180 @@ +/** + * `plannotator annotate a.md b.html ...` (several existing file paths) opens + * ONE review of all of them, run as the real process: the server runs in + * `annotate-bundle` mode with the files in the typed order, one decision + * settles it, and the host result record names each file with its comment + * count. Mixed arguments keep the #1483 errors (with the bundle hint), and a + * strict gate takes only a single target or only file paths. + * + * Every run uses a temp PLANNOTATOR_DATA_DIR and cwd; nothing touches the + * real ~/.plannotator. + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { ANNOTATE_BUNDLE_HINT } from "@plannotator/shared/annotate-target"; + +const entry = resolve(import.meta.dir, "index.ts"); +const distDir = resolve(import.meta.dir, "../dist"); +let stubs: string[] = []; +let root = ""; + +beforeAll(() => { + // The CLI imports the built HTML; API-only tests need just a stub. + stubs = ["index.html", "review.html"].map((name) => join(distDir, name)).filter((path) => !existsSync(path)); + mkdirSync(distDir, { recursive: true }); + for (const path of stubs) writeFileSync(path, "test"); + root = realpathSync(mkdtempSync(join(tmpdir(), "plannotator-annotate-bundle-cli-"))); + mkdirSync(join(root, "docs")); + writeFileSync(join(root, "spec.md"), "# Spec\n\nBody\n"); + writeFileSync(join(root, "docs", "mock.html"), "

Mock

"); + writeFileSync(join(root, "notes.md"), "# Notes\n"); + writeFileSync(join(root, "image.png"), "not really a png"); +}); +afterAll(() => { + for (const path of stubs) rmSync(path, { force: true }); + rmSync(root, { recursive: true, force: true }); +}); + +function env(extra: Record = {}): Record { + return { + ...(process.env as Record), + PLANNOTATOR_CWD: root, + PLANNOTATOR_DATA_DIR: join(root, "data"), + PLANNOTATOR_PORT: "0", + PLANNOTATOR_REMOTE: "0", + PLANNOTATOR_SKIP_BROWSER_OPEN: "1", + PLANNOTATOR_AI: "disabled", + PLANNOTATOR_SHARE: "disabled", + PLANNOTATOR_FEEDBACK_HISTORY: "0", + PLANNOTATOR_ANNOTATE_HISTORY: "0", + ...extra, + }; +} + +function runSync(args: string[]) { + const result = Bun.spawnSync([process.execPath, "run", entry, "annotate", ...args], { + cwd: root, + env: env(), + stdout: "pipe", + stderr: "pipe", + timeout: 30_000, + }); + return { exitCode: result.exitCode, stdout: result.stdout.toString(), stderr: result.stderr.toString() }; +} + +async function waitFor(read: () => T | null | undefined, ms = 20_000): Promise { + const deadline = Date.now() + ms; + for (;;) { + const value = read(); + if (value) return value; + if (Date.now() > deadline) throw new Error("timed out"); + await Bun.sleep(25); + } +} + +/** Start the CLI the way the Claude Code mod does: a ready file and a host result file. */ +function start(args: string[], launch: string) { + const dir = join(root, "data", "claude-code-mod", "session-1", launch); + mkdirSync(dir, { recursive: true }); + const ready = join(dir, "ready"); + const resultPath = join(dir, "result.json"); + const proc = Bun.spawn([process.execPath, "run", entry, "annotate", ...args], { + cwd: root, + env: env({ PLANNOTATOR_READY_FILE: ready, PLANNOTATOR_HOST_RESULT_FILE: resultPath }), + stdout: "pipe", + stderr: "pipe", + }); + const base = async () => { + const line = await waitFor(() => (existsSync(ready) ? readFileSync(ready, "utf8").split("\n")[0] : null)); + return `http://localhost:${(JSON.parse(line) as { port: number }).port}`; + }; + return { proc, base, resultPath }; +} + +const comment = (id: string, documentPath: string) => ({ + id, + blockId: "", + startOffset: 0, + endOffset: 4, + type: "COMMENT", + text: id, + originalText: "Body", + createdA: 1, + documentPath, +}); + +describe("annotate with several file paths", () => { + test("opens one review in the typed order and settles it with one decision naming every file", async () => { + const spec = join(root, "spec.md"); + const mock = join(root, "docs", "mock.html"); + const { proc, base, resultPath } = start(["docs/mock.html", "spec.md", "./docs/mock.html"], "bundle-1"); + const url = await base(); + + const plan = await (await fetch(`${url}/api/plan`)).json(); + expect(plan.mode).toBe("annotate-bundle"); + // Typed order; the duplicate of mock.html is dropped. + expect(plan.bundle).toEqual([ + { path: mock, renderAs: "html" }, + { path: spec, renderAs: "markdown" }, + ]); + + const feedback = "## spec.md\n\nTighten the intro."; + const sent = await fetch(`${url}/api/feedback`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ feedback, annotations: [comment("a", spec), comment("b", spec)] }), + }); + expect(sent.ok).toBe(true); + expect(await proc.exited).toBe(0); + expect(await new Response(proc.stdout).text()).toContain("Tighten the intro."); + + const record = JSON.parse(readFileSync(resultPath, "utf8")); + expect(record.decision).toBe("annotated"); + expect(record.annotationCount).toBe(2); + expect(record.documents).toEqual([ + { path: mock, annotationCount: 0 }, + { path: spec, annotationCount: 2 }, + ]); + // The agent's message names every file of the review. + expect(record.message).toContain(mock); + expect(record.message).toContain(spec); + }, 30_000); + + test("a strict gate opens several files as one review and approves them all", async () => { + const { proc, base } = start(["spec.md", "notes.md", "--gate", "--json", "--require-approval"], "bundle-2"); + const url = await base(); + expect((await (await fetch(`${url}/api/plan`)).json()).mode).toBe("annotate-bundle"); + const approved = await fetch(`${url}/api/approve`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: "{}", + }); + expect(approved.ok).toBe(true); + expect(await proc.exited).toBe(0); + expect(JSON.parse((await new Response(proc.stdout).text()).trim()).decision).toBe("approved"); + }, 30_000); + + test("an unsupported file among them is a startup error naming it", () => { + const result = runSync(["spec.md", "image.png"]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain(join(root, "image.png")); + // Under a strict gate the same misconfiguration is exit 2, never a rejection. + expect(runSync(["spec.md", "image.png", "--gate", "--json", "--require-approval"]).exitCode).toBe(2); + }); + + test("a folder among the paths keeps the ambiguity error, now with the hint", () => { + const result = runSync(["spec.md", "docs/"]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("Ambiguous annotate arguments"); + expect(result.stderr).toContain(ANNOTATE_BUNDLE_HINT); + }); + + test("a strict gate refuses extra words instead of ignoring them", () => { + const result = runSync(["spec.md", "please", "--gate", "--json", "--result-file", "out.json"]); + expect(result.exitCode).toBe(2); + expect(result.stderr).toContain("A strict annotate gate takes one target"); + expect(result.stdout).toBe(""); + }); +}); diff --git a/apps/hook/server/annotate-resolution.ts b/apps/hook/server/annotate-resolution.ts index 708b3ac112..2509872c4c 100644 --- a/apps/hook/server/annotate-resolution.ts +++ b/apps/hook/server/annotate-resolution.ts @@ -34,6 +34,7 @@ import { } from "@plannotator/shared/resolve-file"; import { isConvertedSource, urlToMarkdown } from "@plannotator/shared/url-to-markdown"; import { isLoopbackHostname } from "@plannotator/server/live-proxy"; +import type { AnnotateBundleFile } from "@plannotator/shared/annotate-bundle"; import { LIVE_APP_REQUIRES_HTTP_MESSAGE, LIVE_APP_REQUIRES_LOOPBACK_MESSAGE, @@ -50,7 +51,10 @@ export interface AnnotateResolutionSuccess { rawHtml?: string; absolutePath: string; folderPath?: string; - annotateMode: "annotate" | "annotate-folder"; + /** `annotate-bundle` is built by the CLI's bundle rule, never by this pipeline. */ + annotateMode: "annotate" | "annotate-folder" | "annotate-bundle"; + /** Several files reviewed as one, in review order (annotate-bundle only). */ + bundleFiles?: AnnotateBundleFile[]; sourceInfo?: string; sourceConverted: boolean; isUrl: boolean; diff --git a/apps/hook/server/cli.ts b/apps/hook/server/cli.ts index b97d86de8b..245b986480 100644 --- a/apps/hook/server/cli.ts +++ b/apps/hook/server/cli.ts @@ -234,6 +234,8 @@ export const SUBCOMMAND_HELP: Record = { " plannotator annotate [--markdown] [--no-jina] [--tailscale] [--gate] [--json] [--hook] [--require-approval] [--result-file ]", "", "Open a markdown/text/HTML file, a URL, or a folder of documents in the annotation UI.", + "Several existing file paths (plannotator annotate spec.md mock.html notes.md) open", + "as one review, in that order, with one decision for all of them.", "", "Options:", " --markdown Convert HTML input to markdown instead of rendering it raw", diff --git a/apps/hook/server/host-result.ts b/apps/hook/server/host-result.ts index c7348b9be7..002265984e 100644 --- a/apps/hook/server/host-result.ts +++ b/apps/hook/server/host-result.ts @@ -29,6 +29,7 @@ import { getPlanToolName, } from "@plannotator/shared/prompts"; import type { ReviewOutput } from "./review-output"; +import { annotateBundleDocumentCounts, annotateBundleTargetText } from "@plannotator/shared/annotate-bundle"; export const HOST_RESULT_FILE_ENV = "PLANNOTATOR_HOST_RESULT_FILE"; @@ -59,6 +60,8 @@ export interface HostResultRecord { closedBy?: "agent"; /** With `closedBy`: the reviewer's unsent comments, kept in the draft. */ unsentAnnotations?: number; + /** Annotate of several files (a bundle): each file, in review order, with how many comments were made on it. */ + documents?: { path: string; annotationCount: number }[]; } /** The `closedBy` / `unsentAnnotations` pair a host close adds to a dismissal. */ @@ -167,10 +170,12 @@ interface AnnotateOutcomeLike { } export interface AnnotateHostContext { - /** "last-message" for annotate-last. */ - kind: "file" | "folder" | "url" | "last"; - /** Absolute file/folder path or URL; unused for `last`. */ + /** "last-message" for annotate-last; "bundle" for several files reviewed as one. */ + kind: "file" | "folder" | "url" | "last" | "bundle"; + /** Absolute file/folder path or URL; unused for `last` and `bundle`. */ target?: string; + /** `bundle`: the files in review order (absolute). */ + bundlePaths?: readonly string[]; origin?: Origin; config?: PlannotatorConfig; } @@ -181,6 +186,16 @@ export interface AnnotateHostContext { * framing the OpenCode and Pi hosts use. */ export function annotateHostResult(result: AnnotateOutcomeLike, context: AnnotateHostContext): HostResultRecord { + const record = annotateHostRecord(result, context); + if (context.kind !== "bundle") return record; + // A bundle names each file with its comment count, in review order. + return { + ...record, + documents: annotateBundleDocumentCounts(context.bundlePaths ?? [], Array.isArray(result.annotations) ? result.annotations : []), + }; +} + +function annotateHostRecord(result: AnnotateOutcomeLike, context: AnnotateHostContext): HostResultRecord { const surface: HostResultSurface = context.kind === "last" ? "annotate-last" : "annotate"; const annotationCount = Array.isArray(result.annotations) ? result.annotations.length : undefined; const feedback = (result.feedback ?? "").trim() ? result.feedback ?? "" : ""; @@ -188,7 +203,8 @@ export function annotateHostResult(result: AnnotateOutcomeLike, context: Annotat if (result.exit) { return { v: 1, surface, decision: "dismissed", message: "", noop: true, ...(annotationCount !== undefined && { annotationCount }), ...closedByFields(result) }; } - const header = context.kind === "folder" ? "Folder" : context.kind === "url" ? "URL" : "File"; + const header = context.kind === "folder" ? "Folder" : context.kind === "url" ? "URL" : context.kind === "bundle" ? "Files" : "File"; + if (context.kind === "bundle") context = { ...context, target: annotateBundleTargetText(context.bundlePaths ?? []) }; if (result.approved) { if (!feedback) { return { v: 1, surface, decision: "approved", message: getAnnotateApprovedPrompt(runtime, context.config), noop: true, ...(annotationCount !== undefined && { annotationCount }) }; diff --git a/apps/hook/server/index.ts b/apps/hook/server/index.ts index 7ed941ce9b..ded8845b08 100644 --- a/apps/hook/server/index.ts +++ b/apps/hook/server/index.ts @@ -104,11 +104,16 @@ import { type GoalSetupStage, } from "@plannotator/shared/goal-setup"; import { + ANNOTATE_BUNDLE_HINT, buildAmbiguousAnnotateArgsMessage, buildUnresolvedAnnotateArgsMessage, + probeAnnotateBundlePath, probeAnnotateToken, + resolveAnnotateBundleFiles, selectAnnotateTokenTarget, } from "@plannotator/shared/annotate-target"; +import { annotateBundleRoot, type AnnotateBundleFile } from "@plannotator/shared/annotate-bundle"; +import { plannotatorBundleSubject } from "@plannotator/shared/plannotator-tool"; import { createWorktreePool, type WorktreePool, type PoolEntry } from "@plannotator/shared/worktree-pool"; import { parsePRUrl, checkPRAuth, fetchPR, getCliName, getCliInstallUrl, getMRLabel, getMRNumberLabel, getDisplayRepo, getPlatformLabel, getPRNumber, getPRHeadFetchSpec, getPRCloneCommand } from "@plannotator/server/pr"; import { writeRemoteShareLink } from "@plannotator/server/share-url"; @@ -126,7 +131,7 @@ import { import { readHostMessages, takeHostMessagesPath } from "./host-messages"; import { exitOnPortInUse } from "./port-in-use"; import { parseModPlanInput, readModPlanRevision, writeModPlanRevisionAck } from "./claude-mod-plan"; -import { LIVE_APP_REMOTE_MESSAGE } from "@plannotator/shared/live-probe"; +import { LIVE_APP_REMOTE_MESSAGE, LIVE_APP_REQUIRES_URL_MESSAGE } from "@plannotator/shared/live-probe"; // Bridge sources for live app sessions: the CLI supplies them so // @plannotator/server never imports @plannotator/ui (mirrors the existing // htmlContent precedent). @@ -1387,15 +1392,66 @@ if (args[0] === "sessions") { // disable tolerance entirely so a typo'd flag errors the way it always // did instead of being silently skipped. const targetTokens = args.slice(1); - const tolerantMultiToken = !strictAnnotate && targetTokens.length > 1; // Bare directory names only count as targets when they are the sole // argument; in multi-token mode a stray word matching a directory (or `.`) // must not hijack the fast path. const annotateProbe = (token: string) => probeAnnotateToken(token, projectRoot, { bareDirectories: false }); + // Several files reviewed as one (0.29 bundles): when there are several + // arguments and EVERY one is an existing file named by its path, they open + // as one review in the typed order. Checked first, for strict gates too + // (which take nothing else with several arguments). Anything less keeps the + // tiers below unchanged. + let bundleResolution: Awaited> | null = null; + if (targetTokens.length > 1) { + const bundlePath = (token: string) => probeAnnotateBundlePath(token, projectRoot); + const bundleSelection = selectAnnotateTokenTarget(targetTokens, annotateProbe, { bundlePath }); + if (bundleSelection.kind === "bundle") { + // --app needs a URL, exactly as for a single file. + if (appFlag) exitAnnotateStartupFailure(LIVE_APP_REQUIRES_URL_MESSAGE); + const checked = resolveAnnotateBundleFiles( + bundleSelection.files.map((file) => file.value), + { convertHtml: renderMarkdownFlag }, + ); + if (!checked.ok) exitAnnotateStartupFailure(checked.message); + const bundleRoot = annotateBundleRoot(checked.files.map((file) => file.path)); + console.error(`Files (${checked.files.length}): ${checked.files.map((file) => file.path).join(", ")}`); + bundleResolution = { + ok: true, + markdown: "", + absolutePath: bundleRoot, + annotateMode: "annotate-bundle", + bundleFiles: checked.files, + sourceConverted: false, + isUrl: false, + }; + } else if (strictAnnotate && !targetTokens.every((token) => bundlePath(token) !== null)) { + // A strict gate's arguments are one target or only file paths. The + // first argument's own error wins (a typo'd path keeps its message); + // otherwise the extra words are refused instead of ignored. + const first = await resolveAnnotateTarget({ + rawFilePath, + projectRoot, + noJina: cliNoJina, + renderMarkdown: renderMarkdownFlag, + forceApp: appFlag, + forceStatic: staticFlag, + }); + if (!first.ok) exitAnnotateStartupFailure(first.message); + exitAnnotateStartupFailure( + [ + `A strict annotate gate takes one target, or only existing file paths to review several files together. These arguments are neither: ${targetTokens.join(" ")}`, + ANNOTATE_BUNDLE_HINT, + ].join("\n"), + ); + } + } + + const tolerantMultiToken = !strictAnnotate && targetTokens.length > 1 && bundleResolution === null; + let resolution: Awaited> | null = - tolerantMultiToken + bundleResolution ?? (tolerantMultiToken ? null : await resolveAnnotateTarget({ rawFilePath, @@ -1404,7 +1460,7 @@ if (args[0] === "sessions") { renderMarkdown: renderMarkdownFlag, forceApp: appFlag, forceStatic: staticFlag, - }); + })); if (tolerantMultiToken) { const selection = selectAnnotateTokenTarget(targetTokens, annotateProbe); @@ -1418,7 +1474,9 @@ if (args[0] === "sessions") { forceStatic: staticFlag, }); } else if (selection.kind === "multiple") { - exitAnnotateStartupFailure(buildAmbiguousAnnotateArgsMessage(selection.candidates)); + // This CLI opens several file paths as one review; the hint says so + // (and its presence is how a host tells this CLI from an older one). + exitAnnotateStartupFailure(buildAmbiguousAnnotateArgsMessage(selection.candidates, { bundleHint: true })); } else if (selection.kind === "none" && selection.words.length > 1) { // Content flags only: transport flags (--gate/--json/--hook) describe // this invocation's plumbing, and suggesting them would tell an agent @@ -1474,7 +1532,9 @@ if (args[0] === "sessions") { sourceConverted, isUrl, liveApp: liveAppResolved, + bundleFiles, } = resolution; + const bundlePaths = bundleFiles?.map((file) => file.path); // Remote hard-off (layer 1 of 3; the server throw and the proxy's // unconditional loopback bind are the others). No override env var exists @@ -1511,6 +1571,7 @@ if (args[0] === "sessions") { } : undefined, folderPath, + bundleFiles, sourceInfo, sourceConverted, sharingEnabled, @@ -1562,9 +1623,11 @@ if (args[0] === "sessions") { mode: "annotate", project: annotateProject, startedAt: new Date().toISOString(), - label: folderPath - ? `annotate-${path.basename(folderPath)}` - : `annotate-${isUrl ? hostnameOrFallback(absolutePath) : path.basename(absolutePath)}`, + label: bundlePaths + ? `annotate-${plannotatorBundleSubject(bundlePaths)}` + : folderPath + ? `annotate-${path.basename(folderPath)}` + : `annotate-${isUrl ? hostnameOrFallback(absolutePath) : path.basename(absolutePath)}`, }); await completeAnnotateCommand({ @@ -1574,11 +1637,13 @@ if (args[0] === "sessions") { requireApproval: requireApprovalFlag, resultFile, emitLegacyOutcome: (outcome) => { - publishHostResult(annotateHostResult(outcome, { - kind: folderPath ? "folder" : isUrl ? "url" : "file", - target: folderPath ?? absolutePath, - origin: detectedOrigin, - })); + publishHostResult(annotateHostResult(outcome, bundlePaths + ? { kind: "bundle", bundlePaths, origin: detectedOrigin } + : { + kind: folderPath ? "folder" : isUrl ? "url" : "file", + target: folderPath ?? absolutePath, + origin: detectedOrigin, + })); emitAnnotateOutcome(outcome); }, }); diff --git a/apps/marketing/src/content/docs/commands/annotate.md b/apps/marketing/src/content/docs/commands/annotate.md index 90e526b075..45cb668d6b 100644 --- a/apps/marketing/src/content/docs/commands/annotate.md +++ b/apps/marketing/src/content/docs/commands/annotate.md @@ -66,6 +66,18 @@ When you pass a folder, Plannotator opens a file browser showing all markdown an Build output directories like `_site/`, `public/`, `.docusaurus/`, and `node_modules/` are automatically excluded from the file browser. +## Several files in one review + +Pass several file paths to review them together: + +```bash +plannotator annotate spec.md ui/mock.html notes.md +``` + +They open as one review, in the order you gave them. The first file opens right away. A switcher in the header ("2 of 3 · mock.html") and the Files tab list them in that order, and each file renders as it would alone (markdown, raw HTML, diagram files). There is one decision for all of them: Send Feedback sends one message with a section per file, in the same order, and with `--gate` one Approve covers every file. Each file's comments are also saved under that file, so they come back when you open it again on its own or in another review. + +Every argument must be an existing file named by its path. If anything else is mixed in (a word, a URL, a folder, or a bare name Plannotator would have to search the project for), the command keeps its usual behavior: one file among plain words opens that file, and several targets are an error that names them. Agents with the `plannotator` tool pass the files as a list in `target`. + ## URLs Fetching a URL converts the page to markdown before opening it in the annotation editor. Loopback `http` URLs are the exception: they open your running app live instead, covered in [Local apps](#local-apps) below. diff --git a/apps/opencode-plugin/cli-bridge.test.ts b/apps/opencode-plugin/cli-bridge.test.ts index 0f1dd74a24..1dd4ad5d7d 100644 --- a/apps/opencode-plugin/cli-bridge.test.ts +++ b/apps/opencode-plugin/cli-bridge.test.ts @@ -1,5 +1,5 @@ import { describe, expect, mock, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { @@ -86,6 +86,55 @@ process.exit(1); } }, 20_000); // spawns the stub CLI several times; the 5s default flakes + // Several file paths are one review: each path its own CLI argument (one + // joined argument would be "File not found"), the agent's prompt names + // every file, and an older CLI's "pick one" error reads as "update". + test.skipIf(process.platform === "win32")("several file paths reach the CLI as one review; an older CLI reads as update", async () => { + const root = mkdtempSync(path.join(tmpdir(), "plannotator-annotate-bundle-bridge-")); + writeFileSync(path.join(root, "spec.md"), "# Spec\n"); + writeFileSync(path.join(root, "mock.html"), "

Mock

"); + const argvFile = path.join(root, "argv.json"); + const current = path.join(root, "cli.ts"); + writeFileSync(current, `#!/usr/bin/env bun +import { writeFileSync } from "node:fs"; +writeFileSync(${JSON.stringify(argvFile)}, JSON.stringify(process.argv.slice(2))); +console.log(JSON.stringify({ decision: "annotated", feedback: "two notes" })); +`, { mode: 0o755 }); + const older = path.join(root, "older-cli.ts"); + writeFileSync(older, `#!/usr/bin/env bun +console.error("Ambiguous annotate arguments: 2 of them each resolve to an existing target.\\nRe-run with exactly one target: plannotator annotate "); +process.exit(1); +`, { mode: 0o755 }); + const client = { + app: { log: mock((_entry: { message: string }) => {}) }, + session: { prompt: mock(async (_input: unknown) => ({})) }, + tui: { showToast: mock((_input: any) => {}) }, + }; + const previous = process.env.PLANNOTATOR_BIN; + try { + process.env.PLANNOTATOR_BIN = current; + await handleCliCommand({ command: "plannotator-annotate", client, sessionId: "s1", cwd: root, rawArgs: "spec.md mock.html" }); + expect(JSON.parse(readFileSync(argvFile, "utf8"))).toEqual([ + "annotate", + path.join(root, "spec.md"), + path.join(root, "mock.html"), + "--json", + ]); + const delivered = JSON.stringify(client.session.prompt.mock.calls[0]?.[0]); + expect(delivered).toContain(path.join(root, "spec.md")); + expect(delivered).toContain(path.join(root, "mock.html")); + + process.env.PLANNOTATOR_BIN = older; + client.app.log.mockClear(); + await handleCliCommand({ command: "plannotator-annotate", client, sessionId: "s1", cwd: root, rawArgs: "spec.md mock.html" }); + expect(client.app.log.mock.calls.map(([entry]) => entry.message).join("\n")).toContain("update Plannotator to open several files at once"); + } finally { + if (previous === undefined) delete process.env.PLANNOTATOR_BIN; + else process.env.PLANNOTATOR_BIN = previous; + rmSync(root, { recursive: true, force: true }); + } + }, 20_000); + test("maps OpenCode sharing context into child CLI env", () => { expect(buildCliBridgeEnv({ sharingEnabled: false, diff --git a/apps/opencode-plugin/cli-bridge.ts b/apps/opencode-plugin/cli-bridge.ts index bfa1239ac9..44f054419a 100644 --- a/apps/opencode-plugin/cli-bridge.ts +++ b/apps/opencode-plugin/cli-bridge.ts @@ -11,6 +11,14 @@ import { } from "@plannotator/ai/session-bridge-pull"; import { runPullSessionBridgeClient } from "@plannotator/ai/session-bridge-pull-client"; import { parseAnnotateArgs, type ParsedAnnotateArgs } from "@plannotator/shared/annotate-args"; +import { + annotateInputNamesExistingTarget, + probeAnnotateBundlePath, + probeAnnotateToken, + selectAnnotateTokenTarget, +} from "@plannotator/shared/annotate-target"; +import { annotateBundleTargetText } from "@plannotator/shared/annotate-bundle"; +import { isOlderCliBundleRefusal, PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT } from "@plannotator/shared/plannotator-tool"; import { parseReviewArgs, resolveReviewTarget } from "@plannotator/shared/review-args"; import { composeReviewApprovedMessage, @@ -560,8 +568,24 @@ async function runPlannotatorCli(options: RunCliOptions): Promise } } -export function buildAnnotateCliArgs(parsed: ParsedAnnotateArgs): string[] { - const args = ["annotate", parsed.rawFilePath, "--json"]; +/** + * The files of a review of several files, when the user's annotate words are + * several existing file paths (every word one; the shared bundle rule), as + * absolute paths in the typed order; null otherwise. Each becomes its own CLI + * argument, which is what makes the CLI open them as one review. + */ +export function annotateBundleCliPaths(rawFilePath: string, cwd: string): string[] | null { + if (annotateInputNamesExistingTarget(rawFilePath, cwd)) return null; + const selection = selectAnnotateTokenTarget( + rawFilePath, + (token) => probeAnnotateToken(token, cwd, { bareDirectories: false }), + { bundlePath: (token) => probeAnnotateBundlePath(token, cwd) }, + ); + return selection.kind === "bundle" ? selection.files.map((file) => file.value) : null; +} + +export function buildAnnotateCliArgs(parsed: ParsedAnnotateArgs, bundlePaths?: readonly string[] | null): string[] { + const args = ["annotate", ...(bundlePaths && bundlePaths.length > 1 ? bundlePaths : [parsed.rawFilePath]), "--json"]; if (parsed.gate) args.push("--gate"); if (parsed.renderHtml) args.push("--render-html"); if (parsed.renderMarkdown) args.push("--markdown"); @@ -724,7 +748,7 @@ function getAnnotateFileHeader(filePath: string, cwd?: string): "File" | "Folder export function buildAnnotatePromptFromBridgeOutcome( outcome: CliAnnotateOutcome, target: - | { kind: "file"; fileHeader: "File" | "Folder"; filePath: string } + | { kind: "file"; fileHeader: "File" | "Folder" | "Files"; filePath: string } | { kind: "message" }, ): string | null { if (outcome.decision === "dismissed" || !outcome.feedback?.trim()) return null; @@ -856,26 +880,39 @@ export async function handleCliCommand(input: { return; } + // Several existing file paths open as one review of all of them. + const bundlePaths = annotateBundleCliPaths(parsed.rawFilePath, cwd); const result = await runPlannotatorCli({ client: input.client, - args: buildAnnotateCliArgs(parsed), + args: buildAnnotateCliArgs(parsed, bundlePaths), cwd, readyLabel: "annotation UI", bridge: input.bridge, sessionBridge: sessionBridge(), }); if (result.exitCode !== 0) { - log(input.client, "error", result.stderr.trim() || `Plannotator CLI exited with code ${result.exitCode}`); + // A CLI that predates reviews of several files answers with its + // ambiguity error; say to update instead. + const stderr = result.stderr.trim(); + log( + input.client, + "error", + bundlePaths && isOlderCliBundleRefusal(stderr) + ? PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT + : stderr || `Plannotator CLI exited with code ${result.exitCode}`, + ); return; } logCliWarnings(input.client, result.stderr); const outcome = parseLastJson(result.stdout); - const prompt = buildAnnotatePromptFromBridgeOutcome(outcome, { - kind: "file", - fileHeader: getAnnotateFileHeader(parsed.filePath, input.cwd), - filePath: parsed.filePath, - }); + const prompt = buildAnnotatePromptFromBridgeOutcome(outcome, bundlePaths + ? { kind: "file", fileHeader: "Files", filePath: annotateBundleTargetText(bundlePaths) } + : { + kind: "file", + fileHeader: getAnnotateFileHeader(parsed.filePath, input.cwd), + filePath: parsed.filePath, + }); if (prompt && input.sessionId) { // No annotated message here: the agent the user is talking to reads // the feedback, not OpenCode's default agent (#1612). diff --git a/apps/opencode-plugin/commands.test.ts b/apps/opencode-plugin/commands.test.ts index 1f229d24a3..2d9ad91e97 100644 --- a/apps/opencode-plugin/commands.test.ts +++ b/apps/opencode-plugin/commands.test.ts @@ -239,6 +239,38 @@ describe("handleAnnotateCommand", () => { expect(startAnnotateServerMock.mock.calls[0]?.[0].approvalNotesSupported).toBe(false); }); + // Several existing file paths are one review of all of them (the shared + // bundle rule): the failure is the old ambiguity error, or a prompt that + // names only one of the files. + test("several file paths open one bundle session, and the prompt names every file", async () => { + const projectRoot = makeTempDir(); + const spec = path.join(projectRoot, "spec.md"); + const mock_ = path.join(projectRoot, "mock.html"); + writeFileSync(spec, "# Spec\n"); + writeFileSync(mock_, "

Mock

"); + const deps: any = makeDeps(); + deps.directory = projectRoot; + deps.startAnnotateServer = mock(async (options: any) => ({ + port: 0, + url: "http://localhost", + isRemote: false, + options, + waitForDecision: async () => ({ feedback: "Two notes.", annotations: [{ id: "a1" }] }), + stop: () => {}, + })); + + await handleAnnotateCommand({ properties: { arguments: "mock.html spec.md", sessionID: "session-123" } }, deps); + + const options = deps.startAnnotateServer.mock.calls[0]?.[0]; + expect(options.mode).toBe("annotate-bundle"); + expect(options.bundleFiles).toEqual([ + { path: mock_, renderAs: "html" }, + { path: spec, renderAs: "markdown" }, + ]); + const prompt = deps.client.session.prompt.mock.calls[0]?.[0].body.parts[0].text; + expect(prompt).toContain(`Files: ${mock_}, ${spec}`); + }); + test("injects approved feedback as non-blocking notes with file context", async () => { const projectRoot = makeTempDir(); const filePath = path.join(projectRoot, "plan.md"); diff --git a/apps/opencode-plugin/commands.ts b/apps/opencode-plugin/commands.ts index da6a019285..627fbd4f71 100644 --- a/apps/opencode-plugin/commands.ts +++ b/apps/opencode-plugin/commands.ts @@ -32,9 +32,16 @@ import { annotateInputNamesExistingTarget, buildAmbiguousAnnotateArgsMessage, buildUnresolvedAnnotateArgsMessage, + probeAnnotateBundlePath, probeAnnotateToken, + resolveAnnotateBundleFiles, selectAnnotateTokenTarget, } from "@plannotator/shared/annotate-target"; +import { + annotateBundleRoot, + annotateBundleTargetText, + type AnnotateBundleFile, +} from "@plannotator/shared/annotate-bundle"; import { formatIgnoredReviewWords, parseReviewArgs, resolveReviewTarget, withReviewDirectory } from "@plannotator/shared/review-args"; import { urlToMarkdown, isConvertedSource } from "@plannotator/shared/url-to-markdown"; import { buildLocalWorkspaceReview, type WorkspaceDiffType } from "@plannotator/server/review-workspace"; @@ -366,15 +373,30 @@ export async function handleAnnotateCommand( // pre-pass, and unrecognized dash-prefixed tokens disable tolerance so a // typo'd flag errors the way it always did. const tolerantRoot = directory || process.cwd(); + // Several existing file paths (every word one) open as one review, in the + // typed order: the shared bundle rule, same as the CLI. + let bundleFiles: AnnotateBundleFile[] | undefined; if (!annotateInputNamesExistingTarget(rawFilePath, tolerantRoot)) { - const selection = selectAnnotateTokenTarget(rawFilePath, (token) => - probeAnnotateToken(token, tolerantRoot, { bareDirectories: false }), + const selection = selectAnnotateTokenTarget( + rawFilePath, + (token) => probeAnnotateToken(token, tolerantRoot, { bareDirectories: false }), + { bundlePath: (token) => probeAnnotateBundlePath(token, tolerantRoot) }, ); - if (selection.kind === "single") { + if (selection.kind === "bundle") { + const checked = resolveAnnotateBundleFiles( + selection.files.map((file) => file.value), + { convertHtml: renderMarkdownFlag }, + ); + if (!checked.ok) { + client.app.log({ level: "error", message: checked.message }); + return; + } + bundleFiles = checked.files; + } else if (selection.kind === "single") { filePath = selection.candidate.value; rawFilePath = selection.candidate.value; } else if (selection.kind === "multiple") { - client.app.log({ level: "error", message: buildAmbiguousAnnotateArgsMessage(selection.candidates) }); + client.app.log({ level: "error", message: buildAmbiguousAnnotateArgsMessage(selection.candidates, { bundleHint: true }) }); return; } else if (selection.kind === "none" && selection.words.length > 1) { // Content flags only; --gate is transport for this invocation, not a @@ -396,16 +418,23 @@ export async function handleAnnotateCommand( let rawHtml: string | undefined; let absolutePath: string; let folderPath: string | undefined; - let annotateMode: "annotate" | "annotate-folder" = "annotate"; + let annotateMode: "annotate" | "annotate-folder" | "annotate-bundle" = "annotate"; let isFolder = false; let sourceInfo: string | undefined; let sourceConverted = false; const agentCwd = directory || process.cwd(); // --- URL annotation --- - const isUrl = /^https?:\/\//i.test(filePath); - - if (isUrl) { + const isUrl = !bundleFiles && /^https?:\/\//i.test(filePath); + + if (bundleFiles) { + // The deepest directory holding every file stands in for the session's + // path; the files ride the server's `bundleFiles`. + markdown = ""; + absolutePath = annotateBundleRoot(bundleFiles.map((file) => file.path)); + annotateMode = "annotate-bundle"; + client.app.log({ level: "info", message: `Opening annotation UI for ${bundleFiles.length} files...` }); + } else if (isUrl) { const useJina = resolveUseJina(noJina, loadConfig()); client.app.log({ level: "info", message: `Fetching: ${filePath}${useJina ? " (via Jina Reader)" : " (via fetch+Turndown)"}...` }); try { @@ -499,6 +528,7 @@ export async function handleAnnotateCommand( mode: annotateMode, project: annotateProject, folderPath, + bundleFiles, sourceInfo, sourceConverted, rawHtml, @@ -539,14 +569,19 @@ export async function handleAnnotateCommand( sessionAgent = undefined; } const agent = await resolveAddressableAgent({ client, agent: sessionAgent, directory }); + // A bundle names every file of the review, in order. + const fileHeader = bundleFiles ? "Files" : isFolder ? "Folder" : "File"; + const targetText = bundleFiles + ? annotateBundleTargetText(bundleFiles.map((file) => file.path)) + : absolutePath; const text = result.approved ? getAnnotateApprovedWithNotesPrompt("opencode", undefined, { - context: `${isFolder ? "Folder" : "File"}: ${absolutePath}`, + context: `${fileHeader}: ${targetText}`, feedback: result.feedback, }) : getAnnotateFileFeedbackPrompt("opencode", undefined, { - fileHeader: isFolder ? "Folder" : "File", - filePath: absolutePath, + fileHeader, + filePath: targetText, feedback: result.feedback, }); await deliverOpenCodePrompt({ diff --git a/apps/pi-extension/index.ts b/apps/pi-extension/index.ts index 0207ae49da..a6e8391ae5 100644 --- a/apps/pi-extension/index.ts +++ b/apps/pi-extension/index.ts @@ -99,9 +99,10 @@ function loadPlannotatorPrompts(): Promise { } async function loadAnnotateCommandModules() { - const [annotateArgs, annotateTarget, atReference, resolveFile, referenceCommon] = await Promise.all([ + const [annotateArgs, annotateTarget, annotateBundle, atReference, resolveFile, referenceCommon] = await Promise.all([ import("./generated/annotate-args.ts"), import("./generated/annotate-target.ts"), + import("./generated/annotate-bundle.ts"), import("./generated/at-reference.ts"), import("./generated/resolve-file.ts"), import("./generated/reference-common.ts"), @@ -112,6 +113,10 @@ async function loadAnnotateCommandModules() { buildAmbiguousAnnotateArgsMessage: annotateTarget.buildAmbiguousAnnotateArgsMessage, buildUnresolvedAnnotateArgsMessage: annotateTarget.buildUnresolvedAnnotateArgsMessage, probeAnnotateToken: annotateTarget.probeAnnotateToken, + probeAnnotateBundlePath: annotateTarget.probeAnnotateBundlePath, + resolveAnnotateBundleFiles: annotateTarget.resolveAnnotateBundleFiles, + annotateBundleRoot: annotateBundle.annotateBundleRoot, + annotateBundleTargetText: annotateBundle.annotateBundleTargetText, selectAnnotateTokenTarget: annotateTarget.selectAnnotateTokenTarget, resolveAtReference: atReference.resolveAtReference, hasMarkdownFiles: resolveFile.hasMarkdownFiles, @@ -881,7 +886,7 @@ export default function plannotator(pi: ExtensionAPI, deps: PlannotatorExtension }); pi.registerCommand("plannotator-annotate", { - description: "Open markdown file or folder in annotation UI", + description: "Open a file, several files, a URL or a folder in the annotation UI", handler: async (args, ctx) => { const { FILE_BROWSER_EXCLUDED, @@ -891,6 +896,10 @@ export default function plannotator(pi: ExtensionAPI, deps: PlannotatorExtension buildAmbiguousAnnotateArgsMessage, buildUnresolvedAnnotateArgsMessage, probeAnnotateToken, + probeAnnotateBundlePath, + resolveAnnotateBundleFiles, + annotateBundleRoot, + annotateBundleTargetText, selectAnnotateTokenTarget, resolveAtReference, resolveUserPath, @@ -922,15 +931,30 @@ export default function plannotator(pi: ExtensionAPI, deps: PlannotatorExtension // only count in the sole-arg pre-pass, and unrecognized // dash-prefixed tokens disable tolerance so a typo'd flag errors // the way it always did. + // Several existing file paths (every word one) open as one review, + // in the typed order: the shared bundle rule, same as the CLI. + let bundleFiles: { path: string; renderAs: "markdown" | "html" | "mermaid" | "graphviz" }[] | undefined; if (!annotateInputNamesExistingTarget(rawFilePath, ctx.cwd)) { - const selection = selectAnnotateTokenTarget(rawFilePath, (token: string) => - probeAnnotateToken(token, ctx.cwd, { bareDirectories: false }), + const selection = selectAnnotateTokenTarget( + rawFilePath, + (token: string) => probeAnnotateToken(token, ctx.cwd, { bareDirectories: false }), + { bundlePath: (token: string) => probeAnnotateBundlePath(token, ctx.cwd) }, ); - if (selection.kind === "single") { + if (selection.kind === "bundle") { + const checked = resolveAnnotateBundleFiles( + selection.files.map((file) => file.value), + { convertHtml: renderMarkdownFlag }, + ); + if (!checked.ok) { + ctx.ui.notify(checked.message, "error"); + return; + } + bundleFiles = checked.files; + } else if (selection.kind === "single") { filePath = selection.candidate.value; rawFilePath = selection.candidate.value; } else if (selection.kind === "multiple") { - ctx.ui.notify(buildAmbiguousAnnotateArgsMessage(selection.candidates), "error"); + ctx.ui.notify(buildAmbiguousAnnotateArgsMessage(selection.candidates, { bundleHint: true }), "error"); return; } else if (selection.kind === "none" && selection.words.length > 1) { // Content flags only; --gate is transport for this @@ -959,14 +983,14 @@ export default function plannotator(pi: ExtensionAPI, deps: PlannotatorExtension let rawHtml: string | undefined; let absolutePath: string; let folderPath: string | undefined; - let mode: "annotate" | "annotate-folder" | "annotate-app" | undefined; + let mode: "annotate" | "annotate-folder" | "annotate-app" | "annotate-bundle" | undefined; let sourceInfo: string | undefined; let sourceConverted = false; let isFolder = false; let liveTargetUrl: string | undefined; // --- URL annotation --- - const isUrl = /^https?:\/\//i.test(filePath); + const isUrl = !bundleFiles && /^https?:\/\//i.test(filePath); // --app is contracted to fail loudly whenever it cannot apply; a // file or folder target silently swallowing it would hide the @@ -977,7 +1001,14 @@ export default function plannotator(pi: ExtensionAPI, deps: PlannotatorExtension return; } - if (isUrl) { + if (bundleFiles) { + // The deepest directory holding every file stands in for the + // session's path; the files ride the server's `bundleFiles`. + markdown = ""; + absolutePath = annotateBundleRoot(bundleFiles.map((file) => file.path)); + mode = "annotate-bundle"; + ctx.ui.notify(`Opening annotation UI for ${bundleFiles.length} files...`, "info"); + } else if (isUrl) { // --- Live app detection (shared probe: same 3s timeout, same // "< 500 + HTML + same loopback origin" gate as the Bun CLI) --- const { @@ -1122,6 +1153,7 @@ export default function plannotator(pi: ExtensionAPI, deps: PlannotatorExtension undefined, liveTargetUrl, sessionBridgeFor(ctx, origin), + bundleFiles, ); ctx.ui.notify(sessionOpenedMessage("Annotation opened", session.url), "info"); void session @@ -1145,15 +1177,20 @@ export default function plannotator(pi: ExtensionAPI, deps: PlannotatorExtension getAnnotateApprovedWithNotesPrompt, getAnnotateFileFeedbackPrompt, } = await loadPlannotatorPrompts(); - const context = `${isFolder ? "Folder" : "File"}: ${absolutePath}`; + // A bundle names every file of the review, in order. + const fileHeader = bundleFiles ? "Files" : isFolder ? "Folder" : "File"; + const targetText = bundleFiles + ? annotateBundleTargetText(bundleFiles.map((file) => file.path)) + : absolutePath; + const context = `${fileHeader}: ${targetText}`; const prompt = outcome.promptKind === "approved-with-notes" ? getAnnotateApprovedWithNotesPrompt("pi", loadConfig(), { context, feedback: outcome.feedback, }) : getAnnotateFileFeedbackPrompt("pi", loadConfig(), { - fileHeader: isFolder ? "Folder" : "File", - filePath: absolutePath, + fileHeader, + filePath: targetText, feedback: outcome.feedback, }); sendUserMessageWithCurrentSessionFallback( diff --git a/apps/pi-extension/plannotator-browser.ts b/apps/pi-extension/plannotator-browser.ts index b2f355342d..dd6cac8dc8 100644 --- a/apps/pi-extension/plannotator-browser.ts +++ b/apps/pi-extension/plannotator-browser.ts @@ -25,6 +25,7 @@ import { } from "./server.ts"; import { BROWSER_SESSION_STOPPED } from "./browser-session-error.ts"; import type { SessionBridge } from "./generated/ai/session-bridge.ts"; +import type { AnnotateBundleFile } from "./generated/annotate-bundle.ts"; import { openBrowser, isRemoteSession } from "./server/network.ts"; import { detectProjectName } from "./server/project.ts"; import { parsePRUrl, checkPRAuth, fetchPR } from "./server/pr.ts"; @@ -60,7 +61,7 @@ export { hasReviewBrowserHtml, } from "./plannotator-browser-runtime.ts"; -export type AnnotateMode = "annotate" | "annotate-folder" | "annotate-last" | "annotate-app"; +export type AnnotateMode = "annotate" | "annotate-folder" | "annotate-last" | "annotate-app" | "annotate-bundle"; export interface PlanReviewDecision { approved: boolean; feedback?: string; @@ -819,7 +820,9 @@ export async function startMarkdownAnnotationSession( liveTargetUrl?: string, /** "Ask this session": the bridge to the Pi session that opened this annotation. */ sessionBridge?: SessionBridge, -): Promise> { + /** Several files reviewed as one (mode "annotate-bundle"), in review order. */ + bundleFiles?: AnnotateBundleFile[], +): Promise> { if (!ctx.hasUI) { throw new Error("Plannotator annotation browser is unavailable in this session."); } @@ -864,6 +867,7 @@ export async function startMarkdownAnnotationSession( mode, liveApp, folderPath, + bundleFiles, recentMessages, sourceInfo, sourceConverted, diff --git a/apps/pi-extension/server/serverAnnotate-bundle.test.ts b/apps/pi-extension/server/serverAnnotate-bundle.test.ts new file mode 100644 index 0000000000..5272d6d98b --- /dev/null +++ b/apps/pi-extension/server/serverAnnotate-bundle.test.ts @@ -0,0 +1,15 @@ +/** + * Pi annotate server: several files reviewed as one. Same scenarios as the + * Bun server (packages/server/annotate-bundle.scenarios.ts), so the mirror + * cannot drift. + */ +import { defineAnnotateBundleScenarios } from "../../../packages/server/annotate-bundle.scenarios.ts"; +import { startAnnotateServer } from "./serverAnnotate.ts"; + +defineAnnotateBundleScenarios("pi", async (options) => { + const server = await startAnnotateServer({ + ...options, + htmlContent: "Plannotator", + }); + return { url: server.url, stop: server.stop }; +}); diff --git a/apps/pi-extension/server/serverAnnotate.ts b/apps/pi-extension/server/serverAnnotate.ts index d8b38a19f1..0b78961f05 100644 --- a/apps/pi-extension/server/serverAnnotate.ts +++ b/apps/pi-extension/server/serverAnnotate.ts @@ -67,7 +67,8 @@ import { type FolderAnnotateHistory, } from "./reference.ts"; import { closeAllFileBrowserWatchers, handleFileBrowserStreamRequest } from "./file-browser-watch.ts"; -import { getExtraMarkdownExtensions, MAX_ANNOTATABLE_FILE_BYTES, resolveUserPath, warmFileListCache } from "../generated/resolve-file.ts"; +import { getExtraMarkdownExtensions, isAnnotatableTextPath, MAX_ANNOTATABLE_FILE_BYTES, resolveUserPath, warmFileListCache } from "../generated/resolve-file.ts"; +import { annotateBundleDocumentCounts, annotateBundleRoot, type AnnotateBundleFile } from "../generated/annotate-bundle.ts"; import { createExternalAnnotationHandler } from "./external-annotations.ts"; import { createNodeAgentTerminalBridge } from "./agent-terminal.ts"; import { @@ -253,6 +254,8 @@ export async function startAnnotateServer(options: { origin?: string; mode?: string; folderPath?: string; + /** `annotate-bundle`: the files in review order (mirrors packages/server/annotate.ts). */ + bundleFiles?: AnnotateBundleFile[]; recentMessages?: { messageId: string; text: string; timestamp?: string }[]; sharingEnabled?: boolean; shareBaseUrl?: string; @@ -292,6 +295,14 @@ export async function startAnnotateServer(options: { throw new Error("Live app annotation is unavailable in remote mode"); } + // Several files reviewed as one: mirror of packages/server/annotate.ts. + const bundleFiles = options.mode === "annotate-bundle" ? [...(options.bundleFiles ?? [])] : null; + if (bundleFiles && bundleFiles.length < 2) { + throw new Error("An annotate bundle needs at least two files"); + } + const bundlePaths = bundleFiles ? bundleFiles.map((file) => file.path) : []; + const bundleRoot = bundleFiles ? annotateBundleRoot(bundlePaths) : null; + const gitUser = detectGitUser(); const sharingEnabled = options.sharingEnabled ?? resolveSharingEnabled(loadConfig()); @@ -377,7 +388,9 @@ export async function startAnnotateServer(options: { ? `annotate-app\0${liveAppDraftIdentity(options.liveApp.targetUrl)}` : options.mode === "annotate-folder" && options.folderPath ? `folder:${resolvePath(options.folderPath)}` - : options.renderHtml && options.rawHtml ? options.rawHtml : options.markdown; + : bundleFiles + ? `bundle:\0${bundlePaths.join("\0")}` + : options.renderHtml && options.rawHtml ? options.rawHtml : options.markdown; const draftKey = contentHash(draftSource); // Drafts follow the file as well as its text: mirror of the Bun server // (packages/server/annotate.ts), logic in annotate-draft.ts. Not governed @@ -390,7 +403,7 @@ export async function startAnnotateServer(options: { contentKey: draftKey, filePath: draftFilePath, documents: - draftFilePath !== null || (options.mode === "annotate-folder" && options.folderPath) + draftFilePath !== null || (options.mode === "annotate-folder" && options.folderPath) || bundleFiles ? { isAllowed: (path) => isPathAllowed(path, getReferenceRootPaths()), } @@ -406,7 +419,9 @@ export async function startAnnotateServer(options: { ? [] : options.mode === "annotate-folder" && options.folderPath ? [options.folderPath] - : options.mode === "annotate-app" && options.liveApp + : bundleFiles + ? [...bundlePaths] + : options.mode === "annotate-app" && options.liveApp ? [options.liveApp.targetUrl] : options.filePath ? [options.filePath] : []; const hostControl: HostControl = { @@ -481,6 +496,18 @@ export async function startAnnotateServer(options: { folderAnnotateHistoryCache.set(resolvedFilePath, result); return result; } + // A bundle saves each text file's version history when it opens (mirrors + // packages/server/annotate.ts). + if (bundleFiles && annotateHistoryEnabled) { + for (const file of bundleFiles) { + if (file.renderAs === "html" || !isAnnotatableTextPath(file.path)) continue; + try { + computeFolderAnnotateHistory(file.path, readFileSync(file.path, "utf-8")); + } catch { + // Unreadable now: /api/doc reports the problem when it is opened. + } + } + } // Durable submit records (#678): the caller consuming waitForDecision() may // be gone (agent-side timeout) by the time the reviewer clicks submit — @@ -522,7 +549,9 @@ export async function startAnnotateServer(options: { ? "annotate-last" : options.mode === "annotate-folder" ? "annotate-folder" - : singleFileLocalAnnotate + : bundleFiles + ? "annotate-bundle" + : singleFileLocalAnnotate ? "annotate" : "annotate-url"; @@ -543,7 +572,9 @@ export async function startAnnotateServer(options: { target: options.mode === "annotate-app" && options.liveApp ? { url: options.liveApp.targetUrl } - : isUrlTarget + : bundleFiles + ? { documents: annotateBundleDocumentCounts(bundlePaths, annotationList) } + : isUrlTarget ? { url: options.filePath } : options.mode === "annotate-last" ? { filePath: options.filePath } @@ -602,7 +633,8 @@ export async function startAnnotateServer(options: { function isAllowedHtmlSharePath(targetPath: string): boolean { const roots = new Set([process.cwd()]); if (options.folderPath) roots.add(options.folderPath); - if (!/^https?:\/\//i.test(options.filePath)) roots.add(dirname(options.filePath)); + for (const path of bundlePaths) roots.add(dirname(path)); + if (!bundleFiles && !/^https?:\/\//i.test(options.filePath)) roots.add(dirname(options.filePath)); for (const root of roots) { if (isWithinDirectory(targetPath, root)) return true; } @@ -727,7 +759,7 @@ export async function startAnnotateServer(options: { if (mode === "annotate-last") { return { plan: options.markdown, sourceSave: disabledSourceSave("message-mode") }; } - if (mode === "annotate-folder") { + if (mode === "annotate-folder" || bundleFiles) { return { plan: options.markdown, sourceSave: disabledSourceSave("folder-mode") }; } if (options.renderHtml && options.rawHtml) { @@ -773,6 +805,7 @@ export async function startAnnotateServer(options: { filePath: options.filePath, folderPath: options.folderPath, initialSingleFileSourcePath, + bundlePaths, }); // Live app session state, populated after the annotate port is known (the @@ -914,7 +947,9 @@ export async function startAnnotateServer(options: { shareBaseUrl, pasteApiUrl, repoInfo, - projectRoot: options.folderPath || process.cwd(), + projectRoot: options.folderPath || bundleRoot || process.cwd(), + // The bundle's files in review order (annotate-bundle only). + ...(bundleFiles ? { bundle: bundleFiles } : {}), // Extra extensions the user registered as markdown (#1307). // The renderer needs them to linkify relative/wiki links to // sibling docs the same way it linkifies .md ones. @@ -1113,7 +1148,12 @@ export async function startAnnotateServer(options: { // Inject source file's directory as base for relative path resolution. // Skip for URL annotations — there's no local directory to resolve against. if (!url.searchParams.has("base") && options.filePath && !/^https?:\/\//i.test(options.filePath)) { - url.searchParams.set("base", options.mode === "annotate-folder" && options.folderPath ? options.folderPath : dirname(resolvePath(options.filePath))); + url.searchParams.set( + "base", + options.mode === "annotate-folder" && options.folderPath + ? options.folderPath + : bundleRoot ?? dirname(resolvePath(options.filePath)), + ); } if (options.convertHtml && !url.searchParams.has("convert")) { url.searchParams.set("convert", "1"); @@ -1127,7 +1167,7 @@ export async function startAnnotateServer(options: { onSourceDocumentServed: (path) => openedSourceFilePaths.add(path), rootPaths: getReferenceRootPaths(), annotateHistory: - options.mode === "annotate-folder" && annotateHistoryEnabled + (options.mode === "annotate-folder" || bundleFiles) && annotateHistoryEnabled ? { compute: computeFolderAnnotateHistory } : undefined, rootHtmlVersionDiff, diff --git a/apps/pi-extension/vendor.sh b/apps/pi-extension/vendor.sh index 605433e5ec..0d6f493712 100755 --- a/apps/pi-extension/vendor.sh +++ b/apps/pi-extension/vendor.sh @@ -8,7 +8,7 @@ rm -rf generated mkdir -p generated generated/ai/providers # Modules that MOVED to @plannotator/core — vendor the real impl from core. -for f in feedback-templates project diff-type review-prompt guide-prompt favicon forge-refs code-file annotatable annotation-threads diagram-anchor html-anchor markdown-structure question-block external-annotation agent-jobs agent-terminal source-save open-in-apps diff-paths diff-files guide guide-format guide-viewer-manifest compress crypto; do +for f in feedback-templates project diff-type review-prompt guide-prompt favicon forge-refs code-file annotatable annotate-bundle annotation-threads diagram-anchor html-anchor markdown-structure question-block external-annotation agent-jobs agent-terminal source-save open-in-apps diff-paths diff-files guide guide-format guide-viewer-manifest compress crypto; do src="../../packages/core/$f.ts" printf '// @generated — DO NOT EDIT. Source: packages/core/%s.ts\n' "$f" | cat - "$src" > "generated/$f.ts" done diff --git a/apps/skills/core/plannotator/SKILL.md b/apps/skills/core/plannotator/SKILL.md index 50b9b173fa..0d43aa4275 100644 --- a/apps/skills/core/plannotator/SKILL.md +++ b/apps/skills/core/plannotator/SKILL.md @@ -87,10 +87,11 @@ Targets: - URLs (`https://...`): fetched and converted via Jina Reader by default; `--no-jina` uses plain fetch plus Turndown instead. - Running local apps: a loopback `http://localhost:PORT/` URL whose probe returns HTML opens in live-app mode (annotate the real running page). `--app` forces live mode and fails loudly when it cannot apply; `--static` forces the classic conversion pipeline. Non-loopback URLs always use the conversion pipeline. - Folders: `plannotator annotate docs/` opens a file browser over the folder's supported files. +- Several files: `plannotator annotate spec.md mock.html notes.md` opens them as one review, in the order given, with one decision. Every argument must be an existing file named by its path (no prose, URLs or folders among them). With the `plannotator` tool, pass the list as `target`. Single files are capped at 2MB. Files are read from disk at stable project paths; keep the reviewed source where it lives. -Argument tolerance: extra words are fine (`plannotator annotate look at notes.md please` opens `notes.md`), but two resolvable targets is an error naming both, and an unrecognized dashed token disables the tolerance so flag typos fail loudly. When nothing resolves in a plain multi-word invocation, the CLI prints an agent-addressed handoff on stdout and exits 0: read it, work out the concrete target, and re-run with that exact path or URL. +Argument tolerance: extra words are fine (`plannotator annotate look at notes.md please` opens `notes.md`), but two resolvable targets mixed with prose, a URL or a folder is an error naming them, and an unrecognized dashed token disables the tolerance so flag typos fail loudly. When nothing resolves in a plain multi-word invocation, the CLI prints an agent-addressed handoff on stdout and exits 0: read it, work out the concrete target, and re-run with that exact path or URL. ### Strict gates and exit codes diff --git a/packages/ai/context.ts b/packages/ai/context.ts index d7c84140da..f1fc9cee32 100644 --- a/packages/ai/context.ts +++ b/packages/ai/context.ts @@ -95,6 +95,9 @@ export function buildForkPreamble(ctx: AIContext): string { } case "annotate": { lines.push(`## Annotating: ${ctx.annotate.filePath}`); + if (ctx.annotate.bundlePosition) { + lines.push(`File ${ctx.annotate.bundlePosition.index} of ${ctx.annotate.bundlePosition.total} in a review of several files.`); + } if (ctx.annotate.sourceInfo) { lines.push(`Source: ${ctx.annotate.sourceInfo}`); } @@ -223,6 +226,10 @@ function buildAnnotatePrompt( `## Document: ${ctx.annotate.filePath}`, ]; + if (ctx.annotate.bundlePosition) { + sections.push(`File ${ctx.annotate.bundlePosition.index} of ${ctx.annotate.bundlePosition.total} in a review of several files.`); + } + if (ctx.annotate.sourceInfo) { sections.push(`Source: ${ctx.annotate.sourceInfo}`); } diff --git a/packages/ai/session-bridge.test.ts b/packages/ai/session-bridge.test.ts index 583915e54d..cef8db01da 100644 --- a/packages/ai/session-bridge.test.ts +++ b/packages/ai/session-bridge.test.ts @@ -9,6 +9,7 @@ import { SESSION_BRIDGE_ERROR, SESSION_BRIDGE_PROVIDER_NAME, SessionBridgeProvider, + formatSessionAskText, type SessionBridge, type SessionBridgeAskRequest, type SessionBridgeSink, @@ -395,3 +396,16 @@ describe("Ask this session over the shared /api/ai endpoints", () => { expect(res.status).toBe(403); }); }); + +describe("the question's surface line", () => { + // A review of several files: the session must know which file the reviewer + // is asking about and where it sits, or "this file" is ambiguous. + test("names the open file's place in a review of several files", () => { + const text = formatSessionAskText( + { mode: "annotate", annotate: { content: "

Mock

", filePath: "/repo/mock.html", bundlePosition: { index: 2, total: 3 } } }, + "Why this layout?", + ); + expect(text).toContain("Surface: annotating /repo/mock.html, file 2 of 3"); + expect(formatSessionAskText(CONTEXT, "Q")).toContain("Surface: annotating /repo/notes.md\n"); + }); +}); diff --git a/packages/ai/session-bridge.ts b/packages/ai/session-bridge.ts index d26e22e701..21ad65c274 100644 --- a/packages/ai/session-bridge.ts +++ b/packages/ai/session-bridge.ts @@ -169,10 +169,12 @@ function describeSurface(context: AIContext): string | null { case "plan-review": return "Surface: plan review"; case "annotate": { - const { filePath, sourceInfo } = context.annotate; + const { filePath, sourceInfo, bundlePosition } = context.annotate; if (filePath === "last-message") return "Surface: annotating your last message"; const where = sourceInfo && /^https?:\/\//i.test(sourceInfo) ? sourceInfo : filePath; - return where ? `Surface: annotating ${where}` : "Surface: annotating a document"; + // A review of several files names the open file's place in it. + const position = bundlePosition ? `, file ${bundlePosition.index} of ${bundlePosition.total}` : ""; + return where ? `Surface: annotating ${where}${position}` : "Surface: annotating a document"; } default: return null; diff --git a/packages/core/agent-terminal.ts b/packages/core/agent-terminal.ts index a0e860d5f8..b5f15d2212 100644 --- a/packages/core/agent-terminal.ts +++ b/packages/core/agent-terminal.ts @@ -43,13 +43,14 @@ export type AnnotateAgentTerminalMode = | "annotate" | "annotate-last" | "annotate-folder" + | "annotate-bundle" | string | undefined; export function supportsAnnotateAgentTerminalMode( mode: AnnotateAgentTerminalMode, ): boolean { - return mode === "annotate" || mode === "annotate-folder"; + return mode === "annotate" || mode === "annotate-folder" || mode === "annotate-bundle"; } /** diff --git a/packages/core/ai-context.ts b/packages/core/ai-context.ts index a3130f72f6..f54b90f012 100644 --- a/packages/core/ai-context.ts +++ b/packages/core/ai-context.ts @@ -72,6 +72,8 @@ export interface AnnotateContext { renderAs?: "markdown" | "html"; /** Summary of annotations the user has made. */ annotations?: string; + /** A review of several files: where the open file sits (1-based `index` of `total`). */ + bundlePosition?: { index: number; total: number }; } /** diff --git a/packages/core/annotate-bundle.test.ts b/packages/core/annotate-bundle.test.ts new file mode 100644 index 0000000000..8ac2667e97 --- /dev/null +++ b/packages/core/annotate-bundle.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, test } from "bun:test"; +import { + annotateBundleDocumentCounts, + annotateBundleRelativePath, + annotateBundleRoot, + parseAnnotateBundle, +} from "./annotate-bundle"; + +describe("annotateBundleRoot", () => { + // The failure: a string-prefix comparison makes /repo/doc the root of + // /repo/docs/a.md and /repo/doc/b.md, so labels lose a path segment. + test("is the deepest directory holding every file, compared by segment", () => { + expect(annotateBundleRoot(["/repo/docs/a.md", "/repo/docs/sub/b.md"])).toBe("/repo/docs"); + expect(annotateBundleRoot(["/repo/docs/a.md", "/repo/doc/b.md"])).toBe("/repo"); + expect(annotateBundleRoot(["/a/x.md", "/b/y.md"])).toBe("/"); + expect(annotateBundleRoot(["C:\\work\\a.md", "C:\\work\\ui\\b.html"])).toBe("C:/work"); + }); + + test("labels stay relative to it, and absolute outside it", () => { + expect(annotateBundleRelativePath("/repo/docs/sub/b.md", "/repo/docs")).toBe("sub/b.md"); + expect(annotateBundleRelativePath("/a/x.md", "")).toBe("a/x.md"); + }); +}); + +describe("parseAnnotateBundle", () => { + test("accepts two or more distinct files with known render modes, and nothing else", () => { + const files = [ + { path: "/r/a.md", renderAs: "markdown" }, + { path: "/r/b.html", renderAs: "html" }, + ]; + expect(parseAnnotateBundle(files)).toEqual(files as never); + expect(parseAnnotateBundle([files[0]])).toBeNull(); + expect(parseAnnotateBundle([files[0], files[0]])).toBeNull(); + expect(parseAnnotateBundle([files[0], { path: "/r/c.pdf", renderAs: "pdf" }])).toBeNull(); + expect(parseAnnotateBundle("nope")).toBeNull(); + }); +}); + +describe("annotateBundleDocumentCounts", () => { + test("counts each file's comments in bundle order; bundle-level notes count toward none", () => { + expect( + annotateBundleDocumentCounts(["/r/b.md", "/r/a.md"], [ + { documentPath: "/r/a.md" }, + { documentPath: "/r/a.md" }, + { id: "bundle-note" }, + null, + ]), + ).toEqual([ + { path: "/r/b.md", annotationCount: 0 }, + { path: "/r/a.md", annotationCount: 2 }, + ]); + }); +}); diff --git a/packages/core/annotate-bundle.ts b/packages/core/annotate-bundle.ts new file mode 100644 index 0000000000..f18f0a5fe6 --- /dev/null +++ b/packages/core/annotate-bundle.ts @@ -0,0 +1,142 @@ +/** + * Annotate bundles: several files opened as ONE annotate review, in the order + * the agent (or the user) named them, with one decision for all of them. + * + * `plannotator annotate spec.md mock.html notes.md` (every argument an + * existing, annotatable file named by its path) and the `plannotator` tool's + * `target: [...]` open a bundle. The servers run it as `annotate-bundle`, a + * folder-like session restricted to the explicit, ordered list: /api/plan + * carries `bundle` (this module's `AnnotateBundleFile[]`), the file list keeps + * the given order, and the feedback has one section per file in that order. + * + * Browser-safe and dependency-free: the editor, both servers and the hosts + * share these helpers. The node-side argument rule (which tokens make a + * bundle) lives in `packages/shared/annotate-target.ts`. + */ + +/** How one bundle file renders, the same values /api/doc names in `renderAs`. */ +export type AnnotateBundleRenderAs = "markdown" | "html" | "mermaid" | "graphviz"; + +/** One file of a bundle, in bundle order. `path` is absolute. */ +export interface AnnotateBundleFile { + path: string; + renderAs: AnnotateBundleRenderAs; +} + +const RENDER_AS: readonly AnnotateBundleRenderAs[] = ["markdown", "html", "mermaid", "graphviz"]; + +function separatorFree(path: string): string { + return path.replace(/\\/g, "/"); +} + +/** The file name of a path (either separator). */ +export function annotateBundleBaseName(path: string): string { + const normalized = separatorFree(path).replace(/\/+$/, ""); + return normalized.slice(normalized.lastIndexOf("/") + 1) || normalized; +} + +/** + * The deepest directory that contains every file of the bundle: the root the + * file list labels paths against. `/` (or a drive root) when the files share + * nothing else. Paths are compared segment by segment, never by string prefix. + */ +export function annotateBundleRoot(paths: readonly string[]): string { + if (paths.length === 0) return "/"; + const split = paths.map((path) => separatorFree(path).split("/")); + // Each path's directory segments (the file name is not a directory). + const dirs = split.map((segments) => segments.slice(0, -1)); + const first = dirs[0] as string[]; + let shared = first.length; + for (const segments of dirs.slice(1)) { + let index = 0; + while (index < shared && index < segments.length && segments[index] === first[index]) index += 1; + shared = index; + } + const common = first.slice(0, shared); + if (common.length === 0) return "/"; + const joined = common.join("/"); + // "" is the POSIX root; "C:" a Windows drive root. + if (joined === "") return "/"; + if (/^[A-Za-z]:$/.test(joined)) return `${joined}/`; + return joined; +} + +/** A path relative to the bundle root, for labels ("docs/spec.md"). */ +export function annotateBundleRelativePath(path: string, root: string): string { + const normalized = separatorFree(path); + const base = separatorFree(root).replace(/\/+$/, ""); + if (base === "") return normalized.replace(/^\/+/, ""); + return normalized.startsWith(`${base}/`) ? normalized.slice(base.length + 1) : normalized; +} + +/** "file 2 of 3": where the open file sits in its bundle (1-based). */ +export function annotateBundlePositionText(index: number, total: number): string { + return `file ${index} of ${total}`; +} + +/** + * The `bundle` field of an /api/plan answer, validated: a list of two or + * more `{ path, renderAs }` with distinct absolute-looking paths. Anything + * else is null, so a malformed payload opens no bundle UI. + */ +export function parseAnnotateBundle(value: unknown): AnnotateBundleFile[] | null { + if (!Array.isArray(value) || value.length < 2) return null; + const files: AnnotateBundleFile[] = []; + const seen = new Set(); + for (const entry of value) { + const candidate = entry as { path?: unknown; renderAs?: unknown } | null; + if (!candidate || typeof candidate.path !== "string" || candidate.path.length === 0) return null; + if (!RENDER_AS.includes(candidate.renderAs as AnnotateBundleRenderAs)) return null; + if (seen.has(candidate.path)) return null; + seen.add(candidate.path); + files.push({ path: candidate.path, renderAs: candidate.renderAs as AnnotateBundleRenderAs }); + } + return files; +} + +/** + * The files of a bundle on one line, for the `File: ` slot of the + * annotate feedback prompts (the header there reads "Files"). + */ +export function annotateBundleTargetText(paths: readonly string[]): string { + return paths.join(", "); +} + +/** One bundle file and how many submitted comments were made on it. */ +export interface AnnotateBundleDocumentCount { + path: string; + annotationCount: number; +} + +/** + * Per-file comment counts for a submitted bundle decision, in bundle order: + * the `documents` field the host result record and the feedback archive + * carry. A submitted annotation names its file in `documentPath` (the editor + * sets it on every comment made on a document other than the session's own, + * and a bundle has no document of its own); comments without one (the + * bundle-level notes) count toward no file. + */ +export function annotateBundleDocumentCounts( + paths: readonly string[], + annotations: readonly unknown[], +): AnnotateBundleDocumentCount[] { + const counts = new Map(); + for (const annotation of annotations) { + const documentPath = (annotation as { documentPath?: unknown } | null)?.documentPath; + if (typeof documentPath !== "string") continue; + const key = separatorFree(documentPath); + counts.set(key, (counts.get(key) ?? 0) + 1); + } + return paths.map((path) => ({ path, annotationCount: counts.get(separatorFree(path)) ?? 0 })); +} + +/** + * The index of `path` in the bundle, or -1. Paths compare with either + * separator so a Windows path the server sends matches the one the editor + * built. + */ +export function annotateBundleIndexOf(files: readonly AnnotateBundleFile[], path: string | null | undefined): number { + if (!path) return -1; + const wanted = separatorFree(path); + return files.findIndex((file) => separatorFree(file.path) === wanted); +} diff --git a/packages/core/package.json b/packages/core/package.json index efaa15afc3..dea6acfa1a 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -13,6 +13,7 @@ "./diff-type": "./diff-type.ts", "./review-prompt": "./review-prompt.ts", "./annotatable": "./annotatable.ts", + "./annotate-bundle": "./annotate-bundle.ts", "./annotation-threads": "./annotation-threads.ts", "./agent-jobs": "./agent-jobs.ts", "./agent-terminal": "./agent-terminal.ts", diff --git a/packages/editor/App.bundle.test.tsx b/packages/editor/App.bundle.test.tsx new file mode 100644 index 0000000000..314bfd73d0 --- /dev/null +++ b/packages/editor/App.bundle.test.tsx @@ -0,0 +1,220 @@ +/** + * A review of several files (annotate-bundle) in the editor: the first file + * opens by itself, the switcher and the file list follow the given order + * (never sorted), Next moves to the following file, and one Send Feedback + * carries one section per file in bundle order with each comment once. + * + * Requires DOM (happy-dom) — runs under DOM_TESTS=1. + */ + +import { afterAll, afterEach, describe, expect, test } from "bun:test"; +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { + resetStorageBackend, + setStorageBackend, + type StorageBackend, +} from "@plannotator/ui/utils/storage"; + +const hasDom = typeof document !== "undefined"; + +const appModule = hasDom ? await import("./App") : null; +const App = appModule?.default as typeof import("./App")["default"]; + +const originalFetch = globalThis.fetch; +const originalEventSource = globalThis.EventSource; + +const memory = new Map(); +const memoryBackend: StorageBackend = { + getItem: (key) => memory.get(key) ?? null, + setItem: (key, value) => void memory.set(key, value), + removeItem: (key) => void memory.delete(key), +}; + +function seedAnnouncementsSeen(): void { + memory.set("plannotator-look-feel-announcement-seen", "2"); + memory.set("plannotator-announce-tui-herdr-seen", "1"); + memory.set("plannotator-vim-mode-announcement-seen", "2"); + memory.set("plannotator-plan-ai-announcement-seen", "1"); +} + +class SilentEventSource { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSED = 2; + readonly CONNECTING = 0; + readonly OPEN = 1; + readonly CLOSED = 2; + readonly readyState = SilentEventSource.OPEN; + readonly url: string; + readonly withCredentials = false; + onerror: ((event: Event) => void) | null = null; + onmessage: ((event: MessageEvent) => void) | null = null; + onopen: ((event: Event) => void) | null = null; + constructor(url: string | URL) { + this.url = String(url); + } + addEventListener(): void {} + close(): void {} + dispatchEvent(): boolean { return true; } + removeEventListener(): void {} +} + +const ROOT = "/tmp/bundle-review"; +// Given in this order on purpose: sorted by name, alpha would come first. +const BETA = `${ROOT}/docs/beta.md`; +const ALPHA = `${ROOT}/alpha.md`; +const TEXT: Record = { + [BETA]: "# Beta\n\nBeta body text.\n", + [ALPHA]: "# Alpha\n\nAlpha body text.\n", +}; + +/** A saved comment on each file, merged in when the file opens. */ +const savedComment = (path: string) => ({ + id: `saved-${path.endsWith("beta.md") ? "beta" : "alpha"}`, + blockId: "", + startOffset: 0, + endOffset: 4, + type: "COMMENT", + text: path.endsWith("beta.md") ? "BETA_COMMENT_SENTINEL" : "ALPHA_COMMENT_SENTINEL", + originalText: path.endsWith("beta.md") ? "Beta" : "Alpha", + createdA: 1, +}); + +interface Recorded { method: string; path: string; search: URLSearchParams; body?: string } +const requests: Recorded[] = []; + +const fakeFetch: typeof fetch = async (input, init) => { + const rawUrl = input instanceof Request ? input.url : String(input); + if (rawUrl.startsWith("https://api.github.com/")) return new Response(null, { status: 404 }); + const url = new URL(rawUrl, "http://localhost"); + const method = (init?.method ?? "GET").toUpperCase(); + requests.push({ method, path: url.pathname, search: url.searchParams, body: typeof init?.body === "string" ? init.body : undefined }); + if (url.pathname === "/api/plan") { + return Response.json({ + plan: "", + origin: "claude-code", + mode: "annotate-bundle", + bundle: [ + { path: BETA, renderAs: "markdown" }, + { path: ALPHA, renderAs: "markdown" }, + ], + filePath: ROOT, + projectRoot: ROOT, + documentDrafts: true, + sharingEnabled: false, + serverConfig: {}, + }); + } + if (url.pathname === "/api/doc") { + const path = url.searchParams.get("path") ?? ""; + return Response.json({ markdown: TEXT[path] ?? "", filepath: path, renderAs: "markdown" }); + } + if (url.pathname === "/api/draft/document" && method === "GET") { + const path = url.searchParams.get("path") ?? ""; + return Response.json({ found: true, annotations: [savedComment(path)], globalAttachments: [] }); + } + if (url.pathname === "/api/draft" && method === "GET") return Response.json({ found: false }, { status: 404 }); + if (url.pathname === "/api/ai/capabilities") return Response.json({ available: false, providers: [] }); + return Response.json({ ok: true }); +}; + +let root: Root | null = null; +let host: HTMLElement | null = null; + +async function settle(ms = 0): Promise { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, ms)); + }); +} + +async function waitFor(check: () => boolean, label: string): Promise { + for (let attempt = 0; attempt < 60; attempt += 1) { + if (check()) return; + await settle(25); + } + throw new Error(`timed out waiting for ${label}`); +} + +const switcherText = () => document.querySelector("[data-bundle-switcher]")?.textContent ?? ""; + +async function mount(): Promise { + setStorageBackend(memoryBackend); + seedAnnouncementsSeen(); + globalThis.fetch = fakeFetch; + // SAFETY: the App only uses EventSource's constructor, handlers, and close. + globalThis.EventSource = SilentEventSource as unknown as typeof EventSource; + host = document.createElement("div"); + document.body.appendChild(host); + root = createRoot(host); + await act(async () => { root?.render(); }); + await waitFor(() => switcherText().includes("1 of 2"), "the first file to open"); +} + +afterEach(async () => { + if (root) await act(async () => root?.unmount()); + root = null; + host?.remove(); + host = null; + globalThis.fetch = originalFetch; + globalThis.EventSource = originalEventSource; + if (hasDom) document.body.replaceChildren(); + memory.clear(); + requests.length = 0; + resetStorageBackend(); +}); + +afterAll(() => { + resetStorageBackend(); +}); + +const docRequests = () => requests.filter((r) => r.path === "/api/doc").map((r) => r.search.get("path")); + +describe.if(hasDom)("annotate bundle", () => { + test("the first file opens by itself; the switcher and the file list keep the given order", async () => { + await mount(); + expect(docRequests()[0]).toBe(BETA); + expect(switcherText()).toContain("beta.md"); + expect(document.querySelector('[aria-label="Previous file"]')?.hasAttribute("disabled")).toBe(true); + + // The Files tab lists exactly the bundle, unsorted (beta before alpha), + // labelled relative to the files' common directory. + const items = Array.from(document.querySelectorAll(".file-tree-item")).map((el) => el.getAttribute("title")); + expect(items).toEqual(["docs/beta.md", "alpha.md"]); + // The bundle's directory is never walked as a folder. + expect(requests.some((r) => r.path === "/api/reference/files")).toBe(false); + }); + + test("Next opens the following file, and one Send Feedback has one section per file in bundle order", async () => { + await mount(); + await act(async () => { + document.querySelector('[aria-label="Next file"]')!.click(); + }); + await waitFor(() => switcherText().includes("2 of 2"), "the second file"); + expect(switcherText()).toContain("alpha.md"); + expect(docRequests()).toContain(ALPHA); + // Both files' saved comments are in the session now. + await waitFor(() => !!document.querySelector("[data-decision-primary]")?.textContent?.includes("Send Feedback"), "Send Feedback"); + + await act(async () => { + document.querySelector("[data-decision-primary]")!.click(); + }); + await waitFor(() => requests.some((r) => r.path === "/api/feedback"), "the decision"); + const body = JSON.parse(requests.find((r) => r.path === "/api/feedback")!.body ?? "{}") as { + feedback: string; + annotations: { id: string; documentPath?: string }[]; + }; + + // One section per file, in the order given (beta, then alpha), each comment once. + const betaAt = body.feedback.indexOf(`## ${BETA}`); + const alphaAt = body.feedback.indexOf(`## ${ALPHA}`); + expect(betaAt).toBeGreaterThan(-1); + expect(alphaAt).toBeGreaterThan(betaAt); + expect(body.feedback.split("BETA_COMMENT_SENTINEL")).toHaveLength(2); + expect(body.feedback.split("ALPHA_COMMENT_SENTINEL")).toHaveLength(2); + expect(body.annotations.map((a) => [a.id, a.documentPath]).sort()).toEqual([ + ["saved-alpha", ALPHA], + ["saved-beta", BETA], + ]); + }); +}); diff --git a/packages/editor/App.tsx b/packages/editor/App.tsx index f4e7caf494..b83e0cd1b7 100644 --- a/packages/editor/App.tsx +++ b/packages/editor/App.tsx @@ -15,6 +15,15 @@ import React, { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallba import { toast, Toaster } from 'sonner'; import { type Origin, getAgentName } from '@plannotator/shared/agents'; import { isDiagramRenderKind, shouldStripFrontmatter } from '@plannotator/shared/annotatable'; +import { + annotateBundleBaseName, + annotateBundleIndexOf, + annotateBundleRelativePath, + annotateBundleRoot, + annotateBundleTargetText, + parseAnnotateBundle, + type AnnotateBundleFile, +} from '@plannotator/shared/annotate-bundle'; import { setExtraMarkdownExtensions } from '@plannotator/ui/utils/markdownExtensions'; import { documentRendersHtml, htmlAssetRouteFromDocument, resolveHtmlLinkIntent } from '@plannotator/ui/utils/htmlLinkNavigation'; import { ImageLightbox } from '@plannotator/ui/components/ImageLightbox'; @@ -130,7 +139,7 @@ import { useExternalAnnotationHighlights } from '@plannotator/ui/hooks/useExtern import { useUndoHistory } from '@plannotator/ui/hooks/useUndoHistory'; import { buildPlanAgentInstructions } from '@plannotator/ui/utils/planAgentInstructions'; import { buildAnnotateAgentInstructions, resolveAnnotateInstructionsSurface } from '@plannotator/ui/utils/annotateAgentInstructions'; -import { useFileBrowser } from '@plannotator/ui/hooks/useFileBrowser'; +import { useFileBrowser, type DirState } from '@plannotator/ui/hooks/useFileBrowser'; import { getFileEditStatus } from '@plannotator/ui/components/sidebar/FileBrowser'; import { isVaultBrowserEnabled } from '@plannotator/ui/utils/obsidian'; import { isFileBrowserEnabled, getFileBrowserSettings } from '@plannotator/ui/utils/fileBrowser'; @@ -650,6 +659,10 @@ const App: React.FC = () => { const [approvalNotesSupported, setApprovalNotesSupported] = useState(false); const [clientLease, setClientLease] = useState(null); const [annotateSource, setAnnotateSource] = useState<'file' | 'message' | 'folder' | null>(null); + // A review of several files (annotate-bundle): a folder-like session over + // this explicit, ordered list (annotateSource stays 'folder'). + const [bundleFiles, setBundleFiles] = useState(null); + const bundlePaths = useMemo(() => bundleFiles?.map((file) => file.path) ?? null, [bundleFiles]); const [recentMessages, setRecentMessages] = useState([]); const [selectedMessageId, setSelectedMessageId] = useState(null); const messageStateCacheRef = useRef>(new Map()); @@ -1753,12 +1766,41 @@ const App: React.FC = () => { }); const fileBrowserDirs = useMemo(() => { - const projectDirs = projectRoot ? [projectRoot] : []; + // A bundle's root only labels its files: the Files tab lists the bundle + // itself (bundleDirState below), never a walk of that directory. + const projectDirs = projectRoot && !bundleFiles ? [projectRoot] : []; const userDirs = isFileBrowserEnabled() ? getFileBrowserSettings().directories : []; return [...new Set([...projectDirs, ...userDirs])]; - }, [projectRoot, uiPrefs]); + }, [projectRoot, bundleFiles, uiPrefs]); + + // The bundle as a fixed file-browser section: its files in the given order + // (never sorted), labelled relative to the deepest directory holding them + // all. It is not fetched or watched; the Files tab and the WebMCP document + // list see it beside any directories the user configured. + const bundleDirState = useMemo(() => { + if (!bundleFiles) return null; + const root = annotateBundleRoot(bundleFiles.map((file) => file.path)); + // The file browser joins `${dir.path}/${node.path}`; the filesystem root + // is therefore the empty string, so "/" + "a/b.md" stays absolute. + const dirPath = root.replace(/[\\/]+$/, ''); + return { + path: dirPath, + name: `${bundleFiles.length} files in this review`, + tree: bundleFiles.map((file) => { + const relative = annotateBundleRelativePath(file.path, dirPath); + return { name: relative, path: relative, type: 'file' as const }; + }), + isLoading: false, + error: null, + hasLoadedTree: true, + }; + }, [bundleFiles]); + const navigatorFileBrowser = useMemo( + () => (bundleDirState ? { ...fileBrowser, dirs: [bundleDirState, ...fileBrowser.dirs] } : fileBrowser), + [bundleDirState, fileBrowser], + ); // Clear active file when file browser is disabled useEffect(() => { @@ -1960,6 +2002,31 @@ const App: React.FC = () => { }); }, [editableDocuments, linkedDocHook, fileBrowser, convertHtml, isEditingMarkdown]); + // --- Review of several files (annotate-bundle) --------------------------- + // Opening a bundle file goes through the file-browser selection path, so + // the active file, the doc URL and the linked document stay in step exactly + // as in a folder session. The open document's place in the bundle drives + // the header switcher, the Ask AI surface line and the export order. + const bundleIndex = bundleFiles + ? annotateBundleIndexOf(bundleFiles, linkedDocHook.isActive ? linkedDocHook.filepath : null) + : -1; + const openBundleFile = React.useCallback((path: string, options?: { revealSidebar?: boolean }) => { + if (!bundleDirState) return Promise.resolve(); + return handleFileBrowserSelect(path, bundleDirState.path, options); + }, [bundleDirState, handleFileBrowserSelect]); + const openBundleFileAt = React.useCallback((index: number) => { + const file = bundleFiles?.[index]; + // The switcher moves through the files without popping the sidebar open. + if (file) void openBundleFile(file.path, { revealSidebar: false }); + }, [bundleFiles, openBundleFile]); + // The first file opens as soon as the session loads. + const bundleOpenedRef = useRef(false); + useEffect(() => { + if (!bundleFiles || bundleOpenedRef.current || isLoading) return; + bundleOpenedRef.current = true; + openBundleFileAt(0); + }, [bundleFiles, isLoading, openBundleFileAt]); + // Route linked doc opens through the correct endpoint based on current context const handleOpenLinkedDoc = React.useCallback(( docPath: string, @@ -2037,6 +2104,11 @@ const App: React.FC = () => { // "Viewing / Back to …" header is its only way back), and `--markdown` // sessions convert HTML to markdown, so they follow that convention too. const openOptions = intent.rendersHtml ? { revealSidebar: false } : undefined; + // A link to another file of the same review opens it as that bundle file. + if (bundleFiles && annotateBundleIndexOf(bundleFiles, intent.path) >= 0) { + void openBundleFile(intent.path, openOptions); + return; + } // Folder sessions route through the file-browser selection handler so the // active file, the sidebar and the linked doc stay in step. const activeDirState = fileBrowser.dirs.find(d => d.path === fileBrowser.activeDirPath); @@ -2055,6 +2127,8 @@ const App: React.FC = () => { fileBrowser.activeFile, handleFileBrowserSelect, handleOpenLinkedDoc, + bundleFiles, + openBundleFile, ]); // The header Back control for a linked HTML document. It exists because an @@ -2065,10 +2139,13 @@ const App: React.FC = () => { // stack, so back() from any depth lands there. const htmlLinkedDocBackTarget = useMemo(() => { if (!isHtmlSurface || !linkedDocHook.isActive) return null; + // A bundle file is not a detour: the switcher moves between the files, + // and there is no root document to go back to. + if (bundleIndex >= 0) return null; const root = sourceFilePath; if (!root) return 'Back'; return `Back to ${root.split('/').pop() || root}`; - }, [isHtmlSurface, linkedDocHook.isActive, sourceFilePath]); + }, [isHtmlSurface, linkedDocHook.isActive, sourceFilePath, bundleIndex]); // Wrap linked doc back to also clear file browser active file const handleLinkedDocBack = React.useCallback(() => { @@ -2098,12 +2175,13 @@ const App: React.FC = () => { if (allDirPaths.length === 0) return allAnnotationCounts; const counts = new Map(); for (const [fp, count] of allAnnotationCounts) { - if (allDirPaths.some(dir => pathIsInsideDir(fp, dir))) { + // A bundle's files count wherever they live. + if (allDirPaths.some(dir => pathIsInsideDir(fp, dir)) || (bundleFiles && annotateBundleIndexOf(bundleFiles, fp) >= 0)) { counts.set(fp, count); } } return counts; - }, [allAnnotationCounts, fileBrowser.dirs]); + }, [allAnnotationCounts, fileBrowser.dirs, bundleFiles]); const hasFileAnnotations = fileAnnotationCounts.size > 0; @@ -2294,6 +2372,7 @@ const App: React.FC = () => { sourceFilePath, sourceConverted, annotateSource, + bundleOrder: bundlePaths, }), [ linkedDocHook.getFeedbackDocuments, allAnnotations, @@ -2303,6 +2382,7 @@ const App: React.FC = () => { sourceFilePath, sourceConverted, annotateSource, + bundlePaths, ]); const annotationsOutput = useMemo(() => { @@ -2323,7 +2403,7 @@ const App: React.FC = () => { sections.blocks, sections.annotations, sections.globalAttachments, - annotateSource === 'message' ? 'Message Feedback' : annotateSource === 'folder' ? 'Folder Feedback' : annotateSource === 'file' ? 'File Feedback' : 'Plan Feedback', + annotateSource === 'message' ? 'Message Feedback' : bundleFiles ? 'Review Feedback' : annotateSource === 'folder' ? 'Folder Feedback' : annotateSource === 'file' ? 'File Feedback' : 'Plan Feedback', annotateSource ?? 'plan', { sourceConverted: sections.sourceConverted }, ) @@ -2346,7 +2426,7 @@ const App: React.FC = () => { return output.replace(/^\n+/, ''); // skillContentGeneration re-runs this once lazily fetched human-only skill // contents land in the export registry (module state the exporters read). - }, [getFeedbackSections, editorAnnotations, codeAnnotations, annotateSource, skillContentGeneration]); + }, [getFeedbackSections, editorAnnotations, codeAnnotations, annotateSource, bundleFiles, skillContentGeneration]); // Code-file comments are intentionally not serialized into share URLs in v1. // Hide share entry points once they exist so we do not silently drop feedback. @@ -3316,11 +3396,13 @@ const App: React.FC = () => { codeAnnotations: discard ? [] : codeAnnotations, title: annotateSource === 'message' ? 'Message Feedback' - : annotateSource === 'folder' - ? 'Folder Feedback' - : annotateSource === 'file' - ? 'File Feedback' - : 'Plan Feedback', + : bundleFiles + ? 'Review Feedback' + : annotateSource === 'folder' + ? 'Folder Feedback' + : annotateSource === 'file' + ? 'File Feedback' + : 'Plan Feedback', subject: annotateSource ?? 'plan', sourceConverted: sections.sourceConverted, directEditsSection: buildEditsSection(), @@ -3332,6 +3414,7 @@ const App: React.FC = () => { }); }, [ annotateSource, + bundleFiles, buildEditsSection, buildFeedbackMessageEntries, buildSavedChangesSection, @@ -3606,7 +3689,7 @@ const App: React.FC = () => { if (!res.ok) throw new Error('Not in API mode'); return res.json(); }) - .then((data: { plan: string; origin?: Origin; mode?: 'annotate' | 'annotate-last' | 'annotate-folder' | 'annotate-app' | 'archive' | 'goal-setup'; goalSetup?: GoalSetupBundle; filePath?: string; appUrl?: string; targetUrl?: string; liveToken?: string; sourceInfo?: string; sourceConverted?: boolean; sourceSave?: SourceSaveCapability; gate?: boolean; approvalNotesSupported?: boolean; clientLease?: AnnotateClientLeaseConfig; renderAs?: DocumentRenderAs; rawHtml?: string; shareHtml?: string; diffHtml?: string; convertHtml?: boolean; sharingEnabled?: boolean; shareBaseUrl?: string; pasteApiUrl?: string; repoInfo?: { display: string; branch?: string; host?: string }; previousPlan?: string | null; versionInfo?: { version: number; totalVersions: number; project: string }; planRevision?: number; archivePlans?: ArchivedPlan[]; projectRoot?: string; planDir?: string; isWSL?: boolean; markdownExtensions?: string[]; documentDrafts?: boolean; serverConfig?: { displayName?: string; gitUser?: string; autoUpdate?: boolean; autoUpdateEnv?: boolean }; autoUpdateNotice?: unknown; autoUpdateSupported?: boolean; autoUpdateActive?: boolean; recentMessages?: PickerMessage[]; agentTerminal?: AgentTerminalCapability; feedbackTemplates?: AnnotateFeedbackTemplates }) => { + .then((data: { plan: string; origin?: Origin; mode?: 'annotate' | 'annotate-last' | 'annotate-folder' | 'annotate-app' | 'annotate-bundle' | 'archive' | 'goal-setup'; bundle?: unknown; goalSetup?: GoalSetupBundle; filePath?: string; appUrl?: string; targetUrl?: string; liveToken?: string; sourceInfo?: string; sourceConverted?: boolean; sourceSave?: SourceSaveCapability; gate?: boolean; approvalNotesSupported?: boolean; clientLease?: AnnotateClientLeaseConfig; renderAs?: DocumentRenderAs; rawHtml?: string; shareHtml?: string; diffHtml?: string; convertHtml?: boolean; sharingEnabled?: boolean; shareBaseUrl?: string; pasteApiUrl?: string; repoInfo?: { display: string; branch?: string; host?: string }; previousPlan?: string | null; versionInfo?: { version: number; totalVersions: number; project: string }; planRevision?: number; archivePlans?: ArchivedPlan[]; projectRoot?: string; planDir?: string; isWSL?: boolean; markdownExtensions?: string[]; documentDrafts?: boolean; serverConfig?: { displayName?: string; gitUser?: string; autoUpdate?: boolean; autoUpdateEnv?: boolean }; autoUpdateNotice?: unknown; autoUpdateSupported?: boolean; autoUpdateActive?: boolean; recentMessages?: PickerMessage[]; agentTerminal?: AgentTerminalCapability; feedbackTemplates?: AnnotateFeedbackTemplates }) => { // Initialize config store with server-provided values (config file > cookie > default) configStore.init(data.serverConfig); // Extra extensions the user registered as markdown (#1307) — the @@ -3662,8 +3745,9 @@ const App: React.FC = () => { const diagramSource = data.plan.replace(/\r\n?/g, '\n'); setMarkdown(diagramSource); originalMarkdownRef.current = diagramSource; - } else if (data.mode === 'annotate-folder') { - // Folder annotation mode: clear demo content, let user pick a file + } else if (data.mode === 'annotate-folder' || data.mode === 'annotate-bundle') { + // Folder annotation mode: clear demo content, let user pick a file. + // A bundle opens its first file once loaded (see the effect below). setMarkdown(''); } else if (typeof data.plan === 'string') { // CM6 joins lines with \n; CRLF input would make an untouched @@ -3677,17 +3761,21 @@ const App: React.FC = () => { } } setIsApiMode(true); - if (data.mode === 'annotate' || data.mode === 'annotate-last' || data.mode === 'annotate-folder' || data.mode === 'annotate-app') { + // A bundle is a folder session over an explicit, ordered list. + const bundle = data.mode === 'annotate-bundle' ? parseAnnotateBundle(data.bundle) : null; + const folderLike = data.mode === 'annotate-folder' || data.mode === 'annotate-bundle'; + setBundleFiles(bundle); + if (data.mode === 'annotate' || data.mode === 'annotate-last' || folderLike || data.mode === 'annotate-app') { setAnnotateMode(true); setGate(data.gate ?? false); setApprovalNotesSupported(data.approvalNotesSupported ?? false); setClientLease(data.clientLease ?? null); } - if (data.mode === 'annotate-folder') { + if (folderLike) { sidebar.open('files'); } - if (data.mode === 'annotate' || data.mode === 'annotate-last' || data.mode === 'annotate-folder' || data.mode === 'annotate-app') { - setAnnotateSource(data.mode === 'annotate-last' ? 'message' : data.mode === 'annotate-folder' ? 'folder' : 'file'); + if (data.mode === 'annotate' || data.mode === 'annotate-last' || folderLike || data.mode === 'annotate-app') { + setAnnotateSource(data.mode === 'annotate-last' ? 'message' : folderLike ? 'folder' : 'file'); } if (data.mode === 'annotate-last' && data.recentMessages && data.recentMessages.length > 0) { messageStateCacheRef.current = new Map(); @@ -3705,7 +3793,7 @@ const App: React.FC = () => { setFeedbackTemplates(data.feedbackTemplates ?? null); setSourceConverted(!!data.sourceConverted); if (data.filePath) { - setImageBaseDir(data.mode === 'annotate-folder' ? data.filePath : data.filePath.replace(/\/[^/]+$/, '')); + setImageBaseDir(folderLike ? data.filePath : data.filePath.replace(/\/[^/]+$/, '')); if (data.mode === 'annotate') { setSourceFilePath(data.filePath); } @@ -3971,6 +4059,10 @@ const App: React.FC = () => { }, [openAgentTerminal]); const getAnnotateFeedbackTarget = useCallback((): AnnotateFeedbackTarget => { + // A review of several files names every one, whichever is open. + if (bundlePaths) { + return { fileHeader: 'Files', filePath: annotateBundleTargetText(bundlePaths) }; + } if (linkedDocHook.isActive && linkedDocHook.filepath) { return { fileHeader: 'File', filePath: linkedDocHook.filepath }; } @@ -3986,6 +4078,7 @@ const App: React.FC = () => { return { fileHeader: 'File', filePath: 'current file' }; }, [ annotateSource, + bundlePaths, fileBrowser.activeDirPath, fileBrowser.activeFile, linkedDocHook.filepath, @@ -4845,6 +4938,8 @@ const App: React.FC = () => { annotations: allAnnotations, }, roots: annotationDocumentRoots, + // A review of several files lists them in review order. + order: bundlePaths, }); }, [ linkedDocHook.getDocAnnotations, @@ -4852,6 +4947,7 @@ const App: React.FC = () => { currentDocumentGroupKey, currentDocumentGroupLabel, annotationDocumentRoots, + bundlePaths, ]); const otherDocumentAnnotationCount = useMemo( @@ -4906,6 +5002,10 @@ const App: React.FC = () => { // convention, where the sidebar's "Viewing / Back to …" header is the // way out. const openOptions = documentRendersHtml(path, convertHtml) ? { revealSidebar: false } : undefined; + if (bundleFiles && annotateBundleIndexOf(bundleFiles, path) >= 0) { + await openBundleFile(path, openOptions); + return; + } const dir = fileBrowser.dirs.find((d) => !d.isVault && pathIsInsideDir(path, d.path))?.path; if (dir) { await handleFileBrowserSelect(path, dir, openOptions); @@ -4918,7 +5018,7 @@ const App: React.FC = () => { return; } await linkedDocHook.open(path, undefined, undefined, openOptions); - }, [convertHtml, fileBrowser.dirs, handleFileBrowserSelect, handleLinkedDocBack, linkedDocHook, sourceFilePath]); + }, [bundleFiles, convertHtml, fileBrowser.dirs, handleFileBrowserSelect, handleLinkedDocBack, linkedDocHook, openBundleFile, sourceFilePath]); const jumpToAnnotation = useAnnotationJump({ currentPath: currentDocumentPath, @@ -5009,7 +5109,7 @@ const App: React.FC = () => { getDocAnnotations: linkedDocHook.getDocAnnotations, open: (path: string) => linkedDocHook.open(path), }, - fileBrowserDirs: fileBrowser.dirs, + fileBrowserDirs: navigatorFileBrowser.dirs, fileBrowserActiveFile: fileBrowser.activeFile, openFolderFile: handleFileBrowserSelect, viewerRef, @@ -5094,6 +5194,10 @@ const App: React.FC = () => { sourceConverted: aiSourceConverted, renderAs: aiRenderAs, annotations: aiAnnotationsContext, + // "annotating mock.html, file 2 of 3" in a review of several files. + ...(bundleFiles && bundleIndex >= 0 && linkedDocHook.isActive + ? { bundlePosition: { index: bundleIndex + 1, total: bundleFiles.length } } + : {}), }, }; } @@ -5126,6 +5230,9 @@ const App: React.FC = () => { rawHtml, renderAs, versionInfo, + bundleFiles, + bundleIndex, + linkedDocHook.isActive, ]); const aiChat = useAIChat({ @@ -6005,12 +6112,30 @@ const App: React.FC = () => { const compactDocumentTitle = useMemo(() => { const path = linkedDocHook.filepath ?? sourceFilePath ?? fileBrowser.activeFile; + // A review of several files names the open file's place in it. + if (path && bundleFiles && bundleIndex >= 0) { + return `${annotateBundleBaseName(path)} (${bundleIndex + 1} of ${bundleFiles.length})`; + } if (path) return path.replace(/\\/g, '/').split('/').pop() || path; if (archive.currentInfo?.title) return archive.currentInfo.title; if (annotateSource === 'message') return 'Message'; if (annotateSource === 'folder') return 'Choose a file'; return 'Plan'; - }, [annotateSource, archive.currentInfo?.title, fileBrowser.activeFile, linkedDocHook.filepath, sourceFilePath]); + }, [annotateSource, archive.currentInfo?.title, bundleFiles, bundleIndex, fileBrowser.activeFile, linkedDocHook.filepath, sourceFilePath]); + + // The header's file switcher for a review of several files. + const bundleSwitcher = useMemo(() => { + if (!bundleFiles) return undefined; + const open = bundleIndex >= 0 ? bundleFiles[bundleIndex] : undefined; + return { + index: bundleIndex + 1, + total: bundleFiles.length, + name: open ? annotateBundleBaseName(open.path) : undefined, + title: open?.path, + onPrevious: () => openBundleFileAt(Math.max(0, bundleIndex - 1)), + onNext: () => openBundleFileAt(bundleIndex < 0 ? 0 : Math.min(bundleFiles.length - 1, bundleIndex + 1)), + }; + }, [bundleFiles, bundleIndex, openBundleFileAt]); const callbackShareUrlReady = callbackConfig ? Boolean(shareUrl || shortShareUrl || (renderAs === 'html' && (shareHtml || rawHtml))) @@ -6184,6 +6309,24 @@ const App: React.FC = () => { const compactDocumentActions: CompactPlanAction[] = !isCompactTouchLayout ? [] : [ + // The header switcher is desktop-only; a review of several files + // moves between them from here on the compact shell. + ...(bundleSwitcher && bundleSwitcher.index > 1 + ? [{ + id: 'bundle-previous' as const, + label: 'Previous file', + subtitle: bundleFiles?.[bundleSwitcher.index - 2] ? annotateBundleBaseName(bundleFiles[bundleSwitcher.index - 2]!.path) : undefined, + onSelect: bundleSwitcher.onPrevious, + }] + : []), + ...(bundleSwitcher && bundleSwitcher.index < bundleSwitcher.total + ? [{ + id: 'bundle-next' as const, + label: 'Next file', + subtitle: bundleFiles?.[bundleSwitcher.index] ? annotateBundleBaseName(bundleFiles[bundleSwitcher.index]!.path) : undefined, + onSelect: bundleSwitcher.onNext, + }] + : []), ...(canEditMarkdown && !isEditingMarkdown && !isPlanDiffActive && !archive.archiveMode && !isHtmlSurface ? [{ id: 'edit' as const, @@ -6438,7 +6581,7 @@ const App: React.FC = () => { fileAnnotationCounts={fileAnnotationCounts} highlightedFiles={highlightedFiles} fileEditStatuses={editableDocuments.fileEditStatuses} - fileBrowser={fileBrowser} + fileBrowser={navigatorFileBrowser} onFilesSelectFile={handleNavigatorFileSelect} onFilesFetchAll={() => fileBrowser.fetchAll(fileBrowserDirs)} onFilesRetryVaultDir={(vaultPath) => fileBrowser.addVaultDir(vaultPath)} @@ -6590,6 +6733,7 @@ const App: React.FC = () => { compactDocumentTitle={compactDocumentTitle} compactSessionActions={compactSessionActions} compactDocumentActions={compactDocumentActions} + bundleSwitcher={bundleSwitcher} isApiMode={isApiMode} annotateMode={annotateMode} archiveMode={archive.archiveMode} diff --git a/packages/editor/agentTerminalIntegration.ts b/packages/editor/agentTerminalIntegration.ts index 8bf275ae37..d160da8327 100644 --- a/packages/editor/agentTerminalIntegration.ts +++ b/packages/editor/agentTerminalIntegration.ts @@ -1,5 +1,6 @@ export type AnnotateFeedbackTarget = { - fileHeader: "File" | "Folder"; + /** "Files" names every file of a review of several files. */ + fileHeader: "File" | "Folder" | "Files"; filePath: string; }; diff --git a/packages/editor/components/AppHeader.tsx b/packages/editor/components/AppHeader.tsx index 20d49ec55f..9d4f136c64 100644 --- a/packages/editor/components/AppHeader.tsx +++ b/packages/editor/components/AppHeader.tsx @@ -14,6 +14,7 @@ import type { UIPreferences } from '@plannotator/ui/utils/uiPreferences'; import { SparklesIcon } from '@plannotator/ui/components/SparklesIcon'; import type { CompactPlanAction } from '@plannotator/ui/components/PlanHeaderMenu'; import { HtmlSurfaceControls } from '@plannotator/ui/components/HtmlSurfaceControls'; +import { BundleSwitcher, type BundleSwitcherProps } from './BundleSwitcher'; /** Plannotator's refresh strings for the published control: the document * is a file on disk, so the refresh says so. */ @@ -54,6 +55,10 @@ interface AppHeaderProps { compactDocumentTitle?: string; compactSessionActions?: CompactPlanAction[]; compactDocumentActions?: CompactPlanAction[]; + /** A review of several files: the "2 of 3 · mock.html ‹ ›" switcher beside + * the logo. Desktop only; the compact shell names the position in its + * title and offers previous/next in its Options menu. */ + bundleSwitcher?: BundleSwitcherProps; // Mode flags (stable after mount) isApiMode: boolean; annotateMode: boolean; @@ -169,6 +174,7 @@ export const AppHeader = React.memo(({ compactDocumentTitle, compactSessionActions, compactDocumentActions, + bundleSwitcher, isApiMode, annotateMode, archiveMode, @@ -250,7 +256,10 @@ export const AppHeader = React.memo(({