Skip to content

feat(wsi): DSA annotation overlay — Option B - #1

Closed
raylim wants to merge 184 commits into
feature/native-wsi-viewerfrom
feature/wsi-annotation-overlay
Closed

raylim wants to merge 184 commits into
feature/native-wsi-viewerfrom
feature/wsi-annotation-overlay

Conversation

@raylim

@raylim raylim commented Jun 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Builds on PR cBioPortal#5608 (feature/native-wsi-viewer) to implement Option B from the MSK annotation roadmap.

What's added

Sidebar — "Annotate in DSA" button

  • New msk_dsa_url server config key (null by default, DSA features hidden when absent)
  • When configured, an "Annotations" sidebar section appears for every selected slide
  • Loading state while querying DSA for the slide
  • Slide in DSA: shows annotation count, deep-link to HistomicsUI (/histomics#?image={girderItemId}), show/hide toggle
  • Slide not in DSA: shows "Slide not in DSA" (no button shown)

Read-only Annotorious overlay

  • @annotorious/openseadragon v3 integrated (drawingEnabled: false = no drawing, clicks still work)
  • Annotator created after OSD open event; destroyed on slide change / viewer teardown
  • DSA annotations fetched in parallel with tile load (non-blocking); MobX reaction syncs late-arriving annotations into the annotator automatically
  • Annotation click shows a floating label tooltip over the viewer canvas

Girder item ID resolution

  • At slide selection: GET {msk_dsa_url}/api/v1/item?text={image_id}&limit=5
  • Matches first item whose name starts with image_id; result cached per image_id
  • credentials: 'include' for unified Keycloak SSO session

DSA annotation element types supported

DSA type W3C selector
rectangle (center + w/h) FragmentSelector xywh=pixel:x,y,w,h
polyline closed ≥3 pts SvgSelector <polygon points="..."/>
point FragmentSelector 10×10 sentinel square

Files changed

File Change
src/config/IAppConfig.ts `msk_dsa_url: string
src/config/serverConfigDefaults.ts msk_dsa_url: null
src/shared/components/wsiViewer/WSIViewer.tsx All DSA + Annotorious logic
src/pages/patientView/PatientViewPageTabs.tsx Pass dsaUrl prop
src/shared/components/resources/ResourceTab.tsx Pass dsaUrl prop
src/shared/components/wsiViewer/WSIViewer.spec.tsx +15 unit tests
package.json / pnpm-lock.yaml @annotorious/openseadragon

Tests

46/46 unit tests pass (GREP=WSIViewer.spec pnpm run testMain). New tests cover transformDsaAnnotations (all 4 element types), resolveDsaItemId (cache hit/miss, error cases), fetchDsaAnnotations (success + error).

@raylim
raylim force-pushed the feature/native-wsi-viewer branch from 7a50689 to 6d39446 Compare June 12, 2026 20:40
@raylim
raylim force-pushed the feature/wsi-annotation-overlay branch from 98cdbac to a9bd5b2 Compare June 14, 2026 02:05
@raylim
raylim force-pushed the feature/native-wsi-viewer branch from e712606 to 267b2dc Compare June 24, 2026 20:50
@raylim
raylim force-pushed the feature/native-wsi-viewer branch from fd07208 to be03815 Compare July 22, 2026 20:01
@raylim
raylim force-pushed the feature/native-wsi-viewer branch from fe0c1dd to fad0b42 Compare July 30, 2026 20:47
@raylim
raylim force-pushed the feature/native-wsi-viewer branch 3 times, most recently from f0d56f0 to f0ace25 Compare August 19, 2026 05:30
raylim and others added 22 commits August 19, 2026 18:59
Add WSIViewer React component that renders whole-slide images natively
using OpenSeadragon, replacing the IFrameLoader for HE resources.

- src/shared/components/wsiViewer/WSIViewer.tsx: MobX observer component
  - Fetches patient hierarchy from tile server /patient/{id}
  - Slide sidebar: grouped by sample, click to select
  - OSD viewer with custom TileSource → /tiles/{image_id}/zxy/{z}/{x}/{y}
  - Lazy-loads openseadragon as a separate rspack chunk
  - Auto-selects first servable slide on load

- src/shared/components/wsiViewer/wsiViewerTypes.ts: TypeScript types for
  PatientHierarchy, Sample, Part, Block, Slide, TileMetadata

- src/shared/lib/ResourceConfig.ts:
  - Added nativeViewer?: 'wsi' to ResourceCustomConfig
  - Added HE config entry with nativeViewer: 'wsi'

- src/shared/components/resources/ResourceTab.tsx:
  - Import WSIViewer
  - nativeViewer @computed getter
  - Short-circuit render for nativeViewer === 'wsi'

- package.json / pnpm-lock.yaml: add openseadragon@6.0.2

The resource URL in data_resource_patient.txt must be:
  https://<tile-server>/patient/{patient_id}

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Add a first-class 'H&E Slides' tab to the patient view that renders the
native OpenSeadragon WSI viewer without using the Resources mechanism.

- IAppConfig.ts: add msk_wsi_tile_server_url: string
- serverConfigDefaults.ts: default to empty string (tab hidden)
- PatientViewPageTabs.tsx:
  - Add WSIHESlides = 'wsiHESlides' to enum
  - Import WSIViewer
  - When msk_wsi_tile_server_url is set, push H&E Slides tab that renders
    WSIViewer with url = ${msk_wsi_tile_server_url}/patient/${patientId}

No data files, no resource entries, no per-patient URLs needed.
Set msk_wsi_tile_server_url in application.properties to enable.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Add WSIViewer React component that fetches patient slide hierarchy
  from the MSK tile server and renders tiles via OpenSeadragon 6
- Add H&E Slides patient tab in PatientViewPageTabs, shown when
  msk_wsi_tile_server_url is configured (non-null)
- Add msk_wsi_tile_server_url to IAppConfig + serverConfigDefaults
- Add WSI tile server proxy in rspack.config.js dev server config:
  proxy /patient/<patientId> → tile server patient hierarchy
  proxy /tiles/<id>/... → tile server ZXY tiles
  copy OSD button images from node_modules at build time
- Fix DefinePlugin falsy-string bug: use !== undefined check so that
  WSI_TILE_SERVER='' compiles as "" (empty string), not null
- Add HOST=0.0.0.0 in env/custom.sh so dev server binds on all interfaces
- Add openseadragon TypeScript typings

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Left nav panel: filter chips (All/H&E/IHC), collapsible sample nodes
  with PRIMARY/metastasis badges, oncotree code, slide count, blue stain
  dots, block badges, magnification and file size per slide item
- Right metadata sidebar: slide thumbnail, image properties table
  (dimensions, MPP, objective, zoom levels), pathology table
  (stain, sample, cancer type, oncotree, block label)
- Auto-select first H&E slide on patient load
- Track selectedSample/selectedMeta for sidebar population

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Replace stain-group rank sort with pure chronological order by block_number,
with stain_name as tiebreaker. Both WSIViewer.tsx and viewer/index.html updated.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Image Properties labels: hover tooltips for Dimensions, MPP, Objective,
  Zoom levels, Tile size explaining each field
- OncoTree code badge (nav panel + Pathology table): links to
  oncotree.mskcc.org search for that code
- Sample ID in Pathology table: links to the cBioPortal patient/sample page
  (requires new optional studyId prop threaded from PatientViewPageTabs)
- Slide count badge: tooltip 'Tile-servable / total slides'
- SlideItem magnification: tooltip 'Objective lens magnification'
- SlideItem file size: tooltip 'File size on disk'
- Block badge already had BLOCK_LABEL_TIP; Pathology Block row now also
  has the same tooltip
- MetaTable upgraded: Array<[string,string]> → MetaRow[] supporting
  labelTip and href per row

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The oncotree site was redesigned and no longer supports the old
#/home?version=...&search_term=... hash routing. Link to the root
instead; the code name is shown in the tooltip from hierarchy data.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Slides backed by large S3 objects take ~3-4s on first access (TiffSlide
cold open). After selecting the initial slide, fire off background
metadata fetches for all remaining servable slides at CONCURRENCY=4
so the tile server's SlideCache and Redis metadata cache are warm before
the user clicks another slide.

- metaCache Map stores prefetched TileMetadata per image_id
- mountOSD checks metaCache before fetching (cache hit = instant)
- metaCache cleared on patient change / unmount
- prefetchSlideMetadata skips already-cached and selected slides

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
When the user clicks slide B while slide A's metadata is still fetching,
both mountOSD calls run concurrently. The one that finishes later would
destroy the viewer the earlier one just created, leaving viewerReady=false
forever (infinite loading spinner).

Fix with a monotonic mountSeq counter: each selectSlide bumps the counter
and passes the captured value to mountOSD; any await point checks whether
the sequence is still current and aborts if superseded.

Also:
- Clear this.error on selectSlide so a previous open-failed doesn't
  hide the main viewer for the next slide selection
- Add error handling for metadata fetch (was silently stuck previously)
- Use tileSize (not tileWidth/tileHeight) matching the iframe viewer
- Add tileOverlap: 0, timeout: 90000, imageLoaderLimit: 6

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Change prefetch from CONCURRENCY=4 (all workers) to serial (1 at a time)
  with 200ms pause between slides. With 4 gunicorn workers, CONCURRENCY=4
  saturated all workers causing CLOSE_WAIT pile-up and hung requests.
  Serial prefetch leaves 3 workers free for user-initiated clicks.

- Prefetch now fetches metadata + thumbnail concurrently per slide.
  Both endpoints cache in Redis; subsequent user clicks are served
  instantly without cold SVS opens from ECS.

- Set WSI_TILE_SERVER to absolute URL (http://pllimsksparky3:8081).
  Empty string caused relative tile URLs that routed through rspack
  webpack-dev-middleware, which queues all requests during hot-reloads.
  Absolute URLs bypass rspack proxy entirely.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…-time constant)

Previously the tile server URL was baked into the JS bundle at rspack build
time via DefinePlugin (ENV_WSI_TILE_SERVER). This meant every environment
needed its own rebuild to set a different URL.

Now the frontend defaults to null and reads the value from the Java config
service at runtime (msk.wsi.tile_server.url in application.properties),
exactly like all other server config properties.

Changes:
- serverConfigDefaults.ts: default null instead of build-time constant
- rspack.config.js: remove DefinePlugin ENV_WSI_TILE_SERVER entry
- typings/missing.d.ts: remove ENV_WSI_TILE_SERVER declaration
- env/custom.sh: update comment (WSI_TILE_SERVER still used for dev proxy target)

The Java FrontendPropertiesServiceImpl already has the new enum entry in a
separate commit in the cbioportal backend repo.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- env/custom.sh: replace internal MSK hostname with localhost (was
  inadvertently exposed in the public upstream PR)
- WSIViewer: set this.hierarchy = null in componentWillUnmount so the
  prefetchSlideMetadata loop exits cleanly after unmount (previously
  the loop kept firing fetch() calls on a 200ms cadence until exhausted)
- tileServerBase regex: tolerate optional trailing slash on patient URLs
  so tile/thumbnail URLs are not malformed for ResourceTab-sourced URLs

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
… lifecycle

- tileServerBase: 5 cases covering trailing-slash, path prefix, no-match
- servableSlides: 5 cases covering null hierarchy, filtering, multi-sample flatten
- componentWillUnmount: verifies hierarchy is nulled to stop prefetch loop
- loadHierarchy: error handling (non-ok, network), success state, mountSeq bump
- prefetchSlideMetadata: cancellation when hierarchy nulled mid-loop

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Chip labels ('All', '● H&E', '● IHC') are static strings but using
dangerouslySetInnerHTML on non-static data is a bad pattern.
Use React children instead.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
HE resourceId is used on public cBioPortal (crc_hta11_htan_2021) with
URLs pointing to the old iframe slide viewer. Without this guard,
ResourceTab would render WSIViewer for those resources even when the
tile server is not configured, breaking remote e2e tests and any
cBioPortal instance that uses the HE resourceId without our tile server.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Tests cover:
- HE resourceId returns customizedDisplayName 'H&E Slides'
- nativeViewer: 'wsi' present when msk_wsi_tile_server_url is set
- nativeViewer stripped when msk_wsi_tile_server_url is null or undefined
- RESOURCE_CUSTOM_CONFIGS['HE'] not mutated by the guard

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- CoordBar component overlaid at bottom of OSD viewer
  - X/Y pixel coordinate inputs with Enter-to-navigate
  - 'Go' button pans to entered image coordinates
  - Live cursor position readout in px (and μm when mpp calibration available)
- goToCoordinates() action: parses inputs, converts via
  imageToViewportCoordinates, calls viewport.panTo
- OpenSeadragon MouseTracker tracks cursor position and updates
  cursorPos observable for live display; cleared on mouse exit
- destroyViewer() cleans up MouseTracker before destroying OSD instance
- 4 new unit tests for goToCoordinates (null osdViewer, valid coords,
  empty inputs, non-numeric inputs); 22 WSIViewer tests total

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Fetch n_workers from /health at page load to know how many workers need priming
- prefetchSlideMetadata now fires /warmup n_workers times per slide alongside
  metadata + thumbnail, ensuring all gunicorn workers have the slide open in
  SlideCache (round-robin routing means N calls ≈ N workers warmed)
- Default n_workers = 4 matches Dockerfile CMD --workers 4
- Update prefetchSlideMetadata cancellation test: bound now reflects
  2 (meta+thumb) + n_workers (warmup) fetches per slide

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- URL hash #wsi:slide=<id>&x=<px>&y=<py>&z=<zoom> persists current view
  - Written on slide selection and after every pan/zoom animation finishes
    (OSD animation-finish event)
  - Restored on page load: if hash references a valid slide for this patient,
    that slide is selected and viewport is restored immediately after OSD open
- 'Share view' button in the CoordBar:
  - Writes current state to hash then copies window.location.href to clipboard
  - Shows '✓ Copied' confirmation for 2 s
- readHashState / writeHashState are private helpers; namespaced 'wsi:'
  so they don't clobber other hash fragments
- 5 new unit tests for readHashState (null/empty, unrelated hash, valid parse,
  missing fields, non-numeric); 27 WSIViewer tests total

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…dom tests

Problems fixed:
- window.location.hash = '...' fires hashchange on every pan/zoom; use
  history.replaceState instead so cBioPortal's own hash-based cohort-nav
  is not disrupted and browser history is not polluted
- navigator.clipboard.writeText() was not awaited so a permissions-denied
  rejection was silently swallowed and the execCommand fallback never ran
- readHashState / writeHashState accessed window at describe-level in tests
  (Node env has no window), crashing the entire test suite (0 tests ran)

Changes:
- writeHashState: new URL(href) + history.replaceState(null, '', url)
- readHashState: guard typeof window === 'undefined'
- writeHashState: guard typeof window === 'undefined'
- copyViewLink: make async; await navigator.clipboard.writeText
- WSIViewer.spec: add @jest-environment jsdom docblock; move origHash
  capture to beforeEach (was at describe level, threw ReferenceError)
- 27 tests passing

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
OSD with a custom tile source can default to top-left instead of the
centered zoom-to-fit view. Explicitly call vp.goHome(true) in the
'open' handler when there is no URL hash state to restore, so the slide
always opens centered with the full image visible.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…tion

Register animation-finish handler INSIDE the open callback so OSD's
initial fit animation-finish cannot overwrite the shared-link hash before
the open handler has a chance to read and restore it.

Also call writeHashState() at the end of the open handler so the URL
always reflects the current slide and position immediately on load
(rather than waiting for the first user pan/zoom).

Previously: animation-finish was registered before open fired, so OSD's
goHome animation completion could clobber the #wsi: hash from the shared
URL, making restoration silently restore to the home position.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@raylim
raylim force-pushed the feature/native-wsi-viewer branch from ceaf8fe to a4d99e3 Compare August 19, 2026 23:00
- Add `msk_dsa_url` config key (IAppConfig + serverConfigDefaults)
- Resolve girder item ID from DSA item search API at slide select;
  cache results in-memory per image_id
- Fetch annotations from DSA `/api/v1/annotation?itemId=...` and
  transform DSA element types (rectangle/polyline/point) to W3C Web
  Annotations consumable by @annotorious/openseadragon
- Initialise read-only Annotorious OSD annotator after the OSD
  `open` event; destroy on slide change / viewer teardown
- MobX reaction syncs `dsaAnnotations` into Annotorious so late-
  resolved annotations (fetched after tile opens) appear automatically
- Add "Annotations" sidebar section: annotation count, "Slide not in
  DSA" fallback, "Annotate in DSA" HistomicsUI deep-link, show/hide
  toggle button
- Annotation click shows a floating label tooltip over the viewer
- Thread `dsaUrl={getServerConfig().msk_dsa_url}` through
  PatientViewPageTabs and ResourceTab
- 15 new unit tests (transformDsaAnnotations, resolveDsaItemId,
  fetchDsaAnnotations); all 46 tests pass

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@raylim
raylim force-pushed the feature/wsi-annotation-overlay branch from a9bd5b2 to ca1500b Compare August 20, 2026 03:55
@raylim
raylim force-pushed the feature/native-wsi-viewer branch from 2155e30 to 873066b Compare August 28, 2026 12:51
@raylim

raylim commented Sep 30, 2026

Copy link
Copy Markdown
Owner Author

Superseded. Native annotation authoring now lives in #11 (native track), and its resource-data successor is in progress on codex/wsi-rd-annotations. Closing this DSA overlay (Option B) prototype; the branch is kept.

@raylim raylim closed this Sep 30, 2026
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