Skip to content

vscode: add review comments from the markdown preview pane (hover-+ per block, no editor mode-switch) #859

Closed

Description

@amrmelsayed

Problem

Today the only way to add a review comment to a spec/plan is via the Comments API gutter + in the text editor (packages/vscode/src/comments/plan-review.ts). For long spec/plan documents — which is the typical case, not the exception — raw markdown is significantly harder to read than the rendered preview. The architect's review loop forces a mode-switch every time:

  1. Read in preview (Cmd+K V) — easy
  2. Find the paragraph to comment on
  3. Switch to source editor — context-switch
  4. Find the same paragraph in raw .md — re-find
  5. Click gutter +, type comment, submit
  6. Switch back to preview to continue reading

For a spec with 5+ review comments, that's 10+ context switches. The preview is the natural reading surface for prose-heavy artifacts; the editor is the natural authoring surface. Comments cross the boundary.

Proposal

Add the add-comment affordance directly to the markdown preview pane. v1 scope is authoring only — no thread rendering in the preview. The architect reads in the preview, hovers a paragraph or heading, clicks +, types in an input box, submits. Existing comments still surface in the source editor (architect switches to editor only when they want to see/reply/delete existing threads — uncommon during a first-pass read).

This is deliberately scoped narrow: we add one feature (add) to the preview, leave the other three (read existing threads, reply, delete) where they already live.

Why this works (and the one real limitation)

VS Code's built-in markdown preview is a webview. Extensions can extend it via three contribution points:

Contribution point What it enables
contributes.markdown.previewScripts Inject JavaScript that runs inside the preview webview
contributes.markdown.previewStyles Inject custom CSS into the preview
contributes.markdown.markdownItPlugins Register a markdown-it plugin during AST → HTML rendering

One real limitation: vscode.comments.createCommentController itself doesn't attach to the preview — the Comments API only works on TextEditor surfaces. So we can't reuse the Comments API thread UI in the preview. For authoring only, this is fine — we use a simple vscode.window.showInputBox for the comment text and call into the existing file-write path.

Implementation sketch

1. Preview-side script (new file)

packages/vscode/src/markdown-preview/add-comment.js (loaded via previewScripts):

// On hover over any block element with data-source-line, show a "+" affordance.
// On click, postMessage back to the extension host with the source line.
document.addEventListener('mouseover', (e) => {
  const block = e.target.closest('[data-line]');
  if (!block) return;
  showAddCommentButton(block);
});

function onAddCommentClick(sourceLine) {
  acquireVsCodeApi().postMessage({
    type: 'codev:addComment',
    sourceLine,
  });
}

Markdown-it already emits data-line source-line attributes on block elements when the preview is built (VS Code's own preview uses these for "sync editor to preview" / "sync preview to editor"). We piggyback on the same attribution — no need to add our own.

2. Preview-side styles

packages/vscode/src/markdown-preview/add-comment.css (loaded via previewStyles):

  • Hide the + until hover
  • Position in the gutter or top-right of each block element
  • Use VS Code theme variables (--vscode-textLink-foreground, etc.) for color consistency

3. Extension-host listener

Listen for the postMessage via the markdown preview message-receiver API (vscode.workspace.onDidReceiveMessage is not a thing — actual API path is through markdown.api.v1 if available, or by attaching to the active preview webview's onDidReceiveMessage; verify at implementation time which entry point is current).

On receipt:

const text = await vscode.window.showInputBox({
  prompt: 'Add review comment',
  placeHolder: 'Type your review comment, then Enter to submit',
});
if (!text) return;
await writeReviewMarkerAt(document.uri, sourceLine, text);

writeReviewMarkerAt is a refactor of the existing submitReviewComment in plan-review.ts — extract the file-mutation part so both the editor-side Comments API path and the preview-side path can call it.

4. package.json contribution

"contributes": {
  "markdown.previewScripts": ["./out/markdown-preview/add-comment.js"],
  "markdown.previewStyles": ["./out/markdown-preview/add-comment.css"]
}

These run only for markdown previews, period. No flag, no toggle — purely additive UI affordance gated by hover.

5. Path gating

Limit the + affordance to files matching the same ELIGIBLE_PATH_REGEX from plan-review.ts (/\/codev\/(plans|specs|reviews)\// after #857's regex extension). Other markdown files get the standard preview with no +. Path comes through to the preview script via the existing markdown preview message protocol (the preview already knows the source document URI).

Acceptance criteria

  • Hovering any block element (paragraph, heading, list item, code block) in the markdown preview for a codev/(plans|specs|reviews)/*.md file shows a + affordance
  • Clicking the + opens an InputBox for the comment text
  • Submitting the input writes <!-- REVIEW(@<author>): <text> --> to the source file on the line after the block element clicked (matching the existing editor-side semantics)
  • Author identity matches whatever convention vscode: spec/plan review comments — polish pass (placeholders, reviews/ coverage, author identity, panel discoverability) #857 lands (git config user.name, falling back to architect)
  • No + appears on .md files outside the eligible-path set
  • No regression to the editor-side Comments API path
  • Source-line attribution uses markdown-it's existing data-line attributes — no fork or custom plugin needed for this part
  • writeReviewMarkerAt shared between the editor-side and preview-side submit paths (one mutation function, two entry points)

Out of scope (v1)

  • Rendering existing REVIEW threads inside the preview. Architect switches to the source editor to read/reply/delete existing threads. If this turns out to feel like the bigger friction, that's a Phase 2 (a markdown-it plugin can transform existing REVIEW markers into styled inline call-out HTML).
  • Reply / thread support. Replies are a separate design call (storage format; canReply flag) — handled in the broader Comments-API-side work, not here.
  • Resolve state. Same — separate design call, applies to both editor- and preview-side authoring.
  • Inline diff view of edits to a comment. Not relevant for v1.
  • Touch / mobile support. Hover-triggered affordance assumes a pointing device.

Why this is high leverage

For long documents — which is the typical case for codev specs/plans — the rendered preview is genuinely the right reading surface. Bringing the add-comment action to where the architect is already looking removes 50% of the friction in a review pass. The implementation is well-scoped (three contribution points, one shared mutation function, no Comments API rework) and v1 is intentionally minimal: add-only, no thread rendering. That keeps the PR small and the design decisions deferred (replies, resolve, threading) until the simpler primitive is in users' hands.

Related

Source-line attribution detail (for the implementer)

VS Code's built-in markdown preview uses markdown-it with the linkify, breaks, and source-map options. Block-level tokens carry a map: [startLine, endLine] that gets emitted to HTML as data-line="<startLine>" on the corresponding element. This is how the built-in "sync editor with preview" and "sync preview with editor" features work. We reuse the same attribute — no need to write a custom markdown-it plugin for source-line attribution.

If a future version of VS Code changes this attribute name or removes it, the fallback is to write our own markdown-it plugin that emits a custom data-codev-line attribute. Cheap to add later if needed; not needed for v1.

Activity

  1. self-assigned this
    on May 26, 2026
  2. added
    area/vscode
    on May 26, 2026
  3. amrmelsayed commented on May 30, 2026

    @amrmelsayed
    CollaboratorAuthor

    On it! Working on this with the PIR protocol (plan + dev-approval gates before PR).

  4. added a commit that references this issue on May 30, 2026
  5. amrmelsayed commented on May 31, 2026

    @amrmelsayed
    CollaboratorAuthor

    Investigation snapshot (pir-859 builder, before re-spawn against the cross-surface package)

    This issue is paused at plan-approval. The Codev rendered-preview surface is being extracted as a reusable cross-surface package (vscode + dashboard + future mobile); #859 will be re-planned against that foundation once it lands. Capturing the investigation here so the re-spawn starts from verified ground rather than re-deriving it.

    TL;DR: the issue's stated mechanism (inject a previewScripts script into VS Code's built-in markdown preview and postMessage the clicked line to the extension host) is not achievable — the built-in preview exposes no host-bound message channel to contributed scripts. The goal (comment from a rendered surface, no raw-.md mode-switch) is achievable, but only by rendering the markdown in a surface-owned webview. That is exactly why the package extraction makes sense: the render + affordance + messaging core is built once and consumed everywhere.


    1. Infeasibility of the built-in markdown preview (four primary-source checks)

    The built-in preview is render-only for contributed code. Verified against the platform's own issue tracker and source — four independent checks, all pointing the same way:

    1. acquireVsCodeApi() is single-call-per-webview. The built-in preview's own bootstrap script already calls it once and keeps the handle module-private. A contributed script calling it again throws "An instance of the VS Code API has already been acquired." So a contributed script has no webview-API handle to post with. — Extending markdown preview disallows using acquireVsCodeApi in embedded previewScripts microsoft/vscode#122961, closed as-designed.

    2. The host-side message handler is a closed allowlist. The preview's extension-host onDidReceiveMessage switches over a fixed set only — cacheImageSizes, revealLine, didClick, openLink, showPreviewSecuritySelector, previewStyleLoadError — with no default/passthrough case, and it validates e.source against the previewed resource URI. Even if a custom message reached it, an unrecognized type is silently dropped. — verified in the platform's markdown-language-features preview host module.

    3. command: URIs are blocked in the built-in preview. The preview webview is not created with enableCommandUris, and there is no API to alter the preview webview's security policy — so an <a href="command:…"> affordance injected at render time cannot invoke an extension command. — Use markdown preview like regular webview for extensions microsoft/vscode#84886 (request to relax the preview's security policy), closed out-of-scope.

    4. The exact first-class API this feature needs was proposed and rejected. A proposal for onMarkdownPreview + postMessage/onDidReceiveMessage (i.e. real preview↔host messaging for contributed scripts) was filed and closed out-of-scope. — Communication between an extension and markdown preview script microsoft/vscode#174080. Corroborating signal: the platform's own published extension samples demonstrate only render-time hooks (markdown-it extension), never preview→host messaging — the capability simply isn't there to sample.

    Conclusion: the three contribution points the issue leans on (markdown.previewScripts, markdown.previewStyles, markdown.markdownItPlugins) are all render-only. None carries a channel back to the host. The original acceptance criterion — "click + in the preview → InputBox opens" — cannot be met on the built-in preview. This is a load-bearing premise, not an implementation detail to verify later.


    2. The only workable path: a surface-owned webview (in VS Code: CustomTextEditor)

    The supported way to get hover-+ → host → InputBox is to render the markdown ourselves in a webview we own, so we make the single acquireVsCodeApi() call and get a real bidirectional message channel. In VS Code the cleanest binding is a read-only CustomTextEditorProvider (not a free-floating WebviewPanel): it's tied to the document lifecycle, receives the document URI for free, and surfaces in "Reopen Editor With… → Codev Review Preview" without hijacking the default .md editor or the built-in Cmd+K V preview.

    Provider file-shape (verified pattern):

    class ReviewPreviewProvider implements vscode.CustomTextEditorProvider {
      static readonly viewType = 'codev.reviewPreview';
    
      resolveCustomTextEditor(
        document: vscode.TextDocument,
        panel: vscode.WebviewPanel,
        _token: vscode.CancellationToken,
      ): void {
        panel.webview.options = { enableScripts: true, localResourceRoots: [/* media/ */] };
        panel.webview.html = this.renderHtml(document, panel.webview); // markdown-it → HTML + data-line + CSP/nonce + asWebviewUri
    
        // re-render on edits (new marker, or editor-side changes)
        const sub = vscode.workspace.onDidChangeTextDocument(e => {
          if (e.document.uri.toString() === document.uri.toString()) {
            panel.webview.html = this.renderHtml(document, panel.webview);
          }
        });
        panel.onDidDispose(() => sub.dispose());
    
        // the real channel the built-in preview denies us:
        panel.webview.onDidReceiveMessage(async (msg) => {
          if (msg.type === 'codev:addComment') {
            const text = await vscode.window.showInputBox({ prompt: 'Add review comment' });
            if (text) { await writeReviewMarkerAt(document.uri, msg.endLine, text, author); }
          }
        });
      }
    }

    Registration wiring:

    context.subscriptions.push(
      vscode.window.registerCustomEditorProvider(
        ReviewPreviewProvider.viewType,
        new ReviewPreviewProvider(/* deps */),
        { webviewOptions: { retainContextWhenHidden: true }, supportsMultipleEditorsPerDocument: false },
      ),
    );

    package.json contribution (priority: "option" so it never replaces the default editor):

    "customEditors": [{
      "viewType": "codev.reviewPreview",
      "displayName": "Codev Review Preview",
      "selector": [{ "filenamePattern": "**/*.md" }],
      "priority": "option"
    }]

    Webview side (bundled asset, owns the only acquireVsCodeApi()): on block hover show +; on click acquireVsCodeApi().postMessage({ type: 'codev:addComment', startLine, endLine }).

    Source-line attribution: markdown-it block tokens carry token.map = [startLine, endLineExclusive]. A ~10-line custom rule stamps data-line/data-end-line onto block elements (this is the issue's "fallback: write our own plugin" — it is in fact the required path here, and it's cheap). Positioning nuance worth carrying forward: the marker must be written at the block's end line (token.map[1]), not startLine + 1 — for a multi-line paragraph, start + 1 lands inside the block. The editor-side path writes at clicked-line + 1, which is fine for a single gutter click but does not generalize to block-granular targeting.

    Honest scope note for the re-plan: as a vscode-only build this is the first webview in packages/vscode (no existing createWebviewPanel/registerCustomEditorProvider anywhere in src/), plus a new markdown-it dependency and webview asset plumbing — materially larger than the issue's "three contribution points, no rework" framing. That gap is the whole reason for the package reframe: do the render/affordance/messaging core once in the package; let vscode (and later dashboard/mobile) supply only the thin host bindings.


    3. Adapter contract sketches for the package

    These are forward-looking shapes (the package didn't exist during this investigation) drawn from what is surface-specific vs. portable. The portable core is: markdown-it instance + data-line rule, the hover-+ webview script/css, and the { type, startLine, endLine } message protocol. Everything host-specific factors into adapters:

    // Reading content + observing changes + persisting edits.
    interface FileAdapter {
      read(): Promise<string>;
      onDidChange(cb: () => void): Disposable;            // vscode: onDidChangeTextDocument; dashboard: SSE; mobile: remote sub
      applyInsert(line: number, text: string): Promise<void>;   // vscode: WorkspaceEdit + save; dashboard/mobile: write endpoint
    }
    
    // Owns the ON-DISK serialization so the core stays serialization-agnostic.
    interface MarkerAdapter {
      serialize(author: string, text: string): string;   // → '<!-- REVIEW(@author): text -->'
      parse(content: string): Array<{ line: number; author: string; text: string }>;
      // positional convention: the marker's file position IS its line association (see §4)
    }
    
    // Supplies theme tokens. vscode webviews get --vscode-* for free; other surfaces inject their own palette.
    interface ThemeAdapter {
      cssVariables(): Record<string, string>;             // e.g. { '--accent': 'var(--vscode-textLink-foreground)' }
    }
    
    // Who authored the comment.
    interface AuthorAdapter {
      currentAuthor(): string;                            // vscode: overviewCache.currentUser ?? 'architect'; dashboard: session user
    }

    The core orchestrates: FileAdapter.read() → render (core) → webview posts { startLine, endLine } → core asks host for input text → MarkerAdapter.serialize(AuthorAdapter.currentAuthor(), text) → FileAdapter.applyInsert(endLine, …). The transport for "ask host for input text" is the host's own message handler (vscode: webview.onDidReceiveMessage → showInputBox; dashboard: component callback → modal).


    4. Marker-format correction (important for the package's MarkerAdapter)

    The on-disk format from the editor-side Comments API path (packages/vscode/src/comments/plan-review.ts) is positional:

    <!-- REVIEW(@<author>): <text> -->
    

    Verified specifics:

    • Pattern: /<!--\s*REVIEW\s*\(@([^)]+)\)\s*:\s*([\s\S]*?)\s*-->/g — captures author + body.
    • No line=N attribute. The marker carries no line metadata. Its position in the file (it's inserted on the line after the targeted content, Position(line + 1, 0)) is the entire line association.
    • Body is whitespace-normalized to a single line; leading indent of the anchor line is preserved.
    • Eligibility: /\/codev\/(plans|specs|reviews)\//.

    Implication for the package: the marker format is plain positional HTML-comment serialization with no structured line field — so the MarkerAdapter must own the on-disk format, and the rendering/affordance core stays serialization-agnostic (it deals in { line, author, text }, never in the comment syntax). If the package ever needs to render existing threads inline (a deliberate v1 non-goal here), MarkerAdapter.parse() is the seam — the core asks for markers by line, the adapter decides how they're stored.


    Carry-forward checklist for the re-plan

    • Built-in preview is render-only — no host-bound channel for contributed scripts (4 checks above)
    • Surface-owned webview (CustomTextEditor in vscode) is the only viable path; provider shape + wiring above
    • markdown-it + a data-line/data-end-line source-map rule; write markers at block end line, not start+1
    • Shared writeReviewMarkerAt(uri, line, text, author) refactor out of plan-review.ts — still valid, surface-agnostic
    • Marker format is positional <!-- REVIEW(@author): text -->, no line=N; MarkerAdapter owns it
    • Re-plan against the package once it lands: core in the package, vscode supplies FileAdapter/AuthorAdapter/ThemeAdapter bindings only
  6. added 10 commits that reference this issue on Jun 13, 2026
  7. 4 remaining items

  8. added 12 commits that reference this issue on Jun 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area/vscode

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions