Przejdź do treści
Biblioteka skilli
Programowanie · Budowanie i kod

nimbus-frontend

/nimbus-frontend

Pomaga pisać i zmieniać komponenty Vue 3, moduły Vuex, interfejsy TypeScript i widoki Vuetify 4 zgodnie z wzorcami projektu.

Repozytorium
nimbusimage ↗
Licencja
Apache-2.0
Ostatnia zmiana repozytorium
27.10.2026

Ocena i bezpieczeństwo

89/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść26 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena13 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
3
Skrypty
0
Komentarze HTML
11
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 27.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.

Co sprawdzić przed instalacją
  • SKILL.md zawiera komentarze HTML (11). Nie widać ich w podglądzie Markdown, a model je czyta.

Co robi i kiedy

Pomaga pisać i zmieniać komponenty Vue 3, moduły Vuex, interfejsy TypeScript i widoki Vuetify 4 zgodnie z wzorcami projektu.

Oryginalny opis (EN)

Use when writing or modifying Vue 3 components, Vuex store modules, TypeScript interfaces, or Vuetify 4 UI in the src/ directory. Covers: <script setup> composition API, vuex-module-decorators (@Module, @Action, @Mutation), Vuetify 4 theming (CSS Cascade Layers, light/dark mode), select slot patterns (no .raw wrapper), dialog patterns, API client usage (GirderAPI.ts, AnnotationsAPI.ts), logging utilities (logWarning/logError instead of console.*), button conventions (5-role taxonomy — primary/secondary/tertiary/destructive/icon-only — with required variant and size), button loading states, @gi

Jak działa

  1. Dependency bumps and Vitest 4
  2. Test mocks must model the real store's REPLACEMENT semantics
  3. Component Patterns
  4. Vuetify 4 Patterns
  5. @girder/components Compatibility
  6. Dialogs
  7. API Calls
  8. Palette content stays mounted: gate server work on visibility
  9. An omitted optional boolean prop is false, not undefined
  10. Opening a palette from a component that has no palette registry
Sekcje z nagłówków SKILL.md, w oryginale · 1 241 linii, 11 510 słów
Podgląd SKILL.md
---
name: nimbus-frontend
description: "Use when writing or modifying Vue 3 components, Vuex store modules, TypeScript interfaces, or Vuetify 4 UI in the src/ directory. Covers: <script setup> composition API, vuex-module-decorators (@Module, @Action, @Mutation), Vuetify 4 theming (CSS Cascade Layers, light/dark mode), select slot patterns (no .raw wrapper), dialog patterns, API client usage (GirderAPI.ts, AnnotationsAPI.ts), logging utilities (logWarning/logError instead of console.*), button conventions (5-role taxonomy — primary/secondary/tertiary/destructive/icon-only — with required variant and size), button loading states, @girder/components compatibility, and style guidelines."
---

# Nimbus Frontend Development

## Dependency bumps and Vitest 4

- Compare the actual resolved graph, not the Dependabot title. An override can
  make a proposed bump a no-op. Keep legacy consumers on the API major they
  require; a direct upgrade must not force every transitive consumer across it.
- A pnpm package has both a `packages` entry and a `snapshots` dependency entry.
  Updating only its version and integrity can omit a newly required dependency.
  Re-resolve with pnpm and inspect the diff; a frozen install checks importer
  consistency but does not prove every transitive snapshot is complete.
- Vitest 4 mocks used with `new` must use a regular function or class, not an
  arrow. Sweep sibling constructor mocks, including rarely exercised GIF/ZIP
  paths. Factory methods such as vtk's `newInstance()` remain ordinary calls.
- `vi.restoreAllMocks()` no longer clears standalone mock call history. The
  suite uses `clearMocks: true` for call isolation; tests must still reset any
  implementations or state they change. Do not relax call-count assertions.
- jsdom 24 forwards stylesheet errors through a host console outside Vitest 4's
  test console. Filter only `Could not parse CSS stylesheet` on its existing
  virtual-console handlers, preserving every other error. A console.error
  wrapper in test setup misses these events and can produce hundreds of MB of
  log output. Verify the actual log after a runner upgrade.

## Test mocks must model the real store's REPLACEMENT semantics

A mock that mutates state in place where the real store replaces it makes
tests silently vacuous. `AnalysisPanel.test.ts`'s `setPlots` did
`plots.length = 0; plots.push(...)` while the real `applyAnalysisPlots`
builds a new array. Vue short-circuits a computed whose value is unchanged
by identity, so `analysisPlots` never invalidated and **every watcher
downstream of it silently never re-ran** — a new test for plot-removal
behavior passed against code that did nothing.

It hid because an existing test appeared to cover removal: its watcher
happened to read `analysisPopulation`, which returns a fresh array each
evaluation, so that one re-fired for an unrelated reason.

Rules:
- Mock setters replace (`mocks.plots = [...next]`), matching the store.
- Booleans and other scalars are the same trap in reverse: an intermediate
  computed returning an unchanged `true` stops propagation, so a test that
  changes only downstream data may never re-run the watcher.
- Before trusting a new watcher test, make it FAIL once (revert the fix, or
  assert the opposite) — this one passed for the wrong reason first.

Two related mock traps, both of which make a test assert against something
the component never touched:

- **A `vi.mock` factory captures the spy it closes over.** Reassigning
  `mocks.someAction = vi.fn()` in `beforeEach` leaves the component calling
  the *original* spy while the test asserts on the new one — "expected spy
  to be called, number of calls: 0" with obviously working code. Use
  `mocks.someAction.mockClear()` instead.
- **A plain-object store mock is not reactive**, so a component watching
  `() => store.something` never fires when a test assigns to it. If the
  behavior under test is a watcher on store state, wrap the mock's default
  export in `reactive()` (`vi.mock("@/store", async () => { const { reactive }
  = await import("vue"); return { default: reactive({ … }) }; })`).

## Component Patterns

### Script Setup (Composition API)

All 121 components use `<script setup lang="ts">`:

```vue
<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import store from "@/store";

const props = defineProps<{
  value: string;
}>();

const emit = defineEmits<{
  (e: "update:modelValue", value: string): void;
}>();

const localState = ref("");

const computedValue = computed(() => props.value.toUpperCase());

watch(() => props.value, (newVal) => {
  localState.value = newVal;
});

onMounted(() => {
  // lifecycle hook
});
</script>
```

### Store Access

```typescript
import store from "@/store";
import annotationStore from "@/store/annotation";

// Direct usage in <script setup> — no `this` needed
store.someAction();
annotationStore.filteredAnnotations;
```

Store modules still use `vuex-module-decorators` with `@Module`, `@Mutation`, and `@Action` decorators.

For advanced store patterns (routeMapper, form change detection, caching with batch loading): read `references/store-module-patterns.md`

### Driving the AI panel (agent) from the console

To test the Nimbus AI panel (`src/store/aiPanel.ts`, `AiPanel.vue`) end-to-end without clicking, dispatch its actions on the live store. Two traps:

- **The actions register UNNAMESPACED.** `vuex-module-decorators` puts them in the global action map as `sendUserMessage`, `handleAuthenticatedUserChange`, etc. — NOT `aiPanel/sendUserMessage`. A namespaced dispatch is silently dropped (Vuex warns, resolves a no-op promise, nothing runs). Confirm with `store._actions['sendUserMessage']`.
- `sendUserMessage` runs the whole agent loop and only resolves when the turn ends — **don't await it** if you want to poll progress; fire it and read `store.state.aiPanel.items` / `.running` on a timer.

```js
const store = document.querySelector('#app').__vue_app__.config.globalProperties.$store;
store.commit('setAutoApprove', true);              // skip gated-action approval clicks
await store.dispatch('clearConversationAndStorage'); // full reset (memory + IndexedDB)
store.dispatch('sendUserMessage', 'Find the nuclei in this image.'); // fire, don't await
```

**Send exactly once, from a clean/hydrated state.** Two `sendUserMessage`s in quick succession start two overlapping runs that both push to the module-level `wireMessages`, nesting the tool-result blocks (`content: [[tool_result,…]]`). The next request then fails with Anthropic `400 … messages.N.content.0: Input should be an object`. This is not a create/run bug — it's conversation corruption from concurrent turns. (The UI's `send()` and the `sendUserMessage` guard both check `running`, but a stale in-flight run or leftover persisted conversation can still bite; a hard reload + `clearConversationAndStorage` gives a truly clean slate.) Related: `hydrating` (module var) blocks sends until a reloaded conversation finishes restoring — a dispatch right after reload can no-op; wait a beat. `clearConversation()` (no `force`) no-ops while `running`; use `clearConversationAndStorage`.

Agent tool executors live in `src/agent/executors.ts` (`executeAgentTool(name, input, ctx)`), importable in the Vite dev page for isolated testing: `await import('/src/agent/executors.ts?t=' + Date.now())` (the query-bust avoids a stale module cache). Worker tools save parameters under `tool.values.workerInterfaceValues`; `channelCheckboxes` values are `{channelIndex: true}` maps (a `true` value selects — key-presence alone does not).

### Whole-population reads must handle stub-only mode

Above `stubThreshold` (100K) `annotationStore.annotations` is **empty**. The
population is in `annotationStubs`, and `propertyStore.propertyValues` holds
only the rendered annotations' values for the displayed columns. Code that
reads either one as "the dataset" returns zero there, or worse, a viewport-sized
subset presented as the whole. Nothing errors, and every small-fixture test
passes. This shipped in the AI panel: list/select/color/tag, every analysis
tool and `fit` saw nothing on exactly the datasets where the server summary
reported 700K (AI_PANEL_SPEC.md §4.1).

- Count with `annotationCount`. Get ids with `allAnnotationIds`. Look up one id
  with `getAnnotationOrStubFromId` (O(1); capture the getter once before a
  loop). To iterate, use `annotationStubs.values()` in stub-only mode, or
  `annotationsForIteration`, which copies the map into a new array on every
  access. Stubs have tags/shape/channel/location/color/centroid, but no
  `name` or `coordinates`; narrow with `isHydratedAnnotation`.
- Property values for an arbitrary population: below the threshold, read the
  store. Above it, use the server: aggregates via `fetchAnnotationSummary` or the
  analysis endpoints, or values via `getPropertyValuesForIds(ds, ids, paths)`
  with a **non-empty** `paths` (an empty list means every value).
- Test it by putting the store mock in stub-only mode (`stubOnlyMode: true`,
  `annotations: []`, stubs populated), and confirm the test fails with the fix
  reverted. `executors.test.ts` `describe("stub-only mode")` is the pattern.

### Never assign a big per-annotation map to state without `markRaw`

`annotationStubs`, `hydratedAnnotations`, and `annotationCentroids` hold one
entry per annotation — up to ~700K. Every existing assignment wraps them in
`markRaw(...)`; a new mutation that forgets it hands Vue a raw Map to walk and
proxy entry by entry, and that cost dwarfs whatever the mutation was doing. A
whole-dataset recolor measured **16.9s** with the `markRaw` missing against
~5.5s with it — and the mutation itself was only ~0.5s of that.

Nothing static catches this: `tsc` and lint are happy, and any test with a
handful of fixture annotations is far too small to feel it. The tell is a
measured time that doesn't add up from its parts.

```typescript
// BAD: Vue proxies ~700K entries on assignment
this.annotationStubs = newStubs;

// GOOD: matches the nine other assignments to this map
this.annotationStubs = markRaw(newStubs);
```

`src/store/__tests__/rawStateMaps.test.ts` asserts `isReactive(...) === false`
after every mutation that replaces one of these maps — extend it when you add
another, rather than hand-checking. Verify a new row can fail by deleting only
the `markRaw` call (not the whole mutation — stashing the file reverts it
entirely and the test then fails for the wrong reason).

Note the *array* convention differs: `annotations` is a plain reactive array of
`markRaw`ed items (`setAnnotations` does `annotations.map(markRaw)`), so
`markRaw` goes on the items there, not the array.

### Store Edits Break HMR — Hard-Reload

Editing any `src/store/*.ts` while `pnpm run dev` runs corrupts the store: vuex-module-decorators registers getters at import time with no HMR accept handler, so a hot re-import double-registers → `[vuex] duplicate getter key` cascade and broken state (e.g. annotations stuck at 0). **Hard-reload the page after every store-module edit** before trusting any in-browser behavior. Component `.vue` edits HMR fine — prefer putting temporary instrumentation in `.vue` files.

### Actions That Throw Need `@Action({ rawError: true })`

`vuex-module-decorators` wraps **any** error thrown from a bare `@Action` in a generic `Error("ERR_ACTION_ACCESS_UNDEFINED: Are you trying to access this.someMutation()...")`, discarding the original message — unless the action is declared `@Action({ rawError: true })`. This is a library-wide behavior, not specific to one module.

Most actions in this codebase never throw (they log and return `null`/`false` on failure), so this rarely bites. It matters the moment an action is *designed* to throw so a caller can show the real failure reason (e.g. `addMultiSourceMetadata` throwing a storage-quota message for `MultiSourceConfiguration.vue` to display). Forgetting `rawError: true` silently replaces that message with the cryptic wrapper text — `tsc`/lint/tests all stay green because the action still rejects, just with the wrong message.

```typescript
// BAD: caller's catch block sees "ERR_ACTION_ACCESS_UNDEFINED: ..." instead
// of the real message
@Action
async doThing() {
  throw new Error("Helpful, specific reason");
}

// GOOD
@Action({ rawError: true })
async doThing() {
  throw new Error("Helpful, specific reason");
}
```

When writing a test for an action's thrown-error message, `expect(...).rejects.toThrow("substring")` is not a reliable regression check here: the wrapped error's message embeds the original error's `.stack` (which starts with `"Error: <original message>"`), so a substring match can pass even when `rawError` is missing. Assert the exact `.message` instead. See `src/store/index.test.ts` for the pattern (dispatches the real action instead of mocking `@/store`).

Two traps that let this ship a real bug even after the rule above was documented:

- **An action needs the flag if it merely *propagates*, not only if it contains `throw`.** Awaiting an API call or another action re-throws through your own decorator. `createProperty` has no `throw` and still emitted the blob — so a "grep action bodies for `throw`" audit misses exactly these.
- **Errors get re-wrapped at every `@Action` boundary they cross, across modules.** `createProperty → setProperties → updateConfigurationProperties → syncConfiguration` is four boundaries; one bare `@Action` anywhere on the path mangles the message. Audit every `src/store/*.ts`, not just `index.ts`.

See `references/store-module-patterns.md` for the audit commands, how to tell which callers actually display the message, and the vitest setup details (accessor getters are non-configurable — set `store.state.main.*` directly).

### One Logical Change → One Config Write

`syncConfiguration(key)` PUTs the **whole** key. So a caller that changes three fields by calling a single-field action three times issues three writes of the same key, and a rejection part-way through leaves the shared collection **partially updated while reporting failure** — the same false-reporting `rawError` exists to prevent, one level up. Two instances shipped before this was caught (`set_scale` writing `scales` up to 3×, `update_layer` writing `layers` 2× via `changeLayer` + `saveContrastInConfiguration`).

Validate everything first, then write once:

```typescript
// BAD: validates and persists per field. An invalid tStep leaves pixelSize
// already written — a partial update with no backend failure involved.
if (input.pixelSize) await apply("pixelSize", input.pixelSize);
if (input.tStep) await apply("tStep", input.tStep); // throws on a bad unit

// GOOD: validate all → assign all → one sync
const scales = {};
if (input.pixelSize) scales.pixelSize = validate("pixelSize", input.pixelSize);
if (input.tStep) scales.tStep = validate("tStep", input.tStep);
await main.saveScalesInConfiguration({ scales, throwOnError: true });
```

Interleaved *validation* is the easier half to miss: it fails with no backend involvement at all, so it can't be caught by testing backend rejections. When adding a batch action, keep the singular one — the interactive UI edits one field at a time and legitimately wants it (`ScaleSettings.vue`).

Existing in-codebase idioms for writing once:

- `changeLayer({ ..., sync: false })` per item, then a single `syncConfiguration({ key: "layers", throwOnError: true })` — see `set_layer_visibility`.
- A plural action that assigns all entries then syncs once — `saveScalesInConfiguration`, `setViewContrastOverrides`.
- An optional `delta` merged into an existing action's single write — `saveContrastInConfiguration({ layerId, contrast, delta })`.

Writes to genuinely *different* resources can't be merged (the configuration vs the dataset view are separate endpoints); say so at the call site rather than leaving it looking like an oversight.

### A run must submit what the editor shows

A pipeline step is shown through one path (`displayedSteps`, plus the step
editor's displayed defaults) and run through another (`stepsAsRun`, then
`buildTransientTool`). Any filling the display does must happen on the run
path too: a linked tool saved without values was shown with interface
defaults and run with none (`withInterfaceDefaults`). When the run path gains
an await before a submit (fetching that interface), it needs the same
re-checks as the top of the step: configuration switch and cancel, since
`cancel()` can only cancel a job it already knows. Fetch an interface only
when `getWorkerInterface` is `undefined`; `null` means the worker has none,
and re-asking runs a worker job.

### Live-resolved display: everything derived from the source must follow it

When a view shows values resolved live from a store (a linked pipeline step
showing its tool's current settings), the display is not the only thing
derived from that source. A working copy captured at open time, or a resource
loaded on mount (a worker interface for the step's image), goes stale the
moment the source changes while the view is open. Nothing complains until a
later edit or Save reads the stale copy: removing a step then restored its old
wiring, and a tool's new image left the step with no parameter controls (PR
#1430). Rules:

- Load per-value resources in a `watch` on the value, not only `onMounted` or
  the in-view change handler. Guard an async mount seed against the value
  having changed during its await.
- Before applying an edit to a working copy, carry over the fields the live
  derivation owns, and only those (wiring owns tags and shape, never the
  step's own exclusive-match flag). Carrying the whole object silently
  reverts the edit being applied.

### Watching Getters That Rebuild Their Return Object

`watch(() => someGetter, cb, { deep: true })` on a getter that returns a **new object on every read** fires on every dependency touch — including dependencies the getter reads but that don't change the output (`deep: true` skips the value comparison entirely). This shipped a real bug: a deep watch on `currentFilters` cleared the selection on every Z-scrub because the getter read `z` unconditionally. tsc/lint/reasoning all passed; only the live app caught it.

```typescript
// BAD: fires on every dependency touch
watch(() => annotationListServer.currentFilters, cb, { deep: true });

// GOOD: fires only when content genuinely changes; stringify's traversal
// still registers the nested reactive deps
watch(() => JSON.stringify(annotationListServer.currentFilters), cb);
```

Watch out for stringify cost on large objects.

**This bug recurs even after being fixed once nearby — grep for it.** A second, separate `watch([...9 getters...], cb, { deep: true })` in the same file (`AnnotationList.vue`'s "server-mode reactive refetch" block, a few lines below the `currentFilters` watch above) had the identical bug, confirmed via live instrumentation firing every 30-80ms with **zero** of the 9 tracked values actually changing. Each spurious firing called `setOptions({ page: 1 })`, silently resetting the server-paginated annotation list's page after every click-to-row navigation — while the *rows* stayed correct (the accompanying debounced refetch never settled long enough to fire), so only the page number/footer/Index column were wrong. This looked exactly like "clicking an annotation goes to the wrong spot in the list," and a plausible-looking `VDataTableServer` `update:options` stale-echo race was chased first as the cause (it even reproduced once) before instrumenting the watcher itself proved it was actually firing with no real change. **When you find and fix one instance of this pattern, `grep -n "deep:\s*true" src` for siblings in the same or related files before considering it fixed — a documented fix comment next to one watcher does not protect a copy-pasted watcher elsewhere.**

Not every `{ deep: true }` is this bug — it only applies when the watched source is a **getter function that rebuilds a fresh object/array on each call** (a Vuex/Pinia getter, a `computed`, or a plain function reading store state). A `ref()`/`reactive()` passed **directly** as the watch source (not wrapped in a function) is the correct, safe use of `deep: true` — Vue tracks its stable identity and only fires on genuine in-place mutations. Don't blanket-remove `deep: true` without checking which case you're in.

### An "unknown" value needs ONE spelling and ONE predicate

An uncalibrated dataset's pixel size had three stored spellings — `0` (the intended marker), `null` (JSON's rendering of a `NaN` from `(undefined + undefined) / 2`) and `{1, "m"}` (the configuration default) — and every consumer checked a different subset: the scale bar and blob-metrics worker tested `0`, the line scan tested `1 m`, nothing tested `null`. Each gap was a real bug: a 1.5 km scale bar, a worker crash on `None * 1e-3`, the spatial plugin refusing to adopt a size because "1 m" looked set.

When a value can be "unknown", give it one representation (`unknownPixelSize()` in `src/utils/scales.ts`), one predicate every consumer calls (`isKnownPixelSize`), and normalize legacy spellings at the read boundary (`normalizeScales` in the `scales`/`configurationScales` getters), so workers that receive the value see only real-or-marker. Sweep with a concept search ("where is this value tested for unset?"), not a grep for one spelling. Backend ports of frontend defaults (`server/helpers/default_configuration.py`) are the twin — change both.

### Don't re-key a dataset/configuration watcher on ids

`Viewer.vue`'s `watch([dataset, configuration], fetchAnnotationData)` looks like it should key on ids ("a reload of the same object shouldn't refetch"), but **`refreshDataset()` depends on the object swap**: it re-runs `setSelectedDataset` with the same id, which resets annotation and property state, and only this watcher repopulates it. Keying on ids left the viewer empty after unroll toggles and `addLargeImage` (caught in review of issue #1379). Before narrowing any watcher on `store.dataset`/`store.configuration`, find what resets state on a same-id reload and who repopulates it.

Switching dataset views loads the dataset and configuration **concurrently**, so this watcher sees a mismatched pair (new configuration, old dataset) first. Gate per-dataset fetches on both matching `store.datasetView`, and guard the store action with a sequence token so a superseded fetch can't commit (`fetchAnnotations`, `src/store/__tests__/fetchAnnotationsStale.test.ts`).

### `this.dataset` is the OUTGOING dataset while a view loads

`setDatasetViewId` sets the location (from `?xy=&z=&time=` or the view's
`lastLocation`) before the new dataset arrives, and `this.dataset` still holds
the previous one until `setSelectedDataset` commits. Anything that validates
against `this.dataset` in that window checks the wrong dataset. A setter-side
clamp would cut a deep link that is valid for the incoming dataset, and a save
would write one view's location into another (issue #1388). The location
setters therefore read `locationDataset` (null while `sync.datasetLoading`), and
the location is clamped where the dataset lands (`clampLocationToDatasetImpl`
in `setSelectedDataset` and at the end of `setDatasetViewId`). Per-feature
guards in consumers are not needed. Each clamp site must also schedule
`updateLastLocationInDatasetView`, or the view reopens at the old saved
location. The first cut missed this in `setSelectedDataset`, which
large-image refreshes reach without going through a view load. Do not clamp an
UNROLLED axis: `parseTiles` collapses it to one entry, so the clamp sends a
grid-cell click (which sets the frame, then clears the flag) to frame 0. The
roll-up reload clamps it against the real dimensions. And "unrolled" must mean
the shape `this.dataset` was FETCHED with (`datasetUnroll`), not the live
`unrollZ` flag: a refresh started before a toggle can land after it.
The pending save is the reverse problem: it is only accepted while
`this.dataset` matches `datasetView.datasetId`, so whatever replaces EITHER one
must flush it first. `setDatasetViewId` flushes before replacing the view, and
`setSelectedDataset` before replacing the dataset (`Dataset.vue` switches
datasets with the old view still loaded). Out-of-range indices also travel in
URLs: the breadcrumb view switcher keeps the current query when it moves to
another dataset. See `codebaseDocumentation/DATASET_LOCATION.md` and its
regression checklist.

### A long-running action must pin the configuration it started on

`main.configuration`, `main.tools` and `properties.properties` are the LOADED
configuration's, and opening a dataset of another configuration replaces all
of them while an action that spans worker jobs (a pipeline run, a batch) keeps
going. Each later read then sees the other configuration. Lookups fail, the
fallback creates properties there, and ids are recorded there, while the jobs
still target the original dataset. Guarding one lookup (resolving it once at
the start, or the reload guard in `loadMissingLinkedProperties`) leaves every
other read exposed. Capture `main.configuration.id` before the first await,
then check it before each unit of work, including any reload or cache write
that reads "the loaded configuration" itself, and stop if it changed
(`runPipeline`/`runPipelineBatch`, `CONFIGURATION_CHANGED_DURING_RUN`). Write
anything the action already produced to the captured configuration object, not
through `syncConfiguration`, which writes whichever configuration is loaded.
Never write a store list back after a switch either: `setConfiguration` starts
the new configuration's `fetchProperties` without awaiting it, so for a while
`properties.properties` is still the previous configuration's list, and
`setProperties`/`deleteProperty` would save it as the new one's `propertyIds`
(every reader must check `propertiesConfigurationId` too, not only writers:
the runner and the pipeline editor read the list through `propertiesOf` /
`configurationProperties`; `setProperties` refuses a list whose `propertiesConfigurationId`
is not the loaded configuration, including `null`: a list no fetch has loaded
is no configuration's, and treating "unknown" as safe let a stale list through
after a failed first fetch; and `createProperty` registers nothing if a
switch lands during its request). Keep a run-local record of what the action produced and merge it in
just before the final write: a switch away and back reloads the configuration
from the server, without anything merged into the old object.

### A failed optimistic write restores what the server holds, not its snapshot

An optimistic write (set the value, await the save, restore `previous` on
failure) breaks once writes can overlap. A later write may sit on top of the
failed one, an earlier write it built on may have failed too, or a fetch may
have replaced the value during the await. Restoring the snapshot then puts a
value back that the server never held, or overwrites a newer one. After a
configuration switch it is worse: the old configuration's property list went
back in under the new one's ownership, and the next save wrote it into the new
configuration. Checking "is the value still the one I wrote?" is not enough
either: a nested rollback (from a copying mutation, or a fetch) gives it a new
identity, so the outer rollback is skipped and the list and its ids disagree.

What works here (`writeConfigurationKey` in `index.ts`): per configuration key,
count pending writes and record the last value the server confirmed. Restore
nothing while any write of the key is pending. When the last one settles, if
any of them failed, set the key to the confirmed value. Don't restore at the
latest write's failure: a write can fail before it reaches the API's per-key
queue (a session that expired), while an earlier one is still in flight and
then succeeds. Restore onto the loaded configuration object when it has the
same id, since a switch away and back loads a new object. Rebuild derived state
from the restored value at the same point rather than restoring it separately:
`setProperties` rebuilds the list from the restored `propertyIds`, keeping the
objects that in-flight saves started from so a property an earlier failed save
removed can come back. Key that bookkeeping exactly as the write it shadows
(per configuration here): process-wide counters let a save pending on one
configuration hold back another configuration's rebuild, then clear its
failure flag. Tests: *"restores what the server holds when
overlapping saves both fail (earlier first)"*, *"(out of order)"*, *"ends on an
earlier save's value when a later save fails before it is sent"*.

Every change the server already holds must reach that bookkeeping, not just
the client's own writes. A value set behind its back (a server job registered
a property, and the client appends the id in memory) is missing from the
confirmed value, so a pending write that fails restores it away, and the next
save deletes it on the server. Route such changes through a helper that adds
them to the confirmed value while writes are pending
(`adoptServerConfirmedPropertyId`). Adopt it as soon as the server made
the change, not when a later job reports done: the gene-panel and
neighborhood requests register their property when the request is made, so
adopting at job end left the whole job's runtime for a property save to
unregister it. Don't add a client-side "save it again" repair for the
remaining window (a save sent while that request was in flight); it bypassed
the list-rebuild bookkeeping and could resurrect deletions, and only a
server-side merge of propertyIds writes closes it. And check every path that
builds the next write: `setProperties` builds ids from the loaded list, not
the configuration, so an adopted id no fetch has loaded yet must be carried
over. Tests: *"keeps a property adopted during a pending save when that save
fails"*, *"carries over an adopted property no fetch has loaded yet when
saving"*, *"polls a scheduled job until it succeeds, adopting its property at
once"*.

**Don't fix the estimate's ordering problem by queueing writes; read back.**
A rollback that replays successful patches in response order can be wrong
when overlapping saves were applied by the server in another order, or a
failed bulk save was partly written. PR #1433 first sent each annotation's
saves one at a time. Every review round then found something new the queue
changed: a color-by-property job overtook a held edit, a held edit crossed a
session switch, undo didn't wait for it, and its cancellation looked like a
possible write. A held write is a mechanism every other write path must
coordinate with. Instead, after restoring the estimate, read the affected
records back (`reconcileRestoredAnnotations`, via `hydrateAnnotations`), and
apply each server copy only if the store still holds the restored object, in
the same session and dataset. A read can't overwrite the server, so
overlapping writes can't corrupt anything; the worst case is a briefly stale
display.

### Per-resource component state under a reused route: key it by id

Vue Router reuses a route's component when only a param changes (`/project/A`
→ `/project/B`), so any local state in it, or in a child, stays alive across
the switch. That state includes error messages, progress, job subscriptions
and open dialogs, and late responses for A land in it too. On PR #1414,
`ZenodoPublish`'s refusal message for project A showed on project B. Don't
reset the refs one by one in a `watch(() => props.project.id)`: that list is
hand-maintained and misses the next ref someone adds. Key the component by
the resource id in the parent (`<zenodo-publish :key="project.id" ...>`), so
each resource gets a fresh instance. A late `emit` from the old instance is
dropped (Vue's `emit` returns early once `isUnmounted`). Test it by switching
the resource under a mounted parent and asserting a new child `vm`
(`ProjectInfo.test.ts` *"gives each project its own ZenodoPublish
instance"*).

A related trap: work that "resumes" a server-side operation, such as
re-subscribing to a running job, must not run only in `onMounted`. Run it
whenever the resource *reports* the state (`watch(status, …, { immediate:
true })`), guard it to once per job, and treat "reports running but no job
exists" as a stale copy to re-read. The store does not refetch cached
resources on navigation.

### Every `throttle`/`debounce` needs a `cancel()` in `onBeforeUnmount`

A trailing call that fires after teardown runs against a dead view — in
`AnnotationViewer.vue` that means `layer.annotations()` / `layer.draw()` on a
torn-down GeoJS map, or a store write from a component that no longer exists.
The teardown block already cancels them; the failure mode is *forgetting to add
the new one*, which nothing catches because the component unmounts fine and the
trailing call usually lands harmlessly.

Guard it with a test that records the throttles **at construction** — the
version that listed them by name stayed green while two uncancelled ones
shipped, and a version that scanned `wrapper.vm` only moved the hand-maintained
list to `defineExpose` (an unexposed throttle stays invisible there):

```ts
// top of the test file — delegates to real lodash, so timing is unchanged
const createdThrottles = vi.hoisted(() => [] as any[]);
vi.mock("lodash", async (importOriginal) => {
  const actual = await importOriginal<typeof import("lodash")>();
  const record = (w: any) => { createdThrottles.push(w); return w; };
  return { ...actual,
    throttle: (...a: any[]) => record((actual.throttle as any)(...a)),
    debounce: (...a: any[]) => record((actual.debounce as any)(...a)) };
});

// in the test
createdThrottles.length = 0;
wrapper = mountComponent();
expect(createdThrottles.length).toBeGreaterThanOrEqual(7);  // recording can break too
const named = createdThrottles.map((fn, i) => [
  Object.keys(vm).find((k) => vm[k] === fn) ?? `unexposed#${i}`,
  vi.spyOn(fn, "cancel"),
] as const);
wrapper.unmount();
expect(named.filter(([, s]) => !s.mock.calls.length).map(([n]) => n)).toEqual([]);
```

`<script setup>` bodies run per instance, so setup-scope throttles are created
during mount and land in the recording. One residual gap: a wrapper built lazily
inside a handler isn't recorded until that handler runs.

## Vuetify 4 Patterns

### CSS Cascade Layers

Vuetify 4 wraps all styles in CSS `@layer` declarations. Custom styles (outside layers) automatically win over Vuetify's defaults — no specificity wars.

**Key implications:**
- Most `!important` overrides for Vuetify are unnecessary — remove them
- `:deep()` selectors targeting Vuetify internals "just work" without specificity tricks
- **Exception:** `@girder/components` bundles Vuetify 3 CSS (un-layered), so `!important` IS still needed when overriding Girder component styles

### Light/Dark Mode Theming

```typescript
// In <script setup>
import { useTheme } from "vuetify";
const theme = useTheme();
const isDark = computed(() => theme.current.value.dark);
```

```vue
<!-- In templates -->
<div :class="{
  'v-theme--light': !$vuetify.theme.current.dark,
  'v-theme--dark': $vuetify.theme.current.dark
}">
```

Theme config in `src/plugins/vuetify.ts`:
```typescript
defaultTheme: Persister.get("theme", "dark") === "dark" ? "dark" : "light",
```

Vuetify 4 changed the default theme from `"light"` to `"system"`. Our config sets it explicitly.

### Theme-Aware Styling

**Option 1: Vuetify Components** (preferred) — auto-inherit theme.

**Option 2: Theme classes in SCSS**
```scss
.v-theme--dark & {
  background: rgba(255, 255, 255, 0.05);
}
.v-theme--light & {
  background: rgba(0, 0, 0, 0.05);
}
```

**Option 3: CSS Variables**
```scss
.my-element {
  color: rgb(var(--v-theme-primary));
  background: rgb(var(--v-theme-surface));
}
```

### The viewer's app bar is already full — measure before widening a control

On the dataset view the app bar holds about 20 controls and already overflows
by ~50px at 1024px wide. Anything wider than an icon pushes the right-hand
buttons (help, account, Nimbus AI) off screen with no scrollbar and no error;
a 264px search-field trigger hid all three anywhere from 960px to ~1300px.
Before widening an app-bar control, measure on the **viewer** route (not the
home page, which has half the controls) at 1024 and 1280px:

```js
const ai = document.querySelector('[aria-label="Nimbus AI panel"]');
[innerWidth, Math.round(ai.getBoundingClientRect().right)]  // right must be <= innerWidth
```

Collapse to an icon below `lg` (1280px) rather than `md`.

### Palette commands registered in a right-hand palette are global unless gated

`useCommand` registers for the component's lifetime, and the right-hand
FloatingPalettes (Settings, Object Browser, Snapshots) keep their content
mounted on **every** route via `v-show`. So a command registered in, say,
`ViewerSettings.vue` shows on the dataset list too. Gate it with
`useInViewer()` from `src/commands/context.ts`, and set each command's
`enabled` to match its control's `:disabled`. The left palettes (Navigator,
Layers, Tools) and `ImageViewer.vue` mount only in the viewer.

### A state-flipping palette command names only what it will do

A command whose title flips with state ("Hide minimap" / "Show minimap") must
never match a query asking for the state it already has, or Enter does the
opposite of what was typed. Seven Codex rounds on PR #1429 each found one
more way in:

- synonyms that equate opposites (show = hide);
- loose matching: substring ("lock" in "Unlock", "roll" in "Unroll") or
  subsequence ("open" in "Close…"); the scorer now matches the words in
  `src/commands/stateWords.ts` only as whole title words or keywords;
- keywords naming both directions (`["dark", "light"]`, `["add", "remove"]`);
  `oppositeKeywords.test.ts` scans every array literal for these;
- a description stating the current state ("Visible" made "visible dapi"
  hide the layer);
- a turn-off title that shares a word with the state it ends
  ("Draw every object, ignoring **filters**" matched "filter objects").

The rule: title, keywords, aliases and description describe only the
result of running it, and a turn-off title shares no word with the on state
except the neutral subject ("minimap", "scale bar"). Use `toggleCommands`
with `turnOnKeywords` / `turnOffKeywords`, and test both states with the
query a user would type for each.

### Select/Combobox Slot Items (No `.raw` Wrapper)

Vuetify 4 removed the `.raw` wrapper from select slot items. Items are passed directly. This applies to ALL slot types: `#item`, `#chip`, and `#selection`.

**Object items** — access properties directly:
```vue
<!-- Vuetify 4: access properties directly on object items -->
<v-select :items="items" item-title="displayName">
  <template v-slot:item="{ item, props: itemProps }">
    <v-list-item v-bind="itemProps">
      <template #title>{{ item.displayName }}</template>
      <template #subtitle>{{ item.description }}</template>
    </v-list-item>
  </template>
</v-select>
```

**String items** — `item` IS the string, not a wrapped object. Do NOT use `item.title`:
```vue
<!-- BAD: item.title is undefined on a string — renders empty chips -->
<v-combobox :items="tagList" chips multiple>
  <template v-slot:chip="{ item, props: chipProps }">
    <v-chip v-bind="chipProps">{{ item.title }}</v-chip>  <!-- WRONG -->
  </template>
</v-combobox>

<!-- GOOD: use item directly for string items -->
<v-combobox :items="tagList" chips multiple>
  <template v-slot:chip="{ item, props: chipProps }">
    <v-chip v-bind="chipProps">{{ item }}</v-chip>  <!-- CORRECT -->
  </template>
</v-combobox>
```

**The `#item` slot name did NOT change** (contrary to some sources claiming rename to `#internalItem`).

### `v-select` shows `[object Object]` — set `item-title` to match the item key

Vuetify's `VSelect` defaults to `item-title="title"` and `item-value="value"`. If your items are objects keyed differently, the selected display renders the raw object as **`[object Object]`** (selection still works because `item-value` happens to match).

This bit the tool-creation form: every `select` interface element in `public/config/templates.json` uses `{ text, value }` items, but the generic `VSelect` in `ToolConfigurationItem.vue` set no `item-title`, so **every non-submenu select in the Add-tool dialog** rendered `[object Object]`. Fix: pass `item-title="text"` (the app's convention) for select elements.

```vue
<!-- BAD: items are { text, value } but VSelect looks for `.title` -->
<v-select :items="[{ text: 'Point prompts', value: 'point' }]" />  <!-- [object Object] -->

<!-- GOOD -->
<v-select :items="items" item-title="text" item-value="value" />
```

When you add a non-submenu `select` to a tool template, or render options in a `v-select`, always confirm `item-title` matches the item objects' label key.

### Don't `v-model` a computed that reads a non-reactive pipeline node

`ComputeNode.output` / `ManualInputNode.output` (in `src/pipelines/computePipeline.ts`) is a **plain field, not a Vue ref** (pipeline nodes are `markRaw`'d for perf). A `computed` whose getter reads `node.output` registers **no reactive dependency**, so it never re-evaluates when the node's value changes. Bind a control's `v-model` to such a computed and the control **snaps back to its stale value** on the next render — e.g. a dropdown that "looks selected" but always displays the old option, or a slider that jumps back.

```ts
// BAD: getter reads node.output (non-reactive) → v-model display reverts
const promptMode = computed({
  get: () => promptModeNode.value?.output ?? "point",
  set: (v) => promptModeNode.value?.setValue(v),
});

// GOOD: a reactive ref is the UI source of truth; push into the node on change,
// and seed the ref from config/state on mount + when the tool state changes.
const promptMode = ref<TPromptMode>("point");
watch(promptMode, (v) => segState.value?.nodes.input.promptMode.setValue(v));
```

Reactive **state** fields (from `reactive(...)` in the tool-state factory) are fine to read in computeds — only raw `markRaw`'d node `.output` reads are the trap.

### VRow Density — and `dense` everywhere else

On `<v-row>`, the boolean `dense` prop is deprecated. Use `density="comfortable"`:
```vue
<v-row density="comfortable" align="center">
```

The substitution is **visually identical** — VRow maps
`density === 'comfortable' || dense` to the same `v-row--density-comfortable`
class, so `dense` still works and the only symptom is
`[Vuetify UPGRADE] 'dense' is deprecated` in the console. Don't trust
Vuetify's own JSDoc here: `makeVRowProps` says `@deprecated use
density="compact"` while the runtime warning and the class mapping both say
`comfortable`. `comfortable` is the behavior-preserving one.

**The warning is one-shot per mounted row, not per render.** `deprecate()` is
called from `VRow.setup()`, so re-rendering or updating an existing row never
repeats it — which is exactly why you cannot "re-trigger" it by toggling the UI
that contains it, and why it is usually already gone by the time you attach a
console listener. See the `in-browser-testing` skill for the capture order this
forces.

**`VRow` is the only component that warns.** `deprecate('dense', …)` is called
in exactly one place in Vuetify 4 (`VRow.setup()`). So a `dense` on anything
else is *silent* — and dead: `VCard`, `VListSubheader`, and our own
`tag-picker` / `docker-image-select` / `property-worker-menu` declare no `dense`
prop, so Vue passes it through to the root element as a stray DOM attribute that
styles nothing.

**Delete those; don't convert them.** `VListSubheader` has no `density` prop
either, so a swap is just a different dead attribute. `VCard` *does* have one,
so a swap there newly tightens title/subtitle/text padding — an unrequested
visual change. This is the trap in a scripted sweep: a regex that rewrites
`dense` → `density="comfortable"` on every tag it matches is wrong on most of
them, and a regex restricted to `<v-[a-z-]+` misses the custom-component
instances entirely (they need the opposite treatment, so they can't just be
ignored).

`src/vuetifyDeprecations.test.ts` scans every `.vue` template for a boolean
`dense` on any tag and fails the build, so this can't silently come back.
Extend that test rather than hand-grepping when auditing a new Vuetify
deprecation.

### Icon names: check `@mdi/font` 5.9.55, not the MDI website

`@mdi/font` here is pinned at **5.9.55**, several major versions behind what
mdi.dev documents. A name that doesn't exist in the installed font fails
**silently and invisibly**: Vuetify sets the class, no `::before` rule matches,
and the icon renders as blank space. `tsc`, lint and every component test stay
green — the only symptom is a gap a human notices in a screenshot, which is
exactly how `mdi-gradient-horizontal` shipped on a menu item. The sweep that
followed found two more (`mdi-sitemap-outline`, added after 5.x, in two places;
`mdi-save`, renamed to `mdi-content-save` in 5.x).

Never write an icon name from memory or from current MDI docs — grep the
installed font:

```bash
grep -c '^\.mdi-sitemap-outline::before' node_modules/@mdi/font/css/materialdesignicons.css   # 0 → blank icon
```

`src/__tests__/mdiIconNames.test.ts` enforces this across all of `src/`, so a
bad name now fails the suite instead of shipping. Its one exclusion is itself
(it quotes non-existent names in its own prose). In the browser, the direct
evidence is `getComputedStyle(el, "::before").content` — a codepoint means the
glyph resolved, `none`/`normal` means the class matched no rule.

Common 5.9.55 gotchas: no `-outline` variant for many icons; `save` →
`content-save`; `gradient` has no `-horizontal`/`-vertical` suffix.

### v-menu / v-dialog Initial State

Vuetify 4's `v-menu` respects the initial `v-model` value immediately on mount. Vuetify 3 deferred it. If you set `v-model` to `true` before mount, the menu WILL open. Guard with conditions:
```typescript
// Only auto-open when appropriate
menuOpen.value = route.name === "root" && !store.isLoggedIn;
```

### Global Defaults

Configured in `src/plugins/vuetify.ts`. Vuetify 4's default density is tighter than V3. We set `density: "comfortable"` for list/checkbox components to maintain V3 spacing (needed for `@girder/components` compatibility):
```typescript
defaults: {
  VList: { density: "comfortable" },
  VListItem: { density: "comfortable" },
  VCheckbox: { color: "primary", density: "comfortable" },
  VCheckboxBtn: { density: "comfortable" },
}
```

**An explicit prop beats a `v-defaults-provider` default.** A wrapper that forwards `:disabled="disabled"` with a `false` default passes `false` explicitly, which overrides a surrounding `<v-defaults-provider :defaults="{ global: { disabled: true } }">`. A locked pipeline step's Tags field rendered editable-looking this way while every other field dimmed. Forward `:disabled="disabled || undefined"` so an unset prop falls through to the provider. Test it by mounting under `VDefaultsProvider` and asserting the `v-input--disabled` class: `findComponent().props("disabled")` reads the raw prop and returns `null` either way.

## @girder/components Compatibility

`@girder/components@4.0.0` depends on `vuetify: ^3.10.1` — no Vuetify 4-compatible version exists yet. Key issues:

- Girder bundles ~6.9MB of Vuetify 3 CSS (un-layered), which competes with Vuetify 4 layered CSS
- `!important` is still needed when overriding Girder component styles
- `CustomFileManager.vue` has targeted CSS overrides for the file manager table layout
- See `codebaseDocumentation/VUETIFY4_MIGRATION.md` for full details

### GirderFileManager Prop Names

GirderFileManager (from `@girder/components`) uses **Vuetify 3 prop naming**, not Vuetify 4. Key props:

- `itemsPerPage` (kebab: `items-per-page`) — sets default page size. **NOT** `initialItemsPerPage`.
- `itemsPerPageOptions` (kebab: `items-per-page-options`) — array of page size choices.

These props are defined in `node_modules/@girder/components/src/components/FileManager.vue`. If you use a wrong prop name, it silently falls through as an unrecognized attribute and the component uses its internal default (10).

### Overriding Girder DataTable Row Styles

Girder's `DataTable.vue` renders a `v-data-table-server` with `<tr>` > `<td>` rows. The DOM structure is:

```html
<tr class="v-data-table__tr">
  <td class="...">checkbox</td>
  <td>icon + #row slot content</td>
  <td class="text-right">file size</td>
</tr>
```

To override row styles from a parent component:
- Use **unscoped** `<style>` blocks (scoped styles can't reach into Girder internals)
- Target `table tr` and `table tr td` — these cover both raw elements and Vuetify class selectors (`.v-data-table__tr`, `.v-data-table__td`) since they're the same DOM nodes. No need to duplicate selectors for both.
- `!important` is required because Girder's bundled Vuetify 3 CSS is un-layered
- Scope overrides with a parent wrapper class (e.g., `.browse-expanded .custom-file-manager-wrapper`) to avoid leaking globally

### Persisting User Preferences with Persister

For UI preferences that should survive page reloads (expand/collapse states, view modes, etc.), use `Persister` from `@/store/Persister`:

```typescript
import Persister from "@/store/Persister";

// Read with default
const expanded = ref(Persister.get("myPreferenceKey", false));

// Write on change
function toggle() {
  expanded.value = !expanded.value;
  Persister.set("myPreferenceKey", expanded.value);
}
```

Persister wraps `localStorage` with JSON serialization. It's already used for theme, tour status, and browse mode preferences.

## Dialogs

```vue
<v-dialog v-model="dialogOpen" max-width="600px">
  <v-card>
    <v-card-title>Title</v-card-title>
    <v-card-text>Content</v-card-text>
    <v-card-actions>
      <v-spacer />
      <v-btn @click="dialogOpen = false">Close</v-btn>
    </v-card-actions>
  </v-card>
</v-dialog>
```

### Wide dialogs: `class="wide-dialog"` when using percentage or `vw` widths

Vuetify ships `.v-dialog { width: 50% }` on the outer overlay wrapper. The `width` / `max-width` props on `<v-dialog>` only size the inner `.v-overlay__content` — so `width="60%"` actually renders at 60% of that 50% box (= 30% of viewport), and `width="70vw"` is silently clamped to 50vw.

Whenever a dialog needs a percentage or `vw` width, opt in with `class="wide-dialog"`. The shared rule lives in `src/style.scss` (look for `.wide-dialog.v-dialog { width: auto }`) and lets the prop size against the viewport directly.

```vue
<!-- Bad: width prop silently shrinks to 30% of viewport -->
<v-dialog v-model="open" width="60%">…</v-dialog>

<!-- Good: class lets the 60% prop apply to the viewport -->
<v-dialog v-model="open" width="60%" class="wide-dialog">…</v-dialog>
```

When **not** to add the class:
- `max-width` in pixels (e.g. `max-width="500px"`) — works correctly without the class on any reasonable screen.
- `max-width="33vw"` and similar — `vw` max-widths smaller than 50vw fit inside the default wrapper, so the class is unnecessary.
- Dialogs with no width prop — they rely on the implicit 50% wrapper as a sane default; adding the class would let them shrink to content width, which is usually not what's wanted for confirmation-style dialogs.

If you see a dialog with a `width="N%"` or `width="Nvw"` prop and no `wide-dialog` class, it's almost certainly rendering narrower than intended — add the class.

### Click-outside close runs *after* the outside click — and closes on drags

Vuetify's `v-click-outside` (used by every non-`persistent` `v-dialog` / `v-menu`) runs its close inside a `setTimeout`, i.e. **after** the outside click has bubbled through its own handlers. When the dialog's `@update:model-value(false)` handler clears *shared* state, it can undo what that same click just did: in the worker-tool dialog (`Toolset.vue`), clicking another worker tool selected it, and then the deferred close ran `setSelectedToolId(null)` and deselected it again. It also fires for a drag whose mousedown and mouseup both land outside, so on a scrim-less dialog over the image, **panning the map closes the dialog**.

Neither case can be told apart from inside `update:model-value`. `click:outside` is emitted synchronously just before it, with the click event, so veto there. Snapshot `{clientX, clientY, relevant state}` in a capture-phase `pointerdown` listener (registered only while the dialog is open, removed in the watcher's `onCleanup`), then in `@click:outside` set a one-shot veto when the state changed or the pointer moved more than a few px. Consume the flag in `update:model-value`. Escape emits no `click:outside`, so it still closes. See `onWorkerDialogClickOutside` in `Toolset.vue` and its tests in `Toolset.test.ts`.

A nested overlay (a `v-select` menu inside the dialog) is the top of the overlay stack, so the first outside click closes only that menu and the second closes the dialog. That is expected, not a bug. Tooltips (`_disableGlobalStack`) don't take part in the stack.

### Controlling a dialog from outside: two traps

Both shipped in the command palette's first cut, when the Data I/O dialogs
moved out of their `v-menu` so the palette could open them:

- **A dialog created already open never fires its open watcher.** The CSV
  preview and the index-conversion labels are built in non-immediate
  `watch(dialog, ...)` callbacks. Mounting the dialog (`v-if`) and setting its
  `v-model:open` in the same tick creates it with `dialog === true`, so the
  watcher never sees false → true and the first open shows blank state. Mount
  it closed, `await nextTick()`, then open it (`DataIOMenu.vue`
  `openDataDialog`).
- **An empty slot renders the slot's fallback.** Passing `<template
  #activator />` to silence a component's default activator button does
  nothing: Vue treats slot content that renders only comments as absent and
  shows the fallback, so the dialog's own "Export CSV" button appeared in the
  app bar. A dialog that is always opened from outside should have no
  activator at all; delete it rather than overriding it with nothing.

### Reused dialogs that write to the server: two lifetimes

A dialog instance is reused across close/reopen and across a changing
`dataset` prop (and several instances can exist — one per list row). Its
async handlers mix two things with **different lifetimes**, and every race
found in `ShareDataset.vue` (PR #1403 took ~10 Codex rounds) was one treated
as the other:

1. **What the dialog shows** — loaded lists, notices/errors, typed inputs,
   pending confirmations. Scoped to one *session* (open period × dataset).
   Capture a session claim before each `await` and write back only while it
   holds; bump the session on **every** reset (close *and* dataset switch —
   the dataset id alone recurs, A → B → A). Keep every such field in one
   reset function used by both paths. Loads are latest-wins counters.
2. **Server operations** (create/change/remove/publish/revoke) — they keep
   running after the dialog closes or unmounts. Their in-progress guards
   must live in a **module-level registry keyed by what they change**
   (`utils/pendingMutations.ts`, `utils/pendingPublishes.ts`), shared by all
   instances, with UI flags computed from it — never component refs a reset
   clears. When one settles, every open dialog showing that resource
   **refreshes from the server** (quietly: keep selection and notices), or a
   dialog that loaded mid-change keeps stale rows.

Test it with a never-resolving-until-told promise, `resetState()`/`setProps`
in between, then resolve. Module-level registries leak between tests via
still-mounted wrappers: use `enableAutoUnmount(afterEach)`, or a "refreshes"
assertion can pass because a previous test's open dialog did the refresh.

## API Calls

Use the API classes from store — never put `girderRest.get(...)` in components:

```typescript
import store from "@/store";
const result = await store.api.someMethod();
```

### Your own rights come from the server's effective level, never an ACL row

Don't decide what the current user may do by finding `store.girderUser._id` in an access list's `users`. That list holds only **direct** entries. Someone with access through a Girder group, or a site admin, has no row there, so the UI hides controls the server would allow. Codex caught this on the Share dialog (PR #1406). The access endpoints return `currentUserLevel` (Girder `getAccessLevel`) for this. For a Girder document already in hand, its `_accessLevel` is the same value. Two follow-ons:
- **It's derived state.** After changing the caller's own entry, re-read it from the server: a group may still grant access. Removing your last access turns the access list itself into a 403, so fail closed (`-1`) instead of keeping the old level.
- **Re-read narrowly.** Reloading the whole dialog after a self-change reset the user's collection selection.

### Replacing `girderRest` must reach the API classes too

Every API class (`api`, `annotationsAPI`, `spatialAPI`, …) talks to Girder through
`girderRestProxy`, not through `state.main.girderRest` directly. Two credentials are
therefore in play, and a change to one is not a change to the other. The proxy must
resolve the **live** module state (`liveGirderRest`): the object a class-field
initializer sees as `this` is the construction-time instance, which a mutation never
updates. Before the fix, `openShareLink` committed the link's own client to state while
every API call kept the boot client — so a share view ran as the owner's stored login
(full write access) or, for a recipient with no login, anonymously (private dataset
fails). Its tests asserted `main.girderRest.token` and passed; the regression test now
also asserts `main.api.client.token` (`index.test.ts`, "commits only the latest
validated link"). When you swap or re-token the client, assert on an API class's
client, and check live with `store.state.main.api.client.get('user/me')` — not with
`girderRest`.

### An optional plugin's missing route is a network error, not a 404

A Girder route that was never registered (its plugin is not installed) gets
cherrypy's bare 404 **without CORS headers**, and its preflight gets 405. From the
dev server or any cross-origin frontend the browser blocks it, so axios reports
`Network Error` with no `error.response`. Code that maps 404 to "nothing here" therefore
reads "plugin missing" as "could not ask". This put a Transcripts error button on every
dataset when the server lacked `upenncontrast_spatial`. Don't probe an optional
plugin's routes to discover it. Ask `GET system/loaded_plugins` (public, cached per
`apiRoot`; see `SpatialAPI.isPluginLoaded`) and skip the calls when it is absent. To
test, run a second Girder from the same image with the plugin `pip uninstall`ed on another
port, and point a dev server at it with `VITE_GIRDER_URL` plus the persisted `girderUrl`
localStorage key, which overrides the env var.

## Palette content stays mounted: gate server work on visibility

`FloatingPalette` hides a closed palette with `display: none`; its content is
mounted at app boot and stays mounted. So `onMounted` runs for every user, and
watchers keep firing while nobody can see the panel. Anything that costs
server work must take a visibility prop and defer: the Object Browser's
server-backed list used to refetch on every filter or gate change with its
palette closed — with an analysis gate that is a whole-dataset gate
resolution (8 s on 709K objects) competing with the gate the user just drew.
Pattern: `App.vue` passes the palette's open state (`:visible="annotationPanel"`),
the container forwards `visible && activeTab === '…'`, and the component
records a deferred request while hidden and runs it once when sho

[…] pełny plik w paczce .zip
Pliki w paczce (3)
  • SKILL.md 80 KB
  • references/batch-processing-patterns.md 4 KB
  • references/store-module-patterns.md 12 KB

Wersje

RepozytoriumWynikLicencja
Ta strona · arjunrajlaboratory/nimbusimage89Apache-2.0
arjunrajlaboratory/nimbusimage89Apache-2.0

Identyczna treść występuje jeszcze w 1 innych folderach na GitHubie. Tu pokazujemy jedną, najlepiej ocenioną kopię.

Migawka bazy z 13.11.2026 · wersja paczki 18f6ad117125 (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100vuetify-skilld
    Pomaga pisać i naprawiać kod z Vuetify 4 w zakresie konfiguracji, motywów, ikon, lokalizacji i migracji z wersji 3.
  • 100vuetify
    Pomaga pracować z Vuetify dla Vue 3: komponenty Material Design, tabele danych, responsywne układy i motywy, przy szybkim budowaniu dashboardów firmowych i paneli administracyjnych.
  • 100vue2-to-vue3-migration
    Migruje projekty Vue 2 i Nuxt 2 do Vue 3 i nowszych wersji: Options API, Vuex, Vue Router i TSX.
  • 100frontend-module-standards
    Egzekwuje standardy architektury modułów frontendu React i TypeScript tego repozytorium przy tworzeniu i przeglądzie kodu w src: moduły funkcji, komponenty, hooki, konteksty, API, stan i testy.
  • 100frontend-module-standards
    Pilnuje standardów architektury modułów React i TypeScript w katalogu src: funkcje, komponenty, hooki, konteksty i testy.
  • 95vuetify0
    Buduje interfejsy Vue 3 z bezgłowymi komponentami @vuetify/v0: wybór stanu, walidację formularzy i wzorce WAI-ARIA.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.