Skip to content

feat: overhaul document viewer page (smart summary, badges, flattened evidence, flowing source text) - #492

Merged
BigSimmo merged 2 commits into
mainfrom
claude/document-page-redesign-7dd487
Jul 11, 2026
Merged

feat: overhaul document viewer page (smart summary, badges, flattened evidence, flowing source text)#492
BigSimmo merged 2 commits into
mainfrom
claude/document-page-redesign-7dd487

Conversation

@BigSimmo

Copy link
Copy Markdown
Owner

Summary

UX/UI overhaul of /documents/[id] driven by direct user feedback on the live page:

  • Smart summary (new src/lib/document-summary-formatting.ts) — the stored document_summaries.summary renders through a display-time formatter that strips glued PDF-header boilerplate ("OFFICIAL … Reference #: … Scope Site Disciplines …"), deduplicates passages repeated 2–3×, converts inline numbered headings ("1. Introduction", "2.7. Dosage") into real sections with bullet items, and repairs mid-word truncated tails. Applies to all ~2,000 already-indexed documents with no re-indexing. Boilerplate stripping carries the same clinical-signal keep-bias as the sanitizer's H2 rules (threshold-bearing/action sentences are never dropped; strip reverts if it would consume everything).
  • Summary badge system (new src/lib/document-summary-badges.ts) — safety-relevant labels (Risk / Medication / Clinical action) plus phrases detected in the summary text render as a tone-ordered BadgeCluster (danger reserved for contraindications; S8 → warning + lock, per the badge governance guide). New flags registered in SEMANTIC_FLAG_CATALOGUE so /reference/colour-coding stays complete. DocumentTagCloud chip colours now derive from the same canonical tone map (visual-only change on its 4 other call sites).
  • Pinned source evidence flattened — single quiet panel: accent left borders, ring, glow, and the solid header bar removed; excerpts flow as sentences via flowIndexedText.
  • Indexed source text reads as a documentparseIndexedSourceText merges soft-wrap continuation blocks (no more sentences split across cards), recognises multi-level numbered headings, and the renderer is flowing typography (real lists / plain paragraphs) instead of per-line bordered cards.
  • Meta-only "Document details" card removed — extraction warnings surface as a warning InlineNotice at the sidebar top (clinical safety: never hidden); extraction quality / index version / indexed date demoted to a collapsed "Indexing details" disclosure at the sidebar bottom; tables/diagrams count folded into that section's description.
  • Overview hero fix — it previously showed the raw stored summary, leaking the same header boilerplate on live documents; it now uses the formatter's lead sentences.
  • Demo fixtures now include labels/summary/indexHealth (shaped like the live API response) so the whole page is previewable in demo mode, with a deliberately messy lithium summary that exercises the formatter end-to-end.

All load-bearing selectors/strings asserted by existing Playwright specs are preserved (pinned-source-evidence, highlighted-source-passage, "Highlighted source passage", toggle-full-passage, #source-summary exactly once, mobile ordering, composer hide-on-scroll).

Verification

  • npm run verify:cheap — components run individually: check:runtime, check:github-actions, sitemap:check, lint, typecheck all pass; full vitest passes with --fileParallelism=false (parallel run hit 15s-timeout flakes from concurrent local sessions saturating the machine; same suites pass untouched on main)
  • npm run verify:ui — 123 passed / 2 failed in 15.2m; both failures are off-page cold-compile timeouts (answer quick links, services mode toggle) and pass on immediate warm re-run. All 7 document-viewer specs green, including a new spec covering the summary card badges, boilerplate absence, and the collapsed indexing-details disclosure
  • npm run verify:release — not run (no release claim)
  • npm run format:check — all changed files clean (pre-existing CLAUDE.md CRLF artifact unrelated)
  • npm run eval:retrieval:quality — n/a: no retrieval, ranking, selection, chunking, or scoring behavior changed (display-time rendering only)
  • npm run eval:rag — n/a: answer generation and post-processing untouched
  • npm run check:production-readiness — run; fails only on missing live secrets in this demo-mode worktree (NEXT_PUBLIC_SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY / OPENAI_API_KEY absent by design), which the repo docs classify as expected in demo mode
  • npm run check:deployment-readiness — n/a: no deployment behavior changed

Visual QA: Playwright screenshots at 375 / 768 / 1440 in light and dark; zero horizontal overflow at every width.

Clinical Governance Preflight

  • Source-backed claims still require linked source verification before clinical use (verbatim-quote path untouched; formatter is display-only)
  • No patient-identifiable document workflow was introduced or expanded without explicit governance approval
  • Supabase target remains Clinical KB Database (sjrfecxgysukkwxsowpy) — no env/config changes
  • Service-role keys and private document access remain server-only
  • Demo/synthetic content remains clearly separated from real clinical sources (new fixtures live behind the existing fail-closed assertDemoDataAllowed demo gate)
  • Source metadata, review status, and outdated/unknown-source behavior remain conservative — extraction warnings promoted to an always-visible notice; boilerplate stripping never drops threshold/action sentences
  • Deployment classification/TGA SaMD impact was checked when clinical decision-support behavior changed — no decision-support behavior changed (rendering/formatting only)

Notes

  • The tag-chip recolour intentionally unifies badge colours on 4 other surfaces (document search results, master search header, admin) with the canonical semantic-tone system — approved app-wide by the owner.
  • Coordination: another local session has uncommitted WIP touching overlapping DocumentViewer.tsx regions (branch claude/document-viewer-redesign-55b68b); reconcile before merging both.

🤖 Generated with Claude Code

… evidence, flowing source text)

- Add display-time smart summary formatter (document-summary-formatting.ts):
  strips glued PDF-header boilerplate, dedupes repeated passages, sections
  inline numbered headings, repairs mid-word truncated tails. Works on all
  stored summaries without re-indexing.
- Add summary badge system (document-summary-badges.ts): safety-relevant
  labels + detected phrases render as tone-ordered ClinicalBadge cluster;
  new flags registered in the colour-coding catalogue; DocumentTagCloud
  colours unified with the canonical semantic-tone system app-wide.
- Flatten pinned source evidence card: single quiet panel, no accent left
  borders/ring/solid header bar; excerpts flow via flowIndexedText.
- Fix indexed source text: merge soft-wrap continuation blocks, recognise
  multi-level numbered headings, render as flowing typography instead of
  per-line bordered cards.
- Remove meta-only Document details card: warnings become an InlineNotice
  at the sidebar top, index metadata demoted to a collapsed "Indexing
  details" disclosure, tables/diagrams count folded into that section.
- Route the Overview hero through the formatter (was leaking boilerplate).
- Extend demo data with labels/summary/indexHealth so the page is fully
  previewable in demo mode; add vitest suites for formatter + badges and a
  ui-smoke spec for the redesigned sidebar.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@supabase

supabase Bot commented Jul 11, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project sjrfecxgysukkwxsowpy because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@BigSimmo, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 12 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5be0eeff-0388-478d-bb2d-83770496dac4

📥 Commits

Reviewing files that changed from the base of the PR and between a17bc92 and 74f7a69.

📒 Files selected for processing (3)
  • src/components/DocumentViewer.tsx
  • src/lib/source-text-sanitizer.ts
  • tests/ui-smoke.spec.ts
📝 Walkthrough

Walkthrough

The document viewer now formats stored clinical summaries, derives semantic badges from labels and summary text, reflows indexed excerpts, exposes enriched demo metadata, and presents warnings and indexing details in updated viewer sections.

Changes

Document viewer enrichment

Layer / File(s) Summary
Summary formatting and cleanup
src/lib/document-summary-formatting.ts, src/lib/source-text-sanitizer.ts, tests/document-summary-formatting.test.ts
Stored summaries are cleaned, deduplicated, sectioned, and checked for boilerplate and truncated content.
Indexed excerpt reflow
src/lib/indexed-source-formatting.ts, tests/indexed-source-formatting.test.ts
Multi-level headings, continuation blocks, list blocks, and soft-wrapped excerpts receive updated parsing and formatting behavior.
Semantic summary badges
src/lib/document-summary-badges.ts, src/lib/semantic-flags.ts, src/components/DocumentTagCloud.tsx, tests/document-summary-badges.test.ts
Safety-relevant labels and summary phrases become prioritized badges using shared semantic tones.
Demo payload enrichment
src/lib/demo-data.ts, tests/demo-data.test.ts
Demo payloads include document labels, stored summaries, and synthesized index-health metadata.
Viewer presentation
src/components/DocumentViewer.tsx, tests/ui-smoke.spec.ts
The viewer renders formatted summaries, badges, tags, extraction warnings, indexing details, and reflowed source excerpts with updated layouts.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant DemoPayload
  participant DocumentViewer
  participant SummaryFormatter
  participant BadgeBuilder
  DemoPayload->>DocumentViewer: labels, summary, indexHealth
  DocumentViewer->>SummaryFormatter: stored summary text
  SummaryFormatter-->>DocumentViewer: formatted sections
  DocumentViewer->>BadgeBuilder: labels and summary text
  BadgeBuilder-->>DocumentViewer: semantic badges
  DocumentViewer-->>DocumentViewer: render viewer sections
Loading

Caution

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

  • Ignore

❌ Failed checks (1 error)

Check name Status Explanation Resolution
Verification Claims ❌ Error The PR description includes vague verification claims like “successful cheap checks” and “UI verification” without always giving an exact command/result. Rewrite each verification claim as Ran <command>: passed/failed (or Not run: reason), and avoid generic statements like “checks passed” in summaries/notes.
✅ Passed checks (10 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main UI overhaul and the key viewer improvements included in the change.
Description check ✅ Passed The description follows the required template and includes summary, verification, clinical governance, and notes with concrete details.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Generated And Sensitive Files ✅ Passed PR only touches source/test TS files and synthetic demo fixtures; no secrets, .env files, private keys, caches, build outputs, or other sensitive artifacts were committed.
Risky Git Or Deployment Actions ✅ Passed Changed files are component/lib/test code only, and targeted searches found no new force-push, reset --hard, destructive clean, branch-deletion, or unsafe deploy guidance.
Supabase Project And Schema Safety ✅ Passed Diff vs main only changes UI/demo-data/test TS files; no Supabase project refs, .sql/migration/policy files, or RLS/schema changes appear.
Runtime And Package Manager Integrity ✅ Passed No package-manager/runtime changes found; repo still pins npm@11.17.0, Node 24.x/npm 11.x, engine-strict=true, and the preinstall gate enforces both.
Api Route Failure Handling ✅ Passed No API/server/RAG/provider files changed; the only helper touched returns null for missing demo docs and the rest are client-side formatting/demo-only.
✨ Finishing Touches
🧪 Generate unit tests (beta)

❌ Error creating Unit Test PR.

  • Create PR with unit tests
  • Commit unit tests in branch claude/document-page-redesign-7dd487
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch claude/document-page-redesign-7dd487

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a17bc92059

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/document-summary-formatting.ts
Comment thread src/lib/document-summary-badges.ts
coderabbitai[bot]
coderabbitai Bot previously requested changes Jul 11, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/lib/document-summary-badges.ts`:
- Line 59: Update the contraindication rule in the badge matching configuration
to ignore occurrences negated by phrases such as “not contraindicated” and “no
contraindications.” Make the matching logic inspect the surrounding occurrence
or sentence before assigning the danger badge, and add regression coverage for
both negated forms while preserving matches for actual contraindications.

In `@src/lib/indexed-source-formatting.ts`:
- Around line 193-203: Update flowIndexedText to normalize CRLF sequences
atomically before converting standalone carriage returns, ensuring each Windows
line ending becomes a single newline. Preserve the existing whitespace cleanup
and flow heuristic for the resulting normalized text.
- Around line 16-19: Update the heading detection logic in the visible predicate
to exclude decimal measurement/value lines such as “12.5 mg” and “2.5 mmol/L”
while continuing to recognize valid multi-level and top-level numbered headings.
Add a regression test covering these dose examples and preserving expected
heading matches.
🪄 Autofix (Beta)

❌ Autofix failed (check again to retry)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8f38f074-a244-411b-8283-0394f0b954a1

📥 Commits

Reviewing files that changed from the base of the PR and between 70ec640 and a17bc92.

📒 Files selected for processing (13)
  • src/components/DocumentTagCloud.tsx
  • src/components/DocumentViewer.tsx
  • src/lib/demo-data.ts
  • src/lib/document-summary-badges.ts
  • src/lib/document-summary-formatting.ts
  • src/lib/indexed-source-formatting.ts
  • src/lib/semantic-flags.ts
  • src/lib/source-text-sanitizer.ts
  • tests/demo-data.test.ts
  • tests/document-summary-badges.test.ts
  • tests/document-summary-formatting.test.ts
  • tests/indexed-source-formatting.test.ts
  • tests/ui-smoke.spec.ts

Comment thread src/lib/document-summary-badges.ts
Comment thread src/lib/indexed-source-formatting.ts
Comment thread src/lib/indexed-source-formatting.ts
@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

Cannot run autofix: This PR has merge conflicts.

Please resolve the conflicts with the base branch and try again.

Alternatively, use @coderabbitai resolve merge conflict to automatically resolve the conflicts.

@BigSimmo

Copy link
Copy Markdown
Owner Author

@codex fix all issues blocking merge including comments

…esign

Reconcile two redesigns of /documents/[id]. #489 restructured layout
(document-first hero, sticky evidence rail, section anchors); this branch
adds the content-quality fixes (#492): smart summary formatter, badge
system, flattened pinned evidence, flowing indexed source text, and removal
of the meta "Document details" card.

Conflict resolution in DocumentViewer.tsx:
- Keep #489's sticky-rail <aside> (grid + lg:sticky); nest my extraction-
  warnings InlineNotice inside it (md:col-span-2 lg:col-span-1).
- Drop #489's trimmed "Document details" counts card (user feedback: meta
  content); my high-yield summary section already owns id="source-summary".
- Re-add the indexHealth state + fetch wiring #489 removed, so extraction
  warnings stay visible and the demoted "Indexing details" disclosure works.
- Span the high-yield summary and indexing-details full width on md now that
  their grid pair (the details card) is gone.

Verified: tsc, eslint, prettier, 108 unit tests, no duplicate ids, zero
horizontal overflow at 768/1440 light+dark.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 74f7a691ec

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/indexed-source-formatting.ts
Comment thread src/lib/document-summary-formatting.ts
@chatgpt-codex-connector

Copy link
Copy Markdown

Summary

Testing

  • PATH="$HOME/.nvm/versions/node/v24.15.0/bin:$PATH" npm ci
  • PATH="$HOME/.nvm/versions/node/v24.15.0/bin:$PATH" npm test -- tests/document-summary-badges.test.ts tests/indexed-source-formatting.test.ts tests/document-summary-formatting.test.ts
  • PATH="$HOME/.nvm/versions/node/v24.15.0/bin:$PATH" npm run lint
  • PATH="$HOME/.nvm/versions/node/v24.15.0/bin:$PATH" npm run typecheck
  • PATH="$HOME/.nvm/versions/node/v24.15.0/bin:$PATH" npx prettier --check src/lib/document-summary-badges.ts src/lib/document-summary-formatting.ts src/lib/indexed-source-formatting.ts tests/document-summary-badges.test.ts tests/document-summary-formatting.test.ts tests/indexed-source-formatting.test.ts
  • git diff --check

View task →

@BigSimmo
BigSimmo enabled auto-merge (squash) July 11, 2026 14:37
@BigSimmo
BigSimmo merged commit d8f65eb into main Jul 11, 2026
15 of 17 checks passed
@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Note

Unit test generation is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.


Generating unit tests... This may take up to 20 minutes.

BigSimmo added a commit that referenced this pull request Jul 11, 2026
- badges: contraindication danger badge is now negation-aware — "no
  contraindications" / "not contraindicated" no longer emit a false red
  clinical stop signal (hasPositiveContraindication guard).
- indexed-source: isNumberedHeading no longer classifies decimal dose/value
  lines ("12.5 mg", "2.5 mmol/L") as section headings (require a non-lowercase
  token after the numeric prefix).
- indexed-source: flowIndexedText + parseIndexedSourceText normalize CRLF/CR
  atomically (\r\n? -> \n) so Windows line endings don't become blank lines.
- summary formatter: only repair/flag a truncated tail when the RAW stored
  summary actually ended with an ellipsis; a complete final sentence lacking
  punctuation is left intact (no fabricated ellipsis, no false "trimmed"
  notice). Demo fixture updated to a realistic "…narro..." truncation.
- Regression tests added for all four.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@BigSimmo

Copy link
Copy Markdown
Owner Author

Thanks — all review findings addressed in c2cfd57, with regression tests for each:

  1. Negated contraindications → false danger badge (document-summary-badges.ts, CodeRabbit Major + Codex P2): the contraindication rule now runs through a hasPositiveContraindication guard that scans the ~40 chars before each contraindicat* match for a negation cue (no, not, non, without, nil, no known, …). "no contraindications" / "not contraindicated" no longer emit a danger badge; a genuine contraindication still does. Test: "does not emit a danger badge for negated contraindication text".

  2. Decimal doses classified as headings (indexed-source-formatting.ts, CodeRabbit Major): isNumberedHeading now requires a non-lowercase token after the numeric prefix (\s+(?![a-z])\S), so "12.5 mg" / "2.5 mmol/L" stay paragraphs while Title-Case and digit-led headings still resolve. Test: "does not classify decimal dose/value lines as numbered headings".

  3. CRLF handling (indexed-source-formatting.ts, CodeRabbit): flowIndexedText and parseIndexedSourceText now normalize \r\n?\n atomically, so a Windows line ending is one newline, not a spurious blank line. Test: "treats a Windows CRLF as a single line break".

  4. Complete unpunctuated final sentence truncated (document-summary-formatting.ts, Codex P2): tail repair now only fires when the raw stored summary ended with an ellipsis (captured before the sanitizer normalizes it away), so a complete final sentence lacking a period is left intact with no false "trimmed" notice. Test: "keeps a complete final sentence that merely lacks terminal punctuation".

Verification: tsc, eslint, prettier clean; 112 unit tests pass; the earlier full verify:ui was 132/133 with the single failure a cold-compile flake on an unrelated forms spec (passes warm).

Note: this branch also merged current main (#489 document-first viewer) — the two redesigns are reconciled (#489's layout/sticky-rail + this PR's smart summary, badges, flattened evidence, flowing source text).

@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Request timed out after 900000ms (requestId=8a543201-4535-4d57-bc5c-094657fa153d)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant