diff --git a/.agents/skills/impeccable/SKILL.md b/.agents/skills/impeccable/SKILL.md index 64307cf43..b088b997e 100644 --- a/.agents/skills/impeccable/SKILL.md +++ b/.agents/skills/impeccable/SKILL.md @@ -1,118 +1,46 @@ --- name: impeccable description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks. -version: 3.9.1 +version: 4.0.2 --- -Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft. +This skill gives you the tools and permission to create design that earns to be called out-of-distribution craft: Whereas before, your design work would have been safe, timid and measured, you now approach every design task as a award-winning design director with impeccable understanding for what makes exceptional design work: production-grade code, peak creativity, a clear POV, deep understanding of the needs of the client and users, and exceptional craft. -## Setup - -You MUST do these steps before proceeding: - -1. Run `node .agents/skills/impeccable/scripts/context.mjs` once per session; if the runtime shows this skill's loaded base directory, run `node /scripts/context.mjs` instead. Keep cwd/workdir at the user's project, not the skill directory. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and append `--target ` to the same command. If you've already seen its output in this conversation, do not re-run it. The script either prints the project's PRODUCT.md (and DESIGN.md when present) as a markdown block, or tells you it's missing. Follow whatever it prints. **If it reports `NO_PRODUCT_MD`:** divert into `reference/init.md` first when the user invoked `init`, `teach`, `craft`, or `shape`, or when their wording clearly maps to one of those from-scratch build flows (for example: "build/create/make a landing page", "design a new app", or "shape a feature"). Captured product context is the point of those flows. For any other command, a scoped evaluate / refine / enhance / fix / iterate request against existing code, do **not** divert into init. The existing code is the context: proceed with the requested command, infer the register from the surface in focus (step 4), and offer `$impeccable init` once as a suggestion the user can take later. A missing PRODUCT.md must never block a scoped request. If the output ends with an `UPDATE_AVAILABLE` directive, follow it (ask the user once about updating, then continue). It never blocks the current task. -2. If the user invoked a sub-command (`craft`, `shape`, `audit`, `polish`, ...), you MUST read the command's reference next: **`reference/.md`, or the native variant from the Commands table** (e.g. `reference/audit.native.md`) **when the project platform is native** (`ios` / `android` / `adaptive`, per the `context.mjs` directive). One file, not both. Non-optional. The reference defines the command's flow; without it you will skip steps the user expects. -3. Familiarize yourself with any existing design system, conventions, and components in the code. Read at least one project file (CSS / tokens / theme / a representative component or page). **Required even when you've loaded a sub-command reference in step 2.** Don't reinvent the wheel; use what's there when it works, branch out when the UX wins. -4. Read the matching register reference. **This is non-optional; skipping it produces generic output.** If the project is marketing, a landing page, a campaign, long-form content, or a portfolio (design IS the product), read `reference/brand.md`. If it is app UI, admin, a dashboard, or a tool (design SERVES the product), read `reference/product.md`. Pick by first match: (1) task cue ("landing page" vs "dashboard"); (2) surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. -5. **If PRODUCT.md's `## Platform` is `ios` or `android`**, also read `reference/.md` (HIG / Material 3 conventions). `adaptive` (cross-platform, ships both) reads both files. `web`, absent, or unrecognized: nothing extra to read. `context.mjs` prints the directive when one applies. -6. **If the project is brand-new (no existing CSS tokens / theme / committed brand colors found in step 3)**, run `node .agents/skills/impeccable/scripts/palette.mjs` to receive a brand seed color and composition guidance. This is the anchor for your primary brand color. Compose the rest of the palette (bg, surface, ink, accent, muted) around it per the script's instructions. Use OKLCH throughout. **Skip this step only if step 3 found committed brand colors in existing tokens; in that case identity-preservation wins.** - -## Design guidance - -Produce ready-to-ship, production-grade code, not prototypes or starting points. Take no shortcuts unless the user asks for them (when in doubt, ask). Don't stop until arriving at a complete implementation (beautiful, responsive, fast, precise, bug-free, on brand). You take attention to detail seriously: every page, section or component crafted is battle tested using the tools available to you (browser screenshotting, computer use, etc). GPT is capable of extraordinary work. Don't hold back. - -### General rules - -#### Color - -- **Verify contrast.** Body text must hit ≥4.5:1 against its background; large text (≥18px or bold ≥14px) needs ≥3:1. Placeholder text needs the same 4.5:1, not the muted-gray default. The most common failure: muted gray body text on a tinted near-white. If the contrast is even close, bump the body color toward the ink end of the ramp; light gray "for elegance" is the single biggest reason AI designs feel hard to read. -- Gray text on a colored background looks washed out. Use a darker shade of the background's own hue, or a transparency of the text color. - -#### Typography - -- Cap body line length at 65–75ch. -- Don't pair fonts that are similar but not identical (two geometric sans-serifs, two humanist sans-serifs). Pair on a contrast axis (serif + sans, geometric + humanist) or use one family in multiple weights. -- Hero / display heading ceiling: clamp() max ≤ 6rem (~96px). Above that the page is shouting, not designing. -- Display heading letter-spacing floor: ≥ -0.04em. Anything tighter and letters touch; cramped, not "designed". -- Use `text-wrap: balance` on h1–h3 for even line lengths; `text-wrap: pretty` on long prose to reduce orphans. - -One hard typographic ceiling you currently miss: -- Display letter-spacing ≥ -0.04em. Your default of -0.05 to -0.085em on display H1s makes the letters touch and reads as cramped. -0.02 to -0.03em is plenty for tight grotesque display; -0.04em is the floor. - -#### Layout - -- Vary spacing for rhythm. -- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong. -- Flexbox for 1D, Grid for 2D. Don't default to Grid when `flex-wrap` would be simpler. -- For responsive grids without breakpoints: `repeat(auto-fit, minmax(280px, 1fr))`. -- Build a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip). Never arbitrary values like 999 or 9999. - -#### Motion -- Motion should be intentional, and not be an afterthought. consider it as part of the build. -- Don't animate CSS layout properties unless truly needed. -- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic. -- Use libraries for more advanced motion needs (e.g. motion, gsap, anime.js, lenis etc) -- Reduced motion is not optional. Every animation needs a `@media (prefers-reduced-motion: reduce)` alternative: typically a crossfade or instant transition. -- Staggering the items within one list is legitimate. The tell is the uniform reflex (one identical entrance applied to every section), not motion itself; each reveal should fit what it reveals. Suppressing the reflex is never a reason to ship a page with no motion at all. -- Reveal animations must enhance an already-visible default. Don't gate content visibility on a class-triggered transition; transitions pause on hidden tabs and headless renderers, so the reveal never fires and the section ships blank. -- Premium motion materials are not just transform/opacity. Blur, backdrop-filter, clip-path, mask, and shadow/glow are part of the palette when they materially improve the effect and stay smooth. - -#### Interaction +Core principles: +- Go all out. No hedging, no shortcuts. The deliverable must be complete (except assets the user must provide). +- Dream big and bold. Distinct, beautiful, outstanding and highly inspiring work. +- Iterate with tools available to you (e.g. visual understanding, browser screenshots) until you think this meets the bar. -- Dropdowns rendered with `position: absolute` inside an `overflow: hidden` or `overflow: auto` container will be clipped. Use the native `` / popover API, `position: fixed`, or a portal to escape the stacking context. - -### New projects only (when no prior work exists) - -#### Color & Theme - -- Use OKLCH. -- **The cream / sand / beige body bg is the saturated AI default of 2026.** The whole warm-neutral band (OKLCH L 0.84-0.97, C < 0.06, hue 40-100) reads as cream/sand/paper/parchment regardless of what you call it. Token names like `--paper`, `--cream`, `--sand`, `--bone`, `--flour`, `--linen`, `--parchment`, `--wheat`, `--biscuit`, `--ivory` are tells in themselves. If the brief is "warm, traditional, family-coastal-Italian" or "magazine-warm" or "editorial-restraint", DO NOT translate that into a near-white warm-tinted bg; that's the AI move. Pick: (a) a saturated brand color as the body (terracotta, oxblood, deep ochre, near-black), (b) a true off-white at chroma 0 (or chroma toward the brand's own hue, not toward warmth-by-default), or (c) a darker mid-tone tinted neutral that's clearly the brand's own. "Warmth" in the brand is carried by accent + typography + imagery, not by body bg. -- Tinted neutrals: add 0.005–0.015 chroma toward the brand's hue. Don't default-tint toward warm or cool "because the brand feels that way"; that's the cross-project monoculture move. -- When picking a theme: Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe.".Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does. -- Pick a **color strategy** before picking colors. Four steps on the commitment axis: - - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism. - - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages. - - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz. - - **Drenched**: the surface IS the color. Brand heroes, campaign pages. - -### Absolute bans - -Match-and-refuse. If you're about to write any of these, rewrite the element with different structure. +## Setup -- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing. -- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size. -- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing. -- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché. -- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly. -- **Tiny uppercase tracked eyebrow above every section.** The 2023-era kicker (small all-caps text with wide tracking, "ABOUT" "PROCESS" "PRICING" above each heading) is now the saturated AI scaffold; it appears on 55-95% of generations regardless of brief, which is the definition of a tell. One named kicker as a deliberate brand system is voice; an eyebrow on every section is AI grammar. Choose a different cadence. -- **Numbered section markers as default scaffolding (01 / 02 / 03).** Putting `01 · About / 02 · Process / 03 · Pricing` above every section is the eyebrow trope one tier deeper: reach for it because "landing pages do this" and you're scaffolding by reflex. Numbers earn their place when the section actually IS a sequence (a real 3-step process, an ordered flow, a typed timeline) and the order carries information the reader needs. One deliberate numbered sequence on one page is voice; numbered eyebrows on every section across the site is AI grammar. -- **Text that overflows its container.** Long heading words plus large clamp scales plus narrow grids cause headline overflow on tablet/mobile. Test the heading copy at every breakpoint; if it overflows, reduce the clamp max or rewrite the copy. The viewport is part of the design. +1. Run `node .agents/skills/impeccable/scripts/context.mjs` once per session (if the runtime shows this skill's loaded base directory, run `node /scripts/context.mjs`; keep cwd at the user's project). Pass a named source file or route as `--target `. It loads PRODUCT.md, DESIGN.md, the matching surface brief, and native-platform guidance when applicable; follow its directives and do not rerun it. +2. Before acting, load the one playbook that owns the request: the Commands table's reference for an explicit or clearly implied sub-command, or [reference/new-work.md](reference/new-work.md) for a new surface or replacement visual world. Then inspect the target and at least one representative source of incumbent visual truth (tokens, theme, CSS, component, or asset) before editing. +3. After analysis and direction are resolved, load [reference/craft-floor.md](reference/craft-floor.md) immediately before editing UI. It carries the quality floor, the absolute bans, and the reflexes no detector catches. Do not load it for planning-only work. -**Codex-specific defects** (your most-frequent giveaways; refuse-and-rewrite): +## How to design -- **`border: 1px solid X` + `box-shadow: 0 Npx Mpx ...` with M ≥ 16px** on the same element. The "ghost-card" pattern: 1px border plus soft wide drop shadow on buttons and cards. Don't pair them. Pick one (a single solid border at the brand color, OR a defined shadow at no more than 8px blur), never both as decoration. -- **`border-radius: 32px+` on cards / sections / inputs.** You over-round. Cards top out at 12–16px; full-pill is fine for tags/buttons. Picking 24/28/32/40px on a card is the codex tell; no brand wants "insanely rounded". -- **Hand-drawn / sketchy SVG illustrations.** Class names like `loose-sketch`, `*-sketch`, `doodle`, `wavy`; `feTurbulence` / `feDisplacementMap` "paper grain" filters; 5-to-30 path crude scenes meant to depict a tangible subject (an otter, a table-and-fork, an album cover). All of these read as amateurish, not whimsical. If you can't render the scene with real assets, ship no illustration. Don't attempt sketchy SVG as a fallback. -- **`repeating-linear-gradient(...)` stripe backgrounds.** Diagonal stripes in `body:before` or section backgrounds are pure codex decoration. Don't. -- **Decorative grid backgrounds.** Two-axis CSS grid overlays built from `linear-gradient(... 1px, transparent 1px)` plus `background-size` are a Codex tell unless the surface is an actual canvas, map, blueprint, or measurement tool. Use product structure, real artifacts, or a plain surface instead. -- **Meta-criticism copy.** Naming a concept then layering an ironic modifier, or staging a strawman to "correct" it. Make the specific claim instead. +- **The brief wins.** Honor pinned aesthetics, eras, materials, fonts, and palettes even when they conflict with a saturated-pattern warning. Redirecting a clear brief toward your taste is failure. +- **Refinement preserves; redesign replaces.** Refinement keeps the incumbent identity, behavior, copy, and everything outside scope. Ask before replacing factual copy or adding claims. Redesign keeps product truth, content, function, native affordances, and constraints, but treats the old look as evidence and anti-reference; choose a replacement world in new-work and replace DESIGN.md. Never split the difference into polish on the discarded look. +- **Visual authority is evidence, not a filename.** Missing DESIGN.md alone does not make a project greenfield; new-work decides whether to preserve, expand, or replace the incumbent world. -### The AI slop test +## Modes -If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference. +The mode names what the visitor's success looks like on this surface. -**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses. +- **Persuade:** the visitor decides and acts; design is the product. Landing pages, marketing, campaigns, pricing. Earn attention and action. Ship real imagery when the brief needs it; follow the committed world, not category habit. +- **Operate:** the visitor completes a task. App UI, dashboards, editors, admin, settings, tools. Scanability, consistency, native expectations, and the real usage scene outrank expression. Brand lives in precise details. +- **Read:** the visitor understands something. Docs, articles, guides, help, changelogs. Structure for comprehension, then make the reading experience worth staying in. +- **Experience:** the visitor is inside the work itself. Portfolios, galleries, showcases. Let the artifact lead from the first viewport; the interface recedes. -- **First-order:** if someone could guess the theme + palette from the category alone, it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain. -- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families. +Choose the mode from the requested surface, not the product, and persist it only in that surface brief. A tool's landing page is still Persuade; a fashion house's documentation is still Read; a docs index is Read, not Persuade. See [new-work.md](reference/new-work.md) for new surfaces and [operate.md](reference/operate.md) for deeper Operate/Read guidance. ## Commands | Command | Category | Description | Reference | |---|---|---|---| -| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) | +| `craft [feature]` | Build | Deprecated alias for an ordinary new-work request | [reference/craft.md](reference/craft.md) | | `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) | -| `init` | Build | Set up project context: PRODUCT.md, DESIGN.md, live config, next steps | [reference/init.md](reference/init.md) | +| `init` | Build | Capture durable product context in PRODUCT.md | [reference/init.md](reference/init.md) | | `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) | | `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) | | `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) | @@ -134,43 +62,19 @@ If someone could look at this interface and say "AI made that" without doubt, it | `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) | | `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) | -Plus three management commands: `pin `, `unpin `, and `hooks `, detailed below. - -### Routing rules - -1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` the project has no captured context yet, so lead the menu with `$impeccable init` as the top recommendation (one line on why) and still show the rest below; don't silently jump into init. Otherwise run `node .agents/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.** - - Reason over the signals; there is no score to obey: - - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system). - - `critique.latest` is `null` → the project has never been critiqued; for a set-up project with a real surface, offering `$impeccable critique ` is a strong default. - - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale. - - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them. - - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`. **`live` and the bundled `detect.mjs` are web-only.** If `setup.platform` is `ios`, `android`, or `adaptive`, don't lead with either; the browser overlay and the HTML rule engine don't apply to native app code. - - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`. - - **If `scan.targets` is non-empty and `setup.platform` is not `ios`/`android`/`adaptive`, run `node .agents/skills/impeccable/scripts/detect.mjs --json ` once** (the bundled detector over local files: no network, no npx; it reads HTML/CSS, so skip it for native projects). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it. - - Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede. -2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file (on native platforms, the table's native variant; Setup step 2's one-file rule) and follow its instructions. Everything after the command name is the target. -3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference (same native-variant rule) and proceed as if invoked. If two commands could fit, ask once which. -4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context. - -Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `$impeccable`. - -If the first word is `craft` or `shape`, or routing rule 3 clearly maps the user's intent to either command, setup still runs first, but the matching reference ([reference/craft.md](reference/craft.md) or [reference/shape.md](reference/shape.md)) owns the rest of the flow. Both are from-scratch build flows: if setup invokes `init` as a blocker, finish init, refresh context, then resume the original command and target. - -`teach` is a deprecated alias for `init`: if the user types it, load [reference/init.md](reference/init.md) and proceed as if they ran `init`. +Routing: -## Pin / Unpin +- **No argument:** read [routing.md](reference/routing.md) and present its context-aware menu; never auto-run a command. +- **Explicit or clearly implied command:** load its reference (native variant on native platforms) and follow it. Ask once if two commands fit. +- **Otherwise:** treat the request as general design work. Missing PRODUCT.md routes a new surface or replacement world through init, then new-work; a narrow refinement of existing code proceeds on the incumbent implementation as context.mjs directs, offering init afterward rather than blocking on it. +- `teach` aliases `init`. `craft` is a deprecated alias for ordinary new-work and adds nothing. `shape` owns task discovery, then enters new-work only for visual-world and surface-concept decisions. -**Pin** creates a standalone shortcut so `$` invokes `$impeccable ` directly. **Unpin** removes it. The script writes to every harness directory present in the project. +After init writes PRODUCT.md, resume without rerunning `context.mjs`; init loads the native platform reference itself when the platform it recorded is `ios`, `android`, or `adaptive`. -```bash -node .agents/skills/impeccable/scripts/pin.mjs -``` +**Pin / Unpin:** `node .agents/skills/impeccable/scripts/pin.mjs ` creates or removes a standalone `$` shortcut. Report the script's result concisely; relay stderr verbatim on error. -Valid `` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error. +**Hooks:** `$impeccable hooks ` manages the design detector hook for this project (auto-runs the detector after UI file edits and surfaces findings). Load [reference/hooks.md](reference/hooks.md) when the user invokes it with any argument. -## Hooks +**Doctor:** `$impeccable doctor` reports and repairs drift between this project's Impeccable artifacts (PRODUCT.md, DESIGN.md and its sidecar, config, surface briefs, the hook) and what this version reads. Load [reference/doctor.md](reference/doctor.md) when the user invokes it, or when they ask what is out of date, stale, or needs refreshing. A `CONTEXT_STALE` directive in Setup's output is the cheap subset of the same report; act on it there per its own instructions rather than running doctor unasked. -`$impeccable hooks ` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `$impeccable hooks` with any argument. \ No newline at end of file +**Never repair drift as a side effect of a design task.** A `CONTEXT_STALE` finding is reported, not acted on, unless the user asks. The one exception is a finding marked `auto`, which the next write to that file performs anyway. \ No newline at end of file diff --git a/.agents/skills/impeccable/agents/impeccable_asset_producer.toml b/.agents/skills/impeccable/agents/impeccable_asset_producer.toml index 2419f3ec6..d95bdde27 100644 --- a/.agents/skills/impeccable/agents/impeccable_asset_producer.toml +++ b/.agents/skills/impeccable/agents/impeccable_asset_producer.toml @@ -47,7 +47,7 @@ Ask blockers once, globally. Missing source path/crops or output directory block 3. Treat full-page mock crops as references, not production-resolution source assets. Put a role in `direct` only when the provided source is already a clean, sufficiently large source asset with no semantic text or presentation chrome. 4. Give the parent an execution order for the `produce` bucket. 5. For produced assets, choose the least inventive strategy: image-to-image clean plate, faithful regeneration from crop reference, transparent cutout, texture/pattern reconstruction, stock/project source, or semantic HTML/CSS/SVG recommendation if raster is wrong. -6. Treat every crop as binding reference. In Codex, use the imagegen skill and built-in `image_gen` path by default when generation or editing is needed. +6. Treat every crop as binding reference. Use the harness's native image tool by default when generation or editing is needed (the imagegen skill's built-in `image_gen` path); otherwise use the skill's generate-image.mjs. 7. Remove baked-in UI text, navigation, buttons, body copy, and mock chrome unless the text is part of the asset. 8. Think through the final DOM/CSS representation before generating. If CSS will own radius, clipping, shadows, borders, perspective, responsive cropping, captions, or card frames, do not bake those into the bitmap. 9. Save outputs non-destructively in the requested project directory. @@ -76,7 +76,7 @@ Remove letterboxing, padding, card borders, rounded clipping, CSS shadows, persp Do not add new objects. Do not change the concept. Do not redesign the composition. ``` -For transparent cutouts, use the imagegen skill's built-in-first chroma-key workflow unless the parent explicitly authorizes a true native transparency fallback. +For transparent cutouts, use a chroma-key workflow by default (the imagegen skill's built-in-first path): generate on a flat color that cannot appear in the subject, then post-process to alpha; use true native transparency only when the tool supports it or the parent authorizes it. ## Output Contract diff --git a/.agents/skills/impeccable/agents/impeccable_finish_reviewer.toml b/.agents/skills/impeccable/agents/impeccable_finish_reviewer.toml new file mode 100644 index 000000000..5815055d4 --- /dev/null +++ b/.agents/skills/impeccable/agents/impeccable_finish_reviewer.toml @@ -0,0 +1,26 @@ +name = "impeccable_finish_reviewer" +description = "Reviews a finished Impeccable build against its direction contract, persistence requirements, and the chosen world's quality bar, returning an ordered list of material fixes." +model_reasoning_effort = "high" +nickname_candidates = ["Finishing Eye", "Contract Judge", "Ceiling Check"] +developer_instructions = ''' +# Impeccable Finish Reviewer + +You are the finishing reviewer for an Impeccable build: fresh eyes on a done artifact, outside the build thread's attention gravity. You do not edit anything; the parent agent applies your fixes. + +## Input Contract + +Expect: the original request; the confirmed user answers; the artifact path(s); the direction contract (THESIS, OWN-WORLD, STORY, FIRST VIEWPORT, FORM); PRODUCT.md and DESIGN.md paths; existing hook or detector findings; the chosen world's QUALITY BAR card paths and approved comp paths when they exist; screenshot path(s) when available. When the harness can view images, open the card, the comp, and the screenshot before judging. + +## Checks, in order + +1. **Persistence.** On a new or replacement world: PRODUCT.md and DESIGN.md exist, and DESIGN.md matches the built world. A missing or mismatched file is the first material fix, ahead of any craft point. +2. **Ceiling.** Against the QUALITY BAR card and the approved comp, name the world's native devices the build left unused: frame, depth, lettering treatment, ornament density, motion. Compare commitment and finish, never composition; the card is a bar, not a layout. +3. **Contract, promise by promise.** For each of the five blocks, does the render keep the promise? Apply the memory test to the first viewport: what would a visitor describe an hour later, and is it the thesis or a mood? +4. **Truth.** Demonstration data authored and labeled synthetic; no invented commercial claims; unanswered claims present as marked placeholders, not omissions. + +Do not run a second detector pass; mechanical findings belong to the parent's hooks. + +## Output Contract + +Return exactly four sections: `persistence` (pass/fail with specifics), `ceiling` (the unused native devices, or "reached"), `material_fixes` (ordered, most material first, each one line tied to a check or contract promise, at most eight), and `keep` (one line naming what must not be diluted while fixing). No praise, no summary prose. +''' diff --git a/.agents/skills/impeccable/reference/android.md b/.agents/skills/impeccable/reference/android.md index 3575c31fb..6337b9018 100644 --- a/.agents/skills/impeccable/reference/android.md +++ b/.agents/skills/impeccable/reference/android.md @@ -2,7 +2,7 @@ For native Android apps: Jetpack Compose, Android Views, React Native, Expo, Flutter shipping to Android hardware. -On native, register narrows. Material Design 3 governs structure, navigation, and interaction whatever the register; brand expresses through Material's theming (color roles, type scale, shape, motion). A Material-everywhere cross-platform app that also ships to iPhone still owes iOS its OS guarantees on that hardware: safe-area insets, Reduce Motion, edge-swipe back. +On native, the visitor mode narrows what expression may override. Material Design 3 governs structure, navigation, and interaction in every mode; brand expresses through Material's theming (color roles, type scale, shape, motion). A Material-everywhere cross-platform app that also ships to iPhone still owes iOS its OS guarantees on that hardware: safe-area insets, Reduce Motion, edge-swipe back. ## The Android slop test diff --git a/.agents/skills/impeccable/reference/animate.md b/.agents/skills/impeccable/reference/animate.md index b44d1ac61..6d74d1841 100644 --- a/.agents/skills/impeccable/reference/animate.md +++ b/.agents/skills/impeccable/reference/animate.md @@ -1,203 +1,86 @@ > **Additional context needed**: performance constraints. -Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it. +Use motion to explain state, relationship, and hierarchy, or to create one authored moment the surface has earned. Decoration without purpose is animation debt. --- -## Register +## Visitor mode -Brand: motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions. The saturated AI default is fade-and-rise reveals on every scrolled section; that's a tell, not a choreography. Reserve scroll-triggered motion for moments that earn it. +- **Persuade + Experience:** motion may carry the voice. Prefer one rehearsed focal sequence to repeated section reveals. +- **Operate + Read:** motion serves feedback, state, and continuity. Keep routine transitions fast and do not make users wait through page-load choreography. +- **Native (`ios` / `android` / `adaptive`):** follow the Motion section of [ios.md](ios.md) or [android.md](android.md), including the platform's Reduce Motion behavior. Do not apply the web tooling below. -Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it. +## Find the job -Native (`ios` / `android` / `adaptive`): implementation follows the Motion section of [ios.md](ios.md) / [android.md](android.md) (read it first if Setup hasn't already): system transitions and OS Reduce Motion, never the web tooling below. +Inspect the existing motion language, interaction states, target devices, and performance budget. Find only the places where motion would: ---- +- acknowledge an action; +- make a state change or spatial relationship legible; +- preserve continuity through navigation or layout change; +- direct attention at a meaningful moment; +- embody the selected visual world. + +Ask only when a material constraint cannot be inferred. Do not animate a static area merely because it exists. + +## Set the motion thesis + +Write a short plan before implementation: + +- **Focal moment:** the one sequence or interaction that deserves authorship, if any. +- **Continuity:** the state, layout, or navigation changes that need explanation. +- **Feedback:** the controls and outcomes that need acknowledgment. +- **Budget:** which effects may be expensive and how often they run. + +The focal moment must come from this product and surface concept. A generic fade-and-rise, hover lift, parallax layer, or scroll reveal is not a thesis. + +## Choose material by meaning + +Transform and opacity are reliable foundations, not the entire palette. Choose properties for what the transition communicates: + +- **Continuity and relationship:** shared-element motion, FLIP-style transforms, view transitions, or deliberate spatial movement. +- **Focus and depth:** bounded blur, filter, backdrop, light, or shadow changes. +- **Reveal and composition:** masks, clip paths, cropping, or controlled occlusion. +- **Material and energy:** color, gradient position, texture, distortion, or shader effects when the world and runtime support them. +- **State and feedback:** the smallest change that makes cause and result unmistakable. + +Do not stack techniques for spectacle. One strong material idea, carried through the focal sequence and quiet supporting states, is usually enough. + +Sibling stagger is appropriate when a list appears as a list. Cap the total delay, and never reinterpret every scrolled section as a staggered list. + +## Timing and easing + +Timing should express distance and consequence: + +| Duration | Typical use | +|---|---| +| 100–150 ms | immediate feedback | +| 150–300 ms | routine state change | +| 300–500 ms | layout, overlay, or view transition | +| 500–800 ms | a deliberately authored focal entrance | + +Exit faster than entrance. Use natural deceleration such as `cubic-bezier(0.16, 1, 0.3, 1)` for confident arrivals; do not use bounce or elastic curves by reflex. Long feedback feels like latency. + +## Implement to the runtime + +- Use CSS transitions and keyframes for declarative state and bounded sequences. +- Use Web Animations API or the project's existing motion library for interruption, sequencing, and dynamic values. +- Use View Transitions or shared-element techniques when continuity across states is the point. +- Use scroll-driven motion only when the scroll relationship itself carries meaning, with a robust fallback. +- Do not add a dependency for an effect the existing stack can express cleanly. + +Keep content visible in the default state so failed scripts do not hide the page. Avoid casually animating layout-driving properties such as `width`, `height`, `top`, `left`, and margins; use FLIP, transforms, or grid techniques when appropriate. Bound blur, filter, shadow, canvas, and shader work to isolated regions. Apply `will-change` only during known animation. Measure on target viewports and devices rather than assuming transform means fast. -## Assess Animation Opportunities +## Accessibility and control -Analyze where motion would improve the experience: +Respect autoplay and sound preferences. Any nonessential loop must stop when offscreen or hidden. -1. **Identify static areas**: - - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.) - - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes) - - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious - - **Lack of delight**: Functional but joyless interactions - - **Missed guidance**: Opportunities to direct attention or explain behavior +## Verify -2. **Understand the context**: - - What's the personality? (Playful vs serious, energetic vs calm) - - What's the performance budget? (Mobile-first? Complex page?) - - Who's the audience? (Motion-sensitive users? Power users who want speed?) - - What matters most? (One hero animation vs many micro-interactions?) - -If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. - -**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them. - -## Plan Animation Strategy - -Create a purposeful animation plan: - -- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?) -- **Feedback layer**: Which interactions need acknowledgment? -- **Transition layer**: Which state changes need smoothing? -- **Delight layer**: Where can we surprise and delight? +- The focal motion is specific to the selected world and surface. +- Every supporting animation explains feedback, state, or relationship. +- Interruption and repeated use behave correctly. +- Desktop, mobile, and keyboard paths remain usable. +- Expensive effects stay smooth on the target device. +- Removing an animation would lose meaning or authored character, not merely decoration. -**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments. - -## Implement Animations - -Add motion systematically across these categories: - -### Entrance Animations -- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects) -- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management -- **List rhythm**: Sibling stagger is legitimate for cards-in-a-grid or list-items-appearing. Whole-section fade-on-scroll is not a list and is not legitimate. Cap total stagger time: 10 items at 50ms each = 500ms total. For more items, reduce per-item delay or cap the staggered count. - - Use CSS custom properties for clean stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"`, `style="--i: 1"`, etc. on each item. - -### Micro-interactions -- **Button feedback**: - - Hover: Subtle scale (1.02-1.05), color shift, shadow increase - - Click: Quick scale down then up (0.95 → 1), ripple effect - - Loading: Spinner or pulse state -- **Form interactions**: - - Input focus: Border color transition, slight scale or glow - - Validation: Shake on error, check mark on success, smooth color transitions -- **Toggle switches**: Smooth slide + color transition (200-300ms) -- **Checkboxes/radio**: Check mark animation, ripple effect -- **Like/favorite**: Scale + rotation, particle effects, color transition - -### State Transitions -- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms) -- **Expand/collapse**: Height transition with overflow handling, icon rotation -- **Loading states**: Skeleton screen fades, spinner animations, progress bars -- **Success/error**: Color transitions, icon animations, gentle scale pulse -- **Enable/disable**: Opacity transitions, cursor changes - -### Navigation & Flow -- **Page transitions**: Crossfade between routes, shared element transitions -- **Tab switching**: Slide indicator, content fade/slide -- **Carousel/slider**: Smooth transforms, snap points, momentum -- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators - -### Feedback & Guidance -- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights -- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning -- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation -- **Focus flow**: Highlight path through form or workflow - -### Delight Moments -- **Empty states**: Subtle floating animations on illustrations -- **Completed actions**: Confetti, check mark flourish, success celebrations -- **Easter eggs**: Hidden interactions for discovery -- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches - -## Technical Implementation - -Use appropriate techniques for each animation: - -### Timing & Easing - -**Duration: the 100/300/500 rule.** Timing matters more than easing for "feels right": - -| Duration | Use Case | Examples | -|----------|----------|----------| -| **100–150ms** | Instant feedback | Button press, toggle, color change | -| **200–300ms** | State changes | Menu open, tooltip, hover state | -| **300–500ms** | Layout changes | Accordion, modal, drawer | -| **500–800ms** | Entrance animations | Page load, hero reveal | - -**Easing curves (use these, not CSS defaults):** -```css -/* Recommended: natural deceleration */ ---ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */ ---ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */ ---ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */ - -/* AVOID: feel dated and tacky */ -/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */ -/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */ -``` - -**Exit animations are faster than entrances.** Use ~75% of enter duration. - -### CSS Animations -```css -/* Prefer for simple, declarative animations */ -- transitions for state changes -- @keyframes for complex sequences -- transform and opacity for reliable movement -- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth -``` - -### JavaScript Animation -```javascript -/* Use for complex, interactive animations */ -- Web Animations API for programmatic control -- Framer Motion for React -- GSAP for complex sequences -``` - -### Motion Materials - -Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties. Match material to effect: - -- **Transform / opacity**: movement, press feedback, simple reveals, list choreography -- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances -- **Clip-path / masks**: wipes, reveals, editorial cropping, product-like transitions -- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state -- **Grid-template-rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly - -The hard rule isn't "transform and opacity only." It's: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify smoothness in-browser on target viewports. - -### Performance -- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins) -- **will-change**: Add sparingly for known expensive animations only (e.g. on `:hover` or an `.animating` class), never preemptively across the whole page -- **Scroll triggers**: Use Intersection Observer instead of scroll event listeners; unobserve after the animation fires once -- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate -- **Monitor FPS**: Ensure 60fps on target devices - -### Perceived Performance - -Nobody cares how fast your site *is*, only how fast it feels. The 80ms threshold: anything under ~80ms feels instant because our brains buffer sensory input for that long to synchronize perception. Target this for micro-interactions. - -- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening. -- **Early completion**: Show content progressively, don't wait for everything (progressive images, streaming HTML, skeleton fade-ins). -- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Use for low-stakes actions (likes, follows). Avoid for payments or destructive operations. -- **Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances. -- **Caution**: Too-fast responses can decrease perceived value for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening. - -### Accessibility -```css -@media (prefers-reduced-motion: reduce) { - * { - animation-duration: 0.01ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.01ms !important; - } -} -``` - -**NEVER**: -- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself -- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work -- Use durations over 500ms for feedback (it feels laggy) -- Animate without purpose (every animation needs a reason) -- Ignore `prefers-reduced-motion` (this is an accessibility violation) -- Animate everything (animation fatigue makes interfaces feel exhausting) -- Block interaction during animations unless intentional - -## Verify Quality - -Test animations thoroughly: - -- **Smooth at 60fps**: No jank on target devices -- **Feels natural**: Easing curves feel organic, not robotic -- **Appropriate timing**: Not too fast (jarring) or too slow (laggy) -- **Reduced motion works**: Animations disabled or simplified appropriately -- **Doesn't block**: Users can interact during/after animations -- **Adds value**: Makes interface clearer or more delightful - -When the motion clarifies state instead of decorating it, hand off to `$impeccable polish` for the final pass. +When motion earns its place, hand off to `$impeccable polish` for the final pass. diff --git a/.agents/skills/impeccable/reference/audit.md b/.agents/skills/impeccable/reference/audit.md index 7769a4398..d3483869e 100644 --- a/.agents/skills/impeccable/reference/audit.md +++ b/.agents/skills/impeccable/reference/audit.md @@ -12,6 +12,7 @@ Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the **Check for**: - **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA) +- **Motion sensitivity**: `prefers-reduced-motion` needs an intentional alternative that preserves state change and hierarchy; flag a global `0.01ms` kill that destroys useful feedback, flashing above threshold, and motion that blocks focus, reading, or task completion - **Missing ARIA**: Interactive elements without proper roles, labels, or states - **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps - **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons @@ -52,11 +53,11 @@ Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the **Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets) -### 5. Anti-Patterns (CRITICAL) +### 5. Implementation Integrity (CRITICAL) -Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy). +Run the bundled detector and verify each finding in context. Look for repeated implementation shortcuts, design-system drift, misleading or decorative content, and structure that is interchangeable with an unrelated product. Keep deterministic findings separate from visual judgment and call out false positives. -**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design) +**Score 0-4**: 0=systemic drift, 1=major repeated failures, 2=several verified issues, 3=minor isolated issues, 4=coherent and intentional ## Generate Report @@ -68,13 +69,13 @@ Check against ALL the **DON'T** guidelines from the parent impeccable skill (alr | 2 | Performance | ? | | | 3 | Responsive Design | ? | | | 4 | Theming | ? | | -| 5 | Anti-Patterns | ? | | +| 5 | Implementation Integrity | ? | | | **Total** | | **??/20** | **[Rating band]** | **Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues) -### Anti-Patterns Verdict -**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest. +### Implementation Integrity Verdict +**Start here.** Pass/fail: does the implementation express a coherent product-specific system? Cite verified evidence and detector findings. ### Executive Summary - Audit Health Score: **??/20** ([rating band]) @@ -93,7 +94,7 @@ Tag every issue with **P0-P3 severity**: For each issue, document: - **[P?] Issue name** - **Location**: Component, file, line -- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern +- **Category**: Accessibility / Performance / Theming / Responsive / Implementation Integrity - **Impact**: How it affects users - **WCAG/Standard**: Which standard it violates (if applicable) - **Recommendation**: How to fix it @@ -132,4 +133,3 @@ After presenting the summary, tell the user: - Skip positive findings (celebrate what works) - Forget to prioritize (everything can't be P0) - Report false positives without verification - diff --git a/.agents/skills/impeccable/reference/audit.native.md b/.agents/skills/impeccable/reference/audit.native.md index cc3f01ffd..21bc5586f 100644 --- a/.agents/skills/impeccable/reference/audit.native.md +++ b/.agents/skills/impeccable/reference/audit.native.md @@ -36,7 +36,7 @@ Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the - **Hard-coded colors**: raw hex instead of semantic system colors (iOS) / Material color roles (Android) / design tokens - **Broken dark appearance**: missing dark variants, poor contrast in dark, quick inverts - **Dynamic Color** (Android 12+): no static fallback scheme, or ignored where it fits -- **Off-platform materials**: hand-rolled blur/glassmorphism instead of system materials or tonal elevation +- **Off-platform materials**: hand-rolled visual materials where system materials or tonal elevation are expected **Score 0-4**: 0=Hard-coded everything, 1=Minimal tokens, 2=Partial (tokens exist, inconsistently used), 3=Good (minor hard-coded values), 4=Excellent (semantic throughout, both appearances first-class) @@ -48,7 +48,7 @@ Score against the loaded platform reference(s), including their slop tests. **Ch - **Off-platform navigation**: custom global nav, overloaded tab bars, iOS patterns on Android or vice versa - **Web-shaped controls**: HTML-style buttons, custom toggles, hover-dependent affordances - **Icon drift**: mixed icon sets instead of SF Symbols / Material Symbols -- **AI tells**: the shared absolute bans still apply (AI palette, gradient text, hero metrics) +- **System drift**: repeated shortcuts or decorative patterns that conflict with the product, platform, or established design system **Score 0-4**: 0=Web port (nothing native), 1=Heavy violations (3-4 kinds), 2=Some (1-2 noticeable), 3=Mostly conformant (subtle issues), 4=Fully native (a fluent user trusts every screen) diff --git a/.agents/skills/impeccable/reference/bolder.md b/.agents/skills/impeccable/reference/bolder.md index 6326d409a..9fe39ca59 100644 --- a/.agents/skills/impeccable/reference/bolder.md +++ b/.agents/skills/impeccable/reference/bolder.md @@ -1,120 +1,31 @@ -When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact by making the existing design language more decisive, specific, and committed. +> **Additional context needed**: which section is the target, and what must stay untouched. ---- +"Bolder" is an amplification request, and almost always it is scoped to something that already exists. The surrounding page, its system, and its conventions are the given. Your job is to raise one part to the conviction the rest already implies, without rebuilding anything the brief did not name. The reflex answer, reaching for more effects, is the opposite of bold; reject it first. -## Register +## Scope is sovereign -Brand: "bolder" means distinctive. Express a stronger point of view through hierarchy, pacing, proportion, copy, evidence, and one committed visual idea. +"Everything else stays" is a literal instruction. Touch only the named target. Do not restyle its neighbors, do not migrate the page to a new idea, do not add colors, fonts, radii, shadows, or system primitives the surface does not already own. If the existing system genuinely cannot express the direction, stop and STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. before expanding it, naming the exact addition and the job it would do. -Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, sharper information density, and more decisive prioritization. The amplification is in clarity, not drama. +## Why it reads flat ---- +A section usually reads flat for reasons its neighbors have already solved. Look at what the rest of the page does that this section does not: the display type at full strength, the structural devices that carry meaning, the signature motif, the density and pacing. A flat section is typically one that quietly opts out of the system's own strongest moves. The most reliable bolder pass brings the target up to the expressive level its neighbors already reach, in the system's own vocabulary rather than a new one. -## Assess Current State +## The amplification -Analyze what makes the design feel too safe or boring: +- **Amplify what the system already owns.** Reuse its motif and its type scale at full strength, turned up for this section rather than invented for it. The bolder version should look more like the same brand, not less. +- **Keep content true.** Existing claims are part of the scope: preserve them unless the user supplies replacements. If real evidence is essential to the direction but absent, ask for it. +- **Commit, then clarify.** Half-measures read as noise. Make the one decisive move completely, then quiet everything around it so the move is legible. If every element got louder, the section got flatter. +- **Give it its own rhythm.** The target should read as a peak in the scroll, a shift in density or pace from what surrounds it, not simply more of the same. -1. **Identify weakness sources**: - - **Generic choices**: The page could belong to any product in the category. - - **Timid scale**: Everything is medium-sized with no clear lead. - - **Low contrast**: Important and supporting elements have similar visual weight. - - **Static**: The surface has no meaningful moment of emphasis. - - **Predictable**: The composition follows a default pattern without a point of view. - - **Flat hierarchy**: Nothing stands out or commands attention. +## The skeleton test -2. **Understand the context**: - - What is the brand personality? - - What is the purpose of this surface? - - Who is the audience? - - What design system, tokens, components, and visual conventions already exist? +Strip the copy out of your planned section and study the bare structure. Does the skeleton still say what this section is and why it matters, through hierarchy and the system's devices alone? If it only works once the words return, the boldness is in the text size, not the design. A placeholder for an image or artifact names a job, an anchor and a piece of evidence, not a cue to drop in a decorative photo; fill that job with whatever the subject actually has. -If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. +## Before you finish -**CRITICAL**: "Bolder" does not mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random noise. +- Everything outside the named target is unchanged. +- No new color, font, or system primitive appeared without being asked for. +- The conventions the section carried, including anything that drives an action, still work the same way. +- The section is unmistakably the same brand, only more sure of itself. -**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects." - -## Design-System Lock - -If the project has `DESIGN.md`, tokens, theme variables, or established component styles, treat that system as the boundary. Make the existing language stronger before adding new language. - -Do not invent new colors, gradients, radii, shadows, fonts, decorative backgrounds, or effects just because the request says "bolder." A bolder pass should usually change emphasis, proportion, rhythm, density, contrast, copy, artifact specificity, and layout relationships while staying inside the documented system. - -If the existing system is genuinely too limited to express the bolder direction, stop and ask the user before expanding it. Name the exact additions, the role each would play, and why the current system cannot do the job. If the user approves expansion, update the design system or tokens alongside the implementation. - -## Plan Amplification - -Create a strategy to increase impact while maintaining coherence: - -- **Focal point**: Pick one thing the viewer should remember, then make the rest support it. -- **System levers**: Identify which existing tokens, components, layout patterns, and copy structures can carry more weight. -- **Risk budget**: Decide how far the surface can push while still feeling like the same product or brand. -- **Hierarchy amplification**: Increase contrast between primary, secondary, and tertiary content instead of making every element louder. - -**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration. - -## Amplify the Design - -Systematically increase impact through intention, not a menu of effects: - -### Typography Amplification -- Strengthen the existing type hierarchy before changing typefaces. -- Make important text meaningfully more dominant, and make supporting text quieter. -- Use weight, measure, spacing, and line breaks to sharpen the point of view. -- Add or replace fonts only after user-approved design-system expansion. - -### Color Amplification -- Use the existing palette more decisively before adding colors. -- Shift the proportion, placement, and contrast of documented colors to clarify meaning. -- Treat any new color, gradient, or tint ramp as a design-system expansion that requires user approval. -- Keep color tied to hierarchy, state, or brand meaning; do not use it as surface decoration. - -### Spatial Amplification -- Change proportion, density, alignment, and sequencing so the composition has a stronger point of view. -- Create clearer contrast between dense evidence and open breathing room. -- Let layout express priority and narrative order before adding ornament. -- Preserve responsive behavior and avoid text overflow at every breakpoint. - -### Surface Amplification -- Use existing surface, border, radius, and shadow rules more deliberately. -- Remove timid half-measures: either give an element a clear role or simplify it. -- Add texture, depth, illustration, or decorative treatments only when already established by the system or explicitly approved. -- Make real product artifacts, imagery, data, or copy carry attention before reaching for effects. - -### Motion & Animation -- Design one meaningful moment of emphasis when motion genuinely supports the point. -- Make interaction feedback feel more decisive without becoming distracting. -- Keep transitions smooth and intentional. -- **Bolder != scroll-fade-rise on every section.** That's the saturated AI default, the opposite of bold. - -### Composition Boldness -- Make the dominant idea unmistakable. -- Use layout tension, sequencing, contrast, and restraint to create a stronger read. -- Let the page's structure communicate priority before adding decorative layers. -- If every element is louder, the composition is not bolder; it is flatter. - -**NEVER**: -- Add undocumented design-system primitives without user approval -- Add effects randomly without purpose -- Hide weak hierarchy behind decoration -- Sacrifice readability for aesthetics -- Make everything bold; contrast is the point -- Ignore accessibility -- Overwhelm with motion -- Copy trendy aesthetics blindly - -## Verify Quality - -Ensure amplification maintains usability and coherence: - -- **System-faithful**: Did the pass make the existing design language stronger before adding anything new? -- **No undocumented drift**: Are new colors, gradients, shadows, radii, fonts, and effects either absent or explicitly approved and documented? -- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over. -- **Still functional**: Can users accomplish tasks without distraction? -- **Coherent**: Does everything feel intentional and unified? -- **Memorable**: Will users remember this experience for the intended reason? -- **Performant and accessible**: Does the result stay fast, readable, responsive, and WCAG-conscious? - -**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects." - -When the result feels right, hand off to `$impeccable polish` for the final pass. +When the target holds its own without pulling the page apart, hand off to `$impeccable polish` for the final pass. diff --git a/.agents/skills/impeccable/reference/brand.md b/.agents/skills/impeccable/reference/brand.md deleted file mode 100644 index a461c5484..000000000 --- a/.agents/skills/impeccable/reference/brand.md +++ /dev/null @@ -1,108 +0,0 @@ -# Brand register - -When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made. - -The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look. - -## The brand slop test - -If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?" - -Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home. - -**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register. - -Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart. - -## Typography - -### Font selection procedure - -Every project. Never skip. - -1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words. -2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture. -3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy." -4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over. - -### Reflex-reject list - -Training-data defaults. Ban list. Look further: - -Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif - -### Reflex-reject aesthetic lanes - -Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further. - -- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery. - -(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.) - -The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md). - -### Pairing and voice - -Distinctive + refined is the goal. The specific shape depends on the brand, not on the brand's category. A category ("restaurant", "dev tool", "magazine", "fintech") is not a recipe; treating it as one is the first-order reflex SKILL.md warns against. - -Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair. - -### Scale - -Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted. - -Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room. - -## Color - -Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register. - -- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige. -- Palette IS voice. A calm brand and a restless brand should not share palette mechanics. -- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit. -- Don't converge across projects. Each brand surface differentiates from the last. -- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette. - -## Layout - -- Asymmetric compositions are one option. Break the grid intentionally for emphasis. -- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings. -- For image-led briefs (hotels, restaurants, magazines, photography), full-bleed hero imagery with overlaid menu and centered headline is a canonical move; let the photograph be the design. -- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness. - -## Imagery - -Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo. - -**When the brief implies imagery, you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy. - -- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `
` placeholders. -- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel". -- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one. -- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish". - -"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode. - -## Motion - -- One well-orchestrated page-load beats scattered micro-interactions, when the brand invites it. Some brands skip entrance motion entirely; the restraint is the voice. - -## Brand bans (on top of the shared absolute bans) - -- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume. -- Large rounded-corner icons above every heading. Screams template. -- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.) -- All-caps body copy. Reserve caps for short labels and headings. -- Timid palettes and average layouts. Safe = invisible. -- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs. -- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic. -- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system. - -## Brand permissions - -Brand can afford things product can't. Take them. - -- Ambitious first-load motion. Reveals and typographic choreography that earn their place; not fade-on-scroll for every section. -- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing. -- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics. -- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment. diff --git a/.agents/skills/impeccable/reference/clarify.md b/.agents/skills/impeccable/reference/clarify.md index 123f294d1..4506a31c9 100644 --- a/.agents/skills/impeccable/reference/clarify.md +++ b/.agents/skills/impeccable/reference/clarify.md @@ -1,288 +1,94 @@ -> **Additional context needed**: audience technical level and users' mental state in context. +> **Additional context needed**: audience knowledge and emotional state. -Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task. +Rewrite unclear interface text so users understand what happened, what matters, and what to do next. Preserve factual meaning, product terminology, and brand voice. +## Audit the language ---- +Read the entire interaction path, not isolated strings. Identify: -## Assess Current Copy +- ambiguous nouns, verbs, and actions; +- internal jargon or assumed knowledge; +- vague labels, outcomes, and system states; +- missing consequences, recovery, or timing; +- inconsistent terminology and capitalization; +- redundant headings, intros, helper text, and confirmations; +- text that breaks at realistic widths or in translation; +- tone that ignores stress, risk, success, or urgency. -Identify what makes the text unclear or ineffective: +Infer audience and task from product context and surrounding UI. Ask before changing factual claims, legal meaning, or a term that may be domain-specific. -1. **Find clarity problems**: - - **Jargon**: Technical terms users won't understand - - **Ambiguity**: Multiple interpretations possible - - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file" - - **Length**: Too wordy or too terse - - **Assumptions**: Assuming user knowledge they don't have - - **Missing context**: Users don't know what to do or why - - **Tone mismatch**: Too formal, too casual, or inappropriate for situation +## Set the message hierarchy -2. **Understand the context**: - - Who's the audience? (Technical? General? First-time users?) - - What's the user's mental state? (Stressed during error? Confident during success?) - - What's the action? (What do we want users to do?) - - What's the constraint? (Character limits? Space limitations?) +For each state, decide: -**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets. +1. the one fact the user needs now; +2. the action available next; +3. supporting context that changes the decision; +4. the appropriate tone for this moment. -## Plan Copy Improvements +Say each idea once. If the heading already explains the state, the introduction should add new information or disappear. -Create a strategy for clearer communication: +## Rewrite by function -- **Primary message**: What's the ONE thing users need to know? -- **Action needed**: What should users do next (if anything)? -- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?) -- **Constraints**: Length limits, brand voice, localization considerations +### Actions and navigation -**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words. +Use a specific verb and object when the outcome is not already obvious. Labels should describe what will happen, not the gesture used to trigger it. Keep the same noun and verb for the same concept throughout the product. -## Improve Copy Systematically +For destructive actions, name the object and consequence. Prefer undo over confirmation when recovery is safe. When confirmation is necessary, name the action on both the message and button instead of using `Yes`, `No`, `OK`, or `Submit`. -Refine text across these common areas: +### Forms -### Error Messages -**Bad**: "Error 403: Forbidden" -**Good**: "You don't have permission to view this page. Contact your admin for access." +Use persistent labels; placeholders are examples, not labels. Put format and eligibility requirements before submission. Explain why information is requested only when it is not obvious. Required and optional treatment should be consistent. -**Bad**: "Invalid input" -**Good**: "Email addresses need an @ symbol. Try: name@example.com" +Validation says what needs attention and how to correct it without blaming the user. Keep related instructions near the field and announce errors accessibly. -**Principles**: -- Explain what went wrong in plain language -- Suggest how to fix it -- Don't blame the user -- Include examples when helpful -- Link to help/support if applicable - -### Form Labels & Instructions -**Bad**: "DOB (MM/DD/YYYY)" -**Good**: "Date of birth" (with placeholder showing format) - -**Bad**: "Enter value here" -**Good**: "Your email address" or "Company name" - -**Principles**: -- Use clear, specific labels (not generic placeholders) -- Show format expectations with examples -- Explain why you're asking (when not obvious) -- Put instructions before the field, not after -- Keep required field indicators clear - -### Button & CTA Text -**Bad**: "Click here" | "Submit" | "OK" -**Good**: "Create account" | "Save changes" | "Got it, thanks" +### Errors and permissions -**Principles**: -- Describe the action specifically -- Use active voice (verb + noun) -- Match user's mental model -- Be specific ("Save" is better than "OK") +An actionable error answers: -### Help Text & Tooltips -**Bad**: "This is the username field" -**Good**: "Choose a username. You can change this later in Settings." +1. what failed; +2. why, when known and useful; +3. how to recover or what alternative remains. -**Principles**: -- Add value (don't just repeat the label) -- Answer the implicit question ("What is this?" or "Why do you need this?") -- Keep it brief but complete -- Link to detailed docs if needed +Do not expose internal codes as the primary message. Do not promise a cause or resolution the system cannot know. Treat privacy, payment, deletion, access loss, and blocked work seriously; warmth is welcome, jokes are not. -### Empty States -**Bad**: "No items" -**Good**: "No projects yet. Create your first project to get started." +### Loading, empty, and success states -**Principles**: -- Explain why it's empty (if not obvious) -- Show next action clearly -- Make it welcoming, not dead-end +Loading text names the real operation and sets an honest expectation when the wait is meaningful. Show determinate progress when available; never invent progress. -### Success Messages -**Bad**: "Success" -**Good**: "Settings saved! Your changes will take effect immediately." +An empty state distinguishes first use, no results, filters, permissions, and failure. Explain the state and provide the next useful action. -**Principles**: -- Confirm what happened -- Explain what happens next (if relevant) -- Be brief but complete -- Match the user's emotional moment (celebrate big wins) - -### Loading States -**Bad**: "Loading..." (for 30+ seconds) -**Good**: "Analyzing your data... this usually takes 30-60 seconds" - -**Principles**: -- Set expectations (how long?) -- Explain what's happening (when it's not obvious) -- Show progress when possible -- Offer escape hatch if appropriate ("Cancel") +Success confirms the completed outcome and mentions the next consequence only when it changes what the user should do. Routine success should be brief. -### Confirmation Dialogs -**Bad**: "Are you sure?" -**Good**: "Delete 'Project Alpha'? This can't be undone." +### Help and instructional text -**Principles**: -- State the specific action -- Explain consequences (especially for destructive actions) -- Use clear button labels ("Delete project" not "Yes") -- Don't overuse confirmations (only for risky actions) +Helper text answers an implicit question instead of restating the control. Use progressive disclosure for uncommon detail. Link text must make sense out of context; icon-only controls need accessible names. -### Navigation & Wayfinding -**Bad**: Generic labels like "Items" | "Things" | "Stuff" -**Good**: Specific labels like "Your projects" | "Team members" | "Settings" +## Voice, accessibility, and localization -**Principles**: -- Be specific and descriptive -- Use language users understand (not internal jargon) -- Make hierarchy clear -- Consider information scent (breadcrumbs, current location) +Voice stays consistent; tone adapts to the moment. Use plain language without flattening terminology the audience genuinely knows. -## Apply Clarity Principles +- Write complete translatable messages rather than concatenated fragments. +- Keep variables and numbers structured so translators can reorder them. +- Allow expansion instead of abbreviating prematurely. +- Make alt text convey the image's information; use empty alt for decoration. +- Keep screen-reader names aligned with visible labels and outcomes. +- Do not rely on punctuation, color, or iconography to carry the message alone. -Every piece of copy should follow these rules: +Maintain a short terminology glossary when inconsistency spans the product. Do not vary words for literary effect in an interface. -1. **Be specific**: "Enter email" not "Enter value" -2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity) -3. **Be active**: "Save changes" not "Changes will be saved" -4. **Be human**: "Oops, something went wrong" not "System error encountered" -5. **Tell users what to do**, not just what happened -6. **Be consistent**: Use same terms throughout (don't vary for variety) +## Verify -**NEVER**: -- Use jargon without explanation -- Blame users ("You made an error" → "This field is required") -- Be vague ("Something went wrong" without explanation) -- Use passive voice unnecessarily -- Write overly long explanations (be concise) -- Use humor for errors (be empathetic instead) -- Assume technical knowledge -- Vary terminology (pick one term and stick with it) -- Repeat information (headers restating intros, redundant explanations) -- Use placeholders as the only labels (they disappear when users type) +Read the flow in context and test: -## Verify Improvements +- comprehension without hidden product knowledge; +- actionability at errors, empty states, and decision points; +- factual accuracy and consistent terminology; +- scanability at target widths and 200% zoom; +- long names, localization expansion, pluralization, and dynamic values; +- accessible names and announced state changes; +- tone appropriate to consequence and emotional context. -Test that copy improvements work: +The final copy is as short as it can be without removing meaning or recovery. -- **Comprehension**: Can users understand without context? -- **Actionability**: Do users know what to do next? -- **Brevity**: Is it as short as possible while remaining clear? -- **Consistency**: Does it match terminology elsewhere? -- **Tone**: Is it appropriate for the situation? - -When the copy reads cleanly, hand off to `$impeccable polish` for the final pass. - ---- - -## Reference Material - -The sections below were previously `ux-writing.md` and live inline now so the clarify flow has its deep UX-writing reference in one place. - -### UX Writing - -#### The Button Label Problem - -**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns: - -| Bad | Good | Why | -|-----|------|-----| -| OK | Save changes | Says what will happen | -| Submit | Create account | Outcome-focused | -| Yes | Delete message | Confirms the action | -| Cancel | Keep editing | Clarifies what "cancel" means | -| Click here | Download PDF | Describes the destination | - -**For destructive actions**, name the destruction: -- "Delete" not "Remove" (delete is permanent, remove implies recoverable) -- "Delete 5 items" not "Delete selected" (show the count) - -#### Error Messages: The Formula - -Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input". - -##### Error Message Templates - -| Situation | Template | -|-----------|----------| -| **Format error** | "[Field] needs to be [format]. Example: [example]" | -| **Missing required** | "Please enter [what's missing]" | -| **Permission denied** | "You don't have access to [thing]. [What to do instead]" | -| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." | -| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" | - -##### Don't Blame the User - -Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date". - -#### Empty States Are Opportunities - -Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items". - -#### Voice vs Tone - -**Voice** is your brand's personality, consistent everywhere. -**Tone** adapts to the moment. - -| Moment | Tone Shift | -|--------|------------| -| Success | Celebratory, brief: "Done! Your changes are live." | -| Error | Empathetic, helpful: "That didn't work. Here's what to try..." | -| Loading | Reassuring: "Saving your work..." | -| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." | - -**Never use humor for errors.** Users are already frustrated. Be helpful, not cute. - -#### Writing for Accessibility - -**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context. - -#### Writing for Translation - -##### Plan for Expansion - -German text is ~30% longer than English. Allocate space: - -| Language | Expansion | -|----------|-----------| -| German | +30% | -| French | +20% | -| Finnish | +30-40% | -| Chinese | -30% (fewer chars, but same width) | - -##### Translation-Friendly Patterns - -Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear. - -#### Consistency: The Terminology Problem - -Pick one term and stick with it: - -| Inconsistent | Consistent | -|--------------|------------| -| Delete / Remove / Trash | Delete | -| Settings / Preferences / Options | Settings | -| Sign in / Log in / Enter | Sign in | -| Create / Add / New | Create | - -Build a terminology glossary and enforce it. Variety creates confusion. - -#### Avoid Redundant Copy - -If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well. - -#### Loading States - -Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress. - -#### Confirmation Dialogs: Use Sparingly - -Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No"). - -#### Form Instructions - -Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking. - ---- - -**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors. +When the language reads cleanly, hand off to `$impeccable polish` for the final pass. diff --git a/.agents/skills/impeccable/reference/codex.md b/.agents/skills/impeccable/reference/codex.md deleted file mode 100644 index f174e1f3c..000000000 --- a/.agents/skills/impeccable/reference/codex.md +++ /dev/null @@ -1,105 +0,0 @@ -# Codex: Visual Direction & Asset Production - -This file is loaded by `$impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose. - -Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief. - -### Four stop points before code - -Steps A through D each end with the user. Do not advance past any of them on your own read of the situation. - -1. **STOP after Step A questions.** Wait for answers. -2. **STOP after Step B palette generation.** Wait for "confirm palette." -3. **STOP after Step C mocks.** Wait for direction approval or delegation. -4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code. - -Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it. - -## Step A: Explore Directions with the User - -Before generating anything, run a brief direction conversation grounded in the shape brief. - -**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session. - -Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions: - -- "Brief says 'specimen-page restraint.' Are we closer to a quiet typographic page or a wider editorial spread with hero imagery?" -- "Palette strategy from shape was 'Committed.' Which one color carries the surface (a brand-driven pick rather than a default warm-or-cool framing)? (And no, the answer isn't a cream/sand body bg; that's the saturated AI default.)" - -**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded. - -## Step B: Generate the Brand Palette First - -Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass. - -Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream. - -Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?" - -**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream. - -## Step C: Generate 1-3 Visual Mocks Against the Palette - -Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif. - -- Brand work: push visual identity, composition, mood, and signature motifs. -- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure. -- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero. - -Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything. - -## Step D: Approval Loop - -Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates. - -**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste. - -Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation. - -## Step E: Mock Fidelity Inventory - -Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission. - -Common ingredients to inventory: - -- Hero silhouette and dominant composition -- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.) -- Nav and primary CTA treatment -- Section sequence, especially the second fold -- Image-native content the concept depends on -- Typography, density, color/material treatment, motion cues - -Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong. - -If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation. - -Don't substitute a different hero composition or visual driver post-approval without user sign-off. - -## Step F: Asset Slicing via the Asset Producer - -Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline. - -Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask: - -```text -Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step? -``` - -Pass to the agent: - -- Approved mock path or screenshot reference -- Crop paths or a contact sheet with crop ids -- Output directory -- Required dimensions, format, transparency needs -- Avoid list -- Notes on what should remain semantic HTML/CSS/SVG instead of raster - -Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread. - -Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode. - -Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content. - -## After This File - -Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote. diff --git a/.agents/skills/impeccable/reference/colorize.md b/.agents/skills/impeccable/reference/colorize.md index 08a3862d4..02fa661ef 100644 --- a/.agents/skills/impeccable/reference/colorize.md +++ b/.agents/skills/impeccable/reference/colorize.md @@ -1,257 +1,86 @@ > **Additional context needed**: existing brand colors. -Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit. +Introduce color as hierarchy, meaning, and atmosphere. Preserve confirmed brand and semantic conventions; do not replace a visual world under the guise of colorizing it. --- -## Register +## Visitor mode -Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it. +- **Persuade + Experience:** color may carry the voice and own large regions when the selected world calls for it. +- **Operate + Read:** color primarily encodes action, selection, status, wayfinding, and reading hierarchy. Rarity gives an accent force. -Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen. +## Audit before choosing ---- - -## Assess Color Opportunity - -Analyze the current state and identify opportunities: - -1. **Understand current state**: - - **Color absence**: Pure grayscale? Limited neutrals? One timid accent? - - **Missed opportunities**: Where could color add meaning, hierarchy, or delight? - - **Context**: What's appropriate for this domain and audience? - - **Brand**: Are there existing brand colors we should use? - -2. **Identify where color adds value**: - - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue) - - **Hierarchy**: Drawing attention to important elements - - **Categorization**: Different sections, types, or states - - **Emotional tone**: Warmth, energy, trust, creativity - - **Wayfinding**: Helping users navigate and understand structure - - **Delight**: Moments of visual interest and personality - -If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. - -**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose. - -## Plan Color Strategy - -Create a purposeful color introduction plan: - -- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals) -- **Dominant color**: Which color owns 60% of colored elements? -- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%) -- **Application strategy**: Where does each color appear and why? - -**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more. - -## Introduce Color Strategically - -Add color systematically across these dimensions: - -### Semantic Color -- **State indicators**: - - Success: Green tones (emerald, forest, mint) - - Error: Red/pink tones (rose, crimson, coral) - - Warning: Orange/amber tones - - Info: Blue tones (sky, ocean, indigo) - - Neutral: Gray/slate for inactive states - -- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.) -- **Progress indicators**: Colored bars, rings, or charts showing completion or health +Read DESIGN.md, tokens, assets, current themes, and representative states. Identify: -### Accent Color Application -- **Primary actions**: Color the most important buttons/CTAs -- **Links**: Add color to clickable text (maintain accessibility) -- **Icons**: Colorize key icons for recognition and personality -- **Headers/titles**: Add color to section headers or key labels -- **Hover states**: Introduce color on interaction +- which colors are confirmed brand commitments; +- current surface, text, action, and semantic roles; +- places where grayscale obscures hierarchy or state; +- contrast failures and color-only communication; +- light/dark or data-visualization requirements; +- whether the task asks for more color or a new identity. -### Background & Surfaces -- **Tinted backgrounds**: If you replace pure gray, tint toward the brand hue, not toward a generic-warm-or-cool pair. The default-warm-tint (`oklch(97% 0.01 60)` and its neighbors) is now the AI cream/sand giveaway. Be specific to the brand or stay neutral. -- **Colored sections**: Use subtle background colors to separate areas -- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue) -- **Cards & surfaces**: Tint cards or surfaces toward the brand, not "for warmth" by reflex +If a new identity is required, use [new-work.md](new-work.md). Ask only when a binding brand decision cannot be inferred. -**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales. +## Choose a strategy -### Data Visualization -- **Charts & graphs**: Use color to encode categories or values -- **Heatmaps**: Color intensity shows density or importance -- **Comparison**: Color coding for different datasets or timeframes +Name the intended emotional temperature, dominant relationship, contrast range, and color dosage before editing. The strategy may be restrained or immersive; it must follow the brief and selected world rather than a fixed percentage rule. -### Borders & Accents -- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`) -- **Underlines**: Color underlines for emphasis or active states -- **Dividers**: Subtle colored dividers instead of gray lines -- **Focus rings**: Colored focus indicators matching brand -- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe +Build roles, not a bag of swatches: -**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe. +- canvas and elevated surfaces; +- primary and secondary text; +- action, focus, and selection; +- borders and separators; +- success, warning, error, and information; +- data categories or scales when needed. -### Typography Color -- **Colored headings**: Use brand colors for section headings (maintain contrast) -- **Highlight text**: Color for emphasis or categories -- **Labels & tags**: Small colored labels for metadata or categories +Use the project's existing color space. For a new web palette, prefer OKLCH because lightness and chroma can be adjusted predictably. Choose hue from product meaning and visual direction, never from a default category association. -### Decorative Elements -- **Illustrations**: Add colored illustrations or icons -- **Shapes**: Geometric shapes in brand colors as background elements -- **Gradients**: Colorful gradient overlays or mesh backgrounds -- **Blobs/organic shapes**: Soft colored shapes for visual interest +## Apply at system scale -## Balance & Refinement +- Let the strongest color own a deliberate region or role instead of scattering tiny accents. +- Keep the primary action easy to find; do not spend its color on decoration. +- Tint neutrals only when the brand hue genuinely creates cohesion. Neutral gray is valid when it serves the world. +- On colored surfaces, derive secondary text from the foreground or surface hue rather than using washed-out generic gray. +- Keep semantic meanings consistent, but respect platform and domain conventions instead of assuming fixed hues. +- For data, use distinct lightness, chroma, shape, label, or pattern so color is not the only code. +- In dark mode, design surface elevation and contrast explicitly; do not invert the light theme mechanically. +- Define primitive values and semantic tokens when the project has a token system. Theme changes should normally remap semantic roles. -Ensure color addition improves rather than overwhelms: +Decoration without a relationship to hierarchy, state, content, or the visual world is not a color strategy. -### Maintain Hierarchy -- **Dominant color** (60%): Primary brand color or most used accent -- **Secondary color** (30%): Supporting color for variety -- **Accent color** (10%): High contrast for key moments -- **Neutrals** (remaining): Gray/black/white for structure +## Contrast and perception -### Accessibility -- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components) -- **Don't rely on color alone**: Use icons, labels, or patterns alongside color -- **Test for color blindness**: Verify red/green combinations work for all users +Verify computed foreground/background pairs: -### Cohesion -- **Consistent palette**: Use colors from defined palette, not arbitrary choices -- **Systematic application**: Same color meanings throughout (green always = success) -- **Temperature consistency**: Warm palette stays warm, cool stays cool +| Content | WCAG AA minimum | +|---|---| +| body text | 4.5:1 | +| large text | 3:1 | +| controls, icons, focus indicators | 3:1 | -**NEVER**: -- Use every color in the rainbow (choose 2-4 colors beyond neutrals) -- Apply color randomly without semantic meaning -- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead -- Violate WCAG contrast requirements -- Use color as the only indicator (accessibility issue) -- Make everything colorful (defeats the purpose) -- Default to purple-blue gradients (AI slop aesthetic) +Do not rely on eyesight alone. Check interactive states, overlays, text on images, disabled content, and both themes. Simulate common vision deficiencies. Information conveyed by color also needs text, shape, iconography, or position. -## Verify Color Addition +When deriving OKLCH ramps, vary lightness and reduce chroma near white and black. Do not keep high chroma at extreme lightness merely to make the math uniform. Prefer explicit colors over chains of translucent overlays when alpha would make contrast context-dependent. -Test that colorization improves the experience: +## Verify -- **Better hierarchy**: Does color guide attention appropriately? -- **Clearer meaning**: Does color help users understand states/categories? -- **More engaging**: Does the interface feel warmer and more inviting? -- **Still accessible**: Do all color combinations meet WCAG standards? -- **Not overwhelming**: Is color balanced and purposeful? +- Every color has a stable role or a world-specific atmospheric purpose. +- Attention lands on the intended action, content, or state. +- The palette works across quiet, dense, interactive, error, and empty states. +- Light and dark themes are each composed, not mechanically inverted. +- Contrast and non-color cues pass in all relevant states. +- The result is recognizably this product, not a generic “colorful” treatment. When the palette earns its place, hand off to `$impeccable polish` for the final pass. ## Live-mode signature params -When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage. +When invoked from live mode, every variant declares a `color-amount` parameter. Author CSS against `var(--p-color-amount, 0.5)` so the user can move from neutral to the variant's full color strategy without regeneration. ```json {"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"} ``` -Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract. - ---- - -## Reference Material - -The sections below were previously `color-and-contrast.md` and live inline now so the colorize flow has its deep color reference in one place. - -### Color & Contrast - -#### Color Spaces: Use OKLCH - -**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark. - -The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish. - -The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand. - -#### Building Functional Palettes - -##### Tinted Neutrals - -**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces. - -The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette. - -**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects. - -##### Palette Structure - -A complete system needs: - -| Role | Purpose | Example | -|------|---------|---------| -| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades | -| **Neutral** | Text, backgrounds, borders | 9-11 shade scale | -| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each | -| **Surface** | Cards, modals, overlays | 2-3 elevation levels | - -**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise. - -##### The 60-30-10 Rule (Applied Correctly) - -This rule is about **visual weight**, not pixel count: - -- **60%**: Neutral backgrounds, white space, base surfaces -- **30%**: Secondary colors: text, borders, inactive states -- **10%**: Accent: CTAs, highlights, focus states - -The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power. - -#### Contrast & Accessibility - -##### WCAG Requirements - -| Content Type | AA Minimum | AAA Target | -|--------------|------------|------------| -| Body text | 4.5:1 | 7:1 | -| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 | -| UI components, icons | 3:1 | 4.5:1 | -| Non-essential decorations | None | None | - -##### Dangerous Color Combinations - -These commonly fail contrast or cause readability issues: - -- Light gray text on white (the #1 accessibility fail) -- Red text on green background (or vice versa): 8% of men can't distinguish these -- Blue text on red background (vibrates visually) -- Yellow text on white (almost always fails) -- Thin light text on images (unpredictable contrast) - -##### Testing - -Don't trust your eyes. Use tools: - -- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/) -- Browser DevTools → Rendering → Emulate vision deficiencies -- [Polypane](https://polypane.app/) for real-time testing - -#### Theming: Light & Dark Mode - -##### Dark Mode Is Not Inverted Light Mode - -You can't just swap colors. Dark mode requires different design decisions: - -| Light Mode | Dark Mode | -|------------|-----------| -| Shadows for depth | Lighter surfaces for depth (no shadows) | -| Dark text on light | Light text on dark (reduce font weight) | -| Vibrant accents | Desaturate accents slightly | -| White backgrounds | Either pure black or a deep surface that fits the brand (a brand-tinted near-black at oklch 12-18% works too) | - -In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light. - -##### Token Hierarchy - -Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same. - -#### Alpha Is A Design Smell - -Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed. - ---- - -**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Skipping color blindness testing (8% of men affected). +Add at most two variant-specific parameters, such as palette, temperature, or tint behavior. Follow [live.md](live.md)'s parameter contract. diff --git a/.agents/skills/impeccable/reference/craft-floor.md b/.agents/skills/impeccable/reference/craft-floor.md new file mode 100644 index 000000000..97288e560 --- /dev/null +++ b/.agents/skills/impeccable/reference/craft-floor.md @@ -0,0 +1,45 @@ +# Craft floor + +Load this after the direction is settled, and build without announcing the checklist. A pinned brief or the committed visual world overrides anything here; your own habit does not. When the design hook is active it already enforces the mechanical checks below as you edit: act on its findings instead of re-auditing each rule. + +## Verify + +Each of these is a check on the built result, not an intention. + +- **Contrast:** body and placeholder text ≥4.5:1, large text ≥3:1. On colored surfaces tint secondary text from that hue or the foreground; never gray. +- **Depth:** shadows carry an offset and a soft blur. A zero-offset colored halo is decoration. +- **Spacing:** tight groups, generous separation, more space above a heading than below it. Read the computed values. +- **Type:** body measure 65–75ch, display max 6rem, tracking floor -0.04em, balanced headings, obvious scale and weight steps. Run the real copy at every breakpoint and fix what overflows. +- **Motion:** one authored moment, not scattered effects and not one identical entrance on every section. Exponential ease-out from an already-visible default. Reach past transform and opacity: blur, backdrop-filter, clip-path, mask, and shadow belong to the palette when they stay smooth. +- **States:** hover, disabled, loading, error, empty. Plus real content, working controls, responsive composition, keyboard focus. +- **Copy:** the product's own language. Controls name their action; errors name the problem and the recovery. +- **Coverage:** every brief requirement present and findable within seconds. + +## Refuse + +These are the category's defaults, not bans: the brief's own words can earn any of them. Reaching for one when the axis is free means you were not deciding; recognizing that means rewriting the element, not softening it. + +Page scaffolds: + +- Same-size cards of icon plus heading plus text as the page structure. Cards are the lazy container; nested cards are always wrong. +- The hero-metric template: big number, small label, supporting stats, accent. +- A tracked uppercase eyebrow over every section. One named kicker is a system; an eyebrow everywhere is grammar you did not choose. +- Section numbers (01 / 02 / 03) unless the sequence itself carries information the reader needs. +- A modal for a task that needs neither interruption nor protected focus. + +Surface habits: + +- Gradient text. Emphasis comes from weight or size. +- Glass and blur as decoration rather than as a specific effect. +- A colored `border-left` or `border-right` above 1px on cards, list items, callouts, or alerts. +- Sparklines, progress rings, and soft-shadowed rounded rectangles standing in for content. +- Monospace as a costume for "technical" rather than for code, data, or measurement. +- Light or dark picked by category. Pick it from the use scene: who, where, under what ambient light. + +- Tracking stops at -0.04em. -0.02 to -0.03em usually reads better. +- Declare elevation once, border or shadow. A 1px border under a wide soft shadow is the ghost card. Card radii stay at 12–16px; pills are for small controls. +- Real illustration or none. Sketch-style SVG scenes, `loose-sketch` / `doodle` class names, and `feTurbulence` grain read as amateur. +- Backgrounds are surfaces, textured only from the subject's world. `repeating-linear-gradient` stripes and two-axis grid overlays need an actual canvas, map, blueprint, or measuring tool under them. +- Claims and configuration come from supplied truth; label illustrative values honestly. Naming a concept and then ironizing it is not a claim. + +The floor holds the mechanics; it never picks the direction. With every check green, spend the page on the committed world, and when torn between refined and committed, commit. diff --git a/.agents/skills/impeccable/reference/craft.md b/.agents/skills/impeccable/reference/craft.md index 4adbc2b1f..dbbc9402c 100644 --- a/.agents/skills/impeccable/reference/craft.md +++ b/.agents/skills/impeccable/reference/craft.md @@ -1,123 +1,5 @@ -# Craft Flow +# Craft (deprecated alias) -Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar. +`craft` is a deprecated alias for an ordinary request to make new visual work. It adds no setup, interview, checkpoint, tool, or quality behavior. Apply SKILL.md's normal routing: create missing PRODUCT.md through [init.md](init.md), then follow [new-work.md](new-work.md) for visual authority, world and surface decisions, implementation, and finish. -Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief. - -Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong. - -### Gates: do not compress - -Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is: - -1. **Shape brief confirmed** (Step 1) -2. **Direction questions answered** (codex.md Step A) -3. **Palette confirmed** (codex.md Step B) -4. **One mock direction approved or delegated** (codex.md Step D) - -You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow. - -When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code. - -## Step 0: Project Foundation - -Before shape, before code: figure out what kind of project you're working in. - -Look at the working directory. Run `ls`. Check for: - -- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it. -- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it. -- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set. - -If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief: - -```text -What should this be built on? - - Astro (default for content-led brand sites, landing pages, marketing surfaces) - - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity) - - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment) -``` - -Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task. - -## Step 1: Shape the Design - -Run $impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction. - -Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code. - -If the user already supplied a confirmed brief or ran shape separately, use it and skip this step. - -When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient. - -If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green. - -## Step 2: Load References - -Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult: - -- [layout.md](layout.md) for layout, spacing, grid, container queries, optical adjustments -- [typeset.md](typeset.md) for type hierarchy, font selection, web font loading, OpenType features (Reference Material section) - -Then add references based on the brief's needs: -- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md) -- Animation or transitions? Consult [animate.md](animate.md) (Reference Material covers motion materials, durations, easing, perceived performance) -- Color-heavy or themed? Consult [colorize.md](colorize.md) (Reference Material covers OKLCH, palette structure, dark mode, contrast) -- Responsive requirements? Consult [adapt.md](adapt.md) (Reference Material covers breakpoints, input methods, safe areas, responsive images) -- Heavy on copy, labels, or errors? Consult [clarify.md](clarify.md) (Reference Material covers button labels, error formula, voice/tone, translation) - -## Step 3: Visual Direction & Assets (Harness-Gated) - -If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4. - -If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract. - -Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery. - -## Step 4: Build to Production Quality - -**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow. - -Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration. - -### Production bar - -- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time. -- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change. -- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed. -- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment. -- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width. -- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run. -- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality. -- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix. -- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve. -- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about. -- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace. -- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion. -- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists. -- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths. -- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess. - -## Step 5: Iterate Visually - -Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation. - -If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count. - -For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects. - -After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix. - -Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review. - -Detector or QA output is defect evidence only; never proof the work is finished. - -## Step 6: Present - -Present the result to the user: -- Show the feature in its primary state -- Summarize the browser/viewports checked and the most important fixes made after inspection -- Walk through the key states (empty, error, responsive) -- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients. -- Note any remaining limitations or follow-up risks honestly -- Ask: "What's working? What isn't?" +Do not tell users they need to invoke `craft`. Natural requests such as “build this feature,” “make a landing page,” or “redesign this screen” use the same flow. diff --git a/.agents/skills/impeccable/reference/critique.md b/.agents/skills/impeccable/reference/critique.md index 331ea9972..7f4450f44 100644 --- a/.agents/skills/impeccable/reference/critique.md +++ b/.agents/skills/impeccable/reference/critique.md @@ -19,11 +19,11 @@ Resolve one stable target, run two independent assessments, synthesize a design - "the homepage" -> `site/pages/index.astro` or `index.html` - "the settings modal" -> the primary component file - "this page" -> the current URL or source file -2. **Compute the slug**: +2. **Confirm the target slugs cleanly**: ```bash node .agents/skills/impeccable/scripts/critique-storage.mjs slug "" ``` - Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique. + Every later command also accepts the resolved target directly and derives the same slug internally; never hand-write a slug. If this exits non-zero, skip persistence and trend for this run, but continue the critique. 3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes. ### Assessment Orchestration @@ -52,13 +52,13 @@ If browser automation is available, each assessment creates its own new tab. Nev Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director. Evaluate: -- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill. +- **Design specificity**: Is the composition, interaction, and visual language grounded in this product, or could an unrelated product use it unchanged? Make this judgment before seeing detector output. - **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases. - **Cognitive load**: consult the [Cognitive Load Assessment](#cognitive-load-assessment) section below; report checklist failures and decision points with >4 visible options. - **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments. -- **Nielsen heuristics**: consult the [Heuristics Scoring Guide](#heuristics-scoring-guide) section below; score all 10 heuristics 0-4. +- **Nielsen heuristics**: consult the [Heuristics Scoring Guide](#heuristics-scoring-guide) section below; score all 10 heuristics 0-4, marking any heuristic the mode-applicability rule allows as `n/a` instead of forcing a number. -Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions. +Return: design-specificity verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions. ### Assessment B: Detector + Browser Evidence @@ -124,15 +124,19 @@ Present the Nielsen's 10 heuristics scores as a table: | 8 | Aesthetic and Minimalist Design | ? | | | 9 | Error Recovery | ? | | | 10 | Help and Documentation | ? | | -| **Total** | | **??/40** | **[Rating band]** | +| **Total** | | **??/[applicable max]** | **[Rating band]** | -Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32. +The applicable maximum is 4 times the number of heuristics you actually scored: **/40** when all ten apply, **/32** when two are `n/a`. Never print `/40` over a partial set. -#### Anti-Patterns Verdict +Be honest with scores. A 4 means genuinely excellent. Most real interfaces score 20-32 out of 40. -**Start here.** Does this look AI-generated? +**Mode applicability**: heuristics 7 (Flexibility and Efficiency) and 10 (Help and Documentation) may be scored `n/a` on Persuade and Experience surfaces (landing pages, campaigns, portfolios, bodies of work), as may any other heuristic that genuinely cannot apply to the surface under review. Write `n/a` in the Score cell with a one-line reason, and renormalize the total to the applicable maximum (e.g. **24/32** when two heuristics are n/a) so the rating band stays proportional. The persisted snapshot must record the applicable maximum and which heuristics were scored n/a. -**LLM assessment**: Your own evaluation of AI slop tells. Cover overall aesthetic feel, layout sameness, generic composition, missed opportunities for personality. +#### Design Specificity Verdict + +**Start here.** Does the result feel authored for this product, or category-interchangeable? + +**LLM assessment**: Your unanchored evaluation of design specificity. Cover overall coherence, structural sameness, category-interchangeable choices, and missed opportunities for product character. **Deterministic scan**: Summarize what the automated detector found, with counts and file locations. Note any additional issues the detector caught that you missed, and flag any false positives. @@ -194,30 +198,32 @@ Once the report above is finalized, write it to `.impeccable/critique/` so the u Skip this step if the Setup slug was null (vague or root-level target). -1. **Write the body to a temp file** so you can pipe it to the helper. Use the full critique report (heuristic table, anti-patterns verdict, priority issues, persona red flags, minor observations, and questions), but stop before the "Ask the User" / "Recommended Actions" sections that come later. +1. **Write the body to a temp file** so you can pipe it to the helper. Use the full critique report (heuristic table, design-specificity verdict, priority issues, persona red flags, minor observations, and questions), but stop before the "Ask the User" / "Recommended Actions" sections that come later. Codex: exclude Run Notes from the temp body file; Run Notes are final-chat only because persistence, trend read, and temp cleanup happen after the snapshot write. 2. **Pass the structured metadata** through `IMPECCABLE_CRITIQUE_META` (JSON), then run the write command: ```bash - IMPECCABLE_CRITIQUE_META='{"target":"","total_score":,"p0_count":,"p1_count":}' \ - node .agents/skills/impeccable/scripts/critique-storage.mjs write + IMPECCABLE_CRITIQUE_META='{"target":"","total_score":,"max_score":,"na_heuristics":"","p0_count":,"p1_count":}' \ + node .agents/skills/impeccable/scripts/critique-storage.mjs write "" ``` - The helper prints the absolute path it wrote. + `max_score` is the applicable maximum from the heuristic table (40 when every heuristic applied), so a later run can tell a renormalized total from a full one. The helper prints the absolute path it wrote. 3. **Delete the temp body file** after the write attempt completes, whether the write succeeded or failed. If deletion fails, mention `temp-file cleanup failed: ` briefly in the final output, but do not block the critique. 4. **Read the trend** for context: ```bash - node .agents/skills/impeccable/scripts/critique-storage.mjs trend 5 + node .agents/skills/impeccable/scripts/critique-storage.mjs trend "" 5 ``` This returns a JSON array of the last 5 frontmatter entries (including the one you just wrote). 5. **Append a single line to the user-visible output**, after the report and before the questions: - > **Trend for `` (last 5 runs): 24 → 28 → 32 → 29 → 32** + > **Trend for `` (last 5 runs): 24 → 28 → 32 → 29 → 32 (out of 40)** > Wrote `.impeccable/critique/`. + Read `max_score` on each trend entry. When every entry shares one maximum, state it once as above. When they differ, print each score with its own denominator (`24/32 → 30/40`) and note that the runs scored different heuristic sets, so the line is not a like-for-like comparison. Treat a missing `max_score` on an older entry as 40. + If this is the first run for the slug, the trend is just one score; say so: "First run for this target, no trend yet." This is fire-and-forget. Do not show the user the helper's JSON output; only the human-readable trend line and the written path. Failures here should not block the rest of the flow; print the error and move on. @@ -343,11 +349,11 @@ At any decision point, count the number of distinct options, actions, or pieces - **8+ items**: Overloaded; users will skip, misclick, or abandon **Practical applications**: -- Navigation menus: ≤5 top-level items (group the rest under clear categories) -- Form sections: ≤4 fields visible per group before a visual break - Action buttons: 1 primary, 1–2 secondary, group the rest in a menu -- Dashboard widgets: ≤4 key metrics visible without scrolling -- Pricing tiers: ≤3 options (more causes analysis paralysis) +- Navigation menus: ≤5 top-level items (group the rest under clear categories) +- Long-form articles: one reading path; gather related links into a single block at the end instead of scattering them mid-flow +- Documentation sidebars: ≤4 sibling choices visible per level before grouping kicks in +- Portfolio and gallery indexes: one decision per screen (which piece to open), not filter, sort, and tag controls all at once --- @@ -607,6 +613,8 @@ Even if the system is usable without docs, help should be easy to find, task-foc | 12–19 | Poor | Major UX overhaul required; core experience broken | | 0–11 | Critical | Redesign needed; unusable in current state | +When heuristics were scored `n/a`, the maximum is lower than 40; read the band off the percentage instead of the raw number (90%+ Excellent, 70%+ Good, 50%+ Acceptable, 30%+ Poor, below that Critical). 24/32 is 75%, so Good. + --- #### Issue Severity (P0–P3) diff --git a/.agents/skills/impeccable/reference/delight.md b/.agents/skills/impeccable/reference/delight.md index b31967056..60a8e83ee 100644 --- a/.agents/skills/impeccable/reference/delight.md +++ b/.agents/skills/impeccable/reference/delight.md @@ -1,302 +1,70 @@ -> **Additional context needed**: what's appropriate for the domain (playful vs professional vs quirky vs elegant). +> **Additional context needed**: the brand's emotional range. -Find the moments where personality and unexpected polish would turn a functional interface into one users remember and tell other people about. Add only where the moment earns it; delight everywhere reads as noise. +Make the experience memorable at moments that earn it. Delight is not a layer of generic whimsy; it is product character revealed through a useful interaction, a humane response, or an unexpectedly considered detail. --- -## Register +## Visitor mode -Brand: delight can be distributed across copy voice, section transitions, discovery rewards, seasonal touches, personality across the whole surface. +- **Persuade + Experience:** personality may run through voice, composition, motion, and discovery, provided the artifact remains the focus. +- **Operate + Read:** concentrate delight at meaningful moments such as first use, completion, recovery, or mastery. Reliability carries everything else. -Product: delight at specific moments, not pages. Completion, first-time actions, error recovery, milestone crossings. Reliability and consistency carry the rest of the experience; delight pushed everywhere reads as noise. +## Find the opportunity ---- - -## Assess Delight Opportunities - -Identify where delight would enhance (not distract from) the experience: - -1. **Find natural delight moments**: - - **Success states**: Completed actions (save, send, publish) - - **Empty states**: First-time experiences, onboarding - - **Loading states**: Waiting periods that could be entertaining - - **Achievements**: Milestones, streaks, completions - - **Interactions**: Hover states, clicks, drags - - **Errors**: Softening frustrating moments - - **Easter eggs**: Hidden discoveries for curious users - -2. **Understand the context**: - - What's the brand personality? (Playful? Professional? Quirky? Elegant?) - - Who's the audience? (Tech-savvy? Creative? Corporate?) - - What's the emotional context? (Accomplishment? Exploration? Frustration?) - - What's appropriate? (Banking app ≠ gaming app) - -3. **Define delight strategy**: - - **Subtle sophistication**: Refined micro-interactions (luxury brands) - - **Playful personality**: Whimsical illustrations and copy (consumer apps) - - **Helpful surprises**: Anticipating needs before users ask (productivity tools) - - **Sensory richness**: Satisfying sounds, smooth animations (creative tools) - -If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. - -**CRITICAL**: Delight should enhance usability, never obscure it. If users notice the delight more than accomplishing their goal, you've gone too far. - -## Delight Principles - -Follow these guidelines: - -### Delight Amplifies, Never Blocks -- Delight moments should be quick (< 1 second) -- Never delay core functionality for delight -- Make delight skippable or subtle -- Respect user's time and task focus - -### Surprise and Discovery -- Hide delightful details for users to discover -- Reward exploration and curiosity -- Don't announce every delight moment -- Let users share discoveries with others - -### Appropriate to Context -- Match delight to emotional moment (celebrate success, empathize with errors) -- Respect the user's state (don't be playful during critical errors) -- Match brand personality and audience expectations -- Cultural sensitivity (what's delightful varies by culture) - -### Compound Over Time -- Delight should remain fresh with repeated use -- Vary responses (not same animation every time) -- Reveal deeper layers with continued use -- Build anticipation through patterns - -## Delight Techniques - -Add personality and joy through these methods: - -### Micro-interactions & Animation - -**Button delight**: -```css -/* Satisfying button press */ -.button { - transition: transform 0.1s, box-shadow 0.1s; -} -.button:active { - transform: translateY(2px); - box-shadow: 0 2px 4px rgba(0,0,0,0.2); -} - -/* Ripple effect on click */ -/* Smooth lift on hover */ -.button:hover { - transform: translateY(-2px); - transition: transform 0.2s cubic-bezier(0.25, 1, 0.5, 1); /* ease-out-quart */ -} -``` - -**Loading delight**: -- Playful loading animations (not just spinners) -- Personality in loading messages (write product-specific ones, not generic AI filler) -- Progress indication with encouraging messages -- Skeleton screens with subtle animations - -**Success animations**: -- Checkmark draw animation -- Confetti burst for major achievements -- Gentle scale + fade for confirmation -- Satisfying sound effects (subtle) - -**Hover surprises**: -- Icons that animate on hover -- Color shifts or glow effects -- Tooltip reveals with personality -- Cursor changes (custom cursors for branded experiences) - -### Personality in Copy - -**Playful error messages**: -``` -"Error 404" -"This page is playing hide and seek. (And winning)" - -"Connection failed" -"Looks like the internet took a coffee break. Want to retry?" -``` - -**Encouraging empty states**: -``` -"No projects" -"Your canvas awaits. Create something amazing." - -"No messages" -"Inbox zero! You're crushing it today." -``` - -**Playful labels & tooltips**: -``` -"Delete" -"Send to void" (for playful brand) - -"Help" -"Rescue me" (tooltip) -``` - -**IMPORTANT**: Match copy personality to brand. Banks shouldn't be wacky, but they can be warm. - -### Illustrations & Visual Personality - -**Custom illustrations**: -- Empty state illustrations (not stock icons) -- Error state illustrations (friendly monsters, quirky characters) -- Loading state illustrations (animated characters) -- Success state illustrations (celebrations) - -**Icon personality**: -- Custom icon set matching brand personality -- Animated icons (subtle motion on hover/click) -- Illustrative icons (more detailed than generic) -- Consistent style across all icons - -**Background effects**: -- Subtle particle effects -- Gradient mesh backgrounds -- Geometric patterns -- Parallax depth -- Time-of-day themes (morning vs night) - -### Satisfying Interactions - -**Drag and drop delight**: -- Lift effect on drag (shadow, scale) -- Snap animation when dropped -- Satisfying placement sound -- Undo toast ("Dropped in wrong place? [Undo]") - -**Toggle switches**: -- Smooth slide with spring physics -- Color transition -- Haptic feedback on mobile -- Optional sound effect - -**Progress & achievements**: -- Streak counters with celebratory milestones -- Progress bars that "celebrate" at 100% -- Badge unlocks with animation -- Playful stats ("You're on fire! 5 days in a row") - -**Form interactions**: -- Input fields that animate on focus -- Checkboxes with a satisfying scale pulse when checked -- Success state that celebrates valid input -- Auto-grow textareas - -### Sound Design - -**Subtle audio cues** (when appropriate): -- Notification sounds (distinctive but not annoying) -- Success sounds (satisfying "ding") -- Error sounds (empathetic, not harsh) -- Typing sounds for chat/messaging -- Ambient background audio (very subtle) - -**IMPORTANT**: -- Respect system sound settings -- Provide mute option -- Keep volumes quiet (subtle cues, not alarms) -- Don't play on every interaction (sound fatigue is real) - -### Easter Eggs & Hidden Delights - -**Discovery rewards**: -- Konami code unlocks special theme -- Hidden keyboard shortcuts (Cmd+K for special features) -- Hover reveals on logos or illustrations -- Alt text jokes on images (for screen reader users too!) -- Console messages for developers ("Like what you see? We're hiring!") - -**Seasonal touches**: -- Holiday themes (subtle, tasteful) -- Seasonal color shifts -- Weather-based variations -- Time-based changes (dark at night, light during day) - -**Contextual personality**: -- Different messages based on time of day -- Responses to specific user actions -- Randomized variations (not same every time) -- Progressive reveals with continued use - -### Loading & Waiting States +Inspect the target, DESIGN.md, product voice, repeated-use frequency, and emotional context. Look for: -**Make waiting engaging**: -- Interesting loading messages that rotate -- Progress bars with personality -- Mini-games during long loads -- Fun facts or tips while waiting -- Countdown with encouraging messages +- effort worth acknowledging; +- waiting that can become informative; +- an empty or first-use state that can orient; +- an error or recovery moment that needs empathy; +- an interaction whose physical or verbal response could express the brand; +- a useful capability people might enjoy discovering. -``` -Loading messages: write ones specific to your product, not generic AI filler: -- "Crunching your latest numbers..." -- "Syncing with your team's changes..." -- "Preparing your dashboard..." -- "Checking for updates since yesterday..." -``` +Do not manufacture a celebration for an ordinary click. Ask only when the brand's emotional range or the stakes cannot be inferred. -**WARNING**: Avoid cliched loading messages like "Herding pixels", "Teaching robots to dance", "Consulting the magic 8-ball", "Counting backwards from infinity". These are AI-slop copy, instantly recognizable as machine-generated. Write messages that are specific to what your product actually does. +## Define one delight thesis -### Celebration Moments +State in one sentence what the user should feel and why that feeling belongs to this product. Then choose the smallest system that can deliver it: -**Success celebrations**: -- Confetti for major milestones -- Animated checkmarks for completions -- Progress bar celebrations at 100% -- "Achievement unlocked" style notifications -- Personalized messages ("You published your 10th article!") +- a distinctive response to a meaningful action; +- product-specific language that clarifies while carrying voice; +- an interaction or transition with a recognizable material behavior; +- an illustration, sound, haptic, or environmental detail grounded in the product world; +- a discovery reward that reveals real utility. -**Milestone recognition**: -- First-time actions get special treatment -- Streak tracking and celebration -- Progress toward goals -- Anniversary celebrations +Derive the treatment from product mechanism and visual world, not a stock catalog. -## Implementation Patterns +## Build for the emotional moment -**Animation libraries**: -- Framer Motion (React) -- GSAP (universal) -- Lottie (After Effects animations) -- Canvas confetti (party effects) +- **Success:** match the response to the effort and consequence. Major milestones can expand; routine saves should simply feel certain. +- **Waiting:** show truthful progress, useful context, or product-specific activity. Never fake work or delay completion to stage a flourish. +- **Empty and first use:** make the next action clear before adding personality. +- **Error and recovery:** lead with the problem and recovery. Warmth may reduce stress; jokes must not trivialize loss, money, privacy, or blocked work. +- **Repeated interaction:** keep the response satisfying after the hundredth use. Variation is useful only when it remains coherent and predictable enough to trust. +- **Discovery:** reward curiosity without hiding required functionality. -**Sound libraries**: -- Howler.js (audio management) -- Use-sound (React hook) +Copy must use the product's language. Generic whimsy is worse than neutral clarity. -**Physics libraries**: -- React Spring (spring physics) -- Popmotion (animation primitives) +## Protect the experience -**IMPORTANT**: File size matters. Compress images, optimize animations, lazy load delight features. +Delight must not: -**NEVER**: -- Delay core functionality for delight -- Force users through delightful moments (make skippable) -- Use delight to hide poor UX -- Overdo it (less is more) -- Ignore accessibility (animate responsibly, provide alternatives) -- Make every interaction delightful (special moments should be special) -- Sacrifice performance for delight -- Be inappropriate for context (read the room) +- delay, block, or obscure the primary task; +- override platform conventions or accessibility; +- add unrequested factual claims; +- play sound without consent or ignore mute settings; +- become mandatory, unskippable, or exhausting on repeat; +- add a dependency or asset cost disproportionate to the moment. -## Verify Delight Quality +For authored motion, load [animate.md](animate.md). Respect screen readers, keyboard use, touch, localization, and cultural context. Nonessential loops stop when hidden. Make celebration intensity proportional to frequency and consequence. -Test that delight actually delights: +## Verify -- **User reactions**: Do users smile? Share screenshots? -- **Doesn't annoy**: Still pleasant after 100th time? -- **Doesn't block**: Can users opt out or skip? -- **Performant**: No jank, no slowdown -- **Appropriate**: Matches brand and context -- **Accessible**: Works with reduced motion, screen readers +- The moment is specific enough that a neighboring product could not use it unchanged. +- It improves comprehension, confidence, motivation, or emotional recovery. +- The interface remains fast and obvious without the flourish. +- Repetition does not turn charm into friction. +- Muted, keyboard, touch, and localized paths work. +- The result feels like the selected world, not a generic “delight” treatment. -When the moments feel earned, hand off to `$impeccable polish` for the final pass. +When the personality feels earned, hand off to `$impeccable polish` for the final pass. diff --git a/.agents/skills/impeccable/reference/distill.md b/.agents/skills/impeccable/reference/distill.md index 2ac85043e..9c8322669 100644 --- a/.agents/skills/impeccable/reference/distill.md +++ b/.agents/skills/impeccable/reference/distill.md @@ -66,8 +66,8 @@ Systematically remove complexity across these dimensions: - **Reduce choices**: Fewer buttons, fewer options, clearer path forward (paradox of choice is real) - **Smart defaults**: Make common choices automatic, only ask when necessary - **Inline actions**: Replace modal flows with inline editing where possible -- **Remove steps**: Can signup be one step instead of three? Can checkout be simplified? -- **Clear CTAs**: ONE obvious next step, not five competing actions +- **Remove steps**: Can the flow lose a step? +- **Clear next action**: ONE obvious next action, not five competing ones ### Content Simplification - **Shorter copy**: Cut every sentence in half, then do it again diff --git a/.agents/skills/impeccable/reference/doctor.md b/.agents/skills/impeccable/reference/doctor.md new file mode 100644 index 000000000..e08df6ce7 --- /dev/null +++ b/.agents/skills/impeccable/reference/doctor.md @@ -0,0 +1,53 @@ +Report and repair drift between this project's Impeccable artifacts and what the installed version reads: PRODUCT.md, DESIGN.md and its `.impeccable/design.json` sidecar, `.impeccable/config.json`, persisted surface briefs, and the design hook. + +This is maintenance, not design. Do not redesign anything, do not open files outside the ones the report names, and do not run any other command as a side effect. + +## What this owns, and what it does not + +Three kinds of drift travel under "out of date". Keep them apart: + +- **Tool version.** The installed skill is older than the published one. `context.mjs` reports that at boot as `UPDATE_AVAILABLE` and `npx impeccable update` fixes it. Not this command's job. +- **Schema drift.** An artifact was written by an older Impeccable: fields nothing reads, fields now expected, files in retired locations. Mechanical, and this command repairs most of it. +- **Truth drift.** The code moved on and the document no longer describes it. No file comparison settles this. `document` owns DESIGN.md, `init` owns PRODUCT.md, and this command's job is to hand them a specific gap rather than a vague suspicion. + +## Step 1: Run the pass + +``` +node .agents/skills/impeccable/scripts/doctor.mjs --json +``` + +Add `--target ` when the user named a workspace, file, or route in a monorepo. Without it the report describes the repo root, and in a monorepo that is often the wrong project. + +The output carries `findings` (each with `id`, `artifact`, `path`, `severity`, `summary`, `fix`) and, in a monorepo, `workspaces` with each app's product and design resolution. `ruleRegistryAvailable: false` means ignored rule ids could not be validated; say so rather than implying that list is clean. + +An empty `findings` array is the good outcome. Say so in one line and stop. + +## Step 2: Act by severity + +The severity says what should happen, not how bad it is. + +- **`auto`** carries no decision. Run `node .agents/skills/impeccable/scripts/doctor.mjs --fix` once to apply these, then report what it moved in one line. Do not ask permission first, and do not ask about them afterward. +- **`mention`** needs the user to know but not to decide anything now. State each one in a sentence with its offered fix. +- **`route`** needs a specific command. Name the command and the gap it would close. Run it only if the user asks in this turn; `init` and `document` are conversations, not repairs you perform unattended. + +Report all three groups in one pass. Findings are not errors and the command does not fail on them. + +## Step 3: Deprecated fields are binding + +A finding that reports a deprecated field (`## Register` is the current one) is not a style note. Treat that field as absent for every decision from here on, whatever value it holds, and offer to delete the section. Preserving it "just in case" is how a retired axis keeps steering current output. + +## Step 4: Do not overclaim on truth drift + +`design-md-drift` counts commits to the visual source directories since DESIGN.md was last edited. A commit count is not a contradiction. Report the number, say what it measures, and if the user wants to know whether the document is actually wrong, read DESIGN.md against the current tokens and components and answer from that. Never assert that DESIGN.md is stale because the number is large. + +The same restraint applies to `workspace-context-inherited`. Inheritance is a designed behavior. Whether one product record truthfully describes several apps is a question for the user, not a defect to fix. + +## Monorepo notes + +- `workspace-platform-native-evidence` is the finding that matters most here: a workspace carrying native build files while inheriting a root record that resolves to web gets web guidance for its whole life and never loads [ios.md](ios.md) or [android.md](android.md). The repair is a child PRODUCT.md in that workspace, because one inherited record cannot hold two platforms. +- `config-project-roots-match-nothing` means every `projectRoots` glob missed, so the repo root is silently standing in as the active project. A renamed workspace directory is the usual cause. Report the patterns and ask which directories they should name. +- Use the `workspaces` table to show the user which apps carry their own context, which inherit, and which have none, before proposing any change. + +## Opting out of the boot check + +`context.mjs` reports the cheap subset of these findings at session start, throttled to once a week per project. Set `"stalenessCheck": false` in `.impeccable/config.json` to silence that, or `IMPECCABLE_NO_STALENESS_CHECK=1` for one session. This command still works with the check disabled, and that is the combination to suggest for a user who wants the report only when they ask for it. diff --git a/.agents/skills/impeccable/reference/document.md b/.agents/skills/impeccable/reference/document.md index 3298274c9..c44ed24ba 100644 --- a/.agents/skills/impeccable/reference/document.md +++ b/.agents/skills/impeccable/reference/document.md @@ -1,6 +1,6 @@ Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand. -DESIGN.md follows the [official DESIGN.md format spec](https://raw.githubusercontent.com/google-labs-code/design.md/main/docs/spec.md): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.). +DESIGN.md follows the [official DESIGN.md format spec](https://raw.githubusercontent.com/google-labs-code/design.md/main/docs/spec.md): optional YAML frontmatter carrying machine-readable design tokens, followed by up to eight markdown sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but those present stay in the specified order. Use the canonical headings below so the file remains portable across DESIGN.md-aware tools. ## The frontmatter: token schema @@ -43,26 +43,28 @@ components: Rules that matter: - **Token refs** use `{path.to.token}` (e.g. `{colors.primary}`, `{rounded.md}`). Components may reference primitives; primitives may not reference each other. -- **Stitch validates colors as hex sRGB only** (`#RGB` / `#RGBA` / `#RRGGBB` / `#RRGGBBAA`); OKLCH/HSL/P3 trigger a linter warning, not a hard error. YAML accepts the string either way and our own parser is format-agnostic. Choose based on project posture: (a) if the project has an "OKLCH-only" doctrine or uses Display-P3 values that don't round-trip through sRGB, put OKLCH directly in the frontmatter and accept the Stitch linter warning; (b) if the project wants strict Stitch compliance or plans to use their Tailwind/DTCG export pipeline, put hex in the frontmatter and keep OKLCH in prose as the canonical reference. Never split the source of truth without explicit reason. +- **Colors accept any valid CSS color string.** Hex is the recommended default for portability, but preserve an incumbent `rgb()`, `hsl()`, `oklch()`, wide-gamut, or mixed-color value when it is the project's normative source. Never split the source of truth without explicit reason. - **Component sub-tokens** are limited to 8 props: `backgroundColor`, `textColor`, `typography`, `rounded`, `padding`, `size`, `height`, `width`. Shadows, motion, focus rings, backdrop-filter: none of those fit. Carry them in the sidecar (Step 4b). - **Scale keys are open-ended.** Use whatever names the project already uses (`oxblood-deep`, `surface-container-low`). Don't rename to Material defaults. - **Variants are naming convention, not schema.** `button-primary` / `button-primary-hover` / `button-primary-active` as sibling keys. -## The markdown body: six sections (exact order) +## The markdown body: eight sections (canonical order) 1. `## Overview` 2. `## Colors` 3. `## Typography` -4. `## Elevation` -5. `## Components` -6. `## Do's and Don'ts` +4. `## Layout` +5. `## Elevation & Depth` +6. `## Shapes` +7. `## Components` +8. `## Do's and Don'ts` -Optional evocative subtitles are allowed in the form `## 2. Colors: The [Name] Palette` (Stitch's own outputs do this), but the literal word in each header (Overview, Colors, Typography, Elevation, Components, Do's and Don'ts) must be present. Do NOT add extra top-level sections (Layout Principles, Responsive Behavior, Motion, Agent Prompt Guide). Fold that content into the six spec sections where it naturally belongs. +Omit irrelevant sections rather than filling them with invented rules. Put responsive layout in Layout, depth in Elevation & Depth, radius and form language in Shapes, and per-component behavior in Components. Unknown sections are preserved by the format, but new visual guidance should use the canonical structure whenever it fits. ## When to run -- The user just ran `$impeccable init` and needs the visual side documented. -- The skill noticed no `DESIGN.md` exists and nudged the user to create one. +- New-work found a coherent incumbent visual system but no `DESIGN.md`. +- The first implementation of a new world is complete and its provisional decisions need to be carbonized. - An existing `DESIGN.md` is stale (the design has drifted). - Before a large redesign, to capture the current state as a reference. @@ -71,9 +73,9 @@ If a `DESIGN.md` already exists, **do not silently overwrite it**. Show the user ## Two paths - **Scan mode** (default): the project has design tokens, components, or rendered output. Extract, then confirm descriptive language. Use when there's code to analyze. -- **Seed mode**: the project is pre-implementation (fresh init, nothing built yet). Interview for five high-level answers, write a minimal DESIGN.md marked ``. Re-run in scan mode once there's code. +- **Seed mode**: the project is pre-implementation. Ensure PRODUCT.md exists, then reuse new-work's visual-world workshop and write its directional DESIGN.md seed. Re-run in scan mode once there's code. -Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `$impeccable document --seed` forces seed mode regardless of code presence. +Decide by scanning first (Scan mode Step 1). If the scan finds no tokens, no component files, and no rendered site, offer seed mode; don't silently switch. `$impeccable document --seed` requests new-work's world workshop, but it does not authorize replacing coherent code: when an incumbent system exists, offer scan mode or route an explicit identity-replacement request through new-work. ## Scan mode (approach C: auto-extract, then confirm descriptive language) @@ -97,7 +99,8 @@ Build a structured draft from the discovered tokens. For each token class: - **Typography**: Map observed sizes and weights to the Material hierarchy (display / headline / title / body / label). Note font-family stacks and the scale ratio. - **Elevation**: Catalogue the shadow vocabulary. If the project is flat and uses tonal layering instead, that's a valid answer; state it explicitly. - **Components**: For each common component (button, card, input, chip, list item, tooltip, nav), extract shape (radius), color assignment, hover/focus treatment, internal padding. -- **Spacing + layout**: Fold into Overview or relevant Components. The spec does NOT have a Layout section. +- **Layout + spacing**: Extract grid, container, breakpoint, rhythm, and density behavior into Layout. +- **Shapes**: Extract radius, corner, border, clipping, and recurring form behavior into Shapes. ### Step 2b: Stage the frontmatter @@ -112,19 +115,19 @@ Skip anything the project doesn't have. Empty scale keys or fabricated tokens po ### Step 3: Ask the user for qualitative language -The following require creative input that cannot be auto-extracted. Group them into one `AskUserQuestion` interaction: +The following require creative input that cannot be auto-extracted. Ask them in two structured rounds of no more than three questions each (or the harness's lower limit), waiting between rounds: - **Creative North Star**: a single named metaphor for the whole system ("The Editorial Sanctuary", "The Golden State Curator", "The Lab Notebook"). Offer 2-3 options that honor PRODUCT.md's brand personality. -- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, anti-references (what the system should not feel like). +- **Overview voice**: mood adjectives, aesthetic philosophy in 2-3 sentences, and any confirmed visual anti-reference. - **Color character** (for auto-extracted colors): descriptive names ("Deep Muted Teal-Navy", not "blue-800"). Suggest 2-3 options per key color based on hue/saturation. - **Elevation philosophy**: flat/layered/lifted. If shadows exist, is their role ambient or structural? - **Component philosophy**: the feel of buttons, cards, inputs in one phrase ("tactile and confident" vs. "refined and restrained"). -Quote a line from PRODUCT.md when possible so the user sees their own strategic language carry forward. +Carry a line from PRODUCT.md only when it is a durable brand commitment that actually constrains the visual system. Page strategy and surface concepts do not belong here. ### Step 4: Write DESIGN.md -The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the structure below. Headers must match character-for-character. Optional evocative subtitles (e.g. `## 2. Colors: The Coastal Palette`) are allowed. +The file opens with the YAML frontmatter staged in Step 2b (schema documented at the top of this reference), then the markdown body using the canonical structure below. ```markdown --- @@ -136,13 +139,13 @@ colors: # Design System: [Project Title] -## 1. Overview +## Overview **Creative North Star: "[Named metaphor in quotes]"** -[2-3 paragraph holistic description: personality, density, aesthetic philosophy. Start from the North Star and work outward. State what this system explicitly rejects (pulled from PRODUCT.md's anti-references). End with a short **Key Characteristics:** bullet list.] +[2-3 paragraph holistic description: personality, density, and aesthetic philosophy. Start from the North Star and work outward. State only confirmed visual rejections. End with a short **Key Characteristics:** bullet list.] -## 2. Colors +## Colors [Describe the palette character in one sentence.] @@ -162,7 +165,7 @@ colors: ### Named Rules (optional, powerful) **The [Rule Name] Rule.** [Short, forceful prohibition or doctrine, e.g. "The One Voice Rule. The primary accent is used on ≤10% of any given screen. Its rarity is the point."] -## 3. Typography +## Typography **Display Font:** [Family] (with [fallback]) **Body Font:** [Family] (with [fallback]) @@ -180,7 +183,11 @@ colors: ### Named Rules (optional) **The [Rule Name] Rule.** [Short doctrine about type use.] -## 4. Elevation +## Layout + +[Describe the grid or spatial model, container behavior, density, responsive changes, and the spacing rhythm. Include exact values only when observed.] + +## Elevation & Depth [One paragraph: does this system use shadows, tonal layering, or a hybrid? If "no shadows", say so explicitly and describe how depth is conveyed instead.] @@ -191,7 +198,11 @@ colors: ### Named Rules (optional) **The [Rule Name] Rule.** [e.g. "The Flat-By-Default Rule. Surfaces are flat at rest. Shadows appear only as a response to state (hover, elevation, focus)."] -## 5. Components +## Shapes + +[Describe the form language: corner/radius strategy, borders, clipping, and any recurring silhouette or geometry.] + +## Components For each component, lead with a short character line, then specify shape, color assignment, states, and any distinctive behavior. @@ -223,16 +234,16 @@ For each component, lead with a short character line, then specify shape, color ### [Signature Component] (optional; if the project has a distinctive custom component worth documenting) [Description.] -## 6. Do's and Don'ts +## Do's and Don'ts -Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: include exact colors, pixel values, and named anti-patterns the user mentioned in PRODUCT.md. **Every anti-reference in PRODUCT.md should show up here as a "Don't" with the same language**, so the visual spec carries the strategic line through. Quote PRODUCT.md directly where possible: if PRODUCT.md says *"avoid dark mode with purple gradients, neon accents, glassmorphism"*, the Don'ts here should repeat that by name. +Concrete visual guardrails grounded in the incumbent implementation or the user's chosen world. Lead each with "Do" or "Don't" and include exact values only when established. Do not turn a task-specific concept or surface strategy into a system-wide prohibition. ### Do: - **Do** [specific prescription with exact values / named rule]. - **Do** [...] ### Don't: -- **Don't** [specific prohibition, e.g. "use border-left greater than 1px as a colored stripe"]. +- **Don't** [specific prohibition confirmed by the incumbent system or the user]. - **Don't** [...] - **Don't** [...] ``` @@ -274,7 +285,7 @@ Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user onl "kind": "button | input | nav | chip | card | custom", "refersTo": "button-primary", "description": "One-line what and when.", - "html": "", + "html": "", "css": ".ds-btn-primary { background: #191c1d; color: #fff; padding: 16px 48px; letter-spacing: 0.05em; text-transform: uppercase; font-weight: 500; border: none; border-radius: 0; transition: background 0.2s, transform 0.2s; } .ds-btn-primary:hover { background: oklch(60% 0.25 350); transform: translateY(-2px); }" } ], @@ -307,7 +318,7 @@ The `html` and `css` fields must be **self-contained, drop-in snippets** that re Aim for a tight set of **5-10 components** that best represent the visual system: - **Canonical primitives (always include if the project has them):** button (each variant as a separate component entry), input/text field, navigation, chip/tag, card. -- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md. +- **Signature components (include if distinctive):** the recurring custom patterns that actually define the implemented system. - **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive. If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero. @@ -338,64 +349,40 @@ Your own write is the freshest source; subsequent commands in this session don't ## Seed mode -For projects with no visual system to extract yet. Produces a minimal scaffold, not a full spec. - -### Step 1: Confirm seed mode - -Before interviewing: "There's no existing visual system to scan. I'll ask five quick questions to seed a starter DESIGN.md. You can re-run `$impeccable document` once there's code, to capture the real tokens and components. OK?" - -If the user prefers to skip, stop. No file. - -### Step 2: Five questions - -Group into one `AskUserQuestion` interaction. Options must be concrete. - -1. **Color strategy.** Pick one: - - Restrained: tinted neutrals + one accent ≤10% - - Committed: one saturated color carries 30–60% of the surface - - Full palette: 3–4 named color roles, each deliberate - - Drenched: the surface IS the color - - Then: one hue family or anchor reference ("deep teal", "mustard", "Klim #ff4500 orange"). +For projects with no visual system to extract yet. Produces a user-chosen visual-world scaffold, not a fabricated token spec. -2. **Typography direction.** Pick one (specific fonts come later): - - Serif display + sans body - - Single sans (warm / technical / geometric / humanist; pick a feel) - - Display + mono - - Mono-forward - - Editorial script + sans +### Step 1: Route through new-work's workshop -3. **Motion energy.** Pick one: - - Restrained: state changes only - - Responsive: feedback + transitions, no choreography - - Choreographed: orchestrated entrances, scroll-driven sequences +PRODUCT.md is the prerequisite. If it is missing, load [init.md](init.md) and complete its product interview first. Do not create a visual identity without durable product context. -4. **Three named references.** Brands, products, printed objects. Not adjectives. +If PRODUCT.md exists, load [new-work.md](new-work.md) and resolve visual authority. Seed mode requires a concrete first surface: use the target the user named, or ask what they want to make first. Run new-work's **Create or replace the visual world** flow, then **Commit the world**, so the visual world and its first expression are chosen together. Stop after the directional DESIGN.md seed and surface brief; do not implement. A structured simulated user counts as the user and must get the same choice. -5. **One anti-reference.** What it should NOT feel like. Also named. +If new-work already completed the workshop in this session, use its chosen direction directly. Do not ask again. -### Step 3: Write seed DESIGN.md +### Step 2: Write seed DESIGN.md -Use the six-section spec from Scan mode. Populate what the interview answers; leave the rest as honest placeholders. The seed is a scaffold, not a fabricated spec. +Use the canonical section order from Scan mode. Populate the selected workshop direction and leave unresolved implementation facts as honest placeholders. The seed commits a world and its invariants; it does not pretend implementation tokens already exist. Lead the file with: ```markdown - + ``` Per-section guidance in seed mode: -- **Overview**: Creative North Star and philosophy phrased from the answers (color strategy + motion energy + references). Reference the user's anti-reference directly. -- **Colors**: Color strategy as a Named Rule (e.g. *"The Drenched Rule. The surface IS the color."*). Hue family or anchor reference. No hex values; mark as `[to be resolved during implementation]`. -- **Typography**: the direction the user picked (e.g. "Serif display + sans body"). No font names yet: `[font pairing to be chosen at implementation]`. -- **Elevation**: inferred from motion energy. Restrained/Responsive → flat by default; Choreographed → layered. One sentence. +- **Overview**: the chosen design thesis, layout behavior, material character, imagery stance, motion grammar, and reusable signature. Keep the selected first-surface expression in its surface brief; do not promote its composition into the global world. +- **Colors**: the selected palette strategy and roles. Include values only when the user, an existing asset, or new-work's exploration established them; otherwise mark them `[to be resolved during implementation]`. +- **Typography**: the selected type character and role relationship. Include font names only when established; otherwise mark the pairing `[to be resolved during implementation]`. +- **Layout**: the selected spatial grammar and responsive behavior, without pretending exact measurements are settled. +- **Elevation & Depth**: the selected material and depth behavior, stated as an invariant rather than inferred from a generic preset. +- **Shapes**: the selected form and corner language. - **Components**: omit entirely; no components exist yet. -- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5. +- **Do's and Don'ts**: record the durable guardrails confirmed during the world choice, not task-local refusals. Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render. -### Step 4: Confirm +### Step 3: Confirm 1. Show the seed DESIGN.md. Call out that it is a seed (the marker is the literal commitment). 2. Tell the user: "Re-run `$impeccable document` once you have some code. That pass will extract real tokens and generate the sidecar." @@ -405,15 +392,15 @@ Your own write is the freshest source; no reload needed. ## Style guidelines - **Frontmatter first, prose second.** Tokens go in the YAML frontmatter; prose contextualizes them. Don't redefine a token value in two places; the frontmatter is normative. -- **Cite PRODUCT.md anti-references by name** in the Do's and Don'ts section. If PRODUCT.md lists "SaaS landing-page clichés" or "generic AI tool marketing" as anti-references, the DESIGN.md Don'ts should repeat those phrases verbatim so the visual spec enforces the strategic line. -- **Match the spec, don't invent new sections.** The six section names are fixed. If you have Layout/Motion/Responsive content to document, fold it into Overview (philosophy-level rules) or Components (per-component behavior). +- **Carry only durable product constraints.** A binding logo, identity asset, accessibility need, or brand commitment from PRODUCT.md may constrain DESIGN.md. Surface strategy stays in its surface brief. +- **Match the spec.** Use its eight canonical sections in order and omit any that are irrelevant. Put motion guidance with the world or component it affects rather than creating a token group the schema does not support. - **Descriptive > technical**: "Gently curved edges (8px radius)" > "rounded-lg". Include the technical value in parens, lead with the description. - **Functional > decorative**: for each token, explain WHERE and WHY it's used, not just WHAT it is. - **Exact values in parens**: hex codes, px/rem values, font weights; always the number in parens alongside the description. - **Use Named Rules**: `**The [Name] Rule.** [short doctrine]`. These are memorable, citable, and much stickier for AI consumers than bullet lists. Stitch's own outputs use them heavily ("The No-Line Rule", "The Ghost Border Fallback"). Aim for 1-3 per section. -- **Be forceful**. The voice of a design director. "Prohibited", "forbidden", "never", "always", not "consider", "might", "prefer". Match PRODUCT.md's tone. -- **Concrete anti-pattern tests**. Stitch writes things like *"If it looks like a 2014 app, the shadow is too dark and the blur is too small."* A one-sentence audit test beats a paragraph of principle. -- **Reference PRODUCT.md**. The anti-references section of PRODUCT.md should directly inform the Do's and Don'ts section here. Quote or paraphrase. +- **Be decisive where evidence is decisive.** Use hard language for actual invariants and softer language for provisional guidance. +- **Use concrete audit tests only when they are grounded in the observed system or a confirmed user decision.** A one-sentence test beats a paragraph of principle. +- **Reference PRODUCT.md selectively.** Product truth explains why the world fits; it does not supply page composition or a visual don't-list by default. - **Group colors by role**, not by hex-order or hue-order. Primary / Secondary / Tertiary / Neutral is the spec ordering. ## Pitfalls @@ -423,7 +410,7 @@ Your own write is the freshest source; no reload needed. - Don't invent components that don't exist. If the project only has buttons and cards, only document those. - Don't overwrite an existing DESIGN.md without asking. - Don't duplicate content from PRODUCT.md. DESIGN.md is strictly visual. -- Don't add a "Layout Principles" or "Motion" or "Responsive Behavior" top-level section. The spec has six, not nine. Fold that content where it belongs. +- Don't replace canonical sections with near-synonyms. Put layout and responsive behavior in `Layout`; put motion with the affected world or component. - Don't rename sections even slightly. "Colors" not "Color Palette & Roles". "Typography" not "Typography Rules". Tooling parsing depends on exact headers. - Don't duplicate token values between frontmatter and prose. If a color is in `colors.primary` as hex, the prose can name it and describe its role but should not reassert a different hex. The frontmatter is normative. - Don't invent frontmatter token groups outside Stitch's schema (no `motion:`, `breakpoints:`, `shadows:` at the top level). Stitch's Zod schema only accepts `colors`, `typography`, `rounded`, `spacing`, `components`. Anything else belongs in the sidecar's `extensions`. diff --git a/.agents/skills/impeccable/reference/harden.md b/.agents/skills/impeccable/reference/harden.md index 917be5216..57fd4c70e 100644 --- a/.agents/skills/impeccable/reference/harden.md +++ b/.agents/skills/impeccable/reference/harden.md @@ -261,17 +261,6 @@ t('items', { count }) // Handles complex plural rules - Descriptive alt text - Semantic HTML -**Motion sensitivity**: -```css -@media (prefers-reduced-motion: reduce) { - * { - animation-duration: 0.01ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.01ms !important; - } -} -``` - **High contrast mode**: - Test in Windows high contrast mode - Don't rely only on color diff --git a/.agents/skills/impeccable/reference/hooks.md b/.agents/skills/impeccable/reference/hooks.md index e437ca296..f0321a2cc 100644 --- a/.agents/skills/impeccable/reference/hooks.md +++ b/.agents/skills/impeccable/reference/hooks.md @@ -4,6 +4,10 @@ Manage the **design detector hook** for the current project. The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write. +The detector rules run in two tiers. The per-edit hook surfaces only the immediate tier: mechanical, unambiguous problems worth interrupting an edit for, such as broken images, overflowing or clipped content, contrast and legibility failures, gradient text, glow shadows, and design-system drift. Everything else (copy cadence, palette and typography taste, layout rhythm) is deferred to a deep pass on the `Stop` hook event, which runs the full rule set over every UI file touched in the session and surfaces the remaining findings once, deduplicated against what the per-edit pass already reported. A session with nothing left to report stops silently. Set `hook.perEditRules` to `"all"` in `.impeccable/config.json` to restore the full rule set on every edit. The Stop deep pass is wired for Claude Code and Codex, which both dispatch a native `Stop` hook event. Cursor does not get one (its stop hook is not consistently dispatched; the pre-write gate covers it), and GitHub Copilot's stop-style events do not feed context back to the model, so they keep the full detector per edit. + +Every hook is a mechanical pass. The reflexes no scanner catches live in [craft-floor.md](craft-floor.md), which the skill loads before it edits UI, so they apply whether or not a hook is wired. A session with no automatic hook gets one `MANUAL_DETECTOR_REQUIRED` directive from `context.mjs` asking for a single detector run at the end. + This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook runtime settings live under its `hook` key, and shared detector ignores live under `detector`). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set. Declare server-side template extensions under **`detector.extensions`** when the project uses Blade, Twig, ERB, or Handlebars files; the hook skips them otherwise because they sit outside the built-in extension list. One entry per extension, `{ "ext": ".blade.php", "engine": "html" }`. `engine` picks the analyzer (`html` for markup templates, `text` for JS/TS/CSS-like files) and defaults to `html`. Match against the end of the filename, so double extensions like `.blade.php` and `.html.erb` work. Config only adds extensions; the built-in list always applies. @@ -23,10 +27,11 @@ The first argument is the action. Defaults to `status`. | `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. | | `on` | Set `enabled: true` in `.impeccable/config.json`, record local hook consent as accepted, and install/repair provider hook manifests when the skill is installed. | | `off` | Set `enabled: false` in `.impeccable/config.json`. | -| `ignore-rule ` | Append `` to `detector.ignoreRules`; for `overused-font`, requires `--all-values`. | -| `ignore-file ` | Append `` to `detector.ignoreFiles`. | +| `ignore-rule ` | Append `` to `detector.ignoreRules`; for `overused-font`, requires `--all-values`. Suppresses the rule across the whole project. | +| `ignore-file ` | Append `` to `detector.ignoreFiles`. Suppresses **every** rule for matching files. | | `ignore-value [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/config.json`. | | `ignore-value --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/config.local.json`. | +| `ignore-value "*" --file [--file ...]` | Turn one rule off in matching files only, leaving it active everywhere else. Repeat `--file`, or use `--file=` / `--files=`. A bare `"*"` with no `--file` is refused: use `ignore-rule ` if you really mean project-wide. | | `reset` | Delete the project config, dedup cache, and Cursor pending queue. | ## Flow @@ -51,7 +56,8 @@ Prefer the narrowest exception: - If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/config.json` by default. - For value-specific findings such as `overused-font` and `bounce-easing`, use `ignore-value` when the user confirms the specific value. Do not use `ignore-rule overused-font` for a specific font. -- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file ` for the current file. +- If the finding has no value-specific command, such as `side-tab`, scope that one rule to the file: `ignore-value "*" --file `. Run `npx impeccable detect ` first to see what actually fires there. +- Reach for `ignore-file ` only when the whole file is out of scope for design review: a fixture, a generated artifact, a deliberate slop demo. It silences every rule for that file permanently, including rules that have not been written yet. A real UI surface with one noisy rule wants the file-scoped value ignore above. - Use `ignore-rule ` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally. - Prefer config ignores (the commands above) by default; they keep suppressions in one reviewable place. Reach for an inline comment only when the waiver must travel with a single file that leaves the repo (a generated/exported standalone document, an emailed HTML file). The supported marker is `impeccable-disable ` (whole file) or `impeccable-disable-line` / `impeccable-disable-next-line` (one line), in any comment syntax, with an optional reason after `:` or `--`. The detector honors it by default; `--no-inline-ignores` or `--no-config` bypasses it. @@ -73,7 +79,14 @@ Example whole-rule font exception: node .agents/skills/impeccable/scripts/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally" ``` -Example file-scoped exception: +Example one-rule-in-one-file exception, for a file that is still worth reviewing +for everything else: + +```bash +node .agents/skills/impeccable/scripts/hook-admin.mjs ignore-value design-system-font-size "*" --file "src/overlay/widget.js" --reason "Injected widget builds its own type scale; DESIGN.md's ramp describes the site" +``` + +Example whole-file exception, for a file that is out of scope entirely: ```bash node .agents/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Card.tsx" diff --git a/.agents/skills/impeccable/reference/init.md b/.agents/skills/impeccable/reference/init.md index fc8ec3e72..b9ec90d32 100644 --- a/.agents/skills/impeccable/reference/init.md +++ b/.agents/skills/impeccable/reference/init.md @@ -1,221 +1,122 @@ -# Init Flow +# Init flow -The setup command for a project. One codebase crawl feeds everything it writes: - -- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why". -- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [DESIGN.md format spec](https://raw.githubusercontent.com/google-labs-code/design.md/main/docs/spec.md). Answers "how it looks". -- **`.impeccable/live/config.json`** (live mode): pre-configured so `$impeccable live` boots straight into variant mode with no first-time detour. - -It closes by pointing the user at the best command to run next. Every other impeccable command reads PRODUCT.md and DESIGN.md before doing any work. +`init` captures durable product truth in PRODUCT.md. It does not invent a visual world and does not write DESIGN.md; [new-work.md](new-work.md) creates or expands one, and [document.md](document.md) records an incumbent one. Existing runnable web projects may also receive `.impeccable/live/config.json`. ## Step 1: Load current state -Check what already exists. PRODUCT.md and DESIGN.md live at the project root, or under `.agents/context/` or `docs/` (case-insensitive). Read whichever are present with your native file tool. Also note whether `.impeccable/live/config.json` already exists (Step 6 leaves it untouched if so). - -Decision tree: -- **Neither file exists (empty project or no context yet)**: do Steps 2-4 (write PRODUCT.md), then decide on DESIGN.md based on whether there's code to analyze. -- **PRODUCT.md exists, DESIGN.md missing**: skip to Step 5 and offer to run `$impeccable document` for DESIGN.md. -- **PRODUCT.md exists but has no `## Register` section (legacy)**: add it. Infer a hypothesis from the codebase (see Step 2), confirm with the user, write the field. -- **PRODUCT.md exists but has no `## Platform` section (legacy)**: add it the same way, but only when the project is native (`ios` / `android` / `adaptive`) or the user wants it explicit; a missing field already means `web`. -- **Both exist**: STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. Ask which file to refresh. Skip the one the user doesn't want changed. -- **Just DESIGN.md exists (unusual)**: do Steps 2-4 to produce PRODUCT.md. - -Never silently overwrite an existing file. Always confirm first. - -If init was invoked as a setup blocker by another command, such as `$impeccable craft landing page`, pause that command here. Complete init, then resume the original command. Your own writes are the freshest source; no reload needed. For craft, resume into shape next; init creates project context, but it is not a substitute for the task-specific shape interview and confirmed design brief. - -## Step 2: Explore the codebase - -Before asking questions, thoroughly scan the project to discover what you can. This single crawl feeds PRODUCT.md, DESIGN.md, **and** the live-mode framework detection in Step 6, so be thorough once rather than re-scanning later: - -- **README and docs**: Project purpose, target audience, any stated goals -- **Package.json / config files**: Tech stack, dependencies, existing design libraries, **and the framework** (Vite/SPA, Next.js, Nuxt, SvelteKit, Astro, multi-page static) plus the HTML entry the browser actually loads -- **Existing components**: Current design patterns, spacing, typography in use -- **Brand assets**: Logos, favicons, color values already defined -- **Design tokens / CSS variables**: Existing color palettes, font stacks, spacing scales -- **Any style guides or brand documentation** - -Also form a **register hypothesis** from what you find: - -- Brand signals: `/`, `/about`, `/pricing`, `/blog/*`, `/docs/*`, hero sections, big typography, scroll-driven sections, landing-page-shaped content. -- Product signals: `/app/*`, `/dashboard`, `/settings`, `/(auth)`, forms, data tables, side/top nav, app-shell components. - -Register is a hypothesis at this point, not a decision; Step 3 confirms it. - -Also form a **platform hypothesis**: - -- Native signals: React Native / Expo (`react-native`, `expo`), Flutter (`pubspec.yaml`, `flutter`), SwiftUI / UIKit (`.swift`, `.xcodeproj`, an `ios/` app target), Jetpack Compose / Android (`build.gradle`, an `android/` app module, `AndroidManifest.xml`). An `ios/` and/or `android/` directory that is a real app target, not just a Capacitor/Cordova wrapper around a website. -- Web signals (the default): a web framework (Vite, Next, Nuxt, SvelteKit, Astro), an HTML entry, a CSS/Tailwind setup, no native app target. - -Values: `web` / `ios` / `android` / `adaptive` (one codebase, ships both, adapts per OS). Mobile web is still `web`. Like register, this is a hypothesis; Step 3 confirms it. - -Note what you've learned and what remains unclear. Also note any rough edges worth a follow-up command (thin hierarchy, flat or gray palette, missing error/empty states, dull copy); Step 7 turns these into concrete recommendations without re-analyzing. - -## Step 3: Ask strategic questions (for PRODUCT.md) +Use the PRODUCT.md path resolved by context.mjs. Update it instead of creating a competing authority. In a child app inheriting root context, confirm shared versus app-specific scope before writing. -STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. Ask about anything the codebase doesn't answer with strong, explicit evidence. +- **No PRODUCT.md:** explore, interview, and write it. +- **PRODUCT.md exists:** ask what product knowledge is stale or missing; do not reopen confirmed fields without a reason. +- **Legacy PRODUCT.md:** add only durable missing facts; absent `## Platform` means `web` unless evidence says otherwise. +- **Only DESIGN.md exists:** leave it untouched and create PRODUCT.md. +- **Redesign/rebrand request:** preserve confirmed product truth unless the user changes it. Visual replacement happens later in new-work, not here. -### Interview mode, not confirmation mode +Never silently overwrite an existing file or offer DESIGN.md during init. If another request invoked init, finish PRODUCT.md and resume it. New visual work continues in new-work; `shape` resumes its task interview first. -If the repo is empty or the user's brief is sparse, run a short interview before proposing PRODUCT.md. Do **not** turn a one-sentence request into a complete inferred PRODUCT.md and ask for blanket confirmation. +## Step 2: Explore the project -- Use the harness's structured question tool when one exists. Otherwise, ask directly in chat and stop: one question at a time, with lettered options where the crawl suggests likely answers, waiting for each answer before the next. -- Keep skill vocabulary (register, belief ladder, anti-references) out of question text; ask for the thing in words the user would use. For the brand register, ask like a magazine editor profiling the brand: curious and narrative, drawing out the story, the feel, and what a visitor should come to believe. -- Ask in focused rounds and wait for answers between them. Keep **one topic per question**; add rounds rather than fold several topics into one either-or choice. Options obey the same rule: an option answers only the question asked; never write a compound option that bundles a feeling with a business outcome or names an additional audience. -- Use inferred answers as hypotheses or options, not as finished facts. -- Complete at least one real user-answer round before drafting PRODUCT.md, unless every required answer is directly discoverable from repo docs. -- Round 1 should establish register, platform, users, purpose, positioning, and desired outcome. -- Round 2 should establish brand personality or references, anti-references, and accessibility needs, plus conversion & proof for the brand register. +Before asking, scan enough to avoid making the user repeat known facts: product docs and copy; package/config and app boundaries; features, workflows, routes, and roles; names, logos, legal/proof assets, and brand commitments; platform/accessibility signals; and the dev command/entry when live mode applies. -### Minimum viable interview +Treat repository evidence as a hypothesis, not user approval. Note visual maturity without documenting, extending, or replacing the world. -Ask enough to complete PRODUCT.md. At minimum, cover register confirmation, **platform confirmation** (`web` / `ios` / `android` / `adaptive`), users, purpose, positioning, brand personality, anti-references, and accessibility needs (plus conversion & proof for the brand register) unless each answer is directly discoverable from repo context. Never let the template's default `web` stand unconfirmed for a native or cross-platform repo. After at least one interview round, you may propose inferred answers, but the user must confirm them before you write PRODUCT.md. Never synthesize PRODUCT.md from the original task prompt alone. +Form a platform hypothesis: `web`, `ios`, `android`, or `adaptive` (one product that genuinely adapts its design language per OS). Mobile web remains `web`; a native wrapper around a website does not make its design language native. -### Register (ask first; it shapes everything below) +## Step 3: Interview for product truth -Every design task is either **brand** (marketing, landing, campaign, long-form content, portfolio: design IS the product) or **product** (app UI, admin, dashboards, tools: design SERVES the product). +STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. Ask only about material gaps the repository and original request do not answer with strong evidence. -If Step 2 produced a clear hypothesis, lead with it: *"From the codebase, this looks like a [brand / product] surface. Does that match your intent, or should we treat it differently?"* +Use the structured question tool when available; otherwise ask and wait. Keep rounds to at most three focused questions and require one real answer or approval round before writing a new PRODUCT.md. Confirm inferences. -If the signal is genuinely split (e.g. a product with a big marketing landing), STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. Ask which register describes the **primary** surface. The register can be overridden per task later, but PRODUCT.md carries one default. Settle the default before drafting any register-dependent questions; never batch brand-only questions (Conversion & proof) into the same round as the question that decides the register. +Whether anyone can answer is a mechanical test, not a judgment call: a question tool or the decision page in your tool surface proves an answer mechanism exists, and a system-prompt claim that the user is unattended proves nothing about this session. Probe once with the real first round before concluding no one is there. Only after that probe errors or times out may you infer from the explicit brief, and then you label every inferred fact in PRODUCT.md and disclose the substitution in your first reply, not your last. -### Platform (ask right after register) +Start with the unknowns that most change future product decisions: -Every project targets **web** (includes responsive mobile web), **ios**, **android**, or **adaptive** (one codebase, ships both, adapts per OS: Flutter, React Native, KMP). Platform picks the native rulebook: HIG for `ios`, Material 3 for `android`, both for `adaptive`, none for `web`. +1. Who is the primary user, in what situation, and what job are they doing? +2. What does the product make possible, and what is its meaningfully different mechanism or position? +3. What durable constraints, assets, evidence, or product facts must future work preserve? -If Step 2 produced a clear hypothesis, lead with it: *"From the codebase, this looks like a [web / ios / android / adaptive] project. Does that match?"* For cross-platform apps, decide by the **design language the app renders**, not the toolchain: one look on both platforms (Flutter's Material-everywhere default) takes that platform's value; genuine per-OS adaptation (Cupertino on iOS, Material on Android) is `adaptive`. When in doubt, `web`. +Confirm ambiguous platform separately. Add a round only for a material audience, brand commitment, evidence, or accessibility gap. Record undecided facts instead of inventing them. -A monorepo shipping both a website and a native app gets a PRODUCT.md per app, each with its own `## Platform`; the root PRODUCT.md carries the primary surface's platform. +Do not ask for an aesthetic direction, emotional feel, visual references, colors, typography, or style during init. If the user volunteers a binding visual constraint, record it without expanding it. -### Users & Purpose -- Who uses this? What's their context when using it? -- What job are they trying to get done? -- What is this for? A purpose stated in README or docs is a hypothesis, not strong evidence; confirm it, don't transcribe it. -- What does success look like? -- If more than one kind of user is plausible, confirm a primary and secondary audience; don't manufacture a split that isn't there. An audience implied by another answer (a success metric, a CTA) is still unconfirmed; ask before writing it as secondary. -- If the surface speaks to a different audience than the people who use the product, ask the user to name both. -- For brand: what emotions should the interface evoke? (confidence, delight, calm, urgency) Ask this standalone; don't fold emotions into the success question. -- For product: what workflow are they in? What's the primary task on any given screen? +### What belongs here -### Positioning -- In one line, what does this do that nothing else does? The single strategic claim every screen reinforces. +- users, jobs, workflows, purpose, success, positioning, and operating context; +- capabilities, constraints, terminology, evidence, platform, and accessibility; +- confirmed voice, assets, and brand commitments. -### Brand & Personality -- How would you describe the brand personality in 3 words? -- Reference sites or apps that capture the right feel? What specifically about them? - - Push for specific named references with the *specific* thing about them that fits this brand, not generic "modern" adjectives or category-bucket lanes. -- What should this explicitly NOT look like? Any anti-references? +### What does not belong here -### Conversion & proof (brand register only) -- What's the primary CTA? -- What's the secondary fallback, for visitors not ready for the primary? -- The one line a visitor should remember after 10 seconds. -- What must the visitor believe, in order, before taking the primary CTA? (The template's belief ladder.) -- What proof is on hand? Ask the user to hand over any testimonials, case studies, press, or client/partner logos they already have. If you can receive files directly, collect them; otherwise create `.impeccable/assets/proof/` and ask the user to add files there. Reference supplied files by path; record text proof inline. - -### Accessibility & Inclusion -- Specific accessibility requirements? (WCAG level, known user needs) -- Considerations for reduced motion, color blindness, or other accommodations? - -Skip questions where the answer is already clear. **Do NOT ask about colors, fonts, radii, or visual styling here.** Those belong in DESIGN.md, not PRODUCT.md. +- visual worlds, palettes, typography, components, or page concepts; +- visitor mode, narrative, CTA/proof sequence, or other surface strategy; +- invented testimonials, customers, benchmarks, pricing, licensing, or deployment claims; +- a requirement to decide every optional field. ## Step 4: Write PRODUCT.md -Write PRODUCT.md only after the user has confirmed the strategic answers from Step 3. If an inferred answer is uncertain or unconfirmed, ask before writing. Confirmed means what the user actually said yes to; do not pad a confirmed answer with extras they never picked (additional anti-references, audiences, roadmap claims, a WCAG level), whether drawn from the crawl, another answer, or your own option text. If an extra belongs in the doc, ask about it first. - -Synthesize into a strategic document: +Write only confirmed facts and explicitly marked open decisions. Omit irrelevant sections rather than filling them with generic prose. ```markdown # Product -## Register - -product + ## Platform web ## Users -[Who they are, their context, the job to be done. Primary audience; a secondary audience or a surface-vs-user split only when they apply.] +[Primary users, their situation, and job. Add other audiences only when confirmed.] ## Product Purpose -[What this product does, why it exists, what success looks like] +[What the product does, why it exists, and what success means.] ## Positioning -[The single strategic claim every screen reinforces. Not a visual rule, not an anti-reference.] +[The product mechanism or claim a neighboring product could not truthfully copy.] -## Conversion & proof -[Brand register only. Product register: omit this section entirely, heading included.] -- Primary and secondary CTA: [...] -- The line a visitor remembers after 10 seconds: [...] -- Belief ladder: [...] -- Proof on hand: [testimonials, case studies, press, or logos, referenced by path] +## Operating Context +[Workflows, environments, tools, documents, materials, and rituals that are factual parts of using or evaluating the product.] -## Brand Personality -[Voice, tone, 3-word personality, emotional goals] +## Capabilities and Constraints +[Confirmed functionality, technical constraints, terminology, and explicitly undecided product facts.] -## Anti-references -[What this should NOT look like. Specific bad-example sites or patterns to avoid.] +## Brand Commitments +[Existing name, voice, assets, personality, identity constraints, and references the user explicitly made binding. Omit when none exist.] -## Design Principles -[3-5 strategic principles derived from the conversation. Principles like "practice what you preach", "show, don't tell", "expert confidence". NOT visual rules like "use OKLCH" or "magenta accent".] +## Evidence on Hand +[Real content, data, demonstrations, testimonials, case studies, press, or assets, with paths where applicable. State absences that future work must not fabricate.] + +## Product Principles +[Three to five durable strategic principles derived from confirmed answers; no visual recipes.] ## Accessibility & Inclusion -[WCAG level, known user needs, considerations] +[Known user needs or required standard. Omit when no product-specific requirement was established.] ``` -Register is either `brand` or `product` as a bare value. No prose, no commentary. Platform is `web`, `ios`, `android`, or `adaptive`, also a bare value; omit the section only on legacy files you're leaving untouched, otherwise write `web` explicitly. - -Write fields as prose, and use bold sparingly: only where a word carries a decision, never as a label lead-in on every line. - -Write to `PROJECT_ROOT/PRODUCT.md`. If `.impeccable.md` existed, the loader already renamed it; merge into that content rather than starting from scratch. - -## Step 5: Decide on DESIGN.md - -Offer `$impeccable document` either way. Two paths: - -- **Code exists** (CSS tokens, components, a running site): "I can generate a DESIGN.md that captures your visual system (colors, typography, components) so variants stay on-brand. Want to do that now?" -- **Pre-implementation** (empty project): "I can seed a starter DESIGN.md from five quick questions about color strategy, type direction, motion energy, and references. You can re-run once there's code, to capture the real tokens. Want to do that now?" - -If the user agrees, delegate to `$impeccable document` (it auto-detects scan vs seed). Load its reference and follow that flow. - -If the user prefers to skip, mention they can run `$impeccable document` any time later. - -## Step 6: Configure live mode (when code exists) - -**Skip this step when the platform is native** (`ios` / `android` / `adaptive`): live mode drives a browser overlay. A hybrid wrapper or Expo web target serving HTML doesn't change that. - -If the project has code with HTML entries and a dev server (the same "code exists" condition that puts `$impeccable document` in scan mode), pre-configure live mode now. You already identified the framework and the served HTML entry in Step 2, so this is nearly free, and it spares the user the first-time setup detour when they later run `$impeccable live`. - -**Skip this step for empty / pre-implementation projects** (nothing to inject into yet). Tell the user live mode will configure itself the first time they run it once there's code. +Platform is the bare value `web`, `ios`, `android`, or `adaptive`. Preserve useful legacy headings. New files go at `PROJECT_ROOT/PRODUCT.md`; otherwise update the resolved file. Write it before any visual-world or surface-concept work. -**If `.impeccable/live/config.json` already exists, leave it untouched** and note that live mode is already configured. +Copy the `impeccable:product-schema` comment verbatim, including when you update an older file. It records which version of the product record this file follows, so later versions can tell a deliberately short record from one written before a section existed, and never propose an interview the user has already sat through. Update the number only when this reference's template changes it. Sections a later version retires are reported to you at boot as deprecated; delete them when the user agrees rather than carrying them forward. -Otherwise: +When the platform you just recorded is `ios`, `android`, or `adaptive`, load [ios.md](ios.md), [android.md](android.md), or both before any design work. On a project that had no PRODUCT.md, context.mjs could not know the platform and so never loaded them; init is the only place that learns the answer. -1. Write `.impeccable/live/config.json`. Choose `files` (the HTML entries the browser actually loads), `insertBefore`, and `commentSyntax` from the framework table in [live.md](live.md)'s **First-time setup** section, using the framework you found in Step 2. That table is canonical; do not restate it here. For multi-page static sites, prefer a glob (`["public/**/*.html"]`) over a literal list. -2. Run `node .agents/skills/impeccable/scripts/detect-csp.mjs`. If it reports a patchable shape (`append-arrays` / `append-string`), use the **consent prompt template** from live.md before editing any source file. On decline, skip the patch. For `middleware` / `meta-tag` shapes, surface the detected files and ask the user to add `http://localhost:8400` to `script-src` and `connect-src` manually. For `null`, there's nothing to do. -3. Set `cspChecked: true` in the config once CSP is handled (patched, declined, manual, or not needed). The schema and per-shape patch details live in live.md's First-time setup; follow it rather than duplicating. +### Completion gate -Writing the config file is harmless and needs no consent; only the CSP **source-file patch** requires a yes. +Before loading new-work or resuming shape/build, verify that PRODUCT.md exists at the resolved path and contains the confirmed product record. If the file is absent, init is incomplete. Do not substitute interview notes, a planning packet, or later design prose for the file. -## Step 7: Recommend starting points, then wrap up +## Step 5: Configure live mode when useful -Summarize tersely: -- Register captured (brand / product) and platform captured (web / ios / android / adaptive) -- What was written (PRODUCT.md, DESIGN.md, live config, or a subset) -- The 3-5 strategic principles from PRODUCT.md that will guide future work -- If DESIGN.md or live config is pending, one line on how to set it up later +Skip native or non-runnable projects and leave existing config untouched. Otherwise follow [live.md](live.md)'s first-time setup. Any CSP source edit still requires its stated consent. -Then recommend the **best commands to run next**, drawn from what your Step 2 crawl already surfaced. Do not run a fresh analysis here; surface observations you already have. Tailor to register **and platform**, offer the 2-4 most relevant (not a menu dump), and give the exact command to type. Group by intent: +## Step 6: Wrap up or resume -- **Build something new**: `$impeccable craft ` (shape, then build end-to-end) or `$impeccable shape ` (plan first). Lead with this for empty or early-stage projects. -- **Improve what's there**: name the specific surface. `$impeccable critique ` for a scored UX review; `$impeccable audit ` for a11y / perf / responsive checks; `$impeccable polish ` for a pre-ship pass. When the crawl flagged a specific weakness, point the matching command at it: thin hierarchy or spacing → `layout`, flat or gray palette → `colorize`, missing error / empty states → `harden` or `onboard`, dull or unclear copy → `clarify`. -- **Iterate visually** (web only): `$impeccable live` (configured in Step 6) to pick elements in the browser and generate variants in place. **Skip this group for native platforms.** +Summarize captured and deliberately undecided facts. Do not offer DESIGN.md merely because it is missing. -The full command menu is one bare `$impeccable` away; keep this list short and pointed. +Recommend the next action from the actual project state: -If init was invoked as a blocker by another impeccable command (e.g. the user ran `$impeccable polish` with no PRODUCT.md), resume that original task now. Your own writes are the freshest source; no reload needed. +- Empty or early project: ask naturally for the surface to be built, or use `$impeccable shape ` when the user wants a confirmed brief without implementation. New-work will establish a visual world only when the requested work needs one. +- Existing coherent interface without DESIGN.md: `$impeccable document` if the user wants the incumbent system recorded independently of a new build. +- Existing surface needing work: name the most relevant scoped command. +- Web project ready for visual iteration: `$impeccable live` when configured. -Optionally STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. Ask whether they'd like a brief summary of PRODUCT.md appended to AGENTS.md for easier agent reference. If yes, append a short **Design Context** pointer section there. +If init was invoked by another request, resume without rerunning context.mjs; the native reference above is the one thing that run could not have given you, and new-work owns later visual decisions. diff --git a/.agents/skills/impeccable/reference/interaction-design.md b/.agents/skills/impeccable/reference/interaction-design.md deleted file mode 100644 index c42c9d810..000000000 --- a/.agents/skills/impeccable/reference/interaction-design.md +++ /dev/null @@ -1,189 +0,0 @@ -# Interaction Design - -## The Eight Interactive States - -Every interactive element needs these states designed: - -| State | When | Visual Treatment | -|-------|------|------------------| -| **Default** | At rest | Base styling | -| **Hover** | Pointer over (not touch) | Subtle lift, color shift | -| **Focus** | Keyboard/programmatic focus | Visible ring (see below) | -| **Active** | Being pressed | Pressed in, darker | -| **Disabled** | Not interactive | Reduced opacity, no pointer | -| **Loading** | Processing | Spinner, skeleton | -| **Error** | Invalid state | Red border, icon, message | -| **Success** | Completed | Green check, confirmation | - -**The common miss**: Designing hover without focus, or vice versa. They're different. Keyboard users never see hover states. - -## Focus Rings: Do Them Right - -**Never `outline: none` without replacement.** It's an accessibility violation. Instead, use `:focus-visible` to show focus only for keyboard users: - -```css -/* Hide focus ring for mouse/touch */ -button:focus { - outline: none; -} - -/* Show focus ring for keyboard */ -button:focus-visible { - outline: 2px solid var(--color-accent); - outline-offset: 2px; -} -``` - -**Focus ring design**: -- High contrast (3:1 minimum against adjacent colors) -- 2-3px thick -- Offset from element (not inside it) -- Consistent across all interactive elements - -## Form Design: The Non-Obvious - -**Placeholders aren't labels.** They disappear on input. Always use visible `
+ + + + + + + + +
+
+ Default model + +
+
+ + +
+
+ + + + + + +
+ + + + diff --git a/docs/design/opendesign/os/onboarding.html.artifact.json b/docs/design/opendesign/os/onboarding.html.artifact.json new file mode 100644 index 000000000..21c11f34a --- /dev/null +++ b/docs/design/opendesign/os/onboarding.html.artifact.json @@ -0,0 +1,19 @@ +{ + "version": 1, + "kind": "html", + "title": "os/onboarding.html", + "entry": "os/onboarding.html", + "renderer": "html", + "status": "complete", + "exports": [ + "html", + "pdf", + "zip" + ], + "createdAt": "2026-07-24T22:30:45.656Z", + "updatedAt": "2026-07-24T22:30:45.656Z", + "metadata": { + "inferred": true, + "reconciled": true + } +} \ No newline at end of file diff --git a/docs/design/opendesign/os/onboarding.js b/docs/design/opendesign/os/onboarding.js new file mode 100644 index 000000000..70314c97f --- /dev/null +++ b/docs/design/opendesign/os/onboarding.js @@ -0,0 +1,863 @@ +/* ============================================================ + AGH OS — first-run onboarding + Two steps, mirroring web/src/systems/onboarding: + 1. default model → RuntimeSelector + auth mode (+ bound secret) + 2. workspaces → /api/fs/browse directory browser + selection + The shell renders behind, inert, and wakes when setup commits. + Catalog + selector logic transcribed from + _done/agents/provider-model-reasoning-selector.html. + ============================================================ */ +(() => { +'use strict'; + +const $ = (sel, el = document) => el.querySelector(sel); +const $$ = (sel, el = document) => [...el.querySelectorAll(sel)]; +const esc = (s) => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + +/* ============================================================ + SHELL BACKDROP — dock mirrors app-sidebar.tsx (os-v2 parity) + ============================================================ */ +const ICONS = { + dashboard: '', + sessions: '', + agents: '', + tasks: '', + marketplace: '', + network: '', + vault: '', + loops: '', + jobs: '', + triggers: '', + bridges: '', + knowledge: '', + sandbox: '', +}; +const DOCK_ORDER = [ + 'sessions', 'dashboard', + 'agents', 'network', 'tasks', 'loops', 'jobs', 'triggers', 'sep', + 'marketplace', 'bridges', 'knowledge', 'sep', + 'sandbox', 'vault', +]; +const DOCK_LABEL = { + sessions: 'Sessions', dashboard: 'Dashboard', agents: 'Agents', network: 'Network', + tasks: 'Tasks', loops: 'Loops', jobs: 'Jobs', triggers: 'Triggers', + marketplace: 'Marketplace', bridges: 'Bridges', knowledge: 'Knowledge', + sandbox: 'Sandbox', vault: 'Vault', +}; + +const dockEl = $('#dock'); +const dockZone = $('#dockZone'); +function buildDock() { + dockEl.innerHTML = DOCK_ORDER.map((id, i) => { + if (id === 'sep') return ''; + return ``; + }).join(''); +} +buildDock(); + +/* ============================================================ + CATALOG — mirrors internal/config/provider.go + model-catalog + ============================================================ */ +const HARNESS = { acp: 'cli', pi_acp: 'api key' }; +const EFFORT_ORDER = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']; +const EFFORT_LABEL = { none: 'None', minimal: 'Minimal', low: 'Low', medium: 'Medium', high: 'High', xhigh: 'Extra high', max: 'Max' }; +const effortPos = (e) => { const i = EFFORT_ORDER.indexOf(e); return i < 0 ? 0 : i + 1; }; + +const PROVIDERS = [ + { id: 'claude', name: 'Claude Code', harness: 'acp', auth: 'ready' }, + { id: 'codex', name: 'Codex', harness: 'acp', auth: 'ready' }, + { id: 'gemini', name: 'Gemini CLI', harness: 'acp', auth: 'ready' }, + { id: 'opencode', name: 'OpenCode', harness: 'acp', auth: 'ready' }, + { id: 'cursor', name: 'Cursor Agent', harness: 'acp', auth: 'ready' }, + { id: 'openrouter', name: 'OpenRouter', harness: 'pi_acp', auth: 'ready' }, + { id: 'xai', name: 'xAI', harness: 'pi_acp', auth: 'ready' }, + { id: 'groq', name: 'Groq', harness: 'pi_acp', auth: 'ready' }, + { id: 'moonshot', name: 'Moonshot', harness: 'pi_acp', auth: 'ready' }, + { id: 'zai', name: 'z.ai', harness: 'pi_acp', auth: 'signin' }, +]; +const PROV = {}; PROVIDERS.forEach(p => { PROV[p.id] = p; }); + +const MODELS = [ + { id: 'opus-4.6', provider: 'claude', name: 'Opus 4.6', ctx: 200000, cin: 15, cout: 75, tools: true, reasoning: true, efforts: [], avail: 'live', fav: true, recent: true }, + { id: 'sonnet-4.6', provider: 'claude', name: 'Sonnet 4.6', ctx: 200000, cin: 3, cout: 15, tools: true, reasoning: true, efforts: [], avail: 'live', recent: true }, + { id: 'haiku-4.5', provider: 'claude', name: 'Haiku 4.5', ctx: 200000, cin: 1, cout: 5, tools: true, reasoning: false, efforts: [], avail: 'live' }, + { id: 'gpt-5.4', provider: 'codex', name: 'GPT-5.4', ctx: 400000, cin: 1.25, cout: 10, tools: true, reasoning: true, efforts: ['minimal', 'low', 'medium', 'high', 'xhigh'], def: 'medium', src: 'config', avail: 'live', fav: true, recent: true }, + { id: 'gpt-5.4-mini', provider: 'codex', name: 'GPT-5.4 Mini', ctx: 400000, cin: 0.25, cout: 2, tools: true, reasoning: true, efforts: ['minimal', 'low', 'medium', 'high', 'xhigh'], def: 'low', src: 'config', avail: 'live' }, + { id: 'gpt-5.3', provider: 'codex', name: 'GPT-5.3', ctx: 256000, cin: 1.1, cout: 9, tools: true, reasoning: true, efforts: ['low', 'medium', 'high', 'xhigh'], def: 'medium', src: 'config', avail: 'stale' }, + { id: 'gemini-2.5-pro', provider: 'gemini', name: 'Gemini 2.5 Pro', ctx: 1000000, cin: 1.25, cout: 10, tools: true, reasoning: true, efforts: [], avail: 'live' }, + { id: 'oc-gpt-5.4', provider: 'opencode', name: 'GPT-5.4', ctx: 400000, cin: null, cout: null, tools: true, reasoning: true, efforts: ['low', 'medium', 'high'], def: 'medium', src: 'acp', avail: 'live' }, + { id: 'oc-sonnet', provider: 'opencode', name: 'Sonnet 4.6', ctx: 200000, cin: null, cout: null, tools: true, reasoning: false, efforts: [], avail: 'live' }, + { id: 'cursor-auto', provider: 'cursor', name: 'Auto', ctx: null, cin: null, cout: null, tools: true, reasoning: false, efforts: [], avail: 'live' }, + { id: 'or-deepseek-r1', provider: 'openrouter', name: 'DeepSeek R1', ctx: 128000, cin: 0.55, cout: 2.2, tools: true, reasoning: true, efforts: [], avail: 'live' }, + { id: 'or-llama-3.3', provider: 'openrouter', name: 'Llama 3.3 70B', ctx: 128000, cin: 0.12, cout: 0.3, tools: true, reasoning: false, efforts: [], avail: 'live' }, + { id: 'or-qwen-2.5', provider: 'openrouter', name: 'Qwen 2.5 Coder', ctx: 128000, cin: 0.18, cout: 0.5, tools: true, reasoning: false, efforts: [], avail: 'live' }, + { id: 'grok-4', provider: 'xai', name: 'Grok 4', ctx: 256000, cin: 3, cout: 15, tools: true, reasoning: true, efforts: [], avail: 'live' }, + { id: 'groq-llama-3.3', provider: 'groq', name: 'Llama 3.3 70B', ctx: 128000, cin: 0.59, cout: 0.79, tools: true, reasoning: false, efforts: [], avail: 'live' }, + { id: 'groq-r1-distill', provider: 'groq', name: 'R1 Distill 70B', ctx: 128000, cin: 0.75, cout: 0.99, tools: true, reasoning: true, efforts: [], avail: 'live' }, + { id: 'kimi-k2', provider: 'moonshot', name: 'Kimi K2', ctx: 256000, cin: 0.6, cout: 2.5, tools: true, reasoning: false, efforts: [], avail: 'live' }, + { id: 'glm-4.6', provider: 'zai', name: 'GLM-4.6', ctx: 200000, cin: 0.6, cout: 2.2, tools: true, reasoning: false, efforts: [], avail: 'unavailable', reason: 'Sign in' }, +]; +const MODEL = {}; MODELS.forEach(m => { MODEL[m.id] = m; }); + +/* ---- provider marks (packages/ui/src/logos) ---- */ +const LOGO = { + claude: { vb: '0 0 256 257', inner: '' }, + codex: { vb: '0 0 721 721', inner: '' }, + gemini: { vb: '0 0 296 298', inner: '' }, + cursor: { vb: '0 0 466.73 532.09', inner: '' }, + openrouter: { vb: '0 0 24 24', inner: '' }, + xai: { vb: '0 0 841.89 595.28', inner: '' }, + groq: { vb: '0 0 201 201', fill: true, inner: '' }, + moonshot: { vb: '0 0 1024 1024', inner: '' }, + zai: { vb: '0 0 30 30', inner: '' }, +}; +function glyphSVG(id) { + const L = LOGO[id]; + if (!L) return ''; + return `${L.inner}`; +} +const glyphTile = (cls, id) => `${glyphSVG(id)}`; + +function icon(name) { + const p = { + chev: '', + warn: '', + tools: '', + brain: '', + plus: '', + star: '', + gear: '', + all: '', + }[name]; + return `${p}`; +} +const starSvg = (fill) => ``; + +const fmtCtx = (t) => t == null ? null : t >= 1e6 ? `${t / 1e6}M` : t >= 1000 ? `${Math.round(t / 1000)}k` : String(t); +const fmtCost = (m) => m.cin == null ? null : `$${m.cin}/${m.cout}`; +function imHTML(level, hollow) { + let out = ``; + for (let i = 1; i <= 7; i++) out += ``; + return `${out}`; +} +function reasoningStateFor(m) { + if (m.efforts && m.efforts.length) return { mode: 'levels', levels: m.efforts, def: m.def || m.efforts[0], src: m.src }; + if (m.reasoning) return { mode: 'supported-nolevels' }; + return { mode: 'none' }; +} + +/* ============================================================ + REASONING RANGE SELECTOR (runtime-selector/reasoning-bar.tsx) + ============================================================ */ +function makeSlider(host, cfg) { + const order = (cfg.levels || []).slice().sort((a, b) => effortPos(a) - effortPos(b)); + const values = [''].concat(order); + const last = values.length - 1; + const el = document.createElement('div'); + el.className = 'rz'; + let labels = '', stops = ''; + values.forEach((v, i) => { + const p = last > 0 ? i / last : 0; + const pos = `left:calc(${p}*(100% - var(--rz-h)) + var(--rz-h)/2)`; + let lpos = pos, edge = ''; + if (i === 0) { lpos = 'left:0'; edge = ' data-edge="start"'; } + else if (i === last) { lpos = 'right:0'; edge = ' data-edge="end"'; } + labels += ``; + stops += ``; + }); + el.innerHTML = `
${labels}
` + + `
` + + `
${stops}
`; + host.innerHTML = ''; + host.appendChild(el); + + const track = $('.rz__track', el); + const labelEls = $$('.rz__label', el); + let idx = Math.max(0, values.indexOf(cfg.value || '')); + + const markNearest = (i) => { + el.setAttribute('data-default', i === 0 ? 'true' : 'false'); + labelEls.forEach((l, k) => l.setAttribute('data-on', k === i ? 'true' : 'false')); + }; + const paint = () => { + el.style.setProperty('--rz-p', last > 0 ? idx / last : 0); + markNearest(idx); + track.setAttribute('aria-valuenow', String(idx)); + track.setAttribute('aria-valuetext', idx === 0 ? `Provider default (${EFFORT_LABEL[cfg.def] || 'auto'})` : EFFORT_LABEL[values[idx]]); + }; + const commit = (i) => { + i = Math.max(0, Math.min(last, i)); + const changed = i !== idx; + idx = i; paint(); + if (changed) cfg.onChange?.(values[idx]); + }; + labelEls.forEach(l => l.addEventListener('click', () => { commit(parseInt(l.dataset.idx, 10)); track.focus(); })); + + const pFrom = (ev) => { + const r = track.getBoundingClientRect(), pad = r.height / 2; + return Math.max(0, Math.min(1, (ev.clientX - r.left - pad) / Math.max(1, r.width - 2 * pad))); + }; + let drag = null; + track.addEventListener('pointerdown', ev => { + if (ev.button) return; + drag = { sx: ev.clientX, engaged: false }; + track.setPointerCapture(ev.pointerId); + }); + track.addEventListener('pointermove', ev => { + if (!drag) return; + if (!drag.engaged) { + if (Math.abs(ev.clientX - drag.sx) < 3) return; + drag.engaged = true; el.classList.add('is-dragging'); + } + const p = pFrom(ev); + el.style.setProperty('--rz-p', p); + markNearest(Math.round(p * last)); + }); + track.addEventListener('pointerup', ev => { + if (!drag) return; + drag = null; el.classList.remove('is-dragging'); + commit(Math.round(pFrom(ev) * last)); + track.focus(); + }); + track.addEventListener('pointercancel', () => { if (drag) { drag = null; el.classList.remove('is-dragging'); paint(); } }); + track.addEventListener('keydown', e => { + if (e.key === 'ArrowRight' || e.key === 'ArrowUp') { e.preventDefault(); commit(idx + 1); } + else if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') { e.preventDefault(); commit(idx - 1); } + else if (e.key === 'Home') { e.preventDefault(); commit(0); } + else if (e.key === 'End') { e.preventDefault(); commit(last); } + }); + paint(); +} + +/* ============================================================ + ONBOARDING DRAFT (stores/use-onboarding-draft-store.ts) + ============================================================ */ +const draft = { + step: 1, + maxStep: 1, + provider: 'claude', + model: 'opus-4.6', + reasoning: '', + authMode: 'native_cli', + envVar: '', + apiKey: '', + workspaces: [], +}; +const envVarFor = (id) => `${id.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_API_KEY`; +const defaultAuthFor = (id) => (PROV[id]?.harness === 'pi_acp' ? 'bound_secret' : 'native_cli'); + +/* ============================================================ + RUNTIME SELECTOR — trigger + popup + ============================================================ */ +const LS = { fav: 'agh:pmr:fav', recent: 'agh:pmr:recent' }; +const lsLoad = (k, d) => { try { const v = localStorage.getItem(k); return v ? JSON.parse(v) : d; } catch { return d; } }; +const lsSave = (k, v) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch { /* private mode */ } }; +let favSet = lsLoad(LS.fav, {}); +let recentList = lsLoad(LS.recent, null) || MODELS.filter(m => m.recent).map(m => m.id); +MODELS.forEach(m => { if (m.fav) favSet[m.id] = true; }); + +const trigger = document.createElement('div'); +trigger.className = 'pmr'; +trigger.setAttribute('role', 'group'); +trigger.setAttribute('data-open', 'false'); +trigger.setAttribute('aria-labelledby', 'obRuntimeLabel'); +trigger.setAttribute('data-od-id', 'pmr-trigger'); +$('#obRuntimeMount').appendChild(trigger); + +function renderTrigger() { + const m = MODEL[draft.model], p = PROV[m.provider]; + const rz = reasoningStateFor(m); + const needsAuth = p.auth !== 'ready' || m.avail === 'unavailable'; + let html = `` + + ``; + if (rz.mode === 'levels') { + const cur = draft.reasoning || rz.def; + const isDefault = !draft.reasoning; + html += ``; + } + if (needsAuth) { + const why = m.reason || 'Needs sign in'; + html += `${icon('warn')}`; + } + html += ``; + trigger.innerHTML = html; + $$('[data-focus]', trigger).forEach(seg => { + seg.addEventListener('click', e => { e.stopPropagation(); openPopup(seg.dataset.focus); }); + }); +} + +function renderFacts() { + const m = MODEL[draft.model], p = PROV[m.provider]; + const parts = []; + const ctx = fmtCtx(m.ctx); if (ctx) parts.push(`${ctx} context`); + const cost = fmtCost(m); if (cost) parts.push(`${cost} per Mtok`); + if (m.tools) parts.push('tool calls'); + const rz = reasoningStateFor(m); + if (rz.mode === 'levels') parts.push(`${m.efforts.length} reasoning levels`); + else if (rz.mode === 'supported-nolevels') parts.push('reasoning on'); + parts.push(`${HARNESS[p.harness]} harness`); + $('#obFacts').innerHTML = parts.join(''); +} + +/* ---- popup ---- */ +const pop = $('#rsel'); +const popList = $('#rselList'); +const popRail = $('#rselRail'); +const popRz = $('#rselRz'); +const popSearch = $('#rselSearch'); +const popRefresh = $('#rselRefresh'); +let popOpen = false, railFilter = 'all', query = '', hlIndex = -1; + +function openPopup(focus) { + popOpen = true; railFilter = 'all'; query = ''; popSearch.value = ''; hlIndex = -1; + trigger.setAttribute('data-open', 'true'); + renderRail(); renderList(); renderRz(); + positionPopup(); + pop.setAttribute('data-show', 'true'); + setTimeout(() => { + if (focus === 'reasoning') { const t = $('.rz__track', popRz); if (t) return t.focus(); } + if (focus === 'provider') { const a = $(`.rail__item[data-rail="${draft.provider}"]`, popRail); if (a) return a.focus(); } + popSearch.focus(); + }, 20); + document.addEventListener('mousedown', onDocDown, true); +} +function closePopup() { + if (!popOpen) return; + popOpen = false; + trigger.setAttribute('data-open', 'false'); + pop.setAttribute('data-show', 'false'); + document.removeEventListener('mousedown', onDocDown, true); +} +function onDocDown(e) { if (!pop.contains(e.target) && !trigger.contains(e.target)) closePopup(); } + +function positionPopup() { + const r = trigger.getBoundingClientRect(); + const shown = pop.getAttribute('data-show') === 'true'; + pop.style.visibility = 'hidden'; pop.setAttribute('data-show', 'true'); + const pw = pop.offsetWidth, ph = pop.offsetHeight; + pop.style.visibility = ''; + if (!shown) pop.setAttribute('data-show', 'false'); + let left = r.left, top = r.bottom + 6; + left = Math.max(12, Math.min(left, window.innerWidth - pw - 12)); + if (top + ph > window.innerHeight - 12) top = Math.max(12, r.top - ph - 6); + pop.style.left = `${left}px`; + pop.style.top = `${top}px`; +} + +const railBtn = (id, svg, title, on) => ``; +function renderRail() { + const searching = query.trim().length > 0; + let html = railBtn('all', icon('all'), 'All models', railFilter === 'all') + + railBtn('fav', starSvg(false), 'Favorites', railFilter === 'fav') + + '
'; + PROVIDERS.forEach(p => { + const dim = p.auth !== 'ready'; + html += ``; + }); + html += ``; + popRail.innerHTML = html; + popRail.style.opacity = searching ? '.45' : '1'; + popRail.style.pointerEvents = searching ? 'none' : 'auto'; + $$('.rail__item', popRail).forEach(b => b.addEventListener('click', () => { + const v = b.dataset.rail; + if (v === '__settings') { b.style.color = 'var(--accent-strong)'; setTimeout(() => { b.style.color = ''; }, 500); return; } + railFilter = v; hlIndex = -1; renderRail(); renderList(); popSearch.focus(); + })); +} + +function matchQ(m, p) { + const q = query.trim().toLowerCase(); + if (!q) return true; + const hay = `${m.name} ${p.name} ${m.id} ${m.provider}`.toLowerCase(); + return q.split(/\s+/).every(tok => hay.includes(tok)); +} +function providerAvail(p, ms) { + if (p.auth === 'signin') return { cls: 'av-off', label: 'Sign in' }; + if (ms.some(m => m.avail === 'stale')) return { cls: 'av-stale', label: 'Stale' }; + return { cls: 'av-live', label: 'Live' }; +} +function groupHead(name, harness, avail) { + let h = `
${esc(name)}`; + if (harness) h += `${HARNESS[harness]}`; + if (avail) h += `${avail.label}`; + return `${h}
`; +} +function rowHTML(m) { + const p = PROV[m.provider]; + const sel = draft.model === m.id; + const disabled = m.avail === 'unavailable' || p.auth === 'signin'; + let chips = ''; + const ctx = fmtCtx(m.ctx); if (ctx) chips += `${ctx}`; + const cost = fmtCost(m); if (cost) chips += `${chips ? '' : ''}${cost}`; + if (m.tools) chips += `${chips ? '' : ''}${icon('tools')}tools`; + if (m.efforts && m.efforts.length) chips += `${chips ? '' : ''}${icon('brain')}${m.efforts.length} levels`; + else if (m.reasoning) chips += `${chips ? '' : ''}${icon('brain')}reasoning`; + let right = disabled ? `${esc(m.reason || 'Sign in')}` : ''; + right += `${starSvg(!!favSet[m.id])}`; + return `
` + + glyphTile('mrow__glyph', m.provider) + + `${esc(m.name)}` + + `${esc(p.name)}${chips}` + + `${right}
`; +} +function renderList() { + const searching = query.trim().length > 0; + let html = '', any = false; + if (!searching && (railFilter === 'all' || railFilter === 'fav')) { + const favModels = MODELS.filter(m => favSet[m.id]); + const seen = new Set(); + const pinned = (railFilter === 'fav' ? favModels : recentList.map(id => MODEL[id]).filter(Boolean).concat(favModels)) + .filter(m => m && !seen.has(m.id) && seen.add(m.id)); + if (pinned.length) { + html += groupHead(railFilter === 'fav' ? 'Favorites' : 'Recent & favorites'); + pinned.forEach(m => { html += rowHTML(m); any = true; }); + } + if (railFilter === 'fav') return finishList(html, any); + } + const provs = PROVIDERS.filter(p => (railFilter === 'all' || railFilter === 'fav') ? true : p.id === railFilter); + provs.forEach(p => { + const ms = MODELS.filter(m => m.provider === p.id && matchQ(m, p)); + if (!ms.length) return; + html += groupHead(p.name, p.harness, providerAvail(p, ms)); + ms.forEach(m => { html += rowHTML(m); any = true; }); + }); + if (!any) html = `
No models match “${esc(query.trim())}”.
Try a provider name, or a shorter query.
`; + finishList(html, any); +} +function finishList(html, any) { + popList.innerHTML = html; + if (!any) return; + $$('.mrow', popList).forEach(row => { + const id = row.dataset.model; + row.addEventListener('click', e => { + if (e.target.closest('.mrow__star')) return; + if (row.dataset.disabled === 'true') return; + pickModel(id); + }); + const star = $('.mrow__star', row); + star?.addEventListener('click', e => { + e.stopPropagation(); + if (favSet[id]) delete favSet[id]; else favSet[id] = true; + lsSave(LS.fav, favSet); renderList(); + }); + }); + paintHighlight(); +} +function renderRz() { + const m = MODEL[draft.model]; + const rz = reasoningStateFor(m); + if (rz.mode === 'none') { + popRz.innerHTML = `
${icon('brain')}This model doesn’t use reasoning effort; the provider handles it.
`; + return; + } + if (rz.mode === 'supported-nolevels') { + popRz.innerHTML = `
${icon('brain')}Reasoning is on. ${esc(PROV[m.provider].name)} doesn’t expose selectable effort for ${esc(m.name)}.
`; + return; + } + popRz.innerHTML = `
Reasoning effort` + + `${esc(PROV[m.provider].name)} · ${esc(m.name)}` + + `${rz.src === 'acp' ? 'ACP' : 'catalog'}
`; + makeSlider($('.rzbar__slider', popRz), { + levels: rz.levels, def: rz.def, value: draft.reasoning, model: m.name, + onChange: (v) => { draft.reasoning = v || ''; renderTrigger(); renderFacts(); syncFooter(); positionPopup(); }, + }); +} +function pickModel(id) { + const m = MODEL[id]; + if (!m) return; + const providerChanged = m.provider !== draft.provider; + draft.provider = m.provider; + draft.model = id; + const rz = reasoningStateFor(m); + if (rz.mode !== 'levels' || (draft.reasoning && !rz.levels.includes(draft.reasoning))) draft.reasoning = ''; + // provider change clears bound credentials (use-onboarding-default-model.ts) + if (providerChanged) { + draft.envVar = ''; draft.apiKey = ''; + draft.authMode = defaultAuthFor(draft.provider); + syncAuth(); + } + const seen = new Set(); + recentList = [id, ...recentList].filter(x => !seen.has(x) && seen.add(x)).slice(0, 6); + lsSave(LS.recent, recentList); + renderList(); renderRz(); renderTrigger(); renderFacts(); syncFooter(); positionPopup(); +} +function paintHighlight() { + const rows = $$('.mrow', popList); + rows.forEach((r, i) => r.setAttribute('data-hl', i === hlIndex ? 'true' : 'false')); + const r = rows[hlIndex]; + if (!r) return; + const top = r.offsetTop, h = r.offsetHeight, st = popList.scrollTop, vh = popList.clientHeight; + if (top < st) popList.scrollTop = top - 6; + else if (top + h > st + vh) popList.scrollTop = top + h - vh + 6; +} +function moveHL(dir) { + const rows = $$('.mrow', popList); + const enabled = rows.map((r, i) => r.dataset.disabled !== 'true' ? i : -1).filter(i => i >= 0); + if (!enabled.length) return; + if (hlIndex < 0) hlIndex = enabled[0]; + else { + const pos = enabled.indexOf(hlIndex); + hlIndex = pos < 0 ? enabled[0] : enabled[(pos + dir + enabled.length) % enabled.length]; + } + paintHighlight(); +} +popSearch.addEventListener('input', () => { query = popSearch.value; hlIndex = -1; renderRail(); renderList(); }); +popRefresh.addEventListener('click', () => { + popRefresh.classList.add('spin'); + setTimeout(() => { popRefresh.classList.remove('spin'); renderList(); }, 520); +}); +window.addEventListener('resize', () => { if (popOpen) positionPopup(); }); + +/* ============================================================ + STEP 1 — authentication mode + ============================================================ */ +const authWrap = $('#obAuth'); +const keyFields = $('#obKeyFields'); +const envInput = $('#obEnvVar'); +const keyInput = $('#obApiKey'); + +function syncAuth() { + $$('.authc', authWrap).forEach(b => b.setAttribute('aria-pressed', String(b.dataset.auth === draft.authMode))); + keyFields.hidden = draft.authMode !== 'bound_secret'; + envInput.placeholder = envVarFor(draft.provider); + envInput.value = draft.envVar; + keyInput.value = draft.apiKey; + measurePane(); +} +$$('.authc', authWrap).forEach(b => b.addEventListener('click', () => { + draft.authMode = b.dataset.auth; + if (draft.authMode === 'native_cli') { draft.envVar = ''; draft.apiKey = ''; } + syncAuth(); syncFooter(); + if (draft.authMode === 'bound_secret') envInput.focus(); +})); +envInput.addEventListener('input', () => { draft.envVar = envInput.value; syncFooter(); }); +keyInput.addEventListener('input', () => { draft.apiKey = keyInput.value; syncFooter(); }); + +/* ============================================================ + STEP 2 — directory browser (GET /api/fs/browse, dirs_only) + ============================================================ */ +const HOME = '/Users/pedro'; +const FS = { + '/': ['Applications', 'Library', 'System', 'Users'], + '/Users': ['pedro', 'Shared'], + '/Users/pedro': ['Desktop', 'Developer', 'Documents', 'Downloads', 'Projects'], + '/Users/pedro/Desktop': [], + '/Users/pedro/Developer': ['compozy', 'courses', 'labs', 'oss'], + '/Users/pedro/Developer/compozy': ['agh', 'looper', 'pi', 'releasepr'], + '/Users/pedro/Developer/compozy/agh': ['cmd', 'internal', 'packages', 'web'], + '/Users/pedro/Developer/compozy/looper': [], + '/Users/pedro/Developer/compozy/pi': [], + '/Users/pedro/Developer/compozy/releasepr': [], + '/Users/pedro/Developer/courses': ['branas'], + '/Users/pedro/Developer/courses/branas': ['branasio'], + '/Users/pedro/Developer/courses/branas/branasio': [], + '/Users/pedro/Developer/labs': ['sketches'], + '/Users/pedro/Developer/labs/sketches': [], + '/Users/pedro/Developer/oss': [], + '/Users/pedro/Documents': ['notes'], + '/Users/pedro/Documents/notes': [], + '/Users/pedro/Downloads': [], + '/Users/pedro/Projects': ['field-notes'], + '/Users/pedro/Projects/field-notes': [], + '/Applications': [], '/Library': [], '/System': [], '/Users/Shared': [], + '/Users/pedro/Developer/compozy/agh/cmd': [], '/Users/pedro/Developer/compozy/agh/internal': [], + '/Users/pedro/Developer/compozy/agh/packages': [], '/Users/pedro/Developer/compozy/agh/web': [], +}; +const parentOf = (p) => (p === '/' ? null : p.replace(/\/[^/]+$/, '') || '/'); +const basename = (p) => p.replace(/\/+$/, '').split('/').pop() || p; + +let cwd = HOME; +const dbPath = $('#dbPath'); +const dbList = $('#dbList'); +const dbUse = $('#dbUse'); +const wsListEl = $('#wsList'); +const wsEmpty = $('#wsEmpty'); +const wsCount = $('#wsCount'); + +const isAdded = (p) => draft.workspaces.some(w => w.path === p); + +function renderBrowser() { + dbPath.textContent = cwd; + dbPath.title = cwd; + $('#dbHome').disabled = cwd === HOME; + $('#dbUp').disabled = parentOf(cwd) === null; + dbUse.disabled = isAdded(cwd); + const entries = FS[cwd] || []; + if (!entries.length) { + dbList.innerHTML = '

No sub-folders here. Use this folder, or step back up.

'; + return; + } + dbList.innerHTML = entries.map(name => { + const path = cwd === '/' ? `/${name}` : `${cwd}/${name}`; + const added = isAdded(path); + return `
+ + +
`; + }).join(''); + $$('[data-nav]', dbList).forEach(b => b.addEventListener('click', () => { cwd = b.dataset.nav; renderBrowser(); })); + $$('[data-add]', dbList).forEach(b => b.addEventListener('click', () => addWorkspace(b.dataset.add))); +} +$('#dbHome').addEventListener('click', () => { cwd = HOME; renderBrowser(); }); +$('#dbUp').addEventListener('click', () => { const p = parentOf(cwd); if (p) { cwd = p; renderBrowser(); } }); +dbUse.addEventListener('click', () => addWorkspace(cwd)); + +function addWorkspace(path) { + if (!path || isAdded(path)) return; + draft.workspaces.push({ path, name: basename(path) }); + renderBrowser(); renderWorkspaces(); syncFooter(); syncShellWorkspace(); +} +function removeWorkspace(path) { + draft.workspaces = draft.workspaces.filter(w => w.path !== path); + renderBrowser(); renderWorkspaces(); syncFooter(); syncShellWorkspace(); +} +function renderWorkspaces() { + const n = draft.workspaces.length; + wsCount.textContent = `${n} folder${n === 1 ? '' : 's'}`; + wsEmpty.hidden = n > 0; + wsListEl.hidden = n === 0; + wsListEl.innerHTML = draft.workspaces.map(w => `
  • + + ${esc(w.name)}${esc(w.path)} +
  • `).join(''); + $$('[data-rm]', wsListEl).forEach(b => b.addEventListener('click', () => removeWorkspace(b.dataset.rm))); +} +/* the menu bar fills in behind the scrim as soon as a workspace resolves */ +function syncShellWorkspace() { + const first = draft.workspaces[0]; + const trig = $('#wsTrigger'); + $('#wsName').textContent = first ? first.name : 'No workspace'; + $('#wsAvatar').textContent = first ? first.name.slice(0, 2).toUpperCase() : '··'; + trig.dataset.empty = String(!first); +} + +/* ============================================================ + WIZARD (hooks/use-onboarding-wizard.ts) + ============================================================ */ +const ob = $('#ob'); +const obBody = $('#obBody'); +const backBtn = $('#obBack'); +const nextBtn = $('#obNext'); +const sumEl = $('#obSum'); +const sumLabel = $('#obSumLabel'); +const sumValue = $('#obSumValue'); + +const paneOf = (n) => $(`.ob__pane[data-pane="${n}"]`); + +function configurationError() { + if (draft.step !== 1) return null; + if (draft.authMode === 'bound_secret' && draft.envVar.trim() === '') { + return 'Enter the environment variable the provider expects.'; + } + return null; +} +function canContinue() { + if (draft.step === 1) return configurationError() === null; + return draft.workspaces.length > 0; +} + +function syncFooter() { + const err = configurationError(); + envInput.setAttribute('aria-invalid', String(!!err && draft.authMode === 'bound_secret')); + if (err) { + sumEl.dataset.tone = 'error'; + sumLabel.textContent = 'Needs an answer'; + sumValue.textContent = err; + } else if (draft.step === 1) { + const m = MODEL[draft.model], p = PROV[m.provider]; + const rz = reasoningStateFor(m); + const bits = [p.name, m.name]; + if (rz.mode === 'levels') bits.push(draft.reasoning ? EFFORT_LABEL[draft.reasoning] : 'default effort'); + bits.push(draft.authMode === 'native_cli' ? 'CLI sign-in' : draft.envVar.trim() || 'bound key'); + sumEl.dataset.tone = 'ok'; + sumLabel.textContent = 'Saves as your default'; + sumValue.textContent = bits.join(' · '); + } else { + const n = draft.workspaces.length; + sumEl.dataset.tone = 'ok'; + sumLabel.textContent = 'Workspaces'; + sumValue.textContent = n === 0 + ? 'None yet — add at least one folder to finish.' + : `${n} folder${n === 1 ? '' : 's'} · ${draft.workspaces.map(w => w.name).join(', ')}`; + } + nextBtn.disabled = !canContinue(); +} + +/* The pane is stretched to the body, so its own scrollHeight can never + report less than the current height. `.ob__inner` is the flow-sized + content box, so its offsetHeight is the step's natural height. */ +function measurePane() { + const pane = paneOf(draft.step); + const inner = pane && $('.ob__inner', pane); + if (!inner) return; + if (window.matchMedia('(max-width: 759px)').matches) { obBody.style.removeProperty('--ob-h'); return; } + const chrome = 52 + 44 + 58; + const max = Math.max(280, window.innerHeight - 48 - chrome); + obBody.style.setProperty('--ob-h', `${Math.min(inner.offsetHeight, max)}px`); +} + +function renderSteps() { + $$('.ob__step', $('#obSteps')).forEach(btn => { + const n = Number(btn.dataset.goto); + const state = n < draft.step ? 'done' : n === draft.step ? 'on' : 'off'; + btn.dataset.state = state; + btn.disabled = n > draft.maxStep; + btn.setAttribute('aria-current', state === 'on' ? 'step' : 'false'); + const num = $('.ob__num', btn); + num.innerHTML = state === 'done' + ? '' + : String(n); + }); +} + +function goToStep(n) { + if (n < 1 || n > 2 || n > draft.maxStep || n === draft.step) return; + closePopup(); + const prev = paneOf(draft.step); + draft.step = n; + ob.dataset.step = String(n); + const pane = paneOf(n); + prev.hidden = true; + pane.hidden = false; + pane.dataset.enter = 'true'; + setTimeout(() => pane.removeAttribute('data-enter'), 320); + renderSteps(); + backBtn.disabled = n === 1; + nextBtn.textContent = n === 2 ? 'Finish setup' : 'Continue'; + measurePane(); + syncFooter(); + const landing = n === 2 + ? (dbUse.disabled ? $('.drow__nav', dbList) : dbUse) + : $('.pmr__seg', trigger); + landing?.focus(); +} + +backBtn.addEventListener('click', () => goToStep(draft.step - 1)); +nextBtn.addEventListener('click', () => { + if (!canContinue()) return; + if (draft.step === 1) { + draft.maxStep = 2; + renderSteps(); + goToStep(2); + return; + } + finish(); +}); +$$('.ob__step', $('#obSteps')).forEach(btn => btn.addEventListener('click', () => goToStep(Number(btn.dataset.goto)))); + +/* ============================================================ + COMMIT — POST /api/onboarding/complete, then the shell wakes + ============================================================ */ +function finish() { + nextBtn.disabled = true; + nextBtn.innerHTML = 'Finishing…'; + setTimeout(unlockShell, 720); +} + +function unlockShell() { + const scrim = $('#obScrim'); + scrim.classList.add('is-leaving'); + document.body.dataset.onboarding = 'done'; + setTimeout(() => { + scrim.remove(); + closePopup(); + pop.remove(); + $('#os').removeAttribute('inert'); + dockZone.dataset.locked = 'false'; + $('#deskHint').hidden = false; + setTimeout(() => $$('.dock-item').forEach(el => { el.style.transitionDelay = ''; }), 700); + const m = MODEL[draft.model], p = PROV[m.provider]; + const n = draft.workspaces.length; + toast({ + title: `${draft.workspaces[0].name} · ready`, + body: `Default model ${esc(p.name)} / ${esc(m.name)} · ${n} workspace${n === 1 ? '' : 's'} registered. Sessions start from the dock or ⌘K.`, + actions: [ + { label: 'Open AGH', primary: true, run: () => { window.location.href = 'agh-os-v2.html'; } }, + { label: 'Run setup again', run: () => window.location.reload() }, + ], + }); + }, 300); +} + +/* dock + hint hand off to the running shell once setup is done */ +dockEl.addEventListener('click', e => { + if (document.body.dataset.onboarding !== 'done') return; + if (e.target.closest('.dock-item')) window.location.href = 'agh-os-v2.html'; +}); +$('#dockNew').addEventListener('click', () => { + if (document.body.dataset.onboarding === 'done') window.location.href = 'agh-os-v2.html'; +}); + +function toast({ title, body, actions = [], timeout = 14000 }) { + const el = document.createElement('div'); + el.className = 'toast'; + el.innerHTML = `
    ${title}
    +

    ${body}

    + ${actions.length ? `
    ${actions.map((a, i) => ``).join('')}
    ` : ''}`; + $('#toasts').appendChild(el); + const dismiss = () => { el.classList.add('is-leaving'); setTimeout(() => el.remove(), 240); }; + actions.forEach((a, i) => $(`[data-ta="${i}"]`, el).addEventListener('click', () => { dismiss(); a.run?.(); })); + setTimeout(dismiss, timeout); +} + +/* ============================================================ + KEYBOARD + FOCUS CONTAINMENT + ============================================================ */ +document.addEventListener('keydown', e => { + if (e.key === 'Escape' && popOpen) { e.preventDefault(); closePopup(); return; } + if (popOpen) { + if (e.target.closest?.('.rz')) return; // the slider owns its own keys + if (e.key === 'ArrowDown') { e.preventDefault(); moveHL(1); return; } + if (e.key === 'ArrowUp') { e.preventDefault(); moveHL(-1); return; } + if (e.key === 'Enter') { + const row = $$('.mrow', popList)[hlIndex]; + if (row && row.dataset.disabled !== 'true') { e.preventDefault(); pickModel(row.dataset.model); } + } + return; + } + if (e.key === 'Enter' && (e.metaKey || e.ctrlKey) && document.body.dataset.onboarding === 'active') { + e.preventDefault(); nextBtn.click(); + } +}); +/* setup blocks the shell: focus never escapes the panel while it is open */ +document.addEventListener('focusin', e => { + if (document.body.dataset.onboarding !== 'active') return; + const scrim = $('#obScrim'); + if (!scrim || scrim.contains(e.target) || pop.contains(e.target)) return; + trigger.querySelector('.pmr__seg')?.focus(); +}); +window.addEventListener('resize', measurePane); + +/* ============================================================ + BOOT + ============================================================ */ +draft.authMode = defaultAuthFor(draft.provider); +renderTrigger(); +renderFacts(); +syncAuth(); +renderBrowser(); +renderWorkspaces(); +syncShellWorkspace(); +renderSteps(); +syncFooter(); +measurePane(); +requestAnimationFrame(measurePane); +document.fonts?.ready.then(measurePane); + +})(); diff --git a/docs/design/opendesign/settings/LAYOUTS-IMPLEMENTATION-SPEC.md b/docs/design/opendesign/settings/LAYOUTS-IMPLEMENTATION-SPEC.md new file mode 100644 index 000000000..085c50ca5 --- /dev/null +++ b/docs/design/opendesign/settings/LAYOUTS-IMPLEMENTATION-SPEC.md @@ -0,0 +1,327 @@ +# Settings › Layouts — implementation spec + +Work order to land `settings/settings-layouts.html` in `web/`. +Design rationale and field map: `LAYOUTS-REDESIGN-SPEC.md` (read it first — this document does not repeat the "why"). + +Status: **draft, not started.** +Owning surface: `web/src/systems/settings/` + `web/src/routes/_app/settings/layouts.tsx`. +Breaking change: yes — 11 components are deleted outright (§4). No compat shims, no aliases; this is a hard cut per the greenfield rule. + +--- + +## 1. The load-bearing discovery — do not write geometry code + +**The projector this redesign needs already exists and is already shipping in the OS shell.** + +| Existing | What it gives the settings canvas | +|---|---| +| `web/src/systems/os/lib/layout-projection.ts:371` — `projectLayout(input): LayoutProjection` | pixel rects for every window, stack and **seam** on a desktop, from the same normalized document the daemon stores | +| `ProjectedSeam` (`os/lib/window-manager-types.ts`) | per-boundary `{ id, splitId, boundaryIndex, orientation, rect, value, minValue, maxValue, axisSpan, leadingWeight, trailingWeight }` — a complete drag contract with the identity `layout.resize` uses | +| `web/src/systems/os/lib/seam-preview.ts:23` — `seamWeightDelta(seam, deltaPx)` | pixel delta → weight delta, clamped by the projection minimums **and** the daemon's `MIN_SPLIT_WEIGHT` floor, mirroring `reducer_layout_resize.go` | +| `seam-preview.ts:36` — `applySeamPreviewToDesktop(desktop, seam, deltaPx): LayoutDesktop` | pure, immutable, returns a new desktop with the boundary moved and the weight vector still summing to 1 | +| `os/lib/layout-projection.ts:407` — `clampFloatingRect(input)` | keeps a dragged floating window inside the work area, preserving the title-bar grab relationship | + +Consequences, and these are not optional: + +1. **The settings canvas renders `projectLayout()` output.** It does not compute its own rects. This is what makes the preview *truthful* — it is pixel-identical to what the runtime will render, including the `adaptive-stack` and `minimum-unmet` diagnostics, which the settings editor has never shown. +2. **Seam drags call `applySeamPreviewToDesktop`.** Bug D-2 (§3) then cannot recur, because that function is already a mirror of the reducer and preserves the sum-to-1 invariant by construction. Do not hand-roll pairwise rebalancing in `systems/settings/`. +3. **`useLayoutSeam` (`os/hooks/use-layout-seam.ts`) is NOT reusable as-is** — it dispatches live `layout.resize` commands against the runtime store. Settings edits a *draft document*. Reuse the two pure functions from `seam-preview.ts`; write a separate `use-layout-draft-seam.ts` that applies them to the draft instead of dispatching. +4. `projectLayout` currently lives under `systems/os/`. Settings importing from `systems/os/lib/` is a cross-system import — check `make lint` boundaries before writing the import. If the boundary rule forbids it, the fix is to **move** `layout-projection.ts`, `seam-preview.ts`, `window-manager-types.ts` and `window-manager-schemas.ts` into a shared `systems/window-manager/` module consumed by both `os` and `settings` — not to duplicate them. Duplicating geometry is a blocking failure. + +--- + +## 2. Current inventory + +| File | LOC | Fate | +|---|---:|---| +| `routes/_app/settings/layouts.tsx` | 11 | keep | +| `routes/_app/settings/-layouts-settings-page.tsx` | 167 | rewrite (composition only) | +| `settings/components/window-manager-layout-document-editor.tsx` | 220 | **delete** → canvas + review bar | +| `settings/components/window-manager-layout-node-editor.tsx` | 208 | **delete** → inspector + `layout-mutations.ts` | +| `settings/components/window-manager-layout-profiles.tsx` | 152 | **delete** → profile grid + card + editor | +| `settings/components/window-manager-behavior-fields.tsx` | 109 | **delete** → behavior picks | +| `settings/components/window-manager-geometry-fields.tsx` | 105 | **delete** → gap editor + snap map + ratio track | +| `settings/components/window-manager-binding-fields.tsx` | 94 | **delete** → snap map (zones) + shortcut table + advanced | +| `settings/components/window-manager-config-editor.tsx` | 53 | rewrite (drop the bespoke sticky bar) | +| `settings/components/window-manager-number-field.tsx` | 40 | **delete** | +| `settings/components/window-manager-select-field.tsx` | 40 | **delete** | +| `settings/components/window-manager-toggle-field.tsx` | 25 | **delete** | +| `settings/components/window-manager-config-field-types.ts` | 13 | **delete** if unreferenced after the above | +| `settings/components/window-manager-config-fields.ts` | 3 | **delete** if unreferenced after the above | +| `settings/hooks/use-window-manager-config-editor.ts` | 118 | keep, extend (§6) | +| `settings/hooks/use-window-manager-layout-editor.ts` | 121 | keep, extend (§6) | +| `settings/hooks/use-window-manager-layout-profiles.ts` | 136 | keep, fix (§3 D-4) | +| `settings/lib/window-manager-layout-{types,schema,tree,projection,query}.ts` | 131/404/19/88/72 | keep unchanged | +| `settings/adapters/window-manager-layouts-api.ts` | 262 | keep unchanged | +| `settings/mocks/window-manager-fixtures.ts` | 91 | **rewrite** — currently contains invalid enum values (§3 D-3) | + +Everything else in `systems/settings/` is untouched. + +--- + +## 3. Fix these before building the UI + +Four defects, each independently reproducible today. **D-1 and D-2 must land first** — the redesign's structure assumes they are fixed. + +### D-1 · The split buttons are inverted +`window-manager-layout-node-editor.tsx:79` maps `Split rows → axis "horizontal"`, `:87` maps `Split columns → axis "vertical"`. `layout-projection.ts:190` divides the **width** on `horizontal`, so `horizontal` produces columns. "Split rows" currently produces columns. +**Fix:** the axis vocabulary leaves the UI entirely. The inspector exposes two diagram buttons — **Rows** → `axis: "vertical"`, **Columns** → `axis: "horizontal"`. Add a regression test asserting the mapping against `projectLayout` output, not against the label. + +### D-2 · Every split created in Settings fails validation +`window-manager-layout-node-editor.tsx:41` emits `weights: windowIds.map(() => 1)`. `validate.go:249` requires `|Σweights − 1| ≤ 1e-6`, and `validateLayoutDocument` (`internal/windowmanager/service_layout.go:40-74`) runs `ValidateSnapshot` on the document **as sent**, with no normalization pass. A two-way split therefore sends `[1,1]` and "Validate and preview" returns `topology.split_weight_sum`. +**Fix:** `toSplit` emits `1/n`. Structural conversions move into `settings/lib/window-manager-layout-mutations.ts` (§5) so the invariant has one owner and one test. + +### D-3 · The Storybook fixture asserts enum values that do not exist +`settings/mocks/window-manager-fixtures.ts` declares `aspect_variant: "square" | "wide"` and `overflow_policy: "floating" | "ignore"`, and sets document `version: 1`. The real contract is `any|landscape|portrait`, `stack|reject`, and `SnapshotVersion = 2` (`internal/windowmanager/types.go:9`, enforced at `resource_codec.go:174-180`). +**Fix:** rebuild the fixture from the zod schemas. It should be dense enough to exercise the canvas: ≥ 2 desktops, ≥ 2 groups, a nested split, a stack, a floating window and a minimized window. The current fixture (1 desktop / 1 group / 1 leaf) is why the density problem was never visible in review captures. + +### D-4 · Loading a profile silently discards unapplied edits +`use-window-manager-layout-profiles.ts:92-103` — `selectProfile` calls `onLoad(structuredClone(record.spec.document))`, replacing the whole draft with no confirmation. `remove` (`:75-79`) also deletes with no confirmation. +**Fix:** `Load` is confirmed when `editor.dirty` is true; `Delete` uses `ConfirmDialog` from `@agh/ui`. Also fix the reset asymmetry at `:80-89` — after a delete it clears `id`/`displayName` but leaves `aspect`/`overflow`/`scope` on the deleted record's values. + +--- + +## 4. Delete targets + +Removed in the same change, with no deprecation window: + +``` +web/src/systems/settings/components/window-manager-layout-document-editor.tsx +web/src/systems/settings/components/window-manager-layout-node-editor.tsx +web/src/systems/settings/components/window-manager-layout-profiles.tsx +web/src/systems/settings/components/window-manager-behavior-fields.tsx +web/src/systems/settings/components/window-manager-geometry-fields.tsx +web/src/systems/settings/components/window-manager-binding-fields.tsx +web/src/systems/settings/components/window-manager-number-field.tsx +web/src/systems/settings/components/window-manager-select-field.tsx +web/src/systems/settings/components/window-manager-toggle-field.tsx +web/src/systems/settings/components/window-manager-config-field-types.ts ← if unreferenced +web/src/systems/settings/components/window-manager-config-fields.ts ← if unreferenced +web/src/systems/settings/components/__tests__/window-manager-layout-document-editor.test.tsx +``` + +Plus their entries in `settings/components/index.ts`. The three thin wrappers (`window-manager-{number,select,toggle}-field`) duplicated `SettingsNumberInput` / `SettingsChoiceGroup` / a bare `Switch` and must not be reintroduced. + +`window-manager-layout-document-editor.test.tsx` is deleted rather than migrated because it asserts the DOM of a component that ceases to exist. Its behavioural coverage moves per §9. + +--- + +## 5. New files + +Directory: `web/src/systems/settings/components/layouts/`. Hard cap 500 lines per file; the budgets below are targets, and any file that grows past its budget splits rather than absorbs. + +### Canvas +| File | Responsibility | ~LOC | +|---|---|---:| +| `layout-canvas.tsx` | consumes `projectLayout()`, positions groups/tiles/seams/floats, owns selection | 190 | +| `layout-canvas-tile.tsx` | one projected window or stack, presentational only | 110 | +| `layout-canvas-seam.tsx` | seam handle + detent tooltip; delegates math to `seam-preview.ts` | 120 | +| `layout-canvas-group-edge.tsx` | four group edge handles, overlap flag | 130 | +| `layout-canvas-floating.tsx` | floating/minimized window, drag via `clampFloatingRect` | 110 | +| `layout-desktop-tabs.tsx` | desktop tab strip, click-to-rename | 90 | + +### Inspector + review +| File | Responsibility | ~LOC | +|---|---|---:| +| `layout-inspector.tsx` | routes on selection kind, renders the empty/desktop summary | 130 | +| `layout-inspector-node.tsx` | Rows/Columns/Stack actions, weight readout, Distribute evenly | 150 | +| `layout-inspector-window.tsx` | leaf window picker + stack active picker, "in use" gating | 120 | +| `layout-review-bar.tsx` | dirty → Review → Apply gate, preview counts, diagnostics list | 140 | + +### Profiles +| File | Responsibility | ~LOC | +|---|---|---:| +| `layout-profile-grid.tsx` | card grid + load confirm + delete confirm | 130 | +| `layout-profile-card.tsx` | card, chips, computed thumbnail | 110 | +| `layout-profile-editor.tsx` | 5 fields (name, id, scope, aspect, overflow) + derived slot count | 150 | + +### Global config +| File | Responsibility | ~LOC | +|---|---|---:| +| `window-manager-behavior-picks.tsx` | the 5 diagram pick rows + 2 modifier keycap rows + 3 switch rows | 150 | +| `window-manager-behavior-diagrams.tsx` | the SVG set as data; no logic | 150 | +| `window-manager-gap-editor.tsx` | 1:1 box model, 6 handles, keyboard steppers | 170 | +| `window-manager-snap-map.tsx` | edge bands, corner reach, exit slack, 2 centre-zone bindings | 200 | +| `window-manager-ratio-track.tsx` | repeat-width stops: add / drag / remove / uniqueness | 160 | +| `window-manager-shortcut-table.tsx` | grouped rows, disclosure, conflict banner | 140 | +| `window-manager-shortcut-row.tsx` | label + tiling diagram + chord chip + reset | 100 | + +### Hooks — `web/src/systems/settings/hooks/` +| File | Responsibility | ~LOC | +|---|---|---:| +| `use-layout-canvas-selection.ts` | selection state + `findNode`/`replaceNode` over the draft | 110 | +| `use-layout-draft-seam.ts` | pointer drag → `applySeamPreviewToDesktop` on the draft (**not** a `layout.resize` dispatch) | 120 | +| `use-layout-group-frame-drag.ts` | edge drag → normalized frame, detents, overlap detection | 140 | +| `use-window-manager-shortcuts.ts` | effective chord resolution, recording, conflict map | 150 | + +### Lib — `web/src/systems/settings/lib/` +| File | Responsibility | ~LOC | +|---|---|---:| +| `window-manager-layout-mutations.ts` | `toSplit` / `toStack` / `evenWeights` — **the single owner of the weight-sum invariant** | 90 | +| `window-manager-shortcut-chords.ts` | parse / format / canonicalize / symbolize / detect conflicts | 130 | +| `window-manager-layout-thumbnail.ts` | profile-card rect math (no gaps, no minimums — a diagram, not a projection) | 80 | +| `window-manager-snap-geometry.ts` | px ↔ map-scale conversion for the snap map and gap editor | 70 | + +### `packages/ui` +`Slider` does not exist. `packages/ui/src/components/` has `popover.tsx`, `switch.tsx`, `tabs.tsx`, `tooltip.tsx`, `scroll-area.tsx` — no slider. The `history_limit` control needs one, and a slider is a generic primitive, so per the reuse rule it lands in `packages/ui` with a story and a test, not in `web/`: + +``` +packages/ui/src/components/slider.tsx +packages/ui/src/components/__tests__/slider.test.tsx +web/.storybook/... or packages/ui story colocated per the existing convention +``` + +Everything else composes existing primitives: `Button`, `Input`, `Switch`, `Popover`, `Tooltip`, `ConfirmDialog`, `Field*`, `Eyebrow`, `Item*`, `Spinner`. + +--- + +## 6. Hook changes + +`use-window-manager-layout-editor.ts` — add: +- `setDesktopName(desktopIndex, name)` +- `setNode(nodeId, next)` — replaces a node anywhere in the active desktop +- `setFloatingRect(windowId, rect)` — the document contract already validates `floating_rect`; the current editor simply never wrote it +- `applySeam(seam, deltaPx)` — thin wrapper over `applySeamPreviewToDesktop` + +Keep `reviewCurrent` exactly as it is. The fingerprint gate is correct and the redesign depends on it. + +`use-window-manager-config-editor.ts` — replace the current all-or-nothing `canSave` with per-field validity so the UI can surface *which* value is out of range. Today the only feedback is `aria-invalid` plus a disabled button, and the explanatory string (`"Fix repeat ratios and shortcut JSON before saving."`) is thrown from a code path that can only run after a click that cannot happen. + +`use-window-manager-layout-profiles.ts` — add the confirm gates from D-4; fix the post-delete reset. + +--- + +## 7. Page composition + +`-layouts-settings-page.tsx` becomes composition only (~120 LOC), rendering: + +``` +SettingsPageFrame (needs a width beyond `wide`; see below) +├── LayoutStage ← desktop tabs + LayoutCanvas + LayoutInspector + LayoutReviewBar +├── LayoutProfileGrid + LayoutProfileEditor +├── SettingsGroup "Window behavior" → WindowManagerBehaviorPicks +├── SettingsGroup "Spacing and snapping" → WindowManagerGapEditor | WindowManagerSnapMap | WindowManagerRatioTrack +├── SettingsGroup "Shortcuts" → WindowManagerShortcutTable +├── SettingsAdvancedFold → history Slider + SettingsTiles (provenance) +└── SettingsSaveBar ← the shared one, for the global config draft only +``` + +Two structural fixes here: + +- **One floating bar.** Today `window-manager-config-editor.tsx:34-50` and `window-manager-layout-document-editor.tsx:183-217` are both `sticky bottom-3` in the same scroll region, so two bespoke bars can float on top of each other. In the redesign the document's review bar is **docked inside the stage card** (not sticky) and only the global config uses the shared `SettingsSaveBar` — matching every other settings section's dirty/saved dot and `Discard` / `Save changes` wording. +- **Column width.** `settings-page-frame.tsx:17,46` exposes a boolean `wide` that picks between the `max-w-settings-page-form` and `max-w-settings-page-wide` Tailwind tokens. The canvas + 236px inspector needs ~1040px, so the boolean becomes a `width?: "form" | "wide" | "canvas"` union with a matching `max-w-settings-page-canvas` token — not a bespoke `className` on the call site. Migrate the existing `wide` call sites (Providers, and Layouts itself) in the same change. Below 1100px the inspector stacks under the canvas. + +--- + +## 8. Backend and contract + +**No daemon changes are required for the UI to work.** Every control maps to an existing field; the endpoint list is unchanged from `LAYOUTS-REDESIGN-SPEC.md` §3. + +Two gaps worth deciding on separately — neither blocks this work: + +1. **Layout profiles have no CLI surface.** `internal/cli/window_manager_layout.go` ships `export`, `validate`, `apply`, `watch`; `grep -rn "layout-profile" internal/cli/` returns nothing. The redesign promotes profiles to a first-class surface, so the core premise ("every capability must be manageable by agents") says the CLI should catch up: `agh window-manager layout-profile {list,get,put,delete}` over the existing `…/layout-profiles` routes. **File as its own task** — the web work does not depend on it. +2. **Per-workspace overrides have no UI.** `document.overrides` is a full `WorkspaceConfig` on the wire (`web/src/generated/agh-openapi.d.ts:6220-6252`) but `Record` in the settings types, and the section declares `scope: "global"`, `available_scopes: ["global"]`. Surfacing it needs a new schema and a scope switcher, not a new component. Out of scope here; the redesign states "Global only" in Advanced so the UI does not imply otherwise. + +Config lifecycle: `window_manager.*` is `DiffClassLive` (`internal/config/lifecycle/lifecycle.go:108`) — it hot-applies. The page shows `Applies live` in the head and must **not** render a restart notice. + +--- + +## 9. Test plan + +Placement first, per `consolidate-test-suites`. Every row names the invariant, the layer that owns it, and the suite it belongs in. + +| Invariant | Owning layer | Canonical suite | +|---|---|---| +| `toSplit`/`toStack` always emit weights summing to 1 (D-2) | pure lib | **new** `settings/lib/__tests__/window-manager-layout-mutations.test.ts` | +| Rows→`vertical` / Columns→`horizontal` produce the geometry the projector renders (D-1) | pure lib, asserted through `projectLayout` | same suite as above | +| Chord parse/format/canonicalize round-trips; conflicts detected | pure lib | **new** `settings/lib/__tests__/window-manager-shortcut-chords.test.ts` | +| Seam drag preserves the weight sum and respects `MIN_SPLIT_WEIGHT` | already owned by `seam-preview.ts` | **existing** `os/lib/__tests__/` — extend only if a settings-specific path is added; do **not** duplicate | +| Draft fingerprint invalidates the preview on any edit | hook | **existing** `settings/lib/__tests__/window-manager-layout-query.test.ts` | +| Apply stays disabled until validate + preview match the draft | component | **new** `settings/components/__tests__/layout-review-bar.test.tsx` (replaces the deleted document-editor test) | +| Loading a profile over a dirty draft confirms first (D-4) | component | **new** `settings/components/__tests__/layout-profile-grid.test.tsx` | +| Canvas renders one tile per projected window and marks overlapping groups | component | **new** `settings/components/__tests__/layout-canvas.test.tsx` | +| Config ranges (gaps 0–64, edge band 4–128, corner reach 16–512, exit slack 0–64, ratios 1–8 × 0.1–0.9 unique, history 1–500) | hook | **existing** `settings/components/__tests__/window-manager-config-editor.test.tsx`, retargeted at the hook | +| Slider primitive keyboard + aria contract | primitive | **new** `packages/ui/src/components/__tests__/slider.test.tsx` | + +Forbidden by default and **not** to be added: snapshot tests of the canvas SVG/DOM, CSS assertions, and tests that only re-assert the zod schemas. The schemas already own those. + +Storybook: rewrite `settings/routes/settings-layouts.stories.tsx` against the new fixture (§3 D-3) with at least `default`, `dirty-unreviewed`, `validation-failed` and `no-workspace` stories, so the visual-contract capture actually exercises density. + +--- + +## 10. Accessibility contract + +Non-negotiable — the page is otherwise pointer-only, which would be a regression from a page made of native inputs. + +- Every drag affordance (seam, group edge, gap guide, snap grip, ratio stop) is also `role="slider"` with `aria-valuemin` / `aria-valuemax` / `aria-valuenow` / `aria-label`, and responds to arrow keys (shift = ×10 on px values). +- The canvas is a `listbox`-style selection surface: tiles are focusable, arrow keys move selection, `Enter` opens the inspector's primary action. +- Centre-zone bindings open a real `Popover` menu with `role="menu"`, not a custom div. +- Shortcut recording announces state via `aria-live="polite"` and is cancellable with `Escape`. +- Conflicts and diagnostics are `role="status"` regions, not colour-only signals. + +--- + +## 11. AGH Impact Audit + +```markdown +AGH Impact Audit: + +- Native tools: no impact — checked skills/agh/ tool descriptors and the agh__* registry; + no window-manager tool IDs exist and none are added. The window-manager surface is reached + through the CLI (internal/cli/window_manager_*.go) and HTTP/UDS routes + (internal/api/httpapi/window_manager_routes.go), neither of which changes shape here. + +- Extensibility and hooks: no impact on extensions, hooks, skills/capabilities, bundles, + registries or bridge SDKs — checked internal/hooks event list and the extension surface; + window-manager emits no hook events and exposes no extension point. Config lifecycle is + unchanged: window_manager.* stays DiffClassLive (internal/config/lifecycle/lifecycle.go:108) + and no config.toml key is added, removed or re-ranged. + +- Workspace data isolation: no new data. The layout document is workspace-scoped and already + keyed by workspace_id through the client-state engine (internal/daemon/window_manager_repository.go:17-19); + layout profiles are scope-tagged global|workspace in resource_records with the CHECK at + internal/store/globaldb/schema/definitions/34_resources.sql:5 and the visibility filter at + internal/api/core/window_manager_layout_profiles.go:212-219. The redesign reads the same + queries with the same keys (settings/lib/query-keys.ts:24-36); no new cache, SSE channel or + event path is introduced, so no new cross-workspace leak surface exists. + +- Official AGH skill: no impact — checked skills/agh/ for window-manager references; the skill + documents no layout tool IDs, CLI paths or capabilities. If §8 item 1 (layout-profile CLI verbs) + is taken up as its own task, that task must update skills/agh/. +``` + +**Web/Docs Impact.** Web: the whole of §4–§7. Docs (`packages/site`): `content/runtime/core/configuration/config-toml.mdx:133-161` documents `[window_manager]` and stays accurate — no key changes. No docs change is required for this task; if the layout-profile CLI lands, its reference page is generated and will co-ship there. + +--- + +## 12. QA tracker impact + +User-visible behaviour changes, so this is a **flag, not a retest**: + +- Add `untested` content-addressed scenarios under `docs/qa/scenarios/` for: drag-to-rebalance a split; drag a group edge into an overlap and see it refused; record and reset a shortcut; edit gaps and see the canvas follow; load a saved layout over a dirty draft. +- Reset `qa_status` to `untested` on any existing scenario covering Settings › Layouts. +- D-1 and D-2 are behaviour fixes and each need their own scenario. + +E2E: the page is UI-bearing, so a Playwright lane belongs in `make test-e2e-web` covering the review → apply gate. Pointer-drag assertions are brittle; assert the *outcome* (weights, diagnostics, enabled state) through the store, not the pixel path. + +--- + +## 13. Phasing + +**P1 — correctness.** D-1, D-2, D-3, D-4 with their tests. Ships against the current UI. Independently mergeable and independently valuable. + +**P2 — the stage.** Shared window-manager module if the boundary check demands it (§1.4), canvas + inspector + review bar + desktop tabs, page recomposed, delete targets removed, one save bar. This is the bulk of the work. + +**P3 — the config surface.** Behavior picks, gap editor, snap map, ratio track, shortcut table, `Slider` primitive, advanced fold. + +**P4 — profiles.** Card grid with thumbnails, editor, confirm gates. + +Acceptance for the whole change: `make verify` green; zero `input[type=number]` bound to a geometry field under `systems/settings/`; no file over 500 lines; `agh-ui-screenshot` capture of the new Storybook stories cited in the completion notes. + +--- + +## 14. Open questions + +1. **Boundary rule** — may `systems/settings/` import from `systems/os/lib/`? If not, the shared-module move in §1.4 is mandatory and should be its own commit ahead of P2. Resolve before starting P2. +2. **Group repositioning** — the prototype only resizes groups via their edges, which cannot move a group without also resizing a neighbour. Is a drag-to-move affordance wanted, and if so what happens to the vacated space? The daemon has no "swap groups" command, so any answer here is client-side rect math. +3. **Adaptive-stack diagnostics** — `projectLayout` reports `adaptive-stack` and `minimum-unmet` at the current viewport. Should the settings canvas surface them (honest: "this layout will fold at this width") or suppress them, given the canvas is a fixed-aspect reference and not the user's real viewport? diff --git a/docs/design/opendesign/settings/LAYOUTS-REDESIGN-SPEC.md b/docs/design/opendesign/settings/LAYOUTS-REDESIGN-SPEC.md new file mode 100644 index 000000000..42a819abd --- /dev/null +++ b/docs/design/opendesign/settings/LAYOUTS-REDESIGN-SPEC.md @@ -0,0 +1,110 @@ +# Settings › Layouts — visual redesign + +Prototype: `settings-layouts.html` + `settings-layouts.js` +Replaces: `web/src/routes/_app/settings/-layouts-settings-page.tsx` and its three editor components. + +--- + +## 1. Why + +The current page flattens a spatial domain into scalars. In the *minimal* Storybook fixture (1 desktop, 1 group, 1 leaf) it renders **9 number inputs, 4 free-text inputs, 1 JSON textarea and 12 selects** — and it scales linearly with the layout: `+4 numbers per group`, `+1 number per split child`, `+1 select per node`. A modest 3-desktop workspace is ~59 typed boxes on one scroll. + +Every one of those boxes is a rectangle, a ratio or an inset that got turned into a number on its way to the user: + +| Today | Actually is | +|---|---| +| `x` `y` `w` `h`, four 0–1 decimals, `step=0.05` | a rectangle on a screen | +| `Weight`, a decimal in a detached 7rem column | the position of a divider | +| `Repeat ratios`, a comma-separated string | a set of stops along an axis | +| `Inner/Top/Right/Bottom/Left gap`, five px fields | a box model | +| `Edge band` / `Corner reach` / `Exit slack` | hit zones around the screen edges | +| `Top center` / `Bottom center`, two selects | two positions on the screen edge | +| `Shortcut map`, a raw JSON textarea | 24 named actions with chords | + +The redesign makes each of those the thing it is. **The page contains zero `input[type=number]` for geometry.** The only remaining slider is `history_limit`, which genuinely is a scalar. + +## 2. Information shape + +Per the settings-section rule, Layouts leads with what no other section has: **a canvas**. The page is: + +1. **Workspace layout** — a desktop canvas you manipulate directly, plus a selection inspector and the daemon's validate → preview → apply gate docked inside the stage card. +2. **Saved layouts** — profile cards whose thumbnail is their real geometry, computed from the stored document. +3. **Window behavior** — diagram choice-cards and modifier keycaps instead of 7 selects. +4. **Spacing and snapping** — a 1:1 gap box model, a snap-zone map with the controls sitting where the zones are, and a track of repeat-width stops. +5. **Shortcuts** — a grouped recorder table with tiling geometry icons and live conflict detection. +6. **Advanced** — history limit + provenance. + +## 3. Field map — every control to its contract + +### Layout document (`PUT …/window-manager/layout`, gated by validate + preview) + +| Control | Writes | Rule enforced by the control | +|---|---|---| +| Drag a group edge | `desktops[].groups[].frame.{x,y,w,h}` | clamped to `x,y ≥ 0`, `w,h ≥ 0.08`, `x+w ≤ 1`; magnetic detents at 0, ¼, ⅓, ½, ⅔, ¾, 1; live overlap flag (`topology.group_overlap`) | +| Drag a seam | `…root…weights[]` | the pair is rebalanced, so the vector **always sums to 1** — `topology.split_weight_sum` becomes unreachable | +| Rows / Columns / Stack | replaces the node via the same flatten-and-rebuild as `toSplit`/`toStack` | disabled below 2 windows; emits normalized weights | +| Distribute evenly | `weights[] = 1/n` | — | +| Window picker on a leaf | `leaf.windowId` | windows already claimed by another node are disabled (`topology.window_membership`) | +| Member list on a stack | `stack.activeId` | warns below 2 members (`topology.stack_size`) | +| Desktop tab, click-to-rename | `desktops[].name` | — | +| Drag a floating window | `windows[].floatingRect` | clamped inside 0–1 (`topology.floating_rect`) | +| Import / Export JSON | whole document | import lands in the draft and still passes the review gate | +| Review changes | `POST …/layout/validate` then `POST …/preview` | preview counts come from `changes.{desktopIds,groupIds,nodeIds,windowIds}` — the contract returns ids and counts, never geometry, so the panel shows counts only | +| Apply layout | `PUT …/layout` with `expected_revision` | stays disabled until the preview fingerprint matches the current draft, exactly as `reviewCurrent` does today | + +### Layout profiles (`window_layout` resource) + +| Control | Writes | +|---|---| +| Card → Load | replaces the draft document (now behind a confirm when the draft is dirty) | +| Name / Resource ID | `spec.display_name` / `spec.id` — the hint states that changing the id forks a new record, because `expectedVersion` resets to 0 | +| Scope segmented | `scope.kind` ∈ `global \| workspace` | +| Screen shape segmented | `spec.aspect_variant` ∈ `any \| landscape \| portrait` — labelled as stored-only, because nothing selects a profile by it | +| Overflow cards | `spec.overflow_policy` ∈ `stack \| reject` | +| Footer sentence | `spec.participant_slots`, derived from the document — shown, never edited | + +### Global config (`PATCH /api/settings/window-manager`, one save bar) + +| Control | Writes | Range | +|---|---|---| +| 5 diagram pick rows | `new_window_policy`, `small_viewport_policy`, `focus_policy`, `drag_away_policy`, `desktop_transition` | the literal unions | +| 2 keycap rows | `group_move_modifier`, `swap_modifier` | `alt \| control \| meta \| shift \| none` | +| 3 switches | `focus_wrap`, `focus_follows_pointer`, `raise_on_focus` | — | +| Gap box guides | `gaps.{inner,top,right,bottom,left}` | 0–64, integer | +| Snap map grips | `snap.{edge_band,corner_reach,exit_slack}` | 4–128 / 16–512 / 0–64 | +| Centre zone buttons | `bindings.{top_center,bottom_center}` | `none \| reserved \| zoom` | +| Repeat-width stops | `snap.repeat_ratios` | 1–8 stops, each 0.1–0.9, unique | +| History slider | `history_limit` | 1–500 | +| Shortcut chips | `shortcuts[actionId]` | chord = modifiers + one `KeyboardEvent.code`; only overrides are stored, so the table shows the shipped default with a reset affordance | + +## 4. Deliberately not built + +These do not exist in the contract and were not invented: + +- **Add / remove / reorder desktops, groups or windows.** The stage says so in the tab strip. Those are `desktop.create/delete/reorder` semantic commands on `POST …/commands`, not layout-document edits. +- **Per-display / multi-monitor config.** No display entity exists anywhere in the model. +- **Auto-tiling modes (bsp, master-stack, fibonacci).** `layout.arrange` is a command with presets `horizontal | vertical | grid | stack`; it is not a stored layout property. +- **Floating rules ("app X always floats").** `new_window_policy` is a single global switch; there is no per-app rule table. +- **Per-workspace overrides.** `document.overrides` and `.agh/config.toml` exist, but the settings section is `scope: "global"`, `available_scopes: ["global"]`. Surfacing it needs a new schema, not a new component. +- **Profile auto-activation by screen shape.** `aspect_variant` is stored and nothing consumes it — the UI says so instead of implying a match rule. +- **Undo / redo in the editor.** Only `Reset`. `layout.undo/redo` are daemon commands the settings editor does not call. +- **A visual preview from the daemon.** `preview` returns ids and counts. Every rectangle on this page is computed client-side from `frame` + `weights` + `axis`. + +## 5. Two production defects found while mapping the contract + +**D-1 · The split buttons are inverted.** +`window-manager-layout-node-editor.tsx:79` maps `Split rows → axis "horizontal"` and `:87` maps `Split columns → axis "vertical"`. The projector divides the **width** on `horizontal` (`web/src/systems/os/lib/layout-projection.ts:190`), so `horizontal` produces columns. Pressing "Split rows" today produces columns. The redesign drops the axis vocabulary entirely and labels the two diagram buttons **Rows** (`vertical`) and **Columns** (`horizontal`). + +**D-2 · Every split created in Settings fails validation.** +`toSplit` emits `weights: windowIds.map(() => 1)` (`window-manager-layout-node-editor.tsx:41`). `validate.go:249` requires `|Σweights − 1| ≤ 1e-6`, and `validateLayoutDocument` (`service_layout.go:40-74`) runs `ValidateSnapshot` on the document **as sent**, with no normalization. So a two-way split sends `[1,1]` and "Validate and preview" returns `topology.split_weight_sum`. The redesign emits `1/n` and rebalances pairwise on drag, which makes the invalid state unreachable rather than merely reported. + +Both are code fixes, independent of this redesign. + +## 6. Notes for implementation in `web/` + +- The document review gate, the profile CRUD and the config draft keep their existing hooks (`useWindowManagerLayoutEditor`, `useWindowManagerLayoutProfiles`, `useWindowManagerConfigEditor`). Only the presentation changes. +- The page currently floats **two** competing `sticky bottom-3` bars. Here the document's review bar is docked inside the stage card and only the global config uses the shared `SettingsSaveBar` — one floating bar on the page, matching every other settings section. +- `SettingsPageFrame` needs a width beyond `wide` (960px) for the canvas + inspector; the prototype uses 1040px and collapses the inspector under the canvas below 1100px. +- New primitives worth promoting to `packages/ui` if reused: none. The canvas, gap box, snap map and chord recorder are domain composites and belong in `web/src/systems/settings/`. +- `Delete` on a profile still has no confirmation in production; the prototype confirms only the destructive *load* (which silently discards unapplied edits today). Both deserve confirmation. +- Accessibility: every drag affordance is also a `role="slider"` with arrow-key support and an `aria-valuenow`, so the page is operable without a pointer. diff --git a/docs/design/opendesign/settings/settings-automation.html b/docs/design/opendesign/settings/settings-automation.html index 77e11c88c..d8160c572 100644 --- a/docs/design/opendesign/settings/settings-automation.html +++ b/docs/design/opendesign/settings/settings-automation.html @@ -208,6 +208,7 @@
    Runtime
    + ); +} diff --git a/web/src/systems/os/components/stories/_desktop.tsx b/web/src/systems/os/components/stories/_desktop.tsx index c12d90494..d3fd0b462 100644 --- a/web/src/systems/os/components/stories/_desktop.tsx +++ b/web/src/systems/os/components/stories/_desktop.tsx @@ -67,6 +67,14 @@ export interface DesktopShellProps { dock?: boolean; /** Override dock entries (defaults to full DESK_ITEMS). */ dockItems?: OsDockEntry[]; + /** Extra classes on the dock zone (first-run dormancy). */ + dockClassName?: string; + /** Extra classes on the menubar (first-run dimming). */ + menubarClassName?: string; + /** Menubar workspace slot; omit for the bound `agh` workspace. */ + workspace?: { name: string; monogram: string }; + /** Menubar approvals count; 0 renders no badge. */ + notifications?: number; /** Show the empty-desktop ⌘K hint (OpenDesign `desk-hint`). */ deskHint?: boolean; } @@ -82,18 +90,19 @@ export function DesktopShell({ menubar = true, dock = true, dockItems = DESK_ITEMS, + dockClassName, + menubarClassName, + workspace = { name: "agh", monogram: "AG" }, + notifications = 2, deskHint = false, }: DesktopShellProps) { return (
    {menubar ? ( @@ -114,7 +123,14 @@ export function DesktopShell({

    ) : null} {children} - {dock ? : null} + {dock ? ( + + ) : null}
    ); diff --git a/web/src/systems/os/components/stories/_shell-fixture.tsx b/web/src/systems/os/components/stories/_shell-fixture.tsx new file mode 100644 index 000000000..de7e9c491 --- /dev/null +++ b/web/src/systems/os/components/stories/_shell-fixture.tsx @@ -0,0 +1,185 @@ +import { QueryClient } from "@tanstack/react-query"; +import { fn } from "storybook/test"; + +import type { OsShellHandle } from "../../contexts/os-shell-context"; +import { RoutingCoordinator, type OsRouterPort } from "../../lib/routing-coordinator"; +import type { + OsDesktopRuntimeStore, + OsWindow, + WindowManagerCommandOutcome, + WindowManagerController, +} from "../../lib/os-types"; +import type { WindowManagerConfig, WindowManagerSnapshot } from "../../lib/window-manager-types"; +import { WindowManagerRuntime } from "../../runtime/window-manager-runtime"; + +const ROUTER: OsRouterPort = { navigate: () => {}, replace: () => {} }; + +/** + * Story shell over the real runtime. Nothing is bound, so window commands read + * as unavailable — which is exactly the resting state of a cold desktop. + */ +export function createStoryShell({ collapsedAgent }: { collapsedAgent?: string } = {}) { + const manager = new WindowManagerRuntime(new QueryClient()); + if (collapsedAgent) manager.getState().toggleRailGroup(collapsedAgent); + const coordinator = new RoutingCoordinator(manager, ROUTER); + coordinator.completeHydration(); + return { store: manager, manager, coordinator } satisfies OsShellHandle; +} + +const STORY_DESKTOP_ID = "desktop:story"; + +const CONFIG: WindowManagerConfig = { + newWindowPolicy: "floating", + smallViewportPolicy: "stack", + focusPolicy: "click_directional", + focusWrap: true, + focusFollowsPointer: false, + raiseOnFocus: true, + dragAwayPolicy: "window", + groupMoveModifier: "alt", + swapModifier: "shift", + historyLimit: 50, + desktopTransition: "slide", + gaps: { inner: 8, top: 0, right: 0, bottom: 0, left: 0 }, + snap: { edgeBand: 32, cornerReach: 150, exitSlack: 16, repeatRatios: [0.5, 0.666667, 0.333333] }, + bindings: { topCenter: "zoom", bottomCenter: "reserved" }, + shortcuts: {}, +}; + +const SNAPSHOT: WindowManagerSnapshot = { + version: 1, + workspaceId: "workspace-agh", + revision: 12, + desktops: [], + windows: {}, + history: { undo: [], redo: [] }, + overrides: {}, + updatedAt: "2026-07-23T01:00:00Z", +}; + +function storyWindow(id: string, layer: number): OsWindow { + return { + id, + app: "tasks", + instanceKey: null, + route: { pathname: "/tasks", search: {} }, + desktopId: STORY_DESKTOP_ID, + placement: "tiled", + rect: { x: 40 * layer, y: 40, w: 600, h: 420 }, + layer, + minimized: false, + groupId: null, + nodeId: null, + stackId: null, + stackActive: true, + parentAxis: null, + }; +} + +function outcome(): WindowManagerCommandOutcome { + return { accepted: true, completion: Promise.resolve(true) }; +} + +/** + * Story shell with a live client, two desktops, and a focused tiled window with + * a visible peer — the state in which every Window-menu predicate passes, so + * the enabled menu can be captured. + */ +export function createLiveStoryShell(): OsShellHandle { + const focused = storyWindow("app:tasks", 2); + const peer = storyWindow("app:agents", 1); + const state: OsDesktopRuntimeStore = { + snapshot: SNAPSHOT, + windowManagerConfig: CONFIG, + client: { + workspaceId: "workspace-agh", + clientId: "client:story", + activeDesktopId: STORY_DESKTOP_ID, + focusedWindowId: focused.id, + focusOrder: [focused.id], + connectedAt: "2026-07-23T01:00:00Z", + presentationRevision: 1, + }, + desktops: [ + { + id: STORY_DESKTOP_ID, + name: "Launch", + order: 0, + purpose: "standard", + focusOwner: focused.id, + groups: [], + floating: [], + }, + { + id: "desktop:second", + name: "Review", + order: 1, + purpose: "standard", + focusOwner: null, + groups: [], + floating: [], + }, + ], + projections: {}, + windows: { [focused.id]: focused, [peer.id]: peer }, + activeDesktopId: STORY_DESKTOP_ID, + focusedId: focused.id, + railCollapsedAgentIds: [], + wallpaper: "ember", + reduceMotion: false, + dockMagnify: true, + presentation: "floating", + viewportState: "ready", + hydration: "live", + connectionStatus: "connected", + desktopBounds: { width: 1440, height: 900, origin: { x: 0, y: 0 } }, + openOrFocus: target => ({ windowId: `app:${target.app}`, ...outcome() }), + closeWindow: async () => true, + focusWindow: () => outcome(), + minimizeWindow: async () => true, + restoreWindow: fn(), + zoomWindow: () => outcome(), + toggleFloating: fn(), + moveWindow: fn(), + arrangeLayout: fn(), + commitFloatingRect: () => outcome(), + resizeLayout: () => outcome(), + balanceLayout: fn(), + navigateWindow: () => outcome(), + toggleRailGroup: fn(), + setWallpaper: fn(), + setDockMagnify: fn(), + setReduceMotion: fn(), + setDesktopBounds: fn(), + }; + const controller: WindowManagerController = { + getState: () => state, + getInitialState: () => state, + subscribe: () => () => undefined, + bind: fn(), + unbind: fn(), + setClient: fn(), + setConnectionStatus: fn(), + setLoadError: fn(), + createDesktop: fn(), + renameDesktop: fn(), + reorderDesktop: fn(), + switchDesktop: fn(), + switchDesktopDirection: fn(), + deleteDesktop: fn(), + moveWindowToDesktop: fn(), + tileWindow: fn(), + applySnapTarget: () => outcome(), + focusDirection: fn(), + undoLayout: fn(), + redoLayout: fn(), + balanceFocusedLayout: fn(), + clearConflict: fn(), + refreshSnapshot: fn(), + }; + return { + store: controller, + manager: controller, + coordinator: new RoutingCoordinator(controller, ROUTER), + }; +} diff --git a/web/src/systems/os/components/stories/attention-surfaces.stories.tsx b/web/src/systems/os/components/stories/attention-surfaces.stories.tsx index 4e194ccf9..34a036722 100644 --- a/web/src/systems/os/components/stories/attention-surfaces.stories.tsx +++ b/web/src/systems/os/components/stories/attention-surfaces.stories.tsx @@ -1,18 +1,17 @@ import { useState } from "react"; import type { Meta, StoryObj } from "@storybook/react-vite"; -import { QueryClient } from "@tanstack/react-query"; import { fn, userEvent, within } from "storybook/test"; +import { AgentCreateHostProvider } from "@/systems/agent"; import type { SessionPayload } from "@/systems/session"; import type { WorkspacePayload } from "@/systems/workspace"; -import { OsShellContext, type OsShellHandle } from "../../contexts/os-shell-context"; +import { OsShellContext } from "../../contexts/os-shell-context"; import type { OsAttentionModel } from "../../hooks/use-os-attention"; -import { WindowManagerRuntime } from "../../runtime/window-manager-runtime"; -import { RoutingCoordinator, type OsRouterPort } from "../../lib/routing-coordinator"; import { DesktopMenubar } from "../desktop-menubar"; import { OsSessionsModal } from "../sessions-modal"; import { OsDockZone } from "../os-dock"; +import { createStoryShell } from "./_shell-fixture"; import { buildDeskItems, DesktopShell } from "./_desktop"; function session( @@ -79,15 +78,6 @@ const ATTENTION: OsAttentionModel = { loading: false, }; -function createStoryShell({ collapsedAgent }: { collapsedAgent?: string } = {}): OsShellHandle { - const manager = new WindowManagerRuntime(new QueryClient()); - const router: OsRouterPort = { navigate: () => {}, replace: () => {} }; - if (collapsedAgent) manager.getState().toggleRailGroup(collapsedAgent); - const coordinator = new RoutingCoordinator(manager, router); - coordinator.completeHydration(); - return { store: manager, manager, coordinator }; -} - function SessionsModalFixture({ collapsedAgent }: { collapsedAgent?: string }) { const [shell] = useState(() => createStoryShell({ collapsedAgent })); const dockItems = buildDeskItems({ @@ -108,24 +98,27 @@ function BellFixture() { const [shell] = useState(() => createStoryShell()); return ( - - - + + + + + ); } diff --git a/web/src/systems/os/components/stories/onboarding-setup-panel.stories.tsx b/web/src/systems/os/components/stories/onboarding-setup-panel.stories.tsx new file mode 100644 index 000000000..0cef58351 --- /dev/null +++ b/web/src/systems/os/components/stories/onboarding-setup-panel.stories.tsx @@ -0,0 +1,79 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import type { ReactNode } from "react"; + +import { OnboardingSetupFrame } from "@/systems/onboarding"; +import { onboardingWizardFixture } from "@/systems/onboarding/mocks"; + +import { buildDeskItems, DesktopShell } from "./_desktop"; + +/** + * First run as the OS shows it: the desktop the operator is about to unlock, + * dimmed and dormant, with the blocking setup panel over it. The story harness + * renders the same wallpaper/menubar/dock composition as the OpenDesign + * reference so the visual contract compares like for like. + */ +const meta: Meta = { + title: "systems/os/components/OnboardingSetupPanel", + parameters: { layout: "fullscreen" }, +}; + +export default meta; +type Story = StoryObj; + +const DORMANT_DOCK = "translate-y-1.5 opacity-50 saturate-50"; + +function FirstRunDesktop({ children }: { children: ReactNode }) { + return ( + <> +
    + +
    + {children} + + ); +} + +export const StepRuntime: Story = { + render: () => ( + + + + ), +}; + +export const StepWorkspace: Story = { + render: () => ( + + + + ), +}; + +export const StepWorkspaceEmpty: Story = { + render: () => ( + + false }, + })} + /> + + ), +}; + +export const Committing: Story = { + render: () => ( + + + + ), +}; diff --git a/web/src/systems/os/components/stories/os-menubar.stories.tsx b/web/src/systems/os/components/stories/os-menubar.stories.tsx index a08bf4ab8..6a0364c05 100644 --- a/web/src/systems/os/components/stories/os-menubar.stories.tsx +++ b/web/src/systems/os/components/stories/os-menubar.stories.tsx @@ -1,8 +1,17 @@ +import { useState } from "react"; import type { Meta, StoryObj } from "@storybook/react-vite"; import { fn } from "storybook/test"; +import { AgentCreateHostProvider } from "@/systems/agent"; +import type { WorkspacePayload } from "@/systems/workspace"; + +import { OsShellContext } from "../../contexts/os-shell-context"; +import type { OsAttentionModel } from "../../hooks/use-os-attention"; +import type { DesktopOverlay } from "../../hooks/use-desktop-overlays"; +import { DesktopMenubar } from "../desktop-menubar"; import { OsMenuBar } from "../os-menubar"; import { OsHydrationStatus } from "../os-hydration-status"; +import { createLiveStoryShell, createStoryShell } from "./_shell-fixture"; import { DesktopShell } from "./_desktop"; const meta: Meta = { @@ -13,7 +22,7 @@ const meta: Meta = { docs: { description: { component: - "The desktop menubar: AGH mark, workspace trigger, app menus, the approvals bell, the ⌘K palette chip, and Settings. Glass shell chrome. Controls are buttons only when a callback is supplied.", + 'The desktop menubar: the AGH system menu, the workspace switcher, the static Session / Go / Window / Help set, the approvals bell, the ⌘K chip, and Settings. The mark, the workspace chip, and every app menu sit in one `role="menubar"`, so arrow keys traverse the whole bar and hovering a sibling switches the open menu.', }, }, }, @@ -22,32 +31,116 @@ const meta: Meta = { export default meta; type Story = StoryObj; -/** - * Populated — workspace trigger, full menus, bell with a count, ⌘K chip, and - * Settings, all wired with callbacks, over the carbon desktop. - */ -export const Populated: Story = { - args: { - workspace: { name: "agh", monogram: "AG" }, - menus: ["Session", "View", "Help"], - notifications: 2, - onLogoClick: fn(), - onWorkspaceClick: fn(), - onMenuClick: fn(), - onNotificationsClick: fn(), - onCommandClick: fn(), - onSettingsClick: fn(), +const WORKSPACES: WorkspacePayload[] = [ + { + id: "workspace-agh", + name: "agh", + root_dir: "/workspace/agh", + add_dirs: [], + created_at: "2026-07-20T12:00:00Z", + updated_at: "2026-07-20T12:00:00Z", }, - render: args => ( - - - - ), + { + id: "workspace-site", + name: "site", + root_dir: "/workspace/site", + add_dirs: [], + created_at: "2026-07-20T12:00:00Z", + updated_at: "2026-07-20T12:00:00Z", + }, +]; + +const ATTENTION: OsAttentionModel = { + badges: { sessions: 1, tasks: 1 }, + notificationCount: 2, + rows: [], + sessions: [], + sessionsDisconnected: false, + tasksDisconnected: false, + loading: false, +}; + +function MenubarFixture({ + overlay = null, + live = true, +}: { + overlay?: DesktopOverlay | null; + live?: boolean; +}) { + const [shell] = useState(() => (live ? createLiveStoryShell() : createStoryShell())); + const [active, setActive] = useState(overlay); + return ( + + + + + setActive(current => (open ? id : current === id ? null : current)) + } + attention={ATTENTION} + /> + + + + ); +} + +/** The wired bar at rest, over a live desktop. */ +export const Populated: Story = { + args: { workspace: { name: "agh", monogram: "AG" } }, + render: () => , +}; + +/** The system menu on the mark: identity plus the settings surfaces. */ +export const AghMenuOpen: Story = { + args: { workspace: { name: "agh", monogram: "AG" } }, + render: () => , +}; + +/** Navigation grouped exactly like the dock strip. */ +export const GoMenuOpen: Story = { + args: { workspace: { name: "agh", monogram: "AG" } }, + render: () => , +}; + +/** Window commands with a focused tiled window and a visible peer: all enabled. */ +export const WindowMenuOpen: Story = { + args: { workspace: { name: "agh", monogram: "AG" } }, + render: () => , }; /** - * Presentation-only — no callbacks, controls render as inert chrome. + * The same menu on a cold desktop: no live client, so every command is disabled + * rather than hidden — the shape of the menu never changes under you. */ +export const WindowMenuUnavailable: Story = { + args: { workspace: { name: "agh", monogram: "AG" } }, + render: () => , +}; + +/** Real help: the shortcut reference, the docs, and a support path. */ +export const HelpMenuOpen: Story = { + args: { workspace: { name: "agh", monogram: "AG" } }, + render: () => , +}; + +/** Workspace switcher with the bound set and the overview/creation paths. */ +export const WorkspaceMenuOpen: Story = { + args: { workspace: { name: "agh", monogram: "AG" } }, + render: () => , +}; + +/** Presentation-only — no menu owners, so the bar renders as inert chrome. */ export const PresentationOnly: Story = { args: { workspace: { name: "agh", monogram: "AG" }, notifications: 0 }, render: args => ( @@ -65,10 +158,7 @@ export const DegradedSync: Story = { args: { workspace: { name: "agh", monogram: "AG" }, status: , - onLogoClick: fn(), - onWorkspaceClick: fn(), - onMenuClick: fn(), - onNotificationsClick: fn(), + notifications: 2, onCommandClick: fn(), onSettingsClick: fn(), }, diff --git a/web/src/systems/os/components/stories/os-shell-dialogs.stories.tsx b/web/src/systems/os/components/stories/os-shell-dialogs.stories.tsx new file mode 100644 index 000000000..f979dbc77 --- /dev/null +++ b/web/src/systems/os/components/stories/os-shell-dialogs.stories.tsx @@ -0,0 +1,53 @@ +import { useState } from "react"; +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { fn } from "storybook/test"; + +import { OsShellContext } from "../../contexts/os-shell-context"; +import { OsAboutDialog } from "../os-about-dialog"; +import { OsShortcutsDialog } from "../os-shortcuts-dialog"; +import { createLiveStoryShell } from "./_shell-fixture"; +import { DesktopShell } from "./_desktop"; + +const meta: Meta = { + title: "systems/os/components/OsShellDialogs", + component: OsShortcutsDialog, + parameters: { + layout: "fullscreen", + docs: { + description: { + component: + "The two shell-scoped dialogs the Help and AGH menus open: the keyboard reference (every registry action, bound or not) and the installation identity read straight from `/api/status`.", + }, + }, + }, +}; + +export default meta; +type Story = StoryObj; + +function DialogFixture({ dialog }: { dialog: "shortcuts" | "about" }) { + const [shell] = useState(createLiveStoryShell); + return ( + + + {dialog === "shortcuts" ? ( + + ) : ( + + )} + + + ); +} + +/** Shell, Window, Layout, and Desktops sections over the live registry. */ +export const Shortcuts: Story = { + args: { open: true, onOpenChange: fn() }, + render: () => , +}; + +/** Installation identity: only fields the daemon actually publishes. */ +export const About: Story = { + args: { open: true, onOpenChange: fn() }, + render: () => , +}; diff --git a/web/src/systems/os/hooks/__tests__/os-interaction-hooks.test.tsx b/web/src/systems/os/hooks/__tests__/os-interaction-hooks.test.tsx index 2d8c070d8..e08b3de13 100644 --- a/web/src/systems/os/hooks/__tests__/os-interaction-hooks.test.tsx +++ b/web/src/systems/os/hooks/__tests__/os-interaction-hooks.test.tsx @@ -20,6 +20,7 @@ import { useOsZoomMenu, } from "../use-os-zoom-menu"; import { useOsWindow } from "../use-os-window"; +import { useOsWindowCommands } from "../use-os-window-commands"; import { useOsWinLayer } from "../use-os-win-layer"; import { useOsShortcuts, type OsShortcutHandlers } from "../use-os-shortcuts"; import { windowManagerStore } from "../../stores/window-manager-store"; @@ -438,6 +439,28 @@ describe("useOsShortcuts", () => { expect(liveShell.controller.undoLayout).toHaveBeenCalledOnce(); input.remove(); }); + + it("Should dispatch nothing while disabled, so first-run setup blocks the whole set", () => { + const { wrapper, controller } = createShell(); + const handlers: OsShortcutHandlers = { + onPalette: vi.fn(), + onNewSession: vi.fn(), + onDesktops: vi.fn(), + onEscape: vi.fn(), + }; + renderHook(() => useOsShortcuts(handlers, { enabled: false }), { wrapper }); + + fireEvent.keyDown(document, { key: "k", code: "KeyK", metaKey: true }); + fireEvent.keyDown(document, { key: "n", code: "KeyN", metaKey: true }); + fireEvent.keyDown(document, { key: "z", code: "KeyZ", metaKey: true }); + fireEvent.keyDown(document, { key: "Escape", code: "Escape" }); + + expect(handlers.onPalette).not.toHaveBeenCalled(); + expect(handlers.onNewSession).not.toHaveBeenCalled(); + expect(handlers.onDesktops).not.toHaveBeenCalled(); + expect(handlers.onEscape).not.toHaveBeenCalled(); + expect(controller.undoLayout).not.toHaveBeenCalled(); + }); }); describe("useOsZoomMenu", () => { @@ -536,3 +559,94 @@ describe("useOsWinLayer", () => { }); }); }); + +describe("useOsWindowCommands", () => { + it("Should route focused-window lifecycle through the coordinator when the client is live", async () => { + const shell = createShell(); + const { result } = renderHook(() => useOsWindowCommands(), { wrapper: shell.wrapper }); + + expect(result.current.commandsAvailable).toBe(true); + const actions = result.current.focusedWindowActions; + if (actions === null) throw new Error("a focused live window must expose lifecycle actions"); + await act(async () => actions.close()); + expect(shell.state.closeWindow).toHaveBeenCalledWith("window:primary"); + await act(async () => actions.minimize()); + expect(shell.state.minimizeWindow).toHaveBeenCalledWith("window:primary"); + expect(actions.zoom).not.toBeNull(); + // The fixture window is already floating, so there is nothing to convert. + expect(actions.makeFloating).toBeNull(); + }); + + it("Should withhold every window command while the client is not live", () => { + const shell = createShell({ live: false }); + const { result } = renderHook(() => useOsWindowCommands(), { wrapper: shell.wrapper }); + + expect(result.current.commandsAvailable).toBe(false); + expect(result.current.focusedWindowActions).toBeNull(); + expect(result.current.placementCommands).toHaveLength(0); + expect(result.current.arrangeCommands).toHaveLength(0); + expect(result.current.canToggleFloating).toBe(false); + expect(result.current.canBalanceLayout).toBe(false); + expect(result.current.canEditLayoutHistory).toBe(false); + expect(result.current.canFocusDirection).toBe(false); + expect(result.current.canSwitchDesktop).toBe(false); + }); + + it("Should offer arrange presets only while a visible peer exists", () => { + const withPeer = renderHook(() => useOsWindowCommands(), { wrapper: createShell().wrapper }); + expect(withPeer.result.current.arrangeCommands.length).toBeGreaterThan(0); + + const alone = renderHook(() => useOsWindowCommands(), { + wrapper: createShell({ withPeer: false }).wrapper, + }); + expect(alone.result.current.arrangeCommands).toHaveLength(0); + expect(alone.result.current.placementCommands.length).toBeGreaterThan(0); + }); + + it("Should enable desktop switching only past a second desktop", () => { + const shell = createShell(); + const { result } = renderHook(() => useOsWindowCommands(), { wrapper: shell.wrapper }); + expect(result.current.canSwitchDesktop).toBe(false); + + act(() => + shell.setRuntimeState({ + desktops: [ + { + id: "desktop:main", + name: "Main", + order: 0, + purpose: "standard", + focusOwner: null, + groups: [], + floating: [], + }, + { + id: "desktop:second", + name: "Second", + order: 1, + purpose: "standard", + focusOwner: null, + groups: [], + floating: [], + }, + ], + }) + ); + expect(result.current.canSwitchDesktop).toBe(true); + act(() => result.current.switchDesktop("next")); + expect(shell.controller.switchDesktopDirection).toHaveBeenCalledWith("next"); + }); + + it("Should resolve shortcut glyphs from the live window-manager config", () => { + const shell = createShell(); + const { result } = renderHook(() => useOsWindowCommands(), { wrapper: shell.wrapper }); + expect(result.current.shortcutLabels["window.close"]).toBe("⌘W"); + + act(() => + shell.setRuntimeState({ + windowManagerConfig: { ...CONFIG, shortcuts: { "window.close": "control+shift+KeyW" } }, + }) + ); + expect(result.current.shortcutLabels["window.close"]).toBe("⌃⇧W"); + }); +}); diff --git a/web/src/systems/os/hooks/use-desktop-overlays.ts b/web/src/systems/os/hooks/use-desktop-overlays.ts index 5212be9c1..0c7e433b5 100644 --- a/web/src/systems/os/hooks/use-desktop-overlays.ts +++ b/web/src/systems/os/hooks/use-desktop-overlays.ts @@ -2,16 +2,26 @@ import { useState } from "react"; import { useWindowManagerActions, useWindowManagerOverlay } from "./use-window-manager-store"; +/** + * One id per shell overlay, including one per menubar menu. Sharing a single + * slot is what keeps them mutually exclusive: opening the palette closes a + * menu, and hover-switching between menubar menus resolves through the + * race-safe functional update below regardless of which side fires first. + */ export type DesktopOverlay = + | "agh-menu" | "workspace-menu" | "session-menu" - | "view-menu" + | "go-menu" + | "window-menu" | "help-menu" | "bell" | "palette" | "workspaces" | "desktops" - | "sessions"; + | "sessions" + | "shortcuts" + | "about"; type LocalDesktopOverlay = Exclude; diff --git a/web/src/systems/os/hooks/use-desktop-shell-body.ts b/web/src/systems/os/hooks/use-desktop-shell-body.ts index dc86235bb..94929df91 100644 --- a/web/src/systems/os/hooks/use-desktop-shell-body.ts +++ b/web/src/systems/os/hooks/use-desktop-shell-body.ts @@ -19,8 +19,17 @@ import { useOsShortcuts } from "./use-os-shortcuts"; import { useOsWinLayer } from "./use-os-win-layer"; import { useWorkspaceDetails } from "./use-workspace-details"; +export interface DesktopShellBodyOptions { + /** First-run setup owns the shell; the chrome is inert and shortcuts are off. */ + firstRun?: boolean; +} + /** Composes the live runtime models consumed by the presentational desktop shell body. */ -export function useDesktopShellBody(model: DesktopShellModel) { +export function useDesktopShellBody( + model: DesktopShellModel, + options: DesktopShellBodyOptions = {} +) { + const firstRun = options.firstRun ?? false; const desktopRef = useRef(null); const desktop = useDesktopShellState(); const overlays = useDesktopOverlays(); @@ -49,16 +58,19 @@ export function useDesktopShellBody(model: DesktopShellModel) { { enabled: overlays.activeOverlay === "workspaces" } ); - useOsShortcuts({ - onPalette: () => overlays.toggleOverlay("palette"), - onNewSession: () => model.sessionCreate.openForAgent(""), - onDesktops: () => overlays.toggleOverlay("desktops"), - onEscape: () => { - if (overlays.activeOverlay !== null) return; - if (document.querySelector('[data-slot="dialog-content"]')) return; - desktopRef.current?.focus(); + useOsShortcuts( + { + onPalette: () => overlays.toggleOverlay("palette"), + onNewSession: () => model.sessionCreate.openForAgent(""), + onDesktops: () => overlays.toggleOverlay("desktops"), + onEscape: () => { + if (overlays.activeOverlay !== null) return; + if (document.querySelector('[data-slot="dialog-content"]')) return; + desktopRef.current?.focus(); + }, }, - }); + { enabled: !firstRun } + ); const onResize = (splitId: string, boundaryIndex: number, delta: number) => { // Clear the live seam preview only after the resize reconciles, so panes go diff --git a/web/src/systems/os/hooks/use-menubar-actions.ts b/web/src/systems/os/hooks/use-menubar-actions.ts new file mode 100644 index 000000000..cc9fb8ca9 --- /dev/null +++ b/web/src/systems/os/hooks/use-menubar-actions.ts @@ -0,0 +1,79 @@ +import { useSyncExternalStore } from "react"; + +import { useAgentCreateHost } from "@/systems/agent"; + +import { OS_COMPACT_BREAKPOINT, type OsAppId } from "../lib/os-types"; +import { useOsShell } from "./use-os-shell"; +import { useOsWindowCommands, type OsWindowCommandsModel } from "./use-os-window-commands"; + +/** Below the compact breakpoint the app menus collapse (US-019.EC-3). */ +const COMPACT_QUERY = `(max-width: ${OS_COMPACT_BREAKPOINT - 0.02}px)`; + +function subscribeCompact(callback: () => void): () => void { + if (typeof window === "undefined" || typeof window.matchMedia !== "function") { + return () => undefined; + } + const mql = window.matchMedia(COMPACT_QUERY); + if (typeof mql.addEventListener === "function") { + mql.addEventListener("change", callback); + return () => mql.removeEventListener("change", callback); + } + mql.addListener(callback); + return () => mql.removeListener(callback); +} + +function getCompact(): boolean { + if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false; + return window.matchMedia(COMPACT_QUERY).matches; +} + +export interface MenubarActionsModel { + /** + * Whether the app menus render at all. Below the breakpoint they are removed + * rather than hidden, so the menubar composite never holds an unfocusable + * item; the palette still carries every action. + */ + menusVisible: boolean; + /** The window-manager fence the ⌘K palette uses for the same decisions. */ + canOpenApps: boolean; + windowCommands: OsWindowCommandsModel; + openApp(app: OsAppId): void; + openSettings(): void; + openAppearance(): void; + openLayouts(): void; + openSupport(): void; + newAgent(): void; +} + +/** + * Menubar view-model: the coordinator-backed navigation actions, the shared + * window-command model, and the compact-collapse decision. Menu components stay + * declarative lists and receive every predicate and callback as props. + */ +export function useMenubarActions(): MenubarActionsModel { + const { coordinator } = useOsShell(); + const agentCreate = useAgentCreateHost(); + const windowCommands = useOsWindowCommands(); + const compact = useSyncExternalStore(subscribeCompact, getCompact, () => false); + const canOpenApps = windowCommands.commandsAvailable; + + const openApp = (app: OsAppId) => { + if (canOpenApps) void coordinator.userOpen({ app }); + }; + const openSettingsRoute = (pathname: string) => { + if (canOpenApps) + void coordinator.userOpen({ app: "settings", route: { pathname, search: {} } }); + }; + + return { + menusVisible: !compact, + canOpenApps, + windowCommands, + openApp, + openSettings: () => openApp("settings"), + openAppearance: () => openSettingsRoute("/settings/appearance"), + openLayouts: () => openSettingsRoute("/settings/layouts"), + openSupport: () => openSettingsRoute("/settings/observability"), + newAgent: () => agentCreate.openDialog(), + }; +} diff --git a/web/src/systems/os/hooks/use-os-command-palette.ts b/web/src/systems/os/hooks/use-os-command-palette.ts index 3eb5d9b41..0034f9eb2 100644 --- a/web/src/systems/os/hooks/use-os-command-palette.ts +++ b/web/src/systems/os/hooks/use-os-command-palette.ts @@ -1,19 +1,14 @@ import { useSessionCreate, useSessions } from "@/systems/session"; import { useActiveWorkspace, type WorkspacePayload } from "@/systems/workspace"; -import { - WINDOW_ARRANGE_COMMANDS, - WINDOW_PLACEMENT_COMMANDS, - type WindowArrangeCommand, - type WindowManagerActionId, - type WindowPlacementCommand, +import type { + WindowArrangeCommand, + WindowManagerActionId, + WindowPlacementCommand, } from "../lib/window-manager-command-registry"; -import { dispatchWindowPlacement } from "../lib/window-manager-action-dispatch"; -import { resolveWindowManagerActions } from "../lib/window-manager-shortcuts"; -import { windowManagerCommandsAvailable } from "../lib/window-manager-command-availability"; import type { OsAppId } from "../lib/os-types"; -import { useDesktop } from "./use-desktop"; import { useOsShell } from "./use-os-shell"; +import { useOsWindowCommands, type OsFocusedWindowActions } from "./use-os-window-commands"; type PaletteSession = NonNullable["data"]>[number]; @@ -30,12 +25,7 @@ export interface OsCommandPaletteModel { * where browsers reserve ⌘W/⌘M (US-003.AC-4/EC-3). `zoom` is null in * compact presentation (the control has no meaning in a stack). */ - focusedWindowActions: { - close(): void; - minimize(): void; - zoom: (() => void) | null; - makeFloating: (() => void) | null; - } | null; + focusedWindowActions: OsFocusedWindowActions | null; openApp(app: OsAppId): void; jumpToSession(sessionId: string, agentName: string): void; dispatchPlacement(command: WindowPlacementCommand): void; @@ -50,63 +40,40 @@ export interface OsCommandPaletteModel { /** * Palette view-model: sources (apps come from the registry constant), the - * focused-window snap surface (ADR-009), and the run-and-close dispatch - * pattern. Keeps `OsCommandPalette` purely presentational. + * focused-window snap surface (ADR-009) lifted from `useOsWindowCommands` so + * the menubar cannot drift from it, and the run-and-close dispatch pattern. + * Keeps `OsCommandPalette` purely presentational. */ export function useOsCommandPalette( open: boolean, onOpenChange: (open: boolean) => void, options: { onOpenDesktops?: () => void; onToggleSessions?: () => void } = {} ): OsCommandPaletteModel { - const { coordinator, manager, store } = useOsShell(); + const { coordinator } = useOsShell(); const sessionCreate = useSessionCreate(); const { workspaces, activeWorkspaceId, setActiveWorkspaceId } = useActiveWorkspace(); const sessions = useSessions(activeWorkspaceId, { enabled: open && activeWorkspaceId !== null, }); - const focusedWindow = useDesktop(state => - state.presentation === "floating" && state.focusedId !== null - ? state.windows[state.focusedId] - : undefined - ); - const focusedId = useDesktop(state => state.focusedId); - const presentation = useDesktop(state => state.presentation); - const windowManagerConfig = useDesktop(state => state.windowManagerConfig); - const commandsAvailable = useDesktop(windowManagerCommandsAvailable); - const hasArrangePeer = useDesktop(state => { - if (state.presentation !== "floating" || state.focusedId === null) return false; - for (const win of Object.values(state.windows)) { - if (win.id !== state.focusedId && win.desktopId === state.activeDesktopId && !win.minimized) { - return true; - } - } - return false; - }); + const windowCommands = useOsWindowCommands(); + const { commandsAvailable } = windowCommands; const run = (action: () => void) => { onOpenChange(false); action(); }; - const shortcutLabels = Object.fromEntries( - resolveWindowManagerActions(windowManagerConfig?.shortcuts ?? {}).flatMap(action => - action.shortcutLabel ? [[action.id, action.shortcutLabel] as const] : [] - ) - ) as Partial>; - const focusedWindowActions = - !commandsAvailable || focusedId === null + const windowActions = windowCommands.focusedWindowActions; + const zoom = windowActions?.zoom ?? null; + const makeFloating = windowActions?.makeFloating ?? null; + const focusedWindowActions: OsFocusedWindowActions | null = + windowActions === null ? null : { - close: () => run(() => void coordinator.userClose(focusedId)), - minimize: () => run(() => void coordinator.userMinimize(focusedId)), - zoom: - presentation === "floating" - ? () => run(() => manager.getState().zoomWindow(focusedId)) - : null, - makeFloating: - focusedWindow && focusedWindow.placement !== "floating" - ? () => run(() => manager.getState().toggleFloating(focusedId)) - : null, + close: () => run(windowActions.close), + minimize: () => run(windowActions.minimize), + zoom: zoom === null ? null : () => run(zoom), + makeFloating: makeFloating === null ? null : () => run(makeFloating), }; return { @@ -117,10 +84,9 @@ export function useOsCommandPalette( ), workspaces, activeWorkspaceId, - shortcutLabels, - placementCommands: - commandsAvailable && focusedWindow && windowManagerConfig ? WINDOW_PLACEMENT_COMMANDS : [], - arrangeCommands: commandsAvailable && hasArrangePeer ? WINDOW_ARRANGE_COMMANDS : [], + shortcutLabels: windowCommands.shortcutLabels, + placementCommands: windowCommands.placementCommands, + arrangeCommands: windowCommands.arrangeCommands, openApp: app => run(() => { if (commandsAvailable) void coordinator.userOpen({ app }); @@ -137,23 +103,8 @@ export function useOsCommandPalette( }, }); }), - dispatchPlacement: command => - run(() => { - const state = store.getState(); - if ( - !windowManagerCommandsAvailable(state) || - state.focusedId === null || - state.windowManagerConfig === null - ) - return; - dispatchWindowPlacement(manager, state.focusedId, command); - }), - dispatchArrange: command => - run(() => { - const state = store.getState(); - if (!windowManagerCommandsAvailable(state) || state.focusedId === null) return; - state.arrangeLayout(state.focusedId, command.preset); - }), + dispatchPlacement: command => run(() => windowCommands.dispatchPlacement(command)), + dispatchArrange: command => run(() => windowCommands.dispatchArrange(command)), toggleSessions: () => run(() => options.onToggleSessions?.()), newSession: () => run(() => sessionCreate.openForAgent("")), openDesktops: () => run(() => options.onOpenDesktops?.()), diff --git a/web/src/systems/os/hooks/use-os-shortcuts.ts b/web/src/systems/os/hooks/use-os-shortcuts.ts index 108cea3e1..61593c210 100644 --- a/web/src/systems/os/hooks/use-os-shortcuts.ts +++ b/web/src/systems/os/hooks/use-os-shortcuts.ts @@ -12,6 +12,11 @@ export interface OsShortcutHandlers { onEscape: () => void; } +export interface OsShortcutOptions { + /** Off while a blocking surface owns the shell (first-run setup). */ + enabled?: boolean; +} + function isPlainMod(event: KeyboardEvent): boolean { return (event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey; } @@ -32,8 +37,15 @@ function isEditableTarget(target: EventTarget | null): boolean { * RuntimeSelector registry is deleted), ⌘N new session, Esc focus return, * and the live window-manager action registry. Config overrides are read at * event time, so a successful Settings apply changes dispatch immediately. + * + * `enabled: false` unbinds the listener entirely: ⌘K and ⌘N must not fire behind + * a blocking panel, and `inert` alone does not stop document-level keydown. */ -export function useOsShortcuts(handlers: OsShortcutHandlers): void { +export function useOsShortcuts( + handlers: OsShortcutHandlers, + options: OsShortcutOptions = {} +): void { + const enabled = options.enabled ?? true; const { store, manager } = useOsShell(); const handleKeyDown = useEffectEvent((event: KeyboardEvent) => { if (event.key === "Escape") { @@ -75,8 +87,9 @@ export function useOsShortcuts(handlers: OsShortcutHandlers): void { }); useEffect(() => { + if (!enabled) return undefined; const listener = (event: KeyboardEvent) => handleKeyDown(event); document.addEventListener("keydown", listener); return () => document.removeEventListener("keydown", listener); - }, []); + }, [enabled]); } diff --git a/web/src/systems/os/hooks/use-os-window-commands.ts b/web/src/systems/os/hooks/use-os-window-commands.ts new file mode 100644 index 000000000..e6cd80456 --- /dev/null +++ b/web/src/systems/os/hooks/use-os-window-commands.ts @@ -0,0 +1,146 @@ +import { + WINDOW_ARRANGE_COMMANDS, + WINDOW_PLACEMENT_COMMANDS, + type WindowArrangeCommand, + type WindowManagerActionId, + type WindowPlacementCommand, +} from "../lib/window-manager-command-registry"; +import { dispatchWindowPlacement } from "../lib/window-manager-action-dispatch"; +import { resolveWindowManagerActions } from "../lib/window-manager-shortcuts"; +import { windowManagerCommandsAvailable } from "../lib/window-manager-command-availability"; +import type { FocusDirection } from "../lib/window-manager-types"; +import { useDesktop } from "./use-desktop"; +import { useOsShell } from "./use-os-shell"; + +export interface OsFocusedWindowActions { + close(): void; + minimize(): void; + /** Null in compact presentation — zoom has no meaning in a stack. */ + zoom: (() => void) | null; + /** Null unless the focused window is currently tiled. */ + makeFloating: (() => void) | null; +} + +export interface OsWindowCommandsModel { + /** The daemon fence: an authoritative snapshot plus a live registered client. */ + commandsAvailable: boolean; + shortcutLabels: Readonly>>; + /** + * Lifecycle actions for the focused window, routed through the routing + * coordinator so the URL follows successor focus (Safety Invariant 13). + * Null when no window is focused or commands are unavailable. + */ + focusedWindowActions: OsFocusedWindowActions | null; + /** Placement presets; empty without a focused floating window (truthful UI). */ + placementCommands: readonly WindowPlacementCommand[]; + /** Arrange presets; empty without a second visible window (truthful UI). */ + arrangeCommands: readonly WindowArrangeCommand[]; + dispatchPlacement(command: WindowPlacementCommand): void; + dispatchArrange(command: WindowArrangeCommand): void; + canToggleFloating: boolean; + toggleFloating(): void; + canBalanceLayout: boolean; + balanceLayout(): void; + /** Undo/redo are daemon-mediated; the client holds no layout history. */ + canEditLayoutHistory: boolean; + undoLayout(): void; + redoLayout(): void; + canFocusDirection: boolean; + focusDirection(direction: FocusDirection): void; + canSwitchDesktop: boolean; + switchDesktop(direction: "previous" | "next"): void; +} + +/** + * The one window / layout / desktop command model. The ⌘K palette and the + * menubar's Window menu both read it, so their enablement predicates and their + * dispatch path cannot drift. + * + * Actions here run immediately; a caller that must dismiss its own surface + * first (the palette) wraps them. The keyboard registry keeps its own + * `dispatchWindowManagerAction` path, which still bypasses the coordinator for + * close/minimize — a pre-existing divergence, tracked separately. + */ +export function useOsWindowCommands(): OsWindowCommandsModel { + const { coordinator, manager, store } = useOsShell(); + const focusedWindow = useDesktop(state => + state.presentation === "floating" && state.focusedId !== null + ? state.windows[state.focusedId] + : undefined + ); + const focusedId = useDesktop(state => state.focusedId); + const presentation = useDesktop(state => state.presentation); + const windowManagerConfig = useDesktop(state => state.windowManagerConfig); + const desktopCount = useDesktop(state => state.desktops.length); + const commandsAvailable = useDesktop(windowManagerCommandsAvailable); + const hasArrangePeer = useDesktop(state => { + if (state.presentation !== "floating" || state.focusedId === null) return false; + for (const win of Object.values(state.windows)) { + if (win.id !== state.focusedId && win.desktopId === state.activeDesktopId && !win.minimized) { + return true; + } + } + return false; + }); + + const shortcutLabels = Object.fromEntries( + resolveWindowManagerActions(windowManagerConfig?.shortcuts ?? {}).flatMap(action => + action.shortcutLabel ? [[action.id, action.shortcutLabel] as const] : [] + ) + ) as Partial>; + + const hasFocusedWindow = commandsAvailable && focusedId !== null; + const focusedWindowActions: OsFocusedWindowActions | null = + !commandsAvailable || focusedId === null + ? null + : { + close: () => void coordinator.userClose(focusedId), + minimize: () => void coordinator.userMinimize(focusedId), + zoom: + presentation === "floating" + ? () => void manager.getState().zoomWindow(focusedId) + : null, + makeFloating: + focusedWindow && focusedWindow.placement !== "floating" + ? () => manager.getState().toggleFloating(focusedId) + : null, + }; + + return { + commandsAvailable, + shortcutLabels, + focusedWindowActions, + placementCommands: + commandsAvailable && focusedWindow && windowManagerConfig ? WINDOW_PLACEMENT_COMMANDS : [], + arrangeCommands: commandsAvailable && hasArrangePeer ? WINDOW_ARRANGE_COMMANDS : [], + dispatchPlacement: command => { + const state = store.getState(); + if ( + !windowManagerCommandsAvailable(state) || + state.focusedId === null || + state.windowManagerConfig === null + ) { + return; + } + dispatchWindowPlacement(manager, state.focusedId, command); + }, + dispatchArrange: command => { + const state = store.getState(); + if (!windowManagerCommandsAvailable(state) || state.focusedId === null) return; + state.arrangeLayout(state.focusedId, command.preset); + }, + canToggleFloating: hasFocusedWindow, + toggleFloating: () => { + if (focusedId !== null) manager.getState().toggleFloating(focusedId); + }, + canBalanceLayout: hasFocusedWindow, + balanceLayout: () => manager.balanceFocusedLayout(), + canEditLayoutHistory: commandsAvailable, + undoLayout: () => manager.undoLayout(), + redoLayout: () => manager.redoLayout(), + canFocusDirection: commandsAvailable, + focusDirection: direction => manager.focusDirection(direction), + canSwitchDesktop: commandsAvailable && desktopCount > 1, + switchDesktop: direction => manager.switchDesktopDirection(direction), + }; +} diff --git a/web/src/systems/os/index.ts b/web/src/systems/os/index.ts index 7a5d040ae..2be844926 100644 --- a/web/src/systems/os/index.ts +++ b/web/src/systems/os/index.ts @@ -31,5 +31,55 @@ export { export type { WindowManagerClientView, WindowManagerConfig, + WindowManagerDragModifier, WindowManagerSnapshot, } from "./lib/window-manager-types"; + +// Window geometry. The projector, the seam math and the floating clamp are the +// runtime's own — Settings renders the same rects the shell renders instead of +// computing a second, divergent model. +export { clampFloatingRect, projectLayout, type FloatingRectCommit } from "./lib/layout-projection"; +export { applySeamPreviewToDesktop, seamWeightDelta } from "./lib/seam-preview"; +export { buildWindowManagerMinimums } from "./lib/window-manager-view"; +export type { + LayoutAxis, + LayoutDesktop, + LayoutGroup, + LayoutLeafNode, + LayoutNode, + LayoutProjection, + LayoutProjectionDiagnostic, + LayoutProjectionInput, + LayoutSplitNode, + LayoutStackNode, + NormalizedRect, + PixelRect, + PixelSize, + ProjectedSeam, + ProjectedStack, + ProjectedWindow, + ProjectionGaps, + WindowMinimums, +} from "./lib/window-manager-types"; + +// Keyboard grammar. The action registry is the shipped default keymap; Settings +// edits overrides against it rather than restating the list. +export { + WINDOW_MANAGER_ACTIONS, + WINDOW_PLACEMENT_COMMANDS, + isWindowManagerActionId, + type WindowManagerActionDefinition, + type WindowManagerActionId, + type WindowPlacementId, +} from "./lib/window-manager-command-registry"; +export { + chordFromKeyboardEvent, + findShortcutConflicts, + parseShortcutChord, + resolveWindowManagerActions, + shortcutLabel, + type ParsedShortcutChord, + type ResolvedWindowManagerAction, + type ShortcutConflict, + type ShortcutConflictKind, +} from "./lib/window-manager-shortcuts"; diff --git a/web/src/systems/os/lib/__tests__/window-manager-shortcuts.test.ts b/web/src/systems/os/lib/__tests__/window-manager-shortcuts.test.ts new file mode 100644 index 000000000..31873dc5b --- /dev/null +++ b/web/src/systems/os/lib/__tests__/window-manager-shortcuts.test.ts @@ -0,0 +1,104 @@ +// Suite: window-manager chord grammar +// Invariant: chords read from the keyboard, parsed from storage, and rendered to +// the user all agree with the daemon's canonical form — modifier order +// meta+control+alt+shift, exactly one allowlisted KeyboardEvent.code, at least one +// modifier (internal/windowmanager/shortcuts.go: canonicalShortcutChord) — and the +// two conflict classes the daemon and the shell treat differently stay separable. +// Boundary IN: an overrides map or one keypress. +// Boundary OUT: recording lifecycle, React state, transport. +import { describe, expect, it } from "vitest"; + +import { WINDOW_MANAGER_ACTIONS } from "../window-manager-command-registry"; +import { + chordFromKeyboardEvent, + findShortcutConflicts, + parseShortcutChord, + resolveWindowManagerActions, + shortcutLabel, +} from "../window-manager-shortcuts"; + +function press(init: KeyboardEventInit & { code: string }): KeyboardEvent { + return new KeyboardEvent("keydown", { key: init.code, ...init }); +} + +describe("chordFromKeyboardEvent", () => { + it("Should emit modifiers in the daemon's canonical order", () => { + const chord = press({ + code: "KeyB", + altKey: true, + ctrlKey: true, + metaKey: true, + shiftKey: true, + }); + expect(chordFromKeyboardEvent(chord)).toBe("meta+control+alt+shift+KeyB"); + }); + + it("Should keep listening while only modifiers are held", () => { + expect(chordFromKeyboardEvent(press({ code: "ShiftLeft", key: "Shift", shiftKey: true }))).toBe( + null + ); + expect(chordFromKeyboardEvent(press({ code: "MetaLeft", key: "Meta", metaKey: true }))).toBe( + null + ); + }); + + it("Should reject a chord with no modifier", () => { + expect(chordFromKeyboardEvent(press({ code: "KeyB" }))).toBe(null); + }); + + it("Should reject a code the daemon does not accept", () => { + expect(chordFromKeyboardEvent(press({ code: "F13", ctrlKey: true }))).toBe(null); + expect(chordFromKeyboardEvent(press({ code: "NumpadEnter", ctrlKey: true }))).toBe(null); + }); + + it("Should round-trip through the parser it shares with stored overrides", () => { + const recorded = chordFromKeyboardEvent( + press({ code: "ArrowLeft", ctrlKey: true, altKey: true }) + ); + expect(recorded).toBe("control+alt+ArrowLeft"); + expect(parseShortcutChord(recorded ?? "")?.canonical).toBe(recorded); + expect(shortcutLabel(parseShortcutChord(recorded ?? "")!)).toBe("⌃⌥←"); + }); +}); + +describe("findShortcutConflicts", () => { + it("Should report no conflict for the shipped defaults", () => { + expect(findShortcutConflicts({})).toEqual([]); + }); + + it("Should block when two overrides claim the same chord", () => { + const conflicts = findShortcutConflicts({ + "window.focus.up": "meta+shift+KeyP", + "window.focus.down": "meta+shift+KeyP", + }); + expect(conflicts).toHaveLength(1); + expect(conflicts[0]?.kind).toBe("override"); + expect(conflicts[0]?.chord).toBe("meta+shift+KeyP"); + expect([...(conflicts[0]?.actionIds ?? [])].sort()).toEqual([ + "window.focus.down", + "window.focus.up", + ]); + }); + + it("Should mark an override landing on another action's shipped chord as shadowing", () => { + // control+alt+ArrowLeft ships on window.tile.left. + const conflicts = findShortcutConflicts({ "window.close": "control+alt+ArrowLeft" }); + expect(conflicts).toHaveLength(1); + expect(conflicts[0]?.kind).toBe("default"); + expect(conflicts[0]?.actionIds).toContain("window.tile.left"); + expect(conflicts[0]?.actionIds).toContain("window.close"); + }); + + it("Should ignore an override that only restates its own default", () => { + expect(findShortcutConflicts({ "window.close": "meta+KeyW" })).toEqual([]); + }); + + it("Should ignore actions left unbound", () => { + const unbound = WINDOW_MANAGER_ACTIONS.filter(action => !action.defaultChord); + expect(unbound.length).toBeGreaterThan(0); + expect(resolveWindowManagerActions({}).filter(action => !action.chord)).toHaveLength( + unbound.length + ); + expect(findShortcutConflicts({})).toEqual([]); + }); +}); diff --git a/web/src/systems/os/lib/window-manager-shortcuts.ts b/web/src/systems/os/lib/window-manager-shortcuts.ts index c76c9cd6b..08745ee82 100644 --- a/web/src/systems/os/lib/window-manager-shortcuts.ts +++ b/web/src/systems/os/lib/window-manager-shortcuts.ts @@ -1,6 +1,7 @@ import { WINDOW_MANAGER_ACTIONS, type WindowManagerActionDefinition, + type WindowManagerActionId, } from "./window-manager-command-registry"; type ShortcutModifier = "meta" | "control" | "alt" | "shift"; @@ -16,7 +17,22 @@ export interface ResolvedWindowManagerAction extends WindowManagerActionDefiniti shortcutLabel: string | null; } +/** + * `override` — two stored overrides share a chord, which `CanonicalShortcuts` + * rejects, so the save fails. `default` — one override lands on another action's + * shipped chord; the daemon stores it and the shell resolves whichever action + * comes first in `WINDOW_MANAGER_ACTIONS`. + */ +export type ShortcutConflictKind = "override" | "default"; + +export interface ShortcutConflict { + chord: string; + kind: ShortcutConflictKind; + actionIds: readonly WindowManagerActionId[]; +} + const MODIFIER_ORDER = ["meta", "control", "alt", "shift"] as const; +const MODIFIER_KEYS = new Set(["Meta", "Control", "Alt", "Shift"]); const KEY_CODE_PATTERN = /^(?:Key[A-Z]|Digit[0-9]|Arrow(?:Left|Right|Up|Down)|Bracket(?:Left|Right)|Comma|Period|Slash|Semicolon|Quote|Backquote|Minus|Equal|Backslash|Enter|Space|Tab|Escape|Backspace|Delete|Home|End|PageUp|PageDown|F(?:[1-9]|1[0-2]))$/; @@ -68,6 +84,48 @@ export function resolveWindowManagerActions( }); } +/** + * Reads one keypress as a chord, applying the daemon's grammar + * (`canonicalShortcutChord`): at least one modifier, exactly one allowlisted + * `KeyboardEvent.code`. Returns null for a modifier-only press so a recorder can + * keep listening while the user builds the combination. + */ +export function chordFromKeyboardEvent(event: KeyboardEvent): string | null { + if (MODIFIER_KEYS.has(event.key)) return null; + if (!KEY_CODE_PATTERN.test(event.code)) return null; + const held: ShortcutModifier[] = []; + if (event.metaKey) held.push("meta"); + if (event.ctrlKey) held.push("control"); + if (event.altKey) held.push("alt"); + if (event.shiftKey) held.push("shift"); + if (held.length === 0) return null; + const ordered = MODIFIER_ORDER.filter(modifier => held.includes(modifier)); + return [...ordered, event.code].join("+"); +} + +/** + * Groups every action that resolves to the same chord. `override` conflicts + * block the save; `default` conflicts are shadowing the caller should explain. + */ +export function findShortcutConflicts( + overrides: Readonly> +): readonly ShortcutConflict[] { + const byChord = new Map(); + for (const action of resolveWindowManagerActions(overrides)) { + if (!action.chord) continue; + const holders = byChord.get(action.chord.canonical); + if (holders) holders.push(action.id); + else byChord.set(action.chord.canonical, [action.id]); + } + const conflicts: ShortcutConflict[] = []; + for (const [chord, actionIds] of byChord) { + if (actionIds.length < 2) continue; + const overridden = actionIds.filter(id => overrides[id] != null).length; + conflicts.push({ chord, kind: overridden >= 2 ? "override" : "default", actionIds }); + } + return conflicts; +} + export function shortcutMatches(event: KeyboardEvent, chord: ParsedShortcutChord): boolean { return ( event.code === chord.code && diff --git a/web/src/systems/os/lib/window-manager-view.ts b/web/src/systems/os/lib/window-manager-view.ts index d3e4e51e7..bf26a0125 100644 --- a/web/src/systems/os/lib/window-manager-view.ts +++ b/web/src/systems/os/lib/window-manager-view.ts @@ -114,10 +114,18 @@ export function buildWindowManagerProjections( return projections; } -/** Maps every authoritative window to the same floor used by its interactive frame. */ -export function buildWindowManagerMinimums(snapshot: WindowManagerSnapshot): WindowMinimums { +/** + * Maps every authoritative window to the same floor used by its interactive + * frame. Typed against the shape it reads rather than the whole snapshot, so the + * settings editor can pass a layout document and get identical minimums — the + * projector's `minimum-unmet` and `adaptive-stack` diagnostics only mean + * something if both surfaces measure against the same floor. + */ +export function buildWindowManagerMinimums(source: { + windows: Readonly>; +}): WindowMinimums { return Object.fromEntries( - Object.values(snapshot.windows).map(window => { + Object.values(source.windows).map(window => { const app = osAppId(window.app); const minimum = app === null ? OS_WINDOW_CONSERVATIVE_MINIMUM : getOsAppMinimum(app); return [window.id, { width: minimum.width, height: minimum.height }]; diff --git a/web/src/systems/os/mocks/fixtures.ts b/web/src/systems/os/mocks/fixtures.ts index ce3a8c230..4902dcd9c 100644 --- a/web/src/systems/os/mocks/fixtures.ts +++ b/web/src/systems/os/mocks/fixtures.ts @@ -8,7 +8,8 @@ export const windowManagerSnapshotFixture: AghApiOkJsonResponseFor< "get", "/api/workspaces/{workspace_id}/window-manager" > = { - version: 1, + // SnapshotVersion (internal/windowmanager/types.go:9). + version: 2, workspace_id: storyDefaultWorkspaceId, revision: 12, desktops: [ diff --git a/web/src/systems/runtime/components/runtime-selector/index.ts b/web/src/systems/runtime/components/runtime-selector/index.ts index f1aac605e..4da2d9cc9 100644 --- a/web/src/systems/runtime/components/runtime-selector/index.ts +++ b/web/src/systems/runtime/components/runtime-selector/index.ts @@ -1,10 +1,12 @@ -// Public surface of the RuntimeSelector family. The reasoning enum/label helpers -// and the reasoning/variant type aliases are intentionally NOT re-exported: they -// have no cross-system consumer, and the family/tests import them from `./types` -// directly. Only the component, its value/option contract, and the compound-key -// builder (consumed by the model-catalog mapper) are public. +// Public surface of the RuntimeSelector family. The reasoning enum/position +// helpers and the reasoning/variant type aliases are intentionally NOT +// re-exported: they have no cross-system consumer, and the family/tests import +// them from `./types` directly. Public: the component, its value/option +// contract, the compound-key builder (consumed by the model-catalog mapper), and +// the effort label (consumed by the onboarding setup summary). export { RuntimeSelector, type RuntimeSelectorProps } from "./runtime-selector"; export { runtimeModelKey } from "./model-key"; +export { reasoningEffortLabel } from "./types"; export { type RuntimeAvailability, type RuntimeModelOption, diff --git a/web/src/systems/runtime/index.ts b/web/src/systems/runtime/index.ts index fe4a91e2e..d664b9f85 100644 --- a/web/src/systems/runtime/index.ts +++ b/web/src/systems/runtime/index.ts @@ -16,6 +16,7 @@ export { type RuntimeConnectionTone, } from "./components/connection-indicator.logic"; export { + reasoningEffortLabel, runtimeModelKey, RuntimeSelector, type RuntimeAvailability, diff --git a/web/src/systems/settings/components/__tests__/layout-canvas.test.tsx b/web/src/systems/settings/components/__tests__/layout-canvas.test.tsx new file mode 100644 index 000000000..513ced766 --- /dev/null +++ b/web/src/systems/settings/components/__tests__/layout-canvas.test.tsx @@ -0,0 +1,160 @@ +// Suite: the layout canvas ↔ projector contract +// Invariant: the canvas draws what `projectLayout` produced — one tile per +// projected window, one handle per seam — and marks the topology the daemon +// refuses (overlapping groups) rather than drawing it as if it were fine. +// Boundary IN: a draft desktop + the global config's gaps. +// Boundary OUT: drag arithmetic (owned by seam-preview), the inspector. +import { render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +import type { WindowManagerConfig } from "@/systems/os"; + +import { layoutCanvasProjection } from "../../lib/window-manager-layout-canvas"; +import type { + WindowManagerLayoutDesktop, + WindowManagerLayoutDocument, +} from "../../lib/window-manager-layout-types"; +import { LayoutCanvas } from "../layouts/layout-canvas"; + +const CONFIG = { + gaps: { inner: 8, top: 8, right: 8, bottom: 8, left: 8 }, +} as WindowManagerConfig; + +function windowAt(id: string, desktopId: string) { + return { + id, + app: "tasks", + instanceKey: null, + route: { pathname: "/tasks", search: {} }, + placement: "tiled" as const, + desktopId, + floatingRect: { x: 0.2, y: 0.2, w: 0.4, h: 0.4 }, + minimized: false, + returnAnchor: null, + }; +} + +function documentWith(desktop: WindowManagerLayoutDesktop): WindowManagerLayoutDocument { + return { + version: 2, + workspaceId: "workspace-a", + desktops: [desktop], + windows: { + "app:one": windowAt("app:one", desktop.id), + "app:two": windowAt("app:two", desktop.id), + "app:float": { ...windowAt("app:float", desktop.id), placement: "floating" }, + }, + overrides: {}, + }; +} + +const SPLIT_DESKTOP: WindowManagerLayoutDesktop = { + id: "desktop-one", + name: "Build", + order: 0, + purpose: "standard", + focusOwner: null, + floating: ["app:float"], + groups: [ + { + id: "group-main", + frame: { x: 0, y: 0, w: 1, h: 1 }, + root: { + id: "split-main", + kind: "split", + axis: "horizontal", + weights: [0.5, 0.5], + children: [ + { id: "leaf-one", kind: "leaf", windowId: "app:one" }, + { id: "leaf-two", kind: "leaf", windowId: "app:two" }, + ], + }, + }, + ], +}; + +function renderCanvas(desktop: WindowManagerLayoutDesktop) { + const document = documentWith(desktop); + const projection = layoutCanvasProjection(document, desktop, CONFIG, 1); + render( + + ); + return projection; +} + +describe("LayoutCanvas", () => { + it("Should draw one tile per projected window and one handle per seam", () => { + const projection = renderCanvas(SPLIT_DESKTOP); + + expect(projection.windows).toHaveLength(2); + expect(projection.seams).toHaveLength(1); + for (const projected of projection.windows) { + expect(screen.getByTestId(`layout-canvas-tile-${projected.windowId}`)).toBeInTheDocument(); + } + for (const seam of projection.seams) { + expect(screen.getByTestId(`layout-canvas-seam-${seam.id}`)).toBeInTheDocument(); + } + }); + + it("Should give every divider and group edge a keyboard-operable slider", () => { + renderCanvas(SPLIT_DESKTOP); + + const sliders = screen.getAllByRole("slider"); + // One seam plus four edges of the single group. + expect(sliders).toHaveLength(5); + for (const slider of sliders) { + expect(slider).toHaveAttribute("aria-valuenow"); + expect(slider).toHaveAttribute("tabindex", "0"); + } + }); + + it("Should show floating windows above the tiled ones", () => { + renderCanvas(SPLIT_DESKTOP); + + expect(screen.getByTestId("layout-canvas-floating-app:float")).toBeInTheDocument(); + }); + + it("Should mark the groups whose frames cover each other", () => { + const overlapping: WindowManagerLayoutDesktop = { + ...SPLIT_DESKTOP, + floating: [], + groups: [ + { + id: "group-a", + frame: { x: 0, y: 0, w: 0.7, h: 1 }, + root: { id: "leaf-one", kind: "leaf", windowId: "app:one" }, + }, + { + id: "group-b", + frame: { x: 0.5, y: 0, w: 0.5, h: 1 }, + root: { id: "leaf-two", kind: "leaf", windowId: "app:two" }, + }, + ], + }; + renderCanvas(overlapping); + + expect(screen.getByTestId("layout-canvas-group-group-a")).toHaveAttribute( + "data-overlapping", + "true" + ); + expect(screen.getByTestId("layout-canvas-group-group-b")).toHaveAttribute( + "data-overlapping", + "true" + ); + }); + + it("Should say when a desktop has nothing on it", () => { + renderCanvas({ ...SPLIT_DESKTOP, groups: [], floating: [] }); + + expect(screen.getByText("No windows on this desktop")).toBeInTheDocument(); + }); +}); diff --git a/web/src/systems/settings/components/__tests__/layout-review-bar.test.tsx b/web/src/systems/settings/components/__tests__/layout-review-bar.test.tsx new file mode 100644 index 000000000..9c7a365ed --- /dev/null +++ b/web/src/systems/settings/components/__tests__/layout-review-bar.test.tsx @@ -0,0 +1,168 @@ +// Suite: the layout review gate +// Invariant: a layout reaches the workspace only at the exact revision the daemon +// validated and previewed. Any edit after a check disarms Apply, and a document +// the daemon refused never reaches preview at all. +// Boundary IN: the editor model plus the validate/preview/apply adapter. +// Boundary OUT: the canvas, the inspector, the profile grid. +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import type { ReactNode } from "react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const apiMocks = vi.hoisted(() => ({ + apply: vi.fn(), + preview: vi.fn(), + validate: vi.fn(), +})); + +vi.mock("../../adapters/window-manager-layouts-api", () => ({ + applyWindowManagerLayout: apiMocks.apply, + previewWindowManagerLayout: apiMocks.preview, + validateWindowManagerLayout: apiMocks.validate, +})); + +import { useWindowManagerLayoutEditor } from "../../hooks/use-window-manager-layout-editor"; +import type { WindowManagerLayoutState } from "../../lib/window-manager-layout-types"; +import { LayoutReviewBar } from "../layouts/layout-review-bar"; + +const INITIAL: WindowManagerLayoutState = { + revision: 7, + document: { + version: 2, + workspaceId: "workspace-a", + desktops: [ + { + id: "desktop-one", + name: "Build", + order: 0, + purpose: "standard", + focusOwner: null, + floating: [], + groups: [ + { + id: "group-main", + frame: { x: 0, y: 0, w: 1, h: 1 }, + root: { id: "leaf-one", kind: "leaf", windowId: "app:tasks" }, + }, + ], + }, + ], + windows: { + "app:tasks": { + id: "app:tasks", + app: "tasks", + instanceKey: null, + route: { pathname: "/tasks", search: {} }, + placement: "tiled", + desktopId: "desktop-one", + floatingRect: { x: 0.2, y: 0.2, w: 0.4, h: 0.4 }, + minimized: false, + returnAnchor: null, + }, + }, + overrides: {}, + }, +}; + +function Harness() { + const editor = useWindowManagerLayoutEditor("workspace-a", INITIAL); + return ( + <> + + + + ); +} + +function renderBar() { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, + }); + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + render(, { wrapper }); +} + +describe("LayoutReviewBar", () => { + beforeEach(() => { + vi.clearAllMocks(); + apiMocks.validate.mockResolvedValue({ + workspaceId: "workspace-a", + valid: true, + diagnostics: [], + }); + apiMocks.preview.mockResolvedValue({ + revision: 7, + changed: true, + changes: { + desktopIds: ["desktop-one"], + windowIds: [], + groupIds: [], + nodeIds: [], + clientIds: [], + }, + diagnostics: [], + }); + apiMocks.apply.mockResolvedValue({ revision: 8, applied: true, diagnostics: [] }); + }); + + it("Should keep every action shut while the draft matches the workspace", () => { + renderBar(); + + expect(screen.getByTestId("layout-review-check")).toBeDisabled(); + expect(screen.getByTestId("layout-review-apply")).toBeDisabled(); + expect(screen.getByTestId("layout-review-status")).toHaveTextContent("Revision 7"); + }); + + it("Should apply only the exact document that passed validate and preview", async () => { + renderBar(); + fireEvent.click(screen.getByTestId("edit-desktop")); + + expect(screen.getByTestId("layout-review-apply")).toBeDisabled(); + fireEvent.click(screen.getByTestId("layout-review-check")); + await waitFor(() => expect(screen.getByTestId("layout-review-apply")).toBeEnabled()); + + // A further edit invalidates the check it has not been through. + fireEvent.click(screen.getByTestId("edit-desktop")); + expect(screen.getByTestId("layout-review-apply")).toBeDisabled(); + + fireEvent.click(screen.getByTestId("layout-review-check")); + await waitFor(() => expect(screen.getByTestId("layout-review-apply")).toBeEnabled()); + fireEvent.click(screen.getByTestId("layout-review-apply")); + + await waitFor(() => expect(apiMocks.apply).toHaveBeenCalledTimes(1)); + const [, revision, document] = apiMocks.apply.mock.calls[0] ?? []; + expect(revision).toBe(7); + expect(document.desktops[0].name).toBe("Build!!"); + }); + + it("Should never preview a document the daemon refused", async () => { + apiMocks.validate.mockResolvedValue({ + workspaceId: "workspace-a", + valid: false, + diagnostics: [ + { code: "topology.group_overlap", path: "groups.group-main", message: "groups overlap" }, + ], + }); + renderBar(); + fireEvent.click(screen.getByTestId("edit-desktop")); + fireEvent.click(screen.getByTestId("layout-review-check")); + + await waitFor(() => expect(screen.getByText("topology.group_overlap")).toBeInTheDocument()); + expect(apiMocks.preview).not.toHaveBeenCalled(); + expect(screen.getByTestId("layout-review-apply")).toBeDisabled(); + expect(screen.getByTestId("layout-review-status")).toHaveTextContent("1 problem to fix"); + }); +}); diff --git a/web/src/systems/settings/components/__tests__/window-manager-config-editor.test.tsx b/web/src/systems/settings/components/__tests__/window-manager-config-editor.test.tsx deleted file mode 100644 index dec6099cd..000000000 --- a/web/src/systems/settings/components/__tests__/window-manager-config-editor.test.tsx +++ /dev/null @@ -1,80 +0,0 @@ -// Suite: Window Manager config editor -// Invariant: Save remains unavailable for numeric drafts the daemon would reject. -// Owning layer: the Settings config-editor component and its editor model. -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { fireEvent, render, screen } from "@testing-library/react"; -import type { ReactNode } from "react"; -import { describe, expect, it } from "vitest"; - -import type { WindowManagerConfig } from "@/systems/os"; - -import { useWindowManagerConfigEditor } from "../../hooks/use-window-manager-config-editor"; -import { WindowManagerConfigEditor } from "../window-manager-config-editor"; - -const CONFIG: WindowManagerConfig = { - newWindowPolicy: "floating", - smallViewportPolicy: "stack", - focusPolicy: "click_directional", - focusWrap: true, - focusFollowsPointer: false, - raiseOnFocus: true, - dragAwayPolicy: "window", - groupMoveModifier: "alt", - swapModifier: "shift", - historyLimit: 100, - desktopTransition: "slide", - gaps: { inner: 8, top: 8, right: 8, bottom: 8, left: 8 }, - snap: { - edgeBand: 24, - cornerReach: 96, - exitSlack: 16, - repeatRatios: [0.5, 0.33, 0.67], - }, - bindings: { topCenter: "zoom", bottomCenter: "none" }, - shortcuts: {}, -}; - -function EditorHarness() { - const editor = useWindowManagerConfigEditor(CONFIG); - return ; -} - -function renderEditor() { - const client = new QueryClient({ - defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, - }); - const wrapper = ({ children }: { children: ReactNode }) => ( - {children} - ); - render(, { wrapper }); -} - -describe("WindowManagerConfigEditor", () => { - it("Should disable Save for empty and out-of-range numeric drafts", () => { - renderEditor(); - const history = screen.getByRole("spinbutton", { name: "History limit" }); - const save = screen.getByRole("button", { name: "Save settings" }); - - fireEvent.change(history, { target: { value: "101" } }); - expect(save).toBeEnabled(); - - fireEvent.change(history, { target: { value: "" } }); - expect(history).toHaveAttribute("aria-invalid", "true"); - expect(save).toBeDisabled(); - - fireEvent.change(history, { target: { value: "501" } }); - expect(history).toHaveAttribute("aria-invalid", "true"); - expect(save).toBeDisabled(); - }); - - it("Should reject duplicate ratios using the daemon precision", () => { - renderEditor(); - const ratios = screen.getByRole("textbox", { name: "Repeat ratios" }); - const save = screen.getByRole("button", { name: "Save settings" }); - - fireEvent.change(ratios, { target: { value: "0.5, 0.5000001" } }); - - expect(ratios).toHaveAttribute("aria-invalid", "true"); - expect(save).toBeDisabled(); - }); -}); diff --git a/web/src/systems/settings/components/__tests__/window-manager-layout-document-editor.test.tsx b/web/src/systems/settings/components/__tests__/window-manager-layout-document-editor.test.tsx deleted file mode 100644 index 84f0461b3..000000000 --- a/web/src/systems/settings/components/__tests__/window-manager-layout-document-editor.test.tsx +++ /dev/null @@ -1,265 +0,0 @@ -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { fireEvent, render, screen, waitFor } from "@testing-library/react"; -import { afterEach, describe, expect, it, vi } from "vitest"; - -import type { - WindowManagerLayoutResourceRecord, - WindowManagerLayoutState, - WindowManagerLayoutValidation, -} from "../../lib/window-manager-layout-types"; -import { settingsKeys } from "../../lib/query-keys"; -import { useWindowManagerLayoutEditor } from "../../hooks/use-window-manager-layout-editor"; -import { useWindowManagerLayoutProfiles } from "../../hooks/use-window-manager-layout-profiles"; -import { WindowManagerLayoutDocumentEditor } from "../window-manager-layout-document-editor"; - -const apiMocks = vi.hoisted(() => ({ - apply: vi.fn(), - deleteProfile: vi.fn(), - preview: vi.fn(), - putProfile: vi.fn(), - validate: vi.fn(), -})); - -vi.mock("../../adapters/window-manager-layouts-api", () => ({ - applyWindowManagerLayout: apiMocks.apply, - previewWindowManagerLayout: apiMocks.preview, - validateWindowManagerLayout: apiMocks.validate, - deleteWindowManagerLayoutProfile: apiMocks.deleteProfile, - putWindowManagerLayoutProfile: apiMocks.putProfile, -})); - -const initial: WindowManagerLayoutState = { - revision: 7, - document: { - version: 1, - workspaceId: "workspace-a", - desktops: [ - { - id: "desktop-a", - name: "Primary", - order: 0, - purpose: "standard", - focusOwner: null, - groups: [ - { - id: "group-a", - frame: { x: 0, y: 0, w: 1, h: 1 }, - root: { - id: "leaf-a", - kind: "leaf", - windowId: "window-a", - }, - }, - ], - floating: [], - }, - ], - windows: { - "window-a": { - id: "window-a", - app: "agents", - instanceKey: null, - route: { pathname: "/agents", search: {} }, - placement: "tiled", - desktopId: "desktop-a", - floatingRect: { x: 0.1, y: 0.1, w: 0.5, h: 0.5 }, - minimized: false, - returnAnchor: null, - }, - }, - overrides: {}, - }, -}; - -const PROFILE: WindowManagerLayoutResourceRecord = { - kind: "window_layout", - id: "primary-layout", - version: 3, - scope: { kind: "workspace", id: "workspace-a" }, - spec: { - version: 1, - id: "primary-layout", - displayName: "Primary layout", - aspectVariant: "any", - participantSlots: ["window-a"], - overflowPolicy: "stack", - document: initial.document, - }, - createdAt: "2026-07-22T00:00:00Z", - updatedAt: "2026-07-22T00:00:00Z", -}; - -function EditorHarness({ profiles }: { profiles: readonly WindowManagerLayoutResourceRecord[] }) { - const editor = useWindowManagerLayoutEditor("workspace-a", initial); - const profilesEditor = useWindowManagerLayoutProfiles({ - workspaceId: "workspace-a", - document: editor.draft, - profiles, - onLoad: editor.updateDraft, - }); - return ; -} - -function renderEditor(profiles: readonly WindowManagerLayoutResourceRecord[] = []) { - const queryClient = new QueryClient({ - defaultOptions: { - mutations: { retry: false }, - queries: { retry: false }, - }, - }); - queryClient.setQueryData(settingsKeys.windowManagerLayoutProfiles("workspace-a"), profiles); - const rendered = render( - - - - ); - return { ...rendered, queryClient }; -} - -function validation(valid: boolean): WindowManagerLayoutValidation { - return { - workspaceId: "workspace-a", - valid, - diagnostics: valid - ? [] - : [ - { - code: "invalid_split_weights", - path: "desktops[0].groups[0].root.weights", - message: "Split weights must be positive.", - }, - ], - }; -} - -afterEach(() => { - vi.clearAllMocks(); -}); - -describe("WindowManagerLayoutDocumentEditor", () => { - it("Should apply only the exact document revision that passed validation and preview", async () => { - apiMocks.validate.mockResolvedValue(validation(true)); - apiMocks.preview.mockResolvedValue({ - revision: 7, - changed: true, - changes: { - desktopIds: ["desktop-a"], - windowIds: [], - groupIds: [], - nodeIds: [], - clientIds: [], - }, - diagnostics: [], - }); - apiMocks.apply.mockResolvedValue({ - revision: 8, - applied: true, - diagnostics: [], - }); - renderEditor(); - - const reviewButton = screen.getByRole("button", { - name: "Validate and preview", - }); - const applyButton = screen.getByRole("button", { - name: "Apply reviewed layout", - }); - expect(applyButton).toBeDisabled(); - - fireEvent.click(reviewButton); - - expect(await screen.findByText("Daemon validation passed")).toBeInTheDocument(); - expect(apiMocks.preview).toHaveBeenCalledWith( - "workspace-a", - 7, - expect.objectContaining({ workspaceId: "workspace-a" }), - undefined, - expect.any(AbortSignal) - ); - expect(applyButton).toBeEnabled(); - - fireEvent.change(screen.getByDisplayValue("Primary"), { - target: { value: "Renamed" }, - }); - - expect(applyButton).toBeDisabled(); - expect(screen.queryByTestId("window-manager-layout-review")).not.toBeInTheDocument(); - - fireEvent.click(reviewButton); - await waitFor(() => expect(apiMocks.preview).toHaveBeenCalledTimes(2)); - expect(applyButton).toBeEnabled(); - - fireEvent.click(applyButton); - - await waitFor(() => - expect(apiMocks.apply).toHaveBeenCalledWith( - "workspace-a", - 7, - expect.objectContaining({ - desktops: [ - expect.objectContaining({ - id: "desktop-a", - name: "Renamed", - }), - ], - }) - ) - ); - }); - - it("Should not preview or apply a document rejected by daemon validation", async () => { - apiMocks.validate.mockResolvedValue(validation(false)); - renderEditor(); - - fireEvent.click( - screen.getByRole("button", { - name: "Validate and preview", - }) - ); - - expect(await screen.findByText("Daemon validation failed")).toBeInTheDocument(); - expect(screen.getByTestId("window-manager-layout-review")).toHaveTextContent( - "desktops[0].groups[0].root.weights: Split weights must be positive." - ); - expect(apiMocks.preview).not.toHaveBeenCalled(); - expect( - screen.getByRole("button", { - name: "Apply reviewed layout", - }) - ).toBeDisabled(); - expect(apiMocks.apply).not.toHaveBeenCalled(); - }); - - it("Should move an existing profile scope with its current version and replace its cache identity", async () => { - const moved: WindowManagerLayoutResourceRecord = { - ...PROFILE, - version: 4, - scope: { kind: "global", id: "" }, - updatedAt: "2026-07-23T00:00:00Z", - }; - apiMocks.putProfile.mockResolvedValue(moved); - const { queryClient } = renderEditor([PROFILE]); - - fireEvent.click(screen.getByRole("radio", { name: /Primary layout/ })); - fireEvent.change(screen.getByRole("combobox", { name: "Scope" }), { - target: { value: "global" }, - }); - fireEvent.click(screen.getByRole("button", { name: "Save profile" })); - - await waitFor(() => - expect(apiMocks.putProfile).toHaveBeenCalledWith( - expect.objectContaining({ id: PROFILE.id }), - "global", - "workspace-a", - PROFILE.version - ) - ); - await waitFor(() => - expect( - queryClient.getQueryData( - settingsKeys.windowManagerLayoutProfiles("workspace-a") - ) - ).toEqual([moved]) - ); - }); -}); diff --git a/web/src/systems/settings/components/index.ts b/web/src/systems/settings/components/index.ts index 513aedbe1..89c1bff24 100644 --- a/web/src/systems/settings/components/index.ts +++ b/web/src/systems/settings/components/index.ts @@ -37,8 +37,8 @@ export type { SettingsChoiceGroupProps, SettingsChoiceOption } from "./settings- export { SettingsTile, SettingsTiles } from "./settings-tiles"; export type { SettingsTileProps } from "./settings-tiles"; export { SettingsAdvancedFold, SettingsProvChip } from "./settings-advanced-fold"; -export { RoleSettingsGroup } from "./role-settings-group"; -export type { RoleSettingsGroupProps } from "./role-settings-group"; +export { RoleList } from "./role-list"; +export type { RoleListProps } from "./role-list"; export { SettingsHeroBoard, type SettingsHeroBoardProps, @@ -67,4 +67,5 @@ export { SettingsSaveBar } from "./settings-save-bar"; export { SettingsSourceBadge } from "./settings-source-badge"; export type { SettingsSource } from "./settings-source-badge"; export { WindowManagerConfigEditor } from "./window-manager-config-editor"; -export { WindowManagerLayoutDocumentEditor } from "./window-manager-layout-document-editor"; +export { LayoutStage } from "./layouts/layout-stage"; +export { LayoutProfileGrid } from "./layouts/layout-profile-grid"; diff --git a/web/src/systems/settings/components/layouts/layout-canvas-board-bar.tsx b/web/src/systems/settings/components/layouts/layout-canvas-board-bar.tsx new file mode 100644 index 000000000..58cfb39a2 --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-canvas-board-bar.tsx @@ -0,0 +1,92 @@ +import { Pill } from "@agh/ui"; + +import type { LayoutProjection, LayoutProjectionDiagnostic } from "@/systems/os"; + +import { LAYOUT_CANVAS_REFERENCE } from "../../lib/window-manager-layout-reference"; +import { layoutWindowFace } from "../../lib/window-manager-layout-window-face"; +import type { + WindowManagerLayoutDesktop, + WindowManagerLayoutDocument, +} from "../../lib/window-manager-layout-types"; + +interface LayoutCanvasBoardBarProps { + document: WindowManagerLayoutDocument; + desktop: WindowManagerLayoutDesktop; + projection: LayoutProjection; +} + +const REFERENCE_LABEL = `${LAYOUT_CANVAS_REFERENCE.w} × ${LAYOUT_CANVAS_REFERENCE.h}`; + +/** + * What is on this desktop, and — because the canvas is a fixed reference screen + * rather than the viewport in front of you — the size that reading is true at. + * Without that caption the fit warnings below would be a claim about a screen + * nobody named. + */ +export function LayoutCanvasBoardBar({ document, desktop, projection }: LayoutCanvasBoardBarProps) { + const floating = desktop.floating.filter(id => document.windows[id]?.minimized === false).length; + const minimized = desktop.floating.filter(id => document.windows[id]?.minimized === true).length; + const focusOwner = desktop.focusOwner ? document.windows[desktop.focusOwner] : undefined; + const notes = fitNotes(document, projection.diagnostics); + + return ( +
    +
    + {projection.windows.length} tiled + {floating} floating + {minimized > 0 ? {minimized} minimized : null} + + {desktop.purpose === "focus" ? ( + + Focus desktop + {focusOwner ? ` · ${layoutWindowFace(focusOwner, focusOwner.id).title}` : ""} + + ) : null} + {REFERENCE_LABEL} reference +
    + {notes.length > 0 ? ( +
      + {notes.map(note => ( +
    • {note}
    • + ))} +
    + ) : null} +
    + ); +} + +function fitNotes( + document: WindowManagerLayoutDocument, + diagnostics: readonly LayoutProjectionDiagnostic[] +): string[] { + const folded = diagnostics.filter(entry => entry.code === "adaptive-stack").length; + const cramped = diagnostics.flatMap(entry => + entry.code === "minimum-unmet" + ? [layoutWindowFace(document.windows[entry.windowId], entry.windowId).title] + : [] + ); + const invalid = diagnostics.filter(entry => entry.code === "invalid-group-frame").length; + + const notes: string[] = []; + if (folded > 0) { + notes.push( + `At ${REFERENCE_LABEL}, ${folded} split${folded === 1 ? "" : "s"} ${folded === 1 ? "folds" : "fold"} into a stack because the windows no longer fit side by side.` + ); + } + if (cramped.length > 0) { + const unique = [...new Set(cramped)]; + notes.push( + `At ${REFERENCE_LABEL}, ${unique.join(", ")} ${unique.length === 1 ? "is" : "are"} below the smallest size the window supports.` + ); + } + if (invalid > 0) { + notes.push( + `${invalid} group${invalid === 1 ? "" : "s"} sit outside the desktop. The daemon refuses a layout that leaves the screen.` + ); + } + return notes; +} diff --git a/web/src/systems/settings/components/layouts/layout-canvas-floating.tsx b/web/src/systems/settings/components/layouts/layout-canvas-floating.tsx new file mode 100644 index 000000000..d0bffe7a4 --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-canvas-floating.tsx @@ -0,0 +1,135 @@ +import type { RefObject } from "react"; + +import { cn } from "@agh/ui"; + +import { clampFloatingRect } from "@/systems/os"; + +import { usePointerDrag } from "../../hooks/use-pointer-drag"; +import { normalizedPercentStyle } from "../../lib/window-manager-layout-canvas"; +import { LAYOUT_CANVAS_REFERENCE } from "../../lib/window-manager-layout-reference"; +import { layoutWindowFace } from "../../lib/window-manager-layout-window-face"; +import type { + WindowManagerLayoutWindow, + WindowManagerNormalizedRect, +} from "../../lib/window-manager-layout-types"; + +interface LayoutCanvasFloatingProps { + window: WindowManagerLayoutWindow; + selected: boolean; + canvasRef: RefObject; + onSelect: () => void; + onChange: (rect: WindowManagerNormalizedRect) => void; +} + +const KEYBOARD_STEP = 0.01; + +function toReferencePixels(rect: WindowManagerNormalizedRect) { + return { + x: rect.x * LAYOUT_CANVAS_REFERENCE.w, + y: rect.y * LAYOUT_CANVAS_REFERENCE.h, + w: rect.w * LAYOUT_CANVAS_REFERENCE.w, + h: rect.h * LAYOUT_CANVAS_REFERENCE.h, + }; +} + +/** + * A floating window sits above every group on its desktop. Dragging it writes + * `floatingRect`, clamped by the runtime's own containment rule so it cannot be + * parked outside the work area the shell will restore it into. + */ +export function LayoutCanvasFloating({ + window, + selected, + canvasRef, + onSelect, + onChange, +}: LayoutCanvasFloatingProps) { + const face = layoutWindowFace(window, window.id); + const Icon = face.icon; + + const move = (rect: WindowManagerNormalizedRect, dx: number, dy: number) => { + const pixels = toReferencePixels(rect); + const clamped = clampFloatingRect({ + proposedRect: { ...pixels, x: pixels.x + dx, y: pixels.y + dy }, + workArea: LAYOUT_CANVAS_REFERENCE, + }); + onChange({ + x: clamped.x / LAYOUT_CANVAS_REFERENCE.w, + y: clamped.y / LAYOUT_CANVAS_REFERENCE.h, + w: clamped.w / LAYOUT_CANVAS_REFERENCE.w, + h: clamped.h / LAYOUT_CANVAS_REFERENCE.h, + }); + }; + + const drag = usePointerDrag<{ + rect: WindowManagerNormalizedRect; + originX: number; + originY: number; + scaleX: number; + scaleY: number; + }>({ + onStart: event => { + const canvas = canvasRef.current?.getBoundingClientRect(); + if (!canvas || canvas.width === 0 || canvas.height === 0) return null; + onSelect(); + return { + rect: window.floatingRect, + originX: event.clientX, + originY: event.clientY, + scaleX: LAYOUT_CANVAS_REFERENCE.w / canvas.width, + scaleY: LAYOUT_CANVAS_REFERENCE.h / canvas.height, + }; + }, + onMove: (event, state) => { + move( + state.rect, + (event.clientX - state.originX) * state.scaleX, + (event.clientY - state.originY) * state.scaleY + ); + }, + }); + + return ( + + ); +} diff --git a/web/src/systems/settings/components/layouts/layout-canvas-group-edge.tsx b/web/src/systems/settings/components/layouts/layout-canvas-group-edge.tsx new file mode 100644 index 000000000..35c7fcaa8 --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-canvas-group-edge.tsx @@ -0,0 +1,82 @@ +import type { RefObject } from "react"; + +import { cn } from "@agh/ui"; + +import { + useLayoutGroupFrameDrag, + type LayoutGroupEdge, +} from "../../hooks/use-layout-group-frame-drag"; +import type { + WindowManagerLayoutGroup, + WindowManagerNormalizedRect, +} from "../../lib/window-manager-layout-types"; + +const EDGE_LABEL: Record = { + top: "top", + right: "right", + bottom: "bottom", + left: "left", +}; + +const EDGE_BOX: Record = { + top: "-top-1 right-2 left-2 h-2 cursor-ns-resize", + bottom: "-bottom-1 right-2 left-2 h-2 cursor-ns-resize", + left: "-left-1 top-2 bottom-2 w-2 cursor-ew-resize", + right: "-right-1 top-2 bottom-2 w-2 cursor-ew-resize", +}; + +const EDGE_GRIP: Record = { + top: "h-0.5 w-6", + bottom: "h-0.5 w-6", + left: "h-6 w-0.5", + right: "h-6 w-0.5", +}; + +interface LayoutCanvasGroupEdgeProps { + group: WindowManagerLayoutGroup; + edge: LayoutGroupEdge; + canvasRef: RefObject; + onChange: (frame: WindowManagerNormalizedRect) => void; +} + +/** One edge of a group's share of the desktop — a divider, and a slider. */ +export function LayoutCanvasGroupEdge({ + group, + edge, + canvasRef, + onChange, +}: LayoutCanvasGroupEdgeProps) { + const model = useLayoutGroupFrameDrag(group, edge, canvasRef, onChange); + + return ( +
    +
    + ); +} diff --git a/web/src/systems/settings/components/layouts/layout-canvas-seam.tsx b/web/src/systems/settings/components/layouts/layout-canvas-seam.tsx new file mode 100644 index 000000000..616cf014d --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-canvas-seam.tsx @@ -0,0 +1,92 @@ +import type { RefObject } from "react"; + +import { cn } from "@agh/ui"; + +import type { ProjectedSeam } from "@/systems/os"; + +import { useLayoutDraftSeam } from "../../hooks/use-layout-draft-seam"; +import { LAYOUT_CANVAS_REFERENCE } from "../../lib/window-manager-layout-reference"; +import type { WindowManagerLayoutDesktop } from "../../lib/window-manager-layout-types"; + +interface LayoutCanvasSeamProps { + seam: ProjectedSeam; + desktop: WindowManagerLayoutDesktop; + canvasRef: RefObject; + onChange: (next: WindowManagerLayoutDesktop) => void; +} + +function percent(value: number, span: number): string { + return `${(value / span) * 100}%`; +} + +/** + * The divider between two tiles, dragged where it sits. It is also a slider: + * arrow keys move it, so a layout can be balanced without a pointer. + */ +export function LayoutCanvasSeam({ seam, desktop, canvasRef, onChange }: LayoutCanvasSeamProps) { + const model = useLayoutDraftSeam(seam, desktop, canvasRef, onChange); + const vertical = seam.orientation === "vertical"; + const centreX = seam.rect.x + seam.rect.w / 2; + const centreY = seam.rect.y + seam.rect.h / 2; + + return ( +
    +
    + ); +} diff --git a/web/src/systems/settings/components/layouts/layout-canvas-tile.tsx b/web/src/systems/settings/components/layouts/layout-canvas-tile.tsx new file mode 100644 index 000000000..b08683482 --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-canvas-tile.tsx @@ -0,0 +1,92 @@ +import { cn } from "@agh/ui"; + +import type { ProjectedStack, ProjectedWindow } from "@/systems/os"; + +import { canvasPercentStyle } from "../../lib/window-manager-layout-canvas"; +import { layoutWindowFace } from "../../lib/window-manager-layout-window-face"; +import type { WindowManagerLayoutDocument } from "../../lib/window-manager-layout-types"; + +interface LayoutCanvasTileProps { + document: WindowManagerLayoutDocument; + projected: ProjectedWindow; + stack: ProjectedStack | null; + selected: boolean; + onSelect: () => void; +} + +/** + * One projected window. Purely presentational: the rect comes from the runtime + * projector, so what shows here is the arrangement the shell will actually build. + */ +export function LayoutCanvasTile({ + document, + projected, + stack, + selected, + onSelect, +}: LayoutCanvasTileProps) { + const face = layoutWindowFace(document.windows[projected.windowId], projected.windowId); + const Icon = face.icon; + + return ( + + ); +} + +function LayoutStackTabs({ + document, + stack, +}: { + document: WindowManagerLayoutDocument; + stack: ProjectedStack; +}) { + return ( + + {stack.windowIds.map(windowId => { + const face = layoutWindowFace(document.windows[windowId], windowId); + return ( + + {face.title} + + ); + })} + + ); +} diff --git a/web/src/systems/settings/components/layouts/layout-canvas.tsx b/web/src/systems/settings/components/layouts/layout-canvas.tsx new file mode 100644 index 000000000..68933c385 --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-canvas.tsx @@ -0,0 +1,153 @@ +import { useRef } from "react"; + +import { cn } from "@agh/ui"; + +import type { LayoutProjection, WindowManagerConfig } from "@/systems/os"; + +import type { LayoutSelection } from "../../hooks/use-layout-canvas-selection"; +import { + normalizedPercentStyle, + overlappingGroupIds, +} from "../../lib/window-manager-layout-canvas"; +import type { + WindowManagerLayoutDesktop, + WindowManagerLayoutDocument, + WindowManagerNormalizedRect, +} from "../../lib/window-manager-layout-types"; +import { LayoutCanvasFloating } from "./layout-canvas-floating"; +import { LayoutCanvasGroupEdge } from "./layout-canvas-group-edge"; +import { LayoutCanvasSeam } from "./layout-canvas-seam"; +import { LayoutCanvasTile } from "./layout-canvas-tile"; + +const GROUP_EDGES = ["top", "right", "bottom", "left"] as const; + +interface LayoutCanvasProps { + document: WindowManagerLayoutDocument; + desktop: WindowManagerLayoutDesktop; + projection: LayoutProjection; + config: WindowManagerConfig; + selection: LayoutSelection; + onSelect: (next: LayoutSelection) => void; + onDesktopChange: (next: WindowManagerLayoutDesktop) => void; + onFloatingRectChange: (windowId: string, rect: WindowManagerNormalizedRect) => void; +} + +/** + * The desktop, at the size of a desktop. Every rect on this surface comes from + * the runtime projector, so the arrangement shown is the arrangement the shell + * builds — including where it folds a split into a stack because the windows no + * longer fit. + */ +export function LayoutCanvas({ + document, + desktop, + projection, + config, + selection, + onSelect, + onDesktopChange, + onFloatingRectChange, +}: LayoutCanvasProps) { + const canvasRef = useRef(null); + const overlapping = overlappingGroupIds(desktop); + const stacks = new Map(projection.stacks.map(stack => [stack.nodeId, stack])); + const empty = desktop.groups.length === 0 && desktop.floating.length === 0; + + return ( +
    onSelect(null)} + > + {empty ? ( +
    +

    No windows on this desktop

    +

    Open a window in the workspace to start tiling.

    +
    + ) : null} + + {desktop.groups.map(group => ( +
    + {GROUP_EDGES.map(edge => ( + { + onSelect({ kind: "group", id: group.id }); + onDesktopChange({ + ...desktop, + groups: desktop.groups.map(candidate => + candidate.id === group.id ? { ...candidate, frame } : candidate + ), + }); + }} + /> + ))} +
    + ))} + + {projection.windows.map(projected => ( + onSelect({ kind: "node", id: projected.nodeId })} + /> + ))} + + {projection.seams.map(seam => ( + + ))} + + {desktop.floating.map(windowId => { + const window = document.windows[windowId]; + if (!window) return null; + return ( + onFloatingRectChange(windowId, rect)} + onSelect={() => onSelect({ kind: "window", id: windowId })} + /> + ); + })} + + + Gaps of {config.gaps.inner} pixels between tiles, shown at the reference screen size. + +
    + ); +} diff --git a/web/src/systems/settings/components/layouts/layout-desktop-tabs.tsx b/web/src/systems/settings/components/layouts/layout-desktop-tabs.tsx new file mode 100644 index 000000000..cf1864170 --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-desktop-tabs.tsx @@ -0,0 +1,105 @@ +import { useState } from "react"; + +import { Input, cn } from "@agh/ui"; + +import type { WindowManagerLayoutDesktop } from "../../lib/window-manager-layout-types"; + +interface LayoutDesktopTabsProps { + desktops: readonly WindowManagerLayoutDesktop[]; + activeIndex: number; + onSelect: (index: number) => void; + onRename: (index: number, name: string) => void; +} + +/** + * Desktops are switched here and renamed here — but not created or removed: + * those are semantic commands the workspace owns, not edits to a layout + * document, and the strip says so rather than offering a button that would fail. + */ +export function LayoutDesktopTabs({ + desktops, + activeIndex, + onSelect, + onRename, +}: LayoutDesktopTabsProps) { + const [renaming, setRenaming] = useState(null); + + return ( +
    + {desktops.map((desktop, index) => { + const active = index === activeIndex; + if (renaming === index) { + return ( + { + setRenaming(null); + if (name !== desktop.name) onRename(index, name); + }} + /> + ); + } + return ( + + ); + })} + + + Desktops are created and removed in the workspace, not here + +
    + ); +} + +/** + * Uncontrolled on purpose: the field is mounted only while renaming and the name + * it starts from is the one on screen, so mirroring the prop into state would + * add a second copy of the truth for no gain. + */ +function DesktopNameInput({ name, onCommit }: { name: string; onCommit: (name: string) => void }) { + return ( + onCommit(event.target.value.trim() || name)} + onKeyDown={event => { + if (event.key === "Enter") { + event.preventDefault(); + event.currentTarget.blur(); + } + if (event.key === "Escape") { + event.preventDefault(); + onCommit(name); + } + }} + /> + ); +} diff --git a/web/src/systems/settings/components/layouts/layout-inspector-node.tsx b/web/src/systems/settings/components/layouts/layout-inspector-node.tsx new file mode 100644 index 000000000..82b164cae --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-inspector-node.tsx @@ -0,0 +1,173 @@ +import { Button, Eyebrow, Progress, cn } from "@agh/ui"; + +import { + evenWeights, + layoutNodeIds, + createLayoutNodeIdFactory, + layoutOrientationOf, + toSplit, + toStack, + type LayoutOrientation, +} from "../../lib/window-manager-layout-mutations"; +import { fractionLabel } from "../../lib/window-manager-layout-detents"; +import { layoutNodeWindowIds, replaceLayoutNode } from "../../lib/window-manager-layout-tree"; +import type { + WindowManagerLayoutDesktop, + WindowManagerLayoutNode, +} from "../../lib/window-manager-layout-types"; +import { + LayoutColumnsDiagram, + LayoutRowsDiagram, + LayoutStackDiagram, +} from "./layout-node-diagrams"; + +interface LayoutInspectorNodeProps { + node: WindowManagerLayoutNode; + desktop: WindowManagerLayoutDesktop; + onDesktopChange: (next: WindowManagerLayoutDesktop) => void; +} + +/** + * How this branch arranges the windows under it. Three pictures, not an axis + * enum and a weight column — and the "Arrange as" actions are the only writer of + * split weights besides the seam drag, so both go through the same normalizer. + */ +export function LayoutInspectorNode({ node, desktop, onDesktopChange }: LayoutInspectorNodeProps) { + const windowIds = layoutNodeWindowIds(node); + const canRestructure = windowIds.length >= 2; + const orientation = node.kind === "split" ? layoutOrientationOf(node.axis) : null; + + const mintId = () => + createLayoutNodeIdFactory(desktop.groups.flatMap(group => layoutNodeIds(group.root))); + + const replace = (next: WindowManagerLayoutNode) => { + onDesktopChange(replaceLayoutNode(desktop, node.id, next)); + }; + + return ( + <> +
    + Arrange as +
    + replace(toSplit(node, "rows", mintId()))} + > + + + replace(toSplit(node, "columns", mintId()))} + > + + + replace(toStack(node, mintId()))} + > + + +
    + {canRestructure ? null : ( +

    + A single window has nothing to split. Add a second window to this branch first. +

    + )} +
    + + {node.kind === "split" ? ( + replace({ ...node, weights: evenWeights(node.children.length) })} + /> + ) : null} + + ); +} + +function ArrangeAction({ + active, + disabled, + label, + children, + onSelect, +}: { + active: boolean; + disabled: boolean; + label: string; + children: React.ReactNode; + onSelect: () => void; +}) { + return ( + + ); +} + +function LayoutSplitBalance({ + node, + orientation, + onDistribute, +}: { + node: Extract; + orientation: LayoutOrientation; + onDistribute: () => void; +}) { + const unit = orientation === "rows" ? "Row" : "Column"; + + return ( +
    + Balance +
    + {node.children.map((child, index) => ( + + + {unit} {index + 1} + + + {fractionLabel(node.weights[index] ?? 0)} + + + ))} +
    + +
    + ); +} diff --git a/web/src/systems/settings/components/layouts/layout-inspector-window.tsx b/web/src/systems/settings/components/layouts/layout-inspector-window.tsx new file mode 100644 index 000000000..e17418287 --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-inspector-window.tsx @@ -0,0 +1,140 @@ +import { Check } from "lucide-react"; + +import { Eyebrow, Item, ItemContent, ItemMedia, ItemTitle, cn } from "@agh/ui"; + +import { + desktopWindowIds, + layoutWindowOwners, + replaceLayoutNode, +} from "../../lib/window-manager-layout-tree"; +import { layoutWindowFace } from "../../lib/window-manager-layout-window-face"; +import type { + WindowManagerLayoutDesktop, + WindowManagerLayoutDocument, + WindowManagerLayoutNode, +} from "../../lib/window-manager-layout-types"; + +interface LayoutInspectorWindowProps { + node: WindowManagerLayoutNode; + desktop: WindowManagerLayoutDesktop; + document: WindowManagerLayoutDocument; + onDesktopChange: (next: WindowManagerLayoutDesktop) => void; +} + +/** + * What this tile shows. A leaf picks from the desktop's windows, with the ones + * another node already holds ruled out — the daemon rejects a document that + * places the same window twice, so the picker refuses it rather than reporting + * it afterwards. A stack picks which of its members is on top. + */ +export function LayoutInspectorWindow({ + node, + desktop, + document, + onDesktopChange, +}: LayoutInspectorWindowProps) { + if (node.kind === "leaf") { + const owners = layoutWindowOwners(desktop); + return ( +
    + Shows + { + const owner = owners.get(windowId); + return owner !== undefined && owner !== node.id; + }} + windowIds={desktopWindowIds(document, desktop.id)} + onChoose={windowId => + onDesktopChange(replaceLayoutNode(desktop, node.id, { ...node, windowId })) + } + /> +
    + ); + } + + if (node.kind !== "stack") return null; + + return ( +
    + On top + false} + windowIds={node.windowIds} + onChoose={activeId => + onDesktopChange(replaceLayoutNode(desktop, node.id, { ...node, activeId })) + } + /> + {node.windowIds.length < 2 ? ( +

    + A stack needs at least two windows. The daemon refuses one that holds a single window. +

    + ) : null} +
    + ); +} + +function WindowChoiceList({ + document, + windowIds, + selectedId, + unavailable, + onChoose, +}: { + document: WindowManagerLayoutDocument; + windowIds: readonly string[]; + selectedId: string; + unavailable: (windowId: string) => boolean; + onChoose: (windowId: string) => void; +}) { + if (windowIds.length === 0) { + return

    This desktop has no windows to show.

    ; + } + + return ( +
    + {windowIds.map(windowId => { + const face = layoutWindowFace(document.windows[windowId], windowId); + const Icon = face.icon; + const taken = unavailable(windowId); + const selected = windowId === selectedId; + return ( + { + if (!taken) onChoose(windowId); + }} + > + + + + {face.title} + + {selected ? ( + + ); + })} +
    + ); +} diff --git a/web/src/systems/settings/components/layouts/layout-inspector.tsx b/web/src/systems/settings/components/layouts/layout-inspector.tsx new file mode 100644 index 000000000..23a9cfcd2 --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-inspector.tsx @@ -0,0 +1,170 @@ +import { Eyebrow, PropertyRow } from "@agh/ui"; + +import type { LayoutSelection } from "../../hooks/use-layout-canvas-selection"; +import { overlappingGroupIds } from "../../lib/window-manager-layout-canvas"; +import { fractionLabel } from "../../lib/window-manager-layout-detents"; +import { layoutOrientationOf } from "../../lib/window-manager-layout-mutations"; +import { findLayoutNode, layoutNodeWindowIds } from "../../lib/window-manager-layout-tree"; +import { layoutWindowFace } from "../../lib/window-manager-layout-window-face"; +import type { + WindowManagerLayoutDesktop, + WindowManagerLayoutDocument, +} from "../../lib/window-manager-layout-types"; +import { LayoutInspectorNode } from "./layout-inspector-node"; +import { LayoutInspectorWindow } from "./layout-inspector-window"; + +interface LayoutInspectorProps { + document: WindowManagerLayoutDocument; + desktop: WindowManagerLayoutDesktop; + selection: LayoutSelection; + onDesktopChange: (next: WindowManagerLayoutDesktop) => void; +} + +/** What the selection on the canvas is, and the few things it can be told to do. */ +export function LayoutInspector({ + document, + desktop, + selection, + onDesktopChange, +}: LayoutInspectorProps) { + if (selection === null) { + return ( + +
    + Nothing selected +

    + Click a window to change what it holds or how it splits. Drag a divider to rebalance, or + a group edge to repartition the desktop. +

    +
    +
    + Desktop +
    + + {desktop.groups.length} + + + {desktop.groups.reduce( + (total, group) => total + layoutNodeWindowIds(group.root).length, + 0 + )} + + + {desktop.floating.length} + + + {desktop.purpose === "focus" ? "Focus" : "Standard"} + +
    +
    +
    + ); + } + + if (selection.kind === "group") { + const group = desktop.groups.find(candidate => candidate.id === selection.id); + if (!group) return null; + const overlaps = overlappingGroupIds(desktop).has(group.id); + return ( + +
    + Share of the desktop +
    + + {fractionLabel(group.frame.x)} + + + {fractionLabel(group.frame.y)} + + + {fractionLabel(group.frame.w)} + + + {fractionLabel(group.frame.h)} + +
    +
    + {overlaps ? ( +

    + This group overlaps another one. The daemon refuses a desktop whose groups cover each + other. +

    + ) : null} +
    + ); + } + + if (selection.kind === "window") { + const window = document.windows[selection.id]; + if (!window) return null; + const face = layoutWindowFace(window, selection.id); + return ( + +
    + Floating window +
    + {window.placement} + {window.minimized ? "Yes" : "No"} + + {`${fractionLabel(window.floatingRect.w)} × ${fractionLabel(window.floatingRect.h)}`} + +
    +
    +

    + Drag it on the canvas to reposition. Floating windows sit above every group on this + desktop. +

    +
    + ); + } + + const found = findLayoutNode(desktop, selection.id); + if (!found) return null; + const { node } = found; + const title = + node.kind === "split" + ? layoutOrientationOf(node.axis) === "rows" + ? "Rows" + : "Columns" + : node.kind === "stack" + ? "Stack" + : "Window"; + + return ( + + + + + ); +} + +function InspectorShell({ + title, + subtitle, + children, +}: { + title: string; + subtitle: string; + children: React.ReactNode; +}) { + return ( + + ); +} diff --git a/web/src/systems/settings/components/layouts/layout-node-diagrams.tsx b/web/src/systems/settings/components/layouts/layout-node-diagrams.tsx new file mode 100644 index 000000000..a8b0aa464 --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-node-diagrams.tsx @@ -0,0 +1,76 @@ +/** + * Rows, columns and a stack, drawn rather than named. The daemon's word for the + * first two is an axis whose meaning is the opposite of what it sounds like, so + * the picture is the label and `window-manager-layout-mutations.ts` owns the + * translation. + */ +const SHARED = { + "aria-hidden": true, + fill: "none", + viewBox: "0 0 26 17", +} as const; + +const PANE = { + fill: "currentColor", + fillOpacity: 0.22, + stroke: "currentColor", + strokeOpacity: 0.7, +} as const; + +export function LayoutRowsDiagram({ className }: { className?: string }) { + return ( + + + + + ); +} + +export function LayoutColumnsDiagram({ className }: { className?: string }) { + return ( + + + + + ); +} + +export function LayoutStackDiagram({ className }: { className?: string }) { + return ( + + + + + + ); +} diff --git a/web/src/systems/settings/components/layouts/layout-profile-card.tsx b/web/src/systems/settings/components/layouts/layout-profile-card.tsx new file mode 100644 index 000000000..1450b9296 --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-profile-card.tsx @@ -0,0 +1,140 @@ +import { Trash2 } from "lucide-react"; + +import { Button, Pill, cn } from "@agh/ui"; + +import { layoutThumbnail } from "../../lib/window-manager-layout-thumbnail"; +import type { WindowManagerLayoutResourceRecord } from "../../lib/window-manager-layout-types"; + +interface LayoutProfileCardProps { + record: WindowManagerLayoutResourceRecord; + selected: boolean; + onSelect: () => void; + onLoad: () => void; + onDelete: () => void; +} + +/** + * One saved layout. The thumbnail is the record's own geometry, so cards are + * told apart by shape rather than by reading four names in a row. + */ +export function LayoutProfileCard({ + record, + selected, + onSelect, + onLoad, + onDelete, +}: LayoutProfileCardProps) { + const slots = record.spec.participantSlots.length; + + return ( +
    + +
    + + + +
    +
    + ); +} + +function LayoutProfileThumbnail({ record }: { record: WindowManagerLayoutResourceRecord }) { + const thumbnail = layoutThumbnail(record.spec.document); + + if (thumbnail.tiles.length === 0) { + return ( + + Empty layout + + ); + } + + return ( + + ); +} diff --git a/web/src/systems/settings/components/layouts/layout-profile-editor.tsx b/web/src/systems/settings/components/layouts/layout-profile-editor.tsx new file mode 100644 index 000000000..90a88bf8c --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-profile-editor.tsx @@ -0,0 +1,208 @@ +import { Button, Field, FieldDescription, FieldLabel, Input, cn } from "@agh/ui"; + +import type { WindowManagerLayoutProfilesModel } from "../../hooks/use-window-manager-layout-profiles"; +import type { + WindowManagerLayoutAspect, + WindowManagerLayoutDocument, + WindowManagerLayoutOverflow, + WindowManagerLayoutScopeKind, +} from "../../lib/window-manager-layout-types"; + +interface LayoutProfileEditorProps { + editor: WindowManagerLayoutProfilesModel; + document: WindowManagerLayoutDocument; + onClose: () => void; +} + +const SCOPES: ReadonlyArray<{ value: WindowManagerLayoutScopeKind; label: string; hint: string }> = + [ + { + value: "workspace", + label: "This workspace", + hint: "Visible only inside this workspace.", + }, + { + value: "global", + label: "Every workspace", + hint: "Available in every workspace on this daemon.", + }, + ]; + +const ASPECTS: ReadonlyArray<{ value: WindowManagerLayoutAspect; label: string }> = [ + { value: "any", label: "Any" }, + { value: "landscape", label: "Landscape" }, + { value: "portrait", label: "Portrait" }, +]; + +const OVERFLOWS: ReadonlyArray<{ + value: WindowManagerLayoutOverflow; + label: string; + hint: string; +}> = [ + { + value: "stack", + label: "Fold into a stack", + hint: "Windows that no longer fit share one tile.", + }, + { + value: "reject", + label: "Refuse to restore", + hint: "The layout is not applied at all.", + }, +]; + +/** The five fields a `window_layout` resource actually stores, and nothing else. */ +export function LayoutProfileEditor({ editor, document, onClose }: LayoutProfileEditorProps) { + const slots = Object.keys(document.windows).length; + const forking = editor.selected !== null && editor.selected.id !== editor.id.trim(); + const scopeHint = SCOPES.find(scope => scope.value === editor.scope)?.hint; + + return ( +
    +
    + + editor.setDisplayName(event.target.value)} + /> + + + editor.setId(event.target.value)} + /> + + + + + + + + + + +
    +
    + + {slots} window{slots === 1 ? "" : "s"} captured from the layout in the editor. + + {editor.error ? ( + + {editor.error.message} + + ) : null} + + +
    +
    + ); +} + +function ProfileField({ + label, + hint, + htmlFor, + className, + children, +}: { + label: string; + hint?: string; + htmlFor?: string; + className?: string; + children: React.ReactNode; +}) { + return ( + + + {label} + + {children} + {hint ? {hint} : null} + + ); +} + +function Segmented({ + ariaLabel, + options, + value, + onChange, +}: { + ariaLabel: string; + options: ReadonlyArray<{ value: TValue; label: string }>; + value: TValue; + onChange: (next: TValue) => void; +}) { + return ( +
    + {options.map(option => ( + + ))} +
    + ); +} diff --git a/web/src/systems/settings/components/layouts/layout-profile-grid.tsx b/web/src/systems/settings/components/layouts/layout-profile-grid.tsx new file mode 100644 index 000000000..17cd458aa --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-profile-grid.tsx @@ -0,0 +1,103 @@ +import { Plus } from "lucide-react"; +import { useState } from "react"; + +import { ConfirmDialog } from "@agh/ui"; + +import type { WindowManagerLayoutProfilesModel } from "../../hooks/use-window-manager-layout-profiles"; +import { isSelectedLayoutProfile } from "../../lib/window-manager-layout-profile-key"; +import type { WindowManagerLayoutDocument } from "../../lib/window-manager-layout-types"; +import { LayoutProfileCard } from "./layout-profile-card"; +import { LayoutProfileEditor } from "./layout-profile-editor"; + +interface LayoutProfileGridProps { + editor: WindowManagerLayoutProfilesModel; + document: WindowManagerLayoutDocument; +} + +/** + * Saved layouts as cards, plus the one form that edits them. Both destructive + * paths — replacing unapplied edits, and deleting a record other people can see — + * ask first; the hook decides, this only renders the question. + */ +export function LayoutProfileGrid({ editor, document }: LayoutProfileGridProps) { + const [editing, setEditing] = useState(false); + + return ( +
    +
    + {editor.profiles.map(record => ( + { + editor.selectProfile(record); + editor.requestDelete(); + }} + onLoad={() => editor.requestLoad(record)} + onSelect={() => { + editor.selectProfile(record); + setEditing(true); + }} + /> + ))} + +
    + + {editing ? ( + setEditing(false)} + /> + ) : null} + + + Loading {editor.pendingLoad?.spec.displayName} replaces the layout edits you have + not applied yet. + + } + open={editor.pendingLoad !== null} + title="Replace unapplied layout edits?" + tone="warning" + onConfirm={editor.confirmLoad} + onOpenChange={open => { + if (!open) editor.cancelLoad(); + }} + /> + + + {editor.pendingDelete?.spec.displayName} is removed for everyone who can see it. + The layout in the editor is untouched. + + } + isPending={editor.remove.isPending} + open={editor.pendingDelete !== null} + title="Delete this saved layout?" + onConfirm={editor.confirmDelete} + onOpenChange={open => { + if (!open) editor.cancelDelete(); + }} + /> +
    + ); +} diff --git a/web/src/systems/settings/components/layouts/layout-review-bar.tsx b/web/src/systems/settings/components/layouts/layout-review-bar.tsx new file mode 100644 index 000000000..0ab4f0786 --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-review-bar.tsx @@ -0,0 +1,152 @@ +import { Button, Pill, Spinner } from "@agh/ui"; + +import type { WindowManagerLayoutEditorModel } from "../../hooks/use-window-manager-layout-editor"; + +interface LayoutReviewBarProps { + editor: WindowManagerLayoutEditorModel; +} + +type ReviewTone = "neutral" | "warning" | "success" | "danger"; + +/** + * The gate between an edit and the workspace. It is docked inside the stage + * rather than floating: the layout document and the global settings are two + * different saves, and two overlapping floating bars is how the old page read. + * + * Apply stays shut until the daemon has validated *this* draft — the review is + * keyed by a fingerprint of the document, so a single keystroke afterwards + * disarms it again. + */ +export function LayoutReviewBar({ editor }: LayoutReviewBarProps) { + const reviewing = editor.review.isFetching; + const applying = editor.apply.isPending; + const diagnostics = editor.validation?.valid === false ? editor.validation.diagnostics : []; + const status = describe(editor, { reviewing, applying, problems: diagnostics.length }); + const error = editor.importError ?? errorMessage(editor.mutationError); + + return ( +
    + {diagnostics.length > 0 ? ( +
    +

    The daemon refused this layout

    + {diagnostics.map(diagnostic => ( +

    + {diagnostic.code}{" "} + {diagnostic.path ? `${diagnostic.path} — ` : ""} + {diagnostic.message} +

    + ))} +
    + ) : null} + +
    + + {reviewing || applying ? ( + + ) : ( + + )} + {status.message} + + + {error ? ( + + {error} + + ) : null} + + + +
    +
    + ); +} + +function describe( + editor: WindowManagerLayoutEditorModel, + state: { reviewing: boolean; applying: boolean; problems: number } +): { message: string; tone: ReviewTone } { + if (state.applying) return { message: "Applying…", tone: "success" }; + if (state.reviewing) return { message: "Checking with the daemon…", tone: "warning" }; + if (!editor.dirty) { + return { message: `Revision ${editor.revision} · no unsaved layout edits`, tone: "neutral" }; + } + if (state.problems > 0) { + return { + message: `${state.problems} problem${state.problems === 1 ? "" : "s"} to fix before this can apply`, + tone: "danger", + }; + } + const preview = editor.reviewCurrent ? editor.reviewed?.preview : null; + if (preview) { + if (!preview.changed) { + return { + message: `Checked · this layout matches revision ${editor.revision}`, + tone: "success", + }; + } + return { message: `Checked · ${changeSummary(preview.changes)}`, tone: "success" }; + } + return { + message: "Unreviewed edits · the daemon checks them before they apply", + tone: "warning", + }; +} + +function changeSummary(changes: { + desktopIds: string[]; + groupIds: string[]; + nodeIds: string[]; + windowIds: string[]; +}): string { + const parts = [ + plural(changes.desktopIds.length, "desktop"), + plural(changes.groupIds.length, "group"), + plural(changes.nodeIds.length, "branch"), + plural(changes.windowIds.length, "window"), + ].filter((part): part is string => part !== null); + return parts.length === 0 ? "nothing changes" : `changes ${parts.join(", ")}`; +} + +function plural(count: number, noun: string): string | null { + if (count === 0) return null; + return `${count} ${noun}${count === 1 ? "" : "s"}`; +} + +function errorMessage(error: unknown): string | null { + return error instanceof Error ? error.message : null; +} diff --git a/web/src/systems/settings/components/layouts/layout-stage.tsx b/web/src/systems/settings/components/layouts/layout-stage.tsx new file mode 100644 index 000000000..b3abeeff2 --- /dev/null +++ b/web/src/systems/settings/components/layouts/layout-stage.tsx @@ -0,0 +1,96 @@ +import { useState } from "react"; + +import type { WindowManagerConfig } from "@/systems/os"; + +import { useLayoutCanvasSelection } from "../../hooks/use-layout-canvas-selection"; +import type { WindowManagerLayoutEditorModel } from "../../hooks/use-window-manager-layout-editor"; +import { layoutCanvasProjection } from "../../lib/window-manager-layout-canvas"; +import { LayoutCanvas } from "./layout-canvas"; +import { LayoutCanvasBoardBar } from "./layout-canvas-board-bar"; +import { LayoutDesktopTabs } from "./layout-desktop-tabs"; +import { LayoutInspector } from "./layout-inspector"; +import { LayoutReviewBar } from "./layout-review-bar"; + +interface LayoutStageProps { + editor: WindowManagerLayoutEditorModel; + config: WindowManagerConfig; +} + +/** + * The workspace layout as one object: the desktop you can grab, what the + * selection is, and the daemon's check — all inside a single card, so the review + * gate belongs visibly to the thing being reviewed. + */ +export function LayoutStage({ editor, config }: LayoutStageProps) { + const [activeIndex, setActiveIndex] = useState(0); + const document = editor.draft; + const index = Math.min(activeIndex, Math.max(0, document.desktops.length - 1)); + const desktop = document.desktops[index]; + const selection = useLayoutCanvasSelection( + desktop ?? { + id: "", + name: "", + order: 0, + purpose: "standard", + focusOwner: null, + groups: [], + floating: [], + } + ); + + if (!desktop) { + return ( +
    + This workspace has no desktops yet. Open a window to create the first one. +
    + ); + } + + const projection = layoutCanvasProjection(document, desktop, config, editor.revision); + + return ( +
    + { + setActiveIndex(position); + selection.clear(); + }} + /> + +
    +
    + editor.setDesktop(index, next)} + onFloatingRectChange={editor.setFloatingRect} + onSelect={selection.select} + /> + +
    +
    + editor.setDesktop(index, next)} + /> +
    +
    + + +
    + ); +} diff --git a/web/src/systems/settings/components/layouts/window-manager-behavior-diagrams.tsx b/web/src/systems/settings/components/layouts/window-manager-behavior-diagrams.tsx new file mode 100644 index 000000000..2b964a073 --- /dev/null +++ b/web/src/systems/settings/components/layouts/window-manager-behavior-diagrams.tsx @@ -0,0 +1,204 @@ +import type { ReactNode } from "react"; + +/** + * The behaviour options, drawn. Each picture keeps the accent for one thing — + * "the window this is about" — so selecting an option never repaints the + * drawing: the colour is information, and it means the same in every state. + */ +function Diagram({ children }: { children: ReactNode }) { + return ( + + ); +} + +function Pane({ + x, + y, + width, + height, + opacity = 0.16, +}: { + x: number; + y: number; + width: number; + height: number; + opacity?: number; +}) { + return ( + + ); +} + +function Subject({ x, y, width, height }: { x: number; y: number; width: number; height: number }) { + return ( + + ); +} + +export function DiagramFloatOnTop() { + return ( + + + + + + ); +} + +export function DiagramSplitBesideFocus() { + return ( + + + + + ); +} + +export function DiagramFoldIntoStack() { + return ( + + + + + + ); +} + +export function DiagramRefuse() { + return ( + + + + + ); +} + +export function DiagramClickAndKeys() { + return ( + + + + + + ); +} + +export function DiagramKeysOnly() { + return ( + + + + + + ); +} + +export function DiagramDragWindow() { + return ( + + + + + + ); +} + +export function DiagramDragGroup() { + return ( + + + + + + ); +} + +export function DiagramSlide() { + return ( + + + + + + ); +} + +export function DiagramCrossfade() { + return ( + + + + + ); +} + +export function DiagramInstant() { + return ( + + + + + + ); +} diff --git a/web/src/systems/settings/components/layouts/window-manager-behavior-picks.tsx b/web/src/systems/settings/components/layouts/window-manager-behavior-picks.tsx new file mode 100644 index 000000000..2eb720936 --- /dev/null +++ b/web/src/systems/settings/components/layouts/window-manager-behavior-picks.tsx @@ -0,0 +1,278 @@ +import type { ComponentType, Dispatch, SetStateAction } from "react"; + +import { Switch, cn } from "@agh/ui"; + +import type { WindowManagerConfig, WindowManagerDragModifier } from "@/systems/os"; + +import { SettingRow } from "../setting-row"; +import { + DiagramClickAndKeys, + DiagramCrossfade, + DiagramDragGroup, + DiagramDragWindow, + DiagramFloatOnTop, + DiagramFoldIntoStack, + DiagramInstant, + DiagramKeysOnly, + DiagramRefuse, + DiagramSlide, + DiagramSplitBesideFocus, +} from "./window-manager-behavior-diagrams"; + +type ConfigDraft = Dispatch>; + +interface PickOption { + value: TValue; + label: string; + diagram: ComponentType; +} + +interface PickRow { + key: TKey; + label: string; + description: string; + options: ReadonlyArray>>; +} + +const NEW_WINDOW: PickRow<"newWindowPolicy"> = { + key: "newWindowPolicy", + label: "New windows", + description: "Where a window lands when it opens without a home.", + options: [ + { value: "floating", label: "Float on top", diagram: DiagramFloatOnTop }, + { value: "beside_focus", label: "Split beside focus", diagram: DiagramSplitBesideFocus }, + ], +}; + +const SMALL_VIEWPORT: PickRow<"smallViewportPolicy"> = { + key: "smallViewportPolicy", + label: "Not enough room", + description: "When the screen can no longer hold every tile side by side.", + options: [ + { value: "stack", label: "Fold into a stack", diagram: DiagramFoldIntoStack }, + { value: "reject", label: "Refuse the layout", diagram: DiagramRefuse }, + ], +}; + +const FOCUS: PickRow<"focusPolicy"> = { + key: "focusPolicy", + label: "Taking focus", + description: "Whether a click can move focus, or only the keyboard.", + options: [ + { value: "click_directional", label: "Click and keys", diagram: DiagramClickAndKeys }, + { value: "directional", label: "Keys only", diagram: DiagramKeysOnly }, + ], +}; + +const DRAG_AWAY: PickRow<"dragAwayPolicy"> = { + key: "dragAwayPolicy", + label: "Dragging a tiled window", + description: "What comes along when you pull one out of its group.", + options: [ + { value: "window", label: "Just that window", diagram: DiagramDragWindow }, + { value: "group", label: "Its whole group", diagram: DiagramDragGroup }, + ], +}; + +const TRANSITION: PickRow<"desktopTransition"> = { + key: "desktopTransition", + label: "Switching desktops", + description: "How this browser moves between desktops.", + options: [ + { value: "slide", label: "Slide", diagram: DiagramSlide }, + { value: "crossfade", label: "Crossfade", diagram: DiagramCrossfade }, + { value: "instant", label: "Instant", diagram: DiagramInstant }, + ], +}; + +const MODIFIER_KEYS: ReadonlyArray<{ + value: WindowManagerDragModifier; + symbol: string; + name: string; +}> = [ + { value: "alt", symbol: "⌥", name: "Option" }, + { value: "control", symbol: "⌃", name: "Control" }, + { value: "meta", symbol: "⌘", name: "Command" }, + { value: "shift", symbol: "⇧", name: "Shift" }, + { value: "none", symbol: "None", name: "None" }, +]; + +const TOGGLES = [ + { + key: "focusWrap", + label: "Wrap directional focus", + description: "At the last window in a direction, continue from the opposite edge.", + }, + { + key: "focusFollowsPointer", + label: "Focus follows the pointer", + description: "A window takes focus as soon as the pointer enters it.", + }, + { + key: "raiseOnFocus", + label: "Raise on focus", + description: "Bring a focused floating window above its peers.", + }, +] as const; + +/** + * Seven enums that used to be seven selects. Each option is the arrangement it + * produces, so the choice is read rather than decoded — and the two drag + * modifiers are the keys themselves. + */ +export function WindowManagerBehaviorPicks({ + draft, + setDraft, +}: { + draft: WindowManagerConfig; + setDraft: ConfigDraft; +}) { + return ( + <> + + + + + + + setDraft(current => ({ ...current, groupMoveModifier }))} + /> + setDraft(current => ({ ...current, swapModifier }))} + /> + + {TOGGLES.map(toggle => ( + + setDraft(current => ({ ...current, [toggle.key]: checked })) + } + /> + } + data-testid={`window-manager-${toggle.key}`} + description={toggle.description} + key={toggle.key} + label={toggle.label} + /> + ))} + + ); +} + +function DiagramPickRow({ + row, + draft, + setDraft, +}: { + row: PickRow; + draft: WindowManagerConfig; + setDraft: ConfigDraft; +}) { + const current = draft[row.key]; + + return ( +
    +
    +

    {row.label}

    +

    + {row.description} +

    +
    +
    + {row.options.map(option => { + const Diagram = option.diagram; + const selected = current === option.value; + return ( + + ); + })} +
    +
    + ); +} + +function ModifierRow({ + label, + description, + value, + onChange, +}: { + label: string; + description: string; + value: WindowManagerDragModifier; + onChange: (next: WindowManagerDragModifier) => void; +}) { + return ( + + {MODIFIER_KEYS.map(key => ( + + ))} + + } + description={description} + label={label} + /> + ); +} diff --git a/web/src/systems/settings/components/layouts/window-manager-gap-editor.tsx b/web/src/systems/settings/components/layouts/window-manager-gap-editor.tsx new file mode 100644 index 000000000..5f73bfead --- /dev/null +++ b/web/src/systems/settings/components/layouts/window-manager-gap-editor.tsx @@ -0,0 +1,176 @@ +import type { Dispatch, SetStateAction } from "react"; + +import { cn } from "@agh/ui"; + +import type { WindowManagerConfig } from "@/systems/os"; + +import { dragValueAria, useDragValue } from "../../hooks/use-drag-value"; +import { WINDOW_MANAGER_RANGES } from "../../lib/window-manager-snap-geometry"; + +type GapKey = keyof WindowManagerConfig["gaps"]; + +const OUTER: ReadonlyArray<{ key: Exclude; label: string; axis: "x" | "y" }> = [ + { key: "top", label: "Top gap", axis: "y" }, + { key: "right", label: "Right gap", axis: "x" }, + { key: "bottom", label: "Bottom gap", axis: "y" }, + { key: "left", label: "Left gap", axis: "x" }, +]; + +/** + * The box model at true scale: one pixel of travel is one pixel of gap, so the + * value never has to be typed and never has to be converted in someone's head. + * The inner guide moves at half speed because a seam widens from its centre. + */ +export function WindowManagerGapEditor({ + draft, + setDraft, +}: { + draft: WindowManagerConfig; + setDraft: Dispatch>; +}) { + const gaps = draft.gaps; + const setGap = (key: GapKey) => (value: number) => + setDraft(current => ({ ...current, gaps: { ...current.gaps, [key]: value } })); + + return ( +
    +
    +
    + {[0, 1, 2, 3].map(index => ( +
    + ))} +
    + + {OUTER.map(edge => ( + + ))} + + 2} + style={{ + left: "calc(50% - 5px)", + top: `${gaps.top + 16}px`, + bottom: `${gaps.bottom + 16}px`, + }} + value={gaps.inner} + onChange={setGap("inner")} + /> + 2} + style={{ + top: "calc(50% - 5px)", + left: `${gaps.left + 16}px`, + right: `${gaps.right + 16}px`, + }} + value={gaps.inner} + onChange={setGap("inner")} + /> +
    + +
    + + + + + + + + Shown at actual size + +
    +
    + ); +} + +function GapGuide({ + axis, + label, + value, + style, + scale, + invert, + onChange, +}: { + axis: "x" | "y"; + label: string; + value: number; + style: React.CSSProperties; + scale?: () => number; + invert?: boolean; + onChange: (next: number) => void; +}) { + const range = WINDOW_MANAGER_RANGES.gap; + const drag = useDragValue({ + axis, + invert, + max: range.max, + min: range.min, + scale, + value, + onChange, + }); + + return ( +
    +
    + ); +} + +function Readout({ label, value }: { label: string; value: number }) { + return ( + + {label} + {value}px + + ); +} diff --git a/web/src/systems/settings/components/layouts/window-manager-ratio-track.tsx b/web/src/systems/settings/components/layouts/window-manager-ratio-track.tsx new file mode 100644 index 000000000..567eeedcf --- /dev/null +++ b/web/src/systems/settings/components/layouts/window-manager-ratio-track.tsx @@ -0,0 +1,164 @@ +import type { Dispatch, SetStateAction } from "react"; + +import { cn } from "@agh/ui"; + +import type { WindowManagerConfig } from "@/systems/os"; + +import { usePointerDrag } from "../../hooks/use-pointer-drag"; +import { useWindowManagerRatioTrack } from "../../hooks/use-window-manager-ratio-track"; +import { fractionLabel, nearestDetent } from "../../lib/window-manager-layout-detents"; +import { WINDOW_MANAGER_RANGES } from "../../lib/window-manager-snap-geometry"; + +const EDGE_PAD = 10; +const KEYBOARD_STEP = 0.01; + +function clamp(value: number): number { + const { min, max } = WINDOW_MANAGER_RANGES.repeatRatio; + return Math.min(Math.max(value, min), max); +} + +function round(value: number): number { + return Math.round(value * 1_000_000) / 1_000_000; +} + +/** + * Repeat widths as stops along the axis they describe. Snapping to the same edge + * again cycles through them, so the set is ordered and comparable at a glance — + * which a comma-separated string of decimals never was. + */ +export function WindowManagerRatioTrack({ + draft, + setDraft, +}: { + draft: WindowManagerConfig; + setDraft: Dispatch>; +}) { + const model = useWindowManagerRatioTrack(draft, setDraft); + + return ( +
    +
    +
    + +
    + + Cycle + + {[...model.ratios] + .sort((a, b) => b - a) + .map(ratio => fractionLabel(ratio)) + .join(" → ")} + + + {model.ratios.length >= model.limits.max ? ( + {model.limits.max} stops is the maximum + ) : null} +
    +
    + ); +} + +function RatioStop({ + ratio, + index, + selected, + removable, + positionFromClientX, + onChange, + onRemove, + onSelect, +}: { + ratio: number; + index: number; + selected: boolean; + removable: boolean; + positionFromClientX: (clientX: number) => number | null; + onChange: (next: number) => void; + onRemove: () => void; + onSelect: () => void; +}) { + const drag = usePointerDrag({ + onStart: () => { + onSelect(); + return null; + }, + onMove: event => { + const position = positionFromClientX(event.clientX); + if (position === null) return; + onChange(round(nearestDetent(position, 0.015) ?? position)); + }, + }); + + return ( + + ); +} diff --git a/web/src/systems/settings/components/layouts/window-manager-shortcut-row.tsx b/web/src/systems/settings/components/layouts/window-manager-shortcut-row.tsx new file mode 100644 index 000000000..e6681703f --- /dev/null +++ b/web/src/systems/settings/components/layouts/window-manager-shortcut-row.tsx @@ -0,0 +1,121 @@ +import { RotateCcw } from "lucide-react"; + +import { Button, Kbd, KbdGroup, cn } from "@agh/ui"; + +import type { ResolvedWindowManagerAction, WindowPlacementId } from "@/systems/os"; + +import { WindowTilingDiagram } from "./window-manager-tiling-diagrams"; + +interface WindowManagerShortcutRowProps { + action: ResolvedWindowManagerAction; + overridden: boolean; + recording: boolean; + blocked: boolean; + shadowed: boolean; + onRecord: () => void; + onReset: () => void; +} + +const KEY_SYMBOL: Record = { + meta: "⌘", + control: "⌃", + alt: "⌥", + shift: "⇧", + ArrowLeft: "←", + ArrowRight: "→", + ArrowUp: "↑", + ArrowDown: "↓", + BracketLeft: "[", + BracketRight: "]", + Space: "␣", + Enter: "⏎", + Escape: "⎋", + Backspace: "⌫", + Delete: "⌦", + Tab: "⇥", +}; + +function placementOf(actionId: string): WindowPlacementId | null { + const suffix = actionId.startsWith("window.tile.") ? actionId.slice("window.tile.".length) : null; + return suffix as WindowPlacementId | null; +} + +function chordKeys(chord: string): string[] { + return chord.split("+").map(token => { + if (KEY_SYMBOL[token]) return KEY_SYMBOL[token]; + if (/^Key[A-Z]$/.test(token)) return token.slice(3); + if (/^Digit\d$/.test(token)) return token.slice(5); + return token; + }); +} + +/** One action, the shape it produces, and the keys that trigger it. */ +export function WindowManagerShortcutRow({ + action, + overridden, + recording, + blocked, + shadowed, + onRecord, + onReset, +}: WindowManagerShortcutRowProps) { + const placement = placementOf(action.id); + const chord = action.chord?.canonical ?? null; + + return ( +
    + + {placement ? : null} + + {action.label} + + + {action.id} + + + +
    + ); +} diff --git a/web/src/systems/settings/components/layouts/window-manager-shortcut-table.tsx b/web/src/systems/settings/components/layouts/window-manager-shortcut-table.tsx new file mode 100644 index 000000000..30df216b4 --- /dev/null +++ b/web/src/systems/settings/components/layouts/window-manager-shortcut-table.tsx @@ -0,0 +1,147 @@ +import { ChevronRight } from "lucide-react"; +import { useState } from "react"; + +import { cn } from "@agh/ui"; + +import { + resolveWindowManagerActions, + type ResolvedWindowManagerAction, + type WindowManagerActionId, +} from "@/systems/os"; + +import type { ShortcutRecorderModel } from "../../hooks/use-window-manager-shortcut-recorder"; +import { WindowManagerShortcutRow } from "./window-manager-shortcut-row"; + +const GROUPS: ReadonlyArray<{ title: string; ids: readonly WindowManagerActionId[] }> = [ + { + title: "Window", + ids: ["window.close", "window.minimize", "window.zoom", "window.toggle_floating"], + }, + { + title: "Tiling", + ids: [ + "window.tile.left", + "window.tile.right", + "window.tile.top", + "window.tile.bottom", + "window.tile.top-left", + "window.tile.top-right", + "window.tile.bottom-left", + "window.tile.bottom-right", + ], + }, + { + title: "Focus", + ids: ["window.focus.left", "window.focus.right", "window.focus.up", "window.focus.down"], + }, + { + title: "Desktops", + ids: ["desktop.switch.previous", "desktop.switch.next", "desktop.overview"], + }, + { + title: "Layout", + ids: [ + "layout.arrange.two-up", + "layout.arrange.grid", + "layout.balance", + "layout.undo", + "layout.redo", + ], + }, +]; + +/** + * Every action the daemon accepts a chord for, grouped by what it does. Only the + * ones changed here are stored, so the table shows the shipped default and a way + * back to it rather than a JSON object holding all twenty-four. + */ +export function WindowManagerShortcutTable({ + overrides, + recorder, +}: { + overrides: Readonly>; + recorder: ShortcutRecorderModel; +}) { + const [open, setOpen] = useState>(new Set(["Window", "Tiling"])); + const actions = new Map( + resolveWindowManagerActions(overrides).map(action => [action.id, action]) + ); + + return ( +
    + + {recorder.announcement} + + {GROUPS.map(group => { + const expanded = open.has(group.title); + const changed = group.ids.filter(id => overrides[id] != null).length; + const groupBlocked = group.ids.filter(id => recorder.blocked.has(id)); + const groupShadowed = group.ids.filter(id => recorder.shadowed.has(id)); + return ( +
    + + {expanded ? ( +
    + {group.ids.map(id => { + const action = actions.get(id); + if (!action) return null; + return ( + recorder.start(id)} + onReset={() => recorder.reset(id)} + /> + ); + })} + {groupBlocked.length > 0 ? ( +

    + {groupBlocked.length} shortcut{groupBlocked.length === 1 ? "" : "s"} here share + a chord with another one you changed. The daemon refuses a duplicate, so this + cannot be saved until one of them moves. +

    + ) : null} + {groupShadowed.length > 0 && groupBlocked.length === 0 ? ( +

    + {groupShadowed.length} shortcut{groupShadowed.length === 1 ? "" : "s"} here land + on a chord another action ships with. Both are stored; the first one in this + list wins. +

    + ) : null} +
    + ) : null} +
    + ); + })} +
    + ); +} diff --git a/web/src/systems/settings/components/layouts/window-manager-snap-map.tsx b/web/src/systems/settings/components/layouts/window-manager-snap-map.tsx new file mode 100644 index 000000000..e1f09f9b0 --- /dev/null +++ b/web/src/systems/settings/components/layouts/window-manager-snap-map.tsx @@ -0,0 +1,249 @@ +import { useRef, type Dispatch, type SetStateAction } from "react"; + +import { Popover, PopoverContent, PopoverTrigger, cn } from "@agh/ui"; + +import type { WindowManagerConfig } from "@/systems/os"; + +import { dragValueAria, useDragValue } from "../../hooks/use-drag-value"; +import { + WINDOW_MANAGER_RANGES, + snapMapPercent, + snapMapScale, +} from "../../lib/window-manager-snap-geometry"; + +type BindingKey = keyof WindowManagerConfig["bindings"]; +type BindingValue = WindowManagerConfig["bindings"][BindingKey]; + +const BINDING_OPTIONS: ReadonlyArray<{ value: BindingValue; label: string; hint: string }> = [ + { value: "none", label: "Free", hint: "The centre snaps like any other edge." }, + { value: "reserved", label: "Reserved", hint: "Kept clear — nothing claims this centre." }, + { value: "zoom", label: "Zoom", hint: "Dropping here zooms the window to the desktop." }, +]; + +/** + * Where a dragged window is caught, drawn where it is caught. Each control sits + * inside the region it governs, so nothing here needs a coordinate field: the + * band is the band. + */ +export function WindowManagerSnapMap({ + draft, + setDraft, +}: { + draft: WindowManagerConfig; + setDraft: Dispatch>; +}) { + const mapRef = useRef(null); + const snap = draft.snap; + const scale = () => { + const width = mapRef.current?.getBoundingClientRect().width ?? 0; + return 1 / snapMapScale(width); + }; + const setSnap = (key: "edgeBand" | "cornerReach" | "exitSlack") => (value: number) => + setDraft(current => ({ ...current, snap: { ...current.snap, [key]: value } })); + const setBinding = (key: BindingKey) => (value: BindingValue) => + setDraft(current => ({ ...current, bindings: { ...current.bindings, [key]: value } })); + + const band = snapMapPercent(snap.edgeBand, "x"); + const bandY = snapMapPercent(snap.edgeBand, "y"); + const corner = snapMapPercent(snap.cornerReach, "x"); + const cornerY = snapMapPercent(snap.cornerReach, "y"); + const inset = snapMapPercent(snap.edgeBand + snap.exitSlack, "x"); + const insetY = snapMapPercent(snap.edgeBand + snap.exitSlack, "y"); + + return ( +
    +
    + + + + + {(["left", "right"] as const).map(x => + (["top", "bottom"] as const).map(y => ( + + )) + )} + + + + + + + + +
    + +
    + + + +
    +
    + ); +} + +function SnapGrip({ + axis, + label, + value, + range, + scale, + style, + onChange, +}: { + axis: "x" | "y"; + label: string; + value: number; + range: { min: number; max: number }; + scale: () => number; + style: React.CSSProperties; + onChange: (next: number) => void; +}) { + const drag = useDragValue({ axis, max: range.max, min: range.min, scale, value, onChange }); + + return ( +
    +
    + ); +} + +function CentreZone({ + label, + side, + value, + onChange, +}: { + label: string; + side: "top" | "bottom"; + value: BindingValue; + onChange: (next: BindingValue) => void; +}) { + const current = BINDING_OPTIONS.find(option => option.value === value) ?? BINDING_OPTIONS[0]; + + return ( + + } + style={{ [side]: "6px" }} + > + {current?.label} + + + {BINDING_OPTIONS.map(option => ( + + ))} + + + ); +} + +function Readout({ label, value }: { label: string; value: number }) { + return ( + + {label} + {value}px + + ); +} diff --git a/web/src/systems/settings/components/layouts/window-manager-tiling-diagrams.tsx b/web/src/systems/settings/components/layouts/window-manager-tiling-diagrams.tsx new file mode 100644 index 000000000..467eecd52 --- /dev/null +++ b/web/src/systems/settings/components/layouts/window-manager-tiling-diagrams.tsx @@ -0,0 +1,32 @@ +import type { WindowPlacementId } from "@/systems/os"; + +const PLACEMENT: Record = { + left: [0, 0, 11, 16], + right: [11, 0, 11, 16], + top: [0, 0, 22, 8], + bottom: [0, 8, 22, 8], + "top-left": [0, 0, 11, 8], + "top-right": [11, 0, 11, 8], + "bottom-left": [0, 8, 11, 8], + "bottom-right": [11, 8, 11, 8], +}; + +/** Which half or quarter of the screen a tiling shortcut claims. */ +export function WindowTilingDiagram({ placement }: { placement: WindowPlacementId }) { + const [x, y, width, height] = PLACEMENT[placement]; + + return ( + + ); +} diff --git a/web/src/systems/settings/components/role-advanced-details.tsx b/web/src/systems/settings/components/role-advanced-details.tsx index 02b725a20..8a6faefd5 100644 --- a/web/src/systems/settings/components/role-advanced-details.tsx +++ b/web/src/systems/settings/components/role-advanced-details.tsx @@ -1,67 +1,112 @@ -import type { RoleFallbackEntry, RoleName } from "../types"; +import type { RolesRuntimeOptions } from "../hooks/use-roles-runtime-options"; +import type { RoleRuntimeValue } from "../lib/roles-config"; +import { roleFieldId } from "../lib/roles-validation"; +import type { RoleViewModel } from "../lib/roles-view-model"; +import type { RoleName } from "../types"; import { RoleFallbackEditor } from "./role-fallback-editor"; +import { RoleFieldControl } from "./role-field-control"; import { SettingsAdvancedFold, SettingsProvChip } from "./settings-advanced-fold"; -interface RoleAdvancedDetailsProps { - role: RoleName; - entries: readonly RoleFallbackEntry[]; - provenance: Record; +export interface RoleAdvancedDetailsProps { + vm: RoleViewModel; + options: RolesRuntimeOptions; errors: Record; open: boolean; onOpenChange: (open: boolean) => void; disabled?: boolean; + draftRevision?: number; testId: string; + setRoleField: (role: RoleName, field: string, value: string | number | boolean) => void; + setNumberFieldValidity: (id: string) => (message: string | null) => void; onAdd: () => void; onRemove: (index: number) => void; - onUpdate: (index: number, field: keyof RoleFallbackEntry, value: string) => void; + onUpdate: (index: number, value: RoleRuntimeValue) => void; registerFieldRef: (id: string) => (element: HTMLElement | null) => void; } /** - * Advanced fold hosting the editable fallback chain and the returned config - * provenance chips. The fold is controlled so it opens automatically when its - * role has a fallback validation error. + * The operator layer for one role: tuning knobs, the ordered fallback chain, + * and the config provenance the daemon returned. Rendered bare so it does not + * frame itself inside the role panel that already frames the row. */ export function RoleAdvancedDetails({ - role, - entries, - provenance, + vm, + options, errors, open, onOpenChange, disabled, + draftRevision, testId, + setRoleField, + setNumberFieldValidity, onAdd, onRemove, onUpdate, registerFieldRef, }: RoleAdvancedDetailsProps) { - const provenanceKeys = Object.keys(provenance); + const { role, advancedFields, values, status } = vm; + const provenanceKeys = Object.keys(status.provenance); + return ( - - - {provenanceKeys.length > 0 ? ( -
    - Config provenance -
    - {provenanceKeys.map(key => ( - - {key} · {provenance[key]} - - ))} + +
    + {advancedFields.length > 0 ? ( +
    + {advancedFields.map(field => { + const id = roleFieldId(role, field.key); + return ( + setRoleField(role, field.key, value)} + onValidityChange={ + field.kind === "number" ? setNumberFieldValidity(id) : undefined + } + /> + ); + })} +
    + ) : null} + + {provenanceKeys.length > 0 ? ( +
    + Config provenance +
    + {provenanceKeys.map(key => ( + + {key} · {status.provenance[key]} + + ))} +
    -
    - ) : null} + ) : null} +
    ); } diff --git a/web/src/systems/settings/components/role-effective-hint.tsx b/web/src/systems/settings/components/role-effective-hint.tsx new file mode 100644 index 000000000..34d9b85fe --- /dev/null +++ b/web/src/systems/settings/components/role-effective-hint.tsx @@ -0,0 +1,20 @@ +export interface RoleEffectiveHintProps { + /** Projected value; `null` means the runtime resolves it only at invocation. */ + effective: string | null; + emptyLabel: string; +} + +/** + * Truthful effective-value hint. A `null` projection is stated as unresolved + * rather than filled with a plausible default. + */ +export function RoleEffectiveHint({ effective, emptyLabel }: RoleEffectiveHintProps) { + if (effective == null || effective.trim() === "") { + return {emptyLabel}; + } + return ( + + Effective {effective} + + ); +} diff --git a/web/src/systems/settings/components/role-fallback-editor.tsx b/web/src/systems/settings/components/role-fallback-editor.tsx index c789809cc..5696372d5 100644 --- a/web/src/systems/settings/components/role-fallback-editor.tsx +++ b/web/src/systems/settings/components/role-fallback-editor.tsx @@ -2,81 +2,38 @@ import type { ComponentPropsWithoutRef } from "react"; import { Plus, Trash2 } from "lucide-react"; -import { Button, cn, Input, NativeSelect, NativeSelectOption } from "@agh/ui"; +import { Button, cn } from "@agh/ui"; import { useLocalRowKeys } from "@/hooks/use-local-row-keys"; -import { REASONING_OPTIONS } from "../lib/roles-config"; +import type { RolesRuntimeOptions } from "../hooks/use-roles-runtime-options"; +import type { RoleRuntimeValue } from "../lib/roles-config"; import { fallbackFieldId } from "../lib/roles-validation"; import type { RoleFallbackEntry, RoleName } from "../types"; +import { RoleRuntimeSelector } from "./role-runtime-selector"; interface RoleFallbackEditorProps extends Omit, "role"> { role: RoleName; entries: readonly RoleFallbackEntry[]; + options: RolesRuntimeOptions; errors: Record; disabled?: boolean; testId: string; onAdd: () => void; onRemove: (index: number) => void; - onUpdate: (index: number, field: keyof RoleFallbackEntry, value: string) => void; + onUpdate: (index: number, value: RoleRuntimeValue) => void; registerFieldRef: (id: string) => (element: HTMLElement | null) => void; } -interface FallbackTextFieldProps extends Omit, "id" | "onChange"> { - id: string; - label: string; - value: string; - placeholder: string; - error?: string; - onChange: (value: string) => void; - registerRef: (element: HTMLElement | null) => void; -} - -function FallbackTextField({ - id, - label, - value, - placeholder, - error, - onChange, - registerRef, - className, - ...rootProps -}: FallbackTextFieldProps) { - const errorId = error ? `${id}-error` : undefined; - return ( -
    - - onChange(event.target.value)} - /> - {error ? ( - - {error} - - ) : null} -
    - ); -} - /** - * Accessible fallback-chain array editor for one role. Add/remove routes and - * edit provider, model, and reasoning effort per entry. Edits flow into the - * draft `roles..fallback_chain` and submit with the full section. + * Ordered fallback routes for one role. Each route is a single runtime + * decision, so it is edited through one runtime selector rather than a row of + * free-text fields. */ export function RoleFallbackEditor({ role, entries, + options, errors, disabled, testId, @@ -127,87 +84,51 @@ export function RoleFallbackEditor({ No fallback routes configured.

    ) : ( -
      +
        {entries.map((entry, index) => { - const providerId = fallbackFieldId(role, index, "provider"); - const modelId = fallbackFieldId(role, index, "model"); - const reasoningId = fallbackFieldId(role, index, "reasoning_effort"); - const reasoningError = errors[reasoningId]; - const reasoningErrorId = reasoningError ? `${reasoningId}-error` : undefined; + const id = fallbackFieldId(role, index); + const error = errors[id]; return (
      • -
        - Fallback route {index + 1} - onUpdate(index, "provider", value)} - registerRef={registerFieldRef(providerId)} - /> - onUpdate(index, "model", value)} - registerRef={registerFieldRef(modelId)} - /> -
        - - onUpdate(index, "reasoning_effort", event.target.value)} - > - {REASONING_OPTIONS.map(option => ( - - {option.label} - - ))} - - {reasoningError ? ( - - {reasoningError} - - ) : null} -
        -
        - - +
        + + {/* Register the selector's own trigger so a blocked save focuses + the control the operator has to fix, not a wrapper. */} +
        registerFieldRef(id)(node?.querySelector("button") ?? null)} + className="min-w-0 flex-1" + > + onUpdate(index, value)} + />
        -
        + +
    + {error ? ( + + {error} + + ) : null} ); })} diff --git a/web/src/systems/settings/components/role-field-control.tsx b/web/src/systems/settings/components/role-field-control.tsx index cf63383c1..e90a5cf1d 100644 --- a/web/src/systems/settings/components/role-field-control.tsx +++ b/web/src/systems/settings/components/role-field-control.tsx @@ -1,8 +1,9 @@ import type { ReactNode } from "react"; -import { cn, Input, NativeSelect, NativeSelectOption, Switch } from "@agh/ui"; +import { cn, Input, Switch } from "@agh/ui"; -import { REASONING_OPTIONS, type RoleFieldDescriptor } from "../lib/roles-config"; +import type { RoleFieldDescriptor } from "../lib/roles-config"; +import { RoleEffectiveHint } from "./role-effective-hint"; import { SettingsFieldRow } from "./settings-field-row"; import { SettingsNumberInput } from "./settings-number-input"; @@ -22,18 +23,6 @@ interface RoleFieldControlProps { onValidityChange?: (message: string | null) => void; } -/** Truthful effective-value hint for a routing field — null renders as unresolved. */ -function EffectiveHint({ effective }: { effective: string | null }) { - if (effective == null) { - return Resolves at invocation.; - } - return ( - - Effective {effective} - - ); -} - function renderControl({ field, value, @@ -69,22 +58,6 @@ function renderControl({ onValidityChange={onValidityChange} /> ); - case "select": - return ( - onValueChange(event.target.value)} - > - {REASONING_OPTIONS.map(option => ( - - {option.label} - - ))} - - ); default: return ( {field.description ? {field.description} : null} - {hasEffective ? : null} + {hasEffective ? ( + + ) : null} ); return ( diff --git a/web/src/systems/settings/components/role-list.tsx b/web/src/systems/settings/components/role-list.tsx new file mode 100644 index 000000000..2cc2ca59a --- /dev/null +++ b/web/src/systems/settings/components/role-list.tsx @@ -0,0 +1,70 @@ +import { Button } from "@agh/ui"; + +import type { RolesDisclosure } from "../hooks/use-roles-disclosure"; +import type { RolesRuntimeOptions } from "../hooks/use-roles-runtime-options"; +import type { RoleRuntimeValue } from "../lib/roles-config"; +import type { RoleViewModel } from "../lib/roles-view-model"; +import type { RoleName } from "../types"; +import { RolePanel } from "./role-panel"; + +const TEST_PREFIX = "settings-page-roles"; + +export interface RoleListProps { + roles: readonly RoleViewModel[]; + options: RolesRuntimeOptions; + disclosure: RolesDisclosure; + validationErrors: Record; + disabled?: boolean; + draftRevision?: number; + setRoleEnabled: (role: RoleName, enabled: boolean) => void; + setRoleAgent: (role: RoleName, agent: string) => void; + setRoleField: (role: RoleName, field: string, value: string | number | boolean) => void; + setRoleRuntime: (role: RoleName, value: RoleRuntimeValue) => void; + clearRuntime: (role: RoleName) => void; + setNumberFieldValidity: (id: string) => (message: string | null) => void; + addFallback: (role: RoleName) => void; + removeFallback: (role: RoleName, index: number) => void; + updateFallback: (role: RoleName, index: number, value: RoleRuntimeValue) => void; + registerFieldRef: (id: string) => (element: HTMLElement | null) => void; +} + +function summarize(roles: readonly RoleViewModel[]): string { + const off = roles.filter(role => !role.enabled).length; + const roleCount = `${roles.length} ${roles.length === 1 ? "role" : "roles"}`; + return off > 0 ? `${roleCount} · ${off} off` : roleCount; +} + +/** The six background roles as one list of disclosure rows. */ +export function RoleList({ roles, disclosure, ...panelProps }: RoleListProps) { + const allExpanded = roles.every(role => disclosure.isOpen(role.role)); + + return ( +
    +
    + + {summarize(roles)} + + +
    +
    + {roles.map(vm => ( + disclosure.setOpen(vm.role, open)} + {...panelProps} + /> + ))} +
    +
    + ); +} diff --git a/web/src/systems/settings/components/role-panel-header.tsx b/web/src/systems/settings/components/role-panel-header.tsx new file mode 100644 index 000000000..26787ed96 --- /dev/null +++ b/web/src/systems/settings/components/role-panel-header.tsx @@ -0,0 +1,82 @@ +import { ChevronRight, TriangleAlert } from "lucide-react"; + +import { cn, CollapsibleTrigger, Switch } from "@agh/ui"; + +import type { RoleViewModel } from "../lib/roles-view-model"; +import { RoleStatusBadges } from "./role-status-badges"; + +export interface RolePanelHeaderProps { + vm: RoleViewModel; + bodyId: string; + disabled?: boolean; + testId: string; + onEnabledChange: (enabled: boolean) => void; +} + +/** + * The collapsed read of one role: what it does, how it resolves, whether it is + * on. The switch sits beside the disclosure trigger rather than inside it, so + * the most common action never requires expanding the row. + */ +export function RolePanelHeader({ + vm, + bodyId, + disabled, + testId, + onEnabledChange, +}: RolePanelHeaderProps) { + return ( +
    + + + {vm.hasDiagnostics ? ( + + ) : null} + {vm.routeSummary ? ( + + {vm.routeSummary} + + ) : null} + + +
    + ); +} diff --git a/web/src/systems/settings/components/role-panel.tsx b/web/src/systems/settings/components/role-panel.tsx new file mode 100644 index 000000000..ed065dbdf --- /dev/null +++ b/web/src/systems/settings/components/role-panel.tsx @@ -0,0 +1,148 @@ +import { useId, useState } from "react"; + +import { Collapsible, CollapsibleContent } from "@agh/ui"; + +import type { RolesRuntimeOptions } from "../hooks/use-roles-runtime-options"; +import type { RoleRuntimeValue } from "../lib/roles-config"; +import { roleFieldId } from "../lib/roles-validation"; +import type { RoleViewModel } from "../lib/roles-view-model"; +import type { RoleName } from "../types"; +import { RoleAdvancedDetails } from "./role-advanced-details"; +import { RoleDiagnosticsNotice } from "./role-diagnostics-notice"; +import { RoleFieldControl } from "./role-field-control"; +import { RolePanelHeader } from "./role-panel-header"; +import { RoleRoutingFields } from "./role-routing-fields"; + +const TEST_PREFIX = "settings-page-roles"; + +export interface RolePanelProps { + vm: RoleViewModel; + options: RolesRuntimeOptions; + validationErrors: Record; + open: boolean; + onOpenChange: (open: boolean) => void; + disabled?: boolean; + draftRevision?: number; + setRoleEnabled: (role: RoleName, enabled: boolean) => void; + setRoleAgent: (role: RoleName, agent: string) => void; + setRoleField: (role: RoleName, field: string, value: string | number | boolean) => void; + setRoleRuntime: (role: RoleName, value: RoleRuntimeValue) => void; + clearRuntime: (role: RoleName) => void; + setNumberFieldValidity: (id: string) => (message: string | null) => void; + addFallback: (role: RoleName) => void; + removeFallback: (role: RoleName, index: number) => void; + updateFallback: (role: RoleName, index: number, value: RoleRuntimeValue) => void; + registerFieldRef: (id: string) => (element: HTMLElement | null) => void; +} + +/** + * One role as a disclosure row: the collapsed header answers "what is this, + * how does it route, is it on"; expanding reveals the two routing decisions, + * this role's policy fields, and an Advanced fold for the operator layer. + */ +export function RolePanel({ + vm, + options, + validationErrors, + open, + onOpenChange, + disabled, + draftRevision, + setRoleEnabled, + setRoleAgent, + setRoleField, + setRoleRuntime, + clearRuntime, + setNumberFieldValidity, + addFallback, + removeFallback, + updateFallback, + registerFieldRef, +}: RolePanelProps) { + const { role, fields, advancedFields, values, effective, status } = vm; + const bodyId = `role-panel-${useId().replace(/:/g, "")}`; + const testId = `${TEST_PREFIX}-${role}`; + const [advancedOpen, setAdvancedOpen] = useState(false); + // A blocking error inside the fold force-opens it, so the save flow can focus + // the offending field instead of aiming at a hidden control. + const hasAdvancedError = Object.keys(validationErrors).some( + id => + id.startsWith(`${role}.fallback.`) || + advancedFields.some(field => id === roleFieldId(role, field.key)) + ); + + return ( + + setRoleEnabled(role, enabled)} + /> + +
    + + {/* One recessed well, not a stack of frames: routing and policy rows + read as a single list separated by hairlines. */} +
    + setRoleAgent(role, agent)} + onRuntimeChange={value => setRoleRuntime(role, value)} + onClearRuntime={() => clearRuntime(role)} + /> + {fields.map(field => { + const id = roleFieldId(role, field.key); + return ( + setRoleField(role, field.key, value)} + onValidityChange={ + field.kind === "number" ? setNumberFieldValidity(id) : undefined + } + /> + ); + })} +
    + addFallback(role)} + onRemove={index => removeFallback(role, index)} + onUpdate={(index, value) => updateFallback(role, index, value)} + registerFieldRef={registerFieldRef} + /> +
    +
    +
    + ); +} diff --git a/web/src/systems/settings/components/role-routing-fields.tsx b/web/src/systems/settings/components/role-routing-fields.tsx new file mode 100644 index 000000000..fddc3fdd1 --- /dev/null +++ b/web/src/systems/settings/components/role-routing-fields.tsx @@ -0,0 +1,110 @@ +import { useId } from "react"; + +import { AgentCommandSelect } from "@/systems/agent"; +import { Button } from "@agh/ui"; + +import type { RolesRuntimeOptions } from "../hooks/use-roles-runtime-options"; +import type { RoleRuntimeValue } from "../lib/roles-config"; +import type { RoleViewModel } from "../lib/roles-view-model"; +import { RoleEffectiveHint } from "./role-effective-hint"; +import { RoleRuntimeSelector } from "./role-runtime-selector"; +import { SettingsFieldRow } from "./settings-field-row"; + +export interface RoleRoutingFieldsProps { + vm: RoleViewModel; + options: RolesRuntimeOptions; + disabled?: boolean; + testId: string; + onAgentChange: (agent: string) => void; + onRuntimeChange: (value: RoleRuntimeValue) => void; + onClearRuntime: () => void; +} + +/** + * The two decisions that define a role's route: which agent it runs as, and + * which runtime that agent uses. Both read their effective value from the + * daemon projection rather than restating the draft. + */ +export function RoleRoutingFields({ + vm, + options, + disabled, + testId, + onAgentChange, + onRuntimeChange, + onClearRuntime, +}: RoleRoutingFieldsProps) { + const runtimeLabelId = `${useId().replace(/:/g, "")}-runtime-label`; + const noProviders = !options.loading && options.providers.length === 0; + + return ( + <> + {vm.supportsAgent ? ( + + Route to a catalog agent, or keep the role default. + + + } + control={ + onAgentChange(next ?? "")} + /> + } + /> + ) : null} + Runtime} + description={ + <> + Provider, model and reasoning effort for this role. + {noProviders ? ( + + No providers configured yet. + + ) : ( + + )} + + } + control={ +
    + {vm.hasRuntimeOverride ? ( + + ) : null} + +
    + } + /> + + ); +} diff --git a/web/src/systems/settings/components/role-runtime-selector.tsx b/web/src/systems/settings/components/role-runtime-selector.tsx new file mode 100644 index 000000000..894596fa3 --- /dev/null +++ b/web/src/systems/settings/components/role-runtime-selector.tsx @@ -0,0 +1,60 @@ +import { RuntimeSelector, type RuntimeSelectorValue } from "@/systems/runtime"; + +import type { RoleRuntimeValue } from "../lib/roles-config"; +import type { RolesRuntimeOptions } from "../hooks/use-roles-runtime-options"; + +export interface RoleRuntimeSelectorProps { + value: RoleRuntimeValue; + options: RolesRuntimeOptions; + disabled?: boolean; + triggerId?: string; + triggerTestId: string; + ariaLabelledby?: string; + onChange: (next: RoleRuntimeValue) => void; +} + +/** + * The role routing control: one runtime selector standing in for provider, + * model and reasoning effort. Empty strings mean "inherit", exactly as the + * `[roles]` section stores them. + */ +export function RoleRuntimeSelector({ + value, + options, + disabled, + triggerId, + triggerTestId, + ariaLabelledby, + onChange, +}: RoleRuntimeSelectorProps) { + const selectorValue: RuntimeSelectorValue = { + provider: value.provider, + model: value.model, + reasoning_effort: value.reasoning_effort as RuntimeSelectorValue["reasoning_effort"], + }; + return ( + + onChange({ + provider: next.provider, + model: next.model, + reasoning_effort: next.reasoning_effort, + }) + } + /> + ); +} diff --git a/web/src/systems/settings/components/role-settings-group.tsx b/web/src/systems/settings/components/role-settings-group.tsx deleted file mode 100644 index c68c1e8b3..000000000 --- a/web/src/systems/settings/components/role-settings-group.tsx +++ /dev/null @@ -1,126 +0,0 @@ -import { useState } from "react"; - -import { roleFieldId } from "../lib/roles-validation"; -import type { RoleViewModel } from "../lib/roles-view-model"; -import type { RoleFallbackEntry, RoleName } from "../types"; -import { RoleAdvancedDetails } from "./role-advanced-details"; -import { RoleDiagnosticsNotice } from "./role-diagnostics-notice"; -import { RoleFieldControl } from "./role-field-control"; -import { RoleStatusBadges } from "./role-status-badges"; -import { SettingsGroup } from "./settings-group"; - -const TEST_PREFIX = "settings-page-roles"; - -export interface RoleSettingsGroupProps { - vm: RoleViewModel; - validationErrors: Record; - disabled?: boolean; - draftRevision?: number; - setRoleField: (role: RoleName, field: string, value: string | number | boolean) => void; - setNumberFieldValidity: (id: string) => (message: string | null) => void; - addFallback: (role: RoleName) => void; - removeFallback: (role: RoleName, index: number) => void; - updateFallback: ( - role: RoleName, - index: number, - field: keyof RoleFallbackEntry, - value: string - ) => void; - registerFieldRef: (id: string) => (element: HTMLElement | null) => void; -} - -/** - * One stacked role panel: header (name, badges, resolution line), inline - * diagnostics, editable routing/policy fields, and the advanced fold with the - * fallback editor + provenance chips. - */ -export function RoleSettingsGroup({ - vm, - validationErrors, - disabled, - draftRevision, - setRoleField, - setNumberFieldValidity, - addFallback, - removeFallback, - updateFallback, - registerFieldRef, -}: RoleSettingsGroupProps) { - const { - role, - label, - description, - fields, - values, - fallbackChain, - effective, - badges, - resolutionLine, - status, - } = vm; - const [userOpen, setUserOpen] = useState(false); - const hasFallbackError = Object.keys(validationErrors).some(id => - id.startsWith(`${role}.fallback.`) - ); - - return ( - - {description} - - {resolutionLine} - - - } - action={} - > - -
    - {fields.map(field => { - const id = roleFieldId(role, field.key); - const hasEffective = field.key in effective; - return ( - setRoleField(role, field.key, value)} - onValidityChange={field.kind === "number" ? setNumberFieldValidity(id) : undefined} - /> - ); - })} -
    - addFallback(role)} - onRemove={index => removeFallback(role, index)} - onUpdate={(index, field, value) => updateFallback(role, index, field, value)} - registerFieldRef={registerFieldRef} - /> -
    - ); -} diff --git a/web/src/systems/settings/components/role-status-badges.tsx b/web/src/systems/settings/components/role-status-badges.tsx index 214fa9993..c1259443b 100644 --- a/web/src/systems/settings/components/role-status-badges.tsx +++ b/web/src/systems/settings/components/role-status-badges.tsx @@ -5,13 +5,11 @@ import type { RoleBadge } from "../lib/roles-view-model"; const BADGE_LABELS: Record = { builtin: "BUILTIN", inherit: "INHERIT", - off: "OFF", }; const BADGE_TONE: Record = { builtin: "neutral", inherit: "info", - off: "warning", }; interface RoleStatusBadgesProps { @@ -19,7 +17,7 @@ interface RoleStatusBadgesProps { "data-testid"?: string; } -/** Compact `BUILTIN` / `INHERIT` / `OFF` pills projected from `RoleStatus`. */ +/** Compact `BUILTIN` / `INHERIT` pills projected from `RoleStatus`. */ export function RoleStatusBadges({ badges, "data-testid": testId }: RoleStatusBadgesProps) { if (badges.length === 0) { return null; diff --git a/web/src/systems/settings/components/settings-advanced-fold.tsx b/web/src/systems/settings/components/settings-advanced-fold.tsx index f82d144c5..07577e2d0 100644 --- a/web/src/systems/settings/components/settings-advanced-fold.tsx +++ b/web/src/systems/settings/components/settings-advanced-fold.tsx @@ -14,6 +14,7 @@ export function SettingsAdvancedFold({ open, onOpenChange, padded = false, + bare = false, label = "Advanced", "data-testid": testId, }: { @@ -24,6 +25,11 @@ export function SettingsAdvancedFold({ onOpenChange?: (open: boolean) => void; /** Pad the body when it hosts whole groups instead of flush rows. */ padded?: boolean; + /** + * Drop the panelbox frame so the fold can nest inside a surface that already + * frames itself — nested frames are the anti-pattern this avoids. + */ + bare?: boolean; /** Descriptive toggle label, e.g. "Advanced — limits". */ label?: ReactNode; "data-testid"?: string; @@ -33,14 +39,16 @@ export function SettingsAdvancedFold({ return ( diff --git a/web/src/systems/settings/components/settings-page-frame.tsx b/web/src/systems/settings/components/settings-page-frame.tsx index d8ef55a8e..129afbb5e 100644 --- a/web/src/systems/settings/components/settings-page-frame.tsx +++ b/web/src/systems/settings/components/settings-page-frame.tsx @@ -13,13 +13,24 @@ export interface SettingsPageFrameProps { /** Quiet dotsep meta entries after the description (live counts, freshness). */ meta?: ReadonlyArray<{ key: string; content: ReactNode }>; restart?: SettingsRestartViewState; - /** Listing pages (Providers) get the wide column. */ - wide?: boolean; + /** + * Column width: forms at 768px, listings (Providers) at 960px, and the layout + * canvas at 1040px, where a stage plus its inspector needs the extra room. + */ + width?: SettingsPageWidth; /** Floating save bar (or null for per-item / immediate pages). */ saveBar?: ReactNode; children: ReactNode; } +export type SettingsPageWidth = "form" | "wide" | "canvas"; + +const WIDTH_CLASS: Record = { + form: "max-w-settings-page-form", + wide: "max-w-settings-page-wide", + canvas: "max-w-settings-page-canvas", +}; + /** * Settings page scaffold (design system §04): centered column (768px forms / * 960px listings), subhead sentence + quiet meta, optional restart notice, @@ -30,7 +41,7 @@ export function SettingsPageFrame({ description, meta, restart, - wide = false, + width = "form", saveBar, children, }: SettingsPageFrameProps) { @@ -43,7 +54,7 @@ export function SettingsPageFrame({
    = {}): RolesRuntimeOptions { + return { + providers: providerFixtures, + models: modelFixtures, + agents: [], + loading: false, + catalogLoaded: true, + catalogError: null, + catalogStale: false, + refresh: fn(), + refreshing: false, + ...overrides, + }; +} + +interface PanelArgs { + statuses: readonly RoleStatus[]; + config: SettingsRolesConfig; + validationErrors: Record; + options: RolesRuntimeOptions; + expanded?: boolean; +} + +function RolesPanelHarness({ statuses, config, validationErrors, options, expanded }: PanelArgs) { + const roles = buildRolesViewModel(statuses, config); + const disclosure = useRolesDisclosure({ roles, validationErrors }); + const view = expanded ? { ...disclosure, isOpen: () => true, anyOpen: true } : disclosure; + return ( + +
    + fn()} + addFallback={fn()} + removeFallback={fn()} + updateFallback={fn()} + registerFieldRef={() => fn()} + /> +
    +
    + ); +} + +const meta: Meta = { + title: "systems/settings/components/RolesPanel", + component: RolesPanelHarness, + parameters: { layout: "fullscreen" }, + args: { + statuses: rolesStatusFixture.roles, + config: settingsRolesConfigFixture, + validationErrors: {}, + options: runtimeOptions(), + }, +}; + +export default meta; +type Story = StoryObj; + +/** Default read: six collapsed rows carrying name, resolution, route and switch. */ +export const Collapsed: Story = {}; + +/** Every role expanded, showing the two routing decisions and role policy fields. */ +export const Expanded: Story = { args: { expanded: true } }; + +/** Dream routed at a missing catalog agent — the row opens itself on the warning. */ +export const Diagnostics: Story = { + args: { + statuses: rolesStatusWithDiagnosticFixture.roles, + // The draft names the ghost agent too, so the picker shows it as configured + // rather than collapsing an out-of-catalog value into the default. + config: { + ...settingsRolesConfigFixture, + dream: { ...settingsRolesConfigFixture.dream, agent: "ghost" }, + }, + }, +}; + +/** A fallback route missing its model, so the role and its Advanced fold both open. */ +export const FallbackEditor: Story = { + args: { + config: { + ...settingsRolesConfigWithFallbackFixture, + dream: { + ...settingsRolesConfigWithFallbackFixture.dream, + fallback_chain: [ + settingsRolesConfigWithFallbackFixture.dream.fallback_chain[0]!, + { provider: "", model: "", reasoning_effort: "" }, + ], + }, + }, + validationErrors: { "dream.fallback.1": "Choose a provider and model." }, + }, +}; + +/** No providers configured yet — the runtime row says so instead of offering a dead control. */ +export const NoProviders: Story = { + args: { + expanded: true, + options: runtimeOptions({ providers: [], models: [] }), + }, +}; diff --git a/web/src/systems/settings/components/stories/settings-page-frame.stories.tsx b/web/src/systems/settings/components/stories/settings-page-frame.stories.tsx index cec4cdf84..b1f8411ed 100644 --- a/web/src/systems/settings/components/stories/settings-page-frame.stories.tsx +++ b/web/src/systems/settings/components/stories/settings-page-frame.stories.tsx @@ -66,6 +66,6 @@ export const Listing: Story = { description: "The agent CLIs and model providers your sessions run on.", meta: [{ key: "ready", content: "1 ready" }], slug: "providers", - wide: true, + width: "wide", }, }; diff --git a/web/src/systems/settings/components/window-manager-behavior-fields.tsx b/web/src/systems/settings/components/window-manager-behavior-fields.tsx deleted file mode 100644 index d26331390..000000000 --- a/web/src/systems/settings/components/window-manager-behavior-fields.tsx +++ /dev/null @@ -1,109 +0,0 @@ -import type { WindowManagerConfig } from "@/systems/os"; - -import { SettingsGroup } from "./settings-group"; -import type { ConfigFieldsProps, SelectOption } from "./window-manager-config-field-types"; -import { WindowManagerSelectField } from "./window-manager-select-field"; -import { WindowManagerToggleField } from "./window-manager-toggle-field"; - -type DragModifier = WindowManagerConfig["swapModifier"]; - -const DRAG_MODIFIER_OPTIONS: readonly SelectOption[] = [ - { value: "alt", label: "Alt" }, - { value: "control", label: "Control" }, - { value: "meta", label: "Meta" }, - { value: "shift", label: "Shift" }, - { value: "none", label: "None" }, -]; - -export function WindowManagerBehaviorFields({ draft, setDraft }: ConfigFieldsProps) { - return ( - - setDraft(current => ({ ...current, newWindowPolicy }))} - /> - setDraft(current => ({ ...current, smallViewportPolicy }))} - /> - setDraft(current => ({ ...current, focusPolicy }))} - /> - setDraft(current => ({ ...current, focusWrap }))} - /> - setDraft(current => ({ ...current, focusFollowsPointer }))} - /> - setDraft(current => ({ ...current, raiseOnFocus }))} - /> - setDraft(current => ({ ...current, dragAwayPolicy }))} - /> - setDraft(current => ({ ...current, groupMoveModifier }))} - /> - setDraft(current => ({ ...current, swapModifier }))} - /> - setDraft(current => ({ ...current, desktopTransition }))} - /> - - ); -} diff --git a/web/src/systems/settings/components/window-manager-binding-fields.tsx b/web/src/systems/settings/components/window-manager-binding-fields.tsx deleted file mode 100644 index ea86b3b43..000000000 --- a/web/src/systems/settings/components/window-manager-binding-fields.tsx +++ /dev/null @@ -1,94 +0,0 @@ -import { Input, Textarea } from "@agh/ui"; - -import { SettingsFieldRow } from "./settings-field-row"; -import { SettingsGroup } from "./settings-group"; -import type { ConfigFieldsProps } from "./window-manager-config-field-types"; -import { WindowManagerSelectField } from "./window-manager-select-field"; - -interface WindowManagerBindingFieldsProps extends ConfigFieldsProps { - shortcutsText: string; - shortcutsValid: boolean; - setShortcutsText: (value: string) => void; -} - -export function WindowManagerBindingFields({ - draft, - setDraft, - shortcutsText, - shortcutsValid, - setShortcutsText, -}: WindowManagerBindingFieldsProps) { - return ( - - - setDraft(current => ({ - ...current, - bindings: { ...current.bindings, topCenter }, - })) - } - /> - - setDraft(current => ({ - ...current, - bindings: { ...current.bindings, bottomCenter }, - })) - } - /> - 500 - } - className="h-11 w-32" - min={1} - max={500} - step={1} - type="number" - value={Number.isFinite(draft.historyLimit) ? draft.historyLimit : ""} - onChange={event => { - const historyLimit = event.currentTarget.valueAsNumber; - setDraft(current => ({ ...current, historyLimit })); - }} - /> - } - /> -
    -