Skip to content

Phase 4: HED annotation in the signal viewer - #263

Merged
neuromechanist merged 11 commits into
feature/issue-256-epic-viewer-workbenchfrom
feature/issue-255-phase4-hed-annotation
Sep 1, 2026
Merged

neuromechanist merged 11 commits into
feature/issue-256-epic-viewer-workbenchfrom
feature/issue-255-phase4-hed-annotation

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Part of epic #256. Implements #255.

Summary

Domain experts can now annotate a recording directly in the signal viewer using
the HED-SCORE clinical EEG vocabulary and base HED's artifact terms, and export
the result as BIDS TSV.

A pencil toggle beside the topomap arms annotation mode. With it on:

  • Click the trace to drop a zero-duration event marker; drag horizontally
    for a span with a live range highlight. Both open a popover offering fuzzy
    search over the vocabulary, grouped quick picks, and a free-text note.
  • Click a channel label — the viewer's existing bad-channel gesture, reused
    rather than duplicated — then annotate the marked channels as a set.
  • Annotations draw on an overlay canvas above the traces (dashed line with a
    cap for a marker, translucent violet span for a duration) and as a dedicated
    strip on the events minimap, visually distinct from the dataset's own events.
    Clicking one reopens it to edit or delete.
  • Two downloads, each appearing only when its kind has entries:
    <stem>_events.tsv and <stem>_channels.tsv.

Annotations persist in IndexedDB per (dataset, version, recording), restore on
mount, and flush on teardown, so a recording swap (#258) or an enlarge round
trip keeps them.

Vocabulary bundle

scripts/extract-hed-vocab.mjs parses base HED 8.4.0 and HED-SCORE 2.1.0 from a
local hed-standard/hed-schemas checkout into src/lib/eeg-viewer/hed-vocab.json.
The script header documents regeneration; there is no runtime schema fetch and no
new dependency (the hedxml scanner is ~40 lines).

Tags 488 — 396 SCORE, 92 base HED
Bundle 138 KB raw, 29 KB gzipped
Chunk dist/_astro/hed-vocab.*.js, its own lazy chunk
Quick picks 26, in 3 groups, all validated at generation time

Curated rather than complete: the whole SCORE library (every root is clinical EEG
by construction) plus base-HED's artifact tree, event categories, temporal markers,
and vigilance/postural state. Build verified the viewer chunk does not contain it —
the fetch happens when annotation mode is first entered.

Decisions

  • Scope correction applied. Channel-scoped time ranges are out; a click makes a
    zero-duration marker and a drag makes a span (both ordinary events.tsv rows),
    and channel annotations are a separate, timeless kind with channels.tsv
    semantics. The two kinds stay separate through model, persistence and export.
    Recorded as ADR 0013, which also states what that forecloses.
  • name, not channel, as the channels TSV's first column. BIDS
    channels.tsv requires name; using channel would make the export
    un-mergeable into a real one. It is an annotation file, so it omits the
    type/units columns that belong to the dataset rather than the annotator.
  • SCORE paths ship pre-prefixed (sc:Episode/Epileptic-seizure), so an export
    is usable with "HEDVersion": ["8.4.0", "sc:score_2.1.0"]. The panel says so.
    Open question: sc: is the conventional prefix in the HED-SCORE examples, but
    a sidecar may choose another. Emitting it here keeps the serializer dumb; making
    it configurable is a small change if anyone wants it.
  • Signed-in detection reads [data-user-menu] from the DOM. Nav.astro renders
    it only when getSession returned one, so its presence is exactly "there is a
    session this page can act on" — no extra fetch. A false negative only ever costs
    an extra confirm on leaving.
  • The beforeunload warning also fires when persistence itself failed, not just
    when anonymous. Same exposure, same fix: download the file.
  • Local-only storage in v1, per the issue's own recommendation; ADR 0013 records
    why and when to revisit.
  • Zero changes to src/pages/dataset/[id].astro — the layer mounts from inside
    viewer.ts, so all three mount paths (including Phase 5: View data button opens the enlarge viewer #262's new openRecordingInDialog)
    get annotations for free. Rebased onto e8f9d6c; no conflicts.

Test plan

Gates on the branch tip: lint, typecheck (0 errors), 1347 tests, build — all green.
114 new unit tests (64 model, 28 vocabulary, 22 storage), no mocks; the vocabulary
tests run against the real committed bundle and the storage fallback is the genuine
no-IndexedDB path under node.

Driven end to end in headless Chromium against the dev server on on005514
(129-channel HBN EEG), both themes, inline and enlarged:

  • Click makes a marker, drag makes a span with a live highlight
  • Fuzzy search ("spike" → 22 hits, exact tag first), 26 quick picks
  • Save closes the popover; Escape closes it; clicking an annotation reopens it with its note
  • Channel marking → "Annotate 2 marked channels" → status, tags, description
  • Both downloads produce correct BIDS filenames and content (real tabs, n/a, long-form HED)
  • Annotations survive a collapse/reopen remount (restored from IndexedDB)
  • Gestures still work after the enlarge move; ArrowRight still scrolls time (0.0–10.0 → 2.5–12.5)

Two bugs found and fixed during that pass: an author display:flex silently
beating the UA [hidden] rule (popover and panel never hid), and a default
focus() on close scrolling the trace out from under the annotator.

Deliberately left out

Channel-scoped time ranges (per the scope correction), server-side storage,
sharing, and any contribution path back to the dataset. Keyboard creation of
annotations — the popover, its controls and the annotation list are all
focus-reachable and focus-trapped, but placing a marker still needs the pointer.


Design feedback round

Live testing turned up three things about the popover. All three are in
7a22569, along with two review findings that live in the same code.

1. It covered what it was about. The popover opened at a fixed offset under
the toolbar, so a span dragged out in the middle of the trace was hidden behind
the box asking what it was. It is now placed adjacent to its selection and
never over it: right of it, else left, else below, else above, and only when no
placement clears it, at the right-centre of the trace area. A channel
annotation anchors to that channel's row in the gutter, so the labels it names
stay readable.

The arithmetic (placeAnnotationPopover) is pure and unit-tested — it decides
whether the annotator can see the signal they are describing, which is not
something a screenshot review catches reliably. Coordinates are relative to the
viewer root, so inline and enlarged differ only in the numbers.

One subtlety worth recording: bounds are the visible box, not the viewer
root. Inside the enlarge dialog the root is taller than the dialog that clips
it
(834 px of root in a 739 px dialog on a 1400×900 window), so placing
against the root's own height put the footer below the dialog's edge. Bounds
are therefore the root box intersected with the viewport and with any clipping
ancestor — stopping at <body>, because overflow on the root element clips the
viewport rather than a box, and documentElement.getBoundingClientRect() on a
scrolled page is nowhere near it. That one is a real bug found by testing
inline, not a defensive flourish.

Placement re-runs on every frame the popover survives (time scrubbing, channel
zoom, the enlarge move) and on window resize — twice there, once immediately
and once on the next frame, because a resize can arrive before the new viewport
metrics have settled.

2. Save and Cancel are pinned. The popover no longer scrolls as a whole:
the body scrolls, the footer does not, so the two buttons are on screen
whatever the vocabulary list is doing. Its height is also capped to the visible
bounds, which is what keeps the footer inside the dialog. Enter now saves,
once the draft carries at least one tag or a non-empty comment, except where a
control owns Enter itself (a textarea's newline, a button's or link's
activation — otherwise the quick-pick chips would stop being keyboard
reachable) or an IME is mid-composition. Escape still cancels, and the
footer says so.

3. A channel click annotates that channel. With annotate mode on, clicking
a channel label opens the channel popover for that channel directly instead of
only toggling the bad mark; the popover's status field then decides that mark
on save, so the two cannot disagree. Its quick picks are filtered to the noise
and artifact vocabulary — base HED's artifact tree (the causes) plus SCORE's
terms for what the artifact cost the recording — because "this electrode had a
seizure" is not a thing anybody annotates. The groups are derived from the
bundle (artifactQuickPicks), not curated a second time, so a regenerated
bundle keeps them in step. Outside annotate mode the bad-channel gesture is
exactly as it was. The bulk "annotate N marked channels" entry point stays for
channels marked before the pencil was armed.

Review findings

# Finding Where
1 Escape could close the popover and eject the enlarge dialog (engine-dependent close-request ordering) 7a22569 — guards the surrounding dialog's cancel while the popover is open, and briefly after, since the close request can arrive once it has closed; isPopoverOpen() exposes the same question outwards. Wired from inside the layer via root.closest("dialog") at open time, so dataset/[id].astro stays untouched and the enlarge move cannot leave a stale listener.
2 A destroy during openAnnotationStore leaked the connection af72bd0
3 Lane assignment and the channel index rebuilt on every overlay draw, drags included 7a22569 — both cached on the set's identity (the set is replaced, never mutated, so a stale cache is impossible), the visible-window filter shared with the hit test, drag repaints coalesced to one per frame
4 No coverage of the persistent storage path 1ab6938 — fake-indexeddb as a dev dependency. It is a platform shim, not a mock of anything this repo owns: the actual W3C algorithms under Node, as jsdom is a real DOM. Covers open-and-upgrade, a round trip through a second connection, key separation, and the degrade-to-memory flip through a genuine write failure
5 annotation-ui.ts's pure helpers untested 1ab6938 — 26 tests over placement, the time/pixel mapping, Enter's submit rule, the unsaved-work predicate, the colour blend
6 The channels export was filename-identical to a real channels.tsv dbdfbf3 — now <stem>_channels-annotations.tsv, with a line beside the button saying to merge it into the dataset's own table rather than use it as one
7 formatSeconds could emit -0 96db415

Verified live

Chrome against bun run dev on on005514 (129-channel HBN EEG), inline and
enlarged, both themes, with real mouse and real key events:

  • Drag → pick a tag → click Save: popover closes, the annotation
    persists (1.9912–3.1316 s · Electroencephalographic-seizure +1), the
    span draws, the dialog stays open
  • Enter saves from the search box once a tag is present
    (4.6228–5.5 s · Spike)
  • Escape closes the popover only; the enlarged viewer stays open, and a
    second Escape then closes the dialog — the layering the guard is for
  • Delete from the popover removes the annotation
  • Popover sits beside its selection with the 8 px gap and never over it;
    flips left near the right edge; falls back only where nothing clears
  • Footer inside the dialog's visible area (bottom 772 px against the
    dialog's 780 px), body scrolling (633 px of content in a 557 px box)
  • Channel click in annotate mode opens Annotate 1 channel for that
    channel with 31 artifact picks in 4 groups, no epileptiform or sleep
    terms; saving marks it (E54 · bad · Line-noise-artifact)
  • Window resize with the popover open: it re-places and re-caps its height
    so the footer stays in view

One caveat on that last line: the automation harness resizes the browser
window without dispatching resize (0 events observed across several
resizes), so it was exercised by dispatching a resize event on the same code
path a user's drag of the window edge takes — 709 px tall → 641 px, footer back
inside the viewport. A human dragging the window edge is worth one look.

Parses base HED 8.4.0 and the HED-SCORE 2.1.0 library schema from a local
hed-schemas checkout into a committed JSON bundle (488 tags, 138 KB): the
whole SCORE clinical EEG vocabulary plus curated base-HED subtrees for
artifacts, event categories, temporal markers and vigilance state.

SCORE paths carry the `sc:` namespace prefix so an exported HED string is
usable as-is with `"HEDVersion": ["8.4.0", "sc:score_2.1.0"]`.

Hand-rolled hedxml scanner rather than an XML dependency; the script header
documents how to regenerate. Biome skips the generated bundle.

Tested: script runs clean, resolves all 26 quick picks, rejects duplicates.
`loadHedVocab` is the only reference to the JSON bundle, so Vite splits it
into its own chunk and the viewer's initial bundle never carries it; the
fetch happens when annotation mode is first entered.

Search is hand-rolled scoring over the 488-entry list: exact, prefix,
hyphen word-boundary, substring, path, description, shortest-tag tiebreak.
Multi-word queries are a conjunction scored by their weakest term.

Tested: 28 vitest cases against the real bundle, including chunk-size and
prefix invariants.
Two disjoint kinds: TimeAnnotation (an events.tsv row, duration 0 for a
point marker) and ChannelAnnotation (a channels.tsv row with status and
status_description). Pure module - construction with clamping, sorting,
upsert/remove, windowing, overlap detection, greedy lane assignment for
drawing overlapping spans, and both serializers.

Output is deterministic: total sort order, 0.1 ms rounding without float
noise, n/a for missing, tabs and newlines stripped from free text at the
point it enters the model.

Tested: 64 vitest cases, including byte-identical output for a set built in
a different order.
Keyed by dataset id, dataset version and recording path (a JSON tuple, so
no separator a BIDS path could contain). Not keyed by user: the issue
requires persistence regardless of sign-in.

Every IndexedDB call is guarded. A synchronous throw on open (Firefox
private windows), an absent factory, or a later quota failure degrades to
an in-memory store for the session with `persistent` false, which the
viewer surfaces as "download these". Records read back are re-validated
through the model's constructors rather than trusted.

Tested: 22 vitest cases; the no-IndexedDB fallback is the real path under
node, not a simulated one.
A pencil toggle beside the topomap arms the tool. On the trace, a click
drops a zero-duration event marker and a horizontal drag makes a span,
both opening a focus-trapped popover with fuzzy HED search, grouped quick
picks and a free-text note. In the gutter, channel selection stays the
viewer's existing bad-channel click, which the panel then annotates as a
set; the two exports are separate downloads.

The layer is self-contained: an overlay canvas above the chrome canvas, a
popover and a panel, reading geometry the renderer already computed. It
never owns the arrow keys, and pointer handlers are capture-phase on the
scope so gutter clicks still reach the existing handler.

Annotations restore on mount and flush on teardown, so a recording swap or
an enlarge round trip keeps them. Anonymous or unpersisted work arms a
beforeunload confirm and an in-panel notice.

Tested: driven end to end in Chromium against the dev server on on005514,
both themes, inline and enlarged - marker, drag, edit, delete, search,
quick picks, channel marks, both downloads, restore across a remount.
Records why annotations are two BIDS kinds rather than one type with
optional fields, why storage is local-only in v1, and what that forecloses
(channel-scoped time ranges, cross-device access, sharing).
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

A mount can be destroyed while openAnnotationStore is still in flight — a
recording swap, or the enlarge dialog closing. The resolved connection was
then unreachable: destroy() flushes through `store`, which is still null,
so the IDBDatabase stayed open for the life of the page.

Close it at the point the layer learns it is gone.
formatSeconds rounds before printing, and a value just below zero rounds to
-0, which stringifies as the cell "-0" — a value no reader of an onset column
expects. Return "0" for a rounded zero of either sign.
The channel annotations downloaded as <stem>_channels.tsv, which is the name
of the recording's real channels table while being deliberately not one: it
lists only the annotated channels and omits the type/units columns BIDS
requires. Dropped into a dataset under that name it would delete every
unannotated channel's row.

Rename it <stem>_channels-annotations.tsv.
Three changes from live design feedback, plus two fixes in the same code.

Placement. The popover opened at a fixed offset under the toolbar, which put
it on top of the very span the annotator had just dragged out. It is now
placed adjacent to its selection: right of it, else left, else below, else
above, else — only when nothing clears it — at the right-centre of the trace.
Coordinates are relative to the viewer root, so the same arithmetic serves the
inline and the enlarged mount. Bounds are the *visible* box (root box
intersected with the viewport and any clipping ancestor), because inside the
enlarge dialog the viewer root is taller than the dialog that clips it, and
placing against the root put the footer below the dialog's edge. It follows
the selection across a frame (scrubbing, channel zoom) and a window resize.

Pinned footer. The popover no longer scrolls as a whole: its body does, and
Save/Cancel sit in a footer that cannot leave the frame however long the
vocabulary list is. Enter now saves, once the draft carries a tag or a note,
except where a control owns Enter itself (a textarea's newline, a button's
activation) or an IME is mid-composition. Escape still cancels.

Channel entry. With annotate mode on, clicking a channel label opens the
channel popover for that channel directly rather than only toggling the bad
mark — the popover's status field decides that mark on save. Its quick picks
are the artifact vocabulary (base HED's artifact tree plus SCORE's terms for
what the artifact cost the recording), derived from the bundle rather than
curated a second time. Outside annotate mode the marking gesture is unchanged.

Escape and the enlarge dialog. Whether a cancelled keydown suppresses a modal
dialog's own close request is engine-dependent, so one Escape could have
closed the popover and ejected the enlarged viewer behind it. The layer now
guards the surrounding dialog's `cancel` while its popover is open (and
briefly after, since the close request can arrive once it has closed), and
exposes isPopoverOpen for the same question asked from outside.

Overlay caching. The lane assignment and the channel index were rebuilt on
every drawOverlay, which runs on every pointer move of a drag. Both are now
cached on the set's identity, the visible-window filter is shared with the
hit test, and drag repaints are coalesced to one per frame.
The placement arithmetic decides whether the popover covers the signal being
annotated, which a screenshot review catches unreliably; it and the other pure
helpers are exported precisely so they can be driven without a browser.
26 tests over placement (each candidate, the clamps, bounds that do not start
at the viewer's origin), the time/pixel mapping, Enter's submit rule, the
unsaved-work predicate and the colour blend.

Storage gains a real IndexedDB. fake-indexeddb is a platform shim rather than
a mock of anything here — the actual W3C algorithms under Node, as jsdom is a
real DOM — so nothing in annotation-store.ts is stubbed: the tests drive the
genuine open-and-upgrade, a round trip through a second connection, key
separation, and the degrade-to-memory path through a genuine write failure.
Until now only the no-IndexedDB fallback was covered, because Node has none.
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Both rounds are in, gates green on the tip (1ab6938): lint, typecheck 0 errors, 1347 tests, build. Full write-up is in the PR body under Design feedback round; dispositions below.

Design feedback

Ask Done Commit
Popover must not cover the selection; place it adjacent, flipping to stay in bounds; fall back to the trace's right-centre; work inline and enlarged; survive resize Yes 7a22569
Save/Cancel pinned in a non-scrolling footer; Enter saves when a tag or comment is present; Escape still cancels Yes 7a22569
Annotate-mode channel click opens the channel popover for that channel, quick picks filtered to noise/artifact Yes 7a22569

Two things I hit while testing that are worth knowing:

  • Bounds are the visible box, not the viewer root. Inside the enlarge dialog the viewer root is taller than the dialog that clips it (834 px of root in a 739 px dialog), so sizing against the root put the pinned footer below the dialog's edge — the exact failure the pinning is meant to prevent. Bounds are now the root intersected with the viewport and any clipping ancestor, stopping at <body> (overflow on the root element clips the viewport, not a box, and documentElement.getBoundingClientRect() on a scrolled page is nowhere near the viewer — that one silently squeezed the popover to its 180 px floor in the inline mount).
  • The channel mark and the panel could disagree for one render. mutate redraws the panel before syncChannelMarks updates the montage, so the bulk "annotate N marked channels" entry point missed the channel just saved. The panel is rendered again after the sync.

Review findings

# Disposition
1 — Escape layering Fixed, 7a22569. isPopoverOpen() is exposed as asked, and the defensive cancel guard is wired from inside the layer via root.closest("dialog") at popover-open time. That was the cleanest seam: the viewer's host is moved into the dialog when enlarged, so a listener attached at mount would be on the wrong element (or on none), and dataset/[id].astro stays untouched — which the PR's "zero changes to that file" claim depends on. The guard also holds for ESCAPE_GUARD_MS after the popover closes, because whether the close request arrives before or after the popover's own handler is the engine-dependent part. Verified in Chrome: first Escape closes the popover and leaves the enlarged viewer open; a second Escape closes the dialog.
2 — IDB connection leak Fixed, af72bd0, exactly as prescribed.
3 — Per-draw recomputation Fixed, 7a22569. Lanes and the channel index are cached on the set's identity rather than invalidated by hand — the set is only ever replaced, never mutated in place, so a stale cache is impossible. The visible-window filter is shared with the hit test, and drag repaints go through one rAF per frame.
4 — Real IndexedDB coverage Done, 1ab6938. fake-indexeddb as a dev dependency; open-and-upgrade, a round trip read back through a second connection, key separation, and the persistent→memory flip driven by a genuine write failure (a dead connection, which is the real-world cause) rather than a stubbed error.
5 — Pure helpers untested Done, 1ab6938. 26 tests: placement (every candidate, the clamps, bounds that do not start at the viewer's origin), timeAtX/xAtTime/clampTime, Enter's submit rule, the unsaved-work predicate, withAlpha. The helpers were extracted to module level to make this possible, which is also why the placement logic is testable at all.
6 — Channels export filename Done, dbdfbf3. <stem>_channels-annotations.tsv, plus a line beside the button: merge it into the dataset's channels.tsv rather than use it as one.
7 — formatSeconds negative zero Fixed, 96db415, with a test.

Nothing deferred.

On "Save does nothing"

I could not reproduce it on the settled build, and I think the report caught a mid-edit module: the refactor that hoists the save handler out of the click listener passes through a state where the file does not parse, and a reload in that window leaves the viewer's JS not evaluated at all — which fails Save, Escape and Enter together, exactly as described.

On the current tip, with real mouse and real key events in Chrome (on005514, 129-channel HBN EEG, inline and enlarged, both themes):

  • Drag → pick a tag → click Save: popover closes, annotation persists (1.9912–3.1316 s · Electroencephalographic-seizure +1), span draws, dialog stays open. elementFromPoint at the Save button's centre returns the button itself, so nothing overlays it.
  • Enter from the search box saves once a tag is present (4.6228–5.5 s · Spike).
  • Escape closes the popover only; the dialog survives.
  • Delete from the popover removes the annotation.

Worth a retest now that the build is settled.

Two notes for whoever retests locally:

  • The automation harness resizes the browser window without dispatching resize, so the resize path was exercised by dispatching that event on the same code path a window-edge drag takes (709 px → 641 px, footer back in view). A human drag of the window edge is the one thing left to eyeball.
  • I issued a deleteDatabase('nemar-eeg-annotations') while cleaning up my test annotations, and it is queued behind an open connection in another tab. Until every localhost:4321 tab holding it is closed, a fresh page there may see the store report as unavailable and keep annotations in memory for that session (with the console warning the code already prints). Closing the localhost tabs once clears it; nothing outside the local browser profile is affected.

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