# Personalization & Style Studio

Runtime preferences for color mode, **brand roles** (primary / secondary / accent), **paper & ink** (per mode), motion, and background live behind the **Preferences** module (`core/web/shared/preferences/`). Import from `#shared/preferences`: its export list is explicit and pinned by `core/web/tests/preferences-interface.spec.ts`. `#shared/personalization` is a deprecated re-export kept for one release. The test-only paint override `setPaintForTests` lives in `shared/preferences/testing.ts` and is not in the barrel. Vue adapters (`usePersonalization`, Style Studio draft) call Preferences only; Preferences paints via **`Theme.apply`** / **`Theme.remove`**.

Domain glossary: [CONCEPTS.md](../../../CONCEPTS.md#theme-and-preferences) (**Preferences**, **Committed vs draft**, **Painted theme**, **Style setup**, …). Theme paint surface: [packages/theme.md](../../packages/theme.md). Design: [theme-preferences-deepen design](../../superpowers/specs/2026-09-24-theme-preferences-deepen-design.md) · [implementation plan](../../superpowers/plans/2026-09-24-theme-preferences-deepen.md). Storage: [preferences storage design](../../superpowers/specs/2026-09-30-preferences-storage-admin-session-design.md) · [plan (Part A)](../../superpowers/plans/2026-09-30-preferences-storage-admin-session.md).

| Surface                                                    | Role                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Personalize** (`AppPersonalize`)                         | Color mode, Motion (System · Playful · Reduced, the same setting as Style Studio and the header's _Pause animation_, announced "Applied: Reduced motion"), depth-field background via shared `AppBackgroundPicker` (camera consent, custom hex), named setups, theme studio presets (palette collections and light/dark colors), reset, **Open studio** → `/styles`. **Done** closes on a macrotask; while open, `html[data-personalize-open]` disables phone Menu hit-testing so the closing click cannot toggle the dropdown. |
| **Style Studio** (`/styles`, `AppStyleStudio`)             | Role-first editor (Primary · Secondary · Accent) with live WCAG readout and one-click fixes, paper & ink for the current mode, motion, background, sticky draft bar (Discard changes · Save as setup · Apply), setups with Undo                                                                                                                                                                                                                                                                                                 |
| **Component parity** (`/styles/parity`, `AppStylesParity`) | Native / Foundation / PrimeVue kitchen sink for engineers (was the lower half of `/styles`; `/styles/kitchen-sink` redirects here)                                                                                                                                                                                                                                                                                                                                                                                              |

## Architecture

```
Vue adapters (thin)  →  Preferences (draft / storage / FOUC / setups)  →  Theme.apply / Theme.remove
```

### Preferences API

| Entry                       | Behaviour                                                                                                                                                                                                                                                                                                                                                                                    |
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `load`                      | Flush any pending write, convert the legacy keys once (or, when `tgmc-preferences` already exists, remove leftover legacy keys unread), read `tgmc-preferences`, seed committed + draft (no paint)                                                                                                                                                                                           |
| `preview`                   | Update the in-memory draft + `Theme.apply` (no write)                                                                                                                                                                                                                                                                                                                                        |
| `commit`                    | Draft becomes committed and is painted now; the storage write follows 250 ms after the last commit                                                                                                                                                                                                                                                                                           |
| `flush`                     | Write the pending committed document now (no-op when nothing is pending)                                                                                                                                                                                                                                                                                                                     |
| `discard`                   | Restore committed → re-`Theme.apply`                                                                                                                                                                                                                                                                                                                                                         |
| `reset`                     | Cancel the pending write, remove every key Preferences owns (current and legacy), seed the default document                                                                                                                                                                                                                                                                                  |
| `bindFlushOnHide`           | Flush on `pagehide` and on `visibilitychange` to `hidden`                                                                                                                                                                                                                                                                                                                                    |
| `getDraft` / `getCommitted` | Copies of the in-memory draft / committed document (throw before `load`)                                                                                                                                                                                                                                                                                                                     |
| `foucScript`                | Build-time IIFE string; no runtime `@tgmc/theme` in `<head>`                                                                                                                                                                                                                                                                                                                                 |
| `setups`                    | `list` / `save` / `apply` / `delete` / `restore` / `getActiveId` / `setActiveId` / `invalidate` / `reload` — full preference documents, max 24. `save` / `delete` / `restore` flush the pending write and convert an old-format array before writing, so they never overwrite it. `reload` drops the cache, converts an old-format array, then lists (use it for any re-read outside `load`) |

**Owns:** committed + draft and every storage key (`PREFERENCE_KEYS` in `shared/preferences/storage.ts`). Named style setups are copies of the preference document, not a third module. Snapshots (committed/draft) are deep-copied as plain data (`clonePlain`) — never `structuredClone`, which throws `DataCloneError` on Vue Proxies adapters pass in.

**Modules** (`shared/preferences/`, no import cycles): `document` ← `paint` ← `storage` ← `setups` (list + cache) ← `legacy` ← `draft` (committed / draft, write timer, `load` / `reset`) ← `lifecycle` (setup operations that flush, convert or apply) ← `index` (the `Preferences` surface). `fouc` and `testing` hang off the side.

## Brand roles

| Role      | Default relation to primary                                                                                                                                                              | Override                                      |
| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
| Primary   | Source color: a single hue’s light or dark hex, or a palette’s lightest / darkest swatch                                                                                                 | —                                             |
| Secondary | Analogous step (`Color.resolveBrandRoles`). The larger of black or white, when it beats colorfulness, sets the hue sign: negative and lighter near black, positive and darker near white | Editable; locks until primary changes / reset |
| Accent    | Complementary (`Color.resolveBrandRoles` / `Color.brandAccent`)                                                                                                                          | Editable; locks until primary changes / reset |

Picked hexes are **sources**, not painted values: each becomes the four colour-system variations per role, for **both modes at once** (see [Colour variations and the FOUC map](#colour-variations-and-the-fouc-map)). A pick below 3:1 on a mode's paper is lightness-adjusted until it passes there. `--theme-focus-ring-color` is **not** written — it stays on the theme's AA focus variation so a low-contrast brand pick never hides keyboard focus.

**Derive from primary** (Studio switch on Secondary / Accent) maps to `secondaryLocked` / `accentLocked` via `withDerivedRole()`: on = unlocked and re-derived from primary; off = keep the current hex.

Studio presets (`Theme.presets()`, `theme/core/src/theme-presets.json`) use one derivation for single colors, packs, and palettes. The source is the light/dark hue pair, or the palette’s lightest and darkest swatches. Missing secondary and accent are filled from that source. The background triad (`--portfolio-background-{primary,secondary,accent}-color`) is the pack's painted brand triad — the same three colours the Style Studio pack tile shows (`paintedPackColors`) — so Background → Custom and the tile agree; the palette's extra swatches only paint the pack image (the theme preset still carries them as `backgroundRoles`, which paint no longer reads). Every pack paints three distinct colours: when no analogous secondary clears contrast, `broadAnalogousSecondary` takes the candidate furthest from the primary instead of repeating it. `buildPresetBackgroundTokens` shifts **only the color’s lightness** with the theme's `adjustLightnessFor` (the one implementation; the local `adjustForAa` copy was removed in colour-system Task 3): the brand (and background) triad until it is ≥ 3:1 against that mode’s paper (inside the 15–90 lightness band). Each background-image stop is moved until the ink reads on it (≥ 4.5:1) and then, where the ink still reads, until it stands out from the paper (≥ 3:1) — otherwise a pastel image on the light paper or a near-black one on the dark paper vanishes. Ink and paper are not changed. Light and dark values are written as `--portfolio-*-light-color` / `--portfolio-*-dark-color` (images: `--portfolio-background-image-light` / `-dark`); the unsuffixed `--portfolio-*-color` variables follow the active theme. The pre-rename names (`--portfolio-primary` …) are gone since colour system Task 8; Background → Custom options stored under them are still migrated on load (and by the FOUC script).

Style Studio lists **Packs** and **Colors**. A row shows only the current theme: a gradient from that mode’s primary to its secondary. The name sits on a solid plate (`.style-studio__pack-label`: `--theme-surface-color` with `--theme-text-color`, 15.2:1 light and 16.2:1 dark on the default paper / ink), with the gradient as the chip fill around it. No single colour reads at 4.5:1 on every point of a mid-tone gradient: until 2026-10-19 the label was ink or paper straight on the fills with a halo of the other, and the worst point measured 3.0:1 light / 3.02:1 dark (18 and 19 of 21 chips below 4.5:1); a halo does not count toward WCAG 1.4.3. `core/web/tests/styles-studio.spec.ts` checks every pack in both modes; the old code is in `theme/core/scss/_archive/2026-10-19-pack-label-plate/`. A pack with no background selects Particles; a pack with a background selects Custom and fills those options.

Primary-source inventory of Theme colour inputs (a snapshot; the catalog above is current): [theme-studio-preset-research.md](./theme-studio-preset-research.md).

### Contrast guard

The Studio readout (`AppStyleStudio`, a polite live region) shows what the site will paint, because picks are sources that the colour system adjusts automatically (colour-system Task 3):

| Row                             | Shows                                                                                                                           | Minimum |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------- |
| On the page · <mode> mode       | “Your pick R:1 · shown as ▪ #hex” — the raw pick's ratio, then the active variation `--theme-<role>-color` and its verdict      | 3:1     |
| Button text (primary role only) | “#ink on ▪ #fill” — `--theme-button-fg-color` on `--theme-button-fill-color` (light: white on the primary fill) and its verdict | 4.5:1   |

Painted values are resolved with `resolveCssColorToHex()`; ratios come from `evaluateRoleContrast()` (`core/web/shared/contrast-guard.ts`). The old one-click fixes (“Darken until it passes”, “Use nearest passing shade”, `nearestPassingShade`) were removed: the variation and the primary fill already make the painted colours pass, so there is nothing left to fix by hand. The colour chips are decorative (`aria-hidden`); the hex is in the text; the rows contain no controls and wrap at phone width.

Text links never use the brand primary — they use the theme's `--theme-link-color` — so no role is checked at 4.5:1 on the page. (On the near-black ground, “white text on it ≥ 4.5:1” and “on the page ≥ 4.5:1” cannot both hold for any colour; the 3:1 mark rule always leaves a passing range, pinned by `tests/contrast-guard.spec.ts`.)

Paper ivory/ink constants resolve through `shared/portfolio-chrome.ts` (theme `themeColors`). Atmosphere `--portfolio-*-color` chrome is a set of CSS `color-mix()` blends of the theme colours, so it follows these edits live; the JS recipe mirror for agents/tests is documented in [app-scss.md](./app-scss.md#atmosphere-blend-table).

## Pen & paper

Paper is the **background** and ink the **foreground (text)** in every mode; the theme derives every surface, grey, border and status tone between them (see [theme five-input model](../../packages/theme.md#five-input-colour-model)). Each mode has its own pair.

| Piece                                                               | Where                                                                                                                                                                                                                                                                                       |
| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| State `{ light: {paper, ink}, dark: {paper, ink}, linked }`         | `PaperInkState`, `defaultPaperInk()` (`shared/preferences/document.ts`, exported from `#shared/preferences`)                                                                                                                                                                                |
| Edit one mode (linked → the other mode is the same colours swapped) | `withPaperInk(state, mode, pair)`; `withPaperInkLinked(state, linked, from)`                                                                                                                                                                                                                |
| Tokens written                                                      | Both modes at once: `--theme-paper-{light,dark}-color` / `--theme-ink-{light,dark}-color` (`buildPaperInkTokens`); the stylesheet points `--theme-paper-color` / `--theme-ink-color` at the mode's pair, so a mode switch needs no re-write. A change also recomputes the brand variations. |
| Storage                                                             | `paperInk` inside `tgmc-preferences` (omitted when it equals the defaults); the FOUC script applies the pairs from the colour map (`tgmc-theme-color-tokens`)                                                                                                                               |
| Setups                                                              | `StyleSetup.document.paperInk`; setups saved before paper / ink existed apply the defaults                                                                                                                                                                                                  |

**Style Studio → Paper & ink · <mode> mode:** colour picker + hex for Paper (background) and Ink (text), a strip previewing page → surface → variant → border → secondary → text plus ink alpha washes (8 / 24 / 48 %), the checkbox **"<other> mode uses the inverse"** (on by default), a live readout from `checkPaperInk()` (text and secondary text ≥ 4.5:1, control borders ≥ 3:1, and **Success / Warning / Error / Info text** ≥ 4.5:1 — each status ink as the runtime computes it for this pair, worst of page, surface and variant; a row fails only when the pair leaves no lightness at which that hue reads), **Swap paper and ink** and **Reset paper and ink**. All controls are labelled, ≥ 44 px, and wrap at phone width. Like every Studio edit it previews site-wide and commits on **Apply**.

**Colour mode in the draft.** Theme no longer stores the mode; Preferences does, as `mode` inside `tgmc-preferences`. Picking a mode in Studio previews it; **Apply** commits it: `commitLive` → `Preferences.commit` (written with the rest of the document 250 ms later), then `setThemeMode(mode, { persist: false })` only switches the painted mode. **Discard changes** (`Preferences.discard()`) restores the committed mode. The light / dark / system buttons on **Component parity** (`/styles/parity`) go through the same Studio draft (`useStyleStudioDraft().setDraftMode`), so they preview the mode and leave it to **Apply** or **Discard changes**. On startup the theme plugin reads the mode from `Preferences.load`; if reading storage throws (blocked storage), it uses the runtime default mode.

## Colour variations and the FOUC map

Colour-system Task 3 (spec [2026-09-24-color-system-design.md](../../superpowers/specs/2026-09-24-color-system-design.md), theme side in [packages/theme.md → Runtime](../../packages/theme.md#runtime-model)). Preferences writes one **runtime colour map** inline on `<html>`, for both modes, through `paintDocument` → `Theme.apply` (`shared/preferences/paint.ts`; `usePersonalization` is the Vue adapter):

| Names (per mode `light` / `dark`)                                       | From                                                                                                                                                                                                                                                                                        |
| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--theme-paper-<mode>-color`, `--theme-ink-<mode>-color`                | `buildPaperInkTokens(paperInk)`                                                                                                                                                                                                                                                             |
| `--theme-{primary,secondary,accent}-<mode>{,-background}-color`         | `buildBrandTokens(roles, mode, paperInk, packId)` → theme `buildColorVariations` against that mode's paper (≥ 3:1) and ink (backgrounds, ink ≥ 4.5:1)                                                                                                                                       |
| `--theme-primary-fill-<mode>-color`                                     | theme `buildPrimaryFillTokens`: the primary lightness-moved until white reads ≥ 4.5:1 (light-mode primary buttons; `--theme-primary-fill-color`)                                                                                                                                            |
| `--theme-primary-ink-<mode>-color`                                      | theme `buildPrimaryInkTokens(sources, paperInk)`: the primary source lightness-moved until it reads ≥ 4.5:1 on that mode's page, surface and variant (brand-coloured text; `--theme-primary-ink-color`) — so a pick **and** a paper / ink change recompute it                               |
| `--theme-secondary-ink-<mode>-color`                                    | theme `buildSecondaryInkTokens(sources, paperInk)`: the same for the secondary source (secondary-coloured text; `--theme-secondary-ink-color`) — recomputed on a pick and on paper / ink                                                                                                    |
| `--theme-button-fg-dark-color`                                          | theme `buildButtonInkTokens`: dark button text ≥ 4.5:1 on the dark primary variation (light button text is white on the fill)                                                                                                                                                               |
| `--theme-{primary,secondary}-wash-<mode>-color`                         | theme `buildWashTokens(variations, primaryInk, paperInk)`: the hover (primary) / active (secondary) washes behind primary-ink text on outline, ghost and text buttons, lightness-moved until the ink reads ≥ 4.5:1 on the wash over page, surfaces and variant                              |
| `--theme-{warning,error,info,success,focus}-<mode>{,-background}-color` | `buildStatusTokens(paperInk)` → theme `buildColorVariations` from the **default** status / focus sources against the pair (status ≥ 4.5:1 and focus ≥ 3:1 on paper; backgrounds carry the ink at 4.5:1) — no picker changes these, a custom paper / ink does                                |
| `--theme-{success,warning,error,info}-ink-<mode>-color`                 | theme `buildStatusInkTokens(sources, paperInk)`: the status variation mixed toward the text colour (`STATUS_INK_MIX`, the old stylesheet `color-mix`), then lightness-moved until it reads ≥ 4.5:1 on page, secondary page, surface and variant (status text; `--theme-<status>-ink-color`) |

- **Per-mode sources** (`brandColorSources`): a pack / preset role uses the pack's light / dark pair (whichever mode picked it); the untouched default roles use the theme's own pair; a custom pick is the source for both modes.
- **Status and focus follow the pair.** Before, only the brand variations were recomputed for a custom paper / ink, so status text kept its build-time tone and could fall to ~3.1–3.6:1 (e.g. dark paper `#2a3814` / ink `#f9fae0`: info 3.10, error 3.23, success 3.39; light `#c9c8f6` / `#0b0303`: success 3.55). The map now rebuilds all eight solid colours and the status inks; for the default pair every status / focus value equals the stylesheet default (`runtime-color-tokens.spec.ts`), so nothing changes for an untouched paper / ink.
- **Defaults write nothing** (`buildRuntimeColorTokens` returns `null`): the stylesheet already declares the default variations, so an unpersonalised page has no inline colours and no stored map.
- **No old names:** `--primary-color`, `--secondary-color`, `--accent-color`, `--button-fg`, `--paper`, `--ink` are gone (colour system Task 8): the stylesheet does not declare them and nothing writes them. The theme API still accepts them as input and writes their `--theme-…-color` names instead. The stylesheet switches the active names per mode, so changing mode (Studio or Personalize) needs no colour re-write: the theme registry keeps the per-mode names across the colour-mode writer's full replace. (`usePersonalization` still re-writes its `--portfolio-*-color` preset layer on a mode switch — that layer is replaced, and its unsuffixed names follow the mode.) Returning to the defaults removes the names through `Theme.remove`, so the registry and `:root` agree.
- **Storage:** the map is stored as `tgmc-theme-color-tokens`, derived from the document's brand roles, paper / ink and pack. It is written together with `tgmc-preferences` (a commit, a setup apply, the one-time legacy conversion), and only when its value changes; a normal load writes it only to repair it: the one-time legacy conversion, or a **stale map** (below). `Preferences.reset` removes it.
- **FOUC:** `Preferences.foucScript()` reads the map and applies it before first paint. It is **sanitised**: only the allowlisted names (`RUNTIME_COLOR_TOKEN_NAMES`), only `#rrggbb` values, and nothing when the stored JSON is longer than `COLOR_TOKENS_MAX_LENGTH` (4096; the full map is 2,749 characters — 63 names, every value `#rrggbb`) or not an object — the same rule as `sanitizeColorTokenMap()`. No colour maths runs in `<head>`. The stored map is a cache of `buildRuntimeColorTokens(doc)`, so it goes stale two ways: it predates a runtime name (e.g. `--theme-primary-ink-{light,dark}-color`, the status / focus variations, status inks and washes), or a release changed a builder's output for a name it already has (a wash alpha, a link / focus target, `STATUS_INK_MIX`, the default sources). `Preferences.load` (on mount) rebuilds the map when the document has a custom pick or paper / ink and compares it with the sanitised stored map: when any `RUNTIME_COLOR_TOKEN_NAMES` value is missing or differs it rewrites the map; when they are identical it writes nothing; when the document is the defaults (no map is due) it removes a leftover stored map (`refreshStaleColorTokens`). A returning visitor therefore sees stale values for at most that first load, not until their next commit.
- **Paper / ink values are `#rrggbb`.** The FOUC map keeps only `#rrggbb`, so a stored pair (the document, the legacy `tgmc-paper-ink` key, a setup) is normalised when it is parsed: `#rgb` and `rgb()` expand to lower-case `#rrggbb` (`normalizeOpaqueHex` in `document.ts`), and a value with alpha below 1 or that `Color` cannot parse rejects the pair (the defaults apply). The save path matches the read path: `withPaperInk` stores the same normalised `#rrggbb` (opaque alpha forms such as `#rrggbbff` flatten) and returns the state unchanged for a translucent or unparseable value, and Style Studio refuses a translucent paper / ink with an inline alert (`aria-invalid` on the field) — so a saved pair always reads back (`preferences-storage.spec.ts` round-trip, `style-studio.cy.ts`). Before, a `#fff` paper passed validation but was dropped from the map, so the default paper flashed on every reload and the map was rewritten on every load.
- **Tests:** `core/web/tests/runtime-color-tokens.spec.ts` (variations, sources, status / focus recompute, sanitiser, FOUC script run against fake storage, and `RUNTIME_COLOR_TOKEN_NAMES` ⊆ the names the compiled `_root.scss` declares, so every runtime write has a stylesheet default), `core/web/tests/studio-preset-contrast.spec.ts` (every Studio preset against its contrast targets, both modes) and `core/web-e2e/src/e2e/style-studio.cy.ts` (pick → mode switch → Apply → reload paints the map before hydration → Discard → Reset).

## Background → Custom options

Background → Custom shows Primary / Secondary / Accent (colour), Image (CSS `url()` / gradient) and Repeat / Size / Position / Attachment / Blend (fixed choices). Each writes a `--portfolio-background-*` variable; the colours use the `-color` names (`--portfolio-background-primary-color` …). Options stored under the pre-rename keys (`--portfolio-background-primary` …) are read under the new names (`sanitizeBackgroundOptions`, for the document and every setup), applied by the FOUC script under the new names (a new key wins), and stored under the new names on the next write.

| Piece      | Where                                                                                                                                                                                                                                                                                                                                                                            |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| State      | `backgroundOptions` (`BackgroundOptions`, by CSS variable; absent = the preset / theme default)                                                                                                                                                                                                                                                                                  |
| Validation | `sanitizeBackgroundOption()` — hex for colours, a listed choice, CSS image functions only for Image (no `;` `{` `}` `<` `>`)                                                                                                                                                                                                                                                     |
| Storage    | `backgroundOptions` inside `tgmc-preferences` (omitted when empty); the FOUC script re-applies it before paint                                                                                                                                                                                                                                                                   |
| Writing    | Preferences `paintDocument` → `Theme.apply` merges `buildBackgroundLayer(presetTokens, options)` (preset first, visitor options on top). The Vue adapter clears absent layer keys on `:root`. (Previously the picker wrote to `<html>` directly and every brand / mode change wiped it; it was never saved.)                                                                     |
| Flow       | Style Studio drafts (`setDraftBackgroundOption`) and commits on **Apply**, **Discard** restores; Personalize quick apply commits; setups carry `document.backgroundOptions`                                                                                                                                                                                                      |
| Display    | An absent option shows the value painted on `:root` (the pack's image, repeat, size, position …), not an empty field; a stored option wins. A colour variable the pack does not set stays empty (resolving `var(--unset)` would read the inherited text colour and show black). Hex fields commit only a complete `#rrggbb`, so typing `#2a6` does not paint `#22aa66` mid-entry |

## Draft vs committed

Style Studio edits **preview** through Preferences (`preview` → `Theme.apply`) **without** writing `localStorage` until **Apply** or **Save as setup**. A commit paints immediately and writes `tgmc-preferences` 250 ms after the last commit (`COMMIT_WRITE_DELAY_MS`), so a burst of changes is one write. The pending write is flushed on page hide (`pagehide`, `visibilitychange` to `hidden`) and before setup save / apply / restore / delete; reset drops it and clears every key. The draft **survives in-app navigation** (state lives in Preferences / `useState`) and keeps previewing site-wide until **Apply** or **Discard changes**; a full reload restores the committed prefs, so the app-level `plugins/style-draft-guard.client.ts` (via `useUnsavedDraftGuard`) asks before reload/close while the draft is dirty — on any page, not just `/styles`. Personalize quick-apply always commits.

Saving under an existing name asks inline “Replace ‘NAME’?” (Replace / Save as new); an empty name shows “Name this setup”. Deleting a setup (the 44px `trash-2` button beside it) removes it at once and runs through the layer's `useConfirmUndo`: `UiUndoNotice` under the setup list shows “Deleted “NAME”. [Undo]” for 8 s (the time stops while the line is hovered or focused), the delete is announced, and focus moves to Undo. Several deletes stack one line each. Undo calls `restoreSetup()` (`Preferences.setups.restore` keeps the original position; `restoreSetup` restores the active state), announces “Restored …” and returns focus to the setup; when the window ends with focus on Undo, focus goes to the first setup (or the main landmark when none is left). Leaving the page just drops the offer: the delete is already stored. A delete that hits a full store shows the storage-full message and offers no Undo. Deleting the setup that is selected — stored as active or only picked into the draft — clears the selection, so a later **Apply** never stores the deleted id.

## Named setups

App-owned copies of the full preference document (not `Theme.create` packs), defined in `shared/preferences/document.ts`:

```ts
type StyleSetup = {
  id: string;
  name: string;
  document: PreferenceDocument; // mode, pack, brand roles, motion, background, paper / ink, background options
};
```

Applying a setup commits its document at once (written now, not throttled), marks it active and paints it — mode and pack included. Each stored document goes through the same validator as `tgmc-preferences` (`parsePreferenceDocument`), so a bad field falls back to its default. The list is parsed once and cached. A `storage` event from another tab for `tgmc-style-setups` or `tgmc-style-setup-active`, or with `key === null` (the other tab cleared storage), reloads it with `Preferences.setups.reload`, which also converts an old-format array that a tab still on the previous release may have written.

At most **24** setups (`STYLE_SETUPS_MAX`). Saving a new name at the limit is refused and Studio shows `You have 24 setups — delete one to save another`; replacing an existing setup still works at the limit. **Undo** after a delete is refused the same way when the list is full again (for example another tab saved a setup): `Preferences.setups.restore` returns `{ ok: false, reason: 'limit' }` and writes nothing, Studio shows the same message in `p.style-studio__save-error[role=alert]`, and the Undo stays offered (`restore` returns `false`, so `useConfirmUndo` keeps it pending) until its 8 s expire, so it can be retried once a slot is free. Undo for a setup that is already in the list succeeds without adding a duplicate. A list converted from the old format is not trimmed to 24: it keeps every valid setup, even past the limit, but drops invalid entries (no id, no name, or no brand roles).

## Storage

Preferences owns four `localStorage` keys (`PREFERENCE_KEYS.current`):

| Key                       | Value                                                                                                                                                                                                                               |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `tgmc-preferences`        | The committed look: one JSON document `{ v: 1, mode?, accent?, brandRoles?, motion?, background?, backgroundCustom?, paperInk?, backgroundOptions? }`. Fields equal to the default are omitted. Ignored when longer than 8192 chars |
| `tgmc-theme-color-tokens` | JSON runtime colour map (removed for the defaults) — the FOUC script applies it                                                                                                                                                     |
| `tgmc-style-setups`       | `{ v: 1, setups: [{ id, name, document }] }` — at most 24 setups; each document uses the same compact form as `tgmc-preferences`                                                                                                    |
| `tgmc-style-setup-active` | Active setup id after Apply / quick-apply                                                                                                                                                                                           |

`core/web/tests/preferences-docs.spec.ts` checks that this table lists exactly `PREFERENCE_KEYS.current`.

A missing, oversized, corrupt or wrong-version `tgmc-preferences` loads as the default document.

**Legacy keys (one release).** Before `tgmc-preferences`, each preference had its own key: `tgmc-theme-mode`, `tgmc-brand-roles`, `tgmc-accent`, `tgmc-motion`, `tgmc-background`, `tgmc-background-custom`, `tgmc-paper-ink`, `tgmc-background-options` (`LEGACY_KEYS`), and `tgmc-style-setups` held a plain array. On the first load without `tgmc-preferences`, `shared/preferences/legacy.ts` converts the old keys into one document, writes it (with its colour map) and only then removes them; when `tgmc-preferences` already exists, any old keys still present are removed unread (the new key wins); an old setups array is rewritten as `{ v: 1, setups }` with full documents (a setup without a mode takes the current one). The FOUC script falls back to the old mode, motion and background-options keys only while `tgmc-preferences` is absent (the first paint before conversion); a present but invalid document means defaults, never the old keys. The conversion module, the FOUC fallback and `LEGACY_KEYS` are removed next release ([TODO](./interaction-redesign.md#todo)).

**When storage fails.** A throttled write that throws (quota, private mode) is dropped: the committed look stays painted and in memory for this visit. `tgmc-preferences` and its FOUC colour map `tgmc-theme-color-tokens` are written as a pair (`persistPreferenceDocument`, colour map first): if either write throws, both keys are put back to their previous values before the error reaches the caller, so the first paint never uses colours from a different document. A legacy conversion whose write fails leaves the old keys in place (tried again on the next load) and still returns the converted document. When **Save as setup** (or Replace / Save as new) or a delete's **Undo** hits a full store, Studio shows it in the same line as the setup limit (`p.style-studio__save-error[role=alert]`): `Couldn’t save — browser storage is full`. Applying a setup when storage is full still paints and commits it for the visit (`usePersonalization` falls back to a throttled commit, whose write is then dropped). When the browser blocks `localStorage` (reading it throws `SecurityError`), the theme plugin uses the runtime default mode and `usePersonalization` works on an in-memory store (`app/utils/preference-storage.ts`): the defaults load, and changes last for the visit.

FOUC head script (`Preferences.foucScript()`, `shared/preferences/fouc.ts`) is **owned by Preferences** (codegen). Theme / `Color` supply bake-time allowlists only. The IIFE reads `tgmc-preferences` (same 8192-char and version checks as the loader) for mode, motion and background options, and applies the **committed** runtime colour map (`tgmc-theme-color-tokens`, sanitised — see [above](#colour-variations-and-the-fouc-map)) before paint via `localStorage` + inline `setProperty`. It does not parse setups or brand roles, does **no colour maths**, and does **not** import `@tgmc/theme` at runtime in `<head>`. Resolved mode sets `html[data-theme]`, `style.colorScheme`, and toggles `html.p-dark` for dark.

Paper constants `PORTFOLIO_IVORY` / `PORTFOLIO_INK` read `themeColors.light.background` / `themeColors.dark.background` (Color-normalized). Brand pack primaries that match theme roles also come from `themeColors`; pack-only vivid darks still pass through `Color.toHex`.

## E2E · theme mode smoke

`core/web-e2e/src/e2e/theme-mode.cy.ts` visits the shared `PUBLIC_ROUTES` list (`core/web-e2e/src/support/routes.ts`, same set as `ui-audit.cy.ts`) once under **light** and once under **dark** at a single desktop viewport (1280×800). Before each visit it seeds `tgmc-preferences` with `{ v: 1, motion: 'reduced', mode }` through `seedPreferences` (`core/web-e2e/src/support/preferences.ts`, shared by every spec that seeds or reads preferences), then asserts `#site_main` is visible, that the stored `mode` matches, and that `document.documentElement` has the matching `data-theme`, `color-scheme`, and `.p-dark` (dark only). One extra case seeds the legacy keys `tgmc-theme-mode` (`dark`) and `tgmc-motion` (`reduced`) and checks that the FOUC script paints the legacy mode before hydration (`data-theme` captured at `readyState === 'interactive'`), that both values are converted into `tgmc-preferences`, and that both legacy keys are removed. Storage writes are throttled (250 ms), so assertions that read storage after a UI change retry with `cy.window().should(...)`. It is intentionally not a second ui-audit × viewport matrix.

```bash
# App already on :4200 (dev or Nitro node-server):
E2E_SKIP_WEBSERVER=1 E2E_BASE_URL=http://127.0.0.1:4200 \
  npx cypress run --project core/web-e2e --spec core/web-e2e/src/e2e/theme-mode.cy.ts

# Or let Cypress start Nuxt dev (slower):
npx cypress run --project core/web-e2e --spec core/web-e2e/src/e2e/theme-mode.cy.ts
```

## Background · Camera and Custom

Both surfaces use `AppBackgroundPicker`. Choosing **Camera** first shows “Uses your camera locally — nothing is recorded or sent.” with **Turn on camera** / **Cancel**; the mode (and the browser permission prompt) only switches after Turn on camera.

Choosing **Custom** in Personalize or Style Studio enables a color picker + hex field. Until the visitor picks a colour (the stored value is still `DEFAULT_BACKGROUND_CUSTOM`, the dark paper), the custom colour **follows the active mode's paper** (`backgroundCustomFor`): the field shows it (`backgroundCustomShown`) and the fill paints it, and both switch with the mode. The dark paper is never shown in light mode, where it is the ink itself (1:1 text). Picking exactly the dark paper counts as unpicked. `AppDepthField` then shows a solid `--portfolio-depth-custom-color` fill instead of particles / grid / camera. Page text sits on that fill, so a picked colour is painted as `paintedBackgroundCustom(doc, mode)`: theme `backgroundFor` against the active mode's ink (≥ 4.5:1, lightness band 15–90); the unpicked paper is painted as-is. The hex field keeps the visitor's choice; only the painted fill moves, and it is re-derived on every mode change (e.g. `#ffffff` paints `#e6e6e6` in light mode and `#707070` in dark mode). A pack's background image would cover that fill, so picking a custom colour also sets Image to `none` unless the visitor chose an image themselves (`setBackgroundCustom`); selecting a pack again clears that `none` so the pack's image returns (`applyBrandPack`).

`AppDepthField` mounts once from the site layout (`layouts/site.vue`) so every portfolio page shares the same backdrop. The Docker-only `@tgmc/admin` app does not use that layout and has no depth field.

## Status announcements

Every quick-apply change (mode, background, setup, pack, reset) is announced in a polite `role="status"` line ("Applied: …", cleared after 6 s). A refused camera fills the depth field's `role="status"` note. Messages live in `core/web/shared/live-status.ts`; both regions stay in the DOM (empty when idle) so screen readers announce the change (WCAG 4.1.3). Cypress: `live-regions.cy.ts`.

## UI stack

Studio and Personalize use portfolio `Ui*` wrappers:

- **PrimeVue stack:** `UiColorPicker`, `UiSelect`, `UiInputText`, `UiRadio`, `UiButton`, `UiTag`, `UiDialog`
- **Foundation / native:** same wrappers fall back to native controls; layout uses Foundation XY Grid classes (`grid-x` / `cell`)

The `/styles` page header has the same gap under the site header as the other pages' `.portfolio-hero` (`padding-block-start: var(--portfolio-space)`, 32px at 375px and 67px at 1280px; it was flush, 0px, until 2026-10-19 — `core/web/tests/styles-studio.spec.ts`).

Swatch chips come from `Color.brandSwatchCatalog()` (theme roles, semantics, named palettes in `@tgmc/theme`). Helpers: `Color.resolveBrandRoles`, `Color.brandAccent`, `Color.brandSecondaryCandidates`.

## Related

- Theme Color API + Sass `theme-*`: [packages/theme.md](../../packages/theme.md)
- Domain glossary (Theme and Preferences terms, brand role harmony / override): [CONCEPTS.md](../../../CONCEPTS.md)
- App SCSS / `--portfolio-coral-color` → `--theme-accent-color`: [app-scss.md](./app-scss.md)
- Agent map: [docs/agents/map.md](../../agents/map.md)
- Plan: [plans/2026-09-19-003-feat-style-studio-experience-plan.md](../../plans/2026-09-19-003-feat-style-studio-experience-plan.md)
