The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Navigation: top bar with a Studios launcher, search, phone tabs and next steps
Adarsh58b900b8cf27
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex e8aea96c..6ab85aeb 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -461,7 +461,7 @@ Round 5 part 1 (Work2Skill W1 and W2; plan in `docs/research/work2skill-7.md`).- **Runs on the server** (`src/server/recipes.ts`; routes under `src/app/api/assist/skills/[name]/` with `src/server/recipe-routes.ts`). `compileRun` sends every filled request through the API's own `GenerationRequestSchema` and puts a dual-engine Original on the run's engine. Fuobe never moves a step to the other engine: `recipeEngines` is the engines every step allows under Settings → Engine mode. `estimateRecipe` prices one run or many with `planSteps` / `planFor`, as Assist's approval card does. `runRecipe` starts one `createPipeline` per row, or one `executeTool` call per row whose rows `stampRequests` (`generations.ts`) stamps afterwards. A run is refused with 409 until the plan check has passed on that engine, or while the skill is switched off; a CSV with a header and no rows is a 422.- **Checks** (`verifyRecipe`, `POST …/verify`). `plan`: each step planned and priced as it would start; when every refusal is only a provider to connect (`onlyConnect`: messages that start "Connect"), the same run on the demo route stands in, with a note. `demo` (the default): the plan check, then a free dry run on the mock provider whatever Settings → Demo mode says (`request.demo`; at most 120 s per engine; small stand-in files for media inputs with no example), whose hidden rows go to the Trash; a Run doesn't wait for it. `real` (API only, needs `confirm: true`, holds the request up to 15 minutes): the examples on the user's keys, outputs checked by their structure (`probeMedia`) and the look judged only by a model that sees images (`llmSeesImages`; on the GPU only Ollama, never paid Claude). Tool steps get the plan check only. `needsRecheck` asks for a check again when a step's model was retired (`REPLACED_BY`) or switched off, or the plan hash changed. A check that finds the recipe changed while it ran refuses with 409 and keeps the edit. An uploaded `recipe.json` loses its `verified` dates, and the .zip download (`?format=zip`) never carries this install's checks; examples and source stay out unless `&examples=1`.- **Making a skill from results** (W2; `src/server/recipe-builder.ts`, `src/lib/recipe-builder.ts`, `src/components/skills/*`). `draftFromGenerations` walks the picked results back through `depends_on` and chain slots to the exact requests that made them. Results handed on by hand in the composer (Edit, Animate) are linked by matching file URLs (`linkByFile`); a stack that ran as one job per result becomes one step (`jobsOf`); an expansion comes back as the request it was asked as (`GenerationRequest.asked`; older ones are told apart by step labels and refused with `STEPS_REFUSAL`); a retired model moves to its replacement (`currentRequest`); and Translate & dub, Katana and Captions are lifted to their Assist tools (`dub_video`, `katana`, `add_captions`). Other studios that plan their own steps are refused by name (`STUDIOS`, `notSupported`). Every input starts Fixed. The review screen marks what varies (media, @elements, whole prompts, words picked in a prompt, and the takes, shape, length and quality), and `buildRecipe` and `skillBody` write the recipe and SKILL.md live. `POST /api/assist/skills/draft` returns the draft and the refusals; `/draft/check` runs the plan check and the dry run on an unsaved recipe (kept in memory by recipe hash, `draftKey`: 200 entries for 6 hours, so a restart loses a passed dry run); `/draft/name` is an optional naming pass by Claude or Ollama; `/draft/save` checks the plan again and saves, with 409 for a taken name and 422 for a failing plan. "draft" is a reserved skill name; a user skill already called that would have its GET, PATCH and DELETE routes shadowed by the POST-only draft route (read from the routing, not tested, and nothing renames it). A skill made from demo results says so in its Run form (`DEMO_NOTE`, `source.demo`) until a real test passes.-- **UI.** A recipe skill's card on the Skills page shows "Runs by itself", and its dialog shows where it was checked or why it needs a re-check (`skills-view.tsx`). The Run form (`run-skill-dialog.tsx`, `/assist/skills?run=<name>`) builds its fields from the inputs, offers only engines whose check passed, prices live, lists the steps (`plan-jobs.tsx`) and has a Many tab for CSV rows. ⌘K lists "Run <skill>…" (`skillEntries` in `src/lib/command-search.ts`). "Make a skill from this…" is in every finished result's ⋯ menu and "Make a skill" in the Library's selection bar; `SkillBuilderProvider` wraps `StudioChrome` (`app-sidebar.tsx`), so the viewer opened from ⌘K or a job notification has it too, and loads the review screen on first open.+- **UI.** A recipe skill's card on the Skills page shows "Runs by itself", and its dialog shows where it was checked or why it needs a re-check (`skills-view.tsx`). The Run form (`run-skill-dialog.tsx`, `/assist/skills?run=<name>`) builds its fields from the inputs, offers only engines whose check passed, prices live, lists the steps (`plan-jobs.tsx`) and has a Many tab for CSV rows. ⌘K lists "Run <skill>…" (`skillEntries` in `src/lib/command-search.ts`). "Make a skill from this…" is in every finished result's ⋯ menu and "Make a skill" in the Library's selection bar; `SkillBuilderProvider` wraps the frame in `StudioChrome` (`nav/studio-chrome.tsx`), so the viewer opened from ⌘K or a job notification has it too, and loads the review screen on first open.- **Checked** in demo mode only: unit and API tests (`recipe`, `recipes`, `recipe-builder`) with Demo mode off and no keys, and the browser checks `skills-run` and `skills-builder`. No skill has run with a paid key or on a GPU, the naming pass and look judging have not met a live Claude or Ollama vision model, the three lifts are tested as drafts only, and the real check level has no button. The text agents read (the "Run it" section, a built skill's SKILL.md) mentions a `run_skill` MCP tool that comes with W3 and doesn't exist yet.## MCP server (`src/server/mcp.ts`, `/api/mcp`)@@ -530,10 +530,10 @@ Settings (`src/server/settings.ts`) are typed and validated against allowed valu## UI (`src/components/`, `src/app/(studio)/`)-Liner-inspired shell (pale frame, rounded inset sheet, 13px sidebar rows, serif headlines, pill composer). The sidebar (`app-sidebar.tsx`, rows in `nav-items.ts`) remembers its rail and groups without making the layout dynamic (`SIDEBAR_STATE_SCRIPT` in `src/lib/nav.ts` runs before paint); its Engine group starts folded and Studios open (`DEFAULT_NAV_CLOSED`), and a remembered choice wins. Branded not-found and error pages, and `loading.tsx` skeletons on studio and gallery routes (`skeletons.tsx`; `/marketing` has its own).+Liner-inspired look (serif headlines, pill composer) in a top-bar frame. `StudioChrome` (`components/nav/studio-chrome.tsx`) is the frame of every studio page and the root not-found page: from the md breakpoint up a sticky top bar (`nav/top-bar.tsx`), on a phone a bottom tab bar with its sheets (`nav/phone-tabs.tsx`, `nav/phone-sheets.tsx`), and the search palette everywhere. What the frame lists comes from one model, `src/lib/nav-model.ts` (top-level links, Create, the 28 studios plus Apps in five goal columns, the goals, settings, who may see each entry); `components/nav-items.ts` is derived from it. Covers are real preset stills resolved on the server (`navCovers()` in `src/lib/nav-covers.ts`, passed in by the layout). `CHROME_STATE_SCRIPT` in `src/lib/nav.ts` runs before paint and marks `<html>` (`data-fullscreen-studio`, `data-viewer`, and which bar pills this browser had), so the static shell doesn't shift when the viewer arrives. Branded not-found and error pages, and `loading.tsx` skeletons on studio and gallery routes (`skeletons.tsx`; `/marketing` has its own).-- **Shell (round 4).** "Skip to content" is the first Tab stop, the sidebar is a `<nav aria-label="Main">`, and each page has one `<main>`. Full-screen studios (`fullScreenStudio()` in `nav.ts`: a Cinema, Canvas or Layers project, and every Assist page) fold the sidebar to its icon rail without touching the remembered choice: only `SidebarShell` writes the sidebar cookie, and only when that choice changes (`persistOpen` on `SidebarProvider`). Phones get a header with the menu and Search on gallery and settings pages (`phone-bar.tsx`). `intent-link.tsx` prefetches a link on hover or focus instead of when it appears on screen (rows marked `eager` still prefetch on view). Shortcut labels show ⌘ on Apple devices and Ctrl elsewhere (`src/lib/keys.ts`). Every Copy button goes through `copyText` (`src/lib/clipboard.ts`), so copying works on plain-http LAN addresses. Since round 5 part 1 `StudioChrome` (`app-sidebar.tsx`) wraps the shell in `SkillBuilderProvider` (see Skills that run by themselves).-- **Command palette** (`command-palette.tsx`, ⌘K / Ctrl+K, also the sidebar's Search row and the phone header's Search): pages, Settings sections, apps, camera motions, effects, models (filtered by engine mode, and since round 4 part 4 by Settings → Models & licences through the access summary) and recent creations, ranked with typo tolerance in `src/lib/command-search.ts`. The catalog part is `GET /api/search-index`, a static, prerendered slim index built by `paletteIndex()` in `src/lib/palette-index.ts` and fetched the first time the palette opens. `modelHref()` opens a model where it runs (a studio with `?model=`, a Video tools mode, Image to 3D, an app, Layers, Captions / Trim / Translate), else the Models page filtered by `?q=`; the round-4 tools (Remove object, Genjutsu, FPS Boost, SDR to HDR, Export, the 3D scene) aren't in its lists yet, so their models open the Models page. Since round 4 part 3 every Image to 3D model and Meshy Rigging open `/image-to-3d`, and a Fuobe Original is listed once with both engines. Since round 4 part 4 it also lists "Models & licences" (`/settings/models`) and "Assist connectors". Since round 5 part 1 a "Run a skill" group lists "Run <skill>…" for every enabled recipe skill (`skillEntries`), and Settings lists "Training (AI-Toolkit)". It replaces `global-shortcuts.tsx` (⌘K used to go Home).+- **Shell.** "Skip to content" is the first Tab stop, the bar (and on a phone the tab bar) is a `<nav aria-label="Main">`, and each page has one `<main id="content">`. Page geometry follows the frame through CSS variables in `globals.css` (`--chrome-top`, `--chrome-bottom`, `--content-h`; utilities `h-content`, `min-h-content`, `top-chrome`, `bottom-chrome`), so studio headers stick under the bar and phone composers sit above the tabs. Full-screen studios (`fullScreenStudio()` in `nav.ts`: a Cinema, Canvas or Layers project, and every Assist page) keep the bar on a desktop; on a phone they hide the tabs and their header's Menu button (`nav/phone-nav-button.tsx`, Search elsewhere) opens the menu sheet. `intent-link.tsx` prefetches a link on hover or focus instead of when it appears on screen (rows marked `eager` still prefetch on view); the routes the launcher, menus and sheets lead to are prefetched together once the person reaches for them (`warmNav()` in `nav/top-bar.tsx`). Shortcut labels show ⌘ on Apple devices and Ctrl elsewhere (`src/lib/keys.ts`). Every Copy button goes through `copyText` (`src/lib/clipboard.ts`), so copying works on plain-http LAN addresses. `StudioChrome` wraps the shell in `SkillBuilderProvider` (see Skills that run by themselves).+- **Search palette** (`nav/search-context.tsx` with the provider and the `/`, ⌘K and Ctrl+K keys; the dialog in `nav/search-palette.tsx` and `nav/search-results.tsx`, loaded on first use; also the bar's Search field, the launcher's search link and the phone header's Search, full screen on a phone): the nav model's entries ranked by `searchNav` (`src/lib/nav-search.ts`: typo tolerance, light stemming and a table of intents, so "ad for my perfume" leads with Marketing Studio), with Best matches, Also try, groups by kind, Jump back in (recent creations) and an Every studio grid with goal chips. Below them come pages, Settings sections, apps, camera motions, effects, models (filtered by engine mode, and since round 4 part 4 by Settings → Models & licences through the access summary) and recent creations, ranked with typo tolerance in `src/lib/command-search.ts`. The catalog part is `GET /api/search-index`, a static, prerendered slim index built by `paletteIndex()` in `src/lib/palette-index.ts` and fetched the first time the palette opens. `modelHref()` opens a model where it runs (a studio with `?model=`, a Video tools mode, Image to 3D, an app, Layers, Captions / Trim / Translate), else the Models page filtered by `?q=`; the round-4 tools (Remove object, Genjutsu, FPS Boost, SDR to HDR, Export, the 3D scene) aren't in its lists yet, so their models open the Models page. Since round 4 part 3 every Image to 3D model and Meshy Rigging open `/image-to-3d`, and a Fuobe Original is listed once with both engines. Since round 4 part 4 it also lists "Models & licences" (`/settings/models`) and "Assist connectors". Since round 5 part 1 a "Run a skill" group lists "Run <skill>…" for every enabled recipe skill (`skillEntries`), and Settings lists "Training (AI-Toolkit)". It replaces `global-shortcuts.tsx` (⌘K used to go Home).- **Home** (`src/app/(studio)/page.tsx`): `homeShowcase()` in `src/lib/home-showcase.ts` (server only, `"use cache"`) names the presets, studios, models and skills Home shows and computes every number it quotes from the catalog, the ComfyUI manifest (CREDITS.md's count), the skills folder and `LLM_PROVIDERS`; `tests/home-showcase.test.ts` checks each id has its cover and clip, shows once, and each number is the catalog's. `HomeView` keeps the composer and renders the wall right under it; the sections below (`components/home/home-sections.tsx`) are server components passed as children, with small client islands (`showcase-tile.tsx`, `before-after.tsx`, `home-islands.tsx`). Effect and app cards rest on their clip's peak frame (`public/previews/presets/peak/`, `preset-peaks.generated.ts`, cut by `scripts/gen-preset-peaks.mjs` from the published clips) and their clip starts from that frame (`PresetPreview`'s `rest`). The before/after under Apps shows each app's HD stills (`public/previews/presets/ba/1280/`, `ba/960/` and `ba/512/`, `preset-before-after.generated.ts`, made by `scripts/gen-before-after.mjs` from the reveal clips' masters for every app whose cover is one): each picture starts as its 512 px still, and the browser then picks the 960 or 1280 px copy the screen needs (`srcset`; a 1x desktop or 2x phone the 960, a 2x desktop or 3x phone the 1280), added only once the slider comes within a screen of view and the page has loaded, so it never competes with the page's first paint. The playback store gained `auto: "touch"` (studio cards wait for a hover where one is possible) and `paused` (Pause previews, kept in localStorage under `fuobe:previews`). Assist reads `?prompt=` into a new chat without sending it (`assistDraft`).- **Getting started and connections.** `get-started.tsx` is the first-run guide under Home's composer and at the top of Settings (Use paid models, Use your GPU; no demo card: placeholder results are a Settings switch, for a tour), shown until `onboarded` is set (`showFirstRun`, `FIRST_RUN_SCRIPT` in `src/lib/connections.ts`). Every connection field in Settings is a `ConnectField` (`connect-field.tsx`): Save & test sends the typed value to `POST /api/providers/test` (`{provider, value | values, field}`; the old `{provider}` body still works) and saves it only when the test passes, with a "Save anyway" link. `settings-form.tsx` has a status strip with one chip per connection (`connectionSummary`); since round 4 part 2 it has a LoRAs section (`#loras`, `lora-settings.tsx`: the LoRA folder, the civitai key with Save & test, and the library with licences and Download buttons), which the command palette also lists. `CREDITS.md` (`scripts/credits.mjs`, `src/lib/licences.ts`) lists each open model's licence from the catalog and the workflow manifest; Settings links to it and to Settings → Models & licences (`/settings/models`, `model-access-view.tsx`: the switches; see Models & licences). Round 4 part 4 also adds a Models & licences section and Assist · connectors (`#assist-connectors`, `components/assist/connectors-settings.tsx`) to `settings-form.tsx`. Round 4 part 5 drops the Higgsfield key field and chip and the "Higgsfield first" Preferred provider (`PROVIDER_SETTINGS`, `CLOUD_PROVIDERS` and `connectionSummary` in `src/lib/connections.ts`). Round 5 part 1 adds Training · AI-Toolkit (`#training`: three `ConnectField`s tested as provider `ai-toolkit`), retitles the LoRAs section "LoRAs · looks, motions, effects and adapters" with an Adapters tab, and (fixes-5) makes every "Settings → …" message and `/settings#…` link name a section that exists, which `tests/settings-links.test.ts` enforces.- **Studio pages** render `<Studio config>` (`src/components/studio/studio.tsx`), a server component that passes `studioCatalog(config)` from `src/lib/studio-catalog.ts`: the studio's models without provider field maps. Inside, `CatalogProvider` / `useCatalog()` resolve models; `loadFullCatalog()` imports `@/lib/catalog` lazily for motions, effects, `?preset=` and unknown ids. Client components under `studio/` must not import `@/lib/catalog` or `@/lib/studios`. `StudioPage` renders the same tree in the static shell and after hydration; hand-off params merge into the draft with `mergeHandoff`. `StudioConfig` (`studio-context.tsx`) gained `pickerOps`, `anyOf`, `signature` and `extraModels`, and in round 4 `frames` (Frames mode), `comfyOnly` (a tool that runs only on ComfyUI, with a note and an alternative) and `related` (a link under the hero). `HandoffSync` in `studio-page.tsx` also runs Home's Start: Home issues a one-time token (`issueStartToken` in `src/lib/composer.ts`, kept in sessionStorage) and opens the studio with `?prompt=…&go=<token>`; the studio submits once if `claimStartToken` accepts it, so a link from elsewhere can't start a run. A `?model=` that names the other engine's model switches the remembered engine; since round 4 part 3 it also survives the composer's swap of an untouched draft's default model when the engine is read after hydration (`followEngineDefault`: before, a link on the open engine landed on the studio's default model). Since round 4 part 5 a `?model=` naming a retired model opens on its replacement (`currentModelId`), and Reuse of a run on one migrates its request in the browser (`migrateRequest` without Director words) and toasts what changed; the composer's provider style chip (`ProviderPresetChip`, Higgsfield's live styles) is gone. The line under Home's composer prices what Start will run from the catalog (`startQuotes` in `src/lib/starter-prices.ts`, worded by `startLine` in `src/lib/connections.ts`).@@ -541,7 +541,7 @@ Liner-inspired shell (pale frame, rounded inset sheet, 13px sidebar rows, serif- **Composer** pieces: pure logic in `src/lib/composer.ts` (summary, blockers, `onImageChange`, `fitAttachments`, `firstMissingSlot`; since round 4 `blockerLine` for the phone's blocked-Generate line, `framesRequest` and the Frames strip helpers, the start token), `attachments.ts` (`useAttach`, `useUploadReaper`), `settings-panel.tsx`, `model-picker.tsx` (cmdk), `attach-menu.tsx`, `preset-chips.tsx` (lazy), `radio-keys.ts`, `frames-strip.tsx`, and since round 4 part 3 `look-chip.tsx` (lazy: Fuobe Soul's looks, a popover on desktop and a sheet on phones). Since round 4 part 3 the composer sends `engine` for a Fuobe Original, drops a look when the model changes to one without looks, moves to a motion's or effect's Original when one is picked, and follows a move across an engine switch (the pure helpers are in `src/lib/composer.ts`: see Fuobe Originals). Video finishing reads the attached clip's facts from `POST /api/media/probe` for its "24 → 60 fps · 5 s → 10 s" line and its prices. Since round 5 part 1 Edit video does too (`clipFacts`, fixes-5): a clip edit that keeps the clip's length is priced on its seconds, and `clipBlocker` blocks Generate with the reason when the clip is outside the model's window (`clip-windows.ts`; the server refuses the same for an API call that sends no length, after the clip is uploaded to the provider's storage, nothing billed). Lipsync reads the voice's length (`StudioConfig.voiceFacts`) to price talking avatars, and the Image studio prices a look's step after the picture (`postStepCost`, with the face mosaic's models in `extraModels`). The Look chip has a "No look" state (`none`, Storyboard). Since round 5 part 2 a price is read on the browser's day (`useToday` in `src/hooks/use-today.ts`: null on the server and while the page hydrates, so a launch-priced model shows no price until then, and it changes at UTC midnight): the composer's estimate, the model picker (`pickerPrice`) and the Models page (`rowPrice` with `ModelRow.launch`; `GET /api/models` answers the day's `price` and keeps `launch`). The slim studio catalog carries `Pricing.promo` as it is. A run with LoRAs on an endpoint with no published price shows "Price unknown", never free, in the composer and on Canvas nodes. The Image studio's controls chip reads "Options" (`StudioConfig.controlsTitle`), where MOSS-Image's Quality sits.- **Feed and results**: running tiles show elapsed time and, once progress has moved, time left (`use-now.ts`; `notePace` / `timeLeft` in `src/lib/format.ts`); the newest single result offers next steps (`nextSteps` in `output-actions.ts`); video tiles get a poster (`videoPoster`); ProRes, FFV1 and clips the browser can't decode show as a file card (`VideoFileCard` in `result-media.tsx`). Since round 4 part 2, `useCreateGeneration` (`src/lib/api.ts`) shows a run's `notes` (LoRAs left out, a length the API rounds) as a warning toast. Since round 4 part 3 every studio feed finishes Fuobe Soul pictures (`useSoulFinish`), the viewer's Details show a Look row and a Finish row, and a clip with `meta.grade` offers "Apply the … grade" first.- **Galleries** get slim cards (`src/lib/preset-cards.ts`) with procedural previews (`preset-preview.tsx`, `move-glyphs.ts`); `previewFor` (`src/lib/preset-card-data.ts`) shows a real cover instead when `src/lib/preset-previews.generated.ts` lists one: a still cover is the card's picture as rendered (no tint, bleed, mirroring or move glyph), a clip cover is its first-frame poster with a muted `<video>` over it only while it plays (invisible until its first frame is ready, released when it stops). Every entry records the run, engine, model and variant that made it. `preset-card-data.ts` is the only module that reads the manifest, and only the server gallery pages and Home's server-only showcase import it, so the manifest never ships in client code: the preset header builds the same preview from the slim covers map (`coverPreview` in `src/lib/preset-covers.ts`) (`tests/preset-covers.test.ts` checks the importers, and checks the real manifest against `public/previews`). Every cover URL the site gives ends in its file's content version (`?v=` and 8 hex digits of its sha256; a poster's also covers its 320 px copy in `thumbs/`, whose URL keeps it), written into the manifests by `eval:covers` and `gen-preset-peaks.mjs` (`--versions` on either hashes the files as they are; the covers' one first makes a poster's 320 px copy that's missing or older than its poster, and encodes nothing else), so a cover made again under its old name gets a new URL. Versioned covers are served as `immutable`, for a year in the browser and a day in the CDN (`s-maxage`, so a revert or rollback that gives an old version back never finds the wrong file pinned there); one asked for without its version keeps a day's cache and a week of background revalidation (`next.config.ts`). Both stay outside the sign-in proxy like `samples/`. The file is written by the evaluation harness's `eval:covers`, from a measured run's promoted renders or, with `--from-masters <dir>`, from rendered masters kept outside the repo (`coversFromMasters()` in `scripts/eval/lib/covers.mjs`; it replaces only the ids it writes, and skips an id whose cover another run made elsewhere unless `--replace`). Stills are 4:2:0 JPEGs of at most 768 px; a clip cover is at most 4 s and 512 px, and its last 6 frames are crossfaded into its first ones so the card's loop has no jump (a clip that already ends where it starts is only cut). The first covers came that way: 480 of the 487 app, motion and effect cards (474 stills from Ideogram 4 and 6 clips from MiniMax H3, all rendered in ComfyUI; run `comfyui-previews-2026-10`, in `public/previews/presets/`), while the other 7 keep their procedural preview. Main's later cover work gave 43 apps a before/after reveal clip (Ideogram 4, then Qwen-Image 2.1 Edit), so 48 of the 480 now have a clip (the other 5 from MiniMax H3) and 432 are stills. `preview-playback.ts` decides which play: a clip card plays by itself while it's mostly in view, once scrolling stops, at most 6 at once (3 on a phone), the cards in full view and nearest the middle of the screen first; a procedural preview does so only where nothing can hover (phones), and the preset header plays whatever moves. Nothing plays by itself with reduced motion (turned on while the page is open, it stops at once), Save-Data, on 2G or in a hidden tab; a hover (after a short rest), keyboard focus, or a tap on the preset header still plays one (with reduced motion, only a clip).-- **Sidebar** (round 4 part 2): Studios gains AI Influencer (`/influencer`) and Content Factory (`/content-factory`) in `nav-items.ts`. Round 4 part 5 adds Character Swap Studio (`/character-swap`, short label "Character swap") after Genjutsu.+- **Navigation.** The bar: Create (a menu of the create tools), Studios (the launcher, `nav/studios-launcher.tsx`: every studio grouped by goal on one screen in six columns, Film & video, Social & shorts, Sell & advertise, People & fashion, Sound (Audio with Music, Sound effects, Clean up voice and Translate & dub) and Finish & convert, arrow keys across and down the columns), Apps, Motions & effects, Canvas, Assist, Library, a More menu for what doesn't fit, Search, New creation and the account menu (`nav/account-menu.tsx`; the owner's install status, a visitor's GPU, balance, theme, Thanks & licences, Settings and Sign out, moved from the old sidebar's footer in `nav/status-chips.tsx`). Phones: Home, Create, Studios, Library and You tabs; Studios opens a sheet with every studio at once (`nav/studios-sheet.tsx`). Home has a goal row under the hero (`nav/goal-row.tsx`): each goal opens a band of its studios, one-tap presets and finishing tools. Under a finished result a "Keep going with this" row offers 3 to 5 next steps that open the next studio with the result attached (`nav/next-steps.tsx`, `keepGoing` in `src/lib/next-steps.ts`; in the studio feed, the Viewer and the 3D model card), and the account menu and You sheet show how much of Fuobe this browser has explored with a next one to try (`nav/explore-progress.tsx`, `src/lib/nav-explore.ts`, kept in `localStorage` only).- **Models page** (round 4 part 3; the page itself is gone, the rows still feed the model picker): `ModelRow.engines` (`src/lib/model-rows.ts`) puts an Original under both the Cloud and Open source filters, with both engine icons, "Open source + cloud" (`enginesLabel`) and a "Free · $… / megapixel" price. Since round 4 part 4 models switched off leave the list (`models-table.tsx`), which says how many and links to Settings → Models & licences.- **Sharing** (round 4 part 4): the studio layout (`src/app/(studio)/layout.tsx`) wraps every page in `ShareProvider`, so any result menu can open the Share dialog; the Library gains the Shared tab and Publish in its selection bar, whose phone version folds Like, Pin and Review into a ⋯ menu (see Share links). The public share page lives outside the `(studio)` group, without the studio's frame.- Stand-alone views: color grading (`color-grade-view.tsx`, `src/lib/grade.ts`; since round 4 part 3 Invert and Solarize sliders, the Soul and DoP grade presets, and `?preset=` to open with a grade picked), storyboard, elements + train dialog (since round 4 part 4 `train-dialog.tsx`: the photo rules and tips, the consent tick for characters, the options by family with where each runs, price, time estimate and licence, Train / Retrain / Upgrade, the demo note, "Train anywhere" with the training kit and attaching a LoRA; element cards show a Soul ID, Training, Retrain or Demo badge; `moodboards/train-board.tsx` for "Train as a look…"), library (`library-view.tsx` + `components/library/*`), Assist, and the studios above.diff --git a/docs/FEATURES.md b/docs/FEATURES.mdindex 71d018d0..307585c4 100644--- a/docs/FEATURES.md+++ b/docs/FEATURES.md@@ -107,7 +107,7 @@ More on running it: [Development → Evaluation harness](DEVELOPMENT.md#evaluati## Placeholder results-- **Off by default.** With nothing connected, a run opens the connect card: the ComfyUI on this computer, a server address, or an API key. To give a tour without keys or a GPU, turn on **Settings → Show placeholder results (for a tour)**: every run then makes a result labelled "Placeholder", and the sidebar shows a "Placeholders on" chip that turns it off.+- **Off by default.** With nothing connected, a run opens the connect card: the ComfyUI on this computer, a server address, or an API key. To give a tour without keys or a GPU, turn on **Settings → Show placeholder results (for a tour)**: every run then makes a result labelled "Placeholder", and the top bar and the account menu show a "Placeholders on" chip that turns it off.## Model licencesdiff --git a/docs/billing-hook.md b/docs/billing-hook.mdindex ef682499..cbcb1269 100644--- a/docs/billing-hook.md+++ b/docs/billing-hook.md@@ -6,7 +6,7 @@ the person sees and whether the run may start. With no service set, every run iscall at all.Fuobe has no words of its own for prices or balances. Every word on screen about them (the price on Run, the balance in-the sidebar, a refusal's text, a link, an offer) comes from the service's answers at runtime.+the top bar and the account menu, a refusal's text, a link, an offer) comes from the service's answers at runtime.## Settings@@ -31,7 +31,7 @@ twice: the service must treat a repeated call (the same `requestId`, or the same| `POST /v1/release` | 5 s, through the outbox | the rows couldn't be made after a reserve || `POST /v1/settle` | 5 s, through the outbox | each row that succeeded || `POST /v1/refund` | 5 s, through the outbox | each row that failed, was stopped, or was removed by an output check |-| `GET /v1/balance?account=<id>` | 1 s | the sidebar's balance chip (cached 10 s) |+| `GET /v1/balance?account=<id>` | 1 s | the balance pill and the account menu's balance (cached 10 s) || `POST /v1/account-event` | 5 s, best effort | an account was made, verified, signed in or deleted || `POST /v1/interest` | 5 s | a person pressed an offer's button |diff --git a/docs/public-signup.md b/docs/public-signup.mdindex ef18de82..1d33717d 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -229,10 +229,10 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188refused for space.- **What a visitor sees.** For a guest or an account, `GET /api/status` describes its own GPU(`viewer`), with the open engine and no Demo mode. It says nothing about the studio's own- ComfyUI, providers, keys or local AI servers. The sidebar shows **Your GPU · Connect** (a guest- signs up first), or the account's ComfyUI as online or offline with its GPU and VRAM. At the foot- of the sidebar an account sees its email, which opens a menu with Settings, Your GPU (`/connect`)- and Sign out.+ ComfyUI, providers, keys or local AI servers. The account menu (the top bar's right end; the You+ tab on a phone) shows **Your GPU · Connect** (a guest signs up first), or the account's ComfyUI as+ online or offline with its GPU and VRAM. An account's menu also shows its email, Settings, Your+ GPU (`/connect`) and Sign out.`GET /api/models` lists the open-source models for a visitor, and the studios price a visitor'srun as it would go on its own GPU. The studio's own settings page isn't shown to visitors.@@ -296,7 +296,7 @@ With it on:Image to 3D, extra LoRAs added to a request, and clips and sound as inputs stay on the account's own GPU.- An account can upload pictures for these runs. Clips and sound still need its own GPU or key.- A new account goes back to where it was after sign-up, not to "Connect your GPU". Connecting a GPU stays in- Settings → Your GPU and at `/connect`; the sidebar says "Your GPU · Optional".+ Settings → Your GPU and at `/connect`; the account menu says "Your GPU · Optional".- A run waiting for the studio's GPUs shows its place in line ("In line · 3rd · about 40 s"). A run may wait`FUOBE_POOL_WAIT_MIN` minutes (30 by default); past that it fails.- The account's usual limits apply: runs at once, runs per hour, outputs per run, and its space.diff --git a/src/app/(studio)/error.tsx b/src/app/(studio)/error.tsxindex 3b06ba0d..e6e6fd57 100644--- a/src/app/(studio)/error.tsx+++ b/src/app/(studio)/error.tsx@@ -3,7 +3,7 @@import { useEffect } from "react";import { ErrorState } from "@/components/empty-state";-/** Catches render errors in any studio page; the sidebar (layout) stays usable. */+/** Catches render errors in any studio page; the top bar (layout) stays usable. */export default function Error({ error, retry }: { error: unknown; retry: () => void }) {useEffect(() => {console.error(error);diff --git a/src/app/(studio)/layout.tsx b/src/app/(studio)/layout.tsxindex 931737bd..e713e9ba 100644--- a/src/app/(studio)/layout.tsx+++ b/src/app/(studio)/layout.tsx@@ -1,9 +1,10 @@-import { StudioChrome } from "@/components/app-sidebar";+import { StudioChrome } from "@/components/nav/studio-chrome";import { ShareProvider } from "@/components/share/share-provider";+import { navCovers } from "@/lib/nav-covers";export default function StudioLayout({ children }: { children: React.ReactNode }) {return (- <StudioChrome>+ <StudioChrome covers={navCovers()}><ShareProvider>{children}</ShareProvider></StudioChrome>);diff --git a/src/app/(studio)/page.tsx b/src/app/(studio)/page.tsxindex 1a46d8f5..5fd78cec 100644--- a/src/app/(studio)/page.tsx+++ b/src/app/(studio)/page.tsx@@ -11,10 +11,26 @@ import {StudiosSection,} from "@/components/home/home-sections";import { HomeView } from "@/components/home-view";+import { GoalRow } from "@/components/nav/goal-row";import { ASSIST_SUGGESTIONS } from "@/lib/assist";+import { getPreset } from "@/lib/catalog";import { HOME_TRY, homeShowcase, roundedDown } from "@/lib/home-showcase";+import { GOALS } from "@/lib/nav-model";import { startQuotes, starterPriceLine } from "@/lib/starter-prices";+/** The goal bands' one-tap presets by name, read here so the catalog stays on the server. */+function goalTapNames(): Record<string, string> {+ return Object.fromEntries(+ GOALS.flatMap((g) =>+ g.taps.map((t) => {+ const p = getPreset(t.preset);+ if (!p) throw new Error(`The goal row names ${t.preset}, which isn't in the catalog`);+ return [t.preset, p.name];+ }),+ ),+ );+}+/*** The catalog stays on the server: Home gets slim cards, the numbers it quotes (each computed, lib/home-showcase.ts),* and what Start and the first-run guide cost. The sections under the wall are server components.@@ -26,6 +42,7 @@ export default async function Page() {openModels={roundedDown(home.facts.openModels)}chips={HOME_TRY}assist={{ label: "Plan a perfume ad with Assist", href: `/assist?prompt=${encodeURIComponent(ASSIST_SUGGESTIONS[0])}` }}+ goals={<GoalRow names={goalTapNames()} />}wall={<ShowcaseWall wall={home.wall} />}prices={starterPriceLine()}quotes={startQuotes()}diff --git a/src/app/(studio)/privacy/page.tsx b/src/app/(studio)/privacy/page.tsxindex 38e0953c..ef2ec3d0 100644--- a/src/app/(studio)/privacy/page.tsx+++ b/src/app/(studio)/privacy/page.tsx@@ -32,7 +32,7 @@ export default function Page() {</LegalSection><LegalSection title="Cookies"><p>- One cookie keeps you signed in. Your browser also remembers small preferences, such as your theme and how the sidebar looks. Analytics+ One cookie keeps you signed in. Your browser also remembers small preferences, such as your theme and which studios you have opened. Analyticscookies show us which pages and tools people use, so we can make them better. There are no advertising cookies.</p></LegalSection>diff --git a/src/app/globals.css b/src/app/globals.cssindex 01656dd6..eba0503f 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -269,9 +269,12 @@@apply font-sans;}body {- /* the frame color; the inset <main> sheet uses bg-background */+ /* the frame color (the top bar and pages outside the app frame); the app's <main> uses bg-background */@apply bg-sidebar text-foreground antialiased;font-feature-settings: "cv11", "ss01"; /* Inter: single-storey a, open digits; optional */+ /* viewport-fit=cover puts the page under the notch of a phone held sideways; every page keeps clear of it here (fixed bars pad themselves) */+ padding-left: env(safe-area-inset-left);+ padding-right: env(safe-area-inset-right);}h1, h2, h3, .font-heading {letter-spacing: -0.01em; /* Liner uses -0.03em on Flare; Instrument Serif is already tight */@@ -315,6 +318,38 @@}}+/* ---------------------------------------------------------------------------------------------+ * The app frame (components/nav): the top bar from md (56 px) and the phone's tab bar below it+ * (64 px plus the home indicator's inset). Pages size themselves to what is left: h-content,+ * min-h-content; sticky headers sit under the bar (top-chrome) and sticky footers above the tabs+ * (bottom-chrome). A full-screen studio, and the on-screen keyboard, hide the phone's tabs.+ * ------------------------------------------------------------------------------------------- */+:root {+ --chrome-top: 0px;+ --chrome-bottom: 0px;+ --content-h: calc(100svh - var(--chrome-top) - var(--chrome-bottom));+}+@media (min-width: 768px) {+ :root { --chrome-top: 3.5rem; }+}+@media (max-width: 767.98px) {+ :root { --chrome-bottom: calc(4rem + env(safe-area-inset-bottom)); }+ html[data-fullscreen-studio], html[data-keyboard-open] { --chrome-bottom: 0px; }+}+@media print {+ :root { --chrome-top: 0px; --chrome-bottom: 0px; }+}+@utility h-content { height: var(--content-h); }+@utility min-h-content { min-height: var(--content-h); }+@utility max-h-content { max-height: var(--content-h); }+@utility top-chrome { top: var(--chrome-top); }+@utility bottom-chrome { bottom: var(--chrome-bottom); }+/* A link to #section, and Tab moving down the page, stop clear of the bar and the tabs (focus is never hidden under them). */+html {+ scroll-padding-top: var(--chrome-top);+ scroll-padding-bottom: var(--chrome-bottom);+}+/* Markdown (status / docs pages) */.prose-fuobe { font-size: var(--text-body); line-height: 1.7; }.prose-fuobe h1 { font-family: var(--font-heading); font-size: 34px; line-height: 1.15; margin: 0 0 0.6em; }@@ -344,7 +379,7 @@mask-image: linear-gradient(to right, transparent, #000 var(--fade-l), #000 calc(100% - var(--fade-r)), transparent);}.fade-x[data-fade-start] { --fade-l: 32px; }-.fade-x[data-fade-end] { --fade-r: 32px; }+.fade-x[data-fade-end] { --fade-r: 56px; }/** Home's sections under the fold (home-sections.tsx): the first paint doesn't wait for their layout. Until the page@@ -359,23 +394,6 @@content-visibility: visible;}-/* Sidebar groups that remember being collapsed (app-sidebar.tsx). In icon mode every item shows. */-[data-nav-group][data-open="false"] [data-nav-items] { display: none; }-/* A collapsed group still shows the page you're on (only that item), so something is always lit. */-[data-nav-group][data-open="false"]:has([data-active="true"]) [data-nav-items] { display: revert-layer; }-[data-nav-group][data-open="false"] [data-nav-items] > li:not(:has([data-active="true"])) { display: none; }-[data-collapsible="icon"] [data-nav-group] [data-nav-items] { display: flex; }-[data-collapsible="icon"] [data-nav-group][data-open] [data-nav-items] > li { display: revert-layer; }--/*- * A vertical scroller fades out at an edge with more past it (app-sidebar.tsx). --fade-t and --fade-b- * are as deep as what's hidden there, up to 24px and 40px (scrollFades in src/lib/nav.ts).- */-.fade-y[data-more-above],-.fade-y[data-more-below] {- mask-image: linear-gradient(to bottom, transparent, #000 var(--fade-t, 0px), #000 calc(100% - var(--fade-b, 0px)), transparent);-}-/* ---------------------------------------------------------------------------------------------* Procedural preset previews (preset-preview.tsx, src/lib/preset-cards.ts).* A camera move animates --pv-t from 0 to 1; every depth layer turns it into its own transform:@@ -680,3 +698,8 @@@media (prefers-reduced-motion: reduce) {[data-live-stage] img, [data-live-demo] img { animation: none !important; transition: none !important; }}++/* Menus and popovers open and close without their fade, zoom and slide when the system asks for less motion. */+@media (prefers-reduced-motion: reduce) {+ [data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-sub-content"], [data-slot="popover-content"] { animation: none !important; }+}diff --git a/src/app/layout.tsx b/src/app/layout.tsxindex 10ee5d3c..e19144c0 100644--- a/src/app/layout.tsx+++ b/src/app/layout.tsx@@ -26,6 +26,8 @@ export const metadata: Metadata = {};export const viewport: Viewport = {+ // The page runs under the notch and home indicator; the bars pad themselves with the safe-area insets.+ viewportFit: "cover",themeColor: [{ media: "(prefers-color-scheme: light)", color: "#ffffff" },{ media: "(prefers-color-scheme: dark)", color: "#121213" },diff --git a/src/app/not-found.tsx b/src/app/not-found.tsxindex 88523159..faf5740b 100644--- a/src/app/not-found.tsx+++ b/src/app/not-found.tsx@@ -1,13 +1,14 @@import type { Metadata } from "next";-import { StudioChrome } from "@/components/app-sidebar";+import { StudioChrome } from "@/components/nav/studio-chrome";import { NotFoundState } from "@/components/empty-state";+import { navCovers } from "@/lib/nav-covers";export const metadata: Metadata = { title: "Not found" };/** Unknown URLs anywhere in the app: the branded state inside the usual app frame. */export default function NotFound() {return (- <StudioChrome>+ <StudioChrome covers={navCovers()}><NotFoundState /></StudioChrome>);diff --git a/src/app/providers.tsx b/src/app/providers.tsxindex 3d2de78d..e921e06d 100644--- a/src/app/providers.tsx+++ b/src/app/providers.tsx@@ -29,7 +29,7 @@ export function Providers({ children }: { children: React.ReactNode }) {defaultOptions: { queries: { staleTime: 5_000, refetchOnWindowFocus: true, retry: (n, e) => n < 1 && !NO_RETRY.has((e as { status?: number }).status ?? 0) } },}),);- // Signed in or out in another tab: this one asks who is looking again (its sidebar, its studios' refusals).+ // Signed in or out in another tab: this one asks who is looking again (its menus, its studios' refusals).useEffect(() => {if (typeof BroadcastChannel === "undefined") return;const c = new BroadcastChannel(AUTH_CHANNEL);@@ -54,7 +54,8 @@ export function Providers({ children }: { children: React.ReactNode }) {<QueryClientProvider client={client}><TooltipProvider delayDuration={300}>{children}- <Toaster position="top-center" gap={8} offset={29} />+ {/* Below the top bar on a desktop (56 px and a gap), near the top on a phone (its tabs are at the bottom). */}+ <Toaster position="top-center" gap={8} offset={{ top: 68 }} mobileOffset={{ top: 12 }} /><GuestPrompt /><AddKeyPrompt /><BillingCard />diff --git a/src/app/s/share-page.tsx b/src/app/s/share-page.tsxindex 268d8e43..e1e2d03f 100644--- a/src/app/s/share-page.tsx+++ b/src/app/s/share-page.tsx@@ -9,7 +9,7 @@ import { Carousel, RecreateButton } from "@/components/share/share-client";* owner shares prompts — each prompt with "Recreate in your Fuobe". Server-rendered from* PublicShare (src/server/shares.ts); every file URL is share-scoped. No app chrome, no links into* the studio: a visitor has nothing else to open. It lives with the /s routes, outside the studio- * frame, so its <main> is the page's only one (the studio's is SidebarInset).+ * frame, so its <main> is the page's only one (the studio's is in StudioChrome).*/export function SharePage({ share }: { share: PublicShare }) {const items = orderForLayout(share.items, share.layout, share.coverKey);diff --git a/src/components/ads/ads-home.tsx b/src/components/ads/ads-home.tsxindex dc3d4744..edf8e203 100644--- a/src/components/ads/ads-home.tsx+++ b/src/components/ads/ads-home.tsx@@ -109,7 +109,7 @@ export function AdsHome({ examples }: { examples?: StudioExampleRow }) {// A brand is saved to the studio's library, which is its owner's: a guest or an account is told so, not given the form.const visitor = useIsVisitor();return (- <div className="flex min-h-svh min-w-0 flex-col">+ <div className="flex min-h-content min-w-0 flex-col"><MarketingHeader title="Ads Studio" active="ads" engine={engine} onEngine={setEngine} /><div className="mx-auto w-full min-w-0 max-w-[1240px] flex-1 px-3 pb-20 sm:px-6"><section className="mx-auto max-w-[720px] pt-8 text-center sm:pt-14">diff --git a/src/components/ads/brand-workspace.tsx b/src/components/ads/brand-workspace.tsxindex 0a4c8aad..b7d7796f 100644--- a/src/components/ads/brand-workspace.tsx+++ b/src/components/ads/brand-workspace.tsx@@ -64,7 +64,7 @@ export function BrandWorkspace({ brandId }: { brandId: string }) {if (view.error) {return (- <div className="flex min-h-svh flex-col">+ <div className="flex min-h-content flex-col"><MarketingHeader title="Ads Studio" active="ads" /><div className="mx-auto max-w-md px-4 pt-[14vh] text-center"><h2 className="font-heading text-[26px]">This brand isn't on the shelf</h2>@@ -81,7 +81,7 @@ export function BrandWorkspace({ brandId }: { brandId: string }) {brand && <AdChat brand={brand} products={products} engine={engine} onBatch={() => (setStep("ads"), setChat(false))} onClose={inSheet ? () => setChat(false) : undefined} className="h-full" />;return (- <div className="flex min-h-svh min-w-0 flex-col">+ <div className="flex min-h-content min-w-0 flex-col"><MarketingHeadertitle={brand?.name ?? "Ads Studio"}active="ads"@@ -176,7 +176,7 @@ export function BrandWorkspace({ brandId }: { brandId: string }) {</>)}</div>- {chatReady && <div className="sticky top-28 hidden h-[calc(100svh-8rem)] w-[340px] shrink-0 xl:block">{chatPanel(false)}</div>}+ {chatReady && <div className="sticky top-[calc(var(--chrome-top)+7rem)] hidden h-[calc(var(--content-h)-8rem)] w-[340px] shrink-0 xl:block">{chatPanel(false)}</div>}</div><Sheet open={chat} onOpenChange={setChat}><SheetContent side="right" showCloseButton={false} className="w-full gap-0 p-0 sm:max-w-md">diff --git a/src/components/ads/multiplier.tsx b/src/components/ads/multiplier.tsxindex 70e601a1..b42deea0 100644--- a/src/components/ads/multiplier.tsx+++ b/src/components/ads/multiplier.tsx@@ -313,7 +313,7 @@ export function AdMultiplier({ models, examples }: { models: Record<string, Mode};return (- <div className="flex min-h-svh min-w-0 flex-col">+ <div className="flex min-h-content min-w-0 flex-col"><MarketingHeader title="Ad Multiplier" active="multiplier" engine={engine} onEngine={setEngine} /><div className="mx-auto w-full min-w-0 max-w-[1180px] flex-1 px-3 pt-6 pb-20 sm:px-6 sm:pt-10"><div className="pb-6 text-center">diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsxdeleted file mode 100644index c9091163..00000000--- a/src/components/app-sidebar.tsx+++ /dev/null@@ -1,838 +0,0 @@-"use client";--import dynamic from "next/dynamic";-import { useLinkStatus } from "next/link";-import { usePathname, useSearchParams } from "next/navigation";-import { useTheme } from "next-themes";-import { Fragment, Suspense, useCallback, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";-import { ChevronRight, ChevronsUpDown, Clapperboard, Cpu, LogIn, LogOut, Moon, Plus, Search, Settings2, Sun, UserPlus, X } from "lucide-react";-import {- Sidebar,- SidebarContent,- SidebarFooter,- SidebarGroup,- SidebarGroupLabel,- SidebarHeader,- SidebarInset,- SidebarMenu,- SidebarMenuButton,- SidebarMenuItem,- SidebarProvider,- SidebarRail,- SidebarSeparator,- SidebarTrigger,- useSidebar,-} from "@/components/ui/sidebar";-import { Button } from "@/components/ui/button";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuLabel,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";-import { Kbd } from "@/components/ui/kbd";-import { Skeleton } from "@/components/ui/skeleton";-import { CommandPalette, CommandPaletteProvider, useCommandPalette } from "@/components/command-palette";-import { PlaceholdersOnChip } from "@/components/demo-mode";-import { placeholdersOn } from "@/lib/demo-mode";-import { GitHubMark } from "@/components/github-mark";-import { IntentLink } from "@/components/intent-link";-import { JobNotifications } from "@/components/job-notifications";-import { NAV, type NavGroupDef } from "@/components/nav-items";-import { SkillBuilderProvider } from "@/components/skills/skill-builder-provider";-import { awayFix, openConnect, useComputerSupport } from "@/components/gpu/open-connect";-import { usePagePlace } from "@/components/gpu/use-page-place";-import { ownGpuOf, signInHref, signOut, useEngineMode, useHydrated, useStatus, useViewer, VIEWER_KEY, type StatusInfo } from "@/lib/api";-import { deviceLabel } from "@/lib/gpu/readiness";-import { safeLink, useInterest } from "@/lib/hosted";-import { useModKey } from "@/lib/keys";-import { fullScreenStudio, groupId, NAV_CLOSED_KEY, navActive, NEW_CREATION_HREF, parseClosed, scrollFades, sidebarCookie, SIDEBAR_STATE_SCRIPT, sidebarOpenFromCookie } from "@/lib/nav";-import { isPlainClick } from "@/lib/use-tapped-tab";-import { cn } from "@/lib/utils";--// The note of a tab that runs the person's jobs on their own computer's ComfyUI (only for someone whose runs go there).-const ComputerNote = dynamic(() => import("@/components/gpu/computer-runner").then((m) => m.ComputerNote), { ssr: false });--const NO_SEARCH = new URLSearchParams();--function StatusDot({ ok }: { ok: boolean | undefined }) {- return <span className={cn("size-1.5 shrink-0 rounded-full", ok ? "bg-success" : "bg-subtle-foreground")} />;-}--/**- * The row's label. While the clicked row's route loads (useLinkStatus) it marks the row, which tints- * (has-[[data-pending]]), so the click shows at once even when the next page takes a moment. Nothing- * animates: a shimmer or pulse here costs main-thread frames during the very navigation it waits for- * (measured: about +100 ms per click with the CPU slowed 4x).- */-function NavLabel({ children }: { children: React.ReactNode }) {- const { pending } = useLinkStatus();- return (- <span data-pending={pending || undefined} className={cn(pending && "opacity-70")}>- {children}- </span>- );-}--/**- * The row just clicked: the open page's row from the next frame on, while its route loads, in every group at once (the- * address says again once the route has moved: TappedRowReset).- */-let tappedRow: string | null = null;-const tappedListeners = new Set<() => void>();--function setTappedRow(href: string | null) {- if (tappedRow === href) return;- tappedRow = href;- for (const l of tappedListeners) l();-}--function subscribeTapped(cb: () => void) {- tappedListeners.add(cb);- return () => {- tappedListeners.delete(cb);- };-}--/** Clears the clicked row once the address changes (the route moved, or Back / Forward). Inside Suspense: runtime data. */-function TappedRowReset() {- const pathname = usePathname();- const search = useSearchParams().toString();- useLayoutEffect(() => setTappedRow(null), [pathname, search]);- return null;-}--/** How many rows above and below the open page's row prefetch once the page is idle (the rest wait for a hover, touch or focus). */-const NEAR_ROWS = 2;--function Items({ group, pathname, search }: { group: NavGroupDef; pathname: string; search: URLSearchParams }) {- const hrefs = group.items.map((i) => i.href);- // The open page's row: the rows next to it are the likeliest next taps.- const here = group.items.findIndex((i) => navActive(i.href, pathname, search, hrefs));- const tapped = useSyncExternalStore(subscribeTapped, () => tappedRow, () => null);- const [at, query] = tapped ? tapped.split("?") : [pathname];- const where = tapped ? new URLSearchParams(query ?? "") : search;- return group.items.map((item, i) => {- const active = navActive(item.href, at, where, hrefs);- return (- <SidebarMenuItem key={item.href} className={cn(group.compact && "min-w-0")}>- <SidebarMenuButton- asChild- isActive={active}- tooltip={item.label}- className={cn(- "h-8 text-[13px] has-[[data-pending]]:bg-sidebar-accent data-[active=true]:font-semibold",- group.compact && "h-7 gap-1.5 px-2 text-[12px]",- )}- >- <IntentLink- href={item.href}- eager={item.eager}- settled={here >= 0 && i !== here && Math.abs(i - here) <= NEAR_ROWS}- onClick={(e) => isPlainClick(e) && setTappedRow(item.href)}- aria-current={active ? "page" : undefined}- title={group.compact && item.short ? item.label : undefined}- >- <item.icon />- <NavLabel>{group.compact ? (item.short ?? item.label) : item.label}</NavLabel>- </IntentLink>- </SidebarMenuButton>- </SidebarMenuItem>- );- });-}--/** Query links (`?tab=favorites`) need the search params, which only exist at request time. */-function WithSearch({ group, pathname }: { group: NavGroupDef; pathname: string }) {- return <Items group={group} pathname={pathname} search={useSearchParams()} />;-}--/** Reads the pathname (runtime data) inside Suspense so routes can still prerender. */-function ActiveItems({ group }: { group: NavGroupDef }) {- const pathname = usePathname();- if (!group.items.some((i) => i.href.includes("?"))) return <Items group={group} pathname={pathname} search={NO_SEARCH} />;- return (- <Suspense fallback={<Items group={group} pathname={pathname} search={NO_SEARCH} />}>- <WithSearch group={group} pathname={pathname} />- </Suspense>- );-}--/** The folded groups: remembered in this browser, else DEFAULT_NAV_CLOSED, also on the server. */-function readClosed(): string[] {- try {- return parseClosed(typeof window === "undefined" ? null : localStorage.getItem(NAV_CLOSED_KEY));- } catch {- return parseClosed(null);- }-}--function NavGroup({ group, open, onToggle }: { group: NavGroupDef; open: boolean; onToggle: () => void }) {- const id = groupId(group.label);- return (- <SidebarGroup data-nav-group={id} data-open={open ? "true" : "false"} className="group/nav py-1">- {group.collapsible ? (- <SidebarGroupLabel asChild className="text-[11px] font-medium tracking-wide uppercase">- <button- type="button"- data-nav-toggle- aria-expanded={open}- aria-controls={`nav-${id}`}- onClick={onToggle}- className="w-full cursor-pointer hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"- >- {group.label}- {/* Folded, the label says how much is inside (a single row needs no count). */}- <span className="ml-auto font-normal tracking-normal tabular-nums group-data-[open=true]/nav:hidden">{group.items.length > 1 && group.items.length}</span>- <ChevronRight className="ml-1 size-3.5 transition-transform group-data-[open=true]/nav:ml-auto group-data-[open=true]/nav:rotate-90" />- </button>- </SidebarGroupLabel>- ) : (- <SidebarGroupLabel className="text-[11px] font-medium tracking-wide uppercase">{group.label}</SidebarGroupLabel>- )}- <SidebarMenu id={`nav-${id}`} data-nav-items className={cn(group.compact && "grid grid-cols-2 gap-0.5")}>- <Suspense fallback={<Items group={group} pathname="" search={NO_SEARCH} />}>- <ActiveItems group={group} />- </Suspense>- </SidebarMenu>- </SidebarGroup>- );-}--/**- * Inline script that runs while the HTML is parsed: the server always renders the sidebar- * expanded, this applies the remembered state before the first paint. On the client it renders as- * inert text/plain (React warns about executable scripts it renders itself).- */-function SidebarStateScript() {- return (- <script- type={typeof window === "undefined" ? "text/javascript" : "text/plain"}- suppressHydrationWarning- dangerouslySetInnerHTML={{ __html: SIDEBAR_STATE_SCRIPT }}- />- );-}--/**- * Scrolls `el` into the scrolling `box` as little as it takes, its top first when it doesn't fit, clear of the box's- * faded edges (24px above, 40px below).- */-function reveal(box: HTMLElement | null, el: Element | null | undefined) {- if (!box || !el) return;- const b = box.getBoundingClientRect();- const r = el.getBoundingClientRect();- const below = r.bottom + 40 - b.bottom;- if (below > 0) box.scrollTop += Math.min(below, Math.max(0, r.top - b.top - 24));- else if (r.top - 24 < b.top) box.scrollTop -= b.top - r.top + 24;-}--/**- * Brings the open page's row into view when the page changes: with Studios open, the rows below it (Settings)- * sit below the fold. Inside Suspense: the pathname is runtime data.- */-function RevealActive({ box }: { box: React.RefObject<HTMLDivElement | null> }) {- const pathname = usePathname();- useEffect(() => {- const el = box.current;- if (!el) return;- // Again whenever the list's box changes size (the guest's Sign up row arrives and pushes it down), until the- // person scrolls or clicks in it themselves.- let theirs = false;- const show = () => theirs || reveal(el, el.querySelector('[data-active="true"]'));- const mine = () => (theirs = true);- const frame = requestAnimationFrame(show);- const resized = new ResizeObserver(show);- resized.observe(el);- for (const e of ["wheel", "touchstart", "pointerdown", "keydown"]) el.addEventListener(e, mine, { passive: true });- return () => {- cancelAnimationFrame(frame);- resized.disconnect();- for (const e of ["wheel", "touchstart", "pointerdown", "keydown"]) el.removeEventListener(e, mine);- };- }, [pathname, box]);- return null;-}--/** Tells the shell which page is open (the pathname is runtime data, so it's read inside Suspense). */-function PathWatcher({ onPath }: { onPath: (pathname: string) => void }) {- const pathname = usePathname();- useEffect(() => onPath(pathname), [pathname, onPath]);- return null;-}--interface ShellState {- /** The page that's open (PathWatcher keeps it current). */- path: string;- /** The expanded/collapsed choice in the cookie. */- remembered: boolean;- /** Opened or closed by hand in a full-screen studio (fullScreenStudio): lasts while you stay in it. */- peek: { studio: string; open: boolean } | null;-}--/**- * SidebarProvider that starts from the remembered expanded/collapsed state (the shadcn cookie). In a- * full-screen studio (fullScreenStudio) the sidebar folds to its rail instead; opening it there- * lasts until you leave that studio, and neither writes the cookie.- */-export function SidebarShell({ children, style }: { children: React.ReactNode; style?: React.CSSProperties }) {- // The first client render reads the cookie and the URL itself, as the pre-paint script does, so hydration matches.- const [state, setState] = useState<ShellState>(() => ({- path: typeof window === "undefined" ? "" : window.location.pathname,- remembered: typeof document === "undefined" ? true : sidebarOpenFromCookie(document.cookie),- peek: null,- }));- const studio = fullScreenStudio(state.path);- const open = studio ? state.peek?.studio === studio && state.peek.open : state.remembered;- // Both callbacks are stable, so a new page alone leaves the provider's context as it was and the- // sidebar doesn't render again on every navigation. A change is filed by the page it applies to- // (the state's own path), never by the page a stale callback was made on.- const onOpenChange = useCallback(- (value: boolean) =>- setState((s) => {- const at = fullScreenStudio(s.path);- return at ? { ...s, peek: { studio: at, open: value } } : { ...s, remembered: value };- }),- [],- );- const onPath = useCallback(- (path: string) =>- setState((s) => {- if (s.path === path) return s;- const at = fullScreenStudio(path);- return { ...s, path, peek: at && s.peek?.studio === at ? s.peek : null };- }),- [],- );- // Only the remembered choice reaches the cookie: a studio's fold or peek never does.- useEffect(() => {- if (sidebarOpenFromCookie(document.cookie) !== state.remembered) document.cookie = sidebarCookie(state.remembered);- }, [state.remembered]);- return (- <SidebarProvider open={open} onOpenChange={onOpenChange} persistOpen={false} style={style}>- <Suspense fallback={null}>- <PathWatcher onPath={onPath} />- </Suspense>- {children}- </SidebarProvider>- );-}--/** The first stop for keyboard users: jumps past the sidebar to the page (WCAG 2.4.1). */-function SkipLink() {- return (- <a- href="#content"- onClick={(e) => {- // Focus the page without adding #content to the URL (Settings reads its hash for deep links).- const main = document.getElementById("content");- if (!main) return;- e.preventDefault();- main.focus();- }}- className="sr-only rounded-md bg-background px-3 py-2 text-[13px] font-medium shadow-strong focus:not-sr-only focus:fixed focus:top-2 focus:left-2 focus:z-50 focus:outline-2 focus:outline-ring"- >- Skip to content- </a>- );-}--/** The app frame: sidebar + inset sheet. Used by the studio layout and the root not-found page. */-export function StudioChrome({ children }: { children: React.ReactNode }) {- return (- // The shell stays static: the remembered collapsed state is read on the client (and applied- // before first paint by AppSidebar's inline script), not from cookies() on the server.- <CommandPaletteProvider>- {/* Make a skill from any result's ⋯ menu: a page's, the ⌘K palette's and a job notification's viewer. */}- <SkillBuilderProvider>- <SidebarShell style={{ "--sidebar-width": "15.5rem", "--sidebar-width-icon": "3.25rem" } as React.CSSProperties}>- <SkipLink />- <AppSidebar />- <SidebarInset- id="content"- tabIndex={-1}- className="min-h-svh min-w-0 outline-none md:m-0 md:mt-2 md:rounded-none md:rounded-tl-xl md:border-t-[0.5px] md:border-l-[0.5px] md:shadow-[-2px_0_6px_rgba(0,0,0,.02)] md:peer-data-[variant=inset]:m-0 md:peer-data-[variant=inset]:mt-2 md:peer-data-[variant=inset]:rounded-none md:peer-data-[variant=inset]:rounded-tl-xl"- >- {children}- </SidebarInset>- <CommandPalette />- <JobNotifications />- </SidebarShell>- </SkillBuilderProvider>- </CommandPaletteProvider>- );-}--/**- * Keeps a vertical scroller's fades (.fade-y) in sync: data-more-above / data-more-below, and how deep- * each fade is (scrollFades), so a fade hints at items past the edge without dimming a row that fits.- */-function useScrollFades<T extends HTMLElement>() {- const ref = useRef<T>(null);- useEffect(() => {- const el = ref.current;- if (!el) return;- const update = () => {- const { above, below } = scrollFades(el);- el.toggleAttribute("data-more-above", above > 0);- el.toggleAttribute("data-more-below", below > 0);- el.style.setProperty("--fade-t", `${above}px`);- el.style.setProperty("--fade-b", `${below}px`);- };- update();- el.addEventListener("scroll", update, { passive: true });- const ro = new ResizeObserver(update);- ro.observe(el);- for (const child of el.children) ro.observe(child);- return () => {- el.removeEventListener("scroll", update);- ro.disconnect();- };- }, []);- return ref;-}--/** "Search ⌘K": opens the palette (the keycaps only where there's a keyboard). */-function SearchRow() {- const palette = useCommandPalette();- const { isMobile, setOpenMobile } = useSidebar();- const mod = useModKey();- return (- <SidebarMenuItem>- <SidebarMenuButton- tooltip={`Search (${mod} K)`}- className="h-8 text-[13px]"- aria-keyshortcuts="Meta+K Control+K"- aria-haspopup="dialog"- onClick={() => {- if (isMobile) setOpenMobile(false);- palette.setOpen(true);- }}- >- <Search />- <span>Search</span>- <span className="ml-auto flex gap-0.5 group-data-[collapsible=icon]:hidden [@media(hover:none)]:hidden">- <Kbd>{mod}</Kbd>- <Kbd>K</Kbd>- </span>- </SidebarMenuButton>- </SidebarMenuItem>- );-}--/**- * Runs while the HTML is parsed: `<html data-viewer="owner">` in a browser where the owner was signed in last time, so- * the row kept for "Sign up / Log in" (or an account's menu) isn't drawn and then taken away on every page load.- */-const VIEWER_SCRIPT = `(function(){try{var v=localStorage.getItem("${VIEWER_KEY}");if(v)document.documentElement.setAttribute("data-viewer",v)}catch(e){}})()`;--/** The row's place while the viewer isn't known (in the server's shell too: ViewerRow reads the query, so it's the fallback there). */-function ViewerRowPlaceholder() {- return (- <>- <script type={typeof window === "undefined" ? "text/javascript" : "text/plain"} suppressHydrationWarning dangerouslySetInnerHTML={{ __html: VIEWER_SCRIPT }} />- <SidebarMenuItem aria-hidden className="mt-1 mb-2 h-8 group-data-[collapsible=icon]:h-[70px] [html[data-viewer='owner']_&]:hidden [html[data-viewer='account']_&]:hidden" />- </>- );-}--/**- * Public sign-up, signed out: "Sign up" and "Log in", coming back to this page with its query (a preset picked…). Until- * the viewer is known the row keeps its height, so the menu under it doesn't move when it comes (except in a browser the- * owner or an account used last: they get no row here). Under Suspense: it reads the path.- */-function ViewerRow() {- const viewer = useViewer().data;- // This boundary can hydrate after the viewer query resolved: its first render keeps the server's placeholder.- const hydrated = useHydrated();- const pathname = usePathname();- const search = useSearchParams().toString();- const here = search ? `${pathname}?${search}` : pathname;- const kind = !viewer || !hydrated ? undefined : viewer.owner ? "owner" : viewer.account ? "account" : viewer.publicSignup ? "guest" : "owner";- useEffect(() => {- if (!kind) return;- try {- localStorage.setItem(VIEWER_KEY, kind);- } catch {}- document.documentElement.setAttribute("data-viewer", kind);- }, [kind]);- if (!kind) return <ViewerRowPlaceholder />;- if (kind !== "guest") return null;- return (- <SidebarMenuItem className="mt-1 mb-2 flex gap-1.5 group-data-[collapsible=icon]:flex-col">- <SidebarMenuButton asChild tooltip="Sign up free" className="h-8 flex-1 justify-center bg-primary text-[13px] text-primary-foreground hover:bg-primary/90 hover:text-primary-foreground">- <a href={signInHref("signup", here)}>- <UserPlus />- <span>Sign up</span>- </a>- </SidebarMenuButton>- <SidebarMenuButton asChild tooltip="Log in" className="h-8 flex-1 justify-center border border-sidebar-border text-[13px]">- <a href={signInHref("login", here)}>- <LogIn />- <span>Log in</span>- </a>- </SidebarMenuButton>- </SidebarMenuItem>- );-}--/**- * "Your GPU" in the status strip: a visitor's own (public sign-up), never the install's, or the owner's computer. A- * guest is sent to sign up first; anyone else without one opens "Connect your GPU"; a connected one says whether it- * answers.- */-function YourGpuChip({ gpu, guest, hosted }: { gpu: NonNullable<StatusInfo["viewer"]>["gpu"]; guest: boolean; hosted?: boolean }) {- const cls = "flex w-full flex-col gap-1 rounded-md px-2 py-1.5 text-left text-[12px] text-muted-foreground transition-colors hover:bg-accent group-data-[collapsible=icon]:hidden";- const g = gpu;- // ComfyUI on this computer is closed, or runs without Fuobe's setting: the finder, at that step (elsewhere: /connect).- const fix = awayFix(g.connected ? g : undefined, useComputerSupport());- if (g.connected) {- const vram = g.vramBytes ? `${Math.round(g.vramBytes / 2 ** 30)} GB` : "";- const inner = (- <>- <span className="flex items-center gap-2">- <StatusDot ok={g.online} /> Your GPU- <span className="ml-auto">{g.online ? "online" : g.comfy === "down" ? "ComfyUI not running" : g.comfy === "no-setting" ? "needs a setting" : "offline"}</span>- </span>- {(g.device || vram || g.mode === "computer") && (- <span className="truncate text-[11px]">{[g.mode === "computer" && "Your computer", deviceLabel(g.device), vram && `${vram} VRAM`].filter(Boolean).join(" · ")}</span>- )}- </>- );- return fix ? (- <button type="button" className={cls} onClick={fix}>- {inner}- </button>- ) : (- <IntentLink href="/connect" className={cls}>- {inner}- </IntentLink>- );- }- const body = (- <span className="flex items-center gap-2">- <StatusDot ok={false} /> Your GPU- {/* Runs go to this studio's GPUs too (hosted runs): one's own is an option. */}- <span className={cn("ml-auto font-medium", hosted ? "text-muted-foreground" : "text-brand-text")}>{hosted ? "Optional" : "Connect"}</span>- </span>- );- return guest ? (- <a href={signInHref("signup", "/connect")} className={cls}>- {body}- </a>- ) : (- <button type="button" className={cls} onClick={() => openConnect(true)}>- {body}- </button>- );-}--/**- * The balance chip (a studio with a billing service, src/server/billing.ts): the service's own words for what the- * account has left and when it refills, and a menu with its detail lines, its links, its offer, and the way to run for- * free on one's own GPU or keys.- */-function BalanceChip({ viewer }: { viewer: NonNullable<StatusInfo["viewer"]> }) {- const b = viewer.balance!;- const interest = useInterest();- const cls = "flex w-full flex-col gap-1 rounded-md px-2 py-1.5 text-left text-[12px] text-muted-foreground transition-colors hover:bg-accent group-data-[collapsible=icon]:hidden";- const refill = b.refillAt ? refillWords(b.refillAt) : null;- const action = safeLink(b.action?.url);- return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button type="button" className={cls} aria-label={`${b.chip}${refill ? `, ${refill}` : ""}`}>- <span className="flex items-center gap-2">- <StatusDot ok={b.amount > 0} /> <span className="truncate font-medium text-foreground">{b.chip}</span>- {refill && <span className="ml-auto shrink-0">{refill}</span>}- </span>- {b.sub && <span className="truncate text-[11px]">{b.sub}</span>}- </button>- </DropdownMenuTrigger>- <DropdownMenuContent side="top" align="start" className="w-64">- <DropdownMenuLabel className="text-[12px] font-normal text-muted-foreground">{b.text}</DropdownMenuLabel>- {b.detail.map((d, i) => (- <div key={i} className="flex justify-between gap-3 px-2 py-1 text-[12px]">- <span className="text-muted-foreground">{d.label}</span>- <span className="text-right">{d.text}</span>- </div>- ))}- <DropdownMenuSeparator />- {action && b.action && (- <DropdownMenuItem asChild>- <a href={action} target={action.startsWith("/") ? undefined : "_blank"} rel="noopener noreferrer">- {b.action.label}- </a>- </DropdownMenuItem>- )}- {b.offer && <DropdownMenuItem onSelect={() => interest.mutate(b.offer!.key)}>{b.offer.label}</DropdownMenuItem>}- {(viewer.links ?? []).map((l, i) => {- const href = safeLink(l.url);- return href ? (- <DropdownMenuItem key={i} asChild>- <a href={href} target={href.startsWith("/") ? undefined : "_blank"} rel="noopener noreferrer">- {l.label}- </a>- </DropdownMenuItem>- ) : null;- })}- <DropdownMenuItem asChild>- <IntentLink href="/connect">- <Cpu /> Use your own GPU or keys (free)- </IntentLink>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- );-}--/** "refills in 5 h", in the visitor's own time. */-function refillWords(at: number): string {- const ms = at - Date.now();- if (ms <= 0) return "refills soon";- const h = Math.round(ms / 3_600_000);- return h >= 1 ? `refills in ${h} h` : `refills in ${Math.max(1, Math.round(ms / 60_000))} min`;-}--/**- * Who is signed in (public sign-up): an account's email, with Settings, Your GPU and Sign out. Nothing- * for the owner or a guest. In the rail it's the initial alone; on a phone the menu opens upward. Until hydrated it is- * the server's HTML (no row), even when the viewer query has already answered; until the viewer is known, a browser an- * account used last keeps the row's height, so the footer doesn't move when it comes.- */-function AccountRow() {- const hydrated = useHydrated();- const viewer = useViewer().data;- const account = hydrated ? viewer?.account : undefined;- const { isMobile } = useSidebar();- if (!account) return hydrated && viewer ? null : <div aria-hidden className="hidden h-9 group-data-[collapsible=icon]:h-8 [html[data-viewer='account']_&]:block" />;- return (- <SidebarMenu>- <SidebarMenuItem>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <SidebarMenuButton className="h-9 px-1.5 text-[13px] group-data-[collapsible=icon]:p-1! data-[state=open]:bg-sidebar-accent" aria-label={`Account: ${account.email}`}>- <span aria-hidden className="grid size-6 shrink-0 place-items-center rounded-full bg-brand-faint text-[11px] font-semibold text-brand-text">- {account.email.charAt(0).toUpperCase()}- </span>- <span className="min-w-0 flex-1 truncate" title={account.email}>- {account.email}- </span>- <ChevronsUpDown className="text-muted-foreground" />- </SidebarMenuButton>- </DropdownMenuTrigger>- {/* As wide as the email (on one line, up to 22rem), never narrower than the row: an address breaks only when it must,- and the menu keeps clear of the screen's edges. */}- <DropdownMenuContent- side={isMobile ? "top" : "right"}- align="end"- collisionPadding={8}- className="w-max max-w-[min(22rem,var(--radix-dropdown-menu-content-available-width))] min-w-[max(14rem,var(--radix-dropdown-menu-trigger-width))]"- >- <DropdownMenuLabel className="font-normal">- <span className="block text-[11px]">Signed in as</span>- <span className="block text-[13px] [overflow-wrap:anywhere] text-foreground">{account.email}</span>- </DropdownMenuLabel>- <DropdownMenuSeparator />- <DropdownMenuItem asChild>- <IntentLink href="/settings">- <Settings2 /> Settings- </IntentLink>- </DropdownMenuItem>- <DropdownMenuItem asChild>- <IntentLink href="/connect">- <Cpu /> Your GPU- </IntentLink>- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem onSelect={() => void signOut()}>- <LogOut /> Sign out- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </SidebarMenuItem>- </SidebarMenu>- );-}--export function AppSidebar() {- const { resolvedTheme, setTheme } = useTheme();- const { isMobile, setOpenMobile } = useSidebar();- // On phones the sidebar is a drawer over the page: any link tapped in it closes it.- const closeOnLink = (e: React.MouseEvent) => {- if (isMobile && (e.target as Element).closest("a[href]")) setOpenMobile(false);- };- const content = useScrollFades<HTMLDivElement>();- // Until hydrated, the server's (status-less) sidebar: a status that lands mid-hydration must not change it.- const hydrated = useHydrated();- const statusData = useStatus().data;- const status = hydrated ? statusData : undefined;- const computer = useViewer().data?.computer === true && hydrated;- const cloud = status && (status.providers.fal?.configured || status.providers.replicate?.configured);- const comfy = status?.providers.comfyui?.configured;- const mode = useEngineMode();- // The owner's GPU as "Your GPU": on the owner's computer, or (a hosted studio with nothing connected) one to connect.- const place = usePagePlace();- // Not in Paid APIs only mode: ComfyUI isn't used there, wherever it runs.- const ownerGpu = status && !status.viewer && mode !== "cloud" && (status.ownerGpu || (place === "hosted" && !comfy)) ? (ownGpuOf(status) ?? { connected: false }) : null;- const [closed, setClosed] = useState(readClosed);- const toggle = useCallback((id: string) => {- setClosed((c) => {- const next = c.includes(id) ? c.filter((x) => x !== id) : [...c, id];- try {- localStorage.setItem(NAV_CLOSED_KEY, JSON.stringify(next));- } catch {}- return next;- });- }, []);-- return (- <>- <Sidebar variant="inset" collapsible="icon">- {/* The whole sidebar is the app's navigation landmark (the page is the one main landmark). */}- <nav aria-label="Main" className="flex min-h-0 w-full flex-1 flex-col">- <SidebarHeader className="pt-3" onClick={closeOnLink}>- <div className="flex h-9 items-center justify-between gap-2 px-1 group-data-[collapsible=icon]:justify-center">- <IntentLink href="/" eager className="flex items-center gap-2 group-data-[collapsible=icon]:hidden">- <span className="grid size-7 place-items-center rounded-lg bg-primary text-primary-foreground shadow-soft">- <Clapperboard className="size-4" />- </span>- <span className="font-heading text-[22px] leading-none">Fuobe</span>- </IntentLink>- {isMobile ? (- <Button variant="ghost" size="icon-sm" className="text-muted-foreground" onClick={() => setOpenMobile(false)} aria-label="Close menu">- <X />- </Button>- ) : (- <SidebarTrigger className="text-muted-foreground" />- )}- </div>- <SidebarMenu>- <Suspense fallback={<ViewerRowPlaceholder />}>- <ViewerRow />- </Suspense>- <SearchRow />- <SidebarMenuItem>- <SidebarMenuButton asChild tooltip="New creation" className="h-8 text-[13px] has-[[data-pending]]:bg-sidebar-accent">- <IntentLink href={NEW_CREATION_HREF} eager>- <Plus />- <NavLabel>New creation</NavLabel>- </IntentLink>- </SidebarMenuButton>- </SidebarMenuItem>- </SidebarMenu>- </SidebarHeader>- <SidebarContent ref={content} onClick={closeOnLink} className="scrollbar-none fade-y group-data-[collapsible=icon]:overflow-y-auto">- {NAV.map((group, i) => {- const id = groupId(group.label);- return (- <Fragment key={id}>- {/* Icon mode hides the group labels: a hairline keeps the groups apart. */}- {i > 0 && <SidebarSeparator className="my-1 hidden group-data-[collapsible=icon]:block" />}- <NavGroup- group={group}- open={!group.collapsible || !closed.includes(id)}- onToggle={() => {- toggle(id);- // A group opened near the bottom scrolls up into view, once its rows are on the page.- if (closed.includes(id)) requestAnimationFrame(() => reveal(content.current, content.current?.querySelector(`[data-nav-group="${id}"]`)));- }}- />- </Fragment>- );- })}- <Suspense fallback={null}>- <RevealActive box={content} />- <TappedRowReset />- </Suspense>- </SidebarContent>- <SidebarFooter className="gap-1 border-t border-sidebar-border" onClick={closeOnLink}>- {computer && <ComputerNote />}- {status?.viewer ? (- status.viewer.balance ? (- <BalanceChip viewer={status.viewer} />- ) : (- <YourGpuChip gpu={status.viewer.gpu} guest={status.viewer.kind === "guest"} hosted={!!status.viewer.hosted} />- )- ) : ownerGpu ? (- <>- {mode !== "open" && (- <IntentLink href="/settings" className="flex items-center gap-2 rounded-md px-2 py-1.5 text-[12px] text-muted-foreground transition-colors hover:bg-accent group-data-[collapsible=icon]:hidden">- <StatusDot ok={!!cloud} /> Cloud models- <span className="ml-auto">{cloud ? "connected" : "add key"}</span>- </IntentLink>- )}- <YourGpuChip gpu={ownerGpu} guest={false} />- {mode !== "both" && (- <div className="flex flex-col gap-1.5 px-2 pb-1 text-[11px] text-muted-foreground group-data-[collapsible=icon]:hidden">- <span>{mode === "open" ? "Open source only" : "Paid APIs only"}</span>- </div>- )}- </>- ) : !status ? (- // Not known yet: no "add key / offline" the install may not have, for a visitor who never sees them.- <div aria-hidden className="flex h-[30px] items-center px-2 group-data-[collapsible=icon]:hidden">- <Skeleton className="h-3 w-2/3" />- </div>- ) : (- <IntentLink- href="/settings"- className="flex flex-col gap-1.5 rounded-md px-2 py-1.5 text-[12px] text-muted-foreground transition-colors hover:bg-accent group-data-[collapsible=icon]:hidden"- >- {mode !== "open" && (- <span className="flex items-center gap-2">- <StatusDot ok={cloud} /> Cloud models- <span className="ml-auto">{cloud ? "connected" : "add key"}</span>- </span>- )}- {mode !== "cloud" && (- <span className="flex items-center gap-2">- <StatusDot ok={comfy} /> ComfyUI- <span className="ml-auto">{comfy ? "online" : "offline"}</span>- </span>- )}- {mode !== "both" && <span className="text-[11px] text-muted-foreground">{mode === "open" ? "Open source only" : "Paid APIs only"}</span>}- </IntentLink>- )}- {/* Placeholder results, only while the owner has them on (Settings, for a tour): a click turns them off. Its own- button beside the status link (a button never sits inside a link). */}- {status && !status.viewer && placeholdersOn(status.demoMode) && (- <>- <div className="-mt-1 px-2 pb-1 group-data-[collapsible=icon]:hidden">- <PlaceholdersOnChip />- </div>- {/* Collapsed to icons: the same way out, as a round mark. */}- <div className="hidden justify-center pb-1 group-data-[collapsible=icon]:flex">- <PlaceholdersOnChip icon />- </div>- </>- )}- <SidebarMenu className="flex-row gap-1 group-data-[collapsible=icon]:flex-col">- <SidebarMenuItem className="min-w-0 flex-1">- <SidebarMenuButton tooltip="Toggle theme" className="h-8 text-[13px]" onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}>- <Sun className="hidden dark:block" />- <Moon className="dark:hidden" />- <span className="hidden dark:inline">Light mode</span>- <span className="dark:hidden">Dark mode</span>- </SidebarMenuButton>- </SidebarMenuItem>- <SidebarMenuItem className="shrink-0">- <SidebarMenuButton asChild tooltip="Source code on GitHub" className="h-8 w-8 justify-center p-0 text-[13px]">- <a href="https://github.com/workingprototype/fuobe" target="_blank" rel="noreferrer" title="Source code on GitHub">- <GitHubMark />- <span className="sr-only">Source code on GitHub</span>- </a>- </SidebarMenuButton>- </SidebarMenuItem>- </SidebarMenu>- <AccountRow />- </SidebarFooter>- </nav>- <SidebarRail />- </Sidebar>- <SidebarStateScript />- </>- );-}diff --git a/src/components/assist-view.tsx b/src/components/assist-view.tsxindex 6a962a20..e30c2259 100644--- a/src/components/assist-view.tsx+++ b/src/components/assist-view.tsx@@ -7,7 +7,7 @@ import { useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Skeleton } from "@/components/ui/skeleton";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Switch } from "@/components/ui/switch";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { EngineSwitch } from "@/components/studio/engine-switch";@@ -150,9 +150,8 @@ export function AssistView() {);return (- <div className="flex h-svh min-w-0 flex-col md:h-[calc(100svh-0.5rem)]">+ <div className="flex h-content min-w-0 flex-col"><header className="flex h-14 shrink-0 items-center gap-1.5 px-3 sm:px-6">- <SidebarTrigger className="md:hidden" /><RailButton /><div className="flex min-w-0 flex-1 items-center gap-2">{project && (@@ -193,6 +192,7 @@ export function AssistView() {)}{thread && <ChatMenu chat={thread} onDeleted={() => go(null)} />}</div>+ <PhoneNavButton /></header>{!id ? (diff --git a/src/components/assist/memory-view.tsx b/src/components/assist/memory-view.tsxindex 91eaa174..872ee1ba 100644--- a/src/components/assist/memory-view.tsx+++ b/src/components/assist/memory-view.tsx@@ -19,7 +19,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, Dimport { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty";import { Label } from "@/components/ui/label";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { Textarea } from "@/components/ui/textarea";import { useIsOwner, useIsVisitor } from "@/lib/api";@@ -64,10 +64,9 @@ export function MemoryView({ projectId }: { projectId?: string } = {}) {const projectName = (id: string | null) => projects.data?.find((p) => p.id === id);return (- <div className={cn("flex min-w-0 flex-col", !projectId && "min-h-svh")}>+ <div className={cn("flex min-w-0 flex-col", !projectId && "min-h-content")}>{!projectId && (- <header className="sticky top-0 z-20 flex h-14 items-center gap-1.5 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-1.5 bg-background/85 px-3 backdrop-blur sm:px-6"><RailButton /><h1 className="font-heading text-[22px] leading-none">Memory</h1>{owner && (@@ -81,6 +80,7 @@ export function MemoryView({ projectId }: { projectId?: string } = {}) {</Button></div>)}+ <PhoneNavButton /></header>)}<div className={cn("w-full max-w-[900px] min-w-0 flex-1 px-3 pb-16 sm:px-6", projectId ? "pt-2" : "pt-4 md:pt-8")}>diff --git a/src/components/assist/project-view.tsx b/src/components/assist/project-view.tsxindex 40956cff..65c7a960 100644--- a/src/components/assist/project-view.tsx+++ b/src/components/assist/project-view.tsx@@ -37,7 +37,7 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTriggeimport { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { Textarea } from "@/components/ui/textarea";@@ -97,9 +97,8 @@ function Project({ p }: { p: AssistProject }) {const [tab, setTab] = useState("chats");return (- <div className="flex min-h-svh min-w-0 flex-col">- <header className="sticky top-0 z-20 flex h-14 items-center gap-1.5 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <div className="flex min-h-content min-w-0 flex-col">+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-1.5 bg-background/85 px-3 backdrop-blur sm:px-6"><RailButton /><ProjectDot project={p} className="ml-1" /><h1 className="min-w-0 truncate font-heading text-[22px] leading-none">{p.name}</h1>@@ -120,6 +119,7 @@ function Project({ p }: { p: AssistProject }) {</DropdownMenuContent></DropdownMenu></div>+ <PhoneNavButton /></header><div className="mx-auto w-full max-w-[860px] min-w-0 flex-1 px-3 pb-16 sm:px-6"><div className="mx-auto max-w-[760px] pt-[6vh] sm:pt-[9vh]">diff --git a/src/components/assist/scheduled-view.tsx b/src/components/assist/scheduled-view.tsxindex eca92693..85e98cab 100644--- a/src/components/assist/scheduled-view.tsx+++ b/src/components/assist/scheduled-view.tsx@@ -18,7 +18,7 @@ import {import { Button } from "@/components/ui/button";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { Switch } from "@/components/ui/switch";import { useNow } from "@/components/studio/use-now";@@ -54,10 +54,9 @@ export function ScheduledView({ projectId }: { projectId?: string } = {}) {const visitor = useIsVisitor();return (- <div className={cn("flex min-w-0 flex-col", !projectId && "min-h-svh")}>+ <div className={cn("flex min-w-0 flex-col", !projectId && "min-h-content")}>{!projectId && (- <header className="sticky top-0 z-20 flex h-14 items-center gap-1.5 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-1.5 bg-background/85 px-3 backdrop-blur sm:px-6"><RailButton /><h1 className="font-heading text-[22px] leading-none">Scheduled</h1>{owner && (@@ -68,6 +67,7 @@ export function ScheduledView({ projectId }: { projectId?: string } = {}) {</Button></div>)}+ <PhoneNavButton /></header>)}<div className={cn("w-full max-w-[900px] min-w-0 flex-1 px-3 pb-16 sm:px-6", projectId ? "pt-2" : "pt-4 md:pt-8")}>diff --git a/src/components/assist/shell.tsx b/src/components/assist/shell.tsxindex 32d13881..c4ddd039 100644--- a/src/components/assist/shell.tsx+++ b/src/components/assist/shell.tsx@@ -25,7 +25,7 @@ import { ProjectDot } from "./project-dot";export function AssistShell({ children }: { children: React.ReactNode }) {return (<div className="flex min-w-0 flex-1">- <aside className="sticky top-0 hidden h-svh w-64 shrink-0 flex-col border-r bg-sidebar/40 xl:flex md:h-[calc(100svh-0.5rem)]" aria-label="Assist">+ <aside className="sticky top-chrome hidden h-content w-64 shrink-0 flex-col border-r bg-sidebar/40 xl:flex" aria-label="Assist"><Suspense fallback={<RailSkeleton />}><Rail /></Suspense>diff --git a/src/components/assist/skills-view.tsx b/src/components/assist/skills-view.tsxindex 3d24848c..2fd7dc5d 100644--- a/src/components/assist/skills-view.tsx+++ b/src/components/assist/skills-view.tsx@@ -23,7 +23,7 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTriggeimport { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { Switch } from "@/components/ui/switch";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";@@ -104,9 +104,8 @@ function Skills() {};return (- <div className="flex min-h-svh min-w-0 flex-col">- <header className="sticky top-0 z-20 flex h-14 items-center gap-1.5 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <div className="flex min-h-content min-w-0 flex-col">+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-1.5 bg-background/85 px-3 backdrop-blur sm:px-6"><RailButton /><h1 className="font-heading text-[22px] leading-none">Skills</h1>{owner && (@@ -131,6 +130,7 @@ function Skills() {</Button></div>)}+ <PhoneNavButton /></header><div className="mx-auto w-full max-w-[1100px] min-w-0 flex-1 px-3 pt-4 pb-16 sm:px-6 md:pt-8"><p className="max-w-2xl text-[15px] text-pretty text-muted-foreground">diff --git a/src/components/audio-tools/clean-voice-tool.tsx b/src/components/audio-tools/clean-voice-tool.tsxindex fc2263eb..b48a9d8e 100644--- a/src/components/audio-tools/clean-voice-tool.tsx+++ b/src/components/audio-tools/clean-voice-tool.tsx@@ -306,7 +306,7 @@ export function CleanVoiceTool({ app }: { app?: { name: string; description: str>{!source && !demo && <ToolHero title={app?.name ?? "Clean up voice"} subtitle={TOOL_SUBTITLE} />}{/* The demo's photo narrows on a short screen, so its play button and Noise on / off stay above the fold. */}- <div className={cn("mx-auto space-y-3", demo ? "max-w-[min(760px,max(480px,calc((100svh_-_356px)*4/3)))] pt-6" : "max-w-[860px]", source ? "pt-4" : !demo && "mt-6")}>+ <div className={cn("mx-auto space-y-3", demo ? "max-w-[min(760px,max(480px,calc((var(--content-h)_-_356px)*4/3)))] pt-6" : "max-w-[860px]", source ? "pt-4" : !demo && "mt-6")}>{demo && (<><CleanVoiceDemo name={app?.name ?? "Clean up voice"} ready={known} />diff --git a/src/components/av/tool-shell.tsx b/src/components/av/tool-shell.tsxindex 367f9642..f44a917a 100644--- a/src/components/av/tool-shell.tsx+++ b/src/components/av/tool-shell.tsx@@ -1,6 +1,6 @@"use client";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { EngineSwitch } from "@/components/studio/engine-switch";import { HubHeaderExtras, useInHub } from "@/components/studio/hub-chrome";import { useEngine } from "@/lib/api";@@ -42,15 +42,15 @@ export function ToolShell({</>);return (- <div className="flex min-h-svh min-w-0 flex-col">- <div className="sticky top-0 z-20 bg-background/85 backdrop-blur">+ <div className="flex min-h-content min-w-0 flex-col">+ <div className="sticky top-chrome z-20 bg-background/85 backdrop-blur"><header className="flex h-14 items-center gap-2 px-3 sm:px-6">- <SidebarTrigger className="md:hidden" /><h1 className="min-w-0 truncate font-heading text-[22px] leading-[1.15]">{title}</h1><div className="ml-auto flex shrink-0 items-center gap-2">{header}{engineSwitch && <EngineSwitch value={engine} onChange={setEngine} selfHostedOnly={selfHostedOnly} />}</div>+ <PhoneNavButton /></header>{tabs}</div>diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsxindex 7eccd14f..dce9a985 100644--- a/src/components/canvas/canvas-editor.tsx+++ b/src/components/canvas/canvas-editor.tsx@@ -35,7 +35,7 @@ import { ErrorState, NotFoundState } from "@/components/empty-state";import { Button } from "@/components/ui/button";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { Kbd } from "@/components/ui/kbd";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { EngineSwitch } from "@/components/studio/engine-switch";@@ -208,7 +208,7 @@ export function CanvasEditor({ id }: { id: string }) {function EditorSkeleton() {return (- <div className="flex h-svh flex-col md:h-[calc(100svh-0.5rem)]">+ <div className="flex h-content flex-col"><div className="flex h-14 items-center gap-3 border-b px-3 sm:px-4"><Skeleton className="h-6 w-48" /><Skeleton className="ml-auto h-8 w-24 rounded-full" />@@ -1260,7 +1260,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canvreturn (<EditorStoreContext.Provider value={store}><EditorActionsContext.Provider value={actions}>- <div className="fuobe-canvas flex h-svh min-w-0 flex-col md:h-[calc(100svh-0.5rem)]">+ <div className="fuobe-canvas flex h-content min-w-0 flex-col"><EditorHeadername={name}setName={setName}@@ -1518,7 +1518,6 @@ const EditorHeader = memo(function EditorHeader({const mod = useModKey();return (<header className="z-20 flex h-14 shrink-0 items-center gap-2 border-b bg-background px-2 sm:px-4">- <SidebarTrigger className="md:hidden" /><Tooltip><TooltipTrigger asChild><Link href="/canvas" className="grid size-8 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="All canvases">@@ -1602,6 +1601,7 @@ const EditorHeader = memo(function EditorHeader({</DropdownMenu></div></div>+ <PhoneNavButton /></header>);});diff --git a/src/components/captions/captions-studio.tsx b/src/components/captions/captions-studio.tsxindex a234af91..c275d282 100644--- a/src/components/captions/captions-studio.tsx+++ b/src/components/captions/captions-studio.tsx@@ -207,7 +207,7 @@ function Editor({ video, restored, onReplace }: { video: SlotValue; restored: Sareturn (<div className="grid gap-4 pt-4 lg:grid-cols-[minmax(0,6fr)_minmax(0,5fr)]">- <div className="min-w-0 space-y-3 lg:sticky lg:top-20 lg:self-start">+ <div className="min-w-0 space-y-3 lg:sticky lg:top-[calc(var(--chrome-top)+5rem)] lg:self-start"><Preview video={video} cues={cues} look={lookFor(route, look)} route={route} player={player} onTime={setTime} onDuration={setDuration} /><div className="flex flex-wrap items-center gap-1.5"><p className="min-w-0 flex-1 truncate text-[13px] text-muted-foreground">{video.name}</p>diff --git a/src/components/cinema/workspace.tsx b/src/components/cinema/workspace.tsxindex 159b9bce..a74a4262 100644--- a/src/components/cinema/workspace.tsx+++ b/src/components/cinema/workspace.tsx@@ -11,7 +11,7 @@ import { ErrorState, NotFoundState } from "@/components/empty-state";import { Button } from "@/components/ui/button";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { EngineSwitch } from "@/components/studio/engine-switch";@@ -152,7 +152,7 @@ export function CinemaWorkspace({ id }: { id: string }) {const items = useCinemaItems(id);if (project.isLoading)return (- <div className="flex h-svh flex-col">+ <div className="flex h-content flex-col"><div className="flex h-14 items-center gap-3 border-b px-4"><Skeleton className="h-6 w-48" /></div>@@ -426,9 +426,8 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaGconst builderProps = { projectId: id, folderId, engine, settings, context, brief: project.brief.body };return (- <div className="flex h-svh min-w-0 flex-col md:h-[calc(100svh-0.5rem)]">+ <div className="flex h-content min-w-0 flex-col"><header className="flex h-14 shrink-0 items-center gap-1.5 border-b px-2 sm:gap-2 sm:px-4">- <SidebarTrigger className="md:hidden" /><Tooltip><TooltipTrigger asChild><Link href="/cinema" className="hidden size-8 shrink-0 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground sm:grid" aria-label="All projects">@@ -529,6 +528,7 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG</DropdownMenuItem></DropdownMenuContent></DropdownMenu>+ <PhoneNavButton /></header><div className="flex min-h-0 flex-1">diff --git a/src/components/color-grade-view.tsx b/src/components/color-grade-view.tsxindex d786e37b..cbcac223 100644--- a/src/components/color-grade-view.tsx+++ b/src/components/color-grade-view.tsx@@ -7,7 +7,7 @@ import { Suspense, useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { downloadBlob } from "@/components/ads/render";import { Button } from "@/components/ui/button";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Slider } from "@/components/ui/slider";import { kindOfFile, MAX_MB, MediaSlot, type SlotValue } from "@/components/studio/media-slot";import { uploadFile, useViewer } from "@/lib/api";@@ -415,14 +415,14 @@ function Grader() {const pickFile = (f: File) => open({ url: URL.createObjectURL(f), kind: kindOfFile(f) === "video" ? "video" : "image", file: f });return (- <div className="flex flex-col lg:h-svh">+ <div className="flex flex-col lg:h-content"><header className="flex h-14 shrink-0 items-center gap-2 px-3 sm:px-6">- <SidebarTrigger className="md:hidden" /><h1 className="font-heading text-[22px] leading-none">Color grading</h1><span className="ml-2 hidden rounded-full bg-success/15 px-2 py-0.5 text-[11px] font-medium text-success sm:inline">Free · runs in your browser</span><div className="ml-auto flex items-center gap-2">{input && <MediaSlot label="Replace" kind={input.kind} value={null} onChange={pick} onFile={pickFile} local />}</div>+ <PhoneNavButton /></header><div className="flex min-h-0 flex-1 flex-col gap-3 px-3 pb-3 sm:px-6 lg:flex-row"><div@@ -430,7 +430,7 @@ function Grader() {className={cn("relative grid min-h-[40vh] place-items-center overflow-hidden rounded-xl bg-media lg:flex-1",// On a phone the picture stays at the top while the looks and sliders scroll under it.- input && "max-lg:sticky max-lg:top-0 max-lg:z-10 max-lg:h-[40svh] max-lg:min-h-0",+ input && "max-lg:sticky max-lg:top-chrome max-lg:z-10 max-lg:h-[40svh] max-lg:min-h-0",)}>{!input ? (diff --git a/src/components/command-palette.tsx b/src/components/command-palette.tsxdeleted file mode 100644index baa9fcf1..00000000--- a/src/components/command-palette.tsx+++ /dev/null@@ -1,376 +0,0 @@-"use client";--import { useQuery } from "@tanstack/react-query";-import { AudioLines, Bell, Clapperboard, Code, Cpu, Film, GraduationCap, Heart, Image as ImageIcon, KeyRound, Layers, LayoutGrid, Loader2, LogIn, Play, Plug, Plus, Scale, Server, Settings2, ShieldCheck, Sparkles, SunMoon, UserPlus, UserRound, Wand2, type LucideIcon } from "lucide-react";-import { useRouter } from "next/navigation";-import { useTheme } from "next-themes";-import { createContext, lazy, Suspense, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";-import { useSkills } from "@/components/assist/hooks";-import { NAV } from "@/components/nav-items";-import { MediaThumb } from "@/components/studio/result-media";-import { CommandDialog, CommandEmpty, CommandGroup, CommandItem, CommandList } from "@/components/ui/command";-import { Kbd } from "@/components/ui/kbd";-import { Command as CommandPrimitive } from "cmdk";-import { signInHref, useEngineMode, useGenerations, useIsGuest, useModelAccess, useViewer, type ViewerInfo } from "@/lib/api";-import { FUOBE_REPO } from "@/lib/connections";-import type { Generation } from "@/lib/catalog/types";-import { indexEntries, KIND_LABELS, rankPalette, skillEntries, type PaletteEntry, type PaletteIndex, type PaletteKind } from "@/lib/command-search";-import { useModKey } from "@/lib/keys";-import { userTitle } from "@/lib/library";-import { NEW_CREATION_HREF } from "@/lib/nav";-import { cn } from "@/lib/utils";--// The viewer is only needed once a recent creation is opened from the palette.-const Viewer = lazy(() => import("@/components/studio/viewer").then((m) => ({ default: m.Viewer })));--interface PaletteState {- open: boolean;- setOpen: (open: boolean | ((open: boolean) => boolean)) => void;-}--const PaletteContext = createContext<PaletteState>({ open: false, setOpen: () => {} });--/** Opens and closes the ⌘K palette from anywhere in the app frame (the sidebar's Search row, the phone header, ⌘K). */-export const useCommandPalette = () => useContext(PaletteContext);--/** What had focus when the palette opened: it gets focus back when the palette closes without going anywhere. */-const returnFocus: { current: Element | null } = { current: null };--export function CommandPaletteProvider({ children }: { children: React.ReactNode }) {- const [open, setOpenState] = useState(false);- const openRef = useRef(false);- const setOpen = useCallback((v: boolean | ((open: boolean) => boolean)) => {- const next = typeof v === "function" ? v(openRef.current) : v;- if (next && !openRef.current) returnFocus.current = document.activeElement;- openRef.current = next;- setOpenState(next);- }, []);- const value = useMemo(() => ({ open, setOpen }), [open, setOpen]);- return <PaletteContext.Provider value={value}>{children}</PaletteContext.Provider>;-}--/** Settings sections the palette jumps to (ids in settings-form.tsx). */-const SETTINGS: { id: string; label: string; icon: LucideIcon; keywords: string; href?: string }[] = [- { id: "cloud", label: "API keys", icon: KeyRound, keywords: "fal replicate paid cloud connect" },- { id: "comfyui", label: "ComfyUI server", icon: Server, keywords: "open source gpu url connect local" },- { id: "engine", label: "Engine mode", icon: Cpu, keywords: "open source cloud both" },- { id: "loras", label: "LoRAs", icon: Layers, keywords: "lora folder civitai key looks motions effects download licence" },- { id: "training", label: "Training (AI-Toolkit)", icon: GraduationCap, keywords: "ai-toolkit aitk train lora soul id gpu url token" },- {- id: "models",- label: "Models & licences",- icon: Scale,- keywords: "licence license commercial non-commercial switch off turn on admin providers node packs allow block",- href: "/settings/models",- },- {- id: "about",- label: "Thanks & licences",- icon: Heart,- keywords: "about credits thanks licence license open source models loras node packs libraries attribution",- href: "/settings/licences",- },- { id: "text-ai", label: "AI helper", icon: Sparkles, keywords: "claude ollama lm studio unsloth local llm model enhancer prompt enhancement context" },- { id: "assist-connectors", label: "Assist connectors", icon: Plug, keywords: "mcp connector claude tools notion linear slack server token" },- { id: "notifications", label: "Notifications", icon: Bell, keywords: "browser done alerts" },- { id: "security", label: "Password and API tokens", icon: ShieldCheck, keywords: "security sign in mcp token" },- { id: "demo", label: "Placeholder results", icon: Settings2, keywords: "demo mode placeholder tour free try" },-];--const PAGES: (PaletteEntry & { icon: LucideIcon })[] = NAV.flatMap((g) =>- g.items.map((i) => ({ key: `page:${i.href}`, kind: "page" as const, label: i.label, hint: g.label, href: i.href, keywords: i.keywords, icon: i.icon })),-);-const SETTING_ENTRIES: (PaletteEntry & { icon: LucideIcon })[] = SETTINGS.map((s) => ({- key: `setting:${s.id}`,- kind: "setting",- label: s.label,- hint: "Settings",- href: s.href ?? `/settings#${s.id}`,- keywords: s.keywords,- icon: s.icon,-}));-const visitorSetting = (key: string, label: string, href: string, icon: LucideIcon, keywords: string): PaletteEntry & { icon: LucideIcon } => ({- key: `setting:${key}`,- kind: "setting",- label,- hint: "Settings",- href,- keywords,- icon,-});-const THANKS = SETTING_ENTRIES.find((e) => e.key === "setting:about")!;-/**- * The install's settings are its owner's: an account (public sign-up) gets its own GPU and account, a guest the way to- * connect a GPU; both get Thanks & licences, which they may read.- */-const ACCOUNT_SETTINGS = [- visitorSetting("your-gpu", "Your GPU", "/settings#your-gpu", Cpu, "comfyui gpu connect own server open source"),- visitorSetting("your-keys", "Your keys", "/settings#your-keys", KeyRound, "fal fal.ai replicate api key token paid models nano banana kling veo billing"),- visitorSetting("account", "Account", "/settings#account", UserRound, "email sign out delete account"),- THANKS,-];-const GUEST_SETTINGS = [visitorSetting("connect", "Connect your GPU", "/connect", Cpu, "comfyui gpu own server sign up account open source"), THANKS];--/** The settings the palette offers this viewer (none of the install's to anyone but its owner). */-export function settingEntries(viewer: Pick<ViewerInfo, "owner" | "account"> | undefined): (PaletteEntry & { icon: LucideIcon })[] {- if (viewer?.owner) return SETTING_ENTRIES;- return viewer?.account ? ACCOUNT_SETTINGS : GUEST_SETTINGS;-}--/** Things to do rather than pages to open (Go to): the theme, the source, and for a guest, signing up or in. */-const THEME_HREF = "action:theme";-const ACTIONS: (PaletteEntry & { icon: LucideIcon })[] = [- { key: "action:theme", kind: "page", label: "Toggle dark mode", hint: "Theme", href: THEME_HREF, keywords: "dark light theme night mode appearance", icon: SunMoon },- { key: "action:github", kind: "page", label: "Source on GitHub", hint: "Open source", href: FUOBE_REPO, keywords: "github code repo repository open source download install self host", icon: Code },-];-const GUEST_ACTIONS: (PaletteEntry & { icon: LucideIcon })[] = [- { key: "action:signup", kind: "page", label: "Sign up free", hint: "Account", href: signInHref("signup"), keywords: "sign up register create account join", icon: UserPlus },- { key: "action:login", kind: "page", label: "Log in", hint: "Account", href: signInHref("login"), keywords: "log in login sign in account", icon: LogIn },-];-// Icons as elements made once (a component picked during render would remount on every keystroke).-const iconEl = (Icon: LucideIcon) => <Icon className="text-muted-foreground" />;-const ICONS = new Map<string, React.ReactNode>([...PAGES, ...SETTING_ENTRIES, ...ACCOUNT_SETTINGS, ...GUEST_SETTINGS, ...ACTIONS, ...GUEST_ACTIONS].map((e) => [e.key, iconEl(e.icon)]));-const KIND_ICONS: Partial<Record<PaletteKind, React.ReactNode>> = { app: iconEl(LayoutGrid), motion: iconEl(Film), effect: iconEl(Wand2), model: iconEl(Clapperboard), skill: iconEl(Play) };-/** A model's icon by the studio it opens in: a voice or music model isn't a clapperboard. */-const MODEL_ICONS = { audio: iconEl(AudioLines), image: iconEl(ImageIcon) };-const modelIcon = (href: string) =>- /^\/audio\b/.test(href) ? MODEL_ICONS.audio : /^\/(image|edit|inpaint|outpaint|upscale\/image|image-to-3d)\b/.test(href) ? MODEL_ICONS.image : undefined;--function useDebounced<T>(value: T, ms: number): T {- const [v, setV] = useState(value);- useEffect(() => {- const t = setTimeout(() => setV(value), ms);- return () => clearTimeout(t);- }, [value, ms]);- return v;-}--// The hints are marked as shortcuts so CommandItem drops its check mark, which would share the row's free space with them.-function Row({ entry, onPick }: { entry: PaletteEntry; onPick: (e: PaletteEntry) => void }) {- return (- <CommandItem value={entry.key} onSelect={() => onPick(entry)} className="h-9 gap-2.5 text-[14px]">- {ICONS.get(entry.key) ?? (entry.kind === "model" ? modelIcon(entry.href) : undefined) ?? KIND_ICONS[entry.kind] ?? KIND_ICONS.app}- <span className="min-w-0 truncate">{entry.label}</span>- {entry.hint && <span data-slot="command-shortcut" className="ml-auto shrink-0 truncate pl-2 text-[12px] text-muted-foreground max-sm:max-w-[40%]">{entry.hint}</span>}- </CommandItem>- );-}--function RecentRow({ g, onOpen }: { g: Generation; onOpen: (g: Generation) => void }) {- const title = userTitle(g);- return (- <CommandItem value={`recent:${g.id}`} onSelect={() => onOpen(g)} className="h-11 gap-2.5 text-[14px]">- <span className="relative size-8 shrink-0 overflow-hidden rounded-md bg-muted">{g.outputs[0] && <MediaThumb output={g.outputs[0]} g={g} />}</span>- <span className="min-w-0 truncate">{title}</span>- <span data-slot="command-shortcut" className="ml-auto shrink-0 pl-2 text-[12px] text-muted-foreground">{g.modelName}</span>- </CommandItem>- );-}--function Hints() {- const mod = useModKey();- return (- <div className="flex items-center gap-3 border-t px-3 py-2 text-[12px] text-muted-foreground [@media(hover:none)]:hidden">- <span className="flex items-center gap-1">- <Kbd>↑</Kbd>- <Kbd>↓</Kbd> to move- </span>- <span className="flex items-center gap-1">- <Kbd>↵</Kbd> to open- </span>- <span className="flex items-center gap-1">- <Kbd>Esc</Kbd> to close- </span>- <span className="ml-auto flex items-center gap-1">- <Kbd>{mod}</Kbd>- <Kbd>K</Kbd>- </span>- </div>- );-}--/** What the palette lists and searches; mounted only while it's open. */-function PaletteBody({ onPick, onOpenRecent, onClose }: { onPick: (e: PaletteEntry) => void; onOpenRecent: (g: Generation) => void; onClose: () => void }) {- const [q, setQ] = useState("");- // Not deferred: ranking ~900 entries takes a millisecond, and Enter must act on the list for what was typed.- const query = q;- const dq = useDebounced(q.trim(), 200);- const mode = useEngineMode();- const access = useModelAccess();- const settings = settingEntries(useViewer().data);- // The apps, motions, effects and models load on first open (and stay for the session).- const index = useQuery({- queryKey: ["palette-index"],- queryFn: async () => (await fetch("/api/search-index")).json() as Promise<PaletteIndex>,- staleTime: Infinity,- });- const recent = useGenerations({ q: dq || undefined, limit: 5, statuses: ["succeeded"] }, { keepPrevious: true });- // Skills that run by themselves: "Run <skill>…" opens its Run form.- const skills = useSkills();- const guest = useIsGuest();- const entries = useMemo(- () => [...PAGES, ...ACTIONS, ...(guest ? GUEST_ACTIONS : []), ...settings, ...skillEntries(skills.data ?? []), ...(index.data ? indexEntries(index.data, mode, access) : [])],- [index.data, mode, access, skills.data, settings, guest],- );- const groups = useMemo(() => rankPalette(entries, query), [entries, query]);- const recentItems = (recent.data ?? []).filter((g) => g.outputs[0]);- const searching = !!query.trim();- // cmdk keeps no selection once the rows change (shouldFilter is off): every new query starts on its- // best match, so Enter opens it; arrows move from there.- const best = searching ? (groups[0]?.entries[0]?.key ?? (recentItems[0] ? `recent:${recentItems[0].id}` : "")) : "new";- const [moved, setMoved] = useState<{ query: string; value: string } | null>(null);- const selected = moved?.query === query ? moved.value : best;-- return (- <CommandPrimitive shouldFilter={false} loop value={selected} onValueChange={(value) => setMoved({ query, value })} label="Search Fuobe" className="flex flex-col overflow-hidden rounded-xl bg-popover text-popover-foreground">- <div className="flex items-center gap-2 border-b px-3">- <CommandPrimitive.Input- value={q}- onValueChange={setQ}- autoFocus- placeholder="Search pages, apps, motions, effects, models…"- aria-label="Search Fuobe"- className="h-12 min-w-0 flex-1 bg-transparent text-[15px] outline-none placeholder:text-subtle-foreground"- />- {index.isLoading && searching && <Loader2 className="size-4 shrink-0 animate-spin text-muted-foreground" aria-label="Loading the catalog" />}- {/* Touch screens have no Esc (and the hint row is hidden there): a visible way out. */}- <button- type="button"- onClick={onClose}- className="-mr-1 hidden h-8 shrink-0 items-center rounded-md px-2 text-[14px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground [@media(hover:none)]:inline-flex"- >- Cancel- </button>- </div>- <CommandList className="max-h-[min(60vh,440px)] p-1.5">- {searching ? (- <>- <CommandEmpty className="py-10 text-center text-[13px] text-muted-foreground">- {index.isLoading ? "Looking through apps, motions and models…" : `Nothing matches “${query.trim()}”. Try a shorter word.`}- </CommandEmpty>- {groups.map((g) => (- <CommandGroup key={g.kind} heading={g.label}>- {g.entries.map((e) => (- <Row key={e.key} entry={e} onPick={onPick} />- ))}- </CommandGroup>- ))}- {recentItems.length > 0 && (- <CommandGroup heading={KIND_LABELS.recent}>- {recentItems.map((g) => (- <RecentRow key={g.id} g={g} onOpen={onOpenRecent} />- ))}- </CommandGroup>- )}- </>- ) : (- <>- <CommandGroup>- {/* Enter on an empty query keeps what ⌘K always did: a new creation. */}- <CommandItem value="new" onSelect={() => onPick({ key: "new", kind: "page", label: "New creation", href: NEW_CREATION_HREF })} className="h-9 gap-2.5 text-[14px]">- <Plus className="text-muted-foreground" />- New creation- <span data-slot="command-shortcut" className="ml-auto text-[12px] text-muted-foreground">Home</span>- </CommandItem>- </CommandGroup>- {recentItems.length > 0 && (- <CommandGroup heading={KIND_LABELS.recent}>- {recentItems.map((g) => (- <RecentRow key={g.id} g={g} onOpen={onOpenRecent} />- ))}- </CommandGroup>- )}- <CommandGroup heading={KIND_LABELS.page}>- {PAGES.map((e) => (- <Row key={e.key} entry={e} onPick={onPick} />- ))}- </CommandGroup>- <CommandGroup heading={KIND_LABELS.setting}>- {settings.map((e) => (- <Row key={e.key} entry={e} onPick={onPick} />- ))}- </CommandGroup>- </>- )}- </CommandList>- <Hints />- </CommandPrimitive>- );-}--/**- * The ⌘K / Ctrl+K palette: every page, settings section, app, camera motion, effect and model, and- * your recent creations, with a forgiving search (src/lib/command-search.ts). Rendered once, in the- * app frame.- */-export function CommandPalette() {- const { open, setOpen } = useCommandPalette();- const router = useRouter();- const [viewing, setViewing] = useState<Generation | null>(null);-- useEffect(() => {- const onKey = (e: KeyboardEvent) => {- if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "k") {- e.preventDefault();- setOpen((o) => !o);- }- };- window.addEventListener("keydown", onKey);- return () => window.removeEventListener("keydown", onKey);- }, [setOpen]);-- // Set when the palette closes onto something else (a page, the viewer): focus stays with that.- const leaving = useRef(false);- const { resolvedTheme, setTheme } = useTheme();- const pick = useCallback(- (e: PaletteEntry) => {- setOpen(false);- if (e.href === THEME_HREF) return setTheme(resolvedTheme === "dark" ? "light" : "dark");- if (/^https?:/.test(e.href)) return void window.open(e.href, "_blank", "noopener,noreferrer");- leaving.current = true;- router.push(e.href);- },- [router, setOpen, resolvedTheme, setTheme],- );- const openRecent = useCallback(- (g: Generation) => {- leaving.current = true;- setOpen(false);- setViewing(g);- },- [setOpen],- );- const close = useCallback(() => setOpen(false), [setOpen]);- // Dismissed (Esc, Cancel, a click outside, ⌘K again): focus goes back to where it was, the- // composer you were typing in or the Search row, not to the top of the page.- const restoreFocus = useCallback((e: Event) => {- e.preventDefault();- const el = returnFocus.current;- returnFocus.current = null;- if (leaving.current) {- leaving.current = false;- return;- }- if (el instanceof HTMLElement && el.isConnected) el.focus({ preventScroll: true });- }, []);-- return (- <>- <CommandDialog- open={open}- onOpenChange={setOpen}- title="Search Fuobe"- description="Go to a page, an app, a camera motion, an effect, a model, a settings section or a recent creation."- className={cn("top-[8vh] gap-0 p-0 sm:top-[14vh] sm:max-w-xl")}- onCloseAutoFocus={restoreFocus}- >- <PaletteBody onPick={pick} onOpenRecent={openRecent} onClose={close} />- </CommandDialog>- {viewing && (- <Suspense fallback={null}>- <Viewer generation={viewing} index={0} onClose={() => setViewing(null)} />- </Suspense>- )}- </>- );-}diff --git a/src/components/content-factory/home.tsx b/src/components/content-factory/home.tsxindex 5239f72d..9d33e7cc 100644--- a/src/components/content-factory/home.tsx+++ b/src/components/content-factory/home.tsx@@ -7,7 +7,7 @@ import { useEffect, useId, useRef, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { Switch } from "@/components/ui/switch";import { MediaThumb } from "@/components/studio/feed";@@ -214,13 +214,13 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] })const est = estimate.data;return (- <div className="flex min-h-svh min-w-0 flex-col">- <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <div className="flex min-h-content min-w-0 flex-col">+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6"><h1 className="truncate font-heading text-[22px] leading-none">Content Factory</h1><div className="ml-auto"><EngineSwitch value={engine} onChange={setEngine} selfHostedOnly /></div>+ <PhoneNavButton /></header><div className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 space-y-12 px-3 pb-16 sm:px-6"><div className="mx-auto max-w-[780px] pt-[5vh] text-center sm:pt-[8vh]">diff --git a/src/components/content-factory/series-view.tsx b/src/components/content-factory/series-view.tsxindex 5e25c402..e195be98 100644--- a/src/components/content-factory/series-view.tsx+++ b/src/components/content-factory/series-view.tsx@@ -16,7 +16,7 @@ import {AlertDialogTitle,} from "@/components/ui/alert-dialog";import { Button } from "@/components/ui/button";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { Switch } from "@/components/ui/switch";import { EpisodeTile } from "@/components/faceless/cards";@@ -53,11 +53,11 @@ export function SeriesView({ id, voices }: { id: string; voices: PickerData["voi);const header = (- <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6"><Link href="/content-factory" className="inline-flex min-w-0 items-center gap-1.5 text-[13px] text-muted-foreground hover:text-foreground"><ArrowLeft className="size-4 shrink-0" /> <span className="truncate">Content Factory</span></Link>+ <PhoneNavButton className="ml-auto" /></header>);@@ -74,7 +74,7 @@ export function SeriesView({ id, voices }: { id: string; voices: PickerData["voionError: (e) => toastError(e),});return (- <div className="flex min-h-svh min-w-0 flex-col">+ <div className="flex min-h-content min-w-0 flex-col">{header}<div className="mx-auto w-full max-w-[640px] px-3 pt-16 text-center sm:px-6"><h1 className="font-heading text-[28px]">{error ? "Series not found" : orphan ? "This series' channel was deleted" : "This series hasn't been made yet"}</h1>@@ -104,7 +104,7 @@ export function SeriesView({ id, voices }: { id: string; voices: PickerData["voiconst engine = channel?.settings.engine ?? "cloud";return (- <div className="flex min-h-svh min-w-0 flex-col">+ <div className="flex min-h-content min-w-0 flex-col">{header}<div className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 space-y-8 px-3 pb-16 sm:px-6">{isLoading || !s || !channel || !settings ? (diff --git a/src/components/demo-mode.tsx b/src/components/demo-mode.tsxindex 658f5ab6..ebe29ddf 100644--- a/src/components/demo-mode.tsx+++ b/src/components/demo-mode.tsx@@ -22,7 +22,7 @@ import { cn } from "@/lib/utils";/*** Placeholder results (src/lib/demo-mode.ts): off by default, on only by the owner's choice in Settings, for a tour.- * While on, the sidebar shows "Placeholders on", a chip whose click turns them off (with Undo). Every result the demo+ * While on, the top bar shows "Placeholders on", a chip whose click turns them off (with Undo). Every result the demo* provider made carries a "Placeholder" chip; for the owner it opens a small card with the ways to the real thing:* the ComfyUI on this computer (the connect card), an API key (Settings), and placeholders off.*/@@ -113,8 +113,8 @@ function PlaceholderCard({ close }: { close: () => void }) {}/**- * The sidebar's "Placeholders on" while the switch is on (the owner's only: nobody else's runs make placeholders). A- * click turns them off at once, with Undo in the toast; Settings has the switch itself. `icon`: the collapsed sidebar's+ * The top bar's and the account menu's "Placeholders on" while the switch is on (the owner's only: nobody else's runs make placeholders). A+ * click turns them off at once, with Undo in the toast; Settings has the switch itself. `icon`: a* round version, the same button with only its mark showing.*/export function PlaceholdersOnChip({ className, icon }: { className?: string; icon?: boolean }) {diff --git a/src/components/dub/dub-studio.tsx b/src/components/dub/dub-studio.tsxindex 68b666b4..69e0bdd4 100644--- a/src/components/dub/dub-studio.tsx+++ b/src/components/dub/dub-studio.tsx@@ -480,7 +480,7 @@ function SessionView({ s, onBack }: { s: DubSessionView; onBack: () => void }) {</div><div className="grid gap-4 lg:grid-cols-[minmax(0,5fr)_minmax(0,6fr)]">- <div className="space-y-3 lg:sticky lg:top-20 lg:self-start">+ <div className="space-y-3 lg:sticky lg:top-[calc(var(--chrome-top)+5rem)] lg:self-start"><div className="overflow-hidden rounded-2xl border bg-media"><video ref={video} src={s.video} controls playsInline preload="metadata" onTimeUpdate={(e) => setTime(e.currentTarget.currentTime)} className="max-h-[42vh] w-full object-contain" /></div>diff --git a/src/components/empty-state.tsx b/src/components/empty-state.tsxindex c080ba43..a0d740f4 100644--- a/src/components/empty-state.tsx+++ b/src/components/empty-state.tsx@@ -20,7 +20,7 @@ export function PageState({actions?: React.ReactNode;}) {return (- <div className="flex min-h-svh min-w-0 flex-col">+ <div className="flex min-h-content min-w-0 flex-col"><PhoneBar className="bg-transparent backdrop-blur-none" /><div className="mx-auto flex w-full max-w-[520px] flex-1 flex-col items-center justify-center px-6 pb-[12vh] text-center"><span className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">diff --git a/src/components/evolution/evolution-tool.tsx b/src/components/evolution/evolution-tool.tsxindex 59ae52c5..a188c202 100644--- a/src/components/evolution/evolution-tool.tsx+++ b/src/components/evolution/evolution-tool.tsx@@ -244,7 +244,7 @@ export function EvolutionTool() {</Panel></div>- <Panel className="space-y-4 lg:sticky lg:top-[112px]">+ <Panel className="space-y-4 lg:sticky lg:top-[calc(var(--chrome-top)+112px)]"><Field label="How much should change?"><Segmented label="How much should change?" value={intensity} onChange={setIntensity} options={INTENSITIES.map((i) => ({ value: i.id, label: i.label }))} /><p className="text-[12px] text-muted-foreground" aria-live="polite">diff --git a/src/components/explainer/explainer-studio.tsx b/src/components/explainer/explainer-studio.tsxindex 9cd974b5..f0256a94 100644--- a/src/components/explainer/explainer-studio.tsx+++ b/src/components/explainer/explainer-studio.tsx@@ -8,7 +8,7 @@ import { Button } from "@/components/ui/button";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { Switch } from "@/components/ui/switch";import { EngineSwitch } from "@/components/studio/engine-switch";@@ -277,16 +277,16 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {};return (- <div className="flex min-h-svh min-w-0 flex-col">- <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <div className="flex min-h-content min-w-0 flex-col">+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6"><h1 className="truncate font-heading text-[22px] leading-none">Explainer</h1><div className="ml-auto"><EngineSwitch value={engine} onChange={setEngine} selfHostedOnly /></div>+ <PhoneNavButton /></header><div className="mx-auto grid w-full max-w-[1240px] min-w-0 flex-1 gap-8 px-3 pt-6 pb-16 sm:px-6 lg:grid-cols-[minmax(0,520px)_minmax(0,1fr)]">- <section aria-label="New explainer" className="min-w-0 lg:sticky lg:top-20 lg:self-start">+ <section aria-label="New explainer" className="min-w-0 lg:sticky lg:top-[calc(var(--chrome-top)+5rem)] lg:self-start"><div className="rounded-[20px] border bg-background p-3 shadow-soft transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer sm:p-4"><p className="px-1 text-[11px] font-semibold tracking-[0.14em] text-muted-foreground uppercase">Fuobe Explainer</p><div className="mt-2 flex items-center gap-3 rounded-2xl bg-muted/60 p-2">diff --git a/src/components/faceless/channel-view.tsx b/src/components/faceless/channel-view.tsxindex 679d73a9..3338b47c 100644--- a/src/components/faceless/channel-view.tsx+++ b/src/components/faceless/channel-view.tsx@@ -19,7 +19,7 @@ import {import { Button } from "@/components/ui/button";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { NotFoundState } from "@/components/empty-state";import { FACELESS_STYLE_IDS, genreInfo, getStyle, type ChannelSettings, type FacelessChannel, type PickerData } from "@/lib/catalog/faceless";@@ -137,12 +137,12 @@ export function ChannelView({ id, picker }: { id: string; picker: PickerData })};return (- <div className="flex min-h-svh min-w-0 flex-col">- <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <div className="flex min-h-content min-w-0 flex-col">+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6"><Link href="/faceless" className="inline-flex min-w-0 items-center gap-1.5 text-[13px] text-muted-foreground hover:text-foreground"><ArrowLeft className="size-4 shrink-0" /> <span className="truncate">Faceless Studio</span></Link>+ <PhoneNavButton className="ml-auto" /></header><div className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 space-y-8 px-3 pb-16 sm:px-6">{isLoading || !channel ? (diff --git a/src/components/faceless/episode-view.tsx b/src/components/faceless/episode-view.tsxindex e6e1d88f..66ec3bea 100644--- a/src/components/faceless/episode-view.tsx+++ b/src/components/faceless/episode-view.tsx@@ -39,7 +39,7 @@ import {} from "@/components/ui/alert-dialog";import { Button } from "@/components/ui/button";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { NotFoundState } from "@/components/empty-state";import { MediaThumb } from "@/components/studio/feed";@@ -483,9 +483,8 @@ export function EpisodeView({ id, backHref, backLabel }: { id: string; backHref:const run = (a: "retry" | "rewrite" | "undo" | "upscale", ok?: string) => action.mutate(a, { onSuccess: () => ok && toast.success(ok), onError: (e) => toastError(e) });return (- <div className="flex min-h-svh min-w-0 flex-col">- <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <div className="flex min-h-content min-w-0 flex-col">+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6"><Link href={backHref} className="inline-flex min-w-0 shrink items-center gap-1.5 text-[13px] text-muted-foreground hover:text-foreground"><ArrowLeft className="size-4 shrink-0" /><span className="truncate">{view?.channel?.name ?? backLabel}</span>@@ -542,6 +541,7 @@ export function EpisodeView({ id, backHref, backLabel }: { id: string; backHref:</DropdownMenu></div>)}+ <PhoneNavButton /></header><div className="mx-auto w-full max-w-[1100px] min-w-0 flex-1 space-y-6 px-3 pb-16 sm:px-6">{isLoading || !view || !ep ? (diff --git a/src/components/faceless/episode-wizard.tsx b/src/components/faceless/episode-wizard.tsxindex e2596f4b..9f159a44 100644--- a/src/components/faceless/episode-wizard.tsx+++ b/src/components/faceless/episode-wizard.tsx@@ -6,7 +6,7 @@ import { useRouter } from "next/navigation";import { useEffect, useId, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { NotFoundState } from "@/components/empty-state";import { EngineSwitch } from "@/components/studio/engine-switch";@@ -170,9 +170,8 @@ export function EpisodeWizard({ channelId, picker }: { channelId: string; picker};return (- <div className="flex min-h-svh min-w-0 flex-col">- <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <div className="flex min-h-content min-w-0 flex-col">+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6"><Link href={`/faceless/${channelId}`} className="inline-flex min-w-0 items-center gap-1.5 text-[13px] text-muted-foreground hover:text-foreground"><ArrowLeft className="size-4 shrink-0" /><span className="truncate">{channel?.name ?? "Channel"}</span>@@ -180,6 +179,7 @@ export function EpisodeWizard({ channelId, picker }: { channelId: string; picker<div className="ml-auto"><EngineSwitch value={engine} onChange={setEngine} /></div>+ <PhoneNavButton /></header><div className="mx-auto w-full max-w-[920px] min-w-0 flex-1 px-3 pb-32 sm:px-6"><div className="flex flex-wrap items-center justify-between gap-3 pt-6">@@ -349,7 +349,7 @@ export function EpisodeWizard({ channelId, picker }: { channelId: string; picker</div>{channel && settings && (- <div className="sticky bottom-0 z-20 border-t bg-background/90 pb-[max(0.75rem,env(safe-area-inset-bottom))] backdrop-blur">+ <div className="sticky bottom-chrome z-20 border-t bg-background/90 pb-[max(0.75rem,env(safe-area-inset-bottom))] backdrop-blur"><div className="mx-auto flex w-full max-w-[920px] min-w-0 flex-wrap items-center gap-3 px-3 pt-3 sm:px-6">{step === 2 ? (<>diff --git a/src/components/faceless/faceless-home.tsx b/src/components/faceless/faceless-home.tsxindex 2a0657df..d75e7537 100644--- a/src/components/faceless/faceless-home.tsx+++ b/src/components/faceless/faceless-home.tsx@@ -5,7 +5,7 @@ import { useRouter } from "next/navigation";import { useId, useRef, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { EngineSwitch } from "@/components/studio/engine-switch";import { radioKeys, radioTab } from "@/components/studio/radio-keys";@@ -73,13 +73,13 @@ export function FacelessHome() {};return (- <div className="flex min-h-svh min-w-0 flex-col">- <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <div className="flex min-h-content min-w-0 flex-col">+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6"><h1 className="truncate font-heading text-[22px] leading-none">Faceless Studio</h1><div className="ml-auto"><EngineSwitch value={engine} onChange={setEngine} selfHostedOnly /></div>+ <PhoneNavButton /></header><div className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 space-y-12 px-3 pb-16 sm:px-6"><div className="mx-auto max-w-[760px] pt-[6vh] text-center sm:pt-[9vh]">diff --git a/src/components/faceless/script-review.tsx b/src/components/faceless/script-review.tsxindex 2b1be281..fe0f027f 100644--- a/src/components/faceless/script-review.tsx+++ b/src/components/faceless/script-review.tsx@@ -254,7 +254,7 @@ export function ScriptReview({ view }: { view: EpisodeView }) {/>))}</ol>- <div className="sticky bottom-0 z-10 -mx-3 border-t bg-background/90 px-3 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] backdrop-blur sm:-mx-6 sm:px-6">+ <div className="sticky bottom-chrome z-10 -mx-3 border-t bg-background/90 px-3 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] backdrop-blur sm:-mx-6 sm:px-6"><div className="flex flex-wrap items-center gap-3"><span className="inline-flex items-center gap-1.5 text-[12px] text-muted-foreground" aria-live="polite">{update.isPending ? <Loader2 className="size-3 animate-spin" /> : dirty ? null : <Check className="size-3" />}diff --git a/src/components/fashion/character-sheet.tsx b/src/components/fashion/character-sheet.tsxindex 0670b9fa..6d348385 100644--- a/src/components/fashion/character-sheet.tsx+++ b/src/components/fashion/character-sheet.tsx@@ -2,7 +2,8 @@import { AtSign, Check, Dices, ImagePlus, Loader2, RotateCcw, Shuffle, Sparkles, UserRoundPlus, X } from "lucide-react";import Link from "next/link";-import { Suspense, useMemo, useRef, useState, type ComponentProps } from "react";+import { nanoid } from "nanoid";+import { Suspense, useCallback, useMemo, useRef, useState, type ComponentProps } from "react";import { useSearchParams } from "next/navigation";import { toast } from "sonner";import { PageHeader, PageShell } from "@/components/page-shell";@@ -17,6 +18,7 @@ import { useRun, useRunPreview } from "@/components/photodump/hooks";import { ResultsGrid } from "@/components/photodump/results";import { RunLine } from "@/components/photodump/steps";import { TurnaroundButton } from "@/components/turnaround/turnaround-dialog";+import { HandoffImage } from "@/components/nav/next-steps";import { useElements, useEngine, useGenerations, useLikelyVisitor, useSaveElement } from "@/lib/api";import { castFieldVisible, castNameFor, randomCast, SHEET_MAX_REFS, type CastAnswers, type CastFieldData } from "@/lib/catalog/packs";import { sheetPictures } from "@/lib/catalog/turnaround";@@ -206,6 +208,11 @@ export function CharacterSheetView({ fields, defaults }: { fields: CastFieldDataif (photos.length + list.length > SHEET_MAX_REFS) toast(`Maximum ${SHEET_MAX_REFS} images`);list.slice(0, SHEET_MAX_REFS - photos.length).forEach((f) => fileToList(f, setPhotos, "image"));};+ // A result sent here ("Make a character sheet" under a picture): the first reference photo, From Reference.+ const takeHandoff = useCallback((url: string) => {+ setMode("reference");+ setPhotos((xs) => (xs.some((x) => x.ref === url) ? xs : [{ ref: url, preview: url, kind: "image" as const, id: nanoid(8) }, ...xs].slice(0, SHEET_MAX_REFS)));+ }, []);const create = () => {if (visitor) return;if (mode === "reference" && !photos.length) return toast("Upload at least 1 image");@@ -219,6 +226,9 @@ export function CharacterSheetView({ fields, defaults }: { fields: CastFieldDatareturn (<PageShell wide>+ <Suspense fallback={null}>+ <HandoffImage onImage={takeHandoff} />+ </Suspense><PageHeader title="Character Sheet" description="Build your AI avatar: a consistent character for your videos, from a reference or defined from scratch."><EngineSwitch value={engine} onChange={setEngine} selfHostedOnly /></PageHeader>diff --git a/src/components/fashion/fashion-view.tsx b/src/components/fashion/fashion-view.tsxindex 74c78d38..4187dc9e 100644--- a/src/components/fashion/fashion-view.tsx+++ b/src/components/fashion/fashion-view.tsx@@ -159,7 +159,7 @@ export function FashionView() {);})}</div>- <div className="sticky bottom-3 z-10 flex items-center justify-between gap-3 rounded-2xl border bg-background/95 p-3 shadow-normal backdrop-blur">+ <div className="sticky bottom-[calc(var(--chrome-bottom)+0.75rem)] z-10 flex items-center justify-between gap-3 rounded-2xl border bg-background/95 p-3 shadow-normal backdrop-blur"><p className="min-w-0 truncate text-[13px]">{t ? <span className="font-medium">{t.name}</span> : <span className="text-muted-foreground">Pick a template</span>}</p><Button aria-disabled={!t} className={cn(!t && "opacity-50")} onClick={() => !block(fashionBlocker(s)) && dispatch({ type: "next" })}>Continue <ArrowRight />@@ -292,7 +292,7 @@ function ModelChips({ label, ids, value, onChange }: { label: string; ids: readofunction Footer({ onBack, line, children }: { onBack: () => void; line?: React.ReactNode; children: React.ReactNode }) {return (- <div className="sticky bottom-3 z-10 flex flex-wrap items-center justify-between gap-3 rounded-2xl border bg-background/95 p-3 shadow-normal backdrop-blur">+ <div className="sticky bottom-[calc(var(--chrome-bottom)+0.75rem)] z-10 flex flex-wrap items-center justify-between gap-3 rounded-2xl border bg-background/95 p-3 shadow-normal backdrop-blur"><Button variant="outline" onClick={onBack}><ArrowLeft /> Back</Button>diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsxindex c7a091e7..1cdb2b8a 100644--- a/src/components/genjutsu/genjutsu-studio.tsx+++ b/src/components/genjutsu/genjutsu-studio.tsx@@ -641,7 +641,7 @@ export function GenjutsuStudio({ examples }: { examples?: StudioExampleRow }) {)}</div>- <Panel className="space-y-4 lg:sticky lg:top-[112px]">+ <Panel className="space-y-4 lg:sticky lg:top-[calc(var(--chrome-top)+112px)]"><p className="text-[13px] text-pretty text-muted-foreground">{modeInfo.hint}</p>{MODE_TARGETS[mode].length > 0 && (diff --git a/src/components/gpu/computer-runner.tsx b/src/components/gpu/computer-runner.tsxindex fcef8ab9..7f313a58 100644--- a/src/components/gpu/computer-runner.tsx+++ b/src/components/gpu/computer-runner.tsx@@ -16,7 +16,7 @@ import { loopbackPermission, useComputerSupport } from "./use-local-comfy";/*** "Use the ComfyUI on this computer": while the page is open, one Fuobe tab of this browser runs the person's jobs on* their ComfyUI (computer-runtime.ts). Mounted once, in the app's providers; it starts only for someone whose runs go- * to their own computer. The sidebar shows its note (ComputerNote) while their GPU works, or when ComfyUI needs them.+ * to their own computer. The top bar's pill and the phone's You sheet show its note (ComputerNote) while their GPU works, or when ComfyUI needs them.*/export { awayFix, openConnect, openFinder, type FindReason } from "./open-connect";@@ -181,43 +181,67 @@ function noteOf(s: ComputerState): Note | null {return working ? { text: "Your GPU is working. Keep this tab open.", problem: false } : null;}+/** The note's icon: a warning when the person has something to do, else the GPU with a beat while it works. */+function NoteIcon({ problem }: { problem: boolean }) {+ return problem ? (+ <TriangleAlert aria-hidden className="size-4 shrink-0 text-amber-600 dark:text-amber-400" />+ ) : (+ <span aria-hidden className="relative grid size-4 shrink-0 place-items-center">+ <Cpu className="size-4 text-brand-text" />+ <span className="absolute -top-0.5 -right-0.5 size-1.5 rounded-full bg-primary motion-safe:animate-pulse" />+ </span>+ );+}+/**- * The note in the sidebar, above "Your GPU": the GPU working ("keep this tab open"), or the one thing to do. It sits in- * the sidebar's own space, so it never covers the page; with the sidebar folded, an icon says it.+ * The note: the GPU working ("keep this tab open"), or the one thing to do. It sits in the top bar pill's popover and at+ * the top of the phone's You sheet, so it never covers the page; the pill itself says it in short (ComputerPillFace).*/export function ComputerNote() {const note = noteOf(useComputerState());if (!note) return null;- const icon = note.problem ? (- <TriangleAlert className="size-4 shrink-0 text-amber-600 dark:text-amber-400" />- ) : (- <span className="relative grid size-4 shrink-0 place-items-center">- <Cpu className="size-4 text-brand-text" />- <span className="absolute -top-0.5 -right-0.5 size-1.5 animate-pulse rounded-full bg-primary" />- </span>+ return (+ <div role="status" className={cn("flex gap-2 rounded-md border px-2 py-1.5 text-[12px]", note.problem ? "border-amber-500/50" : "border-transparent bg-brand-faint")}>+ <NoteIcon problem={note.problem} />+ <div className="min-w-0 flex-1">+ <p className="leading-snug">{note.text}</p>+ {note.action && (+ <button type="button" onClick={note.go} className="mt-0.5 font-medium text-brand-text underline-offset-4 hover:underline">+ {note.action}+ </button>+ )}+ </div>+ </div>);+}++/**+ * What the bar's computer pill shows, so the note is seen without opening it: a warning and "Needs you" when there is+ * something to do, the GPU with a beat while it works, else the GPU. Its name starts with the words it shows (from xl;+ * the same words, unseen, below), then says the note. The live region that says a new note is ComputerNoteLive, beside+ * the button, so the note isn't in the button's name twice.+ */+export function ComputerPillFace() {+ const note = noteOf(useComputerState());+ const words = note?.problem ? "Needs you" : "Your computer";return (<>- <div role="status" className={cn("flex gap-2 rounded-md border px-2 py-1.5 text-[12px] group-data-[collapsible=icon]:hidden", note.problem ? "border-amber-500/50" : "border-transparent bg-brand-faint")}>- {icon}- <div className="min-w-0 flex-1">- <p className="leading-snug">{note.text}</p>- {note.action && (- <button type="button" onClick={note.go} className="mt-0.5 font-medium text-brand-text underline-offset-4 hover:underline">- {note.action}- </button>- )}- </div>- </div>- <button- type="button"- title={note.action ? `${note.text} ${note.action}` : note.text}- aria-label={note.text}- onClick={note.go}- className="hidden size-8 place-items-center self-center rounded-md hover:bg-accent group-data-[collapsible=icon]:grid"- >- {icon}- </button>+ {note ? <NoteIcon problem={note.problem} /> : <Cpu aria-hidden className="size-4 text-brand-text" />}+ <span className={cn("hidden xl:inline", note?.problem && "text-amber-700 dark:text-amber-300")}>{words}</span>+ <span className="sr-only xl:hidden">{words}</span>+ <span className="sr-only">+ , your computer's GPU{note ? `. ${note.text}` : ""}+ </span></>);}++/** Says the computer note politely when it changes (beside the pill, outside its button). */+export function ComputerNoteLive() {+ const note = noteOf(useComputerState());+ return (+ <span role="status" data-computer-note className="sr-only">+ {note?.text ?? ""}+ </span>+ );+}diff --git a/src/components/gpu/connect-choice.tsx b/src/components/gpu/connect-choice.tsxindex d371af54..70c96014 100644--- a/src/components/gpu/connect-choice.tsx+++ b/src/components/gpu/connect-choice.tsx@@ -399,7 +399,7 @@ export interface ConnectChoiceProps {/** The two options' box (and the link's form): 36rem at most from sm up, unless a wider page lifts that (sm:max-w-none). */className?: string;/**- * Opened by a button that already said "Use the ComfyUI on this computer" (the guide, the sidebar's Connect): look at+ * Opened by a button that already said "Use the ComfyUI on this computer" (the guide, the account menu's Connect): look at* once. Without it (and without a run or a reason) the finder waits for "Find my ComfyUI": a card that only shows the* choice (Settings, /connect) never moves the runs to this computer by itself.*/diff --git a/src/components/gpu/open-connect.ts b/src/components/gpu/open-connect.tsindex 6a145bae..ce0de166 100644--- a/src/components/gpu/open-connect.ts+++ b/src/components/gpu/open-connect.ts@@ -6,7 +6,7 @@ import { browserSupport, pageCanReach } from "@/lib/local-comfy";/*** Opening "Connect your GPU" (GuestPrompt) from anywhere, and whether this browser can use the ComfyUI on its computer.- * Kept small: the sidebar and the header pill use it without loading the finder or the runner.+ * Kept small: the account menu and the header pill use it without loading the finder or the runner.*//** Why the "Connect your GPU" card opens from the runner: ComfyUI needs the setting again, find ComfyUI, or allow this browser. */diff --git a/src/components/guest-prompt.tsx b/src/components/guest-prompt.tsxindex 2b0272f5..59c5ceb7 100644--- a/src/components/guest-prompt.tsx+++ b/src/components/guest-prompt.tsx@@ -223,7 +223,7 @@ function logInAgain(who: "owner" | "account", here?: string): string {const TITLES: Record<FindReason | RefusalAction | "connect", string> = {run: "Connect your GPU to run this",upload: "Connect your GPU or add a key to add your own files",- // Opened with no run waiting (the setup guide, the sidebar's Connect).+ // Opened with no run waiting (the setup guide, the account menu's Connect).connect: "Connect your GPU",setting: "Your ComfyUI needs Fuobe's setting again",find: "Find your ComfyUI",diff --git a/src/components/home-view.tsx b/src/components/home-view.tsxindex 9a07f043..5c112781 100644--- a/src/components/home-view.tsx+++ b/src/components/home-view.tsx@@ -117,7 +117,7 @@ function FirstRunScript() {}/**- * "New creation" (the sidebar, ⌘K) opens Home with ?new=1: the composer starts empty and takes the+ * "New creation" (the top bar, the Create sheet) opens Home with ?new=1: the composer starts empty and takes the* focus, and the flag leaves the address. It reads the URL, so it sits under Suspense.*/function NewCreation({ onNew }: { onNew: () => void }) {@@ -139,6 +139,7 @@ export function HomeView({openModels,chips,assist,+ goals,wall,children,prices,@@ -149,6 +150,8 @@ export function HomeView({chips: readonly TryChip[];/** The chip that opens Assist with a job typed in: the owner's, in place of the last Try chip. */assist: { label: string; href: string };+ /** The goal row (each goal opens a band of its studios, one-tap presets and tools), right under the composer. */+ goals?: React.ReactNode;wall: React.ReactNode;children: React.ReactNode;/** What a first paid image and clip cost, for the first-run guide. */@@ -390,20 +393,7 @@ export function HomeView({</IntentLink>)}</div>- {guide ? (- <>- <FirstRunScript />- <GetStarted- className={cn("mt-6 max-w-[960px]", !status && "hidden [html[data-first-run='1']_&]:block")}- status={status}- prices={prices}- onMode={(id) => {- setMode(MODES.find((m) => m.id === id) ?? MODES[0]);- focusComposer();- }}- />- </>- ) : nothingConnected && !status?.viewer && (+ {!guide && nothingConnected && !status?.viewer && (<p className="mt-4 text-[13px] text-muted-foreground">{/* Placeholders on (Settings, for a tour): say so; otherwise a run asks for a GPU or a key. */}{placeholdersOn(status?.demoMode) ? (@@ -427,6 +417,26 @@ export function HomeView({)}</div>+ {/* The goals sit right under the hero for everyone; the owner's first-run guide follows them (without its own+ "What do you want to do?" chips, which the goals already are). */}+ {goals}++ {guide && (+ <div className="flex flex-col items-center">+ <FirstRunScript />+ <GetStarted+ className={cn("mt-6 max-w-[960px]", !status && "hidden [html[data-first-run='1']_&]:block")}+ status={status}+ prices={prices}+ intents={!goals}+ onMode={(id) => {+ setMode(MODES.find((m) => m.id === id) ?? MODES[0]);+ focusComposer();+ }}+ />+ </div>+ )}+{wall}{recent.data?.length ? (diff --git a/src/components/home/before-after.tsx b/src/components/home/before-after.tsxindex 2624692e..8009ef93 100644--- a/src/components/home/before-after.tsx+++ b/src/components/home/before-after.tsx@@ -77,7 +77,7 @@ export function BeforeAfterPicture({ still, zoom, hd, onLoad }: { still: BeforeA* has loaded: a browser fetches lazy images well ahead, and on a slow line those would hold up the page's largest* paint.*- * From lg to xl (beside the sidebar) the tabs stand in a column next to the picture, in the room it leaves.+ * From lg to xl the tabs stand in a column next to the picture, in the room it leaves.*/export function BeforeAfter({ pairs }: { pairs: BeforeAfterPair[] }) {const [tab, setTab] = useState(0);diff --git a/src/components/home/home-sections.tsx b/src/components/home/home-sections.tsxindex 544d8db0..218a61ea 100644--- a/src/components/home/home-sections.tsx+++ b/src/components/home/home-sections.tsx@@ -203,7 +203,7 @@ export function LiveEditSection() {const WAVE = [0.3, 0.45, 0.7, 0.5, 0.85, 1, 0.75, 0.55, 0.4, 0.6, 0.9, 0.7, 0.45, 0.3, 0.5, 0.8, 0.95, 0.65, 0.4, 0.55, 0.75, 0.5, 0.35, 0.6, 0.8, 0.55, 0.35, 0.25,];-/** How many of the Audio card's tools it names where its card is narrowest (lg to xl, four cards a row beside the sidebar). */+/** How many of the Audio card's tools it names where its card is narrowest (lg to xl, four cards a row). */const AUDIO_NARROW = 3;/**diff --git a/src/components/home/showcase-tile.tsx b/src/components/home/showcase-tile.tsxindex dfea6fd1..efbf236a 100644--- a/src/components/home/showcase-tile.tsx+++ b/src/components/home/showcase-tile.tsx@@ -8,7 +8,7 @@ import { thumbOf, type PresetCardData } from "@/lib/preset-cards";import { staggered } from "@/lib/preview-playback";import { cn } from "@/lib/utils";-/** How wide a tile shows: half a phone, a quarter from sm, half again beside the sidebar from md, a quarter from lg. */+/** How wide a tile shows: half a phone, a quarter from sm, half again from md, a quarter from lg. */const SIZES = "(min-width: 1024px) 25vw, (min-width: 768px) 50vw, (min-width: 640px) 25vw, 50vw";/** Where tiles 5 to 8 show (the wall has four columns): a tablet held upright, and a desktop. */const FOUR_UP = "(min-width: 640px) and (max-width: 767px), (min-width: 1024px)";diff --git a/src/components/intent-link.tsx b/src/components/intent-link.tsxindex 0ed77933..57bbdbf0 100644--- a/src/components/intent-link.tsx+++ b/src/components/intent-link.tsx@@ -13,7 +13,7 @@ import { cn } from "@/lib/utils";* prefetch" of Next's prefetching guide). `eager` rows prefetch as soon as they're on screen, like a* plain Link: the few routes most visits go to next. `settled` rows prefetch once the page has* loaded and the browser is idle, also when scrolled out of view, after the page's own tabs- * (useIdlePrefetch's "nav" lane): the sidebar gives it to the few rows next to the open page's row.+ * (useIdlePrefetch's "nav" lane).* A page full of these fetches only those routes on a cold visit, not every route behind it.*/export function IntentLink({diff --git a/src/components/layers/layers-editor.tsx b/src/components/layers/layers-editor.tsxindex 25007e7b..b11b522f 100644--- a/src/components/layers/layers-editor.tsx+++ b/src/components/layers/layers-editor.tsx@@ -66,7 +66,7 @@ const RETRY_MS = [2000, 5000, 15000];function EditorSkeleton() {return (- <div className="flex h-svh min-w-0 flex-col overflow-hidden md:h-[calc(100svh-0.5rem)]">+ <div className="flex h-content min-w-0 flex-col overflow-hidden"><div className="flex h-14 items-center gap-3 border-b px-3"><Skeleton className="h-6 w-40" /><Skeleton className="ml-auto h-8 w-64 rounded-full" />@@ -661,7 +661,7 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()return (<Ctx.Provider value={ctx}>- <div className="flex h-svh min-w-0 flex-col overflow-hidden md:h-[calc(100svh-0.5rem)]">+ <div className="flex h-content min-w-0 flex-col overflow-hidden"><TopBarname={view.project.name}onRename={(n) => void actions.rename(id, n).catch((e) => toastError(e))}diff --git a/src/components/layers/mobile-view.tsx b/src/components/layers/mobile-view.tsxindex fdef2eea..b1bf4be0 100644--- a/src/components/layers/mobile-view.tsx+++ b/src/components/layers/mobile-view.tsx@@ -5,7 +5,7 @@ import Link from "next/link";import { useEffect, useState } from "react";import { Button } from "@/components/ui/button";import { Progress } from "@/components/ui/progress";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { DECOMPOSE_COPY, jobStatusText, type LayerDoc, type LayerJob, type LayerProject } from "@/lib/layers";import { isFailed, isRunning, latestJob } from "./editor-context";@@ -60,9 +60,8 @@ export function MobileView({const failed = pending && isFailed(pending) ? pending : undefined;return (- <div className="flex min-h-svh min-w-0 flex-col">- <header className="sticky top-0 z-20 flex h-14 items-center gap-1.5 bg-background/85 px-3 backdrop-blur">- <SidebarTrigger />+ <div className="flex min-h-content min-w-0 flex-col">+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-1.5 bg-background/85 px-3 backdrop-blur"><Button asChild variant="ghost" size="icon-sm" aria-label="All projects"><Link href="/layers"><ArrowLeft />@@ -70,6 +69,7 @@ export function MobileView({</Button><h1 className="min-w-0 flex-1 truncate font-heading text-[20px]">{project.name}</h1><DownloadMenu doc={doc} name={project.name} jobs={jobs} compact />+ <PhoneNavButton /></header><div className="mx-auto w-full max-w-xl flex-1 space-y-5 px-4 pb-12">{!decomposed && !running && !failed ? (diff --git a/src/components/layers/top-bar.tsx b/src/components/layers/top-bar.tsxindex d2e02ea4..a48e3128 100644--- a/src/components/layers/top-bar.tsx+++ b/src/components/layers/top-bar.tsx@@ -17,7 +17,7 @@ import {} from "@/components/ui/dropdown-menu";import { Kbd } from "@/components/ui/kbd";import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { EngineSwitch } from "@/components/studio/engine-switch";import type { Engine } from "@/lib/catalog/types";@@ -172,7 +172,6 @@ export function TopBar(p: {return (<header className="flex h-14 shrink-0 items-center gap-1.5 border-b bg-background px-2 sm:px-3">- <SidebarTrigger className="md:hidden" /><Tooltip><TooltipTrigger asChild><Button asChild variant="ghost" size="icon-sm" aria-label="All projects">@@ -248,7 +247,7 @@ export function TopBar(p: {</TooltipTrigger><TooltipContent>{p.doc.nodes.length ? "Copy the layers as a design file (JSON)" : "Add a layer to copy as JSON."}</TooltipContent></Tooltip>- {/* Icons only below 1024 px (names stay in the tooltips and aria labels), so a tablet with the sidebar open keeps both engines in reach. */}+ {/* Icons only below 1024 px (names stay in the tooltips and aria labels), so a tablet keeps both engines in reach. */}<div className="flex shrink-0 max-lg:[&_a>span]:hidden max-lg:[&_button>span]:hidden"><EngineSwitch value={p.engine} onChange={p.setEngine} /></div>@@ -305,6 +304,7 @@ export function TopBar(p: {</ol></SheetContent></Sheet>+ <PhoneNavButton /></header>);}diff --git a/src/components/library-view.tsx b/src/components/library-view.tsxindex acc924e8..2038c478 100644--- a/src/components/library-view.tsx+++ b/src/components/library-view.tsx@@ -797,7 +797,7 @@ function Inner() {)}{(selecting || selected.size > 0) && !uploadsTab && !sharedTab && (- <div className="pointer-events-none fixed inset-x-0 bottom-0 z-30 flex justify-center px-3 pb-[max(1rem,env(safe-area-inset-bottom))] md:pl-[var(--sidebar-width,0px)]">+ <div className="pointer-events-none fixed inset-x-0 bottom-chrome z-30 flex justify-center px-3 pb-[max(1rem,env(safe-area-inset-bottom))]"><div role="toolbar" aria-label="Selection" className="pointer-events-auto flex max-w-full items-center gap-1 overflow-x-auto rounded-full border bg-background p-1.5 shadow-strong">{/* Phones show just the count, so every action fits at 390 px. */}<span className="shrink-0 px-2.5 text-[13px] font-medium whitespace-nowrap">diff --git a/src/components/live/live-edit-app.tsx b/src/components/live/live-edit-app.tsxindex 363f270e..28f0c542 100644--- a/src/components/live/live-edit-app.tsx+++ b/src/components/live/live-edit-app.tsx@@ -6,7 +6,7 @@ import { useSearchParams } from "next/navigation";import { useMemo, useState } from "react";import { openConnect, useComputerSupport } from "@/components/gpu/open-connect";import { rememberedComfy } from "@/components/gpu/computer-runtime";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Button } from "@/components/ui/button";import { signInHref, useHydrated, useStatus, useViewer } from "@/lib/api";import { cn } from "@/lib/utils";@@ -116,7 +116,7 @@ export function LiveEditPanel({ image, text, onUse, onClose }: { image?: string;export function LiveSkeleton() {return (- <div className="flex h-[100dvh] flex-col gap-3 p-3 sm:p-4" aria-busy>+ <div className="flex h-content flex-col gap-3 p-3 sm:p-4" aria-busy><div className="h-8 w-48 animate-pulse rounded-lg bg-muted" /><div className="min-h-0 flex-1 animate-pulse rounded-2xl bg-muted" /><div className="h-11 animate-pulse rounded-2xl bg-muted" />@@ -128,14 +128,14 @@ export function LiveSkeleton() {function LiveShowcase({ kind }: { kind: "guest" | "connect" | "unsupported" }) {const [nudge, setNudge] = useState(false);return (- <div className="flex min-h-[100dvh] flex-col">+ <div className="flex min-h-content flex-col"><header className="flex h-14 shrink-0 items-center gap-2 px-3 sm:px-6">- <SidebarTrigger className="md:hidden" /><h1 className="flex items-center gap-2 font-heading text-[22px] leading-none"><Zap className="size-4 text-primary" />Live edit</h1><span className="ml-1 rounded-full bg-highlight px-2 py-0.5 text-[11px] font-semibold text-highlight-foreground">New</span>+ <PhoneNavButton className="ml-auto" /></header><div className="mx-auto grid w-full max-w-6xl flex-1 items-center gap-6 px-3 pb-6 sm:px-6 lg:grid-cols-[minmax(0,1.5fr)_minmax(0,1fr)] lg:gap-10"><LiveDemo className="aspect-[4/3] w-full shadow-strong" onTypeAttempt={() => setNudge(true)} />diff --git a/src/components/live/live-editor.tsx b/src/components/live/live-editor.tsxindex d9bddcbd..67cff492 100644--- a/src/components/live/live-editor.tsx+++ b/src/components/live/live-editor.tsx@@ -998,7 +998,7 @@ export function LiveEditor(props: LiveEditorProps) {return (<div- className={cn("flex min-h-0 w-full flex-col bg-background", embedded ? "h-full rounded-2xl border" : "h-[100dvh]")}+ className={cn("flex min-h-0 w-full flex-col bg-background", embedded ? "h-full rounded-2xl border" : "h-content")}data-live-editoronDragOver={(e) => {if ([...e.dataTransfer.items].some((i) => i.kind === "file")) {diff --git a/src/components/marketing/click-to-ad.tsx b/src/components/marketing/click-to-ad.tsxindex c96b7e25..9de23ac8 100644--- a/src/components/marketing/click-to-ad.tsx+++ b/src/components/marketing/click-to-ad.tsx@@ -280,7 +280,7 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {};return (- <div className="flex min-h-svh min-w-0 flex-col">+ <div className="flex min-h-content min-w-0 flex-col"><MarketingHeader title="Click to Ad" active="click" engine={engine} onEngine={setEngine} selfHostedOnly /><div className="mx-auto w-full min-w-0 max-w-[980px] flex-1 space-y-5 px-3 pt-6 pb-20 sm:px-6 sm:pt-10"><div className="pb-2 text-center">diff --git a/src/components/marketing/marketing-studio.tsx b/src/components/marketing/marketing-studio.tsxindex 13cd3d16..356c6d7e 100644--- a/src/components/marketing/marketing-studio.tsx+++ b/src/components/marketing/marketing-studio.tsx@@ -397,7 +397,7 @@ export function MarketingStudio({ models }: { models: Record<string, ModelInfo>};return (- <div className="flex min-h-svh min-w-0 flex-col">+ <div className="flex min-h-content min-w-0 flex-col"><MarketingHeader title="Marketing Studio" active="studio" engine={engine} onEngine={setEngine} selfHostedOnly /><Suspense fallback={null}><UrlParams onTemplate={pickTemplate} onTab={setTab} />@@ -449,7 +449,7 @@ export function MarketingStudio({ models }: { models: Record<string, ModelInfo></div>{/* Docked composer */}- <div className="sticky bottom-0 z-20 bg-gradient-to-t from-background via-background/95 to-transparent px-3 pt-8 pb-[max(0.75rem,env(safe-area-inset-bottom))] sm:px-6">+ <div className="sticky bottom-chrome z-20 bg-gradient-to-t from-background via-background/95 to-transparent px-3 pt-8 pb-[max(0.75rem,env(safe-area-inset-bottom))] sm:px-6"><divref={composer}data-slim={slim || undefined}diff --git a/src/components/marketing/shell.tsx b/src/components/marketing/shell.tsxindex 7315be50..863cb8f5 100644--- a/src/components/marketing/shell.tsx+++ b/src/components/marketing/shell.tsx@@ -3,7 +3,7 @@import { Clapperboard, Copy, LayoutTemplate, MousePointerClick, Target } from "lucide-react";import Link from "next/link";import { useEffect, useRef } from "react";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { EngineSwitch } from "@/components/studio/engine-switch";import { useEngine } from "@/lib/api";import type { Engine } from "@/lib/catalog/types";@@ -44,7 +44,7 @@ export function MarketingHeader({// (with its own header) replaces this one.const [tapped, tap] = useTappedTab<SuiteTab>(active);const current = tapped ?? active;- // The other tools are the likeliest next tap: their pages go ahead of the sidebar's routes (the "page" lane), so a busy+ // The other tools are the likeliest next tap: their pages go ahead of the navigation's routes (the "page" lane), so a busy// prefetch queue never leaves a tab waiting on the server.useIdlePrefetch(TABS.filter((t) => t.id !== active).map((t) => t.href),@@ -58,14 +58,14 @@ export function MarketingHeader({if (el.offsetLeft + el.offsetWidth > box.scrollLeft + box.clientWidth || el.offsetLeft < box.scrollLeft) box.scrollLeft = el.offsetLeft - 12;}, [active]);return (- <header className="sticky top-0 z-30 border-b border-transparent bg-background/85 backdrop-blur supports-[backdrop-filter]:bg-background/70">+ <header className="sticky top-chrome z-30 border-b border-transparent bg-background/85 backdrop-blur supports-[backdrop-filter]:bg-background/70"><div className="flex h-14 min-w-0 items-center gap-2 px-3 sm:px-6">- <SidebarTrigger className="md:hidden" /><h1 className="min-w-0 truncate font-heading text-[22px] leading-none">{title}</h1><div className="ml-auto flex shrink-0 items-center gap-2">{right}{engine && onEngine && <EngineSwitch value={engine} onChange={onEngine} selfHostedOnly={selfHostedOnly} />}</div>+ <PhoneNavButton /></div><nav ref={nav} aria-label="Marketing tools" className="scrollbar-none -mb-px flex gap-1 overflow-x-auto px-3 sm:px-6">{TABS.map((t) => (diff --git a/src/components/marketing/skeletons.tsx b/src/components/marketing/skeletons.tsxindex 273d3813..c33c2b30 100644--- a/src/components/marketing/skeletons.tsx+++ b/src/components/marketing/skeletons.tsx@@ -11,7 +11,7 @@ import { MarketingHeader, type SuiteTab } from "./shell";*/function MarketingFrame({ title, active, children }: { title: string; active: SuiteTab; children: React.ReactNode }) {return (- <div className="flex min-h-svh min-w-0 flex-col">+ <div className="flex min-h-content min-w-0 flex-col"><MarketingHeader title={title} active={active} right={<Skeleton className="h-9 w-40 rounded-full max-sm:w-20" />} /><div className="flex min-w-0 flex-1 flex-col" aria-busy="true" aria-label="Loading">{children}@@ -57,7 +57,7 @@ export function MarketingSkeleton() {))}</div></div>- <div className="sticky bottom-0 px-3 pb-3 sm:px-6">+ <div className="sticky bottom-chrome px-3 pb-3 sm:px-6"><Skeleton className="mx-auto h-14 w-full max-w-[860px] rounded-[20px] sm:rounded-composer" /></div></MarketingFrame>diff --git a/src/components/mixed-media/mixed-studio.tsx b/src/components/mixed-media/mixed-studio.tsxindex 6d5c4be2..cd96e944 100644--- a/src/components/mixed-media/mixed-studio.tsx+++ b/src/components/mixed-media/mixed-studio.tsx@@ -4,7 +4,7 @@ import { ArrowDown, Cloud, Cpu, Download, ImageIcon, Info, Loader2, Search, Sparimport { useDeferredValue, useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { SelfHostNote } from "@/components/self-host-note";import { EngineSwitch } from "@/components/studio/engine-switch";import { MediaThumb } from "@/components/studio/result-media";@@ -103,9 +103,8 @@ export function MixedStudio({window.history.replaceState(null, "", url);};return (- <div className="flex min-h-svh min-w-0 flex-col">- <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <div className="flex min-h-content min-w-0 flex-col">+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6"><h1 className="sr-only font-heading text-[22px] leading-none sm:not-sr-only sm:truncate">Mixed Media</h1><div role="tablist" aria-label="Mixed Media" onKeyDown={tabKeys} className="fade-x scrollbar-none flex h-8 min-w-0 items-center overflow-x-auto rounded-full bg-muted p-0.5 sm:ml-4">{TABS.map((t) => (@@ -126,6 +125,7 @@ export function MixedStudio({{/* A phone's header has room for the tabs, not "Add key" too. */}<EngineSwitch value={engine} onChange={setEngine} wordless selfHostedOnly /></div>+ <PhoneNavButton /></header><div className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 px-3 pb-28 sm:px-6 lg:pb-16">{tab === "history" ? (@@ -273,11 +273,11 @@ function Workspace({ visitor, engine, models, frameModels }: { visitor: boolean;</div>)}</section>- <aside ref={panel} id="mm-editor" className="scrollbar-none min-w-0 scroll-mt-16 lg:sticky lg:top-16 lg:max-h-[calc(100svh-4.5rem)] lg:overflow-y-auto lg:overscroll-contain lg:rounded-2xl">+ <aside ref={panel} id="mm-editor" className="scrollbar-none min-w-0 scroll-mt-16 lg:sticky lg:top-[calc(var(--chrome-top)+4rem)] lg:max-h-[calc(var(--content-h)-4.5rem)] lg:overflow-y-auto lg:overscroll-contain lg:rounded-2xl"><Editor visitor={visitor} engine={engine} models={models} frameModels={frameModels} preset={preset} values={values} setValues={setValues} onClip={setHasClip} /></aside>{preset && !panelVisible && (- <div className="fixed inset-x-3 bottom-[max(0.75rem,env(safe-area-inset-bottom))] z-30 lg:hidden">+ <div className="fixed inset-x-3 bottom-[max(calc(var(--chrome-bottom)+0.75rem),env(safe-area-inset-bottom))] z-30 lg:hidden"><buttontype="button"onClick={() => panel.current?.scrollIntoView({ behavior: "smooth", block: "start" })}diff --git a/src/components/model3d/model-card.tsx b/src/components/model3d/model-card.tsxindex 2bb3a46a..1d2fa3c2 100644--- a/src/components/model3d/model-card.tsx+++ b/src/components/model3d/model-card.tsx@@ -14,8 +14,18 @@ import { toastError } from "@/lib/refusals";import { loadModelViewer, TURNTABLE_BACKDROP, useViewerSrc, viewerLook } from "./model-viewer";import { RigDialog } from "./rig-dialog";import { PlaceholderChip } from "@/components/demo-mode";+import { NextSteps } from "@/components/nav/next-steps";import { recordableType, recordTurntable } from "./turntable";+/**+ * Left out of the card's next steps: its own Animate the spin button is that step (and knows a turntable recorded+ * here), and a rigged character has none.+ */+const SPIN_STEPS = ["animate-spin"] as const;++/** The model file among a result's outputs (its turntable and poster ride along as other outputs); -1 without one. */+const modelAt = (g: Generation) => g.outputs.findIndex((o) => o.kind === "model3d");+/** Downloads besides the main file, by the name the provider gave them. */const FORMAT_LABEL: Record<string, string> = { rigged: "Rigged .glb", walking: "Walk .glb", running: "Run .glb", fbx: ".fbx", splat: "Splat" };const formatLabel = (k: string) => FORMAT_LABEL[k] ?? `.${k}`;@@ -350,6 +360,8 @@ export function ModelCard({ g, cloudAllowed }: { g: Generation; cloudAllowed: bo</Button>)}</div>+ {/* Where the model goes next: an ad, a sharper still (its own Animate the spin button is above). */}+ {modelAt(g) >= 0 && <NextSteps g={g} index={modelAt(g)} variant="row" max={3} skip={SPIN_STEPS} className="pt-1" />}</div>{rigSource && rigging && g.op !== "splat" && <RigDialog glb={rigSource} open={rigging} onOpenChange={setRigging} cloudAllowed={cloudAllowed} />}</article>diff --git a/src/components/model3d/model3d-studio.tsx b/src/components/model3d/model3d-studio.tsxindex f42daf5f..cce8d24b 100644--- a/src/components/model3d/model3d-studio.tsx+++ b/src/components/model3d/model3d-studio.tsx@@ -1,6 +1,7 @@"use client";import { Box, Loader2, PersonStanding } from "lucide-react";+import { nanoid } from "nanoid";import { useRouter, useSearchParams } from "next/navigation";import { Suspense, useCallback, useEffect, useRef, useState } from "react";import { toast } from "sonner";@@ -15,6 +16,7 @@ import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";import { MediaDrop } from "@/components/av/media-drop";import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";import { SelfHostNote } from "@/components/self-host-note";+import { HandoffImage } from "@/components/nav/next-steps";import { ExampleRow } from "@/components/studio/example-row";import { useCreateGeneration, useEngine, useGenerations, useHydrated, useLikelyVisitor, useModelAccess, useStatus } from "@/lib/api";import {@@ -156,6 +158,13 @@ export function Model3dStudio({ info, examples }: { info: Record<string, Model3d},[setEngine],);+ // A picture sent here ("Turn it into 3D" under a result): the photo of From an image, and the front of Several sides.+ const takeHandoff = useCallback((url: string) => {+ const slot: SlotValue = { ref: url, preview: url, kind: "image", id: nanoid(8) };+ setMode((m) => (m === "multi" || m === "text" ? "image" : m));+ setPhoto((p) => (p?.ref === url ? p : slot));+ setViews((v) => (v.front ? v : { ...v, front: slot }));+ }, []);// Models switched off in Settings → Models & licences leave the menu, and the pick falls back to one that is on.const choices = keepOffered(MODELS_3D[mode][engine], (m) => offered(access, m.id, engine));const wanted = picked[`${mode}:${engine}`];@@ -188,6 +197,7 @@ export function Model3dStudio({ info, examples }: { info: Record<string, Model3d<ToolShell title="Image to 3D" selfHostedOnly><Suspense fallback={null}><UrlModel onModel={fromUrl} onMode={setMode} onRig={showRigHint} />+ <HandoffImage onImage={takeHandoff} /></Suspense><ToolHero title="Your product, in 3D" subtitle={HINTS[mode]}>{visitor && <SelfHostNote className="mt-3 max-w-xl">Image to 3D isn't available here.</SelfHostNote>}diff --git a/src/components/nav-items.ts b/src/components/nav-items.tsindex 66a9e1eb..78449114 100644--- a/src/components/nav-items.ts+++ b/src/components/nav-items.ts@@ -1,50 +1,6 @@-import {- AtSign,- AudioLines,- Box,- Brush,- Camera,- Clapperboard,- Drama,- Crop,- Factory,- FastForward,- Film,- GalleryHorizontal,- Home,- ImageIcon,- Images,- Layers,- Layers2,- LayoutGrid,- Library,- Megaphone,- MessageCircle,- Mic2,- Network,- PersonStanding,- Presentation,- Scissors,- Settings,- Shapes,- Shirt,- SlidersHorizontal,- Smartphone,- Sparkles,- Star,- Swords,- Target,- TrendingUp,- Tv,- UserRoundCog,- UserRoundPen,- Video,- Wand2,- WandSparkles,- Zap,- ZoomIn,- type LucideIcon,-} from "lucide-react";+import type { LucideIcon } from "lucide-react";+import { navIcon } from "@/lib/nav-icons";+import { entry, type NavEntry } from "@/lib/nav-model";export interface NavItem {href: string;@@ -54,83 +10,84 @@ export interface NavItem {short?: string;/** Prefetched as soon as it's on screen (the rows most visits start from); the others wait for a hover or touch. */eager?: boolean;- /** More words the ⌘K palette matches ("tts" finds Audio). */+ /** More words search matches ("tts" finds Audio). */keywords?: string;}export interface NavGroupDef {label: string;items: NavItem[];- /** Can be folded away; the choice is remembered (see DEFAULT_NAV_CLOSED). */+ /** Can be folded away. */collapsible?: boolean;/** Two small items per row. */compact?: boolean;}-/** The sidebar, and the destinations of the ⌘K palette. Add a destination with one line in the right group. */-export const NAV: NavGroupDef[] = [+/**+ * The places to create, the library, the studios and settings as four groups, in a fixed order (Home's+ * showcase reads Create and Studios). Labels, links and search words come from the navigation model+ * (src/lib/nav-model.ts); only the grouping and the order are kept here.+ */+const GROUPS: { label: string; ids: string[]; collapsible?: boolean }[] = [{label: "Create",- items: [- { href: "/", label: "Home", icon: Home, eager: true, keywords: "start new creation" },- { href: "/assist", label: "Assist", icon: MessageCircle, eager: true, keywords: "agent chat plan" },- { href: "/image", label: "Image", icon: ImageIcon, eager: true, keywords: "text to image picture photo" },- { href: "/video", label: "Video", icon: Video, eager: true, keywords: "text to video image to video animate" },- { href: "/edit", label: "Edit", icon: Wand2, keywords: "edit image change" },- { href: "/live-edit", label: "Live edit", icon: Zap, keywords: "realtime live as you type instant change" },- { href: "/layers", label: "Layers", icon: Layers2, keywords: "layered psd split" },- { href: "/inpaint", label: "Inpaint", icon: Brush, keywords: "mask fill remove" },- { href: "/color-grade", label: "Color grading", icon: SlidersHorizontal, keywords: "grade lut colour" },- { href: "/motions", label: "Camera motions", icon: Film, keywords: "camera moves presets" },- { href: "/effects", label: "Effects", icon: Sparkles, keywords: "vfx presets" },- { href: "/storyboard", label: "Storyboard", icon: GalleryHorizontal, keywords: "frames story" },- { href: "/canvas", label: "Canvas", icon: Network, keywords: "nodes flow workflow" },- { href: "/apps", label: "Apps", icon: LayoutGrid, keywords: "one-click tools" },- ],- },- {- label: "Library",- items: [- { href: "/library", label: "All creations", icon: Library, eager: true, keywords: "library history results" },- { href: "/library?tab=favorites", label: "Favorites", icon: Star, keywords: "starred liked" },- ],+ ids: ["home", "assist", "image", "video", "edit", "live-edit", "layers", "inpaint", "color-grade", "motions", "effects", "storyboard", "canvas", "apps"],},+ { label: "Library", ids: ["library", "favorites"] },{label: "Studios",- items: [- { href: "/cinema", label: "Cinema Studio", icon: Clapperboard, keywords: "film director shots" },- { href: "/shorts", label: "Shorts Studio", icon: Smartphone, keywords: "vertical reels tiktok" },- { href: "/mixed-media", label: "Mixed Media", icon: Shapes, keywords: "collage" },- { href: "/marketing", label: "Marketing Studio", icon: Megaphone, keywords: "ugc product ads" },- { href: "/ads", label: "Ads Studio", icon: Target, keywords: "brand campaign" },- { href: "/moodboards", label: "Moodboards", icon: Images, keywords: "style references" },- { href: "/photodump", label: "Photodump", icon: Camera, keywords: "photo pack character" },- { href: "/fashion-factory", label: "Fashion Factory", icon: Shirt, keywords: "outfits try-on lookbook" },- { href: "/character-sheet", label: "Character Sheet", icon: UserRoundCog, keywords: "turnaround" },- { href: "/influencer", label: "AI Influencer", icon: UserRoundPen, keywords: "character builder avatar creature shuffle" },- { href: "/faceless", label: "Faceless Studio", icon: Tv, keywords: "youtube channel episodes" },- { href: "/content-factory", label: "Content Factory", icon: Factory, keywords: "series reference brief episodes" },- { href: "/explainer", label: "Explainer", icon: Presentation, keywords: "slides pdf video" },- { href: "/lipsync", label: "Lipsync & avatars", icon: Mic2, keywords: "talking avatar" },- { href: "/genjutsu", label: "Genjutsu", icon: WandSparkles, keywords: "swap insert character motion transfer" },- { href: "/character-swap", label: "Character Swap Studio", short: "Character swap", icon: Drama, keywords: "h3 akatz swap character whole clip shots segments takes" },- { href: "/motion-control", label: "Motion control", icon: PersonStanding, keywords: "pose dance transfer" },- { href: "/video-edit", label: "Edit video", icon: Scissors, keywords: "video edit restyle" },- { href: "/extend", label: "Extend video", icon: FastForward, keywords: "longer continue" },- { href: "/reframe", label: "Reframe", icon: Crop, keywords: "aspect ratio outpaint" },- { href: "/video-tools", label: "Video tools", icon: Layers, keywords: "join trim matte depth captions evolution remove object restore colourise colorize archive old footage black and white" },- { href: "/elements", label: "Elements", icon: AtSign, keywords: "characters places props" },- { href: "/upscale", label: "Upscale", icon: ZoomIn, keywords: "enhance resolution 4k" },- { href: "/audio", label: "Audio", icon: AudioLines, keywords: "voice tts music sfx dub transcribe" },- { href: "/katana", label: "Katana", icon: Swords, keywords: "cut edit clips" },- { href: "/image-to-3d", label: "Image to 3D", icon: Box, keywords: "3d mesh glb" },- { href: "/virality", label: "Hook check", icon: TrendingUp, keywords: "virality predictor hook score" },+ ids: [+ "cinema",+ "shorts",+ "mixed-media",+ "marketing",+ "ads",+ "moodboards",+ "photodump",+ "fashion-factory",+ "character-sheet",+ "influencer",+ "faceless",+ "content-factory",+ "explainer",+ "lipsync",+ "genjutsu",+ "character-swap",+ "motion-control",+ "video-edit",+ "extend",+ "reframe",+ "video-tools",+ "elements",+ "upscale",+ "audio",+ "katana",+ "image-to-3d",+ "virality",],collapsible: true,},- {- label: "More",- items: [{ href: "/settings", label: "Settings", icon: Settings, keywords: "account gpu preferences" }],- collapsible: true,- },+ { label: "More", ids: ["settings"], collapsible: true },];++/** A shorter label where a row is narrow ("Character swap"); the phone tiles use the model's own `short`. */+const ROW_SHORT: Record<string, string> = { "character-swap": "Character swap" };++const item = (e: NavEntry): NavItem => ({+ href: e.href,+ label: e.label,+ icon: navIcon(e.icon),+ ...(ROW_SHORT[e.id] && { short: ROW_SHORT[e.id] }),+ ...(e.eager && { eager: true }),+ keywords: e.keywords,+});++export const NAV: NavGroupDef[] = GROUPS.map((g) => ({+ label: g.label,+ items: g.ids.map((id) => {+ const e = entry(id);+ if (!e) throw new Error(`The navigation model has no ${id}`);+ return item(e);+ }),+ ...(g.collapsible && { collapsible: true }),+}));diff --git a/src/components/nav/account-menu.tsx b/src/components/nav/account-menu.tsxnew file mode 100644index 00000000..5f636488--- /dev/null+++ b/src/components/nav/account-menu.tsx@@ -0,0 +1,293 @@+"use client";++import { Cpu, Heart, LogIn, LogOut, Moon, Scale, Settings2, Sun, UserPlus, UserRound } from "lucide-react";+import { usePathname, useSearchParams } from "next/navigation";+import { useTheme } from "next-themes";+import { Suspense } from "react";+import { PlaceholdersOnChip } from "@/components/demo-mode";+import { GitHubMark } from "@/components/github-mark";+import { IntentLink } from "@/components/intent-link";+import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { signInHref, signOut, useEngineMode, useViewer } from "@/lib/api";+import { FUOBE_REPO } from "@/lib/connections";+import type { ViewerKind } from "@/lib/nav-model";+import { cn } from "@/lib/utils";+import { NAV_MENU_ITEM } from "./create-menu";+import { ExploreProgress } from "./explore-progress";+import { useViewerKind } from "./nav-ui";+import { avatarDot, OwnerStatus, usePlaceholdersOn, useShownStatus, VisitorGpu } from "./status-chips";++/*+ * The account menu (the avatar at the bar's right end) and the phone's You sheet: who is signed in, the GPU and its+ * status as the sidebar's footer said it, how much of Fuobe this browser has explored, then Settings, the theme and the+ * source. What each viewer sees:+ * guest Sign up free, Log in · Your GPU (sign up first) · explore · theme, GitHub+ * account Signed in as <email> · balance or their own GPU · explore · Settings, Your GPU, theme, GitHub · Sign out+ * owner Your setup · cloud models, ComfyUI, mode, the owner's GPU, Placeholders on · explore · Settings, Models &+ * licences, theme, GitHub+ * The owner's status words exist only in the owner's branch: a guest's or an account's menu never says them.+ */++type Variant = "menu" | "sheet";++/** This page with its query, for Sign up and Log in to come back to (inside Suspense: the query is runtime data). */+function useHere(): string {+ const pathname = usePathname();+ const search = useSearchParams().toString();+ return search ? `${pathname}?${search}` : pathname;+}++const SHEET_ROW =+ "flex min-h-12 w-full items-center gap-3 rounded-xl px-3 text-left text-[15px] outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring motion-safe:transition-colors [&_svg]:size-[18px] [&_svg]:shrink-0 [&_svg]:text-muted-foreground";+const MENU_ROW = `h-9 gap-2.5 rounded-md px-2 text-[13.5px] [&_svg]:text-muted-foreground ${NAV_MENU_ITEM}`;++function GuestIdentity({ variant, here }: { variant: Variant; here: string }) {+ if (variant === "menu")+ return (+ <DropdownMenuGroup className="flex flex-col gap-1 p-1">+ <DropdownMenuItem asChild className="h-9 justify-center gap-2 rounded-lg bg-primary text-[13.5px] font-semibold text-primary-foreground focus:bg-primary/90 focus:text-primary-foreground [&_svg]:text-primary-foreground">+ <a href={signInHref("signup", here)}>+ <UserPlus aria-hidden /> Sign up free+ </a>+ </DropdownMenuItem>+ <DropdownMenuItem asChild className="h-9 justify-center gap-2 rounded-lg border text-[13.5px]">+ <a href={signInHref("login", here)}>+ <LogIn aria-hidden /> Log in+ </a>+ </DropdownMenuItem>+ </DropdownMenuGroup>+ );+ return (+ <div className="grid grid-cols-2 gap-2">+ <a+ href={signInHref("signup", here)}+ className="flex h-12 items-center justify-center gap-2 rounded-xl bg-primary text-[15px] font-semibold text-primary-foreground outline-none hover:bg-primary/90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"+ >+ <UserPlus aria-hidden className="size-[18px]" /> Sign up free+ </a>+ <a+ href={signInHref("login", here)}+ className="flex h-12 items-center justify-center gap-2 rounded-xl border text-[15px] font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"+ >+ <LogIn aria-hidden className="size-[18px]" /> Log in+ </a>+ </div>+ );+}++function GuestIdentityHere({ variant }: { variant: Variant }) {+ return <GuestIdentity variant={variant} here={useHere()} />;+}++function Identity({ kind, variant }: { kind: ViewerKind | undefined; variant: Variant }) {+ const email = useViewer().data?.account?.email;+ if (kind === "guest")+ return (+ <Suspense fallback={<GuestIdentity variant={variant} here="/" />}>+ <GuestIdentityHere variant={variant} />+ </Suspense>+ );+ if (kind === "account" && email)+ return variant === "menu" ? (+ <DropdownMenuLabel className="flex flex-col font-normal">+ <span className="text-[11px] text-muted-foreground">Signed in as</span>+ <span className="text-[13px] [overflow-wrap:anywhere] text-foreground">{email}</span>+ </DropdownMenuLabel>+ ) : (+ <div className="flex flex-col px-1">+ <span className="text-[12px] text-muted-foreground">Signed in as</span>+ <span className="text-[15px] font-medium [overflow-wrap:anywhere]">{email}</span>+ </div>+ );+ if (kind === "owner")+ return variant === "menu" ? (+ <DropdownMenuLabel className="pt-2 pb-1 text-[11px] font-semibold tracking-[.08em] text-brand-text uppercase">Your setup</DropdownMenuLabel>+ ) : (+ <p className="px-1 text-[11px] font-semibold tracking-[.08em] text-brand-text uppercase">Your setup</p>+ );+ return null;+}++/** The status block: an owner's install status, a visitor's own GPU or balance (as the sidebar footer showed them). */+function GpuSection({ kind, variant }: { kind: ViewerKind | undefined; variant: Variant }) {+ const placeholders = usePlaceholdersOn(kind);+ const item = variant === "menu";+ if (kind === "owner")+ return (+ <div className={cn("flex flex-col", item ? "gap-0.5" : "gap-1")}>+ <OwnerStatus item={item} />+ {placeholders &&+ (item ? (+ // From xl the bar shows this pill itself, so the menu leaves it out.+ <DropdownMenuLabel className="py-1 font-normal xl:hidden">+ <PlaceholdersOnChip />+ </DropdownMenuLabel>+ ) : (+ <div className="px-2 py-1">+ <PlaceholdersOnChip />+ </div>+ ))}+ </div>+ );+ if (kind === "guest" || kind === "account") return <VisitorGpu item={item} />;+ return null;+}++function ThemeToggle({ variant }: { variant: Variant }) {+ const { resolvedTheme, setTheme } = useTheme();+ const flip = () => setTheme(resolvedTheme === "dark" ? "light" : "dark");+ // The label follows the page's class (dark:), so the server's HTML and the first client render agree.+ const inner = (+ <>+ <Sun aria-hidden className="hidden dark:block" />+ <Moon aria-hidden className="dark:hidden" />+ <span className="hidden dark:inline">Light mode</span>+ <span className="dark:hidden">Dark mode</span>+ </>+ );+ return variant === "menu" ? (+ <DropdownMenuItem+ className={MENU_ROW}+ onSelect={(e) => {+ // The menu stays open: the change shows on it at once.+ e.preventDefault();+ flip();+ }}+ >+ {inner}+ </DropdownMenuItem>+ ) : (+ <button type="button" className={SHEET_ROW} onClick={flip}>+ {inner}+ </button>+ );+}++/** One link of the Links section, as a menu item or a sheet row. */+function LinkRow({ variant, href, external, children }: { variant: Variant; href: string; external?: boolean; children: React.ReactNode }) {+ const link = external ? (+ <a href={href} target="_blank" rel="noreferrer" className={variant === "sheet" ? SHEET_ROW : undefined}>+ {children}+ </a>+ ) : (+ <IntentLink href={href} className={variant === "sheet" ? SHEET_ROW : undefined}>+ {children}+ </IntentLink>+ );+ return variant === "menu" ? (+ <DropdownMenuItem asChild className={MENU_ROW}>+ {link}+ </DropdownMenuItem>+ ) : (+ link+ );+}++function Links({ kind, variant }: { kind: ViewerKind | undefined; variant: Variant }) {+ return (+ <>+ {kind && kind !== "guest" && (+ <LinkRow variant={variant} href="/settings">+ <Settings2 aria-hidden /> Settings+ </LinkRow>+ )}+ {kind === "account" && (+ <LinkRow variant={variant} href="/connect">+ <Cpu aria-hidden /> Your GPU+ </LinkRow>+ )}+ {kind === "owner" && (+ <LinkRow variant={variant} href="/settings/models">+ <Scale aria-hidden /> Models & licences+ </LinkRow>+ )}+ <LinkRow variant={variant} href="/settings/licences">+ <Heart aria-hidden /> Thanks & licences+ </LinkRow>+ <ThemeToggle variant={variant} />+ <LinkRow variant={variant} href={FUOBE_REPO} external>+ <GitHubMark /> Source on GitHub+ </LinkRow>+ </>+ );+}++function SignOut({ variant }: { variant: Variant }) {+ return variant === "menu" ? (+ <DropdownMenuItem className={MENU_ROW} onSelect={() => void signOut()}>+ <LogOut aria-hidden /> Sign out+ </DropdownMenuItem>+ ) : (+ <button type="button" className={SHEET_ROW} onClick={() => void signOut()}>+ <LogOut aria-hidden /> Sign out+ </button>+ );+}++function Sep({ variant }: { variant: Variant }) {+ return variant === "menu" ? <DropdownMenuSeparator className="my-1.5" /> : <hr className="my-1 border-border" />;+}++/**+ * The menu's sections for this viewer. `menu`: inside DropdownMenuContent (links and actions are items, so arrow keys+ * reach them; words are labels). `sheet`: the phone's You sheet, 48 px rows; `onNavigate` runs when a link is followed+ * (the sheet closes). Until the viewer is known it shows only what anyone may see.+ */+export function AccountSections({ variant, onNavigate }: { variant: Variant; onNavigate?: () => void }) {+ const kind = useViewerKind();+ const body = (+ <>+ <Identity kind={kind} variant={variant} />+ {kind && <Sep variant={variant} />}+ <GpuSection kind={kind} variant={variant} />+ <ExploreProgress variant={variant} />+ <Sep variant={variant} />+ <Links kind={kind} variant={variant} />+ {kind === "account" && (+ <>+ <Sep variant={variant} />+ <SignOut variant={variant} />+ </>+ )}+ </>+ );+ if (variant === "menu") return body;+ return (+ <div+ className="flex flex-col gap-2"+ onClick={(e) => {+ if ((e.target as Element).closest("a[href]")) onNavigate?.();+ }}+ >+ {body}+ </div>+ );+}++/**+ * The avatar and its menu (owner and accounts; guests get the same menu from a plain round button beside Sign up). The+ * owner's avatar carries a dot for the install's status (green, or amber when a key or ComfyUI is missing for the+ * engine mode); an account's only a green one, when its own GPU answers.+ */+export function AccountMenu({ kind }: { kind: ViewerKind }) {+ const email = useViewer().data?.account?.email;+ const dot = avatarDot(kind, useShownStatus(), useEngineMode());+ const label = kind === "guest" ? "Menu" : kind === "account" && email ? `Account: ${email}` : `Account and settings${dot === "warn" ? ", something needs a look" : ""}`;+ return (+ <DropdownMenu modal={false}>+ <DropdownMenuTrigger+ aria-label={label}+ className={cn(+ "relative grid size-9 shrink-0 place-items-center rounded-full [@media(pointer:coarse)]:size-11 text-[13px] font-semibold outline-none focus-visible:ring-2 focus-visible:ring-ring motion-safe:transition-colors",+ kind === "guest" ? "border border-sidebar-border text-muted-foreground hover:bg-accent data-[state=open]:bg-accent" : "bg-brand-faint text-brand-text hover:bg-brand-faint-hover data-[state=open]:bg-brand-faint-hover",+ )}+ >+ {kind === "account" && email ? <span aria-hidden>{email.charAt(0).toUpperCase()}</span> : <UserRound aria-hidden className="size-[18px]" />}+ {dot && <span aria-hidden data-dot={dot} className={cn("absolute right-0 bottom-0 size-2 rounded-full ring-2 ring-sidebar", dot === "ok" ? "bg-success" : "bg-warning")} />}+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={10} collisionPadding={12} className="w-80 max-h-[calc(100dvh-5rem)] p-1.5">+ <AccountSections variant="menu" />+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/src/components/nav/cover-thumb.tsx b/src/components/nav/cover-thumb.tsxnew file mode 100644index 00000000..44eb41e7--- /dev/null+++ b/src/components/nav/cover-thumb.tsx@@ -0,0 +1,91 @@+"use client";++import { createElement } from "react";+import { navIcon } from "@/lib/nav-icons";+import type { NavIconName } from "@/lib/nav-model";+import { cn } from "@/lib/utils";+import { useNavCover } from "./nav-ui";++/*+ * A nav cover: a real preset still in a box of fixed size, so nothing moves when the picture arrives. The box shows+ * the muted fill until then (and the entry's icon when the preset has no cover). Covers are decoration next to a+ * written name, so the image is alt="" and the box is hidden from assistive tech.+ */++export type CoverSize = "row" | "tile" | "lead" | "card" | "thumb" | "chip" | "pill" | "wide";++interface SizeSpec {+ /** The box (size, shape); a caller's className can override any of it. */+ box: string;+ /** The image's intrinsic size for its width/height attributes (posters are 512x384, thumbs 320x240). */+ w: number;+ h: number;+ /** Which copy to load: the 320 px thumb for small boxes; fluid boxes pick between both by `sizes`. */+ src: "thumb" | "both";+ sizes: string;+}++export const COVER_SIZES: Record<CoverSize, SizeSpec> = {+ /** 36x27: a launcher row, a search grid tile. */+ row: { box: "h-[27px] w-9 rounded-[6px]", w: 36, h: 27, src: "thumb", sizes: "36px" },+ /** 56x56: the phone Studios sheet. */+ tile: { box: "size-14 rounded-[14px]", w: 56, h: 56, src: "thumb", sizes: "56px" },+ /** 4:3, full width: a launcher column's lead card. */+ lead: { box: "aspect-[4/3] w-full rounded-[12px]", w: 512, h: 384, src: "both", sizes: "(min-width: 1024px) 272px, 72px" },+ /** 4:3, full width: a goal band's studio card. */+ card: { box: "aspect-[4/3] w-full rounded-[14px]", w: 512, h: 384, src: "both", sizes: "(min-width: 768px) 248px, 160px" },+ /** 64x48: a search result row. */+ thumb: { box: "h-12 w-16 rounded-[8px]", w: 64, h: 48, src: "thumb", sizes: "64px" },+ /** 56x42: a one-tap preset chip. */+ chip: { box: "h-[42px] w-14 rounded-[8px]", w: 56, h: 42, src: "thumb", sizes: "56px" },+ /** 40x40: a next-step pill. */+ pill: { box: "size-10 rounded-[10px]", w: 40, h: 40, src: "thumb", sizes: "40px" },+ /** 16:9, full width: the "next to try" card. */+ wide: { box: "aspect-video w-full rounded-[10px]", w: 512, h: 288, src: "both", sizes: "300px" },+};++export function CoverThumb({+ id,+ size,+ icon,+ eager,+ className,+}: {+ /** A preset id with a real cover (NavEntry.cover, a goal tap's preset); undefined shows the fallback. */+ id: string | undefined;+ size: CoverSize;+ /** Shown on the muted fill when there is no cover. */+ icon?: NavIconName;+ /** Load at once (a panel about to open) instead of when it comes near the screen. */+ eager?: boolean;+ className?: string;+}) {+ const cover = useNavCover(id);+ const s = COVER_SIZES[size];+ return (+ <span aria-hidden data-cover={cover ? id : undefined} className={cn("relative block shrink-0 overflow-hidden bg-muted", s.box, className)}>+ {cover ? (+ // eslint-disable-next-line @next/next/no-img-element -- versioned static covers, sized by the box (no optimizer round trip)+ <img+ src={cover.thumb}+ srcSet={s.src === "both" ? `${cover.thumb} 320w, ${cover.poster} 512w` : undefined}+ sizes={s.src === "both" ? s.sizes : undefined}+ width={s.w}+ height={s.h}+ alt=""+ loading={eager ? "eager" : "lazy"}+ decoding="async"+ draggable={false}+ className="absolute inset-0 size-full object-cover object-[50%_25%]"+ />+ ) : icon ? (+ <NavIcon name={icon} className="absolute inset-0 m-auto size-[42%] max-h-6 max-w-6 text-muted-foreground" />+ ) : null}+ </span>+ );+}++/** A model icon by name (NavEntry.icon), decorative. */+export function NavIcon({ name, className }: { name: NavIconName; className?: string }) {+ return createElement(navIcon(name), { "aria-hidden": true, className });+}diff --git a/src/components/nav/create-menu.tsx b/src/components/nav/create-menu.tsxnew file mode 100644index 00000000..a1b8cb88--- /dev/null+++ b/src/components/nav/create-menu.tsx@@ -0,0 +1,162 @@+"use client";++import { ChevronDown, Plus } from "lucide-react";+import { usePathname } from "next/navigation";+import { useId } from "react";+import { IntentLink } from "@/components/intent-link";+import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Kbd } from "@/components/ui/kbd";+import { navActive, NEW_CREATION_HREF } from "@/lib/nav";+import { entry, visibleTo, type NavEntry, type ViewerKind } from "@/lib/nav-model";+import { cn } from "@/lib/utils";+import { NavIcon } from "./cover-thumb";+import { warmNav } from "./nav-prefetch";+import { useViewerKind } from "./nav-ui";++/*+ * Create: the tools that start from words or a picture, in two labelled columns. The bar's Create menu (a menu: arrow+ * keys, typeahead, Esc and focus return come with it) and the phone's Create sheet (a plain list) show the same items.+ * "New creation" (a fresh composer on Home) closes both.+ */++/**+ * A nav menu row: a clear ring on the row the keyboard is on, and a brand bar at the start of the open page's row (the+ * tint alone is too close to the hover one to tell them apart).+ */+export const NAV_MENU_ITEM =+ "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset data-[current]:shadow-[inset_3px_0_0_var(--brand-text)]";++/** The two columns, in order. Storyboard plans a film, so it sits with Make (its card is in the launcher's Film column). */+export const CREATE_COLUMNS = [+ { label: "Make", ids: ["image", "video", "assist", "canvas", "storyboard"] },+ { label: "Edit a picture", ids: ["edit", "live-edit", "inpaint", "layers", "color-grade"] },+] as const;++/** The Create columns this viewer may see. */+export function createColumns(kind: ViewerKind | undefined): { label: string; entries: NavEntry[] }[] {+ return CREATE_COLUMNS.map((c) => ({+ label: c.label,+ entries: c.ids.map((id) => entry(id)).filter((e): e is NavEntry => !!e && visibleTo(e, kind)),+ }));+}++/** Every page the Create menu links to (the bar marks Create when one of them is open). */+export const CREATE_HREFS: readonly string[] = CREATE_COLUMNS.flatMap((c) => c.ids.map((id) => entry(id)?.href ?? "")).filter(Boolean);++/** The current page among `hrefs` (a page below a link counts, as in the sidebar). */+function current(pathname: string, href: string, hrefs: readonly string[]) {+ return navActive(href, pathname, new URLSearchParams(), [...hrefs]);+}++/**+ * The Create items. `menu`: rows of the bar's menu (inside DropdownMenuContent). `sheet`: the phone's Create sheet, 48 px+ * rows with "New creation" first, full width; `onNavigate` closes the sheet when a row is followed.+ */+export function CreateList({ variant, onNavigate }: { variant: "menu" | "sheet"; onNavigate?: () => void }) {+ const kind = useViewerKind();+ const pathname = usePathname();+ const columns = createColumns(kind);+ const ids = useId();+ if (variant === "menu")+ return (+ <>+ <div className="grid grid-cols-2 gap-x-1">+ {columns.map((c, i) => (+ <DropdownMenuGroup key={c.label} aria-labelledby={`${ids}-${i}`} className="flex min-w-0 flex-col">+ <DropdownMenuLabel id={`${ids}-${i}`} className="px-2.5 pt-2 pb-1 text-[11px] font-semibold tracking-[.08em] text-brand-text uppercase">+ {c.label}+ </DropdownMenuLabel>+ {c.entries.map((e) => {+ const on = current(pathname, e.href, CREATE_HREFS);+ return (+ <DropdownMenuItem key={e.id} asChild className={cn("min-h-11 items-start gap-2.5 rounded-lg px-2.5 py-2 data-[current]:bg-brand-faint", NAV_MENU_ITEM)}>+ <IntentLink href={e.href} eager={e.eager} aria-current={on ? "page" : undefined} data-current={on || undefined}>+ <NavIcon name={e.icon} className="mt-0.5 size-4 text-muted-foreground" />+ <span className="flex min-w-0 flex-col">+ <span className={cn("text-[13.5px] leading-tight font-medium", on && "font-semibold")}>{e.label}</span>+ <span className="truncate text-[12px] leading-snug text-muted-foreground">{e.what}</span>+ </span>+ </IntentLink>+ </DropdownMenuItem>+ );+ })}+ </DropdownMenuGroup>+ ))}+ </div>+ <DropdownMenuSeparator className="my-1.5" />+ <DropdownMenuItem asChild className={cn("h-10 gap-2.5 rounded-lg px-2.5 text-[13.5px] font-medium", NAV_MENU_ITEM)}>+ <IntentLink href={NEW_CREATION_HREF} eager>+ <Plus aria-hidden className="size-4 text-brand-text" />+ New creation+ <span className="ml-auto text-[12px] font-normal text-muted-foreground [@media(hover:none)]:hidden">A fresh composer on Home</span>+ <Kbd aria-hidden className="[@media(hover:none)]:hidden">+ ↵+ </Kbd>+ </IntentLink>+ </DropdownMenuItem>+ </>+ );+ const follow = (e: React.MouseEvent) => {+ if ((e.target as Element).closest("a[href]")) onNavigate?.();+ };+ return (+ <div className="flex flex-col gap-4" onClick={follow}>+ <IntentLink+ href={NEW_CREATION_HREF}+ eager+ className="flex h-12 items-center justify-center gap-2 rounded-xl bg-primary text-[15px] font-semibold text-primary-foreground outline-none hover:bg-primary/90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"+ >+ <Plus aria-hidden className="size-5" />+ New creation+ </IntentLink>+ {columns.map((c, i) => (+ <section key={c.label} aria-labelledby={`${ids}-s${i}`} className="flex flex-col">+ <h3 id={`${ids}-s${i}`} className="px-1 pb-1 text-[11px] font-semibold tracking-[.08em] text-brand-text uppercase">+ {c.label}+ </h3>+ <ul className="flex flex-col">+ {c.entries.map((e) => {+ const on = current(pathname, e.href, CREATE_HREFS);+ return (+ <li key={e.id}>+ <IntentLink+ href={e.href}+ eager={e.eager}+ aria-current={on ? "page" : undefined}+ className={cn(+ "flex min-h-12 items-center gap-3 rounded-xl px-2 py-1.5 outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring motion-safe:transition-colors",+ on && "bg-brand-faint",+ )}+ >+ <span className="grid size-9 shrink-0 place-items-center rounded-[10px] bg-muted">+ <NavIcon name={e.icon} className="size-[18px] text-foreground" />+ </span>+ <span className="flex min-w-0 flex-col">+ <span className={cn("text-[15px] leading-tight font-medium", on && "font-semibold")}>{e.label}</span>+ <span className="truncate text-[12.5px] text-muted-foreground">{e.what}</span>+ </span>+ </IntentLink>+ </li>+ );+ })}+ </ul>+ </section>+ ))}+ </div>+ );+}++/** The bar's Create menu. `className`: the bar's item look for the trigger; `active`: a Create page is open. */+export function CreateMenu({ className, active }: { className?: string; active?: boolean }) {+ return (+ <DropdownMenu modal={false} onOpenChange={(o) => o && warmNav("create")}>+ <DropdownMenuTrigger className={className} data-active={active || undefined}>+ Create+ <ChevronDown aria-hidden className="size-3.5 text-muted-foreground motion-safe:transition-transform group-data-[state=open]/bar-item:rotate-180" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" sideOffset={8} collisionPadding={12} className="w-[520px] max-w-[calc(100vw-24px)] p-1.5">+ <CreateList variant="menu" />+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/src/components/nav/explore-progress.tsx b/src/components/nav/explore-progress.tsxnew file mode 100644index 00000000..4f905ac0--- /dev/null+++ b/src/components/nav/explore-progress.tsx@@ -0,0 +1,95 @@+"use client";++import { Sparkles } from "lucide-react";+import { IntentLink } from "@/components/intent-link";+import { DropdownMenuItem, DropdownMenuLabel } from "@/components/ui/dropdown-menu";+import { exploreProgress, nextToTry } from "@/lib/nav-explore";+import type { NavEntry } from "@/lib/nav-model";+import { cn } from "@/lib/utils";+import { CoverThumb } from "./cover-thumb";+import { NAV_MENU_ITEM } from "./create-menu";+import { useExplored } from "./explore-tracker";+import { useViewerKind } from "./nav-ui";++/**+ * How many studios this browser has tried and the next one to try, as one small row with a 40 px cover. Lives in the+ * account menu (`menu`: a menu item, so arrow keys reach it) and the phone's You sheet (`sheet`). Nothing on the+ * server, while hydrating, when this browser's storage is blocked, or before the first studio is tried.+ */+export function ExploreProgress({+ variant,+ onNavigate,+}: {+ variant: "menu" | "sheet";+ /** The suggestion was followed (the You sheet closes). */+ onNavigate?: () => void;+}) {+ const explored = useExplored();+ const kind = useViewerKind();+ if (!explored) return null;+ const { done, total } = exploreProgress(kind, explored);+ if (!total || !done) return null;+ const next = done < total ? nextToTry(kind, explored, explored[explored.length - 1]) : undefined;+ return <ExploreView variant={variant} done={done} total={total} next={next} onNavigate={onNavigate} />;+}++const ROW = "flex min-h-12 items-center gap-3 rounded-[12px] px-1.5 py-1 text-left";++/** The row itself, from numbers (ExploreProgress reads them from this browser). */+export function ExploreView({+ variant,+ done,+ total,+ next,+ onNavigate,+}: {+ variant: "menu" | "sheet";+ done: number;+ total: number;+ next?: NavEntry;+ onNavigate?: () => void;+}) {+ const menu = variant === "menu";+ const count = `${done} of ${total} studios tried`;+ if (done >= total || !next) {+ const body = (+ <>+ <span className="grid size-10 shrink-0 place-items-center rounded-[10px] bg-brand-faint text-brand-text">+ <Sparkles className="size-4" aria-hidden />+ </span>+ <span className="text-[13px] font-medium text-foreground">{done >= total ? "You have tried every studio" : count}</span>+ </>+ );+ return menu ? <DropdownMenuLabel className={cn(ROW, "font-normal")}>{body}</DropdownMenuLabel> : <div className={ROW}>{body}</div>;+ }+ const body = (+ <>+ <CoverThumb id={next.cover} size="pill" icon={next.icon} />+ <span className="flex min-w-0 flex-1 flex-col leading-tight">+ <span className="truncate text-[13px] font-medium text-foreground">+ <span className="text-muted-foreground">Next to try: </span>+ {next.label}+ </span>+ <span className="truncate text-[11.5px] text-muted-foreground">{count}</span>+ </span>+ </>+ );+ // One name for the whole row.+ const label = `Next to try: ${next.label}, ${next.what}. ${count}`;+ return menu ? (+ <DropdownMenuItem asChild className={cn(ROW, "cursor-pointer focus:bg-accent", NAV_MENU_ITEM)}>+ <IntentLink href={next.href} aria-label={label} onClick={onNavigate}>+ {body}+ </IntentLink>+ </DropdownMenuItem>+ ) : (+ <IntentLink+ href={next.href}+ aria-label={label}+ onClick={onNavigate}+ className={cn(ROW, "outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring motion-safe:transition-colors motion-reduce:transition-none")}+ >+ {body}+ </IntentLink>+ );+}diff --git a/src/components/nav/explore-tracker.tsx b/src/components/nav/explore-tracker.tsxnew file mode 100644index 00000000..2c582a6d--- /dev/null+++ b/src/components/nav/explore-tracker.tsx@@ -0,0 +1,87 @@+"use client";++import { usePathname, useSearchParams } from "next/navigation";+import { useEffect, useSyncExternalStore } from "react";+import { activeEntry, type NavEntry } from "@/lib/nav-model";+import { EXPLORE_KEY, parseExplored, withExplored } from "@/lib/nav-explore";++/** The kinds a visit counts for: a studio, a create tool, a preset hub (Apps, Camera motions, Effects). */+const EXPLORABLE: ReadonlySet<NavEntry["kind"]> = new Set<NavEntry["kind"]>(["studio", "create", "presets"]);++/**+ * The entry a page counts as explored: its studio, create tool or preset hub (a hub's modes and a studio's own pages+ * count as the studio: /audio/clean is Audio). Undefined for Home, the Library, Settings and other pages.+ */+export function exploredEntry(pathname: string, search: URLSearchParams): NavEntry | undefined {+ const e = activeEntry(pathname, search);+ return e && EXPLORABLE.has(e.kind) ? e : undefined;+}++// ---------------------------------------------------------------------------+// What this browser has explored: localStorage only (no server, no cookie), every access guarded.++const listeners = new Set<() => void>();+/** The last list read, kept while the stored text is the same, so a snapshot is the same array between renders. */+let cached: { raw: string | null; list: string[] } = { raw: null, list: [] };++/**+ * The entry ids this browser has explored (oldest first), or null when storage can't be read (a private window,+ * blocked site data): then nothing about exploring is shown, rather than a count that never moves.+ */+export function readExplored(): string[] | null {+ let raw: string | null;+ try {+ raw = window.localStorage.getItem(EXPLORE_KEY);+ } catch {+ return null;+ }+ if (raw !== cached.raw) cached = { raw, list: parseExplored(raw) };+ return cached.list;+}++/** Notes an entry as explored. Quietly does nothing when storage is blocked or full. */+export function markExplored(id: string): void {+ const list = readExplored();+ if (!list) return;+ const next = withExplored([...list], id);+ if (next.length === list.length && next.every((x, i) => x === list[i])) return;+ try {+ window.localStorage.setItem(EXPLORE_KEY, JSON.stringify(next));+ } catch {+ return;+ }+ for (const l of listeners) l();+}++/** Calls `onChange` when the explored list changes here or in another tab; returns the unsubscribe. */+export function subscribeExplored(onChange: () => void): () => void {+ listeners.add(onChange);+ // Another tab explored something (or site data was cleared: key null).+ const onStorage = (e: StorageEvent) => {+ if (e.key === null || e.key === EXPLORE_KEY) onChange();+ };+ window.addEventListener("storage", onStorage);+ return () => {+ listeners.delete(onChange);+ window.removeEventListener("storage", onStorage);+ };+}++/** The explored ids, kept in step across tabs; null on the server, while hydrating, and when storage is blocked. */+export function useExplored(): string[] | null {+ return useSyncExternalStore(subscribeExplored, readExplored, () => null);+}++/**+ * Marks each studio, create tool or preset hub explored as it is opened (rendered once by the chrome, inside+ * Suspense: it reads the URL). Renders nothing.+ */+export function ExploreTracker() {+ const pathname = usePathname();+ const search = useSearchParams().toString();+ useEffect(() => {+ const e = exploredEntry(pathname, new URLSearchParams(search));+ if (e) markExplored(e.id);+ }, [pathname, search]);+ return null;+}diff --git a/src/components/nav/goal-row.tsx b/src/components/nav/goal-row.tsxnew file mode 100644index 00000000..8dd05981--- /dev/null+++ b/src/components/nav/goal-row.tsx@@ -0,0 +1,355 @@+"use client";++import { ArrowRight, LayoutGrid, Sparkles, X } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { CardPending, IntentLink } from "@/components/intent-link";+import { CoverThumb } from "@/components/nav/cover-thumb";+import { useNavUi, useViewerKind } from "@/components/nav/nav-ui";+import { NAV_ICONS } from "@/lib/nav-icons";+import { GOALS, goalBand, isNew, tapHref, type GoalId, type NavEntry, type ViewerKind } from "@/lib/nav-model";+import { cn } from "@/lib/utils";++/**+ * Home's goal row: six goals under the hero, each a button that opens a band of that goal's studios, one-tap presets+ * and finishing tools right under the row (in the page's flow, so only what is below it moves). One band at a time;+ * closed on load, so the first paint never changes.+ */++/** The goal a roving key moves the focus to from `i` of `n` (wrapping at the ends), or null for any other key. */+export function rovingTarget(key: string, i: number, n: number): number | null {+ if (n <= 0) return null;+ switch (key) {+ case "ArrowRight":+ return (i + 1) % n;+ case "ArrowLeft":+ return (i - 1 + n) % n;+ case "Home":+ return 0;+ case "End":+ return n - 1;+ default:+ return null;+ }+}++/** What "Plan it with Assist" types into a new chat for a goal that offers it (the owner's: Assist is the owner's). */+export const GOAL_ASSIST_PROMPTS: Partial<Record<GoalId, string>> = {+ film: "Plan a 30-second short film: a 6-frame storyboard of a night heist in Paris, then a camera move and sound for every shot",+ social: "Plan five vertical reels for a fashion label: a hook in the first second, a model on a rooftop at golden hour, music on every cut",+ sell: "Plan a 3-shot ad for a matte black perfume bottle: a hero still, a macro detail, then animate both with a slow push in",+};++/** The Assist link for a goal, or undefined when it has none. */+export function goalAssistHref(id: GoalId): string | undefined {+ const prompt = GOAL_ASSIST_PROMPTS[id];+ return prompt ? `/assist?prompt=${encodeURIComponent(prompt)}` : undefined;+}++/**+ * Marks a sideways rail's ends (.fade-x in globals.css fades an end while there is more past it), as the galleries'+ * category strip does; kept here so the goal row doesn't pull the gallery's module into its own.+ */+function useFadeEdges<T extends HTMLElement>() {+ const ref = useRef<T>(null);+ useEffect(() => {+ const el = ref.current;+ if (!el) return;+ const update = () => {+ el.toggleAttribute("data-fade-start", el.scrollLeft > 2);+ el.toggleAttribute("data-fade-end", el.scrollLeft + el.clientWidth < el.scrollWidth - 2);+ };+ update();+ el.addEventListener("scroll", update, { passive: true });+ const ro = new ResizeObserver(update);+ ro.observe(el);+ return () => {+ el.removeEventListener("scroll", update);+ ro.disconnect();+ };+ }, []);+ return ref;+}++const LABEL = "text-[11px] font-semibold tracking-[0.08em] text-brand-text uppercase";+const FOCUS = "outline-none focus-visible:ring-2 focus-visible:ring-ring";++function NewBadge() {+ return <span className="ml-1.5 inline-block rounded-full bg-highlight px-1.5 align-[2px] text-[10px] leading-4 font-semibold text-highlight-foreground">New</span>;+}++/** A studio (or tool) as a 4:3 cover card. */+function GoalCard({ e }: { e: NavEntry }) {+ return (+ <IntentLink+ href={e.href}+ className={cn(+ "group/card relative flex h-full flex-col overflow-hidden rounded-[14px] border bg-card hover:border-border-strong motion-safe:transition-colors",+ FOCUS,+ )}+ >+ <span className="block overflow-hidden">+ <CoverThumb+ id={e.cover}+ size="card"+ icon={e.icon}+ className="rounded-none ease-out motion-safe:transition-transform motion-safe:duration-[400ms] motion-safe:group-hover/card:scale-[1.03]"+ />+ </span>+ <span className="flex min-w-0 flex-col gap-0.5 px-3 pt-2.5 pb-3 lg:px-3.5 lg:pt-3 lg:pb-3.5">+ {/* Whole names, wrapping where five cards share a narrow band. */}+ <span className="text-[14.5px] leading-snug font-semibold md:max-lg:text-[13.5px]">+ {e.label}+ {isNew(e) && <NewBadge />}+ </span>+ <span className="text-[12px] leading-snug text-muted-foreground">{e.what}</span>+ </span>+ <CardPending />+ </IntentLink>+ );+}++/**+ * One goal's band: its title and line, its studios as cover cards, its one-tap presets and its finishing tools.+ * `names` are the presets' names (from the catalog, read on the server); `kind` decides what the viewer sees.+ */+export function GoalBand({ id, kind, names, onClose }: { id: GoalId; kind: ViewerKind | undefined; names: Readonly<Record<string, string>>; onClose: () => void }) {+ const { goal, cards, finish } = goalBand(id, kind);+ const assist = kind === "owner" && goal.assist ? goalAssistHref(goal.id) : undefined;+ const cardRail = useFadeEdges<HTMLUListElement>();+ const tapRail = useFadeEdges<HTMLUListElement>();+ return (+ <section+ id="goal-band"+ aria-labelledby="goal-band-title"+ className={cn(+ "flex flex-col gap-5 border-b bg-popover px-4 pt-5 pb-6 text-popover-foreground max-sm:-mx-4",+ "sm:rounded-b-[18px] sm:border-x sm:px-6 sm:pt-6 sm:pb-7 sm:shadow-soft",+ "motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-top-1 motion-safe:duration-150",+ )}+ >+ <div className="grid grid-cols-[minmax(0,1fr)_auto] items-start gap-3 sm:grid-cols-[minmax(0,1fr)_auto_auto] sm:items-center">+ <div className="col-start-1 row-start-1 flex min-w-0 flex-col gap-1.5">+ <h2 id="goal-band-title" className="font-heading text-[28px] leading-none sm:text-[34px]">+ {goal.title}+ </h2>+ <p className="text-[13px] text-pretty text-muted-foreground">{goal.line}</p>+ </div>+ {assist && (+ <IntentLink+ href={assist}+ className={cn(+ "col-span-2 row-start-2 inline-flex h-11 items-center gap-2 justify-self-start rounded-full border bg-card pr-4 pl-3.5 text-[13.5px] font-medium hover:bg-accent motion-safe:transition-colors sm:h-10 pointer-coarse:h-11",+ "sm:col-span-1 sm:col-start-2 sm:row-start-1",+ FOCUS,+ )}+ >+ <Sparkles aria-hidden className="size-[15px] text-brand-text" />+ Plan it with Assist+ </IntentLink>+ )}+ <button+ type="button"+ aria-label={`Close ${goal.title}`}+ onClick={onClose}+ className={cn(+ "col-start-2 row-start-1 grid size-11 place-items-center rounded-xl border bg-card hover:bg-accent motion-safe:transition-colors sm:col-start-3 sm:size-10 pointer-coarse:size-11",+ FOCUS,+ )}+ >+ <X aria-hidden className="size-4" />+ </button>+ </div>++ <div className="flex flex-col gap-2.5">+ <h3 className={LABEL}>{goal.cardsLabel}</h3>+ {/* A phone's cards are one rail that scrolls sideways inside the band; wider, one row of five. */}+ <ul+ ref={cardRail}+ role="list"+ className={cn(+ "fade-x scrollbar-none -mx-4 flex snap-x snap-mandatory scroll-px-4 gap-3 overflow-x-auto px-4 sm:-mx-6 sm:scroll-px-6 sm:px-6",+ "md:mx-0 md:grid md:grid-cols-5 md:overflow-visible md:px-0 md:[mask-image:none] lg:gap-4",+ )}+ >+ {cards.map((e) => (+ <li key={e.id} className="w-40 shrink-0 snap-start md:w-auto">+ <GoalCard e={e} />+ </li>+ ))}+ </ul>+ </div>++ <div className="grid gap-5 lg:grid-cols-[minmax(0,1fr)_360px] lg:gap-12">+ <div className="flex min-w-0 flex-col gap-2.5">+ <h3 className={LABEL}>{goal.tapLabel}</h3>+ <ul+ ref={tapRail}+ role="list"+ className="fade-x scrollbar-none -mx-4 flex snap-x snap-mandatory scroll-px-4 gap-2.5 overflow-x-auto px-4 sm:mx-0 sm:grid sm:grid-cols-2 sm:overflow-visible sm:px-0 sm:[mask-image:none]"+ >+ {goal.taps.map((t) => (+ <li key={t.preset} className="w-[220px] shrink-0 snap-start sm:w-auto">+ <IntentLink+ href={tapHref(t.preset)}+ className={cn(+ "relative flex h-[60px] min-w-0 items-center gap-2.5 rounded-xl border bg-card py-2 pr-3 pl-2 hover:bg-accent motion-safe:transition-colors",+ FOCUS,+ )}+ >+ <CoverThumb id={t.preset} size="chip" />+ <span className="flex min-w-0 flex-col gap-0.5">+ <span className="truncate text-[13.5px] leading-snug font-semibold">{names[t.preset] ?? t.preset}</span>+ <span className="truncate text-[11.5px] leading-snug text-muted-foreground">{t.kind}</span>+ </span>+ <CardPending />+ </IntentLink>+ </li>+ ))}+ </ul>+ </div>+ {finish.length > 0 && (+ <div className="flex min-w-0 flex-col gap-2.5">+ <h3 className={LABEL}>{goal.finishLabel}</h3>+ <ul role="list" className="flex flex-col gap-2">+ {finish.map((e) => (+ <li key={e.id}>+ <IntentLink+ href={e.href}+ className={cn(+ "group/finish flex h-11 min-w-0 items-center gap-3 rounded-xl border bg-card px-3.5 hover:bg-accent motion-safe:transition-colors",+ FOCUS,+ )}+ >+ <span className="shrink-0 text-[13.5px] font-semibold">{e.label}</span>+ <span className="min-w-0 flex-1 truncate text-[12px] text-muted-foreground">{e.what}</span>+ <ArrowRight aria-hidden className="size-3.5 shrink-0 text-muted-foreground motion-safe:transition-transform motion-safe:group-hover/finish:translate-x-0.5" />+ </IntentLink>+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ </section>+ );+}++/**+ * The row and the open goal's band. Arrow keys (and Home / End) move between the goals, Enter or Space opens one and+ * opens or closes its band, Esc anywhere in the band closes it and puts the focus back on its goal.+ */+export function GoalRow({ names }: { names: Readonly<Record<string, string>> }) {+ const kind = useViewerKind();+ const { openStudios } = useNavUi();+ const [open, setOpen] = useState<GoalId | null>(null);+ // The goal that holds the row's one tab stop (the last one focused or opened).+ const [stop, setStop] = useState(0);+ const buttons = useRef<(HTMLButtonElement | null)[]>([]);+ const scroller = useFadeEdges<HTMLDivElement>();++ /** Scrolls the row (only the row, never the page) so a goal that sits past its edge comes fully into view. */+ const reveal = (b: HTMLElement) => {+ const s = scroller.current;+ if (!s || s.scrollWidth <= s.clientWidth) return;+ const left = b.offsetLeft - 16;+ const right = b.offsetLeft + b.offsetWidth + 16 - s.clientWidth;+ const to = left < s.scrollLeft ? left : right > s.scrollLeft ? right : null;+ if (to === null) return;+ const still = window.matchMedia("(prefers-reduced-motion: reduce)").matches;+ s.scrollTo({ left: Math.max(0, to), behavior: still ? "auto" : "smooth" });+ };++ const close = () => {+ const i = GOALS.findIndex((g) => g.id === open);+ setOpen(null);+ if (i >= 0) buttons.current[i]?.focus();+ };++ const onRowKey = (e: React.KeyboardEvent) => {+ const i = buttons.current.findIndex((b) => b === e.target);+ if (i < 0) return;+ const next = rovingTarget(e.key, i, GOALS.length);+ if (next === null) return;+ e.preventDefault();+ setStop(next);+ buttons.current[next]?.focus();+ };++ return (+ <div+ data-goal-row+ className="mt-6 sm:mt-8"+ onKeyDown={(e) => {+ if (e.key !== "Escape" || !open || e.defaultPrevented) return;+ e.preventDefault();+ close();+ }}+ >+ <div className="flex h-[52px] items-stretch border-y max-sm:-mx-4">+ {/* A phone scrolls the goals sideways inside the row, never the page. */}+ <div+ ref={scroller}+ role="toolbar"+ aria-label="Start from a goal"+ onKeyDown={onRowKey}+ className="fade-x scrollbar-none relative flex min-w-0 flex-1 snap-x items-stretch gap-0.5 overflow-x-auto"+ >+ {GOALS.map((g, i) => {+ const on = open === g.id;+ const Icon = NAV_ICONS[g.icon as keyof typeof NAV_ICONS] ?? LayoutGrid;+ return (+ <button+ key={g.id}+ ref={(el) => {+ buttons.current[i] = el;+ }}+ type="button"+ tabIndex={i === stop ? 0 : -1}+ aria-expanded={on}+ aria-controls="goal-band"+ data-goal={g.id}+ data-open={on || undefined}+ onFocus={() => setStop(i)}+ onClick={(e) => {+ setStop(i);+ setOpen(on ? null : g.id);+ if (!on) reveal(e.currentTarget);+ }}+ className={cn(+ "flex shrink-0 snap-start items-center gap-2 rounded-t-[10px] border-b-2 border-transparent px-4 text-[14px] whitespace-nowrap text-foreground/80 outline-none hover:bg-accent hover:text-foreground motion-safe:transition-colors",+ // A tablet's row holds all six as words alone (a phone's scrolls, with the icons).+ "md:max-lg:px-2.5 md:max-lg:text-[13.5px]",+ "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",+ on && "border-primary bg-accent text-foreground",+ )}+ >+ <Icon aria-hidden className={cn("size-4 shrink-0 md:max-lg:hidden", on ? "text-brand-text" : "text-muted-foreground")} />+ {/* The label's bold copy keeps its width, so opening a goal never moves the ones beside it. */}+ <span className="grid">+ <span className={cn("col-start-1 row-start-1", on ? "font-semibold" : "font-medium")}>{g.label}</span>+ <span aria-hidden className="invisible col-start-1 row-start-1 font-semibold">+ {g.label}+ </span>+ </span>+ </button>+ );+ })}+ </div>+ <button+ type="button"+ onClick={() => openStudios()}+ className={cn(+ "flex shrink-0 items-center justify-center gap-2 self-center rounded-[10px] text-[13.5px] font-medium text-brand-text hover:bg-brand-faint motion-safe:transition-colors",+ // Its words from xl; narrower, its icon (with the words for screen readers) leaves the goals the room.+ "ml-1 size-11 max-sm:mr-1 xl:ml-2 xl:h-10 xl:w-auto xl:px-3",+ FOCUS,+ )}+ >+ <LayoutGrid aria-hidden className="size-[15px]" />+ <span className="max-xl:sr-only">All studios and tools</span>+ </button>+ </div>+ {open && <GoalBand key={open} id={open} kind={kind} names={names} onClose={close} />}+ </div>+ );+}diff --git a/src/components/nav/nav-prefetch.tsx b/src/components/nav/nav-prefetch.tsxnew file mode 100644index 00000000..08b453fb--- /dev/null+++ b/src/components/nav/nav-prefetch.tsx@@ -0,0 +1,90 @@+"use client";++import { useRouter } from "next/navigation";+import { useEffect } from "react";+import { queueIdlePrefetch } from "@/lib/idle-prefetch";+import { entriesFor, type ViewerKind } from "@/lib/nav-model";++/*+ * Loading a panel's routes ahead: when the launcher, Create, More or a phone sheet opens, the pages one tap in it leads+ * to start loading while the browser is idle, in the idle queue's "nav" lane (src/lib/idle-prefetch.ts), so the open+ * page's own tabs go first. Each link also prefetches on its own when hovered (IntentLink).+ */++/** A panel whose routes load when it opens: the launcher (and the Studios sheet), Create, More. */+export type NavPanel = "studios" | "create" | "more";++const MORE_IDS = ["apps", "motions", "effects", "canvas", "assist"];++/**+ * The routes one tap in a panel leads to (`panel`), or in all of them with the library's (no `panel`): on the site, once+ * each.+ */+export function prefetchHrefs(kind: ViewerKind | undefined, panel?: NavPanel): string[] {+ const hrefs = entriesFor(kind)+ .filter((e) =>+ panel === "studios"+ ? !!e.group+ : panel === "create"+ ? e.kind === "create"+ : panel === "more"+ ? MORE_IDS.includes(e.id)+ : !!e.group || e.kind === "create" || e.kind === "library",+ )+ .map((e) => e.href)+ .filter((h) => h.startsWith("/") && !h.includes("#"));+ return [...new Set(hrefs)];+}++/** A browser asking to save data, or on a slow connection: the panels' routes are not loaded ahead. */+function saveData(): boolean {+ const conn = (navigator as Navigator & { connection?: { saveData?: boolean; effectiveType?: string } }).connection;+ return !!conn && (!!conn.saveData || /(^|-)2g$|^3g$/.test(conn.effectiveType ?? ""));+}++const warmedHrefs = new Set<string>();+let prefetchOne: ((href: string) => void) | null = null;+let queued: string[] = [];+let cancels: (() => void)[] = [];++function flush() {+ if (!prefetchOne || !queued.length) return;+ const go = prefetchOne;+ const list = queued;+ queued = [];+ for (const href of list) cancels.push(queueIdlePrefetch("nav", href, () => go(href)));+}++/**+ * A panel opened (the launcher, Create, More, a phone sheet): the routes one tap in it leads to start loading once the+ * browser is idle, so that tap never waits a round trip. Only that panel's routes, each once per page load, and only+ * when it opens, not on every page load or every pointer that crosses the bar. A browser asking to save data or on a+ * slow connection skips it (the links still prefetch one by one on hover).+ */+export function warmNav(panel: NavPanel) {+ if (typeof navigator === "undefined" || saveData()) return;+ // The routes are the same for everyone (none of them is owner-only): no need to wait for the viewer.+ const fresh = prefetchHrefs(undefined, panel).filter((h) => !warmedHrefs.has(h));+ if (!fresh.length) return;+ for (const h of fresh) warmedHrefs.add(h);+ queued.push(...fresh);+ flush();+}++/** Mounted once per frame (the bar and the phone tabs both mount it; the last one wins): gives warmNav() the router. */+export function NavPrefetcher() {+ const router = useRouter();+ useEffect(() => {+ const own = (href: string) => router.prefetch(href);+ prefetchOne = own;+ flush();+ return () => {+ if (prefetchOne !== own) return;+ prefetchOne = null;+ for (const cancel of cancels) cancel();+ cancels = [];+ };+ }, [router]);+ return null;+}+diff --git a/src/components/nav/nav-ui.tsx b/src/components/nav/nav-ui.tsxnew file mode 100644index 00000000..28e094ab--- /dev/null+++ b/src/components/nav/nav-ui.tsx@@ -0,0 +1,111 @@+"use client";++import { createContext, useCallback, useContext, useMemo, useRef, useState } from "react";+import { useHydrated, useViewer } from "@/lib/api";+import type { NavCover, NavCovers } from "@/lib/nav-covers";+import { viewerKindOf, type LauncherGroupId, type ViewerKind } from "@/lib/nav-model";++/*+ * The app frame's shared state: the covers the server resolved for the nav (preset id → thumb and poster URLs), who is+ * looking, and which of the bar's panels or the phone's sheets is open. One provider for the top bar, the phone tabs and+ * their sheets, so "All studios" anywhere opens the launcher on a desktop and the Studios sheet on a phone.+ */++export type NavSheet = "studios" | "create" | "you";++/** Below this width the phone chrome (bottom tabs and sheets) shows instead of the top bar (Tailwind's md). */+export const PHONE_QUERY = "(max-width: 767px)";++export interface NavUi {+ launcherOpen: boolean;+ setLauncherOpen(v: boolean): void;+ /** The column the launcher was opened for (openStudios(group)): it takes focus first. */+ launcherGroup: LauncherGroupId | undefined;+ /** Where focus goes back to when the launcher closes with Esc: what opened it, when that was not its own button. */+ launcherReturnTo(): HTMLElement | null;+ sheet: NavSheet | null;+ setSheet(v: NavSheet | null): void;+ /** The chip the Studios sheet starts on (openStudios(group)); undefined = All. */+ sheetGroup: LauncherGroupId | undefined;+ /** Every studio: the launcher from the md breakpoint up, the Studios sheet on a phone. */+ openStudios(group?: LauncherGroupId): void;+}++const NavUiContext = createContext<NavUi | null>(null);+const CoversContext = createContext<NavCovers>({});++export function NavUiProvider({ covers, children }: { covers: NavCovers; children: React.ReactNode }) {+ const [launcher, setLauncher] = useState<{ open: boolean; group?: LauncherGroupId }>({ open: false });+ const [sheet, setSheetState] = useState<{ sheet: NavSheet | null; group?: LauncherGroupId }>({ sheet: null });+ const launcherReturn = useRef<HTMLElement | null>(null);++ // Opened or closed by the launcher's own button: focus goes back to it. openStudios() says otherwise.+ const setLauncherOpen = useCallback((open: boolean) => {+ launcherReturn.current = null;+ setLauncher((l) => (l.open === open && !l.group ? l : { open }));+ }, []);+ const launcherReturnTo = useCallback(() => launcherReturn.current, []);+ const setSheet = useCallback((v: NavSheet | null) => setSheetState({ sheet: v }), []);+ const openStudios = useCallback((group?: LauncherGroupId) => {+ const phone = typeof window !== "undefined" && window.matchMedia(PHONE_QUERY).matches;+ if (phone) {+ setSheetState({ sheet: "studios", group });+ return;+ }+ const at = typeof document !== "undefined" ? document.activeElement : null;+ launcherReturn.current = at instanceof HTMLElement && at !== document.body ? at : null;+ setLauncher({ open: true, group });+ }, []);++ const ui = useMemo<NavUi>(+ () => ({+ launcherOpen: launcher.open,+ setLauncherOpen,+ launcherGroup: launcher.open ? launcher.group : undefined,+ launcherReturnTo,+ sheet: sheet.sheet,+ setSheet,+ sheetGroup: sheet.sheet === "studios" ? sheet.group : undefined,+ openStudios,+ }),+ [launcher, sheet, setLauncherOpen, launcherReturnTo, setSheet, openStudios],+ );++ return (+ <CoversContext.Provider value={covers}>+ <NavUiContext.Provider value={ui}>{children}</NavUiContext.Provider>+ </CoversContext.Provider>+ );+}++const CLOSED: NavUi = {+ launcherOpen: false,+ setLauncherOpen: () => {},+ launcherGroup: undefined,+ launcherReturnTo: () => null,+ sheet: null,+ setSheet: () => {},+ sheetGroup: undefined,+ openStudios: () => {},+};++/** The open panels and sheets. Outside the provider (a test, a page rendered alone) everything is closed and inert. */+export function useNavUi(): NavUi {+ return useContext(NavUiContext) ?? CLOSED;+}++/** A preset's cover as the nav shows it (thumb and poster), or undefined when the server resolved none for that id. */+export function useNavCover(presetId: string | undefined): NavCover | undefined {+ const covers = useContext(CoversContext);+ return presetId && Object.hasOwn(covers, presetId) ? covers[presetId] : undefined;+}++/**+ * Who is looking, once known: undefined while hydrating (the server's shell is the same for everyone) and until+ * /api/auth/me answers. Owner-only items render only after this says "owner".+ */+export function useViewerKind(): ViewerKind | undefined {+ const hydrated = useHydrated();+ const viewer = useViewer().data;+ return hydrated ? viewerKindOf(viewer) : undefined;+}diff --git a/src/components/nav/next-steps.tsx b/src/components/nav/next-steps.tsxnew file mode 100644index 00000000..98ff84d9--- /dev/null+++ b/src/components/nav/next-steps.tsx@@ -0,0 +1,146 @@+"use client";++import { ChevronRight } from "lucide-react";+import Link from "next/link";+import { usePathname, useRouter, useSearchParams } from "next/navigation";+import { useEffect, useId } from "react";+import { useEngineMode, useLikelyVisitor } from "@/lib/api";+import type { Generation } from "@/lib/catalog/types";+import { keepGoing, type NextStep } from "@/lib/next-steps";+import { cn } from "@/lib/utils";+import { CoverThumb } from "./cover-thumb";++/** What the heading calls the result, by the kind of output it is. */+const NOUN: Record<string, string> = { image: "picture", video: "clip", audio: "sound", model3d: "model" };++/**+ * Studios that read a handed-over picture with their own small reader (`HandoffImage` below). Both run on a+ * self-hosted Fuobe only, so a guest or an account is never sent there.+ */+const ADAPTERS = { characterSheet: true, imageTo3d: true } as const;++/** The heading over the steps: "Keep going with this picture" (clip, sound, model). */+export function keepGoingTitle(kind: string | undefined): string {+ return `Keep going with this ${NOUN[kind ?? ""] ?? "result"}`;+}++/**+ * "Keep going with this": the next studios or apps for a finished result, each opening with the result already in+ * it. `row` sits under a result (pills that wrap, one sideways rail inside its own box on a phone); `list` is the+ * Viewer's side panel (stacked rows). Nothing when the result has nowhere to go (failed, deleted, text, vectors).+ */+export function NextSteps({+ g,+ index,+ variant,+ max = 5,+ skip,+ onNavigate,+ className,+}: {+ g: Generation;+ index: number;+ variant: "row" | "list";+ max?: number;+ /** Step ids the view already offers in its own way (the 3D card's own Animate the spin). */+ skip?: readonly string[];+ /** Called when a step is chosen (the Viewer closes itself, so a hand-off to the same studio isn't hidden behind it). */+ onNavigate?: () => void;+ className?: string;+}) {+ const engineMode = useEngineMode();+ const visitor = useLikelyVisitor();+ const titleId = useId();+ const steps = keepGoing(g, index, { engineMode, visitor, adapters: visitor ? undefined : ADAPTERS }, max + (skip?.length ?? 0))+ .filter((s) => !skip?.includes(s.id))+ .slice(0, max);+ if (!steps.length) return null;+ const title = keepGoingTitle(g.outputs[index]?.kind);+ const list = variant === "list";+ return (+ // A group, not a landmark: a page of results has many of these (one per 3D model card).+ <div role="group" aria-labelledby={titleId} className={cn(list ? "space-y-1.5" : "min-w-0 space-y-2.5", className)}>+ <p id={titleId} className={cn("text-[12px] font-semibold tracking-[0.08em] text-brand-text uppercase", list && "px-1.5")}>+ {title}+ </p>+ {list ? (+ <ul className="space-y-0.5">+ {steps.map((s) => (+ <li key={s.id}>+ <StepLink step={s} variant="list" onNavigate={onNavigate} />+ </li>+ ))}+ </ul>+ ) : (+ // Phones: one rail that scrolls sideways inside its own box (the page never does); wider screens: pills that wrap.+ <ul className="scrollbar-none flex gap-2.5 overflow-x-auto overscroll-x-contain max-md:snap-x max-md:snap-mandatory md:flex-wrap md:overflow-visible">+ {steps.map((s) => (+ <li key={s.id} className="shrink-0 snap-start">+ <StepLink step={s} variant="row" onNavigate={onNavigate} />+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}++function StepLink({ step, variant, onNavigate }: { step: NextStep; variant: "row" | "list"; onNavigate?: () => void }) {+ const row = variant === "row";+ return (+ // The address carries the result itself: no prefetch (it is a page the studio fills in on arrival).+ <Link+ href={step.href}+ prefetch={false}+ onClick={onNavigate}+ className={cn(+ "flex items-center outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset motion-safe:transition-colors motion-reduce:transition-none",+ row+ ? "h-[52px] gap-2.5 rounded-[14px] border bg-card pr-4 pl-1.5 text-card-foreground hover:border-border-strong hover:bg-accent"+ : "min-h-12 gap-2.5 rounded-lg px-1.5 py-1.5 hover:bg-accent",+ )}+ >+ <CoverThumb id={step.cover} size="pill" icon="Sparkles" className={row ? undefined : "size-9 rounded-lg"} />+ <span className={cn("flex min-w-0 flex-col leading-tight", !row && "flex-1")}>+ <span className={cn("text-[13.5px] font-semibold", row ? "whitespace-nowrap" : "truncate")}>{step.verb}</span>+ <span className={cn("text-[11.5px] text-muted-foreground", row ? "whitespace-nowrap" : "truncate")}>{step.where}</span>+ </span>+ {!row && <ChevronRight className="size-4 shrink-0 text-muted-foreground" aria-hidden />}+ </Link>+ );+}++// ---------------------------------------------------------------------------+// A handed-over picture on studios without the composer's hand-off (Character Sheet, Image to 3D)++/**+ * A Fuobe file address (`/api/files/…`) a link may hand over, else undefined: no other site's address, and no+ * `..` segment (written or %-encoded) that would step out of the files route.+ */+export function handoffFile(v: string | null | undefined): string | undefined {+ if (!v || !/^\/api\/files\/[\w./%-]{1,300}$/.test(v)) return undefined;+ return /\.\.|%2e/i.test(v) ? undefined : v;+}++/**+ * Reads `?image=` (a result sent here by "Keep going with this"): a Fuobe file is passed to `onImage`, then the param+ * is taken out of the address (router.replace), so a reload or Back doesn't add it again. `onImage` must be stable+ * (useCallback) and may run twice in development (Strict Mode): it should ignore a picture it already has. Under its+ * own Suspense: it reads the URL, so the static shell renders without it.+ */+export function HandoffImage({ onImage }: { onImage: (url: string) => void }) {+ const sp = useSearchParams();+ const router = useRouter();+ const pathname = usePathname();+ const raw = sp.get("image");+ useEffect(() => {+ if (raw === null) return;+ const url = handoffFile(raw);+ if (url) onImage(url);+ const rest = new URLSearchParams(sp.toString());+ rest.delete("image");+ const query = rest.toString();+ router.replace(query ? `${pathname}?${query}` : pathname, { scroll: false });+ }, [raw, sp, router, pathname, onImage]);+ return null;+}diff --git a/src/components/nav/phone-nav-button.tsx b/src/components/nav/phone-nav-button.tsxnew file mode 100644index 00000000..5a8929ec--- /dev/null+++ b/src/components/nav/phone-nav-button.tsx@@ -0,0 +1,41 @@+"use client";++import { LayoutGrid, Search } from "lucide-react";+import { useNavUi } from "@/components/nav/nav-ui";+import { useSearchPalette } from "@/components/nav/search-context";+import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";++/**+ * The phone's button at the end of a page's or a studio's header (the top-right corner on every page) (hidden from md up, where the top bar has search and+ * the studios). On most pages it opens the full-screen search. In a full-screen studio (html[data-fullscreen-studio],+ * set before the first paint and kept in step on navigation), where the tab bar steps aside, it is the way out instead:+ * it opens the Studios sheet with Home, Library, You and Search above the studios. The icon and the name switch by CSS+ * from that same attribute, so the server's HTML is already right and nothing changes after hydration.+ */+export function PhoneNavButton({ className }: { className?: string }) {+ const search = useSearchPalette();+ const { setSheet } = useNavUi();+ return (+ <Button+ type="button"+ variant="ghost"+ size="icon"+ aria-haspopup="dialog"+ data-phone-nav-button+ className={cn("size-11 shrink-0 rounded-full text-muted-foreground motion-reduce:transition-none md:hidden", className)}+ onTouchStart={search.warm}+ onPointerEnter={search.warm}+ onFocus={search.warm}+ onClick={() => {+ if (document.documentElement.hasAttribute("data-fullscreen-studio")) setSheet("studios");+ else search.open();+ }}+ >+ <Search className="size-5 [html[data-fullscreen-studio]_&]:hidden" aria-hidden />+ <LayoutGrid className="hidden size-5 [html[data-fullscreen-studio]_&]:block" aria-hidden />+ <span className="sr-only [html[data-fullscreen-studio]_&]:hidden">Search</span>+ <span className="sr-only hidden [html[data-fullscreen-studio]_&]:inline">Menu</span>+ </Button>+ );+}diff --git a/src/components/nav/phone-nav.ts b/src/components/nav/phone-nav.tsnew file mode 100644index 00000000..62ab2f7c--- /dev/null+++ b/src/components/nav/phone-nav.ts@@ -0,0 +1,60 @@+/**+ * Phone navigation helpers (pure, so they're testable): which tab looks selected, what a tab tap opens, whether the+ * on-screen keyboard is up, and the You tab's dot.+ */++export type PhoneTab = "home" | "create" | "studios" | "library" | "you";+/** The sheets the tabs open (NavSheet in nav-ui.tsx). */+export type PhoneSheet = "studios" | "create" | "you";++function under(path: string, pathname: string): boolean {+ return pathname === path || pathname.startsWith(`${path}/`);+}++/**+ * The tab that looks selected. An open sheet's tab, while it is open; otherwise the page's: Home on /, Library in the+ * library, You in settings, Studios in a studio (an entry with a launcher group), Create in a create tool. Nothing on+ * other pages (a gallery of motions, say), so no tab claims a page it doesn't lead to.+ */+export function activePhoneTab(+ pathname: string,+ sheet: PhoneSheet | null,+ entry?: { kind: string; group?: string } | null,+): PhoneTab | null {+ if (sheet) return sheet;+ if (!pathname) return null;+ if (pathname === "/") return "home";+ if (under("/library", pathname)) return "library";+ if (under("/settings", pathname) || under("/connect", pathname)) return "you";+ if (entry?.group) return "studios";+ if (entry?.kind === "create") return "create";+ return null;+}++/** A sheet tab: opens its sheet, switches from another one, and closes its own when tapped again. */+export function toggleSheet(open: PhoneSheet | null, tapped: PhoneSheet): PhoneSheet | null {+ return open === tapped ? null : tapped;+}++/** Input types that bring up the on-screen keyboard (pickers, checkboxes and buttons don't). */+const TYPED = new Set(["", "text", "search", "email", "url", "tel", "password", "number"]);++/** Whether focus is somewhere you type: a text field, a text area or editable text. */+export function typesText(+ el: { tagName?: string; type?: string; isContentEditable?: boolean; readOnly?: boolean; disabled?: boolean } | null | undefined,+): boolean {+ if (!el) return false;+ if (el.isContentEditable) return true;+ const tag = (el.tagName ?? "").toUpperCase();+ if (el.readOnly || el.disabled) return false;+ if (tag === "TEXTAREA") return true;+ return tag === "INPUT" && TYPED.has((el.type ?? "").toLowerCase());+}++/** How much the visible viewport must shrink, in px, before it counts as the keyboard (browser bars move less). */+export const KEYBOARD_MIN = 150;++/** The on-screen keyboard is up: someone is typing and the visible viewport lost more than KEYBOARD_MIN of its height. */+export function keyboardOpen(viewportHeight: number, fullHeight: number, typing: boolean): boolean {+ return typing && viewportHeight < fullHeight - KEYBOARD_MIN;+}diff --git a/src/components/nav/phone-sheets.tsx b/src/components/nav/phone-sheets.tsxnew file mode 100644index 00000000..f2f18f89--- /dev/null+++ b/src/components/nav/phone-sheets.tsx@@ -0,0 +1,211 @@+"use client";++import { usePathname } from "next/navigation";+import { Suspense, useCallback, useEffect, useRef, useState } from "react";+import { Dialog as SheetPrimitive } from "radix-ui";+import { Search, XIcon } from "lucide-react";+import { AccountSections } from "@/components/nav/account-menu";+import { CreateList } from "@/components/nav/create-menu";+import { PHONE_QUERY, useNavUi, type NavSheet } from "@/components/nav/nav-ui";+import { useSearchPalette } from "@/components/nav/search-context";+import { ComputerNoteBlock } from "@/components/nav/status-chips";+import { StudiosSheet } from "@/components/nav/studios-sheet";+import { warmNav } from "@/components/nav/nav-prefetch";+import { cn } from "@/lib/utils";++const TITLES: Record<NavSheet, string> = { studios: "Studios", create: "Create", you: "You" };++/** A drag down this far on the sheet's top (handle and title) closes it, in px. */+const SWIPE_CLOSE = 56;++/** Closes the sheets when the page changes some other way than a tap in them (search, a notification, back). */+function CloseOnNavigate({ onPath }: { onPath: () => void }) {+ const pathname = usePathname();+ const last = useRef(pathname);+ useEffect(() => {+ if (last.current === pathname) return;+ last.current = pathname;+ onPath();+ }, [pathname, onPath]);+ return null;+}++/** On the page and shown (not inside a closed sheet, a hidden bar or a collapsed header). */+function visible(el: Element | null | undefined): el is HTMLElement {+ if (!(el instanceof HTMLElement) || !el.isConnected) return false;+ return typeof el.checkVisibility === "function" ? el.checkVisibility() : el.getClientRects().length > 0;+}++/**+ * Where focus goes when the sheet closes: the tab of the sheet on screen when a tab opened it (Studios, then a tap on+ * You, closes back to You), else what opened it (an "All studios" button), else that tab, else a full-screen+ * studio's Menu button, else the page.+ */+export function sheetReturnTarget(opener: HTMLElement | null, shown: NavSheet, tapped?: HTMLElement | null): HTMLElement | null {+ // A tab tapped over the open sheet (Studios again, Home, Library): focus stays on it.+ if (visible(tapped)) return tapped;+ const tab = document.querySelector(`[data-phone-tabs] [data-tab="${shown}"]`);+ const fromTab = !!opener?.closest("[data-phone-tabs]");+ if (fromTab && visible(tab)) return tab;+ if (visible(opener)) return opener;+ if (visible(tab)) return tab;+ const menu = [...document.querySelectorAll("[data-phone-nav-button]")].find(visible);+ if (menu) return menu as HTMLElement;+ return document.getElementById("content");+}++function YouSheet() {+ return (+ <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto overscroll-contain px-4 pb-1">+ <ComputerNoteBlock />+ <AccountSections variant="sheet" />+ </div>+ );+}++/**+ * The phone's sheets (below md): Studios, Create and You, opened by the tab bar (or by "All studios" anywhere, and by a+ * full-screen studio's menu button). One bottom sheet whose body follows the open tab, so going from one tab to another+ * swaps the body instead of closing one sheet and opening the next. It ends at the tab bar, which stays above its scrim+ * and tappable: a tap there is the tab's own (Studios again closes, another tab switches, Home and Library go there),+ * never a tap outside that closes the sheet first. Modal otherwise: focus stays inside, Esc and the close button close+ * it, and focus goes back to what opened it.+ */+export function PhoneSheets() {+ const { sheet, setSheet, sheetGroup } = useNavUi();+ const search = useSearchPalette();+ // The body on screen: the open sheet's, and the last one's while the sheet slides away.+ const [shown, setShown] = useState<NavSheet>(sheet ?? "studios");+ if (sheet && sheet !== shown) setShown(sheet);+ const opener = useRef<HTMLElement | null>(null);+ const tapped = useRef<HTMLElement | null>(null);+ const handoff = useRef(false);+ const drag = useRef<number | null>(null);+ const close = useCallback(() => setSheet(null), [setSheet]);++ // Widened to the desktop layout (a tablet turned, a window resized), or opened there at all: the sheet is hidden from+ // md up, so it closes rather than hold focus out of sight. The bar's menus take over.+ useEffect(() => {+ if (!sheet) return;+ // A sheet opened (from a tab, or a full-screen studio's Menu): the routes one tap in it leads to start loading.+ if (sheet !== "you") warmNav(sheet);+ const mq = window.matchMedia(PHONE_QUERY);+ const onChange = () => !mq.matches && close();+ onChange();+ mq.addEventListener("change", onChange);+ return () => mq.removeEventListener("change", onChange);+ }, [sheet, close]);++ /** Search from a sheet: the sheet goes and the full-screen search comes; Esc there returns to the tab that opened it. */+ const openSearch = useCallback(() => {+ handoff.current = true;+ const back = opener.current;+ close();+ // A frame later the sheet no longer holds focus, so the search can note where to send it back.+ requestAnimationFrame(() => {+ if (back?.isConnected) back.focus({ preventScroll: true });+ search.open();+ });+ }, [close, search]);++ return (+ <>+ <Suspense fallback={null}>+ <CloseOnNavigate onPath={close} />+ </Suspense>+ <SheetPrimitive.Root open={sheet !== null} onOpenChange={(open) => !open && close()}>+ <SheetPrimitive.Portal>+ <SheetPrimitive.Overlay+ data-slot="sheet-overlay"+ className="fixed inset-x-0 top-0 bottom-[var(--chrome-bottom,0px)] z-50 bg-overlay md:hidden motion-safe:duration-150 motion-safe:data-open:animate-in motion-safe:data-open:fade-in-0 motion-safe:data-closed:animate-out motion-safe:data-closed:fade-out-0"+ />+ <SheetPrimitive.Content+ id="phone-sheet"+ data-slot="sheet-content"+ data-sheet={shown}+ aria-describedby={undefined}+ onOpenAutoFocus={() => {+ const at = document.activeElement;+ opener.current = at instanceof HTMLElement && at !== document.body ? at : null;+ tapped.current = null;+ }}+ onCloseAutoFocus={(e) => {+ // The sheet has no trigger of its own for Radix to return to: focus goes back here. Handed to the search,+ // which has focus now, it stays there.+ e.preventDefault();+ const handed = handoff.current;+ handoff.current = false;+ if (handed) return;+ sheetReturnTarget(opener.current, shown, tapped.current)?.focus({ preventScroll: true });+ tapped.current = null;+ opener.current = null;+ }}+ onInteractOutside={(e) => {+ const target = e.detail.originalEvent.target;+ const tab = target instanceof Element ? target.closest<HTMLElement>("[data-phone-tabs] [data-tab]") : null;+ if (target instanceof Element && target.closest("[data-phone-tabs]")) e.preventDefault();+ if (tab) tapped.current = tab;+ }}+ onClickCapture={(e) => {+ // A link in the sheet goes to its page and the sheet closes (a new-tab click leaves it open).+ const a = (e.target as Element).closest("a[href]");+ if (a && !e.metaKey && !e.ctrlKey && !e.shiftKey && a.getAttribute("target") !== "_blank") close();+ }}+ className={cn(+ "fixed inset-x-0 bottom-[var(--chrome-bottom,0px)] z-50 flex max-h-[calc(100dvh-var(--chrome-bottom,0px)-2.5rem)] flex-col gap-2.5 rounded-t-[22px] border-t border-border bg-popover pt-2 pr-[env(safe-area-inset-right)] pb-3 pl-[env(safe-area-inset-left)] text-popover-foreground shadow-heavy outline-none md:hidden",+ // No tab bar under it in a full-screen studio: it keeps clear of the home indicator itself.+ "[html[data-fullscreen-studio]_&]:pb-[max(0.75rem,env(safe-area-inset-bottom))]",+ "motion-safe:duration-200 motion-safe:data-open:animate-in motion-safe:data-open:fade-in-0 motion-safe:data-open:slide-in-from-bottom-10 motion-safe:data-closed:animate-out motion-safe:data-closed:fade-out-0 motion-safe:data-closed:slide-out-to-bottom-10",+ )}+ >+ <div+ className="flex shrink-0 touch-none flex-col gap-1.5"+ onPointerDown={(e) => {+ if (e.pointerType !== "mouse") drag.current = e.clientY;+ }}+ onPointerUp={(e) => {+ if (drag.current !== null && e.clientY - drag.current > SWIPE_CLOSE) close();+ drag.current = null;+ }}+ onPointerCancel={() => (drag.current = null)}+ >+ <span aria-hidden className="mx-auto h-1 w-10 rounded-full bg-border-strong" />+ <div className="flex items-center gap-3 pr-2 pl-4">+ <SheetPrimitive.Title className="font-heading text-[28px] leading-none font-normal text-foreground">{TITLES[shown]}</SheetPrimitive.Title>+ {shown === "studios" && (+ // In a full-screen studio Search is in the sheet's shortcuts instead.+ <button+ type="button"+ onClick={openSearch}+ className="ml-auto inline-flex h-11 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium text-brand-text outline-none [-webkit-tap-highlight-color:transparent] focus-visible:ring-2 focus-visible:ring-ring [html[data-fullscreen-studio]_&]:invisible"+ >+ <Search className="size-4" aria-hidden /> Search everything+ </button>+ )}+ <SheetPrimitive.Close+ className={cn(+ "grid size-11 shrink-0 place-items-center rounded-full text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",+ shown !== "studios" && "ml-auto",+ )}+ >+ <XIcon className="size-5" aria-hidden />+ <span className="sr-only">Close</span>+ </SheetPrimitive.Close>+ </div>+ </div>+ {shown === "studios" ? (+ // Opened again for another group while open: it starts over on that chip.+ <StudiosSheet key={sheetGroup ?? "all"} group={sheetGroup} onSearch={openSearch} />+ ) : shown === "create" ? (+ <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 pb-1">+ <CreateList variant="sheet" onNavigate={close} />+ </div>+ ) : (+ <YouSheet />+ )}+ </SheetPrimitive.Content>+ </SheetPrimitive.Portal>+ </SheetPrimitive.Root>+ </>+ );+}diff --git a/src/components/nav/phone-tabs.tsx b/src/components/nav/phone-tabs.tsxnew file mode 100644index 00000000..a98e79f0--- /dev/null+++ b/src/components/nav/phone-tabs.tsx@@ -0,0 +1,166 @@+"use client";++import { usePathname } from "next/navigation";+import { Suspense, useEffect } from "react";+import { CircleUserRound, House, LayoutGrid, Library, Plus, type LucideIcon } from "lucide-react";+import { IntentLink } from "@/components/intent-link";+import { useNavUi, useViewerKind } from "@/components/nav/nav-ui";+import { activePhoneTab, keyboardOpen, toggleSheet, typesText, type PhoneSheet, type PhoneTab } from "@/components/nav/phone-nav";+import { avatarDot, useShownStatus } from "@/components/nav/status-chips";+import { NavPrefetcher } from "@/components/nav/nav-prefetch";+import { useEngineMode } from "@/lib/api";+import { navActive } from "@/lib/nav";+import { activeEntry } from "@/lib/nav-model";+import { cn } from "@/lib/utils";++const NO_SEARCH = new URLSearchParams();++type TabDot = ReturnType<typeof avatarDot>;++/** One cell: at least 64 x 56, the icon in a 44 x 28 pill that tints when its tab is selected. */+const CELL =+ "group/tab relative flex h-full min-w-0 flex-col items-center justify-center gap-1 rounded-xl text-[11px] leading-none font-medium text-muted-foreground outline-none select-none [-webkit-tap-highlight-color:transparent] focus-visible:ring-2 focus-visible:ring-ring data-[active]:text-foreground";++function TabFace({ icon: Icon, label, dot }: { icon: LucideIcon; label: string; dot?: TabDot }) {+ return (+ <>+ <span className="relative grid h-7 w-11 place-items-center rounded-full motion-safe:transition-colors motion-safe:duration-150 group-data-[active]/tab:bg-brand-faint group-data-[active]/tab:text-brand-text">+ <Icon className="size-[22px]" strokeWidth={1.75} aria-hidden />+ {dot && (+ <span+ aria-hidden+ data-dot={dot}+ className={cn("absolute top-0 right-1.5 size-2 rounded-full ring-2 ring-sidebar", dot === "ok" ? "bg-success" : "bg-warning")}+ />+ )}+ </span>+ <span className="max-w-full truncate">{label}</span>+ </>+ );+}++/**+ * The You tab's dot, by the avatar's rules (the owner's setup, an account's own GPU when it answers, never a guest's):+ * after hydration only, so the server's shell and the first client render agree, and it takes no space when it comes.+ */+function useYouDot(): TabDot {+ const kind = useViewerKind();+ const status = useShownStatus();+ const mode = useEngineMode();+ return avatarDot(kind, status, mode);+}++function Tabs({ pathname }: { pathname: string }) {+ const { sheet, setSheet } = useNavUi();+ const entry = pathname ? activeEntry(pathname, NO_SEARCH) : undefined;+ const active = activePhoneTab(pathname, sheet, entry);+ const dot = useYouDot();+ const sheetTab = (tab: PhoneSheet, label: string, icon: LucideIcon, tabDot?: TabDot) => (+ <button+ type="button"+ className={CELL}+ data-tab={tab}+ data-active={active === tab || undefined}+ aria-haspopup="dialog"+ aria-expanded={sheet === tab}+ aria-controls={sheet === tab ? "phone-sheet" : undefined}+ onClick={() => setSheet(toggleSheet(sheet, tab))}+ >+ <TabFace icon={icon} label={label} dot={tabDot} />+ </button>+ );+ const linkTab = (tab: PhoneTab, href: string, label: string, icon: LucideIcon) => {+ const current = !!pathname && navActive(href, pathname, NO_SEARCH);+ return (+ <IntentLink+ href={href}+ eager+ className={CELL}+ data-tab={tab}+ data-active={active === tab || undefined}+ aria-current={current ? "page" : undefined}+ // Over an open sheet the tab still goes where it says: the sheet closes on the way.+ onClick={() => setSheet(null)}+ >+ <TabFace icon={icon} label={label} />+ </IntentLink>+ );+ };+ return (+ <>+ {linkTab("home", "/", "Home", House)}+ {sheetTab("create", "Create", Plus)}+ {sheetTab("studios", "Studios", LayoutGrid)}+ {linkTab("library", "/library", "Library", Library)}+ {sheetTab("you", "You", CircleUserRound, dot)}+ </>+ );+}++/** Reads the pathname (runtime data on a project's page) inside Suspense, so the shell around it still prerenders. */+function RouteTabs() {+ return <Tabs pathname={usePathname() ?? ""} />;+}++/**+ * `html[data-keyboard-open]` while the on-screen keyboard is up (focus in a text field and the visible viewport much+ * shorter than the page's): the tab bar steps aside, so it never rides on top of the keyboard over the field. The full+ * height is the one measured while nobody was typing, so a browser that also shrinks the page itself is read the same.+ */+function useKeyboardFlag() {+ useEffect(() => {+ const vv = window.visualViewport;+ if (!vv) return;+ const html = document.documentElement;+ let full = Math.max(window.innerHeight, vv.height);+ let frame = 0;+ const update = () => {+ cancelAnimationFrame(frame);+ // After focusout the new focus isn't set yet: read it a frame later.+ frame = requestAnimationFrame(() => {+ const typing = typesText(document.activeElement as HTMLInputElement | null);+ if (!typing) full = Math.max(window.innerHeight, vv.height);+ html.toggleAttribute("data-keyboard-open", keyboardOpen(vv.height, full, typing));+ });+ };+ vv.addEventListener("resize", update);+ window.addEventListener("focusin", update);+ window.addEventListener("focusout", update);+ window.addEventListener("orientationchange", update);+ return () => {+ cancelAnimationFrame(frame);+ vv.removeEventListener("resize", update);+ window.removeEventListener("focusin", update);+ window.removeEventListener("focusout", update);+ window.removeEventListener("orientationchange", update);+ html.removeAttribute("data-keyboard-open");+ };+ }, []);+}++/**+ * The phone's tab bar (below md): Home, Create, Studios, Library and You, fixed to the bottom above the home indicator.+ * Create, Studios and You open their sheets (PhoneSheets). Steps aside in a full-screen studio (its header button opens+ * the menu sheet instead), while the keyboard is up, and in print. While a sheet is open it sits above the sheet's+ * scrim and stays tappable, so another tab is one tap away.+ */+export function PhoneTabs() {+ const { sheet } = useNavUi();+ useKeyboardFlag();+ return (+ <nav+ aria-label="Main"+ data-phone-tabs+ className={cn(+ "pointer-events-auto fixed inset-x-0 bottom-0 grid h-[calc(4rem+env(safe-area-inset-bottom))] grid-cols-5 border-t border-sidebar-border bg-sidebar/95 pt-[3px] pr-[max(0.5rem,env(safe-area-inset-right))] pb-[calc(0.25rem+env(safe-area-inset-bottom))] pl-[max(0.5rem,env(safe-area-inset-left))] backdrop-blur md:hidden print:hidden [html[data-fullscreen-studio]_&]:hidden [html[data-keyboard-open]_&]:hidden",+ sheet ? "z-[60]" : "z-40",+ )}+ >+ <Suspense fallback={<Tabs pathname="" />}>+ <RouteTabs />+ </Suspense>+ {/* Gives the sheets' route warming the router (the bar mounts one too: either serves). */}+ <NavPrefetcher />+ </nav>+ );+}diff --git a/src/components/nav/search-context.tsx b/src/components/nav/search-context.tsxnew file mode 100644index 00000000..4cf7907e--- /dev/null+++ b/src/components/nav/search-context.tsx@@ -0,0 +1,136 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+import dynamic from "next/dynamic";+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";+import type { PaletteIndex } from "@/lib/command-search";+import type { LauncherGroupId } from "@/lib/nav-model";++/*+ * The search palette's switch: open it from anywhere (the bar's search field, the phone's search icon, / and Ctrl+K+ * or ⌘K), and close it. Only this and the shortcuts are in every page's code; the palette itself (its list, its+ * ranking and the navigation's search words) loads on its own the first time it is wanted, or a moment before, when+ * a pointer rests on the search field.+ */++export interface SearchPaletteApi {+ isOpen: boolean;+ /** Open on a query, or on "Every studio" filtered to one group. */+ open(opts?: { query?: string; group?: LauncherGroupId }): void;+ close(): void;+ /** Load the palette and its catalog now, before it's opened (hover or focus on a search control). */+ warm(): void;+}++export interface PaletteSession {+ open: boolean;+ /** Changes on every open: the palette starts fresh (empty query, top of the list) each time. */+ id: number;+ query?: string;+ group?: LauncherGroupId;+}++/** The apps, motions, effects and models the palette searches (prerendered: GET /api/search-index). */+export const PALETTE_INDEX_KEY = ["palette-index"] as const;+export const fetchPaletteIndex = async (): Promise<PaletteIndex> => (await fetch("/api/search-index")).json();++const loadPalette = () => import("./search-palette");+const SearchPalette = dynamic(() => loadPalette().then((m) => m.SearchPalette), { ssr: false });++const Ctx = createContext<SearchPaletteApi | null>(null);++const INERT: SearchPaletteApi = { isOpen: false, open: () => {}, close: () => {}, warm: () => {} };++/** Opens and closes the search palette. Outside the provider (a page rendered alone, a test) it does nothing. */+export function useSearchPalette(): SearchPaletteApi {+ return useContext(Ctx) ?? INERT;+}++/** Where typing a "/" means a slash, not search: a field, an editor, or a workspace with its own keys. */+export function typesText(target: EventTarget | null): boolean {+ if (!target || typeof (target as Element).closest !== "function") return false;+ const el = target as Element;+ return !!el.closest("input, textarea, select, [contenteditable]:not([contenteditable=false]), [data-hotkeys-off]");+}++/** Ctrl+K (⌘K on Apple keyboards): toggles the palette from anywhere, a text field included. */+export function isPaletteToggle(e: Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">): boolean {+ return (e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "k";+}++/**+ * "/" opens the palette when nothing else wants the key: no modifier, nobody handled it, not while typing, and not+ * over a dialog or a menu that is open.+ */+export function slashOpens(+ e: Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "altKey" | "defaultPrevented" | "isComposing" | "target">,+ doc: Pick<Document, "querySelector"> | undefined = typeof document === "undefined" ? undefined : document,+): boolean {+ if (e.key !== "/" || e.metaKey || e.ctrlKey || e.altKey || e.defaultPrevented || e.isComposing) return false;+ if (typesText(e.target)) return false;+ return !doc?.querySelector('[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"], [role="menu"]');+}++export function SearchPaletteProvider({ children }: { children: React.ReactNode }) {+ const [session, setSession] = useState<PaletteSession>({ open: false, id: 0 });+ // The palette's code is fetched (and mounted, closed) the first time it's warmed or opened, never before.+ const [loaded, setLoaded] = useState(false);+ const openRef = useRef(false);+ /** What had focus when the palette opened: it gets focus back when the palette closes without going anywhere. */+ const returnTo = useRef<Element | null>(null);+ const client = useQueryClient();++ const warm = useCallback(() => {+ setLoaded(true);+ void loadPalette();+ void client.prefetchQuery({ queryKey: PALETTE_INDEX_KEY, queryFn: fetchPaletteIndex, staleTime: Infinity });+ }, [client]);++ const open = useCallback(+ (opts?: { query?: string; group?: LauncherGroupId }) => {+ if (!openRef.current) returnTo.current = typeof document === "undefined" ? null : document.activeElement;+ openRef.current = true;+ warm();+ setSession((s) => ({ open: true, id: s.id + 1, query: opts?.query, group: opts?.group }));+ },+ [warm],+ );++ // What gets focus back (once) when the palette closes without going anywhere.+ const takeReturn = useCallback(() => {+ const el = returnTo.current;+ returnTo.current = null;+ return el;+ }, []);++ const close = useCallback(() => {+ openRef.current = false;+ setSession((s) => (s.open ? { ...s, open: false } : s));+ }, []);++ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (isPaletteToggle(e)) {+ e.preventDefault();+ if (openRef.current) close();+ else open();+ return;+ }+ if (!openRef.current && slashOpens(e)) {+ e.preventDefault();+ open();+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [open, close]);++ const api = useMemo<SearchPaletteApi>(() => ({ isOpen: session.open, open, close, warm }), [session.open, open, close, warm]);++ return (+ <Ctx.Provider value={api}>+ {children}+ {loaded && <SearchPalette session={session} onClose={close} takeReturn={takeReturn} />}+ </Ctx.Provider>+ );+}diff --git a/src/components/nav/search-palette.tsx b/src/components/nav/search-palette.tsxnew file mode 100644index 00000000..a573ff4f--- /dev/null+++ b/src/components/nav/search-palette.tsx@@ -0,0 +1,419 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { Command as CommandPrimitive } from "cmdk";+import { Loader2, Search, X } from "lucide-react";+import { useRouter } from "next/navigation";+import { useTheme } from "next-themes";+import { Dialog as DialogPrimitive } from "radix-ui";+import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useSkills } from "@/components/assist/hooks";+import { Kbd } from "@/components/ui/kbd";+import { signInHref, useEngineMode, useGenerations, useModelAccess } from "@/lib/api";+import type { Generation } from "@/lib/catalog/types";+import { indexEntries, KIND_LABELS, skillEntries } from "@/lib/command-search";+import { useModKey } from "@/lib/keys";+import { entriesFor, LAUNCHER_GROUPS, launcherEntries, studioCount, type LauncherGroupId, type NavEntry } from "@/lib/nav-model";+import { isExternal, isThemeAction, navSearchEntries, searchNav, type NavHit, type SearchResult } from "@/lib/nav-search";+import { cn } from "@/lib/utils";+import { useViewerKind } from "./nav-ui";+import { fetchPaletteIndex, PALETTE_INDEX_KEY, type PaletteSession } from "./search-context";+import { AlsoTile, BestRow, HitRow, RecentRow, sectionHeading, StudioTile } from "./search-results";++/*+ * The search palette: one field that finds every studio, tool, app, camera motion, effect, model, setting and recent+ * creation by what you want to make ("ad for my perfume"), and below it every studio at once, filtered by goal. A+ * dialog over the page on a laptop; the whole screen on a phone. Loaded on its own (search-context.tsx).+ */++// The viewer is only needed once a recent creation is opened from the palette.+const Viewer = lazy(() => import("@/components/studio/viewer").then((m) => ({ default: m.Viewer })));++function useDebounced<T>(value: T, ms: number): T {+ const [v, setV] = useState(value);+ useEffect(() => {+ const t = setTimeout(() => setV(value), ms);+ return () => clearTimeout(t);+ }, [value, ms]);+ return v;+}++/** Enter and Space belong to a button inside the palette, not to the list's selected row (cmdk acts on Enter). */+const keepKeys = (e: React.KeyboardEvent) => {+ if (e.key === "Enter" || e.key === " ") e.stopPropagation();+};++const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-ring";++/** On the page and shown (a launcher link is gone once the launcher closes). */+function shownEl(el: Element | null | undefined): el is HTMLElement {+ if (!(el instanceof HTMLElement) || !el.isConnected) return false;+ return typeof el.checkVisibility === "function" ? el.checkVisibility() : el.getClientRects().length > 0;+}++/**+ * Focus back to what had it when the palette opened; when that is hidden now (a link of the launcher, which closed),+ * to the Studios button, else to the page.+ */+export function returnFocus(el: Element | null) {+ const to = shownEl(el) ? el : [...document.querySelectorAll("[data-studios-trigger]")].find(shownEl) ?? document.getElementById("content");+ to?.focus({ preventScroll: true });+}++export function SearchPalette({ session, onClose, takeReturn }: { session: PaletteSession; onClose: () => void; takeReturn: () => Element | null }) {+ const router = useRouter();+ const { resolvedTheme, setTheme } = useTheme();+ const [viewing, setViewing] = useState<Generation | null>(null);+ // Set when the palette closes onto something else (a page, the viewer): focus stays with that.+ const leaving = useRef(false);++ const pick = useCallback(+ (href: string, id?: string) => {+ onClose();+ if (isThemeAction(href)) return setTheme(resolvedTheme === "dark" ? "light" : "dark");+ if (isExternal(href)) return void window.open(href, "_blank", "noopener,noreferrer");+ leaving.current = true;+ // Signing up or in comes back to this page.+ if (id === "signup" || id === "login") return router.push(signInHref(id, `${location.pathname}${location.search}`));+ router.push(href);+ },+ [onClose, router, resolvedTheme, setTheme],+ );+ const openRecent = useCallback(+ (g: Generation) => {+ leaving.current = true;+ onClose();+ setViewing(g);+ },+ [onClose],+ );+ // Dismissed (Esc, Cancel, a click outside, Ctrl+K again): focus goes back where it was (the field you were typing+ // in, the search button), not to the top of the page.+ const restoreFocus = useCallback(+ (e: Event) => {+ e.preventDefault();+ const el = takeReturn();+ if (leaving.current) {+ leaving.current = false;+ return;+ }+ returnFocus(el);+ },+ [takeReturn],+ );++ return (+ <>+ <DialogPrimitive.Root open={session.open} onOpenChange={(o) => !o && onClose()}>+ <DialogPrimitive.Portal>+ <DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-overlay backdrop-blur-[2px] motion-safe:duration-150 motion-safe:data-open:animate-in motion-safe:data-open:fade-in-0 motion-safe:data-closed:animate-out motion-safe:data-closed:fade-out-0" />+ <DialogPrimitive.Content+ onCloseAutoFocus={restoreFocus}+ className={cn(+ "fixed inset-0 z-50 flex h-dvh w-full flex-col overflow-hidden bg-popover text-popover-foreground outline-none",+ "pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]",+ "md:inset-auto md:top-[58px] md:left-1/2 md:h-auto md:max-h-[min(784px,calc(100dvh-116px))] md:w-[760px] md:max-w-[calc(100vw-2rem)] md:-translate-x-1/2 md:rounded-[18px] md:border md:pt-0 md:pb-0 md:shadow-heavy",+ "motion-safe:duration-150 motion-safe:data-open:animate-in motion-safe:data-open:fade-in-0 motion-safe:data-closed:animate-out motion-safe:data-closed:fade-out-0 md:motion-safe:data-open:zoom-in-98",+ )}+ >+ <DialogPrimitive.Title className="sr-only">Search Fuobe</DialogPrimitive.Title>+ <DialogPrimitive.Description className="sr-only">+ Find a studio, a tool, an app, a camera motion, an effect, a model, a setting or a recent creation, or browse every studio.+ </DialogPrimitive.Description>+ <PaletteBody key={session.id} initialQuery={session.query ?? ""} initialGroup={session.group} onPick={pick} onOpenRecent={openRecent} onClose={onClose} />+ </DialogPrimitive.Content>+ </DialogPrimitive.Portal>+ </DialogPrimitive.Root>+ {viewing && (+ <Suspense fallback={null}>+ <Viewer generation={viewing} index={0} onClose={() => setViewing(null)} />+ </Suspense>+ )}+ </>+ );+}++type Group = LauncherGroupId | "all";++/**+ * Keeps aria-activedescendant on the field and the list on the row that is selected. The selection is ours (each query+ * starts on its best match), and cmdk only updates the id it announces on its own arrow-key moves.+ */+function useActiveDescendant(input: React.RefObject<HTMLInputElement | null>, list: React.RefObject<HTMLDivElement | null>) {+ useEffect(() => {+ const root = list.current;+ if (!root) return;+ const sync = () => {+ const id = root.querySelector("[cmdk-item][data-selected=true]")?.id;+ for (const el of [input.current, root]) {+ if (!el) continue;+ if (id) {+ if (el.getAttribute("aria-activedescendant") !== id) el.setAttribute("aria-activedescendant", id);+ }+ else el.removeAttribute("aria-activedescendant");+ }+ };+ sync();+ const mo = new MutationObserver(sync);+ mo.observe(root, { subtree: true, childList: true, attributes: true, attributeFilter: ["data-selected"] });+ return () => mo.disconnect();+ }, [input, list]);+}++/**+ * The row the list starts on. cmdk keeps no selection once the rows change (the filtering is ours): each new query+ * starts on its best match, so Enter opens it; with nothing typed, on the first studio. The arrows move from there.+ */+export function startValue(searching: boolean, result: SearchResult, recents: Pick<Generation, "id">[], tiles: Pick<NavEntry, "id">[]): string {+ const tile = tiles[0] ? `tile:${tiles[0].id}` : "";+ if (!searching) return tile;+ const first = result.best[0] ?? result.also[0] ?? result.groups[0]?.hits[0];+ return first?.key ?? (recents[0] ? `recent:${recents[0].id}` : tile);+}++/** What the palette lists and searches; mounted afresh on each open. */+export function PaletteBody({+ initialQuery,+ initialGroup,+ onPick,+ onOpenRecent,+ onClose,+}: {+ initialQuery: string;+ initialGroup?: LauncherGroupId;+ onPick: (href: string, id?: string) => void;+ onOpenRecent: (g: Generation) => void;+ onClose: () => void;+}) {+ const [q, setQ] = useState(initialQuery);+ const [group, setGroup] = useState<Group>(initialGroup ?? "all");+ const dq = useDebounced(q.trim(), 200);+ const kind = useViewerKind();+ const mode = useEngineMode();+ const access = useModelAccess();+ const index = useQuery({ queryKey: PALETTE_INDEX_KEY, queryFn: fetchPaletteIndex, staleTime: Infinity });+ const recent = useGenerations({ q: dq || undefined, limit: 5, statuses: ["succeeded"] }, { keepPrevious: true });+ // Skills that run by themselves: "Run <skill>…" opens its Run form.+ const skills = useSkills();+ const input = useRef<HTMLInputElement>(null);+ const list = useRef<HTMLDivElement>(null);+ useActiveDescendant(input, list);++ // Nothing a viewer can't see is searched (and before the viewer is known: what a guest may see).+ const nav = useMemo(() => navSearchEntries(entriesFor(kind)), [kind]);+ const entries = useMemo(+ () => [...nav, ...skillEntries(skills.data ?? []), ...(index.data ? indexEntries(index.data, mode, access, { owner: kind === "owner" }) : [])],+ [nav, skills.data, index.data, mode, access, kind],+ );+ // Not deferred: ranking every entry takes a millisecond or two, and Enter must act on what was typed.+ const result = useMemo(() => searchNav(q, entries), [q, entries]);+ const searching = !!q.trim();+ const recentItems = (recent.data ?? []).filter((g) => g.outputs[0]);+ const tiles = useMemo(() => launcherEntries(kind, group === "all" ? undefined : group), [kind, group]);++ const best = startValue(searching, result, recentItems, tiles);+ const [moved, setMoved] = useState<{ q: string; group: Group; value: string } | null>(null);+ const selected = moved?.q === q && moved.group === group ? moved.value : best;++ const total = result.best.length + result.also.length + result.groups.reduce((n, g) => n + g.hits.length, 0) + (searching ? recentItems.length : 0);+ const announce = useDebounced(searching ? (total ? `${total} result${total === 1 ? "" : "s"}` : "No results") : "", 300);++ const pickHit = (h: NavHit) => onPick(h.href, h.id);+ const pickTile = (e: NavEntry) => onPick(e.href, e.id);+ const groupLabel = group === "all" ? undefined : LAUNCHER_GROUPS.find((g) => g.id === group)?.label;++ return (+ <CommandPrimitive+ shouldFilter={false}+ loop+ value={selected}+ onValueChange={(value) => setMoved({ q, group, value })}+ label="Search Fuobe"+ className="flex min-h-0 flex-1 flex-col"+ >+ <div className="flex h-[68px] shrink-0 items-center gap-3.5 border-b border-brand-text/25 pr-3.5 pl-[22px] max-md:pl-4">+ <Search aria-hidden className="size-5 shrink-0 text-brand-text" />+ <CommandPrimitive.Input+ ref={input}+ value={q}+ onValueChange={setQ}+ autoFocus+ placeholder="What do you want to make?"+ aria-label="Search studios, apps, motions and effects"+ className="h-11 min-w-0 flex-1 bg-transparent text-[20px] caret-brand-text outline-none placeholder:text-muted-foreground max-md:text-[17px]"+ />+ {index.isLoading && searching && <Loader2 className="size-4 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none" aria-label="Loading the catalog" />}+ {q && (+ <button+ type="button"+ aria-label="Clear search"+ onKeyDown={keepKeys}+ onClick={() => {+ setQ("");+ input.current?.focus();+ }}+ className={cn("grid size-10 shrink-0 place-items-center rounded-[10px] text-muted-foreground hover:bg-accent hover:text-foreground max-md:size-11 [@media(pointer:coarse)]:size-11", focusRing)}+ >+ <X className="size-4" />+ </button>+ )}+ {/* Touch screens have no Esc (and a phone shows the palette full screen): a visible way out. */}+ <button+ type="button"+ onKeyDown={keepKeys}+ onClick={onClose}+ // Its name starts with the words it shows (Esc on a desktop, Cancel on a phone), for voice control.+ className={cn(+ "h-10 shrink-0 rounded-[10px] border bg-secondary px-3 max-md:h-11 [@media(pointer:coarse)]:h-11 text-[12px] font-medium text-secondary-foreground hover:bg-accent max-md:border-0 max-md:bg-transparent max-md:px-2 max-md:text-[15px] max-md:text-brand-text [@media(hover:none)]:border-0 [@media(hover:none)]:bg-transparent [@media(hover:none)]:text-[15px] [@media(hover:none)]:text-brand-text",+ focusRing,+ )}+ >+ <span className="max-md:hidden [@media(hover:none)]:hidden">+ Esc<span className="sr-only"> (close search)</span>+ </span>+ <span className="md:hidden [@media(hover:none)]:inline!">+ Cancel<span className="sr-only"> search</span>+ </span>+ </button>+ </div>++ {/* The goal chips: buttons, so outside the list (a listbox holds options only). With nothing typed they head the+ studios right under them; while searching the studios come last, under their own heading. */}+ {!searching && (+ <div className="shrink-0 px-5 pt-2.5 max-md:px-3">+ <div className="flex flex-wrap items-center gap-x-2.5 py-1 md:h-10 md:flex-nowrap md:py-0">+ <span aria-hidden className="ml-1.5 text-[11px] leading-[14px] font-semibold tracking-[.08em] text-brand-text uppercase">+ Every studio+ </span>+ <span className="text-[12px] text-muted-foreground">{groupLabel ? `${tiles.length} in ${groupLabel}` : studioCount()}</span>+ <div+ role="group"+ aria-label="Show the studios for one goal"+ className="-mx-1 flex w-full items-center gap-0.5 overflow-x-auto px-1 scrollbar-none md:ml-auto md:w-auto md:overflow-visible"+ >+ {(["all", ...LAUNCHER_GROUPS.map((g) => g.id)] as Group[]).map((id) => {+ const g = LAUNCHER_GROUPS.find((x) => x.id === id);+ const on = group === id;+ return (+ <button+ key={id}+ type="button"+ aria-pressed={on}+ aria-label={g ? g.label : "All studios"}+ onKeyDown={keepKeys}+ onClick={() => setGroup(id)}+ className={cn("group/chip flex h-11 min-w-11 shrink-0 items-center justify-center rounded-full px-0.5 md:h-10", focusRing)}+ >+ <span+ className={cn(+ "inline-flex h-7 items-center rounded-full border px-[11px] text-[12px] font-medium motion-safe:transition-colors",+ on ? "border-brand-text/40 bg-brand-faint text-brand-text" : "border-border text-muted-foreground group-hover/chip:text-foreground",+ )}+ >+ {g ? g.chip : "All"}+ </span>+ </button>+ );+ })}+ </div>+ </div>+ </div>+ )}++ <CommandPrimitive.List ref={list} className={cn("min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain px-5 pb-3 outline-none max-md:px-3", searching ? "pt-3.5" : "pt-1")}>+ {searching && (+ <>+ {total === 0 && (+ <p className="py-8 text-center text-[13px] text-muted-foreground">+ {index.isLoading ? "Looking through apps, motions and models…" : `Nothing matches “${q.trim()}”. Try a shorter word, or pick a studio below.`}+ </p>+ )}+ {result.best.length > 0 && (+ <CommandPrimitive.Group heading="Best matches" className={cn("mb-4", sectionHeading)}>+ <div className="flex flex-col gap-0.5">+ {result.best.map((h) => (+ <BestRow key={h.key} hit={h} onPick={pickHit} />+ ))}+ </div>+ </CommandPrimitive.Group>+ )}+ {result.also.length > 0 && (+ <CommandPrimitive.Group heading="Also try" className={cn("mb-4", sectionHeading)}>+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">+ {result.also.map((h) => (+ <AlsoTile key={h.key} hit={h} onPick={pickHit} />+ ))}+ </div>+ </CommandPrimitive.Group>+ )}+ {result.groups.map((g) => (+ <CommandPrimitive.Group key={g.kind} heading={g.label} className={cn("mb-4", sectionHeading)}>+ {g.hits.map((h) => (+ <HitRow key={h.key} hit={h} onPick={pickHit} />+ ))}+ </CommandPrimitive.Group>+ ))}+ {recentItems.length > 0 && (+ <CommandPrimitive.Group heading={KIND_LABELS.recent} className={cn("mb-4", sectionHeading)}>+ <div className="grid grid-cols-1 gap-1 sm:grid-cols-2">+ {recentItems.map((g) => (+ <RecentRow key={g.id} g={g} onOpen={onOpenRecent} />+ ))}+ </div>+ </CommandPrimitive.Group>+ )}+ </>+ )}+ <CommandPrimitive.Group+ heading={groupLabel ? `Every studio · ${tiles.length} in ${groupLabel}` : "Every studio"}+ className={cn(searching ? cn("border-t pt-3", sectionHeading) : "**:[[cmdk-group-heading]]:sr-only")}+ >+ <div className="grid grid-cols-2 gap-x-2 min-[420px]:grid-cols-3 md:grid-cols-4">+ {tiles.map((e) => (+ <StudioTile key={e.id} e={e} onPick={pickTile} />+ ))}+ </div>+ </CommandPrimitive.Group>+ {!searching && recentItems.length > 0 && (+ <CommandPrimitive.Group heading="Jump back in" className={cn("mt-3 border-t pt-3", sectionHeading)}>+ <div className="grid grid-cols-1 gap-1 sm:grid-cols-2">+ {recentItems.slice(0, 4).map((g) => (+ <RecentRow key={g.id} g={g} onOpen={onOpenRecent} />+ ))}+ </div>+ </CommandPrimitive.Group>+ )}+ </CommandPrimitive.List>++ <div role="status" aria-live="polite" className="sr-only">+ {announce}+ </div>+ <Hints />+ </CommandPrimitive>+ );+}++function Hints() {+ const mod = useModKey();+ const cap = "h-[22px] min-w-[22px] rounded-md border border-b-2 bg-secondary px-1.5 text-[11px] text-foreground";+ return (+ <div className="flex h-[46px] shrink-0 items-center gap-3 border-t bg-muted/40 px-[22px] text-[12px] text-muted-foreground max-md:hidden [@media(hover:none)]:hidden">+ <span className="flex items-center gap-1">+ <Kbd className={cap}>↑</Kbd>+ <Kbd className={cap}>↓</Kbd>+ <span className="ml-1">to move</span>+ </span>+ <span aria-hidden>·</span>+ <span className="flex items-center gap-2">+ <Kbd className={cap}>Enter</Kbd> to open+ </span>+ <span aria-hidden>·</span>+ <span className="flex items-center gap-2">+ <Kbd className={cap}>Esc</Kbd> to close+ </span>+ <span className="ml-auto flex items-center gap-1.5">+ Open it from anywhere with <Kbd className={cap}>/</Kbd> or <Kbd className={cap}>{mod === "⌘" ? "⌘K" : "Ctrl+K"}</Kbd>+ </span>+ </div>+ );+}diff --git a/src/components/nav/search-results.tsx b/src/components/nav/search-results.tsxnew file mode 100644index 00000000..469b039b--- /dev/null+++ b/src/components/nav/search-results.tsx@@ -0,0 +1,208 @@+"use client";++import { Command as CommandPrimitive } from "cmdk";+import { ChevronRight, Clapperboard, CornerDownLeft, Film, LayoutGrid, Play, Wand2 } from "lucide-react";+import { MediaThumb } from "@/components/studio/result-media";+import type { Generation } from "@/lib/catalog/types";+import { userTitle } from "@/lib/library";+import type { NavEntry } from "@/lib/nav-model";+import type { NavHit } from "@/lib/nav-search";+import { cn } from "@/lib/utils";+import { CoverThumb } from "./cover-thumb";++/*+ * The search palette's rows and tiles. Each is a cmdk item (role="option"), so the arrow keys reach every one of them+ * from the search field, and Enter opens the selected one. The cover boxes have fixed sizes: nothing moves when a+ * picture arrives.+ */++/** A section's heading, as the launcher's columns have them. */+export const sectionHeading =+ "**:[[cmdk-group-heading]]:mb-1.5 **:[[cmdk-group-heading]]:ml-1.5 **:[[cmdk-group-heading]]:text-[11px] **:[[cmdk-group-heading]]:leading-[14px] **:[[cmdk-group-heading]]:font-semibold **:[[cmdk-group-heading]]:uppercase **:[[cmdk-group-heading]]:tracking-[.08em] **:[[cmdk-group-heading]]:text-brand-text";++/** A selected row: a tint and a brand ring strong enough to find (focus stays in the field; cmdk marks it data-selected). */+const selected = "data-[selected=true]:bg-accent data-[selected=true]:shadow-[inset_0_0_0_1.5px_var(--brand-text)]";++/** What kind of thing a hit is, as the tag at the end of its row says it. */+export function kindTag(hit: Pick<NavHit, "kind" | "navKind">): string {+ switch (hit.kind) {+ case "studio":+ return "Studio";+ case "tool":+ return "Tool";+ case "app":+ return "App";+ case "motion":+ return "Motion";+ case "effect":+ return "Effect";+ case "model":+ return "Model";+ case "skill":+ return "Skill";+ case "setting":+ return "Settings";+ case "recent":+ return "Recent";+ }+ return hit.navKind === "create" ? "Create" : hit.navKind === "action" ? "Action" : "Page";+}++const KIND_ICON = { app: LayoutGrid, motion: Film, effect: Wand2, model: Clapperboard, skill: Play } as const;++/** A hit's picture: its nav cover, an index preset's own small cover, or its icon on the muted fill. */+function HitCover({ hit, size }: { hit: NavHit; size: "thumb" | "chip" | "row" }) {+ if (hit.cover?.startsWith("/")) {+ const box = { thumb: "h-12 w-16 rounded-[8px]", chip: "h-[42px] w-14 rounded-[8px]", row: "h-[27px] w-9 rounded-[6px]" }[size];+ const [w, h] = { thumb: [64, 48], chip: [56, 42], row: [36, 27] }[size];+ return (+ <span aria-hidden className={cn("relative block shrink-0 overflow-hidden bg-muted", box)}>+ {/* eslint-disable-next-line @next/next/no-img-element -- versioned static covers, sized by the box */}+ <img src={hit.cover} width={w} height={h} alt="" loading="lazy" decoding="async" draggable={false} className="absolute inset-0 size-full object-cover" />+ </span>+ );+ }+ // A nav entry: its cover, else its icon (CoverThumb draws either in the same box).+ if (hit.cover || hit.icon) return <CoverThumb id={hit.cover} size={size} icon={hit.icon} />;+ const Icon = KIND_ICON[hit.kind as keyof typeof KIND_ICON] ?? LayoutGrid;+ const box = { thumb: "h-12 w-16 rounded-[8px]", chip: "h-[42px] w-14 rounded-[8px]", row: "h-[27px] w-9 rounded-[6px]" }[size];+ return (+ <span aria-hidden className={cn("relative grid shrink-0 place-items-center bg-muted text-muted-foreground", box)}>+ <Icon className="size-4" />+ </span>+ );+}++function Tag({ hit }: { hit: NavHit }) {+ const studio = hit.kind === "studio";+ return (+ <span+ className={cn(+ "inline-flex h-[22px] shrink-0 items-center rounded-full px-2.5 text-[11.5px] font-medium",+ studio ? "bg-brand-faint text-brand-text" : "bg-secondary text-secondary-foreground",+ )}+ >+ {kindTag(hit)}+ </span>+ );+}++/** The Enter keycap on the selected best match. */+function EnterCap() {+ return (+ <span+ aria-hidden+ className="hidden h-[22px] w-[26px] shrink-0 items-center justify-center rounded-md border border-b-2 border-border bg-background group-data-[selected=true]/hit:inline-flex [@media(hover:none)]:hidden!"+ >+ <CornerDownLeft className="size-3" />+ </span>+ );+}++/** A tool's studio before its name ("Audio › Clean up voice"), or a preset's gallery ("Camera motions › Dolly In"). */+function Name({ hit, crumb, className }: { hit: NavHit; crumb?: string; className?: string }) {+ return (+ <span className={cn("block truncate", className)}>+ {crumb && (+ <>+ <span className="font-medium text-muted-foreground">{crumb}</span>+ <ChevronRight aria-hidden className="mx-1 inline size-3 align-[-1px] text-muted-foreground" />+ </>+ )}+ {hit.label}+ </span>+ );+}++const crumbOf = (hit: NavHit) => hit.from ?? (hit.kind === "tool" ? hit.hint : undefined);++/** A best match: a 64x48 cover, its name and line, what it is, and the Enter keycap when selected. */+export function BestRow({ hit, onPick }: { hit: NavHit; onPick: (h: NavHit) => void }) {+ return (+ <CommandPrimitive.Item+ value={hit.key}+ onSelect={() => onPick(hit)}+ className={cn("group/hit flex h-[58px] cursor-pointer items-center gap-3.5 rounded-xl py-[5px] pr-3 pl-[5px] outline-none", selected)}+ >+ <HitCover hit={hit} size="thumb" />+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">+ <Name hit={hit} crumb={crumbOf(hit)} className="text-[14.5px] font-semibold" />+ <span className="truncate text-[12.5px] text-muted-foreground">{hit.what ?? hit.hint}</span>+ </span>+ <Tag hit={hit} />+ <EnterCap />+ </CommandPrimitive.Item>+ );+}++/** "Also try": a preset tile with where it comes from. */+export function AlsoTile({ hit, onPick }: { hit: NavHit; onPick: (h: NavHit) => void }) {+ return (+ <CommandPrimitive.Item+ value={hit.key}+ onSelect={() => onPick(hit)}+ className={cn("group/hit flex h-14 min-w-0 cursor-pointer items-center gap-3 rounded-xl py-[5px] pr-3 pl-[5px] outline-none", selected)}+ >+ <HitCover hit={hit} size="chip" />+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">+ <Name hit={hit} crumb={crumbOf(hit)} className="text-[14px] font-semibold" />+ <span className="truncate text-[12.5px] text-muted-foreground">{hit.what ?? hit.hint}</span>+ </span>+ <Tag hit={hit} />+ </CommandPrimitive.Item>+ );+}++/** Any other match, in its kind's group. */+export function HitRow({ hit, onPick }: { hit: NavHit; onPick: (h: NavHit) => void }) {+ return (+ <CommandPrimitive.Item+ value={hit.key}+ onSelect={() => onPick(hit)}+ className={cn("group/hit flex h-11 cursor-pointer items-center gap-3 rounded-[10px] pr-3 pl-1 text-[14px] outline-none", selected)}+ >+ <HitCover hit={hit} size="row" />+ <Name hit={hit} crumb={hit.kind === "tool" ? hit.hint : undefined} className="min-w-0 flex-1 font-medium" />+ {hit.kind !== "tool" && (hit.what ?? hit.hint) && (+ <span className="max-w-[45%] shrink-0 truncate pl-2 text-[12px] text-muted-foreground max-sm:hidden">{hit.what ?? hit.hint}</span>+ )}+ </CommandPrimitive.Item>+ );+}++/** A studio in "Every studio": a 36x27 cover and its name (the short one on a phone), on up to two lines. */+export function StudioTile({ e, onPick }: { e: NavEntry; onPick: (e: NavEntry) => void }) {+ return (+ <CommandPrimitive.Item+ value={`tile:${e.id}`}+ keywords={[e.label]}+ onSelect={() => onPick(e)}+ className={cn("group/hit flex h-11 min-w-0 cursor-pointer items-center gap-2.5 rounded-[10px] pr-2 pl-1 outline-none md:h-10", selected)}+ >+ <CoverThumb id={e.cover} size="row" icon={e.icon} />+ <span className="line-clamp-2 min-w-0 text-[13px] leading-[1.2] font-medium text-foreground">+ <span className="md:hidden">{e.short ?? e.label}</span>+ <span className="max-md:hidden">{e.label}</span>+ </span>+ </CommandPrimitive.Item>+ );+}++/** A recent creation: its picture, its title and the model that made it. Opens the viewer. */+export function RecentRow({ g, onOpen }: { g: Generation; onOpen: (g: Generation) => void }) {+ return (+ <CommandPrimitive.Item+ value={`recent:${g.id}`}+ onSelect={() => onOpen(g)}+ className={cn("group/hit flex h-14 min-w-0 cursor-pointer items-center gap-3 rounded-xl py-1 pr-3 pl-1 outline-none", selected)}+ >+ <span aria-hidden className="relative h-12 w-16 shrink-0 overflow-hidden rounded-[8px] bg-muted">+ {g.outputs[0] && <MediaThumb output={g.outputs[0]} g={g} />}+ </span>+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="truncate text-[14px] font-semibold">{userTitle(g)}</span>+ <span className="truncate text-[12.5px] text-muted-foreground">{g.modelName}</span>+ </span>+ </CommandPrimitive.Item>+ );+}diff --git a/src/components/nav/status-chips.tsx b/src/components/nav/status-chips.tsxnew file mode 100644index 00000000..91ba31fe--- /dev/null+++ b/src/components/nav/status-chips.tsx@@ -0,0 +1,428 @@+"use client";++import dynamic from "next/dynamic";+import { cloneElement } from "react";+import { Cpu } from "lucide-react";+import { PlaceholdersOnChip } from "@/components/demo-mode";+import { IntentLink } from "@/components/intent-link";+import { awayFix, openConnect, useComputerSupport } from "@/components/gpu/open-connect";+import { usePagePlace } from "@/components/gpu/use-page-place";+import { useHadItems } from "@/components/use-had-items";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Skeleton } from "@/components/ui/skeleton";+import { ownGpuOf, signInHref, useEngineMode, useHydrated, useStatus, useViewer, type EngineMode, type StatusInfo } from "@/lib/api";+import { placeholdersOn } from "@/lib/demo-mode";+import { deviceLabel } from "@/lib/gpu/readiness";+import { safeLink, useInterest } from "@/lib/hosted";+import type { ViewerKind } from "@/lib/nav-model";+import { cn } from "@/lib/utils";++/*+ * What the sidebar's footer said about GPUs, keys and balance, moved here unchanged in what it says and to whom: the+ * owner's status (cloud models, ComfyUI, the engine mode), a visitor's own GPU, an account's balance, the note of a tab+ * that runs the person's jobs on their own computer, and the owner's "Placeholders on". The account menu and the phone's+ * You sheet show them; the bar shows the balance, the computer note and placeholders as pills in slots kept for them+ * before the first paint (html[data-had-…], use-had-items.ts), so nothing in the bar moves when the status arrives.+ */++// The note of a tab that runs the person's jobs on their own computer's ComfyUI (only for someone whose runs go there).+const ComputerNote = dynamic(() => import("@/components/gpu/computer-runner").then((m) => m.ComputerNote), { ssr: false });+/** The pill's face until the runner's code is here: the same icon and words as when there is no note. */+function PillFaceIdle() {+ return (+ <>+ <Cpu aria-hidden className="size-4 text-brand-text" />+ <span className="hidden xl:inline">Your computer</span>+ <span className="sr-only xl:hidden">Your computer</span>+ <span className="sr-only">, your computer's GPU</span>+ </>+ );+}+const ComputerPillFace = dynamic(() => import("@/components/gpu/computer-runner").then((m) => m.ComputerPillFace), { ssr: false, loading: () => <PillFaceIdle /> });+const ComputerNoteLive = dynamic(() => import("@/components/gpu/computer-runner").then((m) => m.ComputerNoteLive), { ssr: false });++type Viewer = NonNullable<StatusInfo["viewer"]>;++const CHIP = "flex min-h-11 w-full flex-col justify-center gap-1 rounded-md px-2 py-1.5 text-left text-[12px] text-muted-foreground transition-colors hover:bg-accent motion-reduce:transition-none";++export function StatusDot({ ok }: { ok: boolean | undefined }) {+ return <span aria-hidden className={cn("size-1.5 shrink-0 rounded-full", ok ? "bg-success" : "bg-subtle-foreground")} />;+}++/**+ * A link or button as a row of a menu (`item`: arrow keys reach it, choosing it closes the menu) or as it is+ * elsewhere. The classes go through the menu item, so they win over its defaults.+ */+function Actionable({ item, className, children }: { item?: boolean; className: string; children: React.ReactElement<{ className?: string }> }) {+ if (!item) return cloneElement(children, { className: cn(className, children.props.className) });+ return (+ <DropdownMenuItem asChild className={cn("items-stretch focus:bg-accent", className)}>+ {children}+ </DropdownMenuItem>+ );+}++/**+ * "Your GPU": a visitor's own (public sign-up), never the install's, or the owner's computer. A guest is sent to sign up+ * first; anyone else without one opens "Connect your GPU"; a connected one says whether it answers.+ */+export function YourGpuChip({ gpu, guest, hosted, item }: { gpu: Viewer["gpu"]; guest: boolean; hosted?: boolean; item?: boolean }) {+ const g = gpu;+ // ComfyUI on this computer is closed, or runs without Fuobe's setting: the finder, at that step (elsewhere: /connect).+ const fix = awayFix(g.connected ? g : undefined, useComputerSupport());+ if (g.connected) {+ const vram = g.vramBytes ? `${Math.round(g.vramBytes / 2 ** 30)} GB` : "";+ const inner = (+ <>+ <span className="flex w-full items-center gap-2">+ <StatusDot ok={g.online} /> Your GPU+ <span className="ml-auto">{g.online ? "online" : g.comfy === "down" ? "ComfyUI not running" : g.comfy === "no-setting" ? "needs a setting" : "offline"}</span>+ </span>+ {(g.device || vram || g.mode === "computer") && (+ <span className="truncate text-[11px]">{[g.mode === "computer" && "Your computer", deviceLabel(g.device), vram && `${vram} VRAM`].filter(Boolean).join(" · ")}</span>+ )}+ </>+ );+ return fix ? (+ <Actionable item={item} className={CHIP}>+ <button type="button" onClick={fix}>+ {inner}+ </button>+ </Actionable>+ ) : (+ <Actionable item={item} className={CHIP}>+ <IntentLink href="/connect">{inner}</IntentLink>+ </Actionable>+ );+ }+ const body = (+ <span className="flex w-full items-center gap-2">+ <StatusDot ok={false} /> Your GPU+ {/* Runs go to this studio's GPUs too (hosted runs): one's own is an option. */}+ <span className={cn("ml-auto font-medium", hosted ? "text-muted-foreground" : "text-brand-text")}>{hosted ? "Optional" : "Connect"}</span>+ </span>+ );+ return guest ? (+ <Actionable item={item} className={CHIP}>+ <a href={signInHref("signup", "/connect")}>{body}</a>+ </Actionable>+ ) : (+ <Actionable item={item} className={CHIP}>+ <button type="button" onClick={() => openConnect(true)}>+ {body}+ </button>+ </Actionable>+ );+}++/** "refills in 5 h", in the visitor's own time. */+export function refillWords(at: number, now = Date.now()): string {+ const ms = at - now;+ if (ms <= 0) return "refills soon";+ const h = Math.round(ms / 3_600_000);+ return h >= 1 ? `refills in ${h} h` : `refills in ${Math.max(1, Math.round(ms / 60_000))} min`;+}++/**+ * The balance's menu items (a studio with a billing service, src/server/billing.ts): the service's own words for what+ * the account has left, its detail lines, its links, its offer, and the way to run for free on one's own GPU or keys.+ */+function BalanceItems({ viewer }: { viewer: Viewer }) {+ const b = viewer.balance!;+ const interest = useInterest();+ const action = safeLink(b.action?.url);+ return (+ <>+ <DropdownMenuLabel className="text-[12px] font-normal text-muted-foreground">{b.text}</DropdownMenuLabel>+ {b.detail.map((d, i) => (+ <div key={i} className="flex justify-between gap-3 px-2 py-1 text-[12px]">+ <span className="text-muted-foreground">{d.label}</span>+ <span className="text-right">{d.text}</span>+ </div>+ ))}+ <DropdownMenuSeparator />+ {action && b.action && (+ <DropdownMenuItem asChild>+ <a href={action} target={action.startsWith("/") ? undefined : "_blank"} rel="noopener noreferrer">+ {b.action.label}+ </a>+ </DropdownMenuItem>+ )}+ {b.offer && <DropdownMenuItem onSelect={() => interest.mutate(b.offer!.key)}>{b.offer.label}</DropdownMenuItem>}+ {(viewer.links ?? []).map((l, i) => {+ const href = safeLink(l.url);+ return href ? (+ <DropdownMenuItem key={i} asChild>+ <a href={href} target={href.startsWith("/") ? undefined : "_blank"} rel="noopener noreferrer">+ {l.label}+ </a>+ </DropdownMenuItem>+ ) : null;+ })}+ <DropdownMenuItem asChild>+ <IntentLink href="/connect">+ <Cpu /> Use your own GPU or keys (free)+ </IntentLink>+ </DropdownMenuItem>+ </>+ );+}++function balanceLabel(viewer: Viewer): { chip: string; refill: string | null } {+ const b = viewer.balance!;+ return { chip: b.chip, refill: b.refillAt ? refillWords(b.refillAt) : null };+}++/**+ * The balance chip with its own menu. `pill`: the bar's compact form (one line, 36 px); otherwise the footer-style block+ * (the You sheet, and inside the account menu it is a submenu-free block with the same items).+ */+export function BalanceChip({ viewer, pill, className }: { viewer: Viewer; pill?: boolean; className?: string }) {+ const b = viewer.balance!;+ const { chip, refill } = balanceLabel(viewer);+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label={`${chip}${refill ? `, ${refill}` : ""}`}+ className={cn(+ pill+ ? "inline-flex h-9 max-w-56 items-center gap-2 rounded-full [@media(pointer:coarse)]:h-11 border border-sidebar-border px-3 text-[12.5px] text-muted-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none data-[state=open]:bg-accent"+ : CHIP,+ className,+ )}+ >+ <span className="flex min-w-0 items-center gap-2">+ <StatusDot ok={b.amount > 0} /> <span className="truncate font-medium text-foreground">{chip}</span>+ {refill && <span className={cn("ml-auto shrink-0", pill && "hidden xl:inline")}>{refill}</span>}+ </span>+ {!pill && b.sub && <span className="truncate text-[11px]">{b.sub}</span>}+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent side={pill ? "bottom" : "top"} align={pill ? "end" : "start"} className="w-64">+ <BalanceItems viewer={viewer} />+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++/** The balance inside the account menu: the chip's words as a label, then its items, at the same level as the menu's. */+export function BalanceSection({ viewer }: { viewer: Viewer }) {+ const b = viewer.balance!;+ const { chip, refill } = balanceLabel(viewer);+ return (+ <>+ <DropdownMenuLabel className="flex flex-col gap-0.5 font-normal">+ <span className="flex items-center gap-2 text-[12.5px]">+ <StatusDot ok={b.amount > 0} /> <span className="font-medium text-foreground">{chip}</span>+ {refill && <span className="ml-auto text-[12px] text-muted-foreground">{refill}</span>}+ </span>+ {b.sub && <span className="text-[11px] text-muted-foreground">{b.sub}</span>}+ </DropdownMenuLabel>+ <BalanceItems viewer={viewer} />+ </>+ );+}++/** The owner's GPU as "Your GPU": on the owner's computer, or (a hosted studio with nothing connected) one to connect. */+function useOwnerGpu(status: StatusInfo | undefined, mode: EngineMode) {+ const place = usePagePlace();+ const comfy = status?.providers.comfyui?.configured;+ // Not in Paid APIs only mode: ComfyUI isn't used there, wherever it runs.+ return status && !status.viewer && mode !== "cloud" && (status.ownerGpu || (place === "hosted" && !comfy)) ? (ownGpuOf(status) ?? { connected: false }) : null;+}++/** The status as it may be shown: none until hydrated (a status that lands mid-hydration must not change the HTML). */+export function useShownStatus(): StatusInfo | undefined {+ const hydrated = useHydrated();+ const data = useStatus().data;+ return hydrated ? data : undefined;+}++/**+ * The owner's status (the sidebar footer's, word for word): cloud models connected or "add key", ComfyUI online or+ * offline (or the owner's computer as "Your GPU"), and the engine mode when it isn't both. Owner only: the caller+ * renders it only for the owner (useViewerKind() === "owner").+ */+export function OwnerStatus({ item }: { item?: boolean }) {+ const status = useShownStatus();+ const mode = useEngineMode();+ const ownerGpu = useOwnerGpu(status, mode);+ if (status?.viewer) return null;+ const cloud = !!status && !!(status.providers.fal?.configured || status.providers.replicate?.configured);+ const comfy = status?.providers.comfyui?.configured;+ const modeLine = mode !== "both" && <span className="px-2 pb-1 text-[11px] text-muted-foreground">{mode === "open" ? "Open source only" : "Paid APIs only"}</span>;+ if (!status)+ return (+ <div aria-hidden className="flex h-[30px] items-center px-2">+ <Skeleton className="h-3 w-2/3" />+ </div>+ );+ if (ownerGpu)+ return (+ <>+ {mode !== "open" && (+ <Actionable item={item} className={cn(CHIP, "flex-row items-center gap-2")}>+ <IntentLink href="/settings">+ <StatusDot ok={cloud} /> Cloud models+ <span className="ml-auto">{cloud ? "connected" : "add key"}</span>+ </IntentLink>+ </Actionable>+ )}+ <YourGpuChip gpu={ownerGpu} guest={false} item={item} />+ {modeLine}+ </>+ );+ return (+ <Actionable item={item} className={cn(CHIP, "gap-1.5")}>+ <IntentLink href="/settings">+ {mode !== "open" && (+ <span className="flex w-full items-center gap-2">+ <StatusDot ok={cloud} /> Cloud models+ <span className="ml-auto">{cloud ? "connected" : "add key"}</span>+ </span>+ )}+ {mode !== "cloud" && (+ <span className="flex w-full items-center gap-2">+ <StatusDot ok={comfy} /> ComfyUI+ <span className="ml-auto">{comfy ? "online" : "offline"}</span>+ </span>+ )}+ {mode !== "both" && <span className="text-[11px] text-muted-foreground">{mode === "open" ? "Open source only" : "Paid APIs only"}</span>}+ </IntentLink>+ </Actionable>+ );+}++/**+ * The account menu's GPU section for a visitor (public sign-up): the balance when the studio bills, else their own GPU.+ * Never the install's.+ */+export function VisitorGpu({ item }: { item?: boolean }) {+ const status = useShownStatus();+ const v = status?.viewer;+ if (!v) return null;+ if (v.balance) return item ? <BalanceSection viewer={v} /> : <BalanceChip viewer={v} />;+ return <YourGpuChip gpu={v.gpu} guest={v.kind === "guest"} hosted={!!v.hosted} item={item} />;+}++/** The owner's "Placeholders on", while it is on (the owner's runs only make placeholders). */+export function usePlaceholdersOn(kind: ViewerKind | undefined): boolean {+ const status = useShownStatus();+ return kind === "owner" && !!status && !status.viewer && placeholdersOn(status.demoMode);+}++/**+ * The dot on the avatar: the owner's whether the engine mode's needs are met (a cloud key unless open source only,+ * ComfyUI unless paid APIs only), green or amber; an account's only when its own GPU answers (a positive mark only);+ * nothing for a guest or while the status is unknown.+ */+export function avatarDot(kind: ViewerKind | undefined, status: StatusInfo | undefined, mode: EngineMode): "ok" | "warn" | null {+ if (!status || !kind || kind === "guest") return null;+ if (kind === "account") return status.viewer?.gpu.connected && status.viewer.gpu.online ? "ok" : null;+ if (status.viewer) return null;+ const cloud = !!(status.providers.fal?.configured || status.providers.replicate?.configured);+ const comfy = status.ownerGpu ? status.ownerGpu.online : !!status.providers.comfyui?.configured;+ return (mode === "open" || cloud) && (mode === "cloud" || comfy) ? "ok" : "warn";+}++/**+ * Remembers which of the bar's pills this browser showed last (a balance, the computer note, placeholders on), so the+ * pre-paint script keeps their room on the next load (html[data-had-balance|computer|placeholders]). Mounted once, in+ * the bar. Nothing is remembered until the viewer and the status are known.+ */+export function useRememberPills(kind: ViewerKind | undefined): { balance: boolean; computer: boolean; placeholders: boolean } {+ const status = useShownStatus();+ const viewer = useViewer().data;+ const hydrated = useHydrated();+ const known = !!kind && !!status;+ const balance = known && !!status.viewer?.balance;+ const computer = hydrated && !!kind && viewer?.computer === true;+ const placeholders = usePlaceholdersOn(kind);+ useHadItems("balance", known ? Number(balance) : undefined);+ useHadItems("computer", hydrated && kind ? Number(computer) : undefined);+ useHadItems("placeholders", known ? Number(placeholders) : undefined);+ return { balance, computer, placeholders };+}++/**+ * The computer note as a bar pill (someone whose runs go to their own computer's ComfyUI, viewer.computer): a 36 px+ * button, with "Your computer" beside it from xl, that opens the note and its one action. When there is nothing to do+ * the popover says where the runs go and links to Your GPU.+ */+export function ComputerPill() {+ return (+ <>+ <Popover>+ <PopoverTrigger+ className="inline-flex h-9 w-full min-w-9 items-center justify-center gap-2 rounded-full [@media(pointer:coarse)]:h-11 border border-sidebar-border px-2 text-[12.5px] text-muted-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none data-[state=open]:bg-accent xl:px-3"+ >+ <ComputerPillFace />+ </PopoverTrigger>+ <PopoverContent align="end" className="group/note w-72">+ <ComputerNote />+ <p className="text-[12px] text-muted-foreground group-has-[[role=status]]/note:hidden">Your runs go to the GPU on this computer. Keep a Fuobe tab open while they run.</p>+ <IntentLink href="/connect" className="text-[12px] font-medium text-brand-text underline-offset-4 hover:underline">+ Your GPU+ </IntentLink>+ </PopoverContent>+ </Popover>+ <ComputerNoteLive />+ </>+ );+}++/** The computer note as the phone's You sheet shows it (at the top), for someone whose runs go to their computer. */+export function ComputerNoteBlock() {+ const hydrated = useHydrated();+ const computer = useViewer().data?.computer === true && hydrated;+ return computer ? <ComputerNote /> : null;+}++/**+ * The bar's pills, in slots whose width is kept from the first paint by html[data-had-…] (the server's shell can't+ * know them): a billing account's balance, the computer pill, the owner's "Placeholders on". A slot that was empty last+ * time takes no room, one that had a pill keeps it until the status says otherwise.+ */+export function BarPills({ kind }: { kind: ViewerKind | undefined }) {+ const { balance, computer, placeholders } = useRememberPills(kind);+ const status = useShownStatus();+ const known = !!kind && !!status;+ return (+ <>+ {known ? (+ balance &&+ status.viewer && (+ <span data-slot="balance-pill" className={cn("flex shrink-0", PILL_W.balance)}>+ <BalanceChip viewer={status.viewer} pill className="w-full" />+ </span>+ )+ ) : (+ <span aria-hidden data-slot="balance-pill" className={cn("hidden shrink-0 [html[data-had-balance]_&]:block", PILL_W.balance)} />+ )}+ {kind ? (+ computer && (+ <span data-slot="computer-pill" className={cn("flex shrink-0", PILL_W.computer)}>+ <ComputerPill />+ </span>+ )+ ) : (+ <span aria-hidden data-slot="computer-pill" className={cn("hidden shrink-0 [html[data-had-computer]_&]:block", PILL_W.computer)} />+ )}+ {known ? (+ placeholders && (+ <span data-slot="placeholders-pill" className={cn("hidden shrink-0 items-center xl:flex", PILL_W.placeholders)}>+ <PlaceholdersOnChip className="h-8 px-3 text-[12px]" />+ </span>+ )+ ) : (+ <span aria-hidden data-slot="placeholders-pill" className={cn("hidden shrink-0 xl:[html[data-had-placeholders]_&]:block", PILL_W.placeholders)} />+ )}+ </>+ );+}++/** Each pill's fixed width: the kept room before the status is known is exactly what the pill takes after. */+export const PILL_W = { balance: "w-40", computer: "w-9 xl:w-[140px]", placeholders: "w-[136px]" } as const;diff --git a/src/components/nav/studio-chrome.tsx b/src/components/nav/studio-chrome.tsxnew file mode 100644index 00000000..ed5bbef0--- /dev/null+++ b/src/components/nav/studio-chrome.tsx@@ -0,0 +1,87 @@+"use client";++import { usePathname } from "next/navigation";+import { Suspense, useLayoutEffect } from "react";+import { JobNotifications } from "@/components/job-notifications";+import { SkillBuilderProvider } from "@/components/skills/skill-builder-provider";+import { CHROME_STATE_SCRIPT, fullScreenStudio } from "@/lib/nav";+import type { NavCovers } from "@/lib/nav-covers";+import { ExploreTracker } from "./explore-tracker";+import { NavUiProvider } from "./nav-ui";+import { PhoneSheets } from "./phone-sheets";+import { PhoneTabs } from "./phone-tabs";+import { SearchPaletteProvider } from "./search-context";+import { TopBar } from "./top-bar";++/**+ * Inline script that runs while the HTML is parsed: the server renders one shell for everyone, this marks the page+ * (full-screen studio, who used this browser last, which bar pills it had) before the first paint, so nothing shifts.+ * On the client it renders as inert text/plain (React warns about executable scripts it renders itself).+ */+function ChromeStateScript() {+ return (+ <script+ type={typeof window === "undefined" ? "text/javascript" : "text/plain"}+ suppressHydrationWarning+ dangerouslySetInnerHTML={{ __html: CHROME_STATE_SCRIPT }}+ />+ );+}++/** Keeps html[data-fullscreen-studio] in step with the page on client navigation. Inside Suspense: runtime data. */+function ChromeState() {+ const pathname = usePathname();+ useLayoutEffect(() => {+ document.documentElement.toggleAttribute("data-fullscreen-studio", fullScreenStudio(pathname) !== null);+ }, [pathname]);+ return null;+}++/** The first stop for keyboard users: jumps past the menus to the page (WCAG 2.4.1). */+function SkipLink() {+ return (+ <a+ href="#content"+ onClick={(e) => {+ // Focus the page without adding #content to the URL (Settings reads its hash for deep links).+ const main = document.getElementById("content");+ if (!main) return;+ e.preventDefault();+ main.focus();+ }}+ className="sr-only rounded-md bg-background px-3 py-2 text-[13px] font-medium shadow-strong focus:not-sr-only focus:fixed focus:top-2 focus:left-2 focus:z-50 focus:outline-2 focus:outline-ring"+ >+ Skip to content+ </a>+ );+}++/**+ * The app frame: the top bar from md up, the bottom tabs and their sheets on a phone, the search palette everywhere.+ * Used by the studio layout and the root not-found page. The covers are resolved on the server and passed down.+ */+export function StudioChrome({ covers, children }: { covers: NavCovers; children: React.ReactNode }) {+ return (+ // The palette renders beside its children, so the covers and the frame's state wrap it.+ <NavUiProvider covers={covers}>+ {/* Make a skill from any result's ⋯ menu: a page's, the palette's and a job notification's viewer. */}+ <SkillBuilderProvider>+ <SearchPaletteProvider>+ <ChromeStateScript />+ <SkipLink />+ <TopBar />+ <main id="content" tabIndex={-1} className="relative flex min-h-content w-full min-w-0 flex-1 flex-col bg-background pb-[var(--chrome-bottom)] outline-none">+ {children}+ </main>+ <PhoneTabs />+ <PhoneSheets />+ <Suspense fallback={null}>+ <ExploreTracker />+ <ChromeState />+ </Suspense>+ <JobNotifications />+ </SearchPaletteProvider>+ </SkillBuilderProvider>+ </NavUiProvider>+ );+}diff --git a/src/components/nav/studios-launcher.tsx b/src/components/nav/studios-launcher.tsxnew file mode 100644index 00000000..97ac869b--- /dev/null+++ b/src/components/nav/studios-launcher.tsx@@ -0,0 +1,327 @@+"use client";++import { ChevronDown, Search } from "lucide-react";+import { usePathname } from "next/navigation";+import { useCallback, useEffect, useId, useRef, useState } from "react";+import { IntentLink } from "@/components/intent-link";+import { Kbd } from "@/components/ui/kbd";+import { isNew, launcherActive, launcherColumns, studioCount, type NavEntry, type ViewerKind } from "@/lib/nav-model";+import { cn } from "@/lib/utils";+import { CoverThumb } from "./cover-thumb";+import { useNavUi, useViewerKind } from "./nav-ui";+import { useSearchPalette } from "./search-context";+import { warmNav } from "./nav-prefetch";++/*+ * Studios: every studio on one panel under the bar, grouped by what you want to make, one click and no scrolling (down to+ * 1280x720, and 1024x768). A disclosure for navigation (a button that shows a panel of links), not a menu: Tab walks the+ * links in order, and arrow keys move in the grid (up and down a column, left and right to the same place in the next+ * one). Esc, a click outside or focus leaving it closes it; Esc gives focus back to what opened it.+ */++export const LAUNCHER_ID = "studios-launcher";++export type LauncherKey = "ArrowUp" | "ArrowDown" | "ArrowLeft" | "ArrowRight" | "Home" | "End";++/**+ * Where an arrow key goes from `at` in columns of `lengths` links (row 0 is the lead card): up and down within the+ * column, stopping at its ends; left and right to the same row of the neighbouring column, or its last when shorter;+ * Home and End to the column's first and last. Null when the key goes nowhere (an edge, another key).+ */+export function launcherMove(lengths: readonly number[], at: { col: number; row: number }, key: string): { col: number; row: number } | null {+ const { col, row } = at;+ const len = lengths[col] ?? 0;+ if (!len) return null;+ let next: { col: number; row: number } | null = null;+ if (key === "ArrowDown") next = row < len - 1 ? { col, row: row + 1 } : null;+ else if (key === "ArrowUp") next = row > 0 ? { col, row: row - 1 } : null;+ else if (key === "Home") next = { col, row: 0 };+ else if (key === "End") next = { col, row: len - 1 };+ else if (key === "ArrowLeft" || key === "ArrowRight") {+ let c = col + (key === "ArrowLeft" ? -1 : 1);+ while (c >= 0 && c < lengths.length && !lengths[c]) c += key === "ArrowLeft" ? -1 : 1;+ next = c >= 0 && c < lengths.length ? { col: c, row: Math.min(row, lengths[c] - 1) } : null;+ }+ return next && (next.col !== col || next.row !== row) ? next : null;+}++/** The launcher entry a page is on (a hub mode not in the launcher counts as its studio), for aria-current. */+export function launcherCurrent(pathname: string): string | undefined {+ return launcherActive(pathname);+}++/** The panel: under the bar, as wide as it, scrolling inside only when the window is too short for it. */+export const LAUNCHER_PANEL =+ "absolute inset-x-0 top-full max-h-[calc(100dvh-3.5rem)] overflow-y-auto overscroll-contain border-b border-sidebar-border bg-popover text-popover-foreground shadow-heavy motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-top-1 motion-safe:duration-150";++const LINK_FOCUS = "outline-none focus-visible:ring-2 focus-visible:ring-ring";++function NewBadge() {+ return <span className="shrink-0 rounded-full bg-highlight px-1.5 py-px text-[10px] leading-4 font-semibold text-highlight-foreground">New</span>;+}++function LeadCard({ e, col, current, now }: { e: NavEntry; col: number; current: boolean; now: number }) {+ return (+ <IntentLink+ href={e.href}+ data-col={col}+ data-row={0}+ aria-current={current ? "page" : undefined}+ className={cn(+ "group/lead flex flex-col overflow-hidden rounded-[14px] border bg-card text-card-foreground hover:border-border-strong motion-safe:transition-colors motion-reduce:transition-none",+ current && "border-brand-text/40 bg-brand-faint",+ LINK_FOCUS,+ )}+ >+ <CoverThumb+ id={e.cover}+ size="lead"+ icon={e.icon}+ eager+ className="max-h-[max(64px,calc(100dvh-592px))] rounded-none md:max-lg:max-h-[max(56px,calc(100dvh-460px))]"+ />+ <span className="flex min-w-0 flex-col gap-0.5 px-3 pt-2.5 pb-3 md:max-lg:px-2.5 md:max-lg:py-2">+ <span className="flex min-w-0 items-center gap-1.5">+ <span className={cn("truncate text-[14px] leading-snug font-semibold md:max-lg:text-[13px]")}>{e.label}</span>+ {isNew(e, now) && <NewBadge />}+ </span>+ <span className="line-clamp-2 text-[12px] leading-[1.35] text-muted-foreground md:max-lg:hidden">{e.what}</span>+ </span>+ </IntentLink>+ );+}++function Row({ e, col, row, current, now }: { e: NavEntry; col: number; row: number; current: boolean; now: number }) {+ return (+ <IntentLink+ href={e.href}+ data-col={col}+ data-row={row}+ aria-current={current ? "page" : undefined}+ title={e.label}+ className={cn(+ "flex min-h-11 items-center gap-2.5 rounded-[10px] px-2 py-1.5 hover:bg-accent motion-safe:transition-colors motion-reduce:transition-none md:max-lg:min-h-9 md:max-lg:px-1.5",+ current && "bg-brand-faint",+ LINK_FOCUS,+ )}+ >+ {/* Six columns leave a row its name and line below 1440 px, and its name alone below 1280 px. */}+ <CoverThumb id={e.cover} size="row" icon={e.icon} eager className="max-[1439.98px]:hidden" />+ <span className="flex min-w-0 flex-col">+ <span className="flex min-w-0 items-center gap-1.5">+ <span className={cn("truncate text-[13px] leading-snug font-medium max-xl:line-clamp-2 max-xl:whitespace-normal", current && "font-semibold")}>{e.label}</span>+ {isNew(e, now) && <NewBadge />}+ </span>+ <span className="line-clamp-2 text-[11.5px] leading-snug text-muted-foreground max-xl:hidden">{e.what}</span>+ </span>+ </IntentLink>+ );+}++/**+ * The launcher's columns as links (no behaviour): one per group, its label, the lead card and the rest. `current`: the+ * open page's entry id. `now`: the clock for the "New" badges.+ */+export function LauncherColumns({ kind, current, now }: { kind: ViewerKind | undefined; current?: string; now: number }) {+ const ids = useId();+ return (+ <div className="grid grid-cols-6 gap-4 2xl:gap-6">+ {launcherColumns(kind).map((c, ci) => (+ <div key={c.group.id} data-group={c.group.id} className="flex min-w-0 flex-col gap-2">+ <p id={`${ids}-${c.group.id}`} className="px-0.5 text-[11px] leading-4 font-semibold tracking-[.08em] text-brand-text uppercase">+ {c.group.label}+ </p>+ <ul aria-labelledby={`${ids}-${c.group.id}`} className="flex flex-col gap-0.5">+ <li className="pb-1.5">+ <LeadCard e={c.lead} col={ci} current={current === c.lead.id} now={now} />+ </li>+ {c.rest.map((e, ri) => (+ <li key={e.id}>+ <Row e={e} col={ci} row={ri + 1} current={current === e.id} now={now} />+ </li>+ ))}+ </ul>+ </div>+ ))}+ </div>+ );+}++/** The panel's body once it is shown or warmed: it reads the path (client only: the panel never renders on the server). */+export function LauncherPanel({ onClose, onSearch }: { onClose: () => void; onSearch: () => void }) {+ const kind = useViewerKind();+ const pathname = usePathname();+ const [now] = useState(() => Date.now());+ // A new page (a link here, back, a notification) closes it.+ const shownAt = useRef(pathname);+ useEffect(() => {+ if (shownAt.current === pathname) return;+ shownAt.current = pathname;+ onClose();+ }, [pathname, onClose]);+ return (+ <div className="mx-auto max-w-[1440px] px-6 pt-5 pb-6 lg:px-10 lg:pt-6 lg:pb-7">+ <div className="flex items-center gap-3.5 pb-4">+ <p className="text-[13px] text-muted-foreground">{studioCount()} studios, grouped by what you want to make</p>+ <span className="flex-1" />+ <button+ type="button"+ onClick={onSearch}+ aria-keyshortcuts="/"+ className={cn("inline-flex h-9 items-center gap-2 rounded-[10px] px-2.5 text-[13px] font-medium text-brand-text hover:bg-brand-faint", LINK_FOCUS)}+ >+ <Search aria-hidden className="size-4" />+ Search all apps, effects and tools+ <Kbd aria-hidden className="[@media(hover:none)]:hidden">+ /+ </Kbd>+ </button>+ </div>+ <LauncherColumns kind={kind} current={launcherCurrent(pathname)} now={now} />+ </div>+ );+}++/**+ * The bar's Studios button and its panel. The panel hangs from the bar (the header is its positioned parent) and spans+ * it. It is mounted, hidden, the first time the pointer or focus comes to the button, so its covers are loading before+ * the click. `className`: the bar's item look; `active`: a studio's page is open.+ */+export function StudiosLauncher({ className, active }: { className?: string; active?: boolean }) {+ const { launcherOpen: open, setLauncherOpen, launcherGroup, launcherReturnTo } = useNavUi();+ const search = useSearchPalette();+ const [warm, setWarm] = useState(false);+ const shown = warm || open;+ const root = useRef<HTMLDivElement>(null);+ const trigger = useRef<HTMLButtonElement>(null);+ const panel = useRef<HTMLElement>(null);+ // Opened with this button: it takes focus to the first lead card. Opened from elsewhere (an "All studios" button,+ // openStudios): focus goes to the lead card of the group asked for.+ const byButton = useRef(false);++ const close = useCallback(+ (returnFocus: boolean) => {+ const back = launcherReturnTo();+ setLauncherOpen(false);+ if (returnFocus) (back?.isConnected ? back : trigger.current)?.focus();+ },+ [launcherReturnTo, setLauncherOpen],+ );+ const closeQuietly = useCallback(() => close(false), [close]);++ useEffect(() => {+ if (!open) return;+ // Opened: the routes one click here leads to start loading.+ warmNav("studios");+ const col = byButton.current ? 0 : Math.max(0, launcherColumns(undefined).findIndex((c) => c.group.id === (launcherGroup ?? "film")));+ byButton.current = false;+ panel.current?.querySelector<HTMLElement>(`[data-col="${col}"][data-row="0"]`)?.focus();+ }, [open, launcherGroup]);++ // While open: a press outside closes it (the press goes on to what it was on), and Esc closes it from anywhere.+ useEffect(() => {+ if (!open) return;+ const down = (e: PointerEvent) => {+ if (!root.current?.contains(e.target as Node)) close(false);+ };+ const key = (e: KeyboardEvent) => {+ if (e.key !== "Escape" || e.defaultPrevented) return;+ e.preventDefault();+ close(true);+ };+ document.addEventListener("pointerdown", down, true);+ document.addEventListener("keydown", key);+ return () => {+ document.removeEventListener("pointerdown", down, true);+ document.removeEventListener("keydown", key);+ };+ }, [open, close]);++ const toggle = () => {+ if (open) return close(false);+ byButton.current = true;+ setWarm(true);+ setLauncherOpen(true);+ };++ const onPanelKey = (e: React.KeyboardEvent) => {+ const at = (e.target as HTMLElement).closest<HTMLElement>("[data-col]");+ if (!at || !panel.current) return;+ const lengths = [...panel.current.querySelectorAll("[data-group]")].map((g) => g.querySelectorAll("[data-col]").length);+ const next = launcherMove(lengths, { col: Number(at.dataset.col), row: Number(at.dataset.row) }, e.key);+ if (/^(Arrow|Home$|End$)/.test(e.key)) e.preventDefault();+ if (next) panel.current.querySelector<HTMLElement>(`[data-col="${next.col}"][data-row="${next.row}"]`)?.focus();+ };++ return (+ <div+ ref={root}+ className="contents"+ onBlur={(e) => {+ // Focus went somewhere else on the page (Tab past the last link, a click on a field): close. Focus lost to+ // nothing (a press on the panel's padding) keeps it open; a press outside closes it above.+ const to = e.relatedTarget as Node | null;+ if (open && to && !root.current?.contains(to)) close(false);+ }}+ >+ <button+ ref={trigger}+ type="button"+ aria-expanded={open}+ // The panel is on the page once warmed (hover, focus) or open.+ aria-controls={shown ? LAUNCHER_ID : undefined}+ data-studios-trigger+ data-active={active || undefined}+ data-state={open ? "open" : "closed"}+ className={className}+ onPointerEnter={() => setWarm(true)}+ onFocus={() => setWarm(true)}+ // Click, Enter and Space open it with focus on the first lead card (arrow keys and Tab go on from there).+ onClick={toggle}+ onKeyDown={(e) => {+ if (e.key !== "ArrowDown" || open) return;+ e.preventDefault();+ toggle();+ }}+ >+ Studios+ <span className="rounded-full bg-brand-faint px-1.5 py-px text-[11px] leading-4 font-semibold text-brand-text tabular-nums">{studioCount()}</span>+ <ChevronDown aria-hidden className="size-3.5 text-muted-foreground group-data-[state=open]/bar-item:rotate-180 motion-safe:transition-transform" />+ </button>+ {shown && (+ <section+ ref={panel}+ id={LAUNCHER_ID}+ aria-label="All studios"+ hidden={!open}+ onKeyDown={onPanelKey}+ onClick={(e) => {+ if ((e.target as Element).closest("a[href]")) close(false);+ }}+ className={LAUNCHER_PANEL}+ >+ <LauncherPanel+ onClose={closeQuietly}+ onSearch={() => {+ // Studios gets focus first, so it is where Esc in the search comes back to (the panel is gone by then).+ close(true);+ search.open();+ }}+ />+ </section>+ )}+ </div>+ );+}++/** Dims the page under the open launcher (decoration: presses go through to the page, which closes the launcher). */+export function LauncherScrim() {+ const { launcherOpen } = useNavUi();+ if (!launcherOpen) return null;+ return (+ <div+ aria-hidden+ className="pointer-events-none fixed inset-x-0 top-14 bottom-0 z-[39] hidden bg-overlay md:block motion-safe:animate-in motion-safe:fade-in-0 motion-safe:duration-150 print:hidden"+ />+ );+}diff --git a/src/components/nav/studios-sheet.tsx b/src/components/nav/studios-sheet.tsxnew file mode 100644index 00000000..d786c68c--- /dev/null+++ b/src/components/nav/studios-sheet.tsx@@ -0,0 +1,109 @@+"use client";++import { usePathname } from "next/navigation";+import { useState } from "react";+import { CircleUserRound, House, Library, Search } from "lucide-react";+import { CoverThumb } from "@/components/nav/cover-thumb";+import { useNavUi, useViewerKind } from "@/components/nav/nav-ui";+import { IntentLink } from "@/components/intent-link";+import { isNew, LAUNCHER_GROUPS, launcherActive, launcherEntries, type LauncherGroupId, type NavEntry } from "@/lib/nav-model";+import { cn } from "@/lib/utils";++/** A goal chip: 32 px to look at, 44 px to tap (the row's padding holds the larger hit area). */+const CHIP =+ "relative h-8 min-w-11 shrink-0 rounded-full border border-border bg-secondary px-[7px] text-[12px] font-medium text-secondary-foreground outline-none after:absolute after:inset-x-0 after:-inset-y-1.5 after:content-[''] focus-visible:ring-2 focus-visible:ring-ring aria-pressed:border-transparent aria-pressed:bg-foreground aria-pressed:text-background motion-safe:transition-colors";++function Tile({ entry, current }: { entry: NavEntry; current: boolean }) {+ const fresh = isNew(entry);+ return (+ <li className="min-w-0">+ <IntentLink+ href={entry.href}+ aria-current={current ? "page" : undefined}+ className="group/tile flex flex-col items-center gap-1 rounded-[16px] px-0.5 pt-0.5 pb-0.5 text-center outline-none [-webkit-tap-highlight-color:transparent] focus-visible:ring-2 focus-visible:ring-ring"+ >+ <span className="relative">+ <CoverThumb+ id={entry.cover}+ icon={entry.icon}+ size="tile"+ eager+ className="size-13 group-aria-[current=page]/tile:ring-2 group-aria-[current=page]/tile:ring-primary group-aria-[current=page]/tile:ring-offset-2 group-aria-[current=page]/tile:ring-offset-popover"+ />+ {fresh && (+ <span aria-hidden className="absolute -top-1 -right-1.5 rounded-full bg-highlight px-1 py-px text-[9px] leading-none font-semibold text-highlight-foreground">+ New+ </span>+ )}+ </span>+ <span aria-hidden className="line-clamp-2 text-[11px] leading-[1.2] text-foreground/85 group-aria-[current=page]/tile:font-semibold group-aria-[current=page]/tile:text-foreground">+ {entry.short ?? entry.label}+ </span>+ <span className="sr-only">+ {entry.label}+ {fresh ? ", new" : ""}+ </span>+ </IntentLink>+ </li>+ );+}++const SHORTCUT =+ "flex h-11 min-w-0 items-center justify-center gap-1.5 rounded-xl bg-secondary px-2 text-[12.5px] font-medium text-secondary-foreground outline-none [-webkit-tap-highlight-color:transparent] focus-visible:ring-2 focus-visible:ring-ring";++/**+ * Where to go from a full-screen studio, which has no tab bar: Home, Library, You and Search, above the studios. Only+ * there (html[data-fullscreen-studio]); with the tab bar on screen these are its tabs.+ */+function Shortcuts({ onSearch }: { onSearch: () => void }) {+ const { setSheet } = useNavUi();+ return (+ <div className="hidden shrink-0 grid-cols-4 gap-2 px-4 [html[data-fullscreen-studio]_&]:grid">+ <IntentLink href="/" eager className={SHORTCUT}>+ <House className="size-4" aria-hidden /> Home+ </IntentLink>+ <IntentLink href="/library" eager className={SHORTCUT}>+ <Library className="size-4" aria-hidden /> Library+ </IntentLink>+ <button type="button" className={SHORTCUT} onClick={() => setSheet("you")}>+ <CircleUserRound className="size-4" aria-hidden /> You+ </button>+ <button type="button" className={SHORTCUT} onClick={onSearch}>+ <Search className="size-4" aria-hidden /> Search+ </button>+ </div>+ );+}++/**+ * The Studios sheet's body (the phone's launcher): every studio on one screen as cover tiles, grouped by what you want to+ * make, with chips that narrow it to one group. All of them fit a 390 x 844 phone without scrolling; a shorter screen+ * scrolls the grid inside the sheet, never the page. The frame, its title and its close button are PhoneSheets'.+ */+export function StudiosSheet({ group: initial, onSearch }: { group?: LauncherGroupId; onSearch: () => void }) {+ const kind = useViewerKind();+ const pathname = usePathname() ?? "";+ const [group, setGroup] = useState<LauncherGroupId | null>(initial ?? null);+ const tiles = launcherEntries(kind, group ?? undefined);+ const current = launcherActive(pathname);+ const chips: { id: LauncherGroupId | null; label: string }[] = [{ id: null, label: "All" }, ...LAUNCHER_GROUPS.map((g) => ({ id: g.id, label: g.chip }))];+ return (+ <>+ <Shortcuts onSearch={onSearch} />+ <div role="group" aria-label="Show the studios for one goal" className="flex shrink-0 gap-1 overflow-x-auto px-4 py-1.5 scrollbar-none">+ {chips.map((c) => (+ <button key={c.id ?? "all"} type="button" aria-pressed={group === c.id} className={CHIP} onClick={() => setGroup(c.id)}>+ {c.label}+ </button>+ ))}+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-4">+ <ul aria-label={group ? LAUNCHER_GROUPS.find((g) => g.id === group)?.label : "All studios"} className="grid grid-cols-5 gap-x-1 gap-y-1.5 pb-1">+ {tiles.map((e) => (+ <Tile key={e.id} entry={e} current={e.id === current} />+ ))}+ </ul>+ </div>+ </>+ );+}diff --git a/src/components/nav/top-bar.tsx b/src/components/nav/top-bar.tsxnew file mode 100644index 00000000..2fcb9221--- /dev/null+++ b/src/components/nav/top-bar.tsx@@ -0,0 +1,275 @@+"use client";++import { ChevronDown, MoreHorizontal, Plus, Search } from "lucide-react";+import { usePathname } from "next/navigation";+import { Suspense } from "react";+import { IntentLink } from "@/components/intent-link";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Kbd } from "@/components/ui/kbd";+import { NEW_CREATION_HREF } from "@/lib/nav";+import { activeEntry, entry, type NavEntry } from "@/lib/nav-model";+import { isPlainClick, useTappedTab } from "@/lib/use-tapped-tab";+import { cn } from "@/lib/utils";+import { CoverThumb, NavIcon } from "./cover-thumb";+import { CreateMenu, NAV_MENU_ITEM } from "./create-menu";+import { useViewerKind } from "./nav-ui";+import { useSearchPalette } from "./search-context";+import { BarPills } from "./status-chips";+import { NavPrefetcher, warmNav } from "./nav-prefetch";+import { LauncherScrim, StudiosLauncher } from "./studios-launcher";+import { ViewerSlot } from "./viewer-slot";++export { prefetchHrefs } from "./nav-prefetch";++/*+ * The top bar (md and up): the wordmark, Create, Studios (the launcher), Apps, Motions & effects, Canvas, Assist and+ * Library; search; New creation; who is looking. 56 px on every page. What doesn't fit moves into More, by CSS alone+ * (nothing is measured, so nothing moves after the first paint):+ * 1440 and up everything, search 280 px, a guest's Log in+ * 1280-1439 Canvas and Assist in More, search 200 px+ * 1024-1279 Apps and Motions & effects in More too+ * 768-1023 the same, search and New creation as icon buttons+ * Measured with the site's fonts for a guest, an account and the owner, a classic scrollbar's width to spare at every+ * width. Below md the phone tabs take over (phone-tabs.tsx).+ */++/** A bar item (link, menu button, the launcher's button). data-active: the page is one of its destinations. */+export const BAR_ITEM =+ "group/bar-item inline-flex h-10 shrink-0 [@media(pointer:coarse)]:h-11 items-center gap-1.5 rounded-[10px] px-2.5 text-[14px] whitespace-nowrap text-foreground/80 outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring motion-safe:transition-colors data-[active]:bg-accent data-[active]:font-semibold data-[active]:text-foreground aria-[current=page]:bg-accent aria-[current=page]:font-semibold aria-[current=page]:text-foreground data-[state=open]:bg-accent data-[state=open]:text-foreground min-[1440px]:px-3.5";++/** Which bar items hold the open page (Create for the create tools, Studios for a studio or one of its tools…). */+export function barActive(pathname: string): { create: boolean; studios: boolean; apps: boolean; motions: boolean; canvas: boolean; assist: boolean; library: boolean } {+ const e = pathname ? activeEntry(pathname, new URLSearchParams()) : undefined;+ return {+ create: e?.kind === "create",+ studios: e?.kind === "studio",+ apps: e?.id === "apps",+ motions: e?.id === "motions" || e?.id === "effects",+ canvas: e?.id === "canvas",+ assist: e?.id === "assist",+ library: e?.kind === "library",+ };+}++type Active = ReturnType<typeof barActive>;+const NONE: Active = barActive("");++function RichItem({ e, current }: { e: NavEntry; current: boolean }) {+ return (+ <DropdownMenuItem asChild className={cn("min-h-12 gap-3 rounded-lg px-2 py-1.5 data-[current]:bg-brand-faint", NAV_MENU_ITEM)}>+ <IntentLink href={e.href} aria-current={current ? "page" : undefined} data-current={current || undefined}>+ <CoverThumb id={e.cover} size="row" icon={e.icon} eager />+ <span className="flex min-w-0 flex-col">+ <span className={cn("text-[13.5px] leading-tight font-medium", current && "font-semibold")}>{e.label}</span>+ <span className="truncate text-[12px] leading-snug text-muted-foreground">{e.what}</span>+ </span>+ </IntentLink>+ </DropdownMenuItem>+ );+}++const pick = (ids: string[]) => ids.map((id) => entry(id)).filter((e): e is NavEntry => !!e);++/** The open page among the galleries and tools in a menu (the menu's content renders on the client only, when open). */+function useOn(): (e: NavEntry) => boolean {+ const pathname = usePathname();+ return (e) => pathname === e.href || pathname.startsWith(`${e.href}/`);+}++function MotionsItems() {+ const on = useOn();+ return pick(["motions", "effects"]).map((e) => <RichItem key={e.id} e={e} current={on(e)} />);+}++/** Motions & effects: the two preset galleries, with their covers. */+function MotionsMenu({ active }: { active: Active }) {+ return (+ <DropdownMenu modal={false} onOpenChange={(o) => o && warmNav("more")}>+ <DropdownMenuTrigger className={cn(BAR_ITEM, "hidden xl:inline-flex")} data-active={active.motions || undefined}>+ Motions & effects+ <ChevronDown aria-hidden className="size-3.5 text-muted-foreground group-data-[state=open]/bar-item:rotate-180 motion-safe:transition-transform" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" sideOffset={8} className="w-80 p-1.5">+ <MotionsItems />+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++function MoreItems() {+ const on = useOn();+ return (+ <>+ {pick(["apps", "motions", "effects"]).map((e) => (+ <div key={e.id} className="xl:hidden">+ <RichItem e={e} current={on(e)} />+ </div>+ ))}+ {pick(["canvas", "assist"]).map((e) => {+ return (+ <DropdownMenuItem key={e.id} asChild className={cn("min-h-12 gap-3 rounded-lg px-2 py-1.5 data-[current]:bg-brand-faint", NAV_MENU_ITEM)}>+ <IntentLink href={e.href} eager={e.eager} aria-current={on(e) ? "page" : undefined} data-current={on(e) || undefined}>+ <span className="grid h-[27px] w-9 shrink-0 place-items-center rounded-[6px] bg-muted">+ <NavIcon name={e.icon} className="size-4 text-muted-foreground" />+ </span>+ <span className="flex min-w-0 flex-col">+ <span className="text-[13.5px] leading-tight font-medium">{e.label}</span>+ <span className="truncate text-[12px] leading-snug text-muted-foreground">{e.what}</span>+ </span>+ </IntentLink>+ </DropdownMenuItem>+ );+ })}+ </>+ );+}++/** More: the bar's items that don't fit at this width (each hides here where the bar shows it). */+function MoreMenu({ active }: { active: Active }) {+ return (+ <DropdownMenu modal={false} onOpenChange={(o) => o && warmNav("more")}>+ <DropdownMenuTrigger+ // Marked when it holds the open page at this width: Canvas and Assist always; Apps, Motions and Effects below xl.+ className={cn(BAR_ITEM, "min-[1440px]:hidden max-xl:data-[narrow]:bg-accent max-xl:data-[narrow]:font-semibold max-xl:data-[narrow]:text-foreground")}+ data-active={active.canvas || active.assist || undefined}+ data-narrow={active.apps || active.motions || undefined}+ >+ <MoreHorizontal aria-hidden className="size-4" />+ More+ <ChevronDown aria-hidden className="size-3.5 text-muted-foreground group-data-[state=open]/bar-item:rotate-180 motion-safe:transition-transform" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" sideOffset={8} className="w-80 p-1.5">+ <MoreItems />+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++/**+ * The bar's links and menus, with the open page's item marked (`active`). `onTap`: a link was clicked, so it is marked+ * from the next frame on, before its page arrives.+ */+function BarLinks({ active, onTap }: { active: Active; onTap?: (href: string) => void }) {+ const cur = (on: boolean) => (on ? "page" : undefined);+ const tap = (href: string) => (e: React.MouseEvent) => isPlainClick(e) && onTap?.(href);+ return (+ <>+ <CreateMenu className={BAR_ITEM} active={active.create} />+ <StudiosLauncher className={BAR_ITEM} active={active.studios} />+ <IntentLink href="/apps" onClick={tap("/apps")} aria-current={cur(active.apps)} className={cn(BAR_ITEM, "hidden xl:inline-flex")}>+ Apps+ </IntentLink>+ <MotionsMenu active={active} />+ <IntentLink href="/canvas" onClick={tap("/canvas")} aria-current={cur(active.canvas)} className={cn(BAR_ITEM, "hidden min-[1440px]:inline-flex")}>+ Canvas+ </IntentLink>+ <IntentLink href="/assist" eager onClick={tap("/assist")} aria-current={cur(active.assist)} className={cn(BAR_ITEM, "hidden min-[1440px]:inline-flex")}>+ Assist+ </IntentLink>+ <IntentLink href="/library" eager onClick={tap("/library")} aria-current={cur(active.library)} className={BAR_ITEM}>+ Library+ </IntentLink>+ <MoreMenu active={active} />+ </>+ );+}++/** Reads the path (runtime data) inside Suspense, so the shell still prerenders; the fallback marks nothing. */+function ActiveBarLinks() {+ const pathname = usePathname();+ const [tapped, onTap] = useTappedTab<string>(pathname);+ return <BarLinks active={barActive(tapped ?? pathname)} onTap={onTap} />;+}++/** Search, styled as a field from lg (an icon button at md): opens the palette; hover or focus starts loading it. */+function SearchField() {+ const search = useSearchPalette();+ return (+ <button+ type="button"+ aria-haspopup="dialog"+ aria-keyshortcuts="/ Meta+K Control+K"+ onClick={() => search.open()}+ onPointerEnter={() => search.warm()}+ onFocus={() => search.warm()}+ className={cn(+ "inline-flex h-10 shrink-0 items-center gap-2 rounded-[10px] text-[13.5px] [@media(pointer:coarse)]:h-11 text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring motion-safe:transition-colors",+ "w-10 justify-center hover:bg-accent hover:text-foreground [@media(pointer:coarse)]:w-11",+ "lg:max-[1439.98px]:w-[200px] lg:justify-start lg:border lg:border-input lg:bg-background/60 lg:px-3 lg:hover:border-border-strong lg:hover:bg-background min-[1440px]:w-[280px]",+ )}+ >+ <Search aria-hidden className="size-[18px] shrink-0 lg:size-4" />+ {/* Its name is the words it shows: "Search Fuobe" to 1439 px, the longer line from 1440 (sr-only below lg). */}+ <span className="sr-only min-w-0 flex-1 truncate text-left lg:not-sr-only">+ <span className="min-[1440px]:hidden">Search Fuobe</span>+ <span className="hidden min-[1440px]:inline">Search studios, apps, effects…</span>+ </span>+ <Kbd aria-hidden className="hidden lg:inline-flex [@media(hover:none)]:hidden">+ /+ </Kbd>+ </button>+ );+}++/**+ * New creation: Home with a fresh composer. Text from lg; an icon with its name for screen readers at md. Filled for an+ * account or the owner; an outline for a guest (html[data-viewer], set before the first paint), whose one filled button+ * is Sign up.+ */+function NewCreation() {+ return (+ <IntentLink+ href={NEW_CREATION_HREF}+ eager+ className="inline-flex h-10 shrink-0 items-center justify-center gap-1.5 rounded-full border border-border-strong px-2.5 text-[14px] font-semibold whitespace-nowrap text-foreground outline-none hover:bg-accent focus-visible:ring-2 [@media(pointer:coarse)]:h-11 [html[data-viewer]:not([data-viewer=guest])_&]:border-transparent [html[data-viewer]:not([data-viewer=guest])_&]:bg-primary [html[data-viewer]:not([data-viewer=guest])_&]:text-primary-foreground [html[data-viewer]:not([data-viewer=guest])_&]:hover:bg-primary/90 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar motion-safe:transition-colors lg:pr-4 lg:pl-3"+ >+ <Plus aria-hidden className="size-[18px]" />+ <span className="sr-only lg:not-sr-only">New creation</span>+ </IntentLink>+ );+}++/** The right-hand cluster's live parts read who is looking once (one subscription for the pills and the avatar). */+function RightCluster() {+ const kind = useViewerKind();+ return (+ <>+ <BarPills kind={kind} />+ <SearchField />+ <NewCreation />+ <ViewerSlot />+ </>+ );+}++/** The bar. Hidden below md and in print; same height on every page, full-screen studios included. */+export function TopBar() {+ return (+ <>+ <header+ data-top-bar+ className="sticky top-0 z-40 hidden h-14 items-center gap-1 border-b border-sidebar-border bg-sidebar/90 px-4 backdrop-blur-md md:flex lg:max-[1439.98px]:px-5 min-[1440px]:px-6 print:hidden"+ >+ <nav aria-label="Main" className="flex min-w-0 items-center gap-0.5">+ <IntentLink+ href="/"+ eager+ aria-label="Fuobe home"+ className="mr-1.5 inline-flex shrink-0 items-center self-stretch rounded-md px-1 font-heading text-[24px] leading-none outline-none focus-visible:ring-2 focus-visible:ring-ring lg:mr-3"+ >+ Fuobe+ </IntentLink>+ <Suspense fallback={<BarLinks active={NONE} />}>+ <ActiveBarLinks />+ </Suspense>+ </nav>+ <span className="min-w-2 flex-1" />+ <div className="flex shrink-0 items-center gap-2">+ <RightCluster />+ </div>+ </header>+ <LauncherScrim />+ <NavPrefetcher />+ </>+ );+}diff --git a/src/components/nav/viewer-slot.tsx b/src/components/nav/viewer-slot.tsxnew file mode 100644index 00000000..ce4585c9--- /dev/null+++ b/src/components/nav/viewer-slot.tsx@@ -0,0 +1,86 @@+"use client";++import { usePathname, useSearchParams } from "next/navigation";+import { Suspense, useEffect } from "react";+import { signInHref, VIEWER_KEY } from "@/lib/api";+import type { ViewerKind } from "@/lib/nav-model";+import { cn } from "@/lib/utils";+import { AccountMenu } from "./account-menu";+import { useViewerKind } from "./nav-ui";++/*+ * The bar's right end: who is looking. The server's shell is the same for everyone, so until the viewer is known it is+ * a placeholder as wide as what is coming: the room for Sign up (and Log in from 1440 px) by default, or the avatar's in a+ * browser an account or the owner used last (html[data-viewer], set before the first paint from localStorage). Then a+ * guest gets Sign up, Log in and a menu button; an account or the owner the avatar and its menu.+ */++/**+ * Fixed widths, so the placeholder and what replaces it take the same room: Log in 68 (from 1440 px), Sign up 84, the menu+ * button 36 (44 on a touch screen), 6 between.+ */+export const VIEWER_W = {+ guest: "w-[126px] min-[1440px]:w-[200px] [@media(pointer:coarse)]:w-[134px] [@media(pointer:coarse)]:min-[1440px]:w-[208px]",+ member: "w-9 [@media(pointer:coarse)]:w-11",+} as const;++const GUEST_BUTTON =+ "inline-flex h-9 shrink-0 items-center justify-center rounded-full text-[13.5px] [@media(pointer:coarse)]:h-11 font-medium whitespace-nowrap outline-none focus-visible:ring-2 focus-visible:ring-ring motion-safe:transition-colors";++function GuestButtons({ here }: { here: string }) {+ return (+ <>+ <a href={signInHref("login", here)} className={cn(GUEST_BUTTON, "hidden w-[68px] text-foreground/80 hover:bg-accent hover:text-foreground min-[1440px]:inline-flex")}>+ Log in+ </a>+ <a href={signInHref("signup", here)} className={cn(GUEST_BUTTON, "w-[84px] bg-primary font-semibold text-primary-foreground hover:bg-primary/90")}>+ Sign up+ </a>+ </>+ );+}++/** Sign up and Log in come back to this page with its query (a preset picked…): the query is runtime data. */+function GuestButtonsHere() {+ const pathname = usePathname();+ const search = useSearchParams().toString();+ return <GuestButtons here={search ? `${pathname}?${search}` : pathname} />;+}++/** Remembers who was looking, for the next page load's first paint (the pre-paint script reads it), and marks <html>. */+function useRememberViewer(kind: ViewerKind | undefined) {+ useEffect(() => {+ if (!kind) return;+ try {+ localStorage.setItem(VIEWER_KEY, kind);+ } catch {}+ document.documentElement.setAttribute("data-viewer", kind);+ }, [kind]);+}++export function ViewerSlot() {+ const kind = useViewerKind();+ useRememberViewer(kind);+ if (!kind)+ return (+ <span+ aria-hidden+ data-slot="viewer"+ className={cn("block h-9 shrink-0", VIEWER_W.guest, "[html[data-viewer='account']_&]:w-9 [html[data-viewer='owner']_&]:w-9 [@media(pointer:coarse)]:[html[data-viewer='account']_&]:w-11 [@media(pointer:coarse)]:[html[data-viewer='owner']_&]:w-11")}+ />+ );+ if (kind !== "guest")+ return (+ <span data-slot="viewer" className={cn("flex shrink-0", VIEWER_W.member)}>+ <AccountMenu kind={kind} />+ </span>+ );+ return (+ <span data-slot="viewer" className={cn("flex shrink-0 items-center justify-end gap-1.5", VIEWER_W.guest)}>+ <Suspense fallback={<GuestButtons here="/" />}>+ <GuestButtonsHere />+ </Suspense>+ <AccountMenu kind="guest" />+ </span>+ );+}diff --git a/src/components/page-shell.tsx b/src/components/page-shell.tsxindex ace1029b..e516581c 100644--- a/src/components/page-shell.tsx+++ b/src/components/page-shell.tsx@@ -4,7 +4,7 @@ import { cn } from "@/lib/utils";/** Scrollable page body for non-studio pages (galleries, settings, library). */export function PageShell({ children, wide }: { children: React.ReactNode; wide?: boolean }) {return (- <div className="flex min-h-svh min-w-0 flex-col">+ <div className="flex min-h-content min-w-0 flex-col"><PhoneBar /><div className={cn("mx-auto w-full min-w-0 flex-1 px-4 pt-4 pb-16 sm:px-8 md:pt-12", wide ? "max-w-[1400px]" : "max-w-[1200px]")}>{children}</div></div>diff --git a/src/components/phone-bar.tsx b/src/components/phone-bar.tsxindex c66baf6d..28d4defb 100644--- a/src/components/phone-bar.tsx+++ b/src/components/phone-bar.tsx@@ -2,30 +2,53 @@import { Search } from "lucide-react";import { IntentLink } from "@/components/intent-link";-import { useCommandPalette } from "@/components/command-palette";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";+import { useSearchPalette } from "@/components/nav/search-context";import { Button } from "@/components/ui/button";-import { SidebarTrigger } from "@/components/ui/sidebar";import { cn } from "@/lib/utils";-/** Opens the ⌘K palette: the way to search on a phone, where there's no keyboard shortcut. */+/** Opens the search: the way to search on a phone, where there's no keyboard shortcut. */export function SearchButton({ className }: { className?: string }) {- const palette = useCommandPalette();+ const search = useSearchPalette();return (- <Button variant="ghost" size="icon-sm" className={cn("text-muted-foreground", className)} aria-label="Search" aria-haspopup="dialog" onClick={() => palette.setOpen(true)}>- <Search />+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className={cn("size-11 rounded-full text-muted-foreground motion-reduce:transition-none", className)}+ aria-label="Search"+ aria-haspopup="dialog"+ onTouchStart={search.warm}+ onPointerEnter={search.warm}+ onFocus={search.warm}+ onClick={() => search.open()}+ >+ <Search className="size-5" aria-hidden /></Button>);}-/** The phone header of gallery and settings pages: the menu, the wordmark (home) and search. Hidden from md up, where the sidebar shows. */+/**+ * The phone header of gallery and settings pages: the wordmark (home) and search; the tab bar at the bottom does the+ * rest. Clear of the notch and the rounded corners. Hidden from md up, where the top bar shows.+ */export function PhoneBar({ className }: { className?: string }) {return (- <div className={cn("sticky top-0 z-20 flex h-12 items-center gap-1.5 bg-background/85 px-3 backdrop-blur md:hidden", className)}>- <SidebarTrigger />- <IntentLink href="/" eager className="rounded-md px-1 font-heading text-[20px] leading-none outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <div+ className={cn(+ "sticky top-chrome z-20 flex h-[calc(3rem+env(safe-area-inset-top))] items-center gap-1.5 bg-background/85 pt-[env(safe-area-inset-top)] pr-[max(0.25rem,env(safe-area-inset-right))] pl-[max(0.75rem,env(safe-area-inset-left))] backdrop-blur md:hidden",+ className,+ )}+ >+ <IntentLink+ href="/"+ eager+ aria-label="Fuobe home"+ className="rounded-md px-1 font-heading text-[22px] leading-none outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >Fuobe</IntentLink>- <SearchButton className="ml-auto" />+ <PhoneNavButton className="ml-auto" /></div>);}diff --git a/src/components/photodump/photodump-view.tsx b/src/components/photodump/photodump-view.tsxindex e5882cbc..38c2e401 100644--- a/src/components/photodump/photodump-view.tsx+++ b/src/components/photodump/photodump-view.tsx@@ -292,7 +292,7 @@ export function PhotodumpView() {})}</div>{!shown.length && <p className="py-10 text-center text-[14px] text-muted-foreground">{tab === "mine" && !needle ? (visitor ? "Saving packs of your own isn't available here." : "No packs of your own yet — create one from your reference photos.") : `No packs match “${q}”`}</p>}- <div className="sticky bottom-3 z-10 flex items-center justify-between gap-3 rounded-2xl border bg-background/95 p-3 shadow-normal backdrop-blur">+ <div className="sticky bottom-[calc(var(--chrome-bottom)+0.75rem)] z-10 flex items-center justify-between gap-3 rounded-2xl border bg-background/95 p-3 shadow-normal backdrop-blur"><p className="min-w-0 truncate text-[13px]">{pack ? <><span className="font-medium">{pack.name}</span> · {pack.count} photos</> : <span className="text-muted-foreground">Pick a pack to continue</span>}</p><Button disabled={!pack} onClick={() => go(1)}>Use this pack <ArrowRight />@@ -357,7 +357,7 @@ export function PhotodumpView() {</div>)}</div>- <aside className="space-y-5 rounded-2xl border p-4 lg:sticky lg:top-6 lg:self-start">+ <aside className="space-y-5 rounded-2xl border p-4 lg:sticky lg:top-[calc(var(--chrome-top)+1.5rem)] lg:self-start"><div className="flex items-center gap-3"><PackCover id={pack.id} name={pack.name} count={pack.count} refs={pack.refs} hue={pack.hue} tone={pack.tone} bare className="size-14 shrink-0 rounded-lg" /><div className="min-w-0">diff --git a/src/components/relight/relight-tool.tsx b/src/components/relight/relight-tool.tsxindex 2c7f241b..6d3388e9 100644--- a/src/components/relight/relight-tool.tsx+++ b/src/components/relight/relight-tool.tsx@@ -641,7 +641,7 @@ export function RelightTool({ app }: { app?: { name: string; description: string<p className="mt-1 hidden max-w-2xl text-[13px] text-pretty text-muted-foreground sm:block">{SUB}</p></div><div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_380px] lg:items-start">- <div className="space-y-2 max-lg:sticky max-lg:top-14 max-lg:z-10 max-lg:-mx-3 max-lg:bg-background/95 max-lg:px-3 max-lg:pb-2 max-lg:backdrop-blur lg:sticky lg:top-20">+ <div className="space-y-2 max-lg:sticky max-lg:top-[calc(var(--chrome-top)+3.5rem)] max-lg:z-10 max-lg:-mx-3 max-lg:bg-background/95 max-lg:px-3 max-lg:pb-2 max-lg:backdrop-blur lg:sticky lg:top-[calc(var(--chrome-top)+5rem)]"><div className="mx-auto w-full max-lg:max-w-[calc(40svh*var(--ar))]" style={{ "--ar": String(pw / Math.max(1, ph)) } as React.CSSProperties}><RelightStagephoto={img}diff --git a/src/components/remove-object/remove-object-tool.tsx b/src/components/remove-object/remove-object-tool.tsxindex 0ef7a8f8..3ae01fb9 100644--- a/src/components/remove-object/remove-object-tool.tsx+++ b/src/components/remove-object/remove-object-tool.tsx@@ -328,7 +328,7 @@ export function RemoveObjectTool() {</div></div>- <Panel className="space-y-4 lg:sticky lg:top-[112px]">+ <Panel className="space-y-4 lg:sticky lg:top-[calc(var(--chrome-top)+112px)]"><Field label="How do you point at it?"><Segmentedlabel="How do you point at it?"diff --git a/src/components/restore/restore-tool.tsx b/src/components/restore/restore-tool.tsxindex 1f811931..c37146a0 100644--- a/src/components/restore/restore-tool.tsx+++ b/src/components/restore/restore-tool.tsx@@ -221,7 +221,7 @@ export function RestoreTool() {)}</div>- <Panel className="space-y-4 lg:sticky lg:top-[112px]">+ <Panel className="space-y-4 lg:sticky lg:top-[calc(var(--chrome-top)+112px)]"><p className="flex gap-2 rounded-lg bg-muted/60 px-3 py-2 text-[12px] leading-snug text-muted-foreground"><Cpu className="mt-0.5 size-3.5 shrink-0" aria-hidden /><span>{open ? GPU_NOTE : CLOUD_NOTE}</span>diff --git a/src/components/self-host-note.tsx b/src/components/self-host-note.tsxindex 584f7ef0..21c79342 100644--- a/src/components/self-host-note.tsx+++ b/src/components/self-host-note.tsx@@ -6,7 +6,7 @@ const studio = "font-medium text-foreground underline underline-offset-4";/*** A tool or a save that guests and accounts can't use: says so up front, with the studios they can use, instead of a* form the server refuses.- * Hidden in a browser the owner used last (`<html data-viewer="owner">`, src/components/app-sidebar.tsx), where a page+ * Hidden in a browser the owner used last (`<html data-viewer="owner">`, set before paint by CHROME_STATE_SCRIPT in src/lib/nav.ts), where a page* that shows it until the viewer is known (useLikelyVisitor) would otherwise draw it and take it away.*/export function SelfHostNote({ children, className }: { children?: React.ReactNode; className?: string }) {diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsxindex 0854031a..ea0b2174 100644--- a/src/components/settings-form.tsx+++ b/src/components/settings-form.tsx@@ -164,7 +164,7 @@ function ChoiceField({function StatusStrip({ status, onGuide, guideOpen }: { status?: StatusInfo; onGuide: () => void; guideOpen: boolean }) {const place = usePagePlace();return (- <div className="sticky top-12 z-10 -mx-4 border-b bg-background/90 px-4 py-2.5 backdrop-blur sm:-mx-8 sm:px-8 md:top-0">+ <div className="sticky top-12 z-10 -mx-4 border-b bg-background/90 px-4 py-2.5 backdrop-blur sm:-mx-8 sm:px-8 md:top-chrome"><nav aria-label="Connections" className="scrollbar-none -my-1 flex items-center gap-1.5 overflow-x-auto py-1">{status ? (<>@@ -741,7 +741,7 @@ export function SettingsForm({ prices }: { prices?: string }) {<span className="min-w-0 space-y-1"><span className="block text-[14px] font-medium">{PLACEHOLDER_SETTING}</span><span className="block text-[13px] leading-relaxed text-muted-foreground">- While it’s on, every run makes a placeholder labelled “Placeholder”, even with keys or ComfyUI connected, and the sidebar says+ While it’s on, every run makes a placeholder labelled “Placeholder”, even with keys or ComfyUI connected, and the top bar says“Placeholders on”. While it’s off, a run with nothing connected asks you to connect ComfyUI or add a key.</span></span>diff --git a/src/components/shorts/session-view.tsx b/src/components/shorts/session-view.tsxindex 36343143..99207f1b 100644--- a/src/components/shorts/session-view.tsx+++ b/src/components/shorts/session-view.tsx@@ -16,7 +16,7 @@ import {AlertDialogHeader,AlertDialogTitle,} from "@/components/ui/alert-dialog";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { MediaThumb } from "@/components/studio/result-media";@@ -78,14 +78,14 @@ export function ShortsSessionView({ id }: { id: string }) {function Frame({ title, children, actions }: { title: string; children: React.ReactNode; actions?: React.ReactNode }) {return (- <div className="flex min-h-svh min-w-0 flex-col">- <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <div className="flex min-h-content min-w-0 flex-col">+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6"><Link href="/shorts?tab=history" aria-label="Back to your shorts" className="grid size-8 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground"><ArrowLeft className="size-4" /></Link><h1 className="min-w-0 truncate font-heading text-[22px] leading-none">{title}</h1><div className="ml-auto flex items-center gap-1">{actions}</div>+ <PhoneNavButton /></header><div className="mx-auto w-full max-w-[1180px] min-w-0 flex-1 px-3 pb-16 sm:px-6">{children}</div></div>@@ -146,7 +146,7 @@ function Session({ s }: { s: View }) {><Steps steps={STEPS} current={finalVideo && !outdated ? 3 : 2} className="pt-6" /><div className="mt-6 grid min-w-0 gap-8 lg:grid-cols-[minmax(0,380px)_minmax(0,1fr)] lg:items-start">- <section aria-label="Full video" className="min-w-0 space-y-3 lg:sticky lg:top-16">+ <section aria-label="Full video" className="min-w-0 space-y-3 lg:sticky lg:top-[calc(var(--chrome-top)+4rem)]"><div className="relative mx-auto max-h-[72svh] w-full overflow-hidden rounded-2xl bg-muted" style={{ aspectRatio: ratio, maxWidth: ratio < 1 ? 360 : undefined }}>{finalVideo ? (<video src={finalVideo.url} controls playsInline preload="metadata" className="size-full bg-black object-contain" aria-label="Your short" />diff --git a/src/components/shorts/shorts-studio.tsx b/src/components/shorts/shorts-studio.tsxindex e2e851e7..c3d5486a 100644--- a/src/components/shorts/shorts-studio.tsx+++ b/src/components/shorts/shorts-studio.tsx@@ -5,7 +5,7 @@ import { useRouter } from "next/navigation";import { useDeferredValue, useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { OldFootageOffer } from "@/components/restore/old-footage";import { SelfHostNote } from "@/components/self-host-note";import { EngineSwitch } from "@/components/studio/engine-switch";@@ -82,9 +82,8 @@ export function ShortsStudio({ models }: { models: Record<Engine, ModelChoice[]>};return (- <div className="flex min-h-svh min-w-0 flex-col">- <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <div className="flex min-h-content min-w-0 flex-col">+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6"><h1 className="min-w-0 truncate font-heading text-[22px] leading-none">Shorts Studio</h1><div role="tablist" aria-label="Shorts Studio" onKeyDown={tabKeys} className="ml-2 flex h-8 shrink-0 items-center rounded-full bg-muted p-0.5 sm:ml-4">{(["presets", "history"] as const).map((t) => (@@ -105,6 +104,7 @@ export function ShortsStudio({ models }: { models: Record<Engine, ModelChoice[]>{/* A phone's header has room for the title and the tabs, not "Add key" too. */}<EngineSwitch value={engine} onChange={setEngine} wordless selfHostedOnly /></div>+ <PhoneNavButton /></header><div className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 px-3 pb-28 sm:px-6 lg:pb-16">{tab === "history" ? (@@ -187,7 +187,7 @@ function Workspace({onEdit={(id) => setDialog({ open: true, preset: custom.data?.find((p) => p.id === id) })}/></section>- <aside ref={setup} id="shorts-setup" aria-labelledby="shorts-step-2" className="scrollbar-none min-w-0 scroll-mt-16 lg:sticky lg:top-16 lg:max-h-[calc(100svh-4.5rem)] lg:overflow-y-auto lg:overscroll-contain lg:rounded-2xl">+ <aside ref={setup} id="shorts-setup" aria-labelledby="shorts-step-2" className="scrollbar-none min-w-0 scroll-mt-16 lg:sticky lg:top-[calc(var(--chrome-top)+4rem)] lg:max-h-[calc(var(--content-h)-4.5rem)] lg:overflow-y-auto lg:overscroll-contain lg:rounded-2xl"><SetupPanelvisitor={visitor}engine={engine}@@ -202,7 +202,7 @@ function Workspace({/></aside>{selectedName && !setupVisible && (- <div className="fixed inset-x-3 bottom-[max(0.75rem,env(safe-area-inset-bottom))] z-30 lg:hidden">+ <div className="fixed inset-x-3 bottom-[max(calc(var(--chrome-bottom)+0.75rem),env(safe-area-inset-bottom))] z-30 lg:hidden"><buttontype="button"onClick={() => setup.current?.scrollIntoView({ behavior: "smooth", block: "start" })}diff --git a/src/components/skeletons.tsx b/src/components/skeletons.tsxindex b168dd4c..d9afe2a2 100644--- a/src/components/skeletons.tsx+++ b/src/components/skeletons.tsx@@ -3,14 +3,14 @@ import { PageHeader, PageShell } from "@/components/page-shell";/** Route skeletons (loading.tsx). Server components with no data: they are part of each route's- * prefetched shell, so a click in the sidebar paints the next page's frame immediately.+ * prefetched shell, so a click in the menus paints the next page's frame immediately.*//** A studio: sticky title bar, hero line, the pill composer. */export function StudioSkeleton() {return (- <div className="flex min-h-svh min-w-0 flex-col" aria-busy="true" aria-label="Loading">- <div className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 sm:px-6">+ <div className="flex min-h-content min-w-0 flex-col" aria-busy="true" aria-label="Loading">+ <div className="sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-3 sm:px-6"><Skeleton className="h-6 w-32 rounded-lg" /><Skeleton className="ml-auto h-9 w-44 rounded-full" /></div>diff --git a/src/components/storyboard-view.tsx b/src/components/storyboard-view.tsxindex aed69878..ce9cebf4 100644--- a/src/components/storyboard-view.tsx+++ b/src/components/storyboard-view.tsx@@ -8,7 +8,7 @@ import { useMemo, useState, useSyncExternalStore } from "react";import { nanoid } from "nanoid";import { toast } from "sonner";import { Button } from "@/components/ui/button";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { Skeleton } from "@/components/ui/skeleton";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { useDebounced } from "@/components/faceless/hooks";@@ -407,13 +407,13 @@ export function StoryboardView({ modelNames = {} }: { /** Display names of the s};return (- <div className="flex min-h-svh min-w-0 flex-col">- <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">- <SidebarTrigger className="md:hidden" />+ <div className="flex min-h-content min-w-0 flex-col">+ <header className="sticky top-chrome z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6"><h1 className="min-w-0 truncate font-heading text-[22px] leading-none">Storyboard</h1><div className="ml-auto"><EngineSwitch value={engine} onChange={setEngine} /></div>+ <PhoneNavButton /></header><div className="mx-auto w-full min-w-0 max-w-[1240px] flex-1 space-y-10 px-3 pb-16 sm:px-6"><div className="mx-auto max-w-[820px] pt-6 text-center">diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsxindex 5a587f28..34506871 100644--- a/src/components/studio/feed.tsx+++ b/src/components/studio/feed.tsx@@ -5,7 +5,6 @@ import { lineWords } from "@/lib/hosted";import { openGpuSetup } from "@/hooks/use-gpu";import { useLocalJob } from "@/components/gpu/computer-runner";import { jobFraction, jobWords } from "@/lib/relay";-import Link from "next/link";import { createContext, memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import {@@ -17,19 +16,20 @@ import {} from "@/components/ui/dropdown-menu";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { OPERATION_LABELS, type Generation } from "@/lib/catalog/types";-import { useCreateGeneration, useEngineMode, useGenerationActions, useLikelyVisitor } from "@/lib/api";+import { useCreateGeneration, useGenerationActions } from "@/lib/api";import { useSoulFinish } from "./soul-finish";import { elapsed, formatCost, leftLabel, notePace, ratioValue, timeAgo, timeLeft } from "@/lib/format";import { downloadHref, downloadName, userTitle } from "@/lib/library";-import { isLayered, nextSteps, shownOutputs } from "@/lib/output-actions";+import { isLayered, shownOutputs } from "@/lib/output-actions";import { cn } from "@/lib/utils";import { copyWithToast } from "@/lib/clipboard";import { toastError } from "@/lib/refusals";-import { ACTION_ICONS, TileActions, useCanHover, type RunnerOptions } from "./result-actions";+import { TileActions, useCanHover, type RunnerOptions } from "./result-actions";import { LayersStack, MediaThumb } from "./result-media";import { useNow } from "./use-now";import { PlaceholderChip } from "@/components/demo-mode";import { Viewer } from "./viewer";+import { NextSteps } from "@/components/nav/next-steps";export { MediaThumb } from "./result-media";export { downloadName } from "@/lib/library";@@ -267,34 +267,6 @@ const OutputTile = memo(function OutputTile({ g, index, ratio, layered, count }:);});-/**- * Under the newest result: three next steps as chips (Animate, Upscale, Edit for a picture). A- * group with several takes has none: which one to animate is picked on its tile.- */-function NextSteps({ g, index }: { g: Generation; index: number }) {- const engineMode = useEngineMode();- const visitor = useLikelyVisitor();- const steps = nextSteps(g, index, 3, { engineMode, visitor });- if (!steps.length) return null;- return (- <nav aria-label="Next steps" className="flex flex-wrap gap-1.5">- {steps.map((a) => {- const Icon = ACTION_ICONS[a.id];- return (- <Link- key={a.id}- href={a.href!}- prefetch={false}- className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50"- >- <Icon className="size-3.5" /> {a.label}- </Link>- );- })}- </nav>- );-}-/** One request: the user's words in serif, a meta line, then its outputs (or progress / failure). */export const GenerationGroup = memo(function GenerationGroup({ g, newest }: { g: Generation; newest?: boolean }) {const feed = useFeed();@@ -424,7 +396,8 @@ export const GenerationGroup = memo(function GenerationGroup({ g, newest }: { g:shown.map((i) => <OutputTile key={g.outputs[i].url} g={g} index={i} ratio={ratio} count={shown.length} />)))}</div>- {newest && !layered && shown.length === 1 && <NextSteps g={g} index={shown[0]} />}+ {/* Under the newest result: where it can go next, with it attached. A group with several takes has none: which one to take on is picked on its tile. */}+ {newest && !layered && shown.length === 1 && <NextSteps g={g} index={shown[0]} variant="row" max={5} className="pt-1" />}</section>);});diff --git a/src/components/studio/hub-chrome.tsx b/src/components/studio/hub-chrome.tsxindex c5652324..bbb3b19a 100644--- a/src/components/studio/hub-chrome.tsx+++ b/src/components/studio/hub-chrome.tsx@@ -4,7 +4,7 @@ import Link, { useLinkStatus } from "next/link";import { usePathname, useRouter } from "next/navigation";import { createContext, Suspense, useCallback, useContext, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";import { createPortal } from "react-dom";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { EngineSwitch } from "@/components/studio/engine-switch";import { useEngine, useLikelyVisitor } from "@/lib/api";import { HUB_MODES, HUB_TITLE, hubOfPath, modeHref, modeOfPath, type HubKind } from "@/lib/hubs";@@ -129,7 +129,7 @@ function HubTabs({}, [active, ref]);// Every mode's whole page, also the ones scrolled out of the row, once the page is idle (a tab on screen already- // prefetches itself), ahead of the sidebar's routes: the "page" lane.+ // prefetches itself), ahead of the navigation's routes: the "page" lane.useIdlePrefetch(modes.map((m) => modeHref(kind, m.id)),"page",@@ -208,15 +208,15 @@ export function HubFrame({ kind, skeleton, children }: { kind: HubKind; skeleton// `waiting` ends before paint when the page arrives, so the skeleton never covers the new page.const skeletonShown = waiting && late;return (- <div className="flex min-h-svh min-w-0 flex-col" data-hub={kind}>- <div className="sticky top-0 z-20 bg-background/85 backdrop-blur" data-hub-chrome>+ <div className="flex min-h-content min-w-0 flex-col" data-hub={kind}>+ <div className="sticky top-chrome z-20 bg-background/85 backdrop-blur" data-hub-chrome><header className="flex h-14 items-center gap-2 px-3 sm:px-6">- <SidebarTrigger className="md:hidden" /><h1 className="min-w-0 truncate font-heading text-[22px] leading-[1.15]">{HUB_TITLE[kind]}</h1><div className="ml-auto flex shrink-0 items-center gap-2"><div ref={slotRef} className="contents" /><HubEngine kind={kind} mode={mode} /></div>+ <PhoneNavButton /></header><Suspense fallback={<HubTabs kind={kind} pathname={null} />}><PathTabs kind={kind} onActive={setMode} onWaiting={setWaiting} />diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsxindex 39b9494b..d2dff723 100644--- a/src/components/studio/studio-page.tsx+++ b/src/components/studio/studio-page.tsx@@ -7,7 +7,7 @@ import { useSearchParams } from "next/navigation";import { memo, Suspense, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";import { nanoid } from "nanoid";import { toast } from "sonner";-import { SidebarTrigger } from "@/components/ui/sidebar";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { HeaderPill } from "@/components/gpu/readiness-chip";import { badgeFor, openGpuSetup, useGpuBadges } from "@/hooks/use-gpu";import type { Generation, MediaKind, ModelDef, Preset } from "@/lib/catalog/types";@@ -310,7 +310,7 @@ function PromptSuggestions({ suggestions }: { suggestions: string[] }) {const model = catalog.getModel(draft.modelId);if (!promptShown(config.hidePrompt, preset?.userPrompt, model?.options.promptless)) return null;return (- <div className="mx-auto mt-4 flex max-w-[760px] flex-wrap justify-center gap-2 px-3 pb-10">+ <div className="mx-auto mt-4 flex w-full max-w-[760px] min-w-0 flex-wrap justify-center gap-2 px-3 pb-10">{suggestions.map((s) => (<buttonkey={s}@@ -427,15 +427,15 @@ function StudioHeader({ title, header, tabs }: { title: string; header?: React.R</HubHeaderExtras>);return (- <div className="sticky top-0 z-20 bg-background/85 backdrop-blur">+ <div className="sticky top-chrome z-20 bg-background/85 backdrop-blur"><header className="flex h-14 items-center gap-2 px-3 sm:px-6">- <SidebarTrigger className="md:hidden" /><h1 className="min-w-0 truncate font-heading text-[22px] leading-[1.15]">{title}</h1><div className="ml-auto flex shrink-0 items-center gap-2">{header}<StudioGpuPill /><EngineSwitch value={engine} onChange={setEngine} /></div>+ <PhoneNavButton /></header>{tabs}</div>@@ -478,7 +478,7 @@ function StudioBody({ header, tabs, examples }: { header?: React.ReactNode; tabsreturn (<divdata-studio- className={cn("relative flex min-w-0 flex-col", inHub ? "flex-1" : "min-h-svh")}+ className={cn("relative flex min-w-0 flex-col", inHub ? "flex-1" : "min-h-content")}onDragEnter={(e) => {if (![...e.dataTransfer.types].includes("Files")) return;dragDepth.current++;@@ -525,7 +525,7 @@ function StudioBody({ header, tabs, examples }: { header?: React.ReactNode; tabs{live && (<div className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 px-3 pb-4 sm:px-6">- <div className="h-[calc(100svh-4.5rem)] min-h-[520px]">+ <div className="h-[calc(var(--content-h)-4.5rem)] min-h-[520px]"><LiveArea onClose={() => setLive(false)} /></div></div>@@ -573,7 +573,7 @@ function StudioBody({ header, tabs, examples }: { header?: React.ReactNode; tabsclassName={cn(live && "hidden",hasItems- ? "sticky bottom-0 z-20 bg-gradient-to-t from-background via-background/95 to-transparent px-3 pt-8 pb-[max(1rem,env(safe-area-inset-bottom))] sm:px-6"+ ? "sticky bottom-chrome z-20 bg-gradient-to-t from-background via-background/95 to-transparent px-3 pt-8 pb-[max(1rem,env(safe-area-inset-bottom))] sm:px-6": "px-3 pt-6 sm:px-6 sm:pt-10",)}>diff --git a/src/components/studio/viewer.tsx b/src/components/studio/viewer.tsxindex 4779fc3f..d9b623c5 100644--- a/src/components/studio/viewer.tsx+++ b/src/components/studio/viewer.tsx@@ -21,6 +21,7 @@ import { ACTION_ICONS, downloadUrl, SaveElementForm, useActionRunner } from "./rimport { LayersStack, ModelViewer, TextReader, VideoFileCard } from "./result-media";import { ReviewSelect } from "@/components/library/review";import { PlaceholderChip } from "@/components/demo-mode";+import { NextSteps } from "@/components/nav/next-steps";/** One line of the details; `center` lines the label up with a control (the Review picker) instead of a text value's first line. */@@ -391,6 +392,8 @@ export function Viewer({</div><div className="flex-1 space-y-4 overflow-y-auto px-4 pb-4"><Details g={g} index={index} />+ {/* Where this result can go next, with it attached (a layer is a part: it goes on from the Layers editor). */}+ {!layered && <NextSteps g={g} index={index} variant="list" max={5} onNavigate={onClose} />}{layered && (<LayerListg={g}@@ -453,6 +456,8 @@ export function Viewer({<SheetDescription className="sr-only">Every action and the details of this result</SheetDescription></SheetHeader><div className="space-y-4 overflow-y-auto px-4">+ {/* The next steps first: on a phone this sheet is where they are. */}+ {!layered && <NextSteps g={g} index={index} variant="list" max={5} onNavigate={onClose} />}<div className="grid grid-cols-2 gap-2">{source && (<Button variant="secondary" size="sm" aria-pressed={comparing} onClick={() => (setComparing((v) => !v), setDrawer(false))}>diff --git a/src/components/thanks/thanks-list.tsx b/src/components/thanks/thanks-list.tsxindex 65a35743..a83f0024 100644--- a/src/components/thanks/thanks-list.tsx+++ b/src/components/thanks/thanks-list.tsx@@ -20,7 +20,7 @@ export function ThanksList({ groups }: { groups: ThanksGroup[] }) {return (<>- <div className="sticky top-12 z-10 -mx-4 border-b bg-background/90 px-4 py-2 backdrop-blur sm:-mx-8 sm:px-8 md:top-0">+ <div className="sticky top-12 z-10 -mx-4 border-b bg-background/90 px-4 py-2 backdrop-blur sm:-mx-8 sm:px-8 md:top-chrome"><div className="flex flex-col gap-2 lg:flex-row lg:items-center"><label className="relative block min-w-0 lg:w-80 lg:shrink-0"><span className="sr-only">Search models, LoRAs, node packs and libraries</span>diff --git a/src/components/ui/sidebar.tsx b/src/components/ui/sidebar.tsxdeleted file mode 100644index a6d4b23b..00000000--- a/src/components/ui/sidebar.tsx+++ /dev/null@@ -1,707 +0,0 @@-"use client"--import * as React from "react"-import { cva, type VariantProps } from "class-variance-authority"-import { cn } from "cn"-import { Slot } from "radix-ui"--import { useIsMobileAfterHydration } from "@/hooks/use-mobile"-import { Button } from "@/components/ui/button"-import { Input } from "@/components/ui/input"-import { Separator } from "@/components/ui/separator"-import {- Sheet,- SheetContent,- SheetDescription,- SheetHeader,- SheetTitle,-} from "@/components/ui/sheet"-import { Skeleton } from "@/components/ui/skeleton"-import {- Tooltip,- TooltipContent,- TooltipTrigger,-} from "@/components/ui/tooltip"-import { MenuIcon, PanelLeftIcon } from "lucide-react"--const SIDEBAR_COOKIE_NAME = "sidebar_state"-const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7-const SIDEBAR_WIDTH = "16rem"-const SIDEBAR_WIDTH_MOBILE = "18rem"-const SIDEBAR_WIDTH_ICON = "3rem"-const SIDEBAR_KEYBOARD_SHORTCUT = "b"--type SidebarContextProps = {- state: "expanded" | "collapsed"- open: boolean- setOpen: (open: boolean) => void- openMobile: boolean- setOpenMobile: (open: boolean) => void- isMobile: boolean- toggleSidebar: () => void-}--const SidebarContext = React.createContext<SidebarContextProps | null>(null)--function useSidebar() {- const context = React.useContext(SidebarContext)- if (!context) {- throw new Error("useSidebar must be used within a SidebarProvider.")- }-- return context-}--function SidebarProvider({- defaultOpen = true,- open: openProp,- onOpenChange: setOpenProp,- persistOpen = true,- className,- style,- children,- ...props-}: React.ComponentProps<"div"> & {- defaultOpen?: boolean- open?: boolean- onOpenChange?: (open: boolean) => void- /** Remember the expanded/collapsed choice in the cookie (off while a page decides it for itself). */- persistOpen?: boolean-}) {- const isMobile = useIsMobileAfterHydration()- const [openMobile, setOpenMobile] = React.useState(false)-- // This is the internal state of the sidebar.- // We use openProp and setOpenProp for control from outside the component.- const [_open, _setOpen] = React.useState(defaultOpen)- const open = openProp ?? _open- const setOpen = React.useCallback(- (value: boolean | ((value: boolean) => boolean)) => {- const openState = typeof value === "function" ? value(open) : value- if (setOpenProp) {- setOpenProp(openState)- } else {- _setOpen(openState)- }-- // This sets the cookie to keep the sidebar state.- if (persistOpen) document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`- },- [setOpenProp, open, persistOpen]- )-- // Helper to toggle the sidebar.- const toggleSidebar = React.useCallback(() => {- return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)- }, [isMobile, setOpen, setOpenMobile])-- // Adds a keyboard shortcut to toggle the sidebar.- React.useEffect(() => {- const handleKeyDown = (event: KeyboardEvent) => {- if (- event.key === SIDEBAR_KEYBOARD_SHORTCUT &&- (event.metaKey || event.ctrlKey)- ) {- event.preventDefault()- toggleSidebar()- }- }-- window.addEventListener("keydown", handleKeyDown)- return () => window.removeEventListener("keydown", handleKeyDown)- }, [toggleSidebar])-- // We add a state so that we can do data-state="expanded" or "collapsed".- // This makes it easier to style the sidebar with Tailwind classes.- const state = open ? "expanded" : "collapsed"-- const contextValue = React.useMemo<SidebarContextProps>(- () => ({- state,- open,- setOpen,- isMobile,- openMobile,- setOpenMobile,- toggleSidebar,- }),- [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]- )-- return (- <SidebarContext.Provider value={contextValue}>- <div- data-slot="sidebar-wrapper"- style={- {- "--sidebar-width": SIDEBAR_WIDTH,- "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,- ...style,- } as React.CSSProperties- }- className={cn(- "group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",- className- )}- {...props}- >- {children}- </div>- </SidebarContext.Provider>- )-}--function Sidebar({- side = "left",- variant = "sidebar",- collapsible = "offcanvas",- className,- children,- dir,- ...props-}: React.ComponentProps<"div"> & {- side?: "left" | "right"- variant?: "sidebar" | "floating" | "inset"- collapsible?: "offcanvas" | "icon" | "none"-}) {- const { isMobile, state, openMobile, setOpenMobile } = useSidebar()-- if (collapsible === "none") {- return (- <div- data-slot="sidebar"- className={cn(- "flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",- className- )}- {...props}- >- {children}- </div>- )- }-- if (isMobile) {- return (- <Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>- <SheetContent- dir={dir}- data-sidebar="sidebar"- data-slot="sidebar"- data-mobile="true"- className="w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"- style={- {- "--sidebar-width": SIDEBAR_WIDTH_MOBILE,- } as React.CSSProperties- }- side={side}- >- <SheetHeader className="sr-only">- <SheetTitle>Sidebar</SheetTitle>- <SheetDescription>Displays the mobile sidebar.</SheetDescription>- </SheetHeader>- <div className="flex h-full w-full flex-col">{children}</div>- </SheetContent>- </Sheet>- )- }-- return (- <div- className="group peer hidden text-sidebar-foreground md:block"- data-state={state}- data-collapsible={state === "collapsed" ? collapsible : ""}- data-variant={variant}- data-side={side}- data-slot="sidebar"- >- {/* This is what handles the sidebar gap on desktop */}- <div- data-slot="sidebar-gap"- className={cn(- "relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",- "group-data-[collapsible=offcanvas]:w-0",- "group-data-[side=right]:rotate-180",- variant === "floating" || variant === "inset"- ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"- : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"- )}- />- <div- data-slot="sidebar-container"- data-side={side}- className={cn(- "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)] md:flex",- // Adjust the padding for floating and inset variants.- variant === "floating" || variant === "inset"- ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"- : "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",- className- )}- {...props}- >- <div- data-sidebar="sidebar"- data-slot="sidebar-inner"- className="flex size-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:shadow-sm group-data-[variant=floating]:ring-1 group-data-[variant=floating]:ring-sidebar-border"- >- {children}- </div>- </div>- </div>- )-}--function SidebarTrigger({- className,- onClick,- ...props-}: React.ComponentProps<typeof Button>) {- const { toggleSidebar } = useSidebar()-- return (- <Button- data-sidebar="trigger"- data-slot="sidebar-trigger"- variant="ghost"- size="icon-sm"- className={cn(className)}- onClick={(event) => {- onClick?.(event)- toggleSidebar()- }}- {...props}- >- {/* Phones get the familiar menu glyph (the sidebar is a drawer there), wider screens the panel. */}- <MenuIcon className="md:hidden" />- <PanelLeftIcon className="max-md:hidden" />- <span className="sr-only">Toggle Sidebar</span>- </Button>- )-}--function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {- const { toggleSidebar } = useSidebar()-- return (- <button- data-sidebar="rail"- data-slot="sidebar-rail"- aria-label="Toggle Sidebar"- tabIndex={-1}- onClick={toggleSidebar}- title="Toggle Sidebar"- className={cn(- "absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:start-1/2 after:w-[2px] hover:after:bg-sidebar-border sm:flex ltr:-translate-x-1/2 rtl:-translate-x-1/2",- "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",- "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",- "group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full hover:group-data-[collapsible=offcanvas]:bg-sidebar",- "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",- "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",- className- )}- {...props}- />- )-}--function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {- return (- <main- data-slot="sidebar-inset"- className={cn(- "relative flex w-full flex-1 flex-col bg-background md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",- className- )}- {...props}- />- )-}--function SidebarInput({- className,- ...props-}: React.ComponentProps<typeof Input>) {- return (- <Input- data-slot="sidebar-input"- data-sidebar="input"- className={cn("h-8 w-full bg-background shadow-none", className)}- {...props}- />- )-}--function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="sidebar-header"- data-sidebar="header"- className={cn("flex flex-col gap-2 p-2", className)}- {...props}- />- )-}--function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="sidebar-footer"- data-sidebar="footer"- className={cn("flex flex-col gap-2 p-2", className)}- {...props}- />- )-}--function SidebarSeparator({- className,- ...props-}: React.ComponentProps<typeof Separator>) {- return (- <Separator- data-slot="sidebar-separator"- data-sidebar="separator"- className={cn("mx-2 w-auto bg-sidebar-border", className)}- {...props}- />- )-}--function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="sidebar-content"- data-sidebar="content"- className={cn(- "no-scrollbar flex min-h-0 flex-1 flex-col gap-0 overflow-auto group-data-[collapsible=icon]:overflow-hidden",- className- )}- {...props}- />- )-}--function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="sidebar-group"- data-sidebar="group"- className={cn("relative flex w-full min-w-0 flex-col p-2", className)}- {...props}- />- )-}--function SidebarGroupLabel({- className,- asChild = false,- ...props-}: React.ComponentProps<"div"> & { asChild?: boolean }) {- const Comp = asChild ? Slot.Root : "div"-- return (- <Comp- data-slot="sidebar-group-label"- data-sidebar="group-label"- className={cn(- "flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 ring-sidebar-ring outline-hidden transition-[margin,opacity] duration-200 ease-linear group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",- className- )}- {...props}- />- )-}--function SidebarGroupAction({- className,- asChild = false,- ...props-}: React.ComponentProps<"button"> & { asChild?: boolean }) {- const Comp = asChild ? Slot.Root : "button"-- return (- <Comp- data-slot="sidebar-group-action"- data-sidebar="group-action"- className={cn(- "absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform group-data-[collapsible=icon]:hidden after:absolute after:-inset-2 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 md:after:hidden [&>svg]:size-4 [&>svg]:shrink-0",- className- )}- {...props}- />- )-}--function SidebarGroupContent({- className,- ...props-}: React.ComponentProps<"div">) {- return (- <div- data-slot="sidebar-group-content"- data-sidebar="group-content"- className={cn("w-full text-sm", className)}- {...props}- />- )-}--function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {- return (- <ul- data-slot="sidebar-menu"- data-sidebar="menu"- className={cn("flex w-full min-w-0 flex-col gap-0", className)}- {...props}- />- )-}--function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {- return (- <li- data-slot="sidebar-menu-item"- data-sidebar="menu-item"- className={cn("group/menu-item relative", className)}- {...props}- />- )-}--const sidebarMenuButtonVariants = cva(- "peer/menu-button group/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm ring-sidebar-ring outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-open:hover:bg-sidebar-accent data-open:hover:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:font-medium data-active:text-sidebar-accent-foreground [&_svg]:size-4 [&_svg]:shrink-0 [&>span:last-child]:truncate",- {- variants: {- variant: {- default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",- outline:- "bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]",- },- size: {- default: "h-8 text-sm",- sm: "h-7 text-xs",- lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",- },- },- defaultVariants: {- variant: "default",- size: "default",- },- }-)--function SidebarMenuButton({- asChild = false,- isActive = false,- variant = "default",- size = "default",- tooltip,- className,- ...props-}: React.ComponentProps<"button"> & {- asChild?: boolean- isActive?: boolean- tooltip?: string | React.ComponentProps<typeof TooltipContent>-} & VariantProps<typeof sidebarMenuButtonVariants>) {- const Comp = asChild ? Slot.Root : "button"- const { isMobile, state } = useSidebar()-- const button = (- <Comp- data-slot="sidebar-menu-button"- data-sidebar="menu-button"- data-size={size}- data-active={isActive}- className={cn(sidebarMenuButtonVariants({ variant, size }), className)}- {...props}- />- )-- if (!tooltip) {- return button- }-- if (typeof tooltip === "string") {- tooltip = {- children: tooltip,- }- }-- return (- <Tooltip>- <TooltipTrigger asChild>{button}</TooltipTrigger>- <TooltipContent- side="right"- align="center"- hidden={state !== "collapsed" || isMobile}- {...tooltip}- />- </Tooltip>- )-}--function SidebarMenuAction({- className,- asChild = false,- showOnHover = false,- ...props-}: React.ComponentProps<"button"> & {- asChild?: boolean- showOnHover?: boolean-}) {- const Comp = asChild ? Slot.Root : "button"-- return (- <Comp- data-slot="sidebar-menu-action"- data-sidebar="menu-action"- className={cn(- "absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform group-data-[collapsible=icon]:hidden peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 after:absolute after:-inset-2 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 md:after:hidden [&>svg]:size-4 [&>svg]:shrink-0",- showOnHover &&- "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 peer-data-active/menu-button:text-sidebar-accent-foreground aria-expanded:opacity-100 md:opacity-0",- className- )}- {...props}- />- )-}--function SidebarMenuBadge({- className,- ...props-}: React.ComponentProps<"div">) {- return (- <div- data-slot="sidebar-menu-badge"- data-sidebar="menu-badge"- className={cn(- "pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium text-sidebar-foreground tabular-nums select-none group-data-[collapsible=icon]:hidden peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 peer-data-active/menu-button:text-sidebar-accent-foreground",- className- )}- {...props}- />- )-}--function SidebarMenuSkeleton({- className,- showIcon = false,- ...props-}: React.ComponentProps<"div"> & {- showIcon?: boolean-}) {- // Random width between 50 to 90%.- const [width] = React.useState(() => {- return `${Math.floor(Math.random() * 40) + 50}%`- })-- return (- <div- data-slot="sidebar-menu-skeleton"- data-sidebar="menu-skeleton"- className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}- {...props}- >- {showIcon && (- <Skeleton- className="size-4 rounded-md"- data-sidebar="menu-skeleton-icon"- />- )}- <Skeleton- className="h-4 max-w-(--skeleton-width) flex-1"- data-sidebar="menu-skeleton-text"- style={- {- "--skeleton-width": width,- } as React.CSSProperties- }- />- </div>- )-}--function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {- return (- <ul- data-slot="sidebar-menu-sub"- data-sidebar="menu-sub"- className={cn(- "mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5 group-data-[collapsible=icon]:hidden",- className- )}- {...props}- />- )-}--function SidebarMenuSubItem({- className,- ...props-}: React.ComponentProps<"li">) {- return (- <li- data-slot="sidebar-menu-sub-item"- data-sidebar="menu-sub-item"- className={cn("group/menu-sub-item relative", className)}- {...props}- />- )-}--function SidebarMenuSubButton({- asChild = false,- size = "md",- isActive = false,- className,- ...props-}: React.ComponentProps<"a"> & {- asChild?: boolean- size?: "sm" | "md"- isActive?: boolean-}) {- const Comp = asChild ? Slot.Root : "a"-- return (- <Comp- data-slot="sidebar-menu-sub-button"- data-sidebar="menu-sub-button"- data-size={size}- data-active={isActive}- className={cn(- "flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground ring-sidebar-ring outline-hidden group-data-[collapsible=icon]:hidden hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[size=md]:text-sm data-[size=sm]:text-xs data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",- className- )}- {...props}- />- )-}--export {- Sidebar,- SidebarContent,- SidebarFooter,- SidebarGroup,- SidebarGroupAction,- SidebarGroupContent,- SidebarGroupLabel,- SidebarHeader,- SidebarInput,- SidebarInset,- SidebarMenu,- SidebarMenuAction,- SidebarMenuBadge,- SidebarMenuButton,- SidebarMenuItem,- SidebarMenuSkeleton,- SidebarMenuSub,- SidebarMenuSubButton,- SidebarMenuSubItem,- SidebarProvider,- SidebarRail,- SidebarSeparator,- SidebarTrigger,- useSidebar,-}diff --git a/src/hooks/use-mobile.ts b/src/hooks/use-mobile.tsindex 65d2dbf9..68b184db 100644--- a/src/hooks/use-mobile.ts+++ b/src/hooks/use-mobile.ts@@ -18,7 +18,7 @@ export function useIsMobile() {}/**- * useIsMobile for a value that feeds a context over the whole page (the sidebar's). It starts as the server's answer and+ * useIsMobile for a value that feeds a context over the whole page. It starts as the server's answer and* takes the phone's in a transition after hydration: a plain update would reach parts of the page that are still* waiting to hydrate, and React would throw their server HTML away and show their skeletons until their code arrives.*/diff --git a/src/lib/api.ts b/src/lib/api.tsindex cd94fb6a..6388dfde 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -1157,11 +1157,11 @@ export function announceAuthChange(): void {} catch {}}-/** Who used this browser last ("owner", "account" or "guest"): the sidebar's first-paint script reads it (app-sidebar.tsx). */+/** Who used this browser last ("owner", "account" or "guest"): the app frame's first-paint script reads it (CHROME_STATE_SCRIPT in nav.ts). */export const VIEWER_KEY = "fuobe:viewer";/**- * Who the next page is for, said before it loads (signing in or out): the sidebar keeps the right row from its first+ * Who the next page is for, said before it loads (signing in or out): the top bar keeps the right room from its first* frame, so its menu doesn't move when the viewer is known.*/export function rememberViewer(kind: "owner" | "account" | "guest"): void {diff --git a/src/lib/command-search.ts b/src/lib/command-search.tsindex 1eea7025..2eaca37e 100644--- a/src/lib/command-search.ts+++ b/src/lib/command-search.ts@@ -1,6 +1,6 @@/*** The ⌘K palette's search (pure, so it's testable): a forgiving word match, and the matches grouped- * by kind, best first. The palette (src/components/command-palette.tsx) renders what this returns.+ * by kind, best first. The search palette (src/components/nav/search-palette.tsx) shows what this returns.*/import { offered, type AccessSummary } from "./model-access";@@ -16,6 +16,8 @@ export interface PaletteEntry {href: string;/** More words that find it, worth less than the label. */keywords?: string;+ /** A preset's small cover (its thumb URL), when it has one. */+ cover?: string;}/** Group headings, in the order groups take when their best matches tie. */@@ -176,6 +178,18 @@ export interface PalettePreset {/** Has a cloud / an open-source route. */cloud: boolean;open: boolean;+ /** Its real cover: the still's version when it is at the usual place, else the still's URL (presetThumb). */+ cover?: string;+}++/**+ * A preset's small cover from what the index carries: the still at /previews/presets/<id>.jpg named by its version,+ * or any other still by its URL. The small copy sits in thumbs/ next to the still, at the same version (thumbOf).+ */+export function presetThumb(id: string, cover: string | undefined): string | undefined {+ if (!cover) return undefined;+ const poster = cover.startsWith("/") ? cover : `/previews/presets/${id}.jpg?v=${cover}`;+ return poster.replace(/\/([^/]+)$/, "/thumbs/$1");}export interface PaletteModel {@@ -195,10 +209,24 @@ export interface PaletteModel {* The palette's entries from the index, for one engine mode: with one engine locked in Settings, a* preset needs a route on that engine and a model must be on it, as in the galleries and pickers.*/-export function indexEntries(index: PaletteIndex, mode: "both" | "cloud" | "open", access?: AccessSummary): PaletteEntry[] {+/**+ * `opts.owner`: the owner is looking. Anyone else never sees "ComfyUI" as a model's maker (it is how this install runs+ * open models, not a maker a visitor picks): the hint says "Open source" alone.+ */+export function indexEntries(index: PaletteIndex, mode: "both" | "cloud" | "open", access?: AccessSummary, opts: { owner?: boolean } = {}): PaletteEntry[] {const runs = (p: PalettePreset) => mode === "both" || p[mode];const presets = (list: PalettePreset[], kind: "app" | "motion" | "effect", href: (id: string) => string) =>- list.filter(runs).map((p): PaletteEntry => ({ key: `${kind}:${p.id}`, kind, label: p.name, hint: p.category, href: href(p.id), ...(APP_KEYWORDS[p.id] && { keywords: APP_KEYWORDS[p.id] }) }));+ list.filter(runs).map(+ (p): PaletteEntry => ({+ key: `${kind}:${p.id}`,+ kind,+ label: p.name,+ hint: p.category,+ href: href(p.id),+ ...(APP_KEYWORDS[p.id] && { keywords: APP_KEYWORDS[p.id] }),+ ...(p.cover && { cover: presetThumb(p.id, p.cover) }),+ }),+ );return [...presets(index.apps, "app", (id) => `/apps/${id}`),...presets(index.motions, "motion", (id) => `/video?preset=${id}`),@@ -209,12 +237,14 @@ export function indexEntries(index: PaletteIndex, mode: "both" | "cloud" | "open.filter((m) => (mode === "both" || (m.engines ?? [m.engine]).includes(mode)) && offered(access, m.id, mode === "both" ? undefined : mode)).map((m): PaletteEntry => {const both = (m.engines?.length ?? 0) > 1;+ const vendor = !opts.owner && /comfy/i.test(m.vendor) ? "" : m.vendor;+ const hint = (rest: string) => (!vendor || vendor === rest ? rest : `${vendor} · ${rest}`);return {key: `model:${m.id}`,kind: "model",label: m.name,// With both engines on, a model on each (TRELLIS.2, Join clips) would show twice under one name; a Fuobe Original is one model on both.- hint: mode === "both" && both ? `${m.vendor} · Open source + cloud` : mode === "both" && m.engine === "open" ? `${m.vendor} · Open source` : m.vendor,+ hint: mode === "both" && both ? hint("Open source + cloud") : mode === "both" && m.engine === "open" ? hint("Open source") : vendor || (m.engine === "open" ? "Open source" : "Cloud"),href: m.href,keywords: `${m.ops} ${both ? "open source free cloud" : m.engine === "open" ? "open source free" : "cloud"}`,};diff --git a/src/lib/demo-mode.ts b/src/lib/demo-mode.tsindex 31343d2c..698355e2 100644--- a/src/lib/demo-mode.ts+++ b/src/lib/demo-mode.ts@@ -1,5 +1,5 @@/**- * Placeholder results' words and ways out, for the sidebar's "Placeholders on" chip and the "Placeholder" chip on a+ * Placeholder results' words and ways out, for the top bar's "Placeholders on" chip and the "Placeholder" chip on a* result (src/components/demo-mode.tsx). Pure, so the rules are tested without a browser.** Placeholder results are off by default on every install: a run with nothing connected opens the connect card. The@@ -14,7 +14,7 @@ export const PLACEHOLDER_SETTING = "Show placeholder results (for a tour)";/** The chip on every result the demo provider made. */export const PLACEHOLDER_CHIP = "Placeholder";-/** The sidebar's chip while the switch is on: a click turns it off. */+/** The top bar's chip while the switch is on: a click turns it off. */export const PLACEHOLDERS_ON = "Placeholders on";export type PlaceholderAction = "computer" | "key" | "off";diff --git a/src/lib/home-showcase.ts b/src/lib/home-showcase.tsindex bad315da..1e4d4448 100644--- a/src/lib/home-showcase.ts+++ b/src/lib/home-showcase.ts@@ -177,7 +177,7 @@ export interface HomeFacts {apps: number;motions: number;effects: number;- /** Every place to create from the sidebar: Create (but Home) and Studios. */+ /** Every place to create from the navigation: Create (but Home) and Studios. */destinations: number;cinemaMoves: number;adTemplates: number;@@ -204,10 +204,10 @@ export const presetHref = (id: string) => (id.startsWith("app-") ? `/apps/${id}`const navItems = (label: string) => NAV.find((g) => g.label === label)?.items ?? [];const navLabel = (href: string) => [...navItems("Create"), ...navItems("Studios")].find((i) => i.href === href)?.label ?? href;-/** The sidebar's places to create, but Home. */+/** The navigation's places to create, but Home. */export const homeDestinations = () => [...navItems("Create"), ...navItems("Studios")].filter((i) => i.href !== "/");-/** The places to create that have no card or section of their own on Home, in the sidebar's order. */+/** The places to create that have no card or section of their own on Home, in the navigation's order. */export const homePills = () =>homeDestinations().filter((i) => !HOME_OWN_SECTIONS.includes(i.href) && !HOME_STUDIOS.some((s) => s.href === i.href))diff --git a/src/lib/hosted.ts b/src/lib/hosted.tsindex 6d0a6e9a..193a85d8 100644--- a/src/lib/hosted.ts+++ b/src/lib/hosted.ts@@ -34,7 +34,7 @@ export interface HostedQuote {offer?: BillingOffer;}-/** The billing service's words for an account's balance (the sidebar chip and its menu). */+/** The billing service's words for an account's balance (the top bar's chip and the account menu). */export interface HostedBalance {amount: number;chip: string;diff --git a/src/lib/idle-prefetch.ts b/src/lib/idle-prefetch.tsindex 0e45851f..79d1318d 100644--- a/src/lib/idle-prefetch.ts+++ b/src/lib/idle-prefetch.ts@@ -23,7 +23,7 @@ export function whenIdle(fn: () => void): () => void {}/**- * Who asked for an idle prefetch: `nav` = the app's own navigation (the sidebar's rows), `page` = the page's own tabs (a+ * Who asked for an idle prefetch: `nav` = the app's own navigation (the routes the bar's panels lead to), `page` = the page's own tabs (a* hub's modes), the likeliest next tap, which go first.*/export type PrefetchLane = "nav" | "page";@@ -89,8 +89,8 @@ function flush() {lanes.page.clear();lanes.nav.clear();for (const job of page) job.run();- // Next serves a prefetch's route tree and shell (the sidebar's forty-odd routes) before any route's URL-specific part (a- // hub mode's own page, a tab's page), so the sidebar's rows go out only once the page's own tabs are in and the page's+ // Next serves a prefetch's route tree and shell (the navigation's forty-odd routes) before any route's URL-specific part (a+ // hub mode's own page, a tab's page), so the navigation's routes go out only once the page's own tabs are in and the page's// own prefetches (its links on screen) have gone quiet.if (nav.length) afterPrefetched(page.map((job) => job.href), () => nav.forEach((job) => job.run()));}@@ -120,7 +120,7 @@ export function prefetchOptions(full: boolean, onInvalidate?: () => void): Prefe/*** Prefetches `hrefs` once the page has loaded and the browser is idle, also links that are off screen (scrolled out of a- * phone's tab row, below the sidebar's fold), and again whenever Next says the prefetched copy went stale. A tap then+ * phone's tab row, below the fold), and again whenever Next says the prefetched copy went stale. A tap then* renders from the client cache instead of waiting a round trip.*/export function useIdlePrefetch(hrefs: readonly string[] | null, lane: PrefetchLane, full = false): void {diff --git a/src/lib/nav-covers.ts b/src/lib/nav-covers.tsnew file mode 100644index 00000000..02f33388--- /dev/null+++ b/src/lib/nav-covers.ts@@ -0,0 +1,32 @@+/**+ * The navigation's covers, resolved on the server: the studios layout passes them down as props (about 2 KB), so no+ * client chunk carries the covers map for the bar, the launcher, the sheets, the goal row or the next steps.+ */+import "server-only";+import { coverIds } from "./nav-model";+import { presetCover } from "./preset-covers";++export interface NavCover {+ /** The still's small copy (320 px wide), for rows and tiles. */+ thumb: string;+ /** The full still, for the 4:3 cards. */+ poster: string;+}++/** Keyed by preset id. */+export type NavCovers = Record<string, NavCover>;++let cached: NavCovers | undefined;++/** Every cover the navigation shows (coverIds()), at its versioned URLs. A missing one is a mistake in the model. */+export function navCovers(): NavCovers {+ if (cached) return cached;+ const out: NavCovers = {};+ for (const id of coverIds()) {+ const c = presetCover(id);+ if (!c) throw new Error(`The navigation names ${id}, which has no cover`);+ out[id] = { thumb: c.thumb, poster: c.poster };+ }+ cached = out;+ return out;+}diff --git a/src/lib/nav-explore.ts b/src/lib/nav-explore.tsnew file mode 100644index 00000000..ae364cf7--- /dev/null+++ b/src/lib/nav-explore.ts@@ -0,0 +1,63 @@+/**+ * How much of Fuobe this browser has tried, and what to try next. Kept in this browser only (localStorage, read and+ * written by components/nav/explore-tracker.tsx, every access guarded): no server, no cookie, no analytics. Pure, so+ * the counting and the suggestion are testable.+ */+import { entriesFor, entry, type NavEntry, type ViewerKind } from "./nav-model";++/** A JSON list of entry ids, oldest first. */+export const EXPLORE_KEY = "fuobe:explored";+/** The most ids kept (the oldest go first). */+export const EXPLORE_MAX = 200;++/** The stored list, tolerant of anything unexpected: not JSON, not a list, numbers in it, repeats. */+export function parseExplored(raw: string | null | undefined): string[] {+ if (!raw) return [];+ try {+ const v: unknown = JSON.parse(raw);+ if (!Array.isArray(v)) return [];+ return [...new Set(v.filter((x): x is string => typeof x === "string" && x.length > 0 && x.length <= 64))].slice(-EXPLORE_MAX);+ } catch {+ return [];+ }+}++/** The list with one more id at its end (the same list when it's there already), at most EXPLORE_MAX long. */+export function withExplored(list: string[], id: string): string[] {+ if (!id || list.includes(id)) return list;+ return [...list, id].slice(-EXPLORE_MAX);+}++/** What counts towards exploring: the studios this viewer sees (the "28 studios" the launcher and the sheet show). */+export function explorable(kind: ViewerKind | undefined): NavEntry[] {+ return entriesFor(kind).filter((e) => e.kind === "studio" && !!e.group);+}++/** "9 of 28 studios tried": tried ids among what this viewer may explore. */+export function exploreProgress(kind: ViewerKind | undefined, explored: string[]): { done: number; total: number } {+ const all = explorable(kind);+ const seen = new Set(explored);+ return { done: all.filter((e) => seen.has(e.id)).length, total: all.length };+}++/**+ * The next studio to try: one not tried yet that shares the most goals with the last one tried (a film studio after+ * a film studio), then a group's lead (Cinema, Shorts, Marketing, Fashion Factory: the premium ones), then a popular+ * one, then the launcher's order. Nothing this viewer can't see.+ */+export function nextToTry(kind: ViewerKind | undefined, explored: string[], lastId?: string): NavEntry | undefined {+ const seen = new Set(explored);+ const goals = new Set(lastId ? (entry(lastId)?.goals ?? []) : []);+ let best: NavEntry | undefined;+ let bestScore = -1;+ for (const e of explorable(kind)) {+ if (seen.has(e.id)) continue;+ // Goals in common first, popular as a tie-break; the first in the model's order wins a tie (strictly greater).+ const score = e.goals.filter((g) => goals.has(g)).length * 10 + (e.lead ? 3 : 0) + (e.popular ? 1 : 0);+ if (score > bestScore) {+ best = e;+ bestScore = score;+ }+ }+ return best;+}diff --git a/src/lib/nav-icons.ts b/src/lib/nav-icons.tsnew file mode 100644index 00000000..607dae32--- /dev/null+++ b/src/lib/nav-icons.ts@@ -0,0 +1,139 @@+/**+ * The navigation's icons by name (src/lib/nav-model.ts names them, so the model stays free of components). Only the+ * icons listed here are bundled; tests/nav-model.test.ts checks every name the model uses is here.+ */+import {+ AtSign,+ AudioLines,+ Bell,+ Box,+ Brush,+ Camera,+ Clapperboard,+ Code,+ Cpu,+ Crop,+ Drama,+ Factory,+ FastForward,+ Film,+ GalleryHorizontal,+ GraduationCap,+ Heart,+ Home,+ ImageIcon,+ Images,+ KeyRound,+ Layers,+ Layers2,+ LayoutGrid,+ Library,+ LogIn,+ Megaphone,+ MessageCircle,+ Mic2,+ Network,+ PersonStanding,+ Plug,+ Plus,+ Presentation,+ Scale,+ Scissors,+ Server,+ Settings,+ Settings2,+ Shapes,+ ShieldCheck,+ Shirt,+ ShoppingBag,+ SlidersHorizontal,+ Smartphone,+ Sparkles,+ Star,+ SunMoon,+ Swords,+ Target,+ TrendingUp,+ Tv,+ UserPlus,+ UserRound,+ UserRoundCog,+ UserRoundPen,+ Video,+ Wand2,+ WandSparkles,+ Zap,+ ZoomIn,+ type LucideIcon,+} from "lucide-react";++export const NAV_ICONS = {+ AtSign,+ AudioLines,+ Bell,+ Box,+ Brush,+ Camera,+ Clapperboard,+ Code,+ Cpu,+ Crop,+ Drama,+ Factory,+ FastForward,+ Film,+ GalleryHorizontal,+ GraduationCap,+ Heart,+ Home,+ ImageIcon,+ Images,+ KeyRound,+ Layers,+ Layers2,+ LayoutGrid,+ Library,+ LogIn,+ Megaphone,+ MessageCircle,+ Mic2,+ Network,+ PersonStanding,+ Plug,+ Plus,+ Presentation,+ Scale,+ Scissors,+ Server,+ Settings,+ Settings2,+ Shapes,+ ShieldCheck,+ Shirt,+ ShoppingBag,+ SlidersHorizontal,+ Smartphone,+ Sparkles,+ Star,+ SunMoon,+ Swords,+ Target,+ TrendingUp,+ Tv,+ UserPlus,+ UserRound,+ UserRoundCog,+ UserRoundPen,+ Video,+ Wand2,+ WandSparkles,+ Zap,+ ZoomIn,+} satisfies Record<string, LucideIcon>;++export type NavIcon = keyof typeof NAV_ICONS;++/** The icon for a name from the model (the grid for a name that isn't here, which the tests rule out). */+export function navIcon(name: string | undefined): LucideIcon {+ return name && Object.hasOwn(NAV_ICONS, name) ? NAV_ICONS[name as NavIcon] : LayoutGrid;+}diff --git a/src/lib/nav-model.ts b/src/lib/nav-model.tsnew file mode 100644index 00000000..f04d5d38--- /dev/null+++ b/src/lib/nav-model.ts@@ -0,0 +1,589 @@+/**+ * The navigation's one model: every place the top bar, the Studios launcher, the phone tabs and sheets, the search+ * palette, Home's goal row and the next steps under a result link to. Pure data and helpers (no React, no icons as+ * components, no catalog), so the server and the browser share it: icons are names (src/lib/nav-icons.ts maps them),+ * covers are preset ids (src/lib/nav-covers.ts resolves them on the server). Every href is a route that exists; none+ * is renamed here.+ */+import { HUB_MODES, modeHref, type HubKind } from "./hubs";+import { navActive, NEW_CREATION_HREF } from "./nav";++export type ViewerKind = "guest" | "account" | "owner";+export type NavKind = "home" | "action" | "create" | "studio" | "presets" | "tool" | "library" | "settings";+/** Launcher columns, the Studios sheet chips and the palette's "Every studio" chips. */+export type LauncherGroupId = "film" | "social" | "sell" | "people" | "sound" | "finish";+/** The goal row on Home. An entry can serve several goals. */+export type GoalId = "film" | "social" | "sell" | "people" | "edit" | "sound";+/** A key of NAV_ICONS (src/lib/nav-icons.ts), where it is typed as keyof typeof NAV_ICONS. */+export type NavIconName = string;++export interface NavEntry {+ /** Stable slug, unique ("cinema", "audio-clean", "setting-comfyui"). */+ id: string;+ /** An existing route; may carry a query (/library?tab=favorites) or a hash (/settings#comfyui). */+ href: string;+ label: string;+ /** Phone tile label, 12 characters at most. */+ short?: string;+ /** One line, 34 characters at most, sentence case, no full stop. */+ what: string;+ kind: NavKind;+ /** Set: it is in the launcher, the Studios sheet and "Every studio". */+ group?: LauncherGroupId;+ /** The group's lead card (one per group). */+ lead?: true;+ /** Goal bands it can appear in. */+ goals: GoalId[];+ /** Search words: what people type for it that its label doesn't say. */+ keywords: string;+ /** A preset id with a real cover (in PRESET_COVERS). */+ cover?: string;+ icon: NavIconName;+ /** Who sees it anywhere (bar, menus, sheets, search, next steps). Omitted: everyone. */+ visibility?: readonly ViewerKind[];+ /** First in "Every studio" before a search, and among the featured studios. */+ popular?: true;+ /** ISO date: a "New" badge until then. */+ newUntil?: string;+ /** Prefetched as soon as it's on screen: the few routes most visits start from. */+ eager?: true;+ /** A tool's studio id ("audio" for audio-clean): search shows "Audio › Clean up voice". */+ parent?: string;+}++export interface LauncherGroup {+ id: LauncherGroupId;+ label: string;+ chip: string;+}++export interface Goal {+ id: GoalId;+ label: string;+ icon: NavIconName;+ title: string;+ line: string;+ /** "Studios" | "Tools" | "Audio and voice". */+ cardsLabel: string;+ /** 4-5 NavEntry ids (4:3 cover cards). */+ cards: string[];+ tapLabel: string;+ /** 2-4 listed presets. */+ taps: { preset: string; kind: "App" | "Camera motion" | "Effect" }[];+ /** "Finish" | "Picture tools". */+ finishLabel: string;+ /** 2-3 NavEntry ids (text links). */+ finish: string[];+ /** Show "Plan it with Assist" (to the owner only). */+ assist?: true;+}++const OWNER: readonly ViewerKind[] = ["owner"];+const ACCOUNT: readonly ViewerKind[] = ["account"];+const GUEST: readonly ViewerKind[] = ["guest"];+const VISITORS: readonly ViewerKind[] = ["guest", "account"];++/** Where the source lives (as connections.ts says it; kept here so this module imports nothing heavy). */+const REPO = "https://github.com/workingprototype/fuobe";+/** A "do this" entry that isn't a page: the palette toggles the theme. */+export const THEME_ACTION = "action:theme";++/**+ * "New" badges: a studio added after the first ones shows one for 30 days from the day its page was added (its+ * route's first commit). The first studios (the first week) never do.+ */+const newFor30Days = (added: string) => new Date(Date.parse(added) + 30 * 86_400_000).toISOString().slice(0, 10);++/** Top level, create, presets, library and settings pages. */+const PAGES: NavEntry[] = [+ { id: "home", href: "/", label: "Home", what: "Start from words or a picture", kind: "home", goals: [], keywords: "start new creation home", icon: "Home", eager: true },+ { id: "new", href: NEW_CREATION_HREF, label: "New creation", what: "A fresh composer on Home", kind: "action", goals: [], keywords: "new creation start fresh blank compose", icon: "Plus" },+ { id: "assist", href: "/assist", label: "Assist", what: "Plan it with an agent", kind: "create", goals: [], keywords: "agent chat plan assistant ai helper", icon: "MessageCircle", eager: true },+ { id: "image", href: "/image", label: "Image", what: "Text to image", kind: "create", goals: [], keywords: "text to image picture photo generate", cover: "app-poster", icon: "ImageIcon", eager: true, popular: true },+ { id: "video", href: "/video", label: "Video", what: "Text or image to video", kind: "create", goals: ["film"], keywords: "text to video image to video animate clip", cover: "motion-fpv-drone", icon: "Video", eager: true, popular: true },+ { id: "edit", href: "/edit", label: "Edit", what: "Change a picture with words", kind: "create", goals: ["edit"], keywords: "edit image change photo retouch", cover: "app-relight", icon: "Wand2" },+ { id: "live-edit", href: "/live-edit", label: "Live edit", what: "Changes as you type", kind: "create", goals: ["edit"], keywords: "realtime live as you type instant change", icon: "Zap", newUntil: newFor30Days("2026-11-01") },+ { id: "inpaint", href: "/inpaint", label: "Inpaint", what: "Paint over a part", kind: "create", goals: ["edit", "people"], keywords: "mask fill remove brush fix", cover: "app-change-background", icon: "Brush" },+ { id: "layers", href: "/layers", label: "Layers", what: "Split a picture into layers", kind: "create", goals: ["edit"], keywords: "layered psd split cutout", cover: "app-packshot", icon: "Layers2" },+ { id: "color-grade", href: "/color-grade", label: "Color grading", what: "Grade and match colors", kind: "create", goals: ["edit", "film"], keywords: "grade lut colour color", cover: "app-color-grading", icon: "SlidersHorizontal" },+ { id: "canvas", href: "/canvas", label: "Canvas", what: "Wire models together", kind: "create", goals: [], keywords: "nodes flow workflow graph", icon: "Network" },+ { id: "motions", href: "/motions", label: "Camera motions", what: "Crane and drone moves for any shot", kind: "presets", goals: ["film"], keywords: "camera moves presets dolly crane drone orbit", cover: "motion-crane-up", icon: "Film" },+ { id: "effects", href: "/effects", label: "Effects", what: "Visual effects for any clip", kind: "presets", goals: ["film", "social"], keywords: "vfx presets visual effects", cover: "effect-nature-bloom", icon: "Sparkles" },+ { id: "library", href: "/library", label: "All creations", what: "Everything you have made", kind: "library", goals: [], keywords: "library history results creations", icon: "Library", eager: true },+ { id: "favorites", href: "/library?tab=favorites", label: "Favorites", what: "The ones you starred", kind: "library", goals: [], keywords: "starred liked", icon: "Star" },+ { id: "settings", href: "/settings", label: "Settings", what: "Account, GPU and preferences", kind: "settings", goals: [], keywords: "account gpu preferences", icon: "Settings" },+ { id: "connect", href: "/connect", label: "Connect your GPU", what: "Run on your own ComfyUI, free", kind: "settings", goals: [], keywords: "comfyui gpu own server sign up account open source", icon: "Cpu", visibility: VISITORS },+ {+ id: "models-licences",+ href: "/settings/models",+ label: "Models & licences",+ what: "Switch models on or off",+ kind: "settings",+ goals: [],+ keywords: "licence license commercial non-commercial switch off turn on admin providers node packs allow block",+ icon: "Scale",+ visibility: OWNER,+ },+ {+ id: "thanks",+ href: "/settings/licences",+ label: "Thanks & licences",+ what: "The open models Fuobe is built on",+ kind: "settings",+ goals: [],+ keywords: "about credits thanks licence license open source models loras node packs libraries attribution",+ icon: "Heart",+ },+];++/** The launcher's studios (and Apps), column by column; each column's lead first. */+const STUDIOS: NavEntry[] = [+ // Film & video+ { id: "cinema", href: "/cinema", label: "Cinema Studio", short: "Cinema", what: "Direct shots like a film set", kind: "studio", group: "film", lead: true, goals: ["film"], keywords: "film director shots movie cinematic scene", cover: "motion-arc-left", icon: "Clapperboard", popular: true },+ { id: "storyboard", href: "/storyboard", label: "Storyboard", short: "Storyboard", what: "Plan a film frame by frame", kind: "studio", group: "film", goals: ["film"], keywords: "frames story plan shots", cover: "app-shots", icon: "GalleryHorizontal" },+ { id: "motion-control", href: "/motion-control", label: "Motion control", short: "Motion", what: "Copy any dance or pose", kind: "studio", group: "film", goals: ["film", "people"], keywords: "pose dance transfer choreography", cover: "motion-static", icon: "PersonStanding" },+ { id: "extend", href: "/extend", label: "Extend video", short: "Extend", what: "Make a clip longer", kind: "studio", group: "film", goals: ["film", "edit"], keywords: "longer continue lengthen", cover: "motion-aerial-pullback", icon: "FastForward" },+ { id: "reframe", href: "/reframe", label: "Reframe", short: "Reframe", what: "Any shape, vertical first", kind: "studio", group: "film", goals: ["film", "social", "edit"], keywords: "aspect ratio outpaint vertical crop resize", cover: "app-expand-image", icon: "Crop" },+ { id: "video-edit", href: "/video-edit", label: "Edit video", short: "Edit video", what: "Restyle a clip with words", kind: "studio", group: "film", goals: ["film", "edit"], keywords: "video edit restyle change clip", cover: "effect-outfit-switch", icon: "Scissors" },+ { id: "katana", href: "/katana", label: "Katana", short: "Katana", what: "Cut clips into a story", kind: "studio", group: "film", goals: ["film"], keywords: "cut edit clips timeline montage", cover: "app-clipcut", icon: "Swords" },+ {+ id: "video-tools",+ href: "/video-tools",+ label: "Video tools",+ short: "Video tools",+ what: "Trim, matte, depth, captions",+ kind: "studio",+ group: "film",+ goals: ["film", "edit"],+ keywords: "join trim matte depth captions evolution remove object restore colourise colorize archive old footage black and white",+ cover: "app-video-background-remover",+ icon: "Layers",+ },+ // Social & shorts+ { id: "shorts", href: "/shorts", label: "Shorts Studio", short: "Shorts", what: "Vertical reels ready to post", kind: "studio", group: "social", lead: true, goals: ["social"], keywords: "vertical reels tiktok short instagram", cover: "motion-catwalk", icon: "Smartphone", popular: true },+ { id: "faceless", href: "/faceless", label: "Faceless Studio", short: "Faceless", what: "A channel without a face", kind: "studio", group: "social", goals: ["social"], keywords: "youtube channel episodes faceless", cover: "motion-hyperlapse", icon: "Tv" },+ { id: "content-factory", href: "/content-factory", label: "Content Factory", short: "Content", what: "A series from one brief", kind: "studio", group: "social", goals: ["social", "sell"], keywords: "series reference brief episodes batch", cover: "app-transitions", icon: "Factory", newUntil: newFor30Days("2026-10-24") },+ { id: "lipsync", href: "/lipsync", label: "Lipsync & avatars", short: "Lipsync", what: "A photo that talks", kind: "studio", group: "social", goals: ["social", "sound", "people"], keywords: "talking avatar lip sync speak presenter", cover: "app-talking-photo", icon: "Mic2", popular: true },+ { id: "explainer", href: "/explainer", label: "Explainer", short: "Explainer", what: "Slides into a video", kind: "studio", group: "social", goals: ["social"], keywords: "slides pdf video presentation tutorial", cover: "app-breakdown", icon: "Presentation" },+ { id: "virality", href: "/virality", label: "Hook check", short: "Hook check", what: "Score your first 3 seconds", kind: "studio", group: "social", goals: ["social"], keywords: "virality predictor hook score retention", cover: "app-hook-frame", icon: "TrendingUp" },+ // Sell & advertise+ { id: "marketing", href: "/marketing", label: "Marketing Studio", short: "Marketing", what: "UGC and product films", kind: "studio", group: "sell", lead: true, goals: ["sell"], keywords: "ugc product ads commercial brand", cover: "app-macroshot-product", icon: "Megaphone", popular: true },+ { id: "ads", href: "/ads", label: "Ads Studio", short: "Ads", what: "Campaigns in every size", kind: "studio", group: "sell", goals: ["sell"], keywords: "brand campaign advert banner sizes", cover: "app-billboard-ad", icon: "Target" },+ { id: "mixed-media", href: "/mixed-media", label: "Mixed Media", short: "Mixed Media", what: "Collage, paint and photo", kind: "studio", group: "sell", goals: ["sell", "film"], keywords: "collage paint scrapbook", cover: "effect-magazine", icon: "Shapes" },+ { id: "moodboards", href: "/moodboards", label: "Moodboards", short: "Moodboards", what: "Lock a look, reuse it", kind: "studio", group: "sell", goals: ["sell", "people"], keywords: "style references mood look", cover: "app-steal-the-look", icon: "Images" },+ { id: "photodump", href: "/photodump", label: "Photodump", short: "Photodump", what: "A photo pack of one person", kind: "studio", group: "sell", goals: ["sell", "people", "social"], keywords: "photo pack character photoshoot", cover: "app-headshot-generator", icon: "Camera" },+ // People & fashion+ { id: "fashion-factory", href: "/fashion-factory", label: "Fashion Factory", short: "Fashion", what: "Outfits, try-ons, lookbooks", kind: "studio", group: "people", lead: true, goals: ["people", "sell"], keywords: "outfits try-on lookbook dress clothes fashion", cover: "app-outfit-swap", icon: "Shirt", popular: true },+ { id: "influencer", href: "/influencer", label: "AI Influencer", short: "Influencer", what: "Build a character", kind: "studio", group: "people", goals: ["people", "social"], keywords: "character builder avatar creature shuffle", cover: "app-ai-influencer", icon: "UserRoundPen", newUntil: newFor30Days("2026-10-24") },+ { id: "character-sheet", href: "/character-sheet", label: "Character Sheet", short: "Character sheet", what: "One face, every angle", kind: "studio", group: "people", goals: ["people"], keywords: "turnaround angles consistent", cover: "app-fuobe-angles", icon: "UserRoundCog" },+ {+ id: "character-swap",+ href: "/character-swap",+ label: "Character Swap",+ short: "Character swap",+ what: "Swap the star of a clip",+ kind: "studio",+ group: "people",+ goals: ["people", "edit", "film"],+ keywords: "h3 akatz swap character whole clip shots segments takes",+ cover: "app-character-swap",+ icon: "Drama",+ newUntil: newFor30Days("2026-10-27"),+ },+ { id: "genjutsu", href: "/genjutsu", label: "Genjutsu", short: "Genjutsu", what: "Insert or swap anyone", kind: "studio", group: "people", goals: ["people", "edit"], keywords: "swap insert character motion transfer", cover: "effect-turning-metal", icon: "WandSparkles", newUntil: newFor30Days("2026-10-23") },+ { id: "elements", href: "/elements", label: "Elements", short: "Elements", what: "Your people, places, props", kind: "studio", group: "people", goals: ["people", "film"], keywords: "characters places props", cover: "app-figurine", icon: "AtSign" },+ // Sound (the Audio studio leads; its main modes follow it, from HUB_TOOLS)+ {+ id: "audio",+ href: "/audio",+ label: "Audio",+ short: "Audio",+ what: "Voice, music and dubbing",+ kind: "studio",+ group: "sound",+ lead: true,+ goals: ["sound"],+ keywords: "voice voiceover tts text to speech narration music sfx dub transcribe sound",+ cover: "app-asmr-host",+ icon: "AudioLines",+ },+ // Finish & convert+ { id: "upscale", href: "/upscale", label: "Upscale", short: "Upscale", what: "Sharper images and video", kind: "studio", group: "finish", lead: true, goals: ["edit"], keywords: "enhance resolution 4k sharpen", cover: "app-upscale", icon: "ZoomIn" },+ { id: "image-to-3d", href: "/image-to-3d", label: "Image to 3D", short: "Image to 3D", what: "A model you can turn", kind: "studio", group: "finish", goals: ["edit", "sell"], keywords: "3d mesh glb model", cover: "app-3d-rotation", icon: "Box" },+ { id: "apps", href: "/apps", label: "Apps", short: "Apps", what: "One-tap photo and clip tools", kind: "presets", group: "finish", goals: ["social", "sell", "people"], keywords: "one-click tools one tap", cover: "app-3d-figure", icon: "LayoutGrid" },+];++/** What each hub mode does, and the words people type for it. */+const TOOL_COPY: Record<string, { what: string; keywords: string; cover?: string; label?: string; short?: string }> = {+ "upscale-image": { what: "Sharper, larger pictures", keywords: "photo picture enhance 4k 8k sharpen resolution" },+ "upscale-video": { what: "Sharper, larger clips", keywords: "4k 8k enhance clip restore faces resolution" },+ "upscale-fps": { what: "Smoother motion", keywords: "frame interpolation 60fps 120fps slow motion slowmo" },+ "upscale-hdr": { what: "10-bit HDR from any clip", keywords: "sdr hdr hdr10 exr prores 10 bit" },+ "upscale-export": { what: "ProRes and lossless files", keywords: "export prores h265 ffv1 exr codec deliver master" },+ "audio-speech": { what: "Text to speech in any voice", keywords: "tts voiceover narration read aloud clone voice" },+ "audio-dialogue": { what: "A conversation, one voice each", keywords: "conversation podcast two speakers multi voice" },+ "audio-voice-change": { what: "Swap the voice, keep the timing", keywords: "voice changer convert speech to speech" },+ "audio-design": { what: "A new voice from a few words", keywords: "voice design create custom new voice describe" },+ "audio-translate": { what: "Your video in another language", keywords: "dub dubbing localize translate lip sync", cover: "app-asmr-promo", label: "Translate & dub", short: "Translate" },+ "audio-transcribe": { what: "Words from any clip", keywords: "subtitles text speech to text srt vtt captions" },+ "audio-clean": { what: "Remove noise and echo", keywords: "denoise podcast mic fix reverb enhance speech", cover: "app-clean-up-voice", short: "Clean up" },+ "audio-split": { what: "Voice and music apart", keywords: "stems karaoke separate vocals instrumental" },+ "audio-sfx": { what: "Sound effects from words", keywords: "sfx foley whoosh sound effect", cover: "app-asmr-add-on", short: "Sound effects" },+ "audio-music": { what: "A track from a few words", keywords: "song soundtrack beat jingle background music score", cover: "effect-live-concert", short: "Music" },+ "audio-loop": { what: "Loop or lengthen a track", keywords: "loop extend longer repeat" },+ "audio-join": { what: "Join sounds into one", keywords: "merge combine concatenate audio" },+ "audio-video": { what: "Sound that fits the picture", keywords: "foley sfx v2a video to audio", cover: "app-asmr-classic" },+ "video-tools-matte": { what: "Cut out the background", keywords: "remove background green screen alpha matte rotoscope" },+ "video-tools-remove-object": { what: "Erase anything from a clip", keywords: "erase clean plate inpaint video object" },+ "video-tools-remove-dialogue": { what: "Keep the sound, lose the words", keywords: "speech mute voice keep music" },+ "video-tools-evolution": { what: "One shot that morphs over time", keywords: "morph transformation timelapse ageing" },+ "video-tools-restore": { what: "Old footage, sharp and in color", keywords: "colourise colorize archive old footage black and white" },+ "video-tools-relight": { what: "New light on any clip", keywords: "lighting golden hour neon" },+ "video-tools-depth": { what: "A depth map of every frame", keywords: "depth map z pass parallax compositing" },+ "video-tools-captions": { what: "Burned-in captions", keywords: "subtitles srt captions text" },+ "video-tools-trim": { what: "Cut a clip to length", keywords: "cut shorten" },+ "video-tools-join": { what: "Cut clips together", keywords: "merge combine clips" },+ "video-tools-colors": { what: "Match colors to a picture", keywords: "match colors colour palette grade" },+};++const HUB_ORDER: HubKind[] = ["upscale", "audio", "video-tools"];+const HUB_ICON: Record<HubKind, NavIconName> = { upscale: "ZoomIn", audio: "AudioLines", "video-tools": "Layers" };++/**+ * The Sound column: the Audio studio, then its main modes in this order (voice is the studio's first mode, so the lead+ * card stands for it). These modes are in the launcher, the Studios sheet and "Every studio" as well as in search.+ */+const SOUND_COLUMN = ["audio", "audio-music", "audio-sfx", "audio-clean", "audio-translate"];++/** Every hub mode as a tool of its studio (found by search, linked from the goal bands). */+const HUB_TOOLS: NavEntry[] = HUB_ORDER.flatMap((hub) =>+ HUB_MODES[hub].map((m): NavEntry => {+ const id = `${hub}-${m.id}`;+ const copy = TOOL_COPY[id];+ return {+ id,+ href: modeHref(hub, m.id),+ label: copy?.label ?? m.label,+ what: copy?.what ?? m.label,+ kind: "tool",+ goals: [],+ keywords: copy?.keywords ?? "",+ // Its studio's icon: in search a tool shows its studio's cover (or its own), so the bar's code carries no extra icons.+ icon: HUB_ICON[hub],+ parent: hub,+ ...(copy?.cover && { cover: copy.cover }),+ ...(copy?.short && { short: copy.short }),+ ...(SOUND_COLUMN.includes(id) && { group: "sound" as const, goals: ["sound" as const] }),+ ...(m.ownerOnly && { visibility: OWNER }),+ };+ }),+);++/** Pages inside a studio that people look for by name. */+const SUB_TOOLS: NavEntry[] = [+ { id: "marketing-click-to-ad", href: "/marketing/click-to-ad", label: "Click to ad", what: "From a product link to an ad", kind: "tool", goals: [], keywords: "product link url to ad shop page amazon", icon: "Megaphone", parent: "marketing" },+ { id: "ads-multiplier", href: "/ads/multiplier", label: "Ad multiplier", what: "One ad in many versions", kind: "tool", goals: [], keywords: "variations versions sizes multiply", icon: "Target", parent: "ads" },+ { id: "assist-skills", href: "/assist/skills", label: "Skills", what: "Reusable recipes", kind: "tool", goals: [], keywords: "skill recipe playbook automation", icon: "MessageCircle", parent: "assist" },+];++/**+ * Settings sections (ids as in settings-form.tsx). The install's own settings are its owner's; an account gets its+ * own GPU, keys and account; a guest the way to connect a GPU. Everyone may read Thanks & licences.+ */+const SETTINGS: NavEntry[] = (+ [+ ["cloud", "API keys", "fal replicate paid cloud connect", "KeyRound"],+ ["comfyui", "ComfyUI server", "open source gpu url connect local", "Server"],+ ["engine", "Engine mode", "open source cloud both", "Cpu"],+ ["loras", "LoRAs", "lora folder civitai key looks motions effects download licence", "Layers"],+ ["training", "Training (AI-Toolkit)", "ai-toolkit aitk train lora soul id gpu url token", "GraduationCap"],+ ["text-ai", "AI helper", "claude ollama lm studio unsloth local llm model enhancer prompt enhancement context", "Sparkles"],+ ["assist-connectors", "Assist connectors", "mcp connector claude tools notion linear slack server token", "Plug"],+ ["notifications", "Notifications", "browser done alerts", "Bell"],+ ["security", "Password and API tokens", "security sign in mcp token", "ShieldCheck"],+ ["demo", "Placeholder results", "demo mode placeholder tour free try", "Settings2"],+ ] as const+).map(([section, label, keywords, icon]): NavEntry => ({+ id: `setting-${section}`,+ href: `/settings#${section}`,+ label,+ what: "Settings",+ kind: "settings",+ goals: [],+ keywords,+ icon,+ visibility: OWNER,+}));++const ACCOUNT_SETTINGS: NavEntry[] = [+ { id: "your-gpu", href: "/settings#your-gpu", label: "Your GPU", what: "Run on your own ComfyUI", kind: "settings", goals: [], keywords: "comfyui gpu connect own server open source", icon: "Cpu", visibility: ACCOUNT },+ {+ id: "your-keys",+ href: "/settings#your-keys",+ label: "Your keys",+ what: "Your own paid model keys",+ kind: "settings",+ goals: [],+ keywords: "fal fal.ai replicate api key token paid models nano banana kling veo billing",+ icon: "KeyRound",+ visibility: ACCOUNT,+ },+ { id: "account", href: "/settings#account", label: "Account", what: "Email, sign out, delete", kind: "settings", goals: [], keywords: "email sign out delete account", icon: "UserRound", visibility: ACCOUNT },+];++/** Things to do rather than pages to open: search only. Sign up and Log in get their return path at render. */+const ACTIONS: NavEntry[] = [+ { id: "toggle-theme", href: THEME_ACTION, label: "Toggle dark mode", what: "Switch light and dark", kind: "action", goals: [], keywords: "dark light theme night mode appearance", icon: "SunMoon" },+ { id: "github", href: REPO, label: "Source on GitHub", what: "Open source, MIT", kind: "action", goals: [], keywords: "github code repo repository open source download install self host", icon: "Code" },+ { id: "signup", href: "/login?signup=1", label: "Sign up free", what: "Save your work, run more", kind: "action", goals: [], keywords: "sign up register create account join", icon: "UserPlus", visibility: GUEST },+ { id: "login", href: "/login", label: "Log in", what: "Back to your account", kind: "action", goals: [], keywords: "log in login sign in account", icon: "LogIn", visibility: GUEST },+];++export const NAV_ENTRIES: readonly NavEntry[] = [...PAGES, ...STUDIOS, ...HUB_TOOLS, ...SUB_TOOLS, ...SETTINGS, ...ACCOUNT_SETTINGS, ...ACTIONS];++export const LAUNCHER_GROUPS: readonly LauncherGroup[] = [+ { id: "film", label: "Film & video", chip: "Film" },+ { id: "social", label: "Social & shorts", chip: "Social" },+ { id: "sell", label: "Sell & advertise", chip: "Sell" },+ { id: "people", label: "People & fashion", chip: "People" },+ { id: "sound", label: "Sound", chip: "Sound" },+ { id: "finish", label: "Finish & convert", chip: "Finish" },+];++export const GOALS: readonly Goal[] = [+ {+ id: "film",+ label: "Make a film",+ icon: "Clapperboard",+ title: "Make a film",+ line: "Studios, camera moves and finishing tools for film",+ cardsLabel: "Studios",+ cards: ["cinema", "storyboard", "katana", "motion-control", "extend"],+ tapLabel: "One-tap for films",+ taps: [+ { preset: "motion-drone-reveal", kind: "Camera motion" },+ { preset: "effect-northern-lights", kind: "Effect" },+ { preset: "effect-turning-metal", kind: "Effect" },+ { preset: "app-color-grading", kind: "App" },+ ],+ finishLabel: "Finish",+ finish: ["video-tools", "audio", "upscale"],+ assist: true,+ },+ {+ id: "social",+ label: "Grow on social",+ icon: "TrendingUp",+ title: "Grow on social",+ line: "Studios, one-tap apps and finishing tools for social",+ cardsLabel: "Studios",+ cards: ["shorts", "faceless", "content-factory", "lipsync", "explainer"],+ tapLabel: "One-tap for social",+ taps: [+ { preset: "app-talking-photo", kind: "App" },+ { preset: "app-plushies", kind: "App" },+ { preset: "effect-outfit-switch", kind: "Effect" },+ { preset: "app-renaissance", kind: "App" },+ ],+ finishLabel: "Finish",+ finish: ["virality", "reframe", "video-tools-captions"],+ assist: true,+ },+ {+ id: "sell",+ label: "Sell a product",+ icon: "ShoppingBag",+ title: "Sell a product",+ line: "Studios, one-tap apps and finishing tools for products",+ cardsLabel: "Studios",+ cards: ["marketing", "ads", "photodump", "mixed-media", "moodboards"],+ tapLabel: "One-tap for products",+ taps: [+ { preset: "app-giant-product", kind: "App" },+ { preset: "app-billboard-ad", kind: "App" },+ { preset: "app-commercial-faces", kind: "App" },+ { preset: "motion-drone-reveal", kind: "Camera motion" },+ ],+ finishLabel: "Finish",+ finish: ["upscale", "reframe"],+ assist: true,+ },+ {+ id: "people",+ label: "People & fashion",+ icon: "UserRound",+ title: "People & fashion",+ line: "Studios and one-tap looks for people and fashion",+ cardsLabel: "Studios",+ cards: ["fashion-factory", "influencer", "character-sheet", "genjutsu", "elements"],+ tapLabel: "One-tap for people",+ taps: [+ { preset: "app-makeup-studio", kind: "App" },+ { preset: "app-commercial-faces", kind: "App" },+ { preset: "app-3d-figure", kind: "App" },+ { preset: "app-plushies", kind: "App" },+ ],+ finishLabel: "Finish",+ finish: ["inpaint", "upscale"],+ },+ {+ id: "edit",+ label: "Edit & finish",+ icon: "SlidersHorizontal",+ title: "Edit & finish",+ line: "Change a picture or a clip you already have",+ cardsLabel: "Tools",+ cards: ["video-edit", "character-swap", "upscale", "reframe", "image-to-3d"],+ tapLabel: "One-tap looks",+ taps: [+ { preset: "app-renaissance", kind: "App" },+ { preset: "app-color-grading", kind: "App" },+ { preset: "effect-turning-metal", kind: "Effect" },+ { preset: "app-3d-render", kind: "App" },+ ],+ finishLabel: "Picture tools",+ finish: ["edit", "inpaint", "layers"],+ },+ {+ id: "sound",+ label: "Sound",+ icon: "AudioLines",+ title: "Sound",+ line: "Voice, music and sound for anything you make",+ cardsLabel: "Audio and voice",+ cards: ["audio", "lipsync", "audio-translate", "audio-video"],+ tapLabel: "One-tap with a voice",+ taps: [+ { preset: "app-talking-photo", kind: "App" },+ { preset: "app-asmr-host", kind: "App" },+ ],+ finishLabel: "Finish",+ finish: ["audio-clean", "audio-split", "audio-transcribe"],+ },+];++/**+ * Covers of the next steps under a result (src/lib/next-steps.ts), by step: listed here so coverIds() names every+ * cover the navigation shows, and nav-covers.ts resolves them all on the server.+ */+export const STEP_COVERS = {+ animate: "motion-dolly-in",+ talk: "app-talking-photo",+ sheet: "app-fuobe-angles",+ billboard: "app-billboard-ad",+ upscale: "app-upscale",+ giant: "app-giant-product",+ edit: "app-relight",+ grade: "app-color-grading",+ threeD: "app-3d-rotation",+ extend: "motion-aerial-pullback",+ sound: "effect-live-concert",+ split: "app-asmr-host",+ reframe: "app-expand-image",+ swap: "effect-turning-metal",+ voice: "app-asmr-promo",+ clean: "app-clean-up-voice",+ spin: "app-product-360",+} as const;++const byId = new Map(NAV_ENTRIES.map((e) => [e.id, e]));++export function entry(id: string): NavEntry | undefined {+ return byId.get(id);+}++/** Whether a viewer sees an entry anywhere. A viewer not known yet sees what a guest may see, and no more. */+export function visibleTo(e: NavEntry, kind: ViewerKind | undefined): boolean {+ return !e.visibility || e.visibility.includes(kind ?? "guest");+}++export function entriesFor(kind: ViewerKind | undefined): NavEntry[] {+ return NAV_ENTRIES.filter((e) => visibleTo(e, kind));+}++/** Who is looking: the owner, an account (public sign-up) or a guest (signed out while sign-up is open). */+export function viewerKindOf(v: { owner?: boolean; account?: unknown; publicSignup?: boolean } | undefined): ViewerKind | undefined {+ if (!v) return undefined;+ return v.owner ? "owner" : v.account ? "account" : v.publicSignup ? "guest" : "owner";+}++/** The launcher's columns, one per group, each with its lead card and the rest in order. */+export function launcherColumns(kind: ViewerKind | undefined): { group: LauncherGroup; lead: NavEntry; rest: NavEntry[] }[] {+ return LAUNCHER_GROUPS.map((group) => {+ const all = NAV_ENTRIES.filter((e) => e.group === group.id && visibleTo(e, kind));+ if (group.id === "sound") all.sort((a, b) => SOUND_COLUMN.indexOf(a.id) - SOUND_COLUMN.indexOf(b.id));+ const lead = all.find((e) => e.lead) ?? all[0];+ return { group, lead, rest: all.filter((e) => e !== lead) };+ });+}++/** Every launcher entry in column order (the Studios sheet's tiles and the palette's "Every studio"). */+export function launcherEntries(kind: ViewerKind | undefined, group?: LauncherGroupId): NavEntry[] {+ return launcherColumns(kind)+ .filter((c) => !group || c.group.id === group)+ .flatMap((c) => [c.lead, ...c.rest]);+}++const LAUNCHER_HREFS = NAV_ENTRIES.filter((e) => e.group).map((e) => e.href);++/**+ * The launcher entry the path is on (its id), the one whose link matches best: /audio/music is Music, /audio and+ * /audio/dialogue are Audio, /marketing/click-to-ad is Marketing Studio. None for a page outside the launcher.+ */+export function launcherActive(pathname: string): string | undefined {+ let best: NavEntry | undefined;+ for (const e of NAV_ENTRIES) {+ if (!e.group || !navActive(e.href, pathname, new URLSearchParams(), LAUNCHER_HREFS)) continue;+ if (!best || e.href.length > best.href.length) best = e;+ }+ return best?.id;+}++/** How many studios there are (Apps is not one): for copy such as "28 studios". */+export function studioCount(): number {+ return NAV_ENTRIES.filter((e) => e.group && e.kind === "studio").length;+}++/** A goal's band on Home: its cards and finishing links that this viewer may see. */+export function goalBand(id: GoalId, kind: ViewerKind | undefined): { goal: Goal; cards: NavEntry[]; finish: NavEntry[] } {+ const goal = GOALS.find((g) => g.id === id);+ if (!goal) throw new Error(`No goal ${id}`);+ const pick = (ids: string[]) => ids.map((i) => byId.get(i)).filter((e): e is NavEntry => !!e && visibleTo(e, kind));+ return { goal, cards: pick(goal.cards), finish: pick(goal.finish) };+}++/** Entries that are pages of their own (no actions, no settings sections, nothing off the site). */+const ROUTES = NAV_ENTRIES.filter((e) => e.kind !== "tool" && e.kind !== "action" && e.href.startsWith("/") && !e.href.includes("#"));+const ROUTE_HREFS = ROUTES.map((e) => e.href);++/**+ * The page the path is on: the entry whose link matches best (navActive, with every other page as a sibling, so+ * /library?tab=favorites wins over /library, and /settings/models over /settings). A hub's modes and a studio's own+ * pages count as the studio (/audio/clean is Audio, /marketing/click-to-ad is Marketing Studio).+ */+export function activeEntry(pathname: string, search: URLSearchParams): NavEntry | undefined {+ let best: NavEntry | undefined;+ for (const e of ROUTES) {+ if (!navActive(e.href, pathname, search, ROUTE_HREFS)) continue;+ if (!best || e.href.length > best.href.length) best = e;+ }+ return best;+}++/** Whether an entry shows its "New" badge now (the browser's clock). */+export function isNew(e: NavEntry, now: number = Date.now()): boolean {+ return !!e.newUntil && now < Date.parse(e.newUntil);+}++/** Every preset id the navigation shows a cover for: entries, goal taps, next steps. nav-covers.ts resolves these. */+export function coverIds(): string[] {+ const ids = [+ ...NAV_ENTRIES.map((e) => e.cover),+ ...GOALS.flatMap((g) => g.taps.map((t) => t.preset)),+ ...Object.values(STEP_COVERS),+ ].filter((id): id is string => !!id);+ return [...new Set(ids)];+}++/** Where a goal tap's preset opens, as the galleries link it: an app's page, else Video with it picked. */+export const tapHref = (preset: string) => (preset.startsWith("app-") ? `/apps/${preset}` : `/video?preset=${preset}`);diff --git a/src/lib/nav-search.ts b/src/lib/nav-search.tsnew file mode 100644index 00000000..138d41a0--- /dev/null+++ b/src/lib/nav-search.ts@@ -0,0 +1,392 @@+/**+ * The search palette's ranking (pure, so it's testable and instant: a couple of milliseconds for every studio, tool,+ * app, motion, effect and model). It reads a query the way people type one ("ad for my perfume"): filler words out,+ * plurals and -ing folded, every word matched against names and search words, and a table of intents that knows a+ * perfume ad is a job for Marketing Studio. The word match itself is command-search.ts's (wordScore).+ */+import { GROUP_LIMIT, KIND_LABELS, normalize, wordScore, type PaletteEntry, type PaletteKind } from "./command-search";+import { entry as navEntry, THEME_ACTION, type NavEntry, type NavKind } from "./nav-model";++export type HitKind = PaletteKind | "studio" | "tool";++/** What the palette searches: the index's entries (PaletteEntry) and the navigation's (navSearchEntries). */+export interface SearchEntry extends Omit<PaletteEntry, "kind"> {+ kind: HitKind;+ /** The nav entry id, or the preset / model id. */+ id?: string;+ /** One line under the name. */+ what?: string;+ /** A preset id (nav covers) or a full thumb URL (index presets). */+ cover?: string;+ /** The nav entry's kind (studio, create, tool…), which decides its tag and its weight. */+ navKind?: NavKind;+ /** A nav icon name. */+ icon?: string;+ popular?: boolean;+}++export interface NavHit {+ key: string;+ kind: HitKind;+ label: string;+ what?: string;+ href: string;+ /** A preset id or a full thumb URL. */+ cover?: string;+ /** Where it comes from, before its name ("Camera motions" › Dolly In). */+ from?: string;+ hint?: string;+ icon?: string;+ navKind?: NavKind;+ id?: string;+ score: number;+}++export interface Intent {+ id: string;+ /** Query words (or phrases) that mean it. */+ triggers: string[];+ /** Nav entry ids or preset ids, best first. */+ targets: string[];+}++export interface SearchResult {+ /** The top three, whatever their kind. */+ best: NavHit[];+ /** The next two apps, motions or effects, with where they come from. */+ also: NavHit[];+ /** Everything else that matched, by kind, each group capped. */+ groups: { kind: string; label: string; hits: NavHit[] }[];+}++/** Words that carry no meaning for finding a tool ("make me an ad for my perfume" is about an ad and a perfume). */+export const STOPWORDS: ReadonlySet<string> = new Set(+ "a an the for my our your of to with in on and me i we want need some something like please make create do can how new turn into change add get put use using from this that it".split(" "),+);++/** What people mean, and where it's done best (the first target first). */+export const INTENTS: readonly Intent[] = [+ {+ id: "product-ad",+ triggers: [..."ad advert advertisement commercial promo perfume fragrance cosmetic skincare lipstick product packshot sell shop brand campaign ecommerce amazon shopify launch".split(" "), "product photo", "product shot"],+ targets: ["marketing", "ads", "app-giant-product", "app-billboard-ad", "app-product-shot", "motion-dolly-in", "effect-turning-metal"],+ },+ { id: "ugc", triggers: ["ugc", "testimonial", "review", "unboxing"], targets: ["marketing", "app-unboxing-video", "lipsync"] },+ { id: "reel", triggers: ["reel", "reels", "tiktok", "short", "shorts", "vertical", "instagram", "story", "viral"], targets: ["shorts", "reframe", "virality", "content-factory"] },+ { id: "channel", triggers: ["youtube", "channel", "faceless", "episode", "series", "podcast"], targets: ["faceless", "content-factory", "explainer", "audio"] },+ { id: "film", triggers: ["film", "movie", "cinematic", "scene", "shot", "director", "trailer", "music video"], targets: ["cinema", "storyboard", "motions", "katana"] },+ { id: "dance", triggers: ["dance", "choreography", "pose", "moves", "tiktok dance"], targets: ["motion-control", "app-dance", "genjutsu"] },+ { id: "talk", triggers: ["talk", "talking", "speak", "lipsync", "lip sync", "avatar", "presenter", "spokesperson"], targets: ["lipsync", "app-talking-photo", "audio-speech"] },+ { id: "sound", triggers: ["sound", "audio"], targets: ["audio", "audio-sfx", "audio-music"] },+ { id: "voice", triggers: ["voice", "voiceover", "voice over", "narration", "narrator", "tts", "text to speech", "read aloud"], targets: ["audio-speech", "audio", "lipsync"] },+ { id: "music", triggers: ["music", "song", "soundtrack", "beat", "jingle", "score", "background music"], targets: ["audio-music", "audio", "audio-video"] },+ { id: "sfx", triggers: ["sfx", "foley", "whoosh", "sound effect"], targets: ["audio-sfx", "audio-video", "audio"] },+ { id: "clean-audio", triggers: ["noise", "echo", "denoise", "clean audio", "mic"], targets: ["audio-clean", "app-clean-up-voice"] },+ { id: "dub", triggers: ["translate", "dub", "dubbing", "language", "localize"], targets: ["audio-translate", "video-tools-captions"] },+ { id: "captions", triggers: ["caption", "captions", "subtitle", "subtitles", "srt"], targets: ["video-tools-captions", "audio-transcribe"] },+ { id: "fashion", triggers: ["outfit", "dress", "clothes", "fashion", "try on", "tryon", "lookbook", "wear", "model shoot"], targets: ["fashion-factory", "app-virtual-try-on", "app-outfit-swap", "effect-outfit-switch"] },+ { id: "character", triggers: ["character", "consistent", "same face", "turnaround", "angles", "persona"], targets: ["character-sheet", "influencer", "elements", "app-fuobe-angles"] },+ { id: "influencer", triggers: ["influencer", "creator", "persona", "ai model"], targets: ["influencer", "photodump", "fashion-factory"] },+ { id: "swap", triggers: ["swap", "replace", "face swap", "insert", "deepfake", "recast"], targets: ["character-swap", "genjutsu", "app-face-swap", "app-recast"] },+ { id: "upscale", triggers: ["upscale", "4k", "8k", "sharper", "sharpen", "enhance", "hd", "resolution", "blurry"], targets: ["upscale", "upscale-video", "app-upscale"] },+ { id: "background", triggers: ["background", "bg", "remove background", "cutout", "green screen", "transparent"], targets: ["video-tools-matte", "app-remove-background", "app-change-background", "layers"] },+ { id: "fix", triggers: ["fix", "retouch", "remove", "erase", "object", "inpaint"], targets: ["inpaint", "video-tools-remove-object", "app-object-remover", "edit"] },+ { id: "animate", triggers: ["animate", "motion", "move", "bring to life", "image to video"], targets: ["video", "motions", "app-bring-to-life"] },+ // Not "model": an AI model, a fashion model and a 3D model are three things.+ { id: "3d", triggers: ["3d", "mesh", "glb", "turntable", "figure", "figurine"], targets: ["image-to-3d", "app-3d-figure", "app-3d-rotation"] },+ { id: "photos", triggers: ["photos", "photoshoot", "headshot", "portrait", "profile picture", "dating"], targets: ["photodump", "app-headshot-generator", "image"] },+ { id: "moodboard", triggers: ["moodboard", "mood", "style", "look", "aesthetic", "reference"], targets: ["moodboards", "app-steal-the-look", "app-style-transfer"] },+ { id: "colour", triggers: ["color", "colour", "grade", "lut", "cinematic look"], targets: ["color-grade", "app-color-grading"] },+ { id: "longer", triggers: ["longer", "extend", "continue"], targets: ["extend"] },+ { id: "aspect", triggers: ["aspect", "ratio", "crop", "resize", "vertical", "square", "widescreen"], targets: ["reframe", "app-expand-image"] },+ { id: "slides", triggers: ["slides", "pdf", "presentation", "explain", "tutorial"], targets: ["explainer"] },+ { id: "collage", triggers: ["collage", "paper", "paint", "scrapbook", "magazine"], targets: ["mixed-media", "effect-magazine"] },+ { id: "scene", triggers: ["sky", "backdrop", "scenery", "sunset", "weather", "location", "setting"], targets: ["app-change-background", "edit", "inpaint", "live-edit"] },+ {+ id: "cartoon",+ triggers: ["anime", "cartoon", "cartoonify", "toon", "comic", "manga", "pixar", "ghibli", "illustration", "illustrated", "drawing", "stylize", "stylise"],+ targets: ["app-style-transfer", "app-comic-book", "effect-comic", "app-3d-figure", "mixed-media"],+ },+ {+ id: "restore",+ triggers: ["restore", "restoration", "old photo", "old picture", "damaged", "scratched", "faded", "colorize", "colourise", "colorise", "colourize", "black and white"],+ targets: ["app-restore-photo", "app-colorize", "upscale", "video-tools"],+ },+ { id: "logo", triggers: ["logo", "wordmark", "lettering", "typography", "font", "signage"], targets: ["image", "app-text-edit", "ads"] },+ {+ id: "property",+ triggers: ["real estate", "property", "interior", "apartment", "listing", "realtor", "house tour", "home tour", "walkthrough"],+ targets: ["motions", "edit", "upscale", "video"],+ },+ { id: "hook", triggers: ["hook", "thumbnail", "first seconds", "retention", "engagement"], targets: ["virality", "app-hook-frame"] },+];++/**+ * A word's plain form, for matching only: plurals ("ads" → "ad", "perfumes" → "perfume", "dresses" → "dress") and+ * -ing ("talking" → "talk", "dubbing" → "dub"). Short words and words that only look plural ("dress", "canvas")+ * stay as they are.+ */+export function stem(word: string): string {+ if (word.length > 5 && word.endsWith("ing")) {+ let s = word.slice(0, -3);+ // A doubled last letter ("dubb", "runn"), but not ss / ll ("dressing", "selling").+ if (s.length > 3 && s.at(-1) === s.at(-2) && !/[sl]$/.test(s)) s = s.slice(0, -1);+ return s.length >= 3 ? s : word;+ }+ if (word.length > 4 && /(ss|x|z|ch|sh)es$/.test(word)) return word.slice(0, -2);+ if (word.length >= 3 && word.endsWith("s") && !/(ss|us|is|as)$/.test(word)) return word.slice(0, -1);+ return word;+}++/** The words that matter in a query: normalized, filler words out (unless that leaves none). */+export function queryWords(query: string): string[] {+ const all = normalize(query).split(" ").filter(Boolean);+ const kept = all.filter((w) => !STOPWORDS.has(w));+ return kept.length ? kept : all;+}++// ---------------------------------------------------------------------------+// Scoring++interface Prepared {+ label: string;+ keywords: string;+ hint: string;+ what: string;+}++const prepared = new WeakMap<SearchEntry, Prepared>();+function prep(e: SearchEntry): Prepared {+ let p = prepared.get(e);+ if (!p) {+ p = { label: normalize(e.label), keywords: normalize(e.keywords ?? ""), hint: normalize(e.hint ?? ""), what: normalize(e.what ?? "") };+ prepared.set(e, p);+ }+ return p;+}++/** wordScore without its letters-in-order guess: for the hint and the line, where a guess is only noise. */+function plainScore(word: string, text: string): number {+ if (!text) return 0;+ if (text === word) return 100;+ if (text.startsWith(word)) return 80;+ if (text.includes(` ${word}`)) return 60;+ // Inside a word only from three letters ("ad" is not in "grade").+ return word.length > 2 && text.includes(word) ? 40 : 0;+}++/** Words this short are never a letters-in-order guess ("logo" is not "Log in", nor "longer"). */+const GUESS_FROM = 5;++/**+ * wordScore for a name: a short word only as written (no guess), and the start of a longer word ("photo" in+ * "Photodump") worth less than a whole word ("photo" in "Restore Photo"), so a name that only shares letters with+ * the query doesn't beat one that has its word.+ */+function nameScore(w: string, text: string): number {+ const s = w.length < GUESS_FROM ? plainScore(w, text) : wordScore(w, text);+ if (s === 80 && text.length > w.length && text[w.length] !== " ") return 62;+ return s;+}++/** One query word against one entry: its name counts in full, its search words half, its hint and its line less. */+function wordBest(w: string, p: Prepared): number {+ return Math.max(nameScore(w, p.label), nameScore(w, p.keywords) / 2, p.hint ? plainScore(w, p.hint) * 0.4 - 1 : 0, plainScore(w, p.what) / 2.5);+}++/** A word or its plain form, whichever matches better. */+function wordMatch(w: string, s: string, p: Prepared): number {+ return s === w ? wordBest(w, p) : Math.max(wordBest(w, p), wordBest(s, p));+}++/**+ * How well the words match an entry: every word matching (strict), else at least half of them, worth less (loose: a+ * query with a filler word the table doesn't know still finds its studio).+ */+function textScore(words: string[], stems: string[], p: Prepared): number {+ let total = 0;+ let matched = 0;+ for (let i = 0; i < words.length; i++) {+ const s = wordMatch(words[i], stems[i], p);+ if (s > 0) matched++;+ total += s;+ }+ if (!matched) return 0;+ if (matched === words.length) {+ // The whole query reading as the label's start beats the same words matched one by one; every word of a longer+ // query matching is worth something over an intent that names the entry for one of them ("upscale video": the+ // Upscale studio's Video tool before the studio).+ const bonus = words.length > 1 ? (p.label.startsWith(words.join(" ")) ? 20 : 16) : 0;+ return (total + bonus) / words.length;+ }+ return matched * 2 >= words.length ? (total / words.length) * 0.8 : 0;+}++/** Where people mostly go wins close calls: a studio over a preset of the same name. */+function kindBonus(e: SearchEntry): number {+ switch (e.navKind) {+ case "studio":+ return 10;+ case "tool":+ return 6;+ case "settings":+ return 4;+ case "create":+ case "presets":+ case "home":+ case "library":+ case "action":+ return 8;+ }+ return e.kind === "page" ? 8 : e.kind === "setting" ? 4 : 0;+}++/**+ * An intent's weight for its targets, by place: its first target beats a name that only has one of the query's words+ * ("film" finds Cinema Studio before the Film Colors effect), and loses to a name that is the query ("dance" → Dance).+ */+const intentWeight = (position: number) => 75 - 5 * position;+const INTENT_CAP = 95;++/** The intents a query means: a trigger is one of its words (or that word's plain form), or a phrase in it. */+function firedIntents(query: string, words: string[], stems: string[], intents: readonly Intent[]): Intent[] {+ const text = ` ${normalize(query)} `;+ const set = new Set([...words, ...stems]);+ // A query word or its plain form ("ads" fires "ad"); not the other way round, so "photo" doesn't fire "photos".+ return intents.filter((it) => it.triggers.some((t) => (t.includes(" ") ? text.includes(` ${t} `) : set.has(t))));+}++/** Weaker matches than this share of the best are noise next to it (as in rankPalette). */+const KEEP_FROM_BEST = 0.35;+const KEEP_FROM_REAL_MATCH = 0.6;+const REAL_MATCH = 39;+/** Below this, nothing is shown as the best match (a word shared with a name: "real" in "Sketch to Real"). */+const BEST_FROM = 30;++/** The id an intent target names: a nav entry's id, or a preset's ("app:app-dance" → "app-dance"). */+const idOf = (e: SearchEntry) => e.id ?? e.key.slice(e.key.indexOf(":") + 1);++/** Where a group of hits is listed, and how many it shows. */+function groupOf(kind: HitKind): { kind: string; label: string; limit: number } {+ if (kind === "studio" || kind === "tool" || kind === "page") return { kind: "studio", label: "Studios & tools", limit: GROUP_LIMIT.page };+ return { kind, label: KIND_LABELS[kind], limit: GROUP_LIMIT[kind] };+}+const GROUP_ORDER = ["studio", "app", "motion", "effect", "model", "skill", "setting", "recent"];++const toHit = (e: SearchEntry, score: number): NavHit => ({+ key: e.key,+ kind: e.kind,+ label: e.label,+ href: e.href,+ score,+ ...(e.what !== undefined && { what: e.what }),+ ...(e.cover && { cover: e.cover }),+ ...(e.hint && { hint: e.hint }),+ ...(e.icon && { icon: e.icon }),+ ...(e.navKind && { navKind: e.navKind }),+ ...(e.id && { id: e.id }),+});++/**+ * The matches for a query: the best three, two presets to also try, and the rest by kind. An empty query matches+ * nothing (the palette shows its own start: recent work and every studio).+ */+export function searchNav(query: string, entries: SearchEntry[], opts: { intents?: readonly Intent[] } = {}): SearchResult {+ const empty: SearchResult = { best: [], also: [], groups: [] };+ const words = queryWords(query);+ if (!words.length) return empty;+ const stems = words.map(stem);+ const fired = firedIntents(query, words, stems, opts.intents ?? INTENTS);+ // An intent that explains only part of the query counts for less ("upscale video": Upscale's Video tool, which has+ // both words, before the studio the intent names for "upscale").+ const triggerWords = new Set(fired.flatMap((it) => it.triggers.flatMap((t) => t.split(" "))));+ const explained = words.filter((w, i) => triggerWords.has(w) || triggerWords.has(stems[i])).length;+ const share = 0.5 + (0.5 * explained) / words.length;+ const boosts = new Map<string, number>();+ for (const it of fired) {+ it.targets.forEach((t, i) => boosts.set(t, Math.min(INTENT_CAP, (boosts.get(t) ?? 0) + intentWeight(i) * share)));+ }++ const scored: { e: SearchEntry; text: number; boost: number; bonus: number }[] = [];+ let top = 0;+ for (const e of entries) {+ const text = textScore(words, stems, prep(e));+ const boost = boosts.size ? (boosts.get(idOf(e)) ?? 0) : 0;+ if (!text && !boost) continue;+ const bonus = kindBonus(e) + (e.popular ? 2 : 0) - e.label.length / 100;+ if (text) top = Math.max(top, text + bonus);+ scored.push({ e, text, boost, bonus });+ }+ // Letters-in-order guesses next to a real match are noise; what an intent names always stays.+ // With an intent to go by, the faintest guesses go too ("real estate" is not "Sign up free").+ const floor = Math.max(top * (top >= REAL_MATCH ? KEEP_FROM_REAL_MATCH : KEEP_FROM_BEST), fired.length ? 20 : 0);+ const hits = scored+ .filter((x) => x.boost > 0 || x.text + x.bonus >= floor)+ .map((x) => toHit(x.e, Math.max(x.text, x.boost) + 0.1 * Math.min(x.text, x.boost) + x.bonus))+ .sort((a, b) => b.score - a.score);++ // Only real matches are "best" (and so what Enter opens): a word that merely appears in a name is listed by kind.+ // A single long word that matches nothing as written is a typo ("cinma"), and its guess is the match.+ const strong = fired.length > 0 || top >= BEST_FROM || (words.length === 1 && words[0].length >= GUESS_FROM);+ const best = strong ? hits.slice(0, 3) : [];+ const also = (strong ? hits.slice(3) : [])+ .filter((h) => (h.kind === "app" || h.kind === "motion" || h.kind === "effect") && h.score >= REAL_MATCH)+ .slice(0, 2)+ .map((h) => ({ ...h, from: KIND_LABELS[h.kind as PaletteKind] }));+ const shown = new Set([...best, ...also].map((h) => h.key));+ const byGroup = new Map<string, { kind: string; label: string; limit: number; hits: NavHit[] }>();+ for (const h of hits) {+ if (shown.has(h.key)) continue;+ const g = groupOf(h.kind);+ const list = byGroup.get(g.kind) ?? { ...g, hits: [] };+ if (list.hits.length < g.limit) list.hits.push(h);+ byGroup.set(g.kind, list);+ }+ const groups = [...byGroup.values()]+ .sort((a, b) => b.hits[0].score - a.hits[0].score || GROUP_ORDER.indexOf(a.kind) - GROUP_ORDER.indexOf(b.kind))+ .map(({ kind, label, hits }) => ({ kind, label, hits }));+ return { best, also, groups };+}++// ---------------------------------------------------------------------------+// Entries++const HIT_KIND: Record<NavKind, HitKind> = {+ home: "page",+ action: "page",+ create: "page",+ presets: "page",+ library: "page",+ studio: "studio",+ tool: "tool",+ settings: "setting",+};++/** A nav entry as the palette searches it: a tool under its studio ("Audio › Clean up voice"), with its studio's cover. */+export function navSearchEntry(e: NavEntry): SearchEntry {+ const parent = e.parent ? navEntry(e.parent) : undefined;+ return {+ key: `nav:${e.id}`,+ kind: HIT_KIND[e.kind],+ id: e.id,+ label: e.label,+ href: e.href,+ hint: parent?.label ?? (e.kind === "settings" ? "Settings" : undefined),+ // A tool is found by its studio's name too ("upscale video", "audio music").+ keywords: parent ? `${e.keywords} ${parent.label} ${parent.keywords}` : e.keywords,+ what: e.what,+ navKind: e.kind,+ icon: e.icon,+ ...((e.cover ?? parent?.cover) && { cover: e.cover ?? parent?.cover }),+ ...(e.popular && { popular: true }),+ };+}++/** The palette's entries for a set of nav entries (entriesFor(kind): nothing a viewer can't see is ever searched). */+export function navSearchEntries(entries: readonly NavEntry[]): SearchEntry[] {+ return entries.map(navSearchEntry);+}++/** Whether a hit is a page on this site (else an action: the theme, or a link to open in a new tab). */+export const isThemeAction = (href: string) => href === THEME_ACTION;+export const isExternal = (href: string) => /^https?:/.test(href);diff --git a/src/lib/nav.ts b/src/lib/nav.tsindex 682b7731..7fecbae4 100644--- a/src/lib/nav.ts+++ b/src/lib/nav.ts@@ -1,31 +1,11 @@-/** Sidebar helpers (pure, so they're testable): active state, and the remembered group and collapse state. */--/** Group labels the user collapsed, in localStorage. */-export const NAV_CLOSED_KEY = "fuobe:nav-closed";-/**- * Folded until the user opens them (nothing remembered yet). Every group starts open, so a first visit shows- * that the studios exist. ⌘K reaches folded rows too.- */-export const DEFAULT_NAV_CLOSED: readonly string[] = [];-/** Written by the shadcn SidebarProvider ("true" / "false"). */-export const SIDEBAR_COOKIE = "sidebar_state";+/** App frame helpers (pure, so they're testable): which link is the open page, full-screen studios, the pre-paint script. */export const groupId = (label: string) => label.toLowerCase().replace(/[^a-z0-9]+/g, "-");-/** "New creation" (the sidebar and ⌘K): Home with a fresh composer, so it does more than the Home row. Home drops the flag. */+/** "New creation" (the top bar, the phone's Create sheet): Home with a fresh composer, so it does more than the Home row. Home drops the flag. */export const NEW_CREATION_PARAM = "new";export const NEW_CREATION_HREF = `/?${NEW_CREATION_PARAM}=1`;-/**- * How deep the sidebar's fades are, in px: as much as is hidden past each edge, up to 24 at the top- * and 40 at the bottom. So a few pixels of padding past the edge never dim the last row, and a row- * the edge cuts through is always faded, never cut sharp.- */-export function scrollFades(el: { scrollTop: number; clientHeight: number; scrollHeight: number }): { above: number; below: number } {- const depth = (hidden: number, max: number) => (hidden < 1 ? 0 : Math.round(Math.min(hidden, max)));- return { above: depth(el.scrollTop, 24), below: depth(el.scrollHeight - el.clientHeight - el.scrollTop, 40) };-}-function pathMatches(path: string, pathname: string) {return path === "/" ? pathname === "/" : pathname === path || pathname.startsWith(`${path}/`);}@@ -52,50 +32,30 @@ export function navActive(href: string, pathname: string, search: URLSearchParam});}-/**- * Read the collapsed groups (ids) from storage; tolerant of anything unexpected. Nothing stored (or- * nothing readable) means the defaults; a stored list, even an empty one, is the user's own choice.- */-export function parseClosed(raw: string | null | undefined): string[] {- try {- const v = raw == null ? null : JSON.parse(raw);- return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [...DEFAULT_NAV_CLOSED];- } catch {- return [...DEFAULT_NAV_CLOSED];- }-}--export function sidebarOpenFromCookie(cookie: string): boolean {- return !new RegExp(`(?:^|;\\s*)${SIDEBAR_COOKIE}=false(?:;|$)`).test(cookie);-}--/** The cookie that remembers the expanded/collapsed choice (as the shadcn SidebarProvider writes it). */-export function sidebarCookie(open: boolean): string {- return `${SIDEBAR_COOKIE}=${open}; path=/; max-age=${60 * 60 * 24 * 7}`;-}-/*** Full-screen studios: a project open in Cinema, Canvas or Layers, Assist (with its own rail of- * chats), and Live edit (the picture fills the page). They have a sidebar of their own, so the app sidebar folds to its icon rail while one is- * open, without touching the remembered choice, and comes back on the way out.+ * chats), and Live edit (the picture fills the page). They take the whole screen: on a phone the tab bar steps aside and+ * the header button opens the menu instead.*/const FULL_SCREEN = /^\/(?:(?:cinema|canvas|layers)\/[^/]+\/?|assist(?:\/.*)?|live-edit\/?)$/;/*** Which full-screen studio a path belongs to (null on any other page): the project's own path, or- * "/assist" for every Assist page (its chats, projects, skills and memory are one workspace). The- * sidebar opened by hand stays open while you move inside one studio, and folds again in the next.+ * "/assist" for every Assist page (its chats, projects, skills and memory are one workspace).*/export function fullScreenStudio(pathname: string): string | null {if (!FULL_SCREEN.test(pathname)) return null;return /^\/assist(?:\/|$)/.test(pathname) ? "/assist" : pathname.replace(/\/$/, "");}+/** The bar's pills whose room is kept from the first paint (use-had-items.ts names, remembered by the bar). */+export const CHROME_HAD_PILLS = ["balance", "computer", "placeholders"] as const;+/**- * Inline script that applies the remembered state to the server-rendered sidebar before the first- * paint: the collapsed rail (the cookie, or a full-screen studio) and the folded groups- * (localStorage). The server renders the default folds (DEFAULT_NAV_CLOSED); a remembered list- * opens or folds every foldable group to match. React's first client render reads the same values,- * so hydration matches the patched DOM.+ * Inline script that runs while the HTML is parsed, so the app frame has its final shape on the first paint (the+ * server renders one shell for everyone): `data-fullscreen-studio` on a full-screen studio (the phone's tab bar+ * gives it the whole screen), `data-viewer` as this browser last knew it ("fuobe:viewer", as api.ts's VIEWER_KEY:+ * the bar's right side keeps a guest's or an account's room), and `data-had-<pill>` for the bar's pills it showed+ * last (use-had-items.ts). Every read is guarded: blocked storage leaves the defaults.*/-export const SIDEBAR_STATE_SCRIPT = `(function(){try{var d=document;if(/(?:^|;\\s*)${SIDEBAR_COOKIE}=false(?:;|$)/.test(d.cookie)||${FULL_SCREEN}.test(location.pathname)){var s=d.querySelector('[data-slot="sidebar"]');if(s){s.setAttribute("data-state","collapsed");s.setAttribute("data-collapsible","icon")}}var r=localStorage.getItem("${NAV_CLOSED_KEY}");if(r===null)return;var c=JSON.parse(r);if(!Array.isArray(c))return;d.querySelectorAll("[data-nav-group]").forEach(function(e){var b=e.querySelector("[data-nav-toggle]");if(!b)return;var o=c.indexOf(e.getAttribute("data-nav-group"))<0?"true":"false";e.setAttribute("data-open",o);b.setAttribute("aria-expanded",o)})}catch(e){}})()`;+export const CHROME_STATE_SCRIPT = `(function(){var d=document.documentElement;try{if(${FULL_SCREEN}.test(location.pathname))d.setAttribute("data-fullscreen-studio","")}catch(e){}try{var v=localStorage.getItem("fuobe:viewer");if(v==="guest"||v==="account"||v==="owner")d.setAttribute("data-viewer",v)}catch(e){}try{${JSON.stringify(CHROME_HAD_PILLS)}.forEach(function(n){var x=localStorage.getItem("fuobe:had:"+n);if(x&&/^[1-9][0-9]?$/.test(x))d.setAttribute("data-had-"+n,x)})}catch(e){}})()`;diff --git a/src/lib/next-steps.ts b/src/lib/next-steps.tsnew file mode 100644index 00000000..981a3738--- /dev/null+++ b/src/lib/next-steps.ts@@ -0,0 +1,148 @@+/**+ * "Keep going with this": three to five next steps under a finished result, each opening the studio or app that+ * takes it further with the result already in it. Built on outputActions() (src/lib/output-actions.ts), so a step+ * goes through the same hand-off URL as the result's own menu, and what a guest or an account can't open is left+ * out the same way. Pure: components/nav/next-steps.tsx renders it.+ */+import { animateSpinHref, model3dView } from "./av/model3d";+import type { Generation } from "./catalog/types";+import { STEP_COVERS } from "./nav-model";+import { isVector, nextSteps, outputActions, type ActionContext, type OutputActionId } from "./output-actions";++export interface NextStep {+ /** Unique within one list ("animate", "upscale"). */+ id: string;+ /** What it does, short ("Animate it"). */+ verb: string;+ /** Where it opens ("Video"). */+ where: string;+ href: string;+ /** A preset id with a real cover (nav-covers.ts resolves it). */+ cover?: string;+}++export interface KeepGoingContext {+ engineMode?: "both" | "open" | "cloud";+ /** A guest or an account: hand-offs to tools only a self-hosted Fuobe runs are left out. */+ visitor?: boolean;+ /** Studios that read ?image= on arrival; until they do, no step links to them. */+ adapters?: { characterSheet?: boolean; imageTo3d?: boolean };+}++const q = (url: string) => encodeURIComponent(url);++const PERSON_WORDS = /\b(model|models|woman|women|man|men|girl|girls|boy|boys|person|people|portrait|face|she|he|her|his|influencer|actor|actress|outfit|dress)\b/g;+const PRODUCT_WORDS = /\b(product|products|bottle|perfume|fragrance|shoe|shoes|sneaker|sneakers|bag|handbag|watch|ring|packshot|ad|advert|cosmetic|lipstick|skincare)\b/g;+/** Results from a studio about people, or about selling. */+const PEOPLE_FEATURES = /^(fashion|photodump|influencer|character-sheet|swap-studio|genjutsu|lipsync|motion-control|elements)/;+const PRODUCT_FEATURES = /^(marketing|ads|ad-multiplier|click-to-ad|product)/;++/** Whether a picture is of someone, of a product, or something else: its studio first, then its words. */+export function imageSubject(g: Pick<Generation, "feature" | "prompt" | "presetId" | "request">): "person" | "product" | "other" {+ if (PEOPLE_FEATURES.test(g.feature ?? "")) return "person";+ if (PRODUCT_FEATURES.test(g.feature ?? "")) return "product";+ const words = `${g.prompt ?? g.request?.prompt ?? ""} ${(g.presetId ?? g.request?.presetId ?? "").replace(/-/g, " ")}`.toLowerCase();+ const person = words.match(PERSON_WORDS)?.length ?? 0;+ const product = words.match(PRODUCT_WORDS)?.length ?? 0;+ if (product > person) return "product";+ if (person) return "person";+ return "other";+}++/** A video's next steps from the result's own hand-offs (outputActions), with their words here. */+const VIDEO_STEPS: Partial<Record<OutputActionId, { verb: string; where: string; cover?: string }>> = {+ grade: { verb: "Color grade", where: "Color grading", cover: STEP_COVERS.grade },+ extend: { verb: "Make it longer", where: "Extend video", cover: STEP_COVERS.extend },+ upscale: { verb: "Sharpen to 4K", where: "Upscale", cover: STEP_COVERS.upscale },+ regenerate: { verb: "Regenerate in 2K", where: "Upscale", cover: STEP_COVERS.upscale },+ "add-sound": { verb: "Add sound", where: "Audio", cover: STEP_COVERS.sound },+ "split-soundtrack": { verb: "Split voice and music", where: "Audio", cover: STEP_COVERS.split },+ "remove-dialogue": { verb: "Remove dialogue", where: "Video tools" },+ reframe: { verb: "Reframe for phones", where: "Reframe", cover: STEP_COVERS.reframe },+ genjutsu: { verb: "Swap who is in it", where: "Genjutsu", cover: STEP_COVERS.swap },+};++/**+ * Up to `max` next steps for output `index` of `g`, best first. Nothing for a result that failed, was deleted, is+ * text, or is a vector (the hand-offs read pixels).+ */+export function keepGoing(g: Generation, index: number, ctx: KeepGoingContext = {}, max = 5): NextStep[] {+ const o = g.outputs[index];+ if (!o || g.status !== "succeeded" || g.deletedAt || o.kind === "text") return [];+ if (o.kind === "image" && isVector(g, o)) return [];+ const actx: ActionContext = { engineMode: ctx.engineMode, visitor: ctx.visitor };+ const steps: NextStep[] = [];+ const add = (s: NextStep | null | undefined | false) => {+ if (s && !steps.some((x) => x.id === s.id)) steps.push(s);+ };++ switch (o.kind) {+ case "image": {+ const U = q(o.url);+ const animate: NextStep = { id: "animate", verb: "Animate it", where: "Video", href: `/video?image=${U}`, cover: STEP_COVERS.animate };+ const upscale: NextStep = { id: "upscale", verb: "Sharpen to 4K", where: "Upscale", href: `/upscale?image=${U}`, cover: STEP_COVERS.upscale };+ const edit: NextStep = { id: "edit", verb: "Change it with words", where: "Edit", href: `/edit?image=${U}`, cover: STEP_COVERS.edit };+ const threeD = ctx.adapters?.imageTo3d && { id: "image-to-3d", verb: "Turn it into 3D", where: "Image to 3D", href: `/image-to-3d?image=${U}`, cover: STEP_COVERS.threeD };+ const subject = imageSubject(g);+ if (subject === "person") {+ add(animate);+ add({ id: "talk", verb: "Make it talk", where: "Lipsync & avatars", href: `/lipsync?image=${U}`, cover: STEP_COVERS.talk });+ add(ctx.adapters?.characterSheet && { id: "character-sheet", verb: "Make a character sheet", where: "Character Sheet", href: `/character-sheet?image=${U}`, cover: STEP_COVERS.sheet });+ add({ id: "billboard", verb: "Put it in an ad", where: "Billboard ad", href: `/apps/app-billboard-ad?image=${U}`, cover: STEP_COVERS.billboard });+ add(upscale);+ } else if (subject === "product") {+ add(animate);+ add({ id: "giant", verb: "Put it in an ad", where: "Giant product", href: `/apps/app-giant-product?image=${U}`, cover: STEP_COVERS.giant });+ add(threeD);+ add(upscale);+ add(edit);+ } else {+ add(animate);+ add(edit);+ add(upscale);+ add({ id: "grade", verb: "Color grade", where: "Color grading", href: `/color-grade?image=${U}`, cover: STEP_COVERS.grade });+ add(threeD);+ }+ break;+ }+ case "video": {+ // Today's order first (a grade still to apply, Extend, Upscale or Regenerate, sound), then the rest.+ for (const a of nextSteps(g, index, 5, actx)) {+ const words = VIDEO_STEPS[a.id];+ // A grade to apply says which one ("Apply the Teal & Orange grade").+ if (words && a.href) add({ id: a.id, ...words, ...(a.id === "grade" && { verb: a.label }), href: a.href });+ }+ const all = outputActions(g, index, actx);+ for (const id of ["extend", "upscale", "add-sound", "reframe", "genjutsu"] as const) {+ const a = all.find((x) => x.id === id && x.href);+ if (a?.href && VIDEO_STEPS[id]) add({ id, ...VIDEO_STEPS[id], href: a.href });+ }+ break;+ }+ case "audio": {+ const all = outputActions(g, index, actx);+ const pick = (id: OutputActionId, verb: string, where: string, cover?: string) => {+ const a = all.find((x) => x.id === id && x.href);+ return a?.href ? { id, verb, where, href: a.href, ...(cover && { cover }) } : null;+ };+ add(pick("lipsync", "Make a photo say it", "Lipsync & avatars", STEP_COVERS.talk));+ add(pick("voice-change", "Change the voice", "Audio", STEP_COVERS.voice));+ add(pick("loop-audio", "Loop or extend", "Audio", STEP_COVERS.split));+ add(pick("split-soundtrack", "Split voice and music", "Audio", STEP_COVERS.split));+ add(pick("clean-voice", "Clean up voice", "Audio", STEP_COVERS.clean));+ break;+ }+ case "model3d": {+ const view = model3dView(g);+ const spin = animateSpinHref(view);+ if (spin) add({ id: "animate-spin", verb: "Animate the spin", where: "Video", href: spin, cover: STEP_COVERS.animate });+ if (view.poster) {+ const P = q(view.poster);+ add({ id: "product-360", verb: "Put it in an ad", where: "Product 360", href: `/apps/app-product-360?image=${P}`, cover: STEP_COVERS.spin });+ add({ id: "upscale", verb: "Sharpen the still", where: "Upscale", href: `/upscale?image=${P}`, cover: STEP_COVERS.upscale });+ }+ break;+ }+ }+ return steps.slice(0, max);+}diff --git a/src/lib/palette-index.ts b/src/lib/palette-index.tsindex cc75698c..d2309c24 100644--- a/src/lib/palette-index.ts+++ b/src/lib/palette-index.ts@@ -8,6 +8,7 @@ import { enginesOf } from "@/lib/catalog/engines";import { OPERATION_LABELS, type ModelDef, type Operation, type Preset } from "@/lib/catalog/types";import type { PaletteIndex, PaletteModel, PalettePreset } from "@/lib/command-search";import { TOOL_MODELS } from "@/lib/layers";+import { presetCover } from "@/lib/preset-covers";import type { StudioConfig } from "@/components/studio/studio-context";import {AUDIO_STUDIO,@@ -94,7 +95,18 @@ export function modelHref(m: ModelDef): string {return KIND_HOME[m.kind];}-const preset = (p: Preset): PalettePreset => ({ id: p.id, name: p.name, category: p.category, cloud: !!p.cloud, open: !!p.open });+/** A still at the usual place travels as its version alone (presetThumb, command-search.ts, rebuilds the URL). */+function coverOf(id: string): string | undefined {+ const c = presetCover(id);+ if (!c) return undefined;+ const usual = new RegExp(`^/previews/presets/${id}\\.jpg\\?v=([0-9a-f]+)$`).exec(c.poster);+ return usual ? usual[1] : c.poster;+}++const preset = (p: Preset): PalettePreset => {+ const cover = coverOf(p.id);+ return { id: p.id, name: p.name, category: p.category, cloud: !!p.cloud, open: !!p.open, ...(cover && { cover }) };+};const model = (m: ModelDef): PaletteModel => ({id: m.id,diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.tsindex 95ef4410..799dda1b 100644--- a/src/server/account-gpu.ts+++ b/src/server/account-gpu.ts@@ -179,7 +179,7 @@ export interface VisitorView {* connecting a GPU of its own is optional.*/hosted?: boolean;- /** The billing service's words for the account's balance (billing.ts): the sidebar chip and its menu. */+ /** The billing service's words for the account's balance (billing.ts): the top bar's chip and the account menu. */balance?: Balance;/** Extra links the billing service sends for the menu. */links?: Action[];diff --git a/tests/command-palette.test.ts b/tests/command-palette.test.tsindex 48556d77..d938fbea 100644--- a/tests/command-palette.test.ts+++ b/tests/command-palette.test.ts@@ -6,6 +6,8 @@ import { APPS, EFFECTS, getModel, MODELS, MOTIONS } from "@/lib/catalog";import { entryScore, indexEntries, normalize, rankPalette, skillEntries, wordScore, type PaletteEntry } from "@/lib/command-search";import { modelHref, paletteIndex } from "@/lib/palette-index";import { rowPriceOn, toModelRow } from "@/lib/model-rows";+import { entriesFor, type ViewerKind } from "@/lib/nav-model";+import { navSearchEntries } from "@/lib/nav-search";import { hubModePaths, studioRoutes } from "./e2e/_routes.mjs";const page = (label: string, href: string, keywords?: string): PaletteEntry => ({ key: `page:${href}`, kind: "page", label, href, keywords });@@ -128,7 +130,9 @@ describe("palette index", () => {expect(index.models).toHaveLength(MODELS.filter((m) => !m.hidden).length);// No prompt templates, routes or LoRA URLs: the whole thing stays small.expect(JSON.stringify(index).length).toBeLessThan(160_000);- expect(Object.keys(index.apps[0]).sort()).toEqual(["category", "cloud", "id", "name", "open"]);+ // A cover travels as a version (a still at the usual place) or a URL, so the palette shows the real cover.+ for (const p of [...index.apps, ...index.motions, ...index.effects]) for (const k of Object.keys(p)) expect(["category", "cloud", "cover", "id", "name", "open"], k).toContain(k);+ expect(index.apps.find((a) => a.id === "app-giant-product")?.cover).toMatch(/^[0-9a-f]{8}$/);});it("opens every model somewhere that exists, in a studio of its kind when there is one", () => {@@ -171,9 +175,11 @@ describe("palette index", () => {it("opens every page and settings section the palette lists", () => {for (const p of PAGES) expect(routes.paths.has(pathOf(p.href)), p.href).toBe(true);+ // The owner's settings sections (the navigation model's, src/lib/nav-model.ts) are in the settings form.const form = fs.readFileSync(path.resolve(__dirname, "../src/components/settings-form.tsx"), "utf8");- const palette = fs.readFileSync(path.resolve(__dirname, "../src/components/command-palette.tsx"), "utf8");- const ids = [...palette.matchAll(/\{ id: "([a-z-]+)", label:/g)].map((m) => m[1]);+ const ids = entriesFor("owner")+ .filter((e) => e.id.startsWith("setting-"))+ .map((e) => e.href.split("#")[1]);expect(ids.length).toBeGreaterThan(4);for (const id of ids) expect(form, `settings section #${id}`).toContain(`id="${id}"`);});@@ -205,18 +211,23 @@ describe("palette index", () => {});describe("palette settings by viewer", () => {- it("offers the install's settings to its owner only; an account gets its own GPU, its own keys, its account and the licences", async () => {- const { settingEntries } = await import("@/components/command-palette");- const hrefs = (v: Parameters<typeof settingEntries>[0]) => settingEntries(v).map((e) => e.href);- expect(hrefs({ owner: true })).toEqual(expect.arrayContaining(["/settings#engine", "/settings#cloud", "/settings#security", "/settings/models", "/settings/licences"]));- expect(hrefs({ owner: false, account: { email: "[email protected]" } })).toEqual(["/settings#your-gpu", "/settings#your-keys", "/settings#account", "/settings/licences"]);+ /** The settings a viewer's search offers (src/lib/nav-model.ts): sections, pages and Connect your GPU. */+ const hrefs = (kind: ViewerKind | undefined) =>+ navSearchEntries(entriesFor(kind))+ .filter((e) => e.kind === "setting")+ .map((e) => e.href)+ .sort();++ it("offers the install's settings to its owner only; an account gets its own GPU, its own keys, its account and Thanks & licences", () => {+ expect(hrefs("owner")).toEqual(expect.arrayContaining(["/settings#engine", "/settings#cloud", "/settings#security", "/settings/models", "/settings/licences", "/settings"]));+ expect(hrefs("account")).toEqual(["/connect", "/settings", "/settings#account", "/settings#your-gpu", "/settings#your-keys", "/settings/licences"]);// "api key", "fal", "nano banana": an account finds where its own key goes.- const keys = settingEntries({ owner: false, account: { email: "[email protected]" } }).find((e) => e.href === "/settings#your-keys");+ const keys = navSearchEntries(entriesFor("account")).find((e) => e.href === "/settings#your-keys");expect(keys?.keywords).toMatch(/api key/);expect(keys?.keywords).toMatch(/nano banana/);- expect(hrefs({ owner: false })).toEqual(["/connect", "/settings/licences"]);+ expect(hrefs("guest")).toEqual(["/connect", "/settings", "/settings/licences"]);// Not known yet: nothing of the owner's.- expect(hrefs(undefined)).toEqual(["/connect", "/settings/licences"]);+ expect(hrefs(undefined)).toEqual(["/connect", "/settings", "/settings/licences"]);});});diff --git a/tests/e2e/character-swap-studio.mjs b/tests/e2e/character-swap-studio.mjsindex c2d20917..d46dca09 100644--- a/tests/e2e/character-swap-studio.mjs+++ b/tests/e2e/character-swap-studio.mjs@@ -2,7 +2,7 @@// character, a clip, Detect edits, a cut at the playhead and Keep original, the transcript and Build shot prompts, a// click on a frame and Track shot, a mask and a scene anchor approved, two segments (the second continuing from the// first, waiting for it), takes made, compared and reviewed, Export decisions, and the assembly with a download. Then every stage at 1440 and 390 px, light and dark, without sideways scroll;-// a project on your GPU shows its 24 fps copy; an AVI on the cloud gets a copy the browser can play; the sidebar links+// a project on your GPU shows its 24 fps copy; an AVI on the cloud gets a copy the browser can play; the Studios launcher links// here and Genjutsu's Character swap opens its clip and character in a new project; an unknown project is a 404.// Usage: node tests/e2e/character-swap-studio.mjs [appUrl] [--shots <dir>] (app in demo mode, ComfyUI unreachable).// Exits 1 on a failed check.@@ -59,7 +59,10 @@ try {await page.goto(`${app}/character-swap`, { waitUntil: "load", timeout: 180_000 });await page.getByRole("heading", { name: "Swap a character through whole clips" }).waitFor({ timeout: 120_000 });check("projects page: hero and steps", (await text()).includes("Who and the scene"));- check("sidebar links the studio", (await page.locator('a[href="/character-swap"]').count()) > 0);+ await page.getByRole("button", { name: /^Studios/ }).click();+ const launcher = page.getByRole("region", { name: "All studios" });+ check("the Studios launcher links the studio", (await launcher.locator('a[href="/character-swap"]').count()) > 0);+ await page.keyboard.press("Escape");await page.getByPlaceholder("Project name, e.g. Rain scene").fill("Rain scene");await page.getByRole("button", { name: /New project · cloud/ }).click();await page.waitForURL(/\/character-swap\/swap-/, { timeout: 60_000 });diff --git a/tests/e2e/cinema-blockout.mjs b/tests/e2e/cinema-blockout.mjsindex 8b9df252..678896a0 100644--- a/tests/e2e/cinema-blockout.mjs+++ b/tests/e2e/cinema-blockout.mjs@@ -69,10 +69,7 @@ async function open(ctx, engine, query = "") {await ctx.addInitScript((e) => localStorage.setItem("fuobe.engine", e), engine);await hideDevBadge(ctx);const page = await ctx.newPage();- // The app sidebar's hydration mismatch at desktop width (its Suspense fallback, ViewerRowPlaceholder) is the base- // branch's: it shows on /image and on /cinema with no blockout at all (2026-11-01). Any other mismatch counts.- const known = (m) => /^Hydration failed/.test(m) && /ViewerRowPlaceholder/.test(m) && !/Blockout/.test(m);- page.on("pageerror", (e) => !known(e.message) && errors.push(e.message));+ page.on("pageerror", (e) => errors.push(e.message));await page.goto(`${app}/cinema/${project.id}${query}`, { waitUntil: "load", timeout: 120_000 });return page;}diff --git a/tests/e2e/computer-mode.mjs b/tests/e2e/computer-mode.mjsindex 29fe71bc..b55a439d 100644--- a/tests/e2e/computer-mode.mjs+++ b/tests/e2e/computer-mode.mjs@@ -28,6 +28,13 @@ const check = (name, ok, detail = "") => {console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? ` — ${detail}` : ""}`);};const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+// The computer note: the top bar's pill says it (a live region inside it), and its popover holds the note's one action.+const pillNote = (page) => page.locator("[data-computer-note]");+async function openPill(page) {+ const pop = page.locator('[data-slot="popover-content"]');+ if (!(await pop.isVisible().catch(() => false))) await page.getByRole("button", { name: /your computer's GPU/i }).click({ timeout: 5_000 }).catch(() => {});+ return pop;+}async function until(fn, ms = 30_000, every = 250) {const end = Date.now() + ms;@@ -224,9 +231,9 @@ try {})();const tile = await until(() => page.getByText("Keep this tab open", { exact: true }).first().isVisible(), 30_000);check("the run's tile says to keep this tab open", !!tile);- const note = page.locator('[data-sidebar="footer"] [role="status"]').filter({ hasText: "Your GPU is working. Keep this tab open." });- const noted = await until(() => note.isVisible(), 20_000);- check("the note says the GPU is working, in the sidebar's own space", !!noted);+ const note = pillNote(page).filter({ hasText: "Your GPU is working. Keep this tab open." });+ const noted = await until(async () => (await note.count()) > 0, 20_000);+ check("the bar's computer pill says the GPU is working", !!noted);// Nothing of Fuobe's own sits over the page's buttons (the newest run's Reuse and More among them).const covered = await page.evaluate(() =>[...document.querySelectorAll("#content button")]@@ -311,10 +318,12 @@ try {await page.screenshot({ path: path.join(shots, "7-setting-again.png") });const seen = new Set();for (let end = Date.now() + 12_000; Date.now() < end; await sleep(250)) {- const t = await page.locator('[data-sidebar="footer"] [role="status"]').first().textContent().catch(() => null);+ const t = await pillNote(page).first().textContent().catch(() => null);if (t) seen.add(t);}- check("the note says the setting is missing, steadily, with its fix", seen.size > 0 && [...seen].every((t) => t.includes("without Fuobe's setting") && t.includes("Show me how")), [...seen].join(" | "));+ check("the note says the setting is missing, steadily", seen.size > 0 && [...seen].every((t) => t.includes("without Fuobe's setting")), [...seen].join(" | "));+ check("…with its fix in the pill's popover", await (await openPill(page)).getByRole("button", { name: "Show me how" }).isVisible());+ await page.keyboard.press("Escape");const waiting = (await runs(page)).find((g) => g.id === rid);check("the run says the same", waiting?.message === "ComfyUI is running, but Fuobe can't use it yet. Install Fuobe Connect in ComfyUI, and Fuobe goes on by itself.", waiting?.message);check("the status strip doesn't say all is well", !!(await until(() => page.getByText("needs a setting").first().isVisible(), 15_000)));@@ -332,8 +341,9 @@ try {await stopFake();const r = await api(page, "/api/generations", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a quiet harbour" }) });const rid = r.body?.items?.[0]?.id;- const down = await until(() => page.locator('[data-sidebar="footer"] [role="status"]').filter({ hasText: "ComfyUI isn't answering" }).isVisible(), 30_000);- check("ComfyUI closed: the note says so, with a way to find it", !!down && (await page.getByRole("button", { name: "Find my ComfyUI" }).isVisible()));+ const down = await until(async () => (await pillNote(page).filter({ hasText: "ComfyUI isn't answering" }).count()) > 0, 30_000);+ check("ComfyUI closed: the note says so, with a way to find it", !!down && (await (await openPill(page)).getByRole("button", { name: "Find my ComfyUI" }).isVisible()));+ await page.keyboard.press("Escape");const waiting = await until(async () => (await runs(page)).find((g) => g.id === rid && g.message === "ComfyUI isn't answering. Start it again, and Fuobe goes on by itself."), 20_000);check("the run says ComfyUI isn't answering", !!waiting);check("the status strip says ComfyUI isn't running", !!(await until(() => page.getByText("ComfyUI not running").first().isVisible(), 20_000)));@@ -394,11 +404,11 @@ try {await page.goto(`${SITE}/library`, { waitUntil: "load" });const r = await api(page, "/api/generations", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a paper boat" }) });const rid = r.body?.items?.[0]?.id;- const ask = page.locator('[data-sidebar="footer"] [role="status"]').filter({ hasText: "Run them from this browser?" });- check("a browser not allowed yet: its note asks first", !!(await until(() => ask.isVisible(), 30_000)));+ const ask = pillNote(page).filter({ hasText: "Run them from this browser?" });+ check("a browser not allowed yet: its note asks first", !!(await until(async () => (await ask.count()) > 0, 30_000)));check("…and it never reached an app on this computer by itself", ctx.loopback.length === 0, ctx.loopback.slice(0, 3).join(" "));await page.evaluate((port) => localStorage.setItem("fuobe.comfy.port", String(port)), FAKE_PORT);- await ask.getByRole("button", { name: "Connect" }).click();+ await (await openPill(page)).getByRole("button", { name: "Connect" }).click();const card = page.getByRole("dialog");await card.getByText("Run your GPU jobs from this browser").waitFor({ timeout: 15_000 });check("the card explains the browser's question before it comes", await card.getByText("Press Allow. Fuobe only talks to ComfyUI.").isVisible());diff --git a/tests/e2e/instant-tabs.mjs b/tests/e2e/instant-tabs.mjsindex 86b8b4ee..4b893e16 100644--- a/tests/e2e/instant-tabs.mjs+++ b/tests/e2e/instant-tabs.mjs@@ -163,7 +163,7 @@ try {const answered = frames.find((f) => f.path === sw.to || f.skeleton);check(answered && answered.ms <= 120, `neither ${sw.to} nor its skeleton showed within 100 ms (first at ${answered?.ms} ms)`);if (settled) {- // Once the page has settled every mode is prefetched (ahead of the sidebar's routes): the switch is drawn from the+ // Once the page has settled every mode is prefetched (ahead of the navigation's routes): the switch is drawn from the// client cache, with no request and no skeleton.const asked = rsc.slice(before).filter((r) => !r.prefetch);check(!asked.length, `the switch waited for the server: ${asked.map((r) => r.url.replace(app, "")).join(", ")}`);@@ -285,20 +285,29 @@ try {await ctx.close();}- if (step("desktop: sidebar Image → Audio never blanks the content area")) {+ if (step("desktop: Studios launcher Image → Audio never blanks the content area")) {const { ctx, page } = await context("desktop");await openRoute(page, `${app}/image`, { settleMs: 4000 });- const audio = page.locator('[data-sidebar="sidebar"]').getByRole("link", { name: /^Audio$/ }).first();- const row = '[data-sidebar="sidebar"] [data-active="true"]';- const frames = await sampleSwitch(page, audio, "desktop", { bar: HUB.bar, body: HUB.body, current: row }, (f) => f.path === "/audio" && f.bar && f.body > 0 && !f.skeleton);+ await page.locator("[data-top-bar]").getByRole("button", { name: /^Studios/ }).click();+ const audio = page.locator("#studios-launcher").getByRole("link", { name: /^Audio/ }).first();+ await audio.waitFor();+ const frames = await sampleSwitch(page, audio, "desktop", { bar: HUB.bar, body: HUB.body, current: HUB.current }, (f) => f.path === "/audio" && f.bar && f.body > 0 && !f.skeleton);const blank = frames.filter((f) => f.content === 0);check(!blank.length, `the content area was blank in ${blank.length} frame(s), from ${blank[0]?.ms} ms`);- const moved = frames.findIndex((f) => f.current === "Audio");- check(moved >= 0 && moved <= 1, `the Audio row became the open page's only at frame ${moved} (${frames[moved]?.ms} ms)`);const last = frames[frames.length - 1];check(last.path === "/audio" && last.bar, `Audio did not land with its tabs (last frame ${JSON.stringify(last)})`);await ctx.close();}++ if (step("desktop: the bar's Library is marked the frame after the click")) {+ const { ctx, page } = await context("desktop");+ await openRoute(page, `${app}/image`, { settleMs: 4000 });+ const library = page.locator("[data-top-bar]").getByRole("link", { name: "Library", exact: true });+ const frames = await sampleSwitch(page, library, "desktop", { current: '[data-top-bar] a[aria-current="page"]' }, (f) => f.path === "/library");+ const moved = frames.findIndex((f) => f.current === "Library");+ check(moved >= 0 && moved <= 1, `Library became the open page's item only at frame ${moved} (${frames[moved]?.ms} ms)`);+ await ctx.close();+ }} finally {await browser.close();}diff --git a/tests/e2e/nav.mjs b/tests/e2e/nav.mjsnew file mode 100644index 00000000..d3aa91a1--- /dev/null+++ b/tests/e2e/nav.mjs@@ -0,0 +1,560 @@+// The navigation in a real browser: the top bar and its Studios launcher, the search palette, the phone's tabs and+// sheets, Home's goal row, the next steps under a result and the explore count.+// Usage: node tests/e2e/nav.mjs [appUrl] [shotsDir]+// The app must be running with placeholders on (Settings → demo mode), so a result can be made without a key.+// E2E_OWNER_PASSWORD: the studio's password, when it has one (the owner's checks sign in with it; a studio without+// one is the owner's). Account checks need public sign-up; they make throwaway qa accounts and delete them.+// Exits 1 if any check fails; screenshots (dark and light, 1440x900 and 390x844) go to shotsDir when given.+import fs from "node:fs";+import path from "node:path";+import { DESKTOP, launch, openRoute, PHONE } from "./_browser.mjs";++const args = process.argv.slice(2).filter((a) => !a.startsWith("--"));+const app = (args[0] ?? "http://localhost:3000").replace(/\/$/, "");+const shots = args[1];+if (shots) fs.mkdirSync(shots, { recursive: true });+const failures = [];+const check = (ok, what, detail = "") => {+ console.log(`${ok ? "✓" : "✗"} ${what}${!ok && detail ? ` (${detail})` : ""}`);+ if (!ok) failures.push(what);+};+const shot = async (page, name) => shots && (await page.screenshot({ path: path.join(shots, `${name}.png`) }));+const me = async (ctx) => (await (await ctx.request.get(`${app}/api/auth/me`)).json().catch(() => null)) ?? {};+const publicSignup = !!(await fetch(`${app}/api/auth/me`).then((r) => r.json()).catch(() => null))?.publicSignup;+const VISITOR_WORDS = ["ComfyUI", "add key", "offline", "Paid APIs only", "Open source only", "Placeholder"];++const browser = await launch();+const accounts = [];++/** A browser context as `who`: "guest", "owner" (signed in when the studio has a password) or "account" (signed up). */+async function as(who, device = DESKTOP, extra = {}) {+ const ctx = await browser.newContext({ ...device, ...extra });+ ctx.errors = [];+ if (who === "owner" && process.env.E2E_OWNER_PASSWORD) await ctx.request.post(`${app}/api/auth/login`, { data: { password: process.env.E2E_OWNER_PASSWORD } });+ if (who === "account") {+ const email = `qa-nav-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}@example.com`;+ const password = `Qa-${Math.random().toString(36).slice(2)}-${Date.now()}`;+ const res = await ctx.request.post(`${app}/api/auth/signup`, { data: { email, password } });+ if (!res.ok()) throw new Error(`sign-up answered ${res.status()}`);+ accounts.push({ ctx, password });+ }+ const kind = await me(ctx);+ if (who === "owner" && !kind.owner) throw new Error("couldn't sign in as the owner (set E2E_OWNER_PASSWORD)");+ return ctx;+}+async function page(ctx) {+ const p = await ctx.newPage();+ p.on("pageerror", (e) => ctx.errors.push(e.message.split("\n")[0]));+ p.on("console", (m) => m.type() === "error" && !/Failed to load resource/.test(m.text()) && ctx.errors.push(m.text().slice(0, 200)));+ return p;+}+const focused = (p) =>+ p.evaluate(() => {+ const a = document.activeElement;+ if (!a || a === document.body) return null;+ const style = getComputedStyle(a);+ const ring = (style.outlineStyle !== "none" && parseFloat(style.outlineWidth) > 0) || (style.boxShadow && style.boxShadow !== "none");+ return { name: (a.getAttribute("aria-label") || a.textContent || "").replace(/\s+/g, " ").trim(), ring, col: a.getAttribute("data-col"), row: a.getAttribute("data-row"), href: a.getAttribute("href") };+ });+const inView = (loc) =>+ loc.evaluateAll((els) =>+ els.map((e) => {+ const r = e.getBoundingClientRect();+ return r.width > 0 && r.top >= 0 && r.left >= 0 && r.bottom <= innerHeight && r.right <= innerWidth;+ }),+ );+const sideScroll = (p) => p.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);++try {+ // 1. Keyboard order and focus rings, desktop.+ {+ const ctx = await as("guest");+ const p = await page(ctx);+ await openRoute(p, `${app}/image`);+ const order = [];+ let rings = true;+ for (let i = 0; i < 12; i++) {+ await p.keyboard.press("Tab");+ const f = await focused(p);+ order.push(f?.name ?? "");+ if (i > 0 && !f?.ring) rings = false;+ }+ const want = ["Skip to content", "Fuobe home", "Create", /^Studios/, "Apps", "Motions & effects", "Canvas", "Assist", "Library", /^Search/, "New creation"];+ const ok = want.every((w, i) => (typeof w === "string" ? order[i] === w : w.test(order[i])));+ check(ok, "Tab order: Skip, wordmark, Create, Studios, Apps, Motions & effects, Canvas, Assist, Library, Search, New creation", order.join(" › "));+ check(rings, "every bar stop shows a focus ring");+ // The search field is 280 px from 1440 (an lg rule must not win over it) and its name is the words it shows.+ const field = await p.locator('[data-top-bar] button[aria-keyshortcuts="/ Meta+K Control+K"]').evaluate((b) => ({ w: b.getBoundingClientRect().width, text: b.innerText.trim(), label: b.getAttribute("aria-label") }));+ check(field.w >= 270 && field.text.startsWith("Search studios, apps, effects…") && !field.label, "search field: 280 px at 1440, its name is its visible words", JSON.stringify(field));+ // Hovering the bar loads no routes ahead; opening the launcher loads its own.+ const reqs = [];+ p.on("request", (r) => r.headers()["next-router-prefetch"] && reqs.push(r.url()));+ await p.locator("[data-top-bar]").getByRole("link", { name: "Fuobe home" }).hover();+ await p.locator("[data-top-bar]").getByRole("link", { name: "Library", exact: true }).hover();+ await p.mouse.move(700, 500);+ await p.waitForTimeout(3000);+ const onHover = reqs.length;+ await p.locator("[data-top-bar]").getByRole("button", { name: /^Studios/ }).click();+ await p.waitForTimeout(3000);+ check(onHover <= 3 && reqs.length > onHover, "prefetch: hovering the bar loads at most the hovered links; opening Studios loads its routes", `${onHover} on hover, ${reqs.length} after opening`);+ await p.keyboard.press("Escape");+ await ctx.close();+ }++ // 2. The Studios launcher: keys, fit, a pick, and the active marks.+ {+ const ctx = await as("guest");+ const p = await page(ctx);+ await openRoute(p, `${app}/image`);+ const trigger = p.locator("[data-top-bar]").getByRole("button", { name: /^Studios/ });+ const panel = p.locator("#studios-launcher");+ const heading = p.locator("main h1").first();+ const before = await heading.boundingBox();+ await trigger.focus();+ await p.keyboard.press("Enter");+ await panel.waitFor({ state: "visible" });+ check((await trigger.getAttribute("aria-expanded")) === "true", "launcher: Enter opens it (aria-expanded)");+ const first = await focused(p);+ check(/^Cinema Studio/.test(first?.name ?? ""), "launcher: focus starts on Cinema Studio", first?.name);+ await p.keyboard.press("ArrowRight");+ const right = await focused(p);+ check(right?.col === "1" && right?.row === "0", "launcher: Right goes to the next column's lead", JSON.stringify(right));+ await p.keyboard.press("ArrowDown");+ const down = await focused(p);+ check(down?.col === "1" && down?.row === "1", "launcher: Down goes down the column", JSON.stringify(down));+ await p.keyboard.press("ArrowUp");+ await p.keyboard.press("ArrowLeft");+ const back = await focused(p);+ check(back?.col === "0" && back?.row === "0", "launcher: Up and Left come back", JSON.stringify(back));+ await p.keyboard.press("End");+ const end = await focused(p);+ await p.keyboard.press("Home");+ const home = await focused(p);+ check(end?.href !== home?.href && home?.col === "0" && home?.row === "0", "launcher: End and Home jump to the ends");+ const after = await heading.boundingBox();+ check(!!before && !!after && before.y === after.y && before.x === after.x, "launcher: opening it does not move the page");+ await shot(p, "launcher-keys-1440");+ await p.keyboard.press("Escape");+ await panel.waitFor({ state: "hidden" });+ check(await trigger.evaluate((t) => t === document.activeElement), "launcher: Esc closes it and focus goes back to Studios");+ // Search from the launcher, then Esc: focus comes back to Studios (the launcher's own button is gone by then).+ await trigger.click();+ await panel.getByRole("button", { name: /^Search all apps/ }).click();+ await p.getByRole("dialog", { name: "Search Fuobe" }).waitFor();+ await p.keyboard.press("Escape");+ await p.getByRole("dialog", { name: "Search Fuobe" }).waitFor({ state: "detached" });+ check(await trigger.evaluate((t) => t === document.activeElement), "launcher: its Search, then Esc, gives focus back to Studios");+ await trigger.click();+ await panel.waitFor({ state: "visible" });+ await p.keyboard.press("/");+ await p.getByRole("dialog", { name: "Search Fuobe" }).waitFor();+ await p.keyboard.press("Escape");+ await p.getByRole("dialog", { name: "Search Fuobe" }).waitFor({ state: "detached" });+ check(await trigger.evaluate((t) => t === document.activeElement), "launcher: / from inside it, then Esc, gives focus back to Studios");+ for (const [w, h] of [+ [1440, 900],+ [1280, 800],+ [1280, 720],+ [1024, 768],+ ]) {+ await p.setViewportSize({ width: w, height: h });+ await trigger.click();+ await panel.waitFor({ state: "visible" });+ const links = panel.getByRole("link");+ const seen = await inView(links);+ const scrolls = await panel.evaluate((el) => el.scrollHeight > el.clientHeight + 1);+ check(seen.length === 33 && seen.every(Boolean) && !scrolls, `launcher at ${w}x${h}: all 33 links on screen, no scrolling`, `${seen.filter(Boolean).length}/${seen.length}`);+ await p.keyboard.press("Escape");+ }+ await p.setViewportSize(DESKTOP.viewport);+ await trigger.click();+ await panel.getByRole("link", { name: /^Marketing Studio/ }).click();+ const landed = await (p.waitForURL((u) => new URL(u).pathname === "/marketing", { timeout: 20_000 }).then(() => panel.waitFor({ state: "hidden" }))).then(() => true, () => false);+ check(landed, "launcher: Marketing Studio lands on /marketing and the launcher closes");+ check((await trigger.getAttribute("data-active")) !== null, "on /marketing the Studios trigger is marked");+ await trigger.click();+ check((await panel.getByRole("link", { name: /^Marketing Studio/ }).getAttribute("aria-current")) === "page", "…and Marketing Studio has aria-current=page");+ await p.keyboard.press("Escape");+ check(ctx.errors.length === 0, "launcher pages: no console errors", ctx.errors.join(" | "));+ await ctx.close();+ }++ // 3. Create and the guest menu are real menus.+ {+ const ctx = await as("guest");+ const p = await page(ctx);+ await openRoute(p, `${app}/`);+ for (const name of ["Create", "Menu"]) {+ const button = p.locator("[data-top-bar]").getByRole("button", { name, exact: true });+ await button.focus();+ await p.keyboard.press("Enter");+ const menu = p.getByRole("menu");+ await menu.waitFor();+ await p.keyboard.press("ArrowDown");+ const item = await p.evaluate(() => document.activeElement?.getAttribute("role"));+ await p.keyboard.press("Escape");+ await menu.waitFor({ state: "detached" });+ check(item === "menuitem" && (await button.evaluate((b) => b === document.activeElement)), `${name}: role=menu, arrows reach the items, Esc gives focus back`);+ }+ await ctx.close();+ }++ // 4. The search palette.+ {+ const ctx = await as("owner");+ const p = await page(ctx);+ const dialog = p.getByRole("dialog", { name: "Search Fuobe" });+ await openRoute(p, `${app}/`);+ await p.locator("main h1").first().click();+ await p.keyboard.press("/");+ check(await dialog.waitFor({ timeout: 10_000 }).then(() => true, () => false), "palette: / on the page opens it");+ await shot(p, "palette-empty-1440");+ await p.keyboard.press("Escape");+ await openRoute(p, `${app}/image`);+ const box = p.locator("[data-composer] textarea").first();+ await box.click();+ await p.keyboard.type("a/b");+ check((await box.inputValue()).endsWith("a/b") && !(await dialog.isVisible()), "palette: / typed in the composer is a slash");+ await p.keyboard.press("ControlOrMeta+k");+ await dialog.waitFor();+ await p.keyboard.press("Escape");+ await dialog.waitFor({ state: "detached" });+ check(await p.evaluate(() => !!document.activeElement?.matches("[data-composer] textarea")), "palette: Ctrl+K from the composer, Esc back to the composer");+ await p.keyboard.press("ControlOrMeta+k");+ await dialog.waitFor();+ await p.keyboard.type("ad for my perfume");+ await p.locator('[cmdk-item][data-selected="true"]').first().waitFor();+ await p.waitForTimeout(500);+ const rows = await dialog.locator("[cmdk-item]").evaluateAll((els) => els.slice(0, 3).map((e) => e.getAttribute("data-value")));+ check(rows.join() === "nav:marketing,nav:ads,app:app-giant-product", "palette: “ad for my perfume” → Marketing Studio, Ads Studio, Giant Product", rows.join());+ // Screen readers hear the row that is selected: the field's aria-activedescendant follows it, typing included.+ const announced = () => p.evaluate(() => {+ const sel = document.querySelector("[cmdk-item][data-selected=true]")?.id;+ const input = document.querySelector("[cmdk-input]")?.getAttribute("aria-activedescendant");+ return !!sel && sel === input;+ });+ const a1 = await announced();+ await p.keyboard.press("ArrowDown");+ await p.waitForTimeout(100);+ const a2 = await announced();+ await p.keyboard.type(" ");+ await p.waitForTimeout(500);+ const a3 = await announced();+ await p.keyboard.press("Backspace");+ await p.waitForTimeout(500);+ check(a1 && a2 && a3, "palette: aria-activedescendant names the selected row (on typing and on arrows)", JSON.stringify([a1, a2, a3]));+ // The goal chips are buttons outside the listbox.+ check((await dialog.locator("[role=listbox] button").count()) === 0, "palette: no buttons inside the listbox");+ await shot(p, "palette-perfume-keys-1440");+ await p.keyboard.press("Enter");+ check(await (p.waitForURL((u) => new URL(u).pathname === "/marketing", { timeout: 20_000 })).then(() => true, () => false), "palette: Enter opens Marketing Studio");+ await p.keyboard.press("ControlOrMeta+k");+ await dialog.waitFor();+ await dialog.getByRole("group", { name: "Show the studios for one goal" }).getByRole("button", { name: /^Sell/ }).click();+ await p.waitForTimeout(300);+ const tiles = await dialog.locator('[cmdk-item][data-value^="tile:"]').count();+ check(tiles === 5, "palette: the Sell chip shows 5 studios", String(tiles));+ await p.keyboard.press("Escape");+ await openRoute(p, `${app}/`);+ await p.keyboard.press("ControlOrMeta+k");+ await dialog.waitFor();+ await p.waitForTimeout(400);+ const firstTile = await dialog.locator('[cmdk-item][data-selected="true"]').getAttribute("data-value");+ await p.keyboard.press("Enter");+ await p.waitForURL((u) => new URL(u).pathname !== "/", { timeout: 20_000 }).catch(() => {});+ check(firstTile?.startsWith("tile:") && new URL(p.url()).pathname !== "/", "palette: Enter on an empty query opens a studio tile", `${firstTile} → ${p.url()}`);+ check(ctx.errors.length === 0, "palette pages: no console errors", ctx.errors.join(" | "));+ await ctx.close();+ }++ // 5. Phone: tabs, the Studios sheet, search, full-screen studios, no sideways scroll.+ for (const size of [PHONE.viewport, { width: 360, height: 640 }]) {+ const label = `${size.width}x${size.height}`;+ const ctx = await as("guest", { ...PHONE, viewport: size });+ const p = await page(ctx);+ await openRoute(p, `${app}/image`);+ const tabs = p.locator("[data-phone-tabs]");+ const cells = await tabs.locator("[data-tab]").evaluateAll((els) => els.map((e) => e.getBoundingClientRect()).map((r) => [r.width, r.height, r.bottom]));+ check(cells.length === 5 && cells.every(([w, h]) => w >= 44 && h >= 44), `${label}: five tabs, each at least 44x44`, JSON.stringify(cells));+ check(cells.every(([, , b]) => Math.abs(b - size.height) <= 8), `${label}: the tabs sit at the bottom`);+ await tabs.getByRole("button", { name: "Studios" }).tap();+ const sheet = p.locator("#phone-sheet");+ await sheet.waitFor({ state: "visible" });+ await p.waitForTimeout(350);+ const tiles = sheet.locator("ul").first().getByRole("link");+ const seen = await inView(tiles);+ if (size.height >= 844) check(seen.length === 33 && seen.every(Boolean), `${label}: the Studios sheet shows all 33 without scrolling`, `${seen.filter(Boolean).length}/${seen.length}`);+ else check(seen.length === 33, `${label}: the Studios sheet lists all 33 (it scrolls inside at this height)`, String(seen.length));+ await sheet.getByRole("button", { name: /^Film/ }).tap();+ check((await sheet.locator("ul").first().getByRole("link").count()) === 8, `${label}: the Film chip shows 8`);+ if (size.height >= 844) await shot(p, "phone-studios-sheet-film-390");+ await tabs.locator('[data-tab="library"]').tap();+ const went = await (p.waitForURL((u) => new URL(u).pathname === "/library", { timeout: 20_000 }).then(() => sheet.waitFor({ state: "detached", timeout: 5_000 }))).then(() => true, () => false);+ check(went, `${label}: Library tapped over the open sheet goes to /library and closes it`);+ for (const [tab, name] of [["studios", "Studios"], ["create", "Create"], ["you", "You"]]) {+ await tabs.getByRole("button", { name }).focus();+ await p.keyboard.press("Enter");+ await sheet.waitFor({ state: "visible" });+ await p.keyboard.press("Escape");+ const closed = await (sheet.waitFor({ state: "detached", timeout: 5_000 })).then(() => true, () => false);+ const back = await p.evaluate((t) => document.activeElement?.getAttribute("data-tab") === t, tab);+ check(closed && back, `${label}: Esc closes the ${name} sheet and focus goes back to its tab`);+ }+ await openRoute(p, `${app}/image`);+ await p.locator("main").getByRole("button", { name: "Search", exact: true }).first().tap();+ const dialog = p.getByRole("dialog", { name: "Search Fuobe" });+ await dialog.waitFor();+ const full = await dialog.evaluate((d) => {+ const r = d.getBoundingClientRect();+ return r.width >= innerWidth - 1 && r.height >= innerHeight - 1;+ });+ check(full && (await dialog.getByRole("button", { name: /^Cancel/ }).isVisible()), `${label}: the header's search opens the full-screen palette with Cancel`);+ await dialog.getByRole("button", { name: /^Cancel/ }).tap();+ await dialog.waitFor({ state: "detached" });+ for (const r of ["/assist"]) {+ await openRoute(p, app + r);+ check(!(await tabs.isVisible()), `${label}: no tabs on ${r}`);+ await p.getByRole("button", { name: "Menu", exact: true }).first().tap();+ await sheet.waitFor({ state: "visible" });+ check((await sheet.getByRole("link", { name: "Library" }).count()) > 0, `${label}: the header's Menu on ${r} opens the menu sheet`);+ await p.keyboard.press("Escape");+ }+ for (const r of ["/", "/image", "/video", "/audio", "/marketing", "/library", "/settings", "/cinema", "/apps", "/effects"]) {+ await openRoute(p, app + r, { settleMs: 300 });+ const over = await sideScroll(p);+ if (over > 0) check(false, `${label}: ${r} does not scroll sideways`, `${over}px`);+ }+ check(ctx.errors.length === 0, `${label}: no console errors`, ctx.errors.join(" | "));+ await ctx.close();+ }++ // 6. No layout shift on load, for each kind of viewer. Each page is seen once first: the bar keeps the room of the pills+ // and the avatar this browser saw last (and an owner's very first Home also has its first-run guide arrive).+ for (const who of ["guest", "owner", ...(publicSignup ? ["account"] : [])]) {+ const ctx = await as(who);+ await ctx.addInitScript(() => {+ window.__cls = 0;+ new PerformanceObserver((l) => {+ for (const e of l.getEntries()) if (!e.hadRecentInput) window.__cls += e.value;+ }).observe({ type: "layout-shift", buffered: true });+ });+ const p = await page(ctx);+ for (const r of ["/", "/image", "/library", "/marketing"]) {+ await p.goto(app + r, { waitUntil: "load" });+ await p.waitForTimeout(1500);+ await p.goto(app + r, { waitUntil: "load" });+ await p.waitForTimeout(2500);+ const cls = await p.evaluate(() => window.__cls);+ check(cls < 0.01, `${who}: ${r} CLS ${cls.toFixed(4)} < 0.01`);+ }+ check(ctx.errors.length === 0, `${who}: no console errors on load`, ctx.errors.join(" | "));+ await ctx.close();+ }++ // 7. Home's goal row.+ for (const who of ["guest", "owner"]) {+ const ctx = await as(who);+ const p = await page(ctx);+ await openRoute(p, `${app}/`);+ const row = p.getByRole("toolbar", { name: "Start from a goal" });+ const goals = row.locator("[data-goal]");+ check((await goals.count()) === 6, `${who}: six goals on Home`);+ await goals.first().focus();+ await p.keyboard.press("ArrowRight");+ await p.keyboard.press("ArrowRight");+ const at = await p.evaluate(() => document.activeElement?.getAttribute("data-goal"));+ check(at === "sell", `${who}: Right moves along the goals`, at);+ const title = p.locator("main h1").first();+ const before = await title.boundingBox();+ await p.keyboard.press("Enter");+ const band = p.locator("#goal-band");+ await band.waitFor({ state: "visible" });+ const text = await band.innerText();+ check(/Marketing Studio/.test(text) && /Giant product/i.test(text), `${who}: Sell opens its band (Marketing Studio … Giant product)`);+ check((await title.boundingBox())?.y === before?.y, `${who}: the band leaves the page above it in place`);+ check(/Plan it with Assist/.test(text) === (who === "owner"), `${who}: “Plan it with Assist” only for the owner`);+ if (who === "owner") await shot(p, "home-sell-band-keys-1440");+ await p.keyboard.press("Escape");+ await band.waitFor({ state: "detached" });+ check((await p.evaluate(() => document.activeElement?.getAttribute("data-goal"))) === "sell", `${who}: Esc closes the band, focus back on Sell`);+ await ctx.close();+ }++ // 8. Next steps under a result (the owner's feed; a placeholder result).+ {+ const ctx = await as("owner");+ const p = await page(ctx);+ await openRoute(p, `${app}/image`);+ const made = await p.evaluate(() =>+ fetch("/api/generations", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ feature: "image", modelId: "nano-banana-pro", prompt: "a matte black perfume bottle on wet stone, product photo", params: { aspectRatio: "1:1" } }) }).then((r) => r.json()),+ );+ const id = made.items?.[0]?.id;+ for (let i = 0; i < 40; i++) {+ const g = await p.evaluate((id) => fetch(`/api/generations/${id}`).then((r) => r.json()), id);+ if ((g.generation ?? g).status === "succeeded") break;+ await p.waitForTimeout(500);+ }+ await openRoute(p, `${app}/image`);+ const steps = p.getByRole("group", { name: /Keep going with this picture/ }).first();+ const shown = await steps.waitFor({ timeout: 30_000 }).then(() => true, () => false);+ const hrefs = shown ? await steps.getByRole("link").evaluateAll((els) => els.map((e) => e.getAttribute("href"))) : [];+ check(shown && hrefs.length >= 3 && hrefs.length <= 5 && hrefs.every((h) => /[?&]image=/.test(h)), "image result: “Keep going with this picture” with 3-5 links that carry the picture", hrefs.join(" "));+ await steps.scrollIntoViewIfNeeded().catch(() => {});+ await shot(p, "next-steps-1440");+ const sharpen = steps.getByRole("link", { name: /Sharpen to 4K/ });+ if (await sharpen.count()) {+ await sharpen.click();+ await p.waitForURL((u) => new URL(u).pathname.startsWith("/upscale"), { timeout: 20_000 });+ await p.waitForTimeout(1500);+ check((await p.locator('main img[src^="/api/files/"]').count()) > 0, "Sharpen to 4K opens Upscale with the picture in its slot");+ }+ const clip = await p.evaluate(() =>+ fetch("/api/generations", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ feature: "video", modelId: "oss-minimax-h3", op: "t2v", prompt: "a fashion model walks a neon runway, slow push-in", params: { duration: 5, aspectRatio: "16:9" } }) }).then((r) => r.json()),+ );+ for (let i = 0; i < 40; i++) {+ const g = await p.evaluate((id) => fetch(`/api/generations/${id}`).then((r) => r.json()), clip.items?.[0]?.id);+ if ((g.generation ?? g).status === "succeeded") break;+ await p.waitForTimeout(500);+ }+ await openRoute(p, `${app}/video`);+ const clipSteps = p.getByRole("group", { name: /Keep going with this clip/ }).first();+ await clipSteps.waitFor({ timeout: 30_000 }).catch(() => {});+ const firstClip = await clipSteps.getByRole("link").first().getAttribute("href").catch(() => null);+ check(!!firstClip && /\/(extend|color-grade)/.test(firstClip), "clip result: Extend comes first (after a grade's own step)", firstClip);+ await ctx.close();+ }++ // 9. Explore: three studios visited show in the menu; blocked storage breaks nothing.+ {+ const ctx = await as("owner");+ const p = await page(ctx);+ for (const r of ["/cinema", "/shorts", "/marketing"]) await openRoute(p, app + r, { settleMs: 400 });+ await p.locator("[data-top-bar]").getByRole("button", { name: /^Account and settings/ }).click();+ const menu = p.getByRole("menu");+ await menu.waitFor();+ const text = await menu.innerText();+ check(/\b3 of 28 studios tried/.test(text) && /Next to try:/.test(text), "explore: 3 visited show as “3 of 28 studios tried” with a next one", text.match(/\d+ of \d+ studios tried/)?.[0]);+ await shot(p, "account-menu-explore-1440");+ await p.keyboard.press("Escape");+ await ctx.close();+ const blocked = await as("guest");+ await blocked.addInitScript(() => {+ const no = () => {+ throw new DOMException("blocked", "SecurityError");+ };+ Object.defineProperty(window, "localStorage", { get: no });+ });+ const q = await page(blocked);+ for (const r of ["/", "/image", "/library"]) {+ await openRoute(q, app + r, { settleMs: 400 });+ check(await q.locator("[data-top-bar]").isVisible(), `blocked storage: ${r} still renders`);+ }+ await q.locator("[data-top-bar]").getByRole("button", { name: "Menu", exact: true }).click();+ check(!/studios tried/.test(await q.getByRole("menu").innerText()), "blocked storage: the menu shows no explore count");+ await blocked.close();+ }++ // 10. What visitors never see.+ for (const who of ["guest", ...(publicSignup ? ["account"] : [])]) {+ const ctx = await as(who);+ const p = await page(ctx);+ await openRoute(p, `${app}/image`);+ const button = who === "guest" ? p.locator("[data-top-bar]").getByRole("button", { name: "Menu", exact: true }) : p.locator("[data-top-bar]").getByRole("button", { name: /^Account: / });+ await button.click();+ const menuText = await p.getByRole("menu").innerText();+ await p.keyboard.press("Escape");+ const phone = await browser.newContext({ ...PHONE, storageState: await ctx.storageState() });+ const q = await phone.newPage();+ await openRoute(q, `${app}/image`);+ await q.locator("[data-phone-tabs]").getByRole("button", { name: "You" }).tap();+ await q.locator("#phone-sheet").waitFor({ state: "visible" });+ const sheetText = await q.locator("#phone-sheet").innerText();+ if (who === "guest") await shot(q, "phone-you-sheet-guest-390");+ await phone.close();+ const said = VISITOR_WORDS.filter((w) => menuText.includes(w) || sheetText.includes(w));+ check(said.length === 0, `${who}: the menu and the You sheet never say setup words`, said.join(", "));+ for (const query of ["comfyui server", "restore colourise"]) {+ await p.keyboard.press("ControlOrMeta+k");+ const dialog = p.getByRole("dialog", { name: "Search Fuobe" });+ await dialog.waitFor();+ await p.keyboard.type(query);+ await p.waitForTimeout(700);+ const values = await dialog.locator("[cmdk-item]").evaluateAll((els) => els.map((e) => `${e.getAttribute("data-value")} ${e.textContent}`));+ const bad = values.filter((v) => /setting:comfyui|video-tools-restore|Restore & colourise/i.test(v));+ check(bad.length === 0, `${who}: searching “${query}” offers no owner-only row`, bad.slice(0, 2).join(" | "));+ await p.keyboard.press("Escape");+ }+ await ctx.close();+ }++ // 11. Reduced motion: no transitions on the launcher, sheets and band.+ {+ const ctx = await as("guest", DESKTOP, { reducedMotion: "reduce" });+ const p = await page(ctx);+ await openRoute(p, `${app}/`);+ await p.locator("[data-top-bar]").getByRole("button", { name: /^Studios/ }).click();+ const dur = (sel) => p.locator(sel).first().evaluate((e) => [getComputedStyle(e).transitionDuration, getComputedStyle(e).animationDuration, getComputedStyle(e).animationName]);+ const launcher = await dur("#studios-launcher");+ check(launcher[0].split(",").every((d) => parseFloat(d) === 0) && (launcher[2] === "none" || parseFloat(launcher[1]) === 0), "reduced motion: the launcher doesn't animate", launcher.join(" "));+ await p.keyboard.press("Escape");+ await p.locator('[data-goal="sell"]').click();+ const band = await dur("#goal-band");+ check(band[0].split(",").every((d) => parseFloat(d) === 0) && (band[2] === "none" || parseFloat(band[1]) === 0), "reduced motion: the goal band doesn't animate", band.join(" "));+ await ctx.close();+ const phone = await as("guest", PHONE, { reducedMotion: "reduce" });+ const q = await page(phone);+ await openRoute(q, `${app}/image`);+ await q.locator("[data-phone-tabs]").getByRole("button", { name: "Studios" }).tap();+ await q.locator("#phone-sheet").waitFor({ state: "visible" });+ const sheet = await q.locator("#phone-sheet").evaluate((e) => [getComputedStyle(e).animationName, getComputedStyle(e).animationDuration]);+ check(sheet[0] === "none" || parseFloat(sheet[1]) === 0, "reduced motion: the Studios sheet doesn't slide", sheet.join(" "));+ await phone.close();+ }++ // 12. Screenshots in both themes for review.+ if (shots) {+ for (const scheme of ["dark", "light"]) {+ const ctx = await as("owner", DESKTOP, { colorScheme: scheme });+ const p = await page(ctx);+ await openRoute(p, `${app}/`);+ await shot(p, `bar-home-1440-${scheme}`);+ await p.locator("[data-top-bar]").getByRole("button", { name: /^Studios/ }).click();+ await p.waitForTimeout(400);+ await shot(p, `launcher-1440-${scheme}`);+ await p.keyboard.press("Escape");+ await p.locator('[data-goal="sell"]').click();+ await p.waitForTimeout(500);+ await shot(p, `home-sell-band-1440-${scheme}`);+ await p.keyboard.press("ControlOrMeta+k");+ await p.keyboard.type("ad for my perfume");+ await p.waitForTimeout(900);+ await shot(p, `palette-perfume-1440-${scheme}`);+ await p.keyboard.press("Escape");+ await p.locator("[data-top-bar]").getByRole("button", { name: /^Account and settings/ }).click();+ await p.waitForTimeout(400);+ await shot(p, `account-menu-owner-1440-${scheme}`);+ await ctx.close();+ const phone = await as("owner", PHONE, { colorScheme: scheme });+ const q = await page(phone);+ await openRoute(q, `${app}/`);+ await shot(q, `phone-home-390-${scheme}`);+ await q.locator("[data-phone-tabs]").getByRole("button", { name: "Studios" }).tap();+ await q.waitForTimeout(500);+ await shot(q, `phone-studios-sheet-390-${scheme}`);+ await q.locator("[data-phone-tabs]").locator('[data-tab="you"]').tap();+ await q.waitForTimeout(500);+ await shot(q, `phone-you-sheet-390-${scheme}`);+ await phone.close();+ }+ }+} catch (e) {+ check(false, `stopped: ${e.message.split("\n").slice(0, 4).join(" ")}`);+} finally {+ for (const { ctx, password } of accounts) {+ await ctx.request.delete(`${app}/api/auth/me`, { data: { password } }).catch(() => {});+ await ctx.close().catch(() => {});+ }+ await browser.close();+}+console.log(failures.length ? `\n${failures.length} failed:\n- ${failures.join("\n- ")}` : "\nNavigation checks passed.");+process.exit(failures.length ? 1 : 0);diff --git a/tests/e2e/owner-computer.mjs b/tests/e2e/owner-computer.mjsindex 4bca386b..fce575f6 100644--- a/tests/e2e/owner-computer.mjs+++ b/tests/e2e/owner-computer.mjs@@ -37,6 +37,16 @@ const check = (name, ok, detail = "") => {console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? ` — ${detail}` : ""}`);};const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+/**+ * The install's status lives in the account menu (the avatar at the top bar's right end): opens it (again, after a page+ * load or a dialog closed it) and returns it.+ */+async function statusMenu(page) {+ const menu = page.getByRole("menu");+ if (!(await menu.isVisible().catch(() => false))) await page.getByRole("button", { name: /^Account and settings/ }).click({ timeout: 5_000 }).catch(() => {});+ return menu;+}+async function until(fn, ms = 30_000, every = 250) {const end = Date.now() + ms;for (;;) {@@ -254,10 +264,15 @@ async function hosted() {check("Settings now say ComfyUI runs on the owner's computer", settings?.settings?.find((s) => s.name === "comfyWhere")?.value === "computer");await page.keyboard.press("Escape");- // The sidebar and Settings' strip say where the GPU is.- const chip = await until(() => page.getByText(/^Your computer · NVIDIA GeForce RTX 5090/).first().isVisible(), 45_000, 500);- check("the sidebar: Your GPU · online · Your computer · RTX 5090", !!chip && (await page.locator('[data-sidebar="footer"]').getByText("online").isVisible()));- await shoot(page, "sidebar-online");+ // The account menu and Settings' strip say where the GPU is.+ // The line is in the account menu now (the sidebar footer showed it all the time): open it, then read it.+ const chip = await until(async () => {+ const menu = await statusMenu(page);+ return (await menu.getByText(/^Your computer · NVIDIA GeForce RTX 5090/).first().isVisible()) && (await menu.getByText("online", { exact: true }).first().isVisible());+ }, 45_000, 500);+ check("the account menu: Your GPU · online · Your computer · RTX 5090", !!chip);+ await shoot(page, "menu-online");+ await page.keyboard.press("Escape");await page.goto(`${SITE}/settings`, { waitUntil: "load" });const strip = page.getByRole("navigation", { name: "Connections" });check("Settings' strip: Your GPU · Your computer · Online", !!(await until(() => strip.getByText("Your computer · Online").isVisible(), 30_000)));@@ -286,22 +301,22 @@ async function hosted() {check("/connect: never the link's words", !(await page.getByText(/Your link didn't answer/).isVisible()));await shoot(page, "connect-computer");- // ComfyUI closes: the sidebar says so; it comes back and goes on.+ // ComfyUI closes: the account menu says so; it comes back and goes on.await page.goto(`${SITE}/image?model=oss-z-image-turbo`, { waitUntil: "load" });await stopFake(PC_PORT);- const down = await until(() => page.locator('[data-sidebar="footer"]').getByText("ComfyUI not running").isVisible(), 70_000, 1000);- check("ComfyUI closed: the sidebar says ComfyUI not running", !!down);- await shoot(page, "sidebar-comfy-down");+ const down = await until(async () => (await statusMenu(page)).getByText("ComfyUI not running").isVisible(), 70_000, 1000);+ check("ComfyUI closed: the account menu says ComfyUI not running", !!down);+ await shoot(page, "menu-comfy-down");await startFake(PC_PORT, SITE, { guard: true });- check("ComfyUI back: online again", !!(await until(() => page.locator('[data-sidebar="footer"]').getByText("online").isVisible(), 70_000, 1000)));+ check("ComfyUI back: online again", !!(await until(async () => (await statusMenu(page)).getByText("online").isVisible(), 70_000, 1000)));- // ComfyUI started the usual way (without Fuobe's setting): the sidebar's line opens the fix; /connect says it once.+ // ComfyUI started the usual way (without Fuobe's setting): the account menu's row opens the fix; /connect says it once.await stopFake(PC_PORT);await startFake(PC_PORT, "off");- const needs = page.locator('[data-sidebar="footer"]').getByRole("button", { name: /needs a setting/ });- check("no setting: the sidebar says needs a setting, as a button", !!(await until(() => needs.isVisible(), 70_000, 1000)));+ const needs = page.getByRole("menu").getByRole("menuitem", { name: /needs a setting/ });+ check("no setting: the account menu says needs a setting, as an item", !!(await until(async () => (await statusMenu(page), needs.isVisible()), 70_000, 1000)));await needs.click();- check("the sidebar's button opens the setting's fix", !!(await until(() => page.getByRole("dialog").getByRole("heading", { name: "Your ComfyUI needs Fuobe's setting again" }).isVisible(), 15_000)));+ check("the account menu's item opens the setting's fix", !!(await until(() => page.getByRole("dialog").getByRole("heading", { name: "Your ComfyUI needs Fuobe's setting again" }).isVisible(), 15_000)));check("the fix: the start file", !!(await until(() => page.getByRole("dialog").getByRole("button", { name: /Download start file/ }).first().isVisible(), 15_000)));await shoot(page, "dialog-no-setting");await page.keyboard.press("Escape");@@ -322,7 +337,8 @@ async function hosted() {await shoot(page, "connect-no-setting");await stopFake(PC_PORT);await startFake(PC_PORT, SITE, { guard: true });- check("ComfyUI back with the setting: online again", !!(await until(() => page.locator('[data-sidebar="footer"]').getByText("online").isVisible(), 70_000, 1000)));+ check("ComfyUI back with the setting: online again", !!(await until(async () => (await statusMenu(page)).getByText("online").isVisible(), 70_000, 1000)));+ await page.keyboard.press("Escape");// H2. A phone of the owner's: what the computer said, why not here, and the server way.{@@ -366,7 +382,8 @@ async function hosted() {// Disconnect: back to the server's address, nothing connected.await sec.getByRole("button", { name: "Disconnect" }).click();check("Disconnect: the choice again, this computer first", !!(await until(() => sec.getByText("Use the ComfyUI on this computer", { exact: true }).first().isVisible(), 15_000)));- check("the sidebar: Your GPU · Connect", !!(await until(() => page.locator('[data-sidebar="footer"]').getByRole("button", { name: /Your GPU\s*Connect/ }).isVisible(), 40_000, 500)));+ check("the account menu: Your GPU · Connect", !!(await until(async () => (await statusMenu(page)).getByRole("menuitem", { name: /Your GPU\s*Connect/ }).isVisible(), 40_000, 500)));+ await page.keyboard.press("Escape");await shoot(page, "settings-choose", { scroll: "#comfyui" });await page.getByRole("navigation", { name: "Connections" }).getByText("Connect").waitFor({ timeout: 30_000 });check("Settings' strip: Your GPU · Connect", true);@@ -422,10 +439,10 @@ async function hosted() {}, 60_000, 500);check("the demo run went through", demoDone?.status === "succeeded", demoDone?.error ?? demoDone?.status ?? "no run");const count = (await runs(page)).length;- await page.locator('[data-sidebar="footer"]').getByRole("button", { name: /Your GPU\s*Connect/ }).click();+ await (await statusMenu(page)).getByRole("menuitem", { name: /Your GPU\s*Connect/ }).click();const d3 = page.getByRole("dialog");- check("the sidebar's Connect: Connect your GPU, with no run waiting", !!(await until(() => d3.getByRole("heading", { name: "Connect your GPU", exact: true }).isVisible(), 15_000)));- check("the sidebar's Connect looks at once", !!(await until(() => d3.getByText(/Your GPU is connected/).isVisible(), 30_000)));+ check("the account menu's Connect: Connect your GPU, with no run waiting", !!(await until(() => d3.getByRole("heading", { name: "Connect your GPU", exact: true }).isVisible(), 15_000)));+ check("the account menu's Connect looks at once", !!(await until(() => d3.getByText(/Your GPU is connected/).isVisible(), 30_000)));await sleep(6000);check("no run started again", (await runs(page)).length === count, `${(await runs(page)).length} vs ${count}`);await page.keyboard.press("Escape");@@ -570,8 +587,8 @@ async function local() {await sleep(12_000);await studio(page, "/image?model=oss-z-image-turbo");await generate(page, "another one");- const card = await until(() => page.getByRole("dialog").filter({ hasText: "Connect your GPU to run this" }).isVisible(), 20_000);- check("local: ComfyUI gone, Generate opens the connect card, no error toast", !!card && !(await page.locator("[data-sonner-toast]").filter({ hasText: "Connect ComfyUI in Settings" }).first().isVisible().catch(() => false)));+ const gate = await until(() => page.getByRole("dialog").filter({ hasText: "Connect your GPU to run this" }).isVisible(), 20_000);+ check("local: ComfyUI gone, Generate opens the connect card, no error toast", !!gate && !(await page.locator("[data-sonner-toast]").filter({ hasText: "Connect ComfyUI in Settings" }).first().isVisible().catch(() => false)));check("the browser reached nothing on this computer but the studio", ctx.loopback.length === 0, ctx.loopback.join(", "));await ctx.close();}diff --git a/tests/e2e/regenerate-2k.mjs b/tests/e2e/regenerate-2k.mjsindex 9c488684..59f463fa 100644--- a/tests/e2e/regenerate-2k.mjs+++ b/tests/e2e/regenerate-2k.mjs@@ -63,7 +63,7 @@ try {// ---- Upscale → Video, open engine.let ctx = await setup(browser, device, theme, "open");let page = await ctx.newPage();- // (The sidebar's account row hydrates its dev-server Suspense script differently: not this package's.)+ // (An old dev-server hydration note about the account row: not this package's.)page.on("pageerror", (e) => !/Hydration failed[\s\S]*ViewerRowPlaceholder/.test(e.message) && failures.push(`${label} page error: ${e.message.split("\n")[0]}`));await openRoute(page, `${app}/upscale/video`);const group = page.getByRole("radiogroup", { name: "How to finish the clip" });@@ -153,7 +153,7 @@ try {page = await ctx.newPage();await openRoute(page, `${app}/video`);// The next steps under the newest result.- const chipStep = page.getByRole("navigation", { name: "Next steps" }).first().getByRole("link", { name: "Regenerate in 2K" });+ const chipStep = page.getByRole("group", { name: /Keep going with this/ }).first().getByRole("link", { name: "Regenerate in 2K" });await chipStep.waitFor({ timeout: 30_000 });check(await chipStep.isVisible(), `${label}: the next steps offer Regenerate in 2K`);const tileOpen = page.getByRole("button", { name: /^Open “A red fox/ }).first();diff --git a/tests/e2e/shell.mjs b/tests/e2e/shell.mjsindex 887b10b2..87f2dbf7 100644--- a/tests/e2e/shell.mjs+++ b/tests/e2e/shell.mjs@@ -1,86 +1,130 @@// App-shell checks in a real browser (the app must be running; demo mode is fine).// Usage: node tests/e2e/shell.mjs [appUrl] (pnpm test:e2e:shell). Exits 1 on the first failure.//-// 1. Phone: the sidebar drawer closes when a link in it is tapped (nav item, New creation, footer),-// and its Search row opens the ⌘K palette.-// 2. A first visit shows Studios and folds Engine, with Library right after Create; a collapsed group-// still shows the page you're on.-// 3. Landmarks: "Skip to content" is the first Tab stop, one <main>, the sidebar is <nav "Main">.-// 4. ⌘K / Ctrl+K opens the palette; a typo still finds a page and Enter opens it; Esc gives focus+// 1. Phone: a link tapped in a bottom-tab sheet (Studios, Create) goes to its page and closes the sheet; a tab tapped+// over an open sheet goes where it says; "Search everything" hands over to the full-screen search.+// 2. Landmarks: "Skip to content" is the first Tab stop, one <main>, the top bar is <nav "Main">.+// 3. ⌘K / Ctrl+K opens the palette; a typo still finds a page and Enter opens it; Esc gives focus// back to the composer; an open-source model picked under the Cloud switch opens on its engine.-// 5. Full-screen studios (Assist, an open Cinema or Layers project…) fold the app sidebar to its rail-// without changing the remembered state; opened by hand, it stays open inside that studio only.-// 6. Deep links into Settings (/settings#comfyui) scroll to the section after a client navigation.-// 7. Galleries: "Show more" pressed from the keyboard moves focus to the first new card.-// 8. New creation on Home starts over (empty composer, focused); the sidebar's bottom fade is never-// deeper than what's hidden below it.-// 9. With public sign-up on: an account sees its email in the sidebar, and its menu signs it out+// 4. Full-screen studios (Assist, an open Cinema or Layers project…) mark the page before paint and keep the top bar on a+// desktop; on a phone they hide the tabs and the header's button opens the menu sheet.+// 5. Deep links into Settings (/settings#comfyui) scroll to the section after a client navigation.+// 6. Galleries: "Show more" pressed from the keyboard moves focus to the first new card.+// 7. New creation on Home starts over (empty composer, focused).+// 8. With public sign-up on: an account sees its initial in the bar, and its menu signs it out// (a throwaway qa account, deleted at the end).import assert from "node:assert/strict";-import path from "node:path";-import { DESKTOP, launch, openRoute, PHONE, root } from "./_browser.mjs";+import { DESKTOP, launch, openRoute, PHONE } from "./_browser.mjs";-const app = (process.argv.slice(2).find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");+const app = (+ process.argv.slice(2).find((a) => !a.startsWith("--")) ??+ "http://localhost:3000"+).replace(/\/$/, "");const browser = await launch();const step = (name) => console.log(`- ${name}`);+// With a password set on the studio (E2E_OWNER_PASSWORD), the owner's checks sign in first; a studio without one is the owner's.+async function asOwner(ctx) {+ if (process.env.E2E_OWNER_PASSWORD)+ assert.ok(+ (+ await ctx.request.post(`${app}/api/auth/login`, {+ data: { password: process.env.E2E_OWNER_PASSWORD },+ })+ ).ok(),+ "owner signed in",+ );+ return !!(+ await (await ctx.request.get(`${app}/api/auth/me`)).json().catch(() => null)+ )?.owner;+}try {{const ctx = await browser.newContext(PHONE);const page = await ctx.newPage();- for (const [from, link, to] of [- ["/image", /^Effects$/, "/effects"],- ["/effects", /^New creation/, "/"],- ["/", /^Favorites$/, "/library"],- // The footer's engine status links to Settings too.- ["/image", /^Cloud models/, "/settings"],+ const tabs = page.locator("[data-phone-tabs]");+ const sheet = page.locator("#phone-sheet");+ for (const [from, tab, link, to] of [+ ["/image", "Studios", /^Cinema/, "/cinema"],+ ["/effects", "Create", /^New creation/, "/"],]) {- step(`phone: tapping “${link.source.replace(/[\^$]/g, "")}” in the drawer on ${from} closes it`);+ step(+ `phone: tapping “${link.source.replace(/[\^$]/g, "")}” in the ${tab} sheet on ${from} closes it`,+ );await openRoute(page, app + from);- await page.getByRole("button", { name: "Toggle Sidebar" }).first().tap();- const drawer = page.locator('[data-mobile="true"]');- await drawer.waitFor({ state: "visible" });- await drawer.getByRole("link", { name: link }).first().tap();- await page.waitForURL((u) => new URL(u).pathname === to, { timeout: 20_000 });- await drawer.waitFor({ state: "detached", timeout: 5_000 });+ await tabs.getByRole("button", { name: tab }).tap();+ await sheet.waitFor({ state: "visible" });+ await sheet.getByRole("link", { name: link }).first().tap();+ await page.waitForURL((u) => new URL(u).pathname === to, {+ timeout: 20_000,+ });+ await sheet.waitFor({ state: "detached", timeout: 5_000 });}- step("phone: Search in the drawer opens the palette");+ step("phone: Library tapped over the open Studios sheet goes to /library");+ await openRoute(page, `${app}/image`);+ await tabs.getByRole("button", { name: "Studios" }).tap();+ await sheet.waitFor({ state: "visible" });+ // (A modal sheet hides the rest of the page from screen readers, who close it first; a finger still reaches the tabs.)+ await tabs.locator('[data-tab="library"]').tap();+ await page.waitForURL((u) => new URL(u).pathname === "/library", {+ timeout: 20_000,+ });+ await sheet.waitFor({ state: "detached", timeout: 5_000 });++ step("phone: Search everything in the Studios sheet opens the palette");await openRoute(page, `${app}/image`);- await page.getByRole("button", { name: "Toggle Sidebar" }).first().tap();- await page.locator('[data-mobile="true"]').getByRole("button", { name: /^Search/ }).tap();+ await tabs.getByRole("button", { name: "Studios" }).tap();+ await sheet.getByRole("button", { name: "Search everything" }).tap();await page.getByRole("dialog", { name: "Search Fuobe" }).waitFor();- await page.locator('[data-mobile="true"]').waitFor({ state: "detached", timeout: 5_000 });+ await sheet.waitFor({ state: "detached", timeout: 5_000 });await ctx.close();}{const ctx = await browser.newContext(DESKTOP);const page = await ctx.newPage();- step("a first visit shows Studios, folds Engine, and Library follows Create");+ step(+ "Skip to content is the first Tab stop; one <main>; the top bar is a navigation landmark",+ );await openRoute(page, `${app}/image`);- const groups = await page.locator("[data-nav-group]").evaluateAll((els) => els.map((e) => [e.getAttribute("data-nav-group"), e.getAttribute("data-open")]));- assert.deepEqual(groups, [["create", "true"], ["library", "true"], ["studios", "true"], ["engine", "false"]]);-- step("Skip to content is the first Tab stop; one <main>; the sidebar is a navigation landmark");await page.keyboard.press("Tab");- assert.equal(await page.evaluate(() => document.activeElement?.textContent), "Skip to content");+ assert.equal(+ await page.evaluate(() => document.activeElement?.textContent),+ "Skip to content",+ );await page.keyboard.press("Enter");- assert.equal(await page.evaluate(() => document.activeElement?.id), "content");+ assert.equal(+ await page.evaluate(() => document.activeElement?.id),+ "content",+ );assert.equal(await page.locator("main").count(), 1, "one <main>");- assert.ok((await page.getByRole("navigation", { name: "Main" }).getByRole("link", { name: "Video" }).count()) > 0, "sidebar links are inside <nav aria-label=Main>");+ assert.ok(+ (await page+ .getByRole("navigation", { name: "Main" })+ .getByRole("link", { name: "Library" })+ .count()) > 0,+ "bar links are inside <nav aria-label=Main>",+ );- step("⌘K / Ctrl+K opens the palette; “cinma” finds Cinema Studio; Enter opens it");+ step(+ "⌘K / Ctrl+K opens the palette; “cinma” finds Cinema Studio; Enter opens it",+ );await page.keyboard.press("ControlOrMeta+k");const dialog = page.getByRole("dialog", { name: "Search Fuobe" });await dialog.waitFor();await page.keyboard.type("cinma");- // The start list (which also lists Cinema Studio) gives way to the matches.- await dialog.getByRole("option", { name: /^New creation/ }).waitFor({ state: "detached" });- await dialog.getByRole("option", { name: /^Cinema Studio/ }).first().waitFor();+ // The best match is picked (not the "Every studio" tile that the start list picks first).+ await page+ .locator('[cmdk-item][data-value="nav:cinema"][data-selected="true"]')+ .waitFor({ timeout: 10_000 });await page.keyboard.press("Enter");- await page.waitForURL((u) => new URL(u).pathname === "/cinema", { timeout: 20_000 });+ await page.waitForURL((u) => new URL(u).pathname === "/cinema", {+ timeout: 20_000,+ });await dialog.waitFor({ state: "detached" });- step("Esc closes the palette and gives focus back to the composer you were typing in");+ step(+ "Esc closes the palette and gives focus back to the composer you were typing in",+ );await openRoute(page, `${app}/image`);const box = page.locator("[data-composer] textarea").first();await box.click();@@ -90,88 +134,100 @@ try {await page.keyboard.press("Escape");await dialog.waitFor({ state: "detached" });await page.waitForTimeout(100);- assert.ok(await page.evaluate(() => !!document.activeElement?.matches("[data-composer] textarea")), "focus is back in the composer");+ assert.ok(+ await page.evaluate(+ () => !!document.activeElement?.matches("[data-composer] textarea"),+ ),+ "focus is back in the composer",+ );- step("an open-source model picked under the Cloud switch opens on the open engine");- await page.evaluate(() => localStorage.setItem("fuobe.engine", "cloud"));- await openRoute(page, `${app}/video`);- await page.keyboard.press("ControlOrMeta+k");- await dialog.waitFor();- await page.keyboard.type("FLUX.2 [dev]");- await dialog.getByRole("option", { name: /^FLUX\.2 \[dev\]/ }).first().waitFor();- await page.keyboard.press("Enter");- await page.waitForURL((u) => new URL(u).pathname === "/image" && new URL(u).searchParams.get("model") === "oss-flux2-dev", { timeout: 20_000 });- await page.getByRole("button", { name: /^Model: FLUX\.2 \[dev\]\./ }).waitFor({ timeout: 20_000 });- assert.equal(await page.evaluate(() => localStorage.getItem("fuobe.engine")), "open", "the switch moved to Open source");+ // The engine follows the model for the owner (a visitor's runs stay where their own engine is).+ if (await asOwner(ctx)) {+ step(+ "an open-source model picked under the Cloud switch opens on the open engine",+ );+ await page.evaluate(() => localStorage.setItem("fuobe.engine", "cloud"));+ await openRoute(page, `${app}/video`);+ await page.keyboard.press("ControlOrMeta+k");+ await dialog.waitFor();+ await page.keyboard.type("FLUX.2 [dev]");+ await dialog+ .getByRole("option", { name: /^FLUX\.2 \[dev\]/ })+ .first()+ .waitFor();+ await page.keyboard.press("Enter");+ await page.waitForURL(+ (u) =>+ new URL(u).pathname === "/image" &&+ new URL(u).searchParams.get("model") === "oss-flux2-dev",+ { timeout: 20_000 },+ );+ await page+ .getByRole("button", { name: /^Model: FLUX\.2 \[dev\]\./ })+ .waitFor({ timeout: 20_000 });+ assert.equal(+ await page.evaluate(() => localStorage.getItem("fuobe.engine")),+ "open",+ "the switch moved to Open source",+ );+ } else step("(skipped: the engine switch check needs the owner)");await ctx.close();}{const ctx = await browser.newContext(DESKTOP);const page = await ctx.newPage();- step("full-screen studios fold the app sidebar to its rail, and it comes back on the way out");- const sidebar = page.locator('[data-slot="sidebar"]').first();+ step(+ "full-screen studios mark the page before paint, keep the top bar, and the mark goes on the way out",+ );+ const marked = () =>+ page.evaluate(() =>+ document.documentElement.hasAttribute("data-fullscreen-studio"),+ );await openRoute(page, `${app}/assist`);- assert.equal(await sidebar.getAttribute("data-state"), "collapsed", "folded on Assist");- await page.getByRole("navigation", { name: "Main" }).getByRole("link", { name: "Image", exact: true }).click();- await page.waitForURL((u) => new URL(u).pathname === "/image");- await page.waitForFunction(() => document.querySelector('[data-slot="sidebar"]')?.getAttribute("data-state") === "expanded");- const cookies = await ctx.cookies();- assert.ok(!cookies.some((c) => c.name === "sidebar_state" && c.value === "false"), "the remembered state is untouched");-- step("opened by hand in Assist, the sidebar stays open on Assist's own pages, and folds again next time");- const nav = page.getByRole("navigation", { name: "Main" });- const state = (s) => page.waitForFunction((s) => document.querySelector('[data-slot="sidebar"]')?.getAttribute("data-state") === s, s);- await nav.getByRole("link", { name: "Assist", exact: true }).click();- await page.waitForURL((u) => new URL(u).pathname === "/assist");- await state("collapsed");- await nav.getByRole("button", { name: "Toggle Sidebar" }).click();- await state("expanded");- await page.evaluate(() => window.next.router.push("/assist/skills"));- await page.waitForURL((u) => new URL(u).pathname === "/assist/skills");- await page.waitForTimeout(300);- assert.equal(await sidebar.getAttribute("data-state"), "expanded", "still open on Skills");- await nav.getByRole("link", { name: "Image", exact: true }).click();- await page.waitForURL((u) => new URL(u).pathname === "/image");- await nav.getByRole("link", { name: "Assist", exact: true }).click();- await page.waitForURL((u) => new URL(u).pathname === "/assist");- await state("collapsed");- assert.ok(!(await ctx.cookies()).some((c) => c.name === "sidebar_state"), "no cookie written");+ assert.ok(await marked(), "marked on Assist");+ assert.ok(+ await page.locator("[data-top-bar]").isVisible(),+ "the bar stays on Assist",+ );+ await page+ .getByRole("navigation", { name: "Main" })+ .getByRole("link", { name: "Library" })+ .click();+ await page.waitForURL((u) => new URL(u).pathname === "/library");+ await page.waitForFunction(+ () => !document.documentElement.hasAttribute("data-fullscreen-studio"),+ );+ assert.ok(+ !(await ctx.cookies()).some((c) => c.name === "sidebar_state"),+ "no cookie written",+ );await ctx.close();}{- // Below 1440 px the Layers editor used to fold the sidebar itself, writing the cookie.- const ctx = await browser.newContext({ ...DESKTOP, viewport: { width: 1280, height: 860 } });+ const ctx = await browser.newContext(PHONE);const page = await ctx.newPage();- step("reopening a Layers project leaves the remembered sidebar state alone");- await openRoute(page, `${app}/layers`);- const chooser = page.waitForEvent("filechooser");- await page.getByRole("button", { name: "Upload Media" }).first().click();- await (await chooser).setFiles(path.join(root, "public/samples/grade-sample.jpg"));- await page.waitForURL(/\/layers\/[\w-]+$/, { timeout: 60_000 });- await page.getByRole("button", { name: "Separate layers" }).waitFor({ timeout: 60_000 });- await page.getByRole("link", { name: "All projects" }).click();- await page.waitForURL((u) => new URL(u).pathname === "/layers");- await page.getByRole("link", { name: /^Open project/ }).first().click();- await page.waitForURL(/\/layers\/[\w-]+$/);- await page.getByRole("button", { name: "Separate layers" }).waitFor({ timeout: 60_000 });- await page.getByRole("link", { name: "All projects" }).click();- await page.waitForURL((u) => new URL(u).pathname === "/layers");- await page.waitForFunction(() => document.querySelector('[data-slot="sidebar"]')?.getAttribute("data-state") === "expanded");- assert.ok(!(await ctx.cookies()).some((c) => c.name === "sidebar_state" && c.value === "false"), "the cookie still says expanded");+ step(+ "phone: a full-screen studio hides the tabs, and its header's Menu opens the menu sheet",+ );+ await openRoute(page, `${app}/assist`);+ assert.ok(+ !(await page.locator("[data-phone-tabs]").isVisible()),+ "no tabs on Assist",+ );+ await page.getByRole("button", { name: "Menu", exact: true }).first().tap();+ const sheet = page.locator("#phone-sheet");+ await sheet.waitFor({ state: "visible" });+ assert.ok(+ (await sheet.getByRole("link", { name: "Library" }).count()) > 0,+ "the menu sheet leads to Library",+ );+ await page.keyboard.press("Escape");+ await sheet.waitFor({ state: "detached", timeout: 5_000 });await ctx.close();}{const ctx = await browser.newContext(DESKTOP);const page = await ctx.newPage();- step("a collapsed group still shows the active page");- await openRoute(page, `${app}/cinema`);- const studios = page.locator('[data-nav-group="studios"]');- if ((await studios.getAttribute("data-open")) !== "false") await studios.locator("[data-nav-toggle]").click();- assert.equal(await studios.getAttribute("data-open"), "false");- assert.ok(await studios.getByRole("link", { name: "Cinema Studio" }).isVisible(), "Cinema Studio stays visible");- assert.ok(!(await studios.getByRole("link", { name: "Upscale" }).isVisible()), "other Studios items are folded away");- await studios.locator("[data-nav-toggle]").click(); // leave it open for the next run-step("/workflows and /settings/about redirect to Home and Settings");await openRoute(page, `${app}/workflows`);await page.waitForURL((u) => new URL(u).pathname === "/");@@ -186,52 +242,86 @@ try {await more.focus();await page.keyboard.press("Enter");await page.waitForTimeout(300);- const focused = await page.evaluate(() => document.activeElement?.getAttribute("href"));+ const focused = await page.evaluate(() =>+ document.activeElement?.getAttribute("href"),+ );assert.equal(focused, await cards.nth(before).getAttribute("href"));await ctx.close();}{const ctx = await browser.newContext(DESKTOP);const page = await ctx.newPage();- step("New creation on Home clears the prompt, focuses the composer and leaves no flag in the address");+ step(+ "New creation on Home clears the prompt, focuses the composer and leaves no flag in the address",+ );await openRoute(page, `${app}/`);const box = page.getByRole("textbox", { name: "Describe what to create" });await box.fill("a red fox");- await page.getByRole("navigation", { name: "Main" }).getByRole("link", { name: "New creation" }).click();- await page.waitForFunction(() => location.search === "" && document.activeElement?.getAttribute("aria-label") === "Describe what to create", null, { timeout: 10_000 });+ await page+ .locator("[data-top-bar]")+ .getByRole("link", { name: "New creation" })+ .click();+ await page.waitForFunction(+ () =>+ location.search === "" &&+ document.activeElement?.getAttribute("aria-label") ===+ "Describe what to create",+ null,+ { timeout: 10_000 },+ );assert.equal(await box.inputValue(), "");-- step("the sidebar's bottom fade is no deeper than what's hidden below it");- const fade = await page.locator('[data-sidebar="content"]').evaluate((el) => ({- hidden: el.scrollHeight - el.clientHeight - el.scrollTop,- depth: parseFloat(el.style.getPropertyValue("--fade-b")) || 0,- }));- assert.ok(fade.depth <= Math.max(0, Math.ceil(fade.hidden)) && fade.depth <= 40, `fade ${fade.depth}px for ${fade.hidden}px hidden`);await ctx.close();}- if (!(await fetch(`${app}/api/auth/me`).then((r) => r.json()).catch(() => null))?.publicSignup) {- step("(skipped: the account row needs public sign-up)");+ if (+ !(+ await fetch(`${app}/api/auth/me`)+ .then((r) => r.json())+ .catch(() => null)+ )?.publicSignup+ ) {+ step("(skipped: the account menu needs public sign-up)");} else {const ctx = await browser.newContext(DESKTOP);const page = await ctx.newPage();- step("an account sees its email in the sidebar, and its menu signs it out");+ step("an account sees its menu in the bar, and the menu signs it out");const email = `qa-shell-${Date.now().toString(36)}@example.com`;const password = `Qa-${Math.random().toString(36).slice(2)}-${Date.now()}`;try {- assert.ok((await ctx.request.post(`${app}/api/auth/signup`, { data: { email, password } })).ok(), "signed up");+ assert.ok(+ (+ await ctx.request.post(`${app}/api/auth/signup`, {+ data: { email, password },+ })+ ).ok(),+ "signed up",+ );await openRoute(page, `${app}/`);- const nav = page.getByRole("navigation", { name: "Main" });- await nav.getByText(email).waitFor({ timeout: 15_000 });- await nav.getByRole("button", { name: `Account: ${email}` }).click();+ const bar = page.locator("[data-top-bar]");+ const avatar = bar.getByRole("button", { name: `Account: ${email}` });+ await avatar.waitFor({ timeout: 15_000 });+ await avatar.click();const menu = page.getByRole("menu");- for (const name of ["Settings", "Your GPU", "Sign out"]) await menu.getByRole("menuitem", { name }).waitFor();- await menu.getByRole("menuitem", { name: "Sign out" }).click();- await nav.getByRole("link", { name: "Log in" }).waitFor({ timeout: 15_000 });- assert.equal(await nav.getByText(email).count(), 0, "signed out");+ await menu.getByText(email).waitFor();+ for (const name of [/Settings/, /Your GPU/, /Sign out/])+ await menu.getByRole("menuitem", { name }).first().waitFor();+ await menu.getByRole("menuitem", { name: /Sign out/ }).click();+ await bar+ .getByRole("link", { name: "Sign up" })+ .waitFor({ timeout: 15_000 });+ assert.equal(+ await bar.getByRole("button", { name: `Account: ${email}` }).count(),+ 0,+ "signed out",+ );} finally {- await ctx.request.post(`${app}/api/auth/login`, { data: { email, password } }).catch(() => {});- const gone = await ctx.request.delete(`${app}/api/auth/me`, { data: { password } }).catch(() => null);- if (gone?.status() !== 204) console.warn(` (couldn't delete ${email}: ${gone?.status()})`);+ await ctx.request+ .post(`${app}/api/auth/login`, { data: { email, password } })+ .catch(() => {});+ const gone = await ctx.request+ .delete(`${app}/api/auth/me`, { data: { password } })+ .catch(() => null);+ if (gone?.status() !== 204)+ console.warn(` (couldn't delete ${email}: ${gone?.status()})`);await ctx.close();}}diff --git a/tests/goal-row.test.ts b/tests/goal-row.test.tsnew file mode 100644index 00000000..4bf8f14a--- /dev/null+++ b/tests/goal-row.test.ts@@ -0,0 +1,170 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { createElement, type ReactNode } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it, vi } from "vitest";++vi.mock("next/navigation", () => ({+ useRouter: () => ({ prefetch: () => {}, push: () => {}, replace: () => {}, back: () => {}, refresh: () => {} }),+ usePathname: () => "/",+ useSearchParams: () => new URLSearchParams(),+}));++import { GOAL_ASSIST_PROMPTS, GoalBand, GoalRow, goalAssistHref, rovingTarget } from "@/components/nav/goal-row";+import { NavUiProvider } from "@/components/nav/nav-ui";+import { ASSIST_PROMPT_MAX } from "@/lib/assist";+import { APPS, EFFECTS, MOTIONS, getPreset } from "@/lib/catalog";+import { presetHref } from "@/lib/home-showcase";+import { navCovers } from "@/lib/nav-covers";+import { GOALS, goalBand, tapHref, type ViewerKind } from "@/lib/nav-model";+import { presetCover } from "@/lib/preset-covers";++/*+ * Home's goal row (src/components/nav/goal-row.tsx): six goals, each opening a band of its studios, one-tap presets and+ * finishing tools, all from the nav model, with real covers. The page reads the presets' names on the server.+ */++const names: Record<string, string> = Object.fromEntries(GOALS.flatMap((g) => g.taps.map((t) => [t.preset, getPreset(t.preset)?.name ?? ""])));+const covers = navCovers();+// The provider as createElement types it with its children passed after the props.+const Nav = NavUiProvider as (p: { covers: typeof covers; children?: ReactNode }) => ReactNode;++const render = (node: ReactNode) =>+ renderToStaticMarkup(+ createElement(QueryClientProvider, { client: new QueryClient() }, createElement(Nav, { covers }, node)),+ );+const band = (id: (typeof GOALS)[number]["id"], kind: ViewerKind | undefined) => render(createElement(GoalBand, { id, kind, names, onClose: () => {} }));+/** Every href in the markup, in order (React escapes & as &). */+const hrefs = (html: string) => [...html.matchAll(/href="([^"]*)"/g)].map((m) => m[1].replaceAll("&", "&"));+/** The markup's words, without its tags. */+const words = (html: string) => html.replace(/<[^>]+>/g, " ");+const count = (html: string, s: string) => html.split(s).length - 1;+const KINDS: (ViewerKind | undefined)[] = [undefined, "guest", "account", "owner"];+const TYPE_OF = { App: "app", "Camera motion": "motion", Effect: "effect" } as const;+const GALLERY = new Set([...APPS, ...MOTIONS, ...EFFECTS].map((p) => p.id));++describe("goal row keys", () => {+ it("moves between the goals with the arrows, Home and End, wrapping at the ends", () => {+ expect(rovingTarget("ArrowRight", 0, 6)).toBe(1);+ expect(rovingTarget("ArrowRight", 5, 6)).toBe(0);+ expect(rovingTarget("ArrowLeft", 0, 6)).toBe(5);+ expect(rovingTarget("ArrowLeft", 3, 6)).toBe(2);+ expect(rovingTarget("Home", 4, 6)).toBe(0);+ expect(rovingTarget("End", 1, 6)).toBe(5);+ });++ it("leaves every other key alone", () => {+ for (const key of ["Enter", " ", "Tab", "ArrowUp", "ArrowDown", "Escape", "a"]) expect(rovingTarget(key, 2, 6)).toBeNull();+ expect(rovingTarget("ArrowRight", 0, 0)).toBeNull();+ });+});++describe("goal row data", () => {+ it("offers six goals in the row's order", () => {+ expect(GOALS.map((g) => g.id)).toEqual(["film", "social", "sell", "people", "edit", "sound"]);+ });++ it("links each one-tap preset where its gallery card links it, and names it as the catalog does", () => {+ for (const g of GOALS) {+ expect(g.taps.length, g.id).toBeGreaterThanOrEqual(2);+ expect(g.taps.length, g.id).toBeLessThanOrEqual(4);+ for (const t of g.taps) {+ const p = getPreset(t.preset);+ expect(p, t.preset).toBeDefined();+ // Its own gallery card (not an old id kept as an alias of another).+ expect(GALLERY.has(t.preset), t.preset).toBe(true);+ expect(p!.type, t.preset).toBe(TYPE_OF[t.kind]);+ expect(presetCover(t.preset), t.preset).toBeDefined();+ expect(names[t.preset]).toBe(p!.name);+ expect(tapHref(t.preset)).toBe(presetHref(t.preset));+ }+ }+ expect(tapHref("app-giant-product")).toBe("/apps/app-giant-product");+ expect(tapHref("motion-drone-reveal")).toBe("/video?preset=motion-drone-reveal");+ });++ it("types a goal's plan into Assist only for the goals that offer it", () => {+ for (const g of GOALS) {+ const href = goalAssistHref(g.id);+ if (!g.assist) continue;+ const prompt = GOAL_ASSIST_PROMPTS[g.id];+ expect(prompt, g.id).toBeTruthy();+ expect(prompt!.length).toBeLessThanOrEqual(ASSIST_PROMPT_MAX);+ expect(href).toBe(`/assist?prompt=${encodeURIComponent(prompt!)}`);+ expect(new URL(href!, "http://x").searchParams.get("prompt")).toBe(prompt);+ }+ for (const id of Object.keys(GOAL_ASSIST_PROMPTS)) expect(GOALS.find((g) => g.id === id)?.assist, id).toBe(true);+ });+});++describe("goal row markup", () => {+ it("renders closed: six goal buttons, one tab stop, no band and no pictures yet", () => {+ const html = render(createElement(GoalRow, { names }));+ expect(html).toContain('role="toolbar"');+ expect(html).toContain('aria-label="Start from a goal"');+ expect(count(html, "data-goal=")).toBe(6);+ expect(count(html, 'aria-expanded="false"')).toBe(6);+ expect(html).not.toContain('aria-expanded="true"');+ expect(count(html, 'aria-controls="goal-band"')).toBe(6);+ expect(count(html, 'tabindex="0"')).toBe(1);+ expect(count(html, 'tabindex="-1"')).toBe(5);+ expect(html.indexOf('tabindex="0"')).toBeLessThan(html.indexOf('data-goal="social"'));+ for (const g of GOALS) expect(html).toContain(`data-goal="${g.id}"`);+ // Each label in the row's order (its bold copy, which keeps the width, is hidden from screen readers).+ const order = GOALS.map((g) => html.indexOf(`>${g.label.replace("&", "&")}<`));+ expect(order.every((i) => i > 0)).toBe(true);+ expect([...order].sort((a, b) => a - b)).toEqual(order);+ expect(html).toContain("All studios and tools");+ expect(html).not.toContain('id="goal-band"');+ expect(html).not.toContain("<img");+ });++ for (const g of GOALS) {+ it(`opens the ${g.id} band with the model's studios, presets and tools`, () => {+ for (const kind of KINDS) {+ const html = band(g.id, kind);+ const want = goalBand(g.id, kind);+ expect(html).toContain('id="goal-band"');+ expect(html).toContain('aria-labelledby="goal-band-title"');+ expect(html).toContain(`id="goal-band-title"`);+ expect(html).toContain(g.title.replace("&", "&"));+ expect(html).toContain(`aria-label="Close ${g.title.replace("&", "&")}"`);+ const links = hrefs(html).filter((h) => !h.startsWith("/assist?prompt="));+ expect(links).toEqual([...want.cards.map((e) => e.href), ...g.taps.map((t) => tapHref(t.preset)), ...want.finish.map((e) => e.href)]);+ expect(want.cards.length, g.id).toBeGreaterThanOrEqual(4);+ expect(want.cards.length, g.id).toBeLessThanOrEqual(5);+ for (const t of g.taps) {+ expect(html).toContain(names[t.preset]);+ // Its real cover, at the versioned URL the server resolved.+ const c = covers[t.preset];+ expect(html.includes(c.thumb) || html.includes(c.poster), t.preset).toBe(true);+ }+ for (const e of want.cards.filter((e) => e.cover)) {+ const c = covers[e.cover!];+ expect(html.includes(c.poster) || html.includes(c.thumb), e.id).toBe(true);+ }+ }+ });+ }++ it("shows Plan it with Assist to the owner only, on the goals that have it", () => {+ for (const g of GOALS) {+ for (const kind of KINDS) {+ const html = band(g.id, kind);+ const shown = kind === "owner" && !!g.assist;+ expect(html.includes("Plan it with Assist"), `${g.id} ${kind}`).toBe(shown);+ expect(hrefs(html).some((h) => h.startsWith("/assist?prompt=")), `${g.id} ${kind}`).toBe(shown);+ }+ }+ });++ it("never shows a guest or an account a word about the studio's own setup", () => {+ for (const g of GOALS) {+ for (const kind of [undefined, "guest", "account"] as const) {+ const text = words(band(g.id, kind));+ for (const w of ["ComfyUI", "add key", "Add key", "offline", "online", "Paid APIs only", "Open source only", "Placeholder", "Plan it with Assist"]) {+ expect(text.includes(w), `${g.id} ${kind}: ${w}`).toBe(false);+ }+ }+ }+ });+});diff --git a/tests/instant-tabs.test.ts b/tests/instant-tabs.test.tsindex be497e59..7351b6cd 100644--- a/tests/instant-tabs.test.ts+++ b/tests/instant-tabs.test.ts@@ -41,8 +41,7 @@ describe("hub tabs never leave the screen during a switch", () => {expect(chrome).toMatch(/<HubCtx\.Provider value=\{store\}>/);expect(chrome).toMatch(/const slotRef = useCallback\(\(el: HTMLElement \| null\) => store\.set\(el\), \[store\]\);/);expect(chrome).toMatch(/<div ref=\{slotRef\} className="contents" \/>/);- // The sidebar's context takes the phone's answer in a transition after hydration, for the same reason.- expect(src("src/components/ui/sidebar.tsx")).toMatch(/const isMobile = useIsMobileAfterHydration\(\)/);+ // The phone's answer comes in a transition after hydration, for the same reason.expect(src("src/hooks/use-mobile.ts")).toMatch(/React\.startTransition\(read\)/);});@@ -108,16 +107,16 @@ describe("other tab bars switch without a round trip", () => {expect(lib).not.toMatch(/router\.replace\(/);});- it("the sidebar rows next to the open page's row prefetch once the page is idle; the others on hover, touch or focus", () => {- const sidebar = src("src/components/app-sidebar.tsx");- expect(sidebar).toMatch(/const NEAR_ROWS = 2;/);- expect(sidebar).toMatch(/<IntentLink\s+href=\{item\.href\}\s+eager=\{item\.eager\}\s+settled=\{here >= 0 && i !== here && Math\.abs\(i - here\) <= NEAR_ROWS\}\s/);- // The clicked row is the open page's row from the next frame on, in every group; the address takes over once it moves.- expect(sidebar).toMatch(/onClick=\{\(e\) => isPlainClick\(e\) && setTappedRow\(item\.href\)\}/);- expect(sidebar).toMatch(/useLayoutEffect\(\(\) => setTappedRow\(null\), \[pathname, search\]\);/);- expect(sidebar).toMatch(/const active = navActive\(item\.href, at, where, hrefs\);/);+ it("the bar's routes prefetch on hover, touch or focus, a panel's when it opens, after the page's own tabs; a clicked bar link is marked at once", () => {+ const bar = src("src/components/nav/top-bar.tsx");+ // The clicked link is the open page's item from the next frame on; the address takes over once it moves.+ expect(bar).toMatch(/const \[tapped, onTap\] = useTappedTab<string>\(pathname\);/);+ expect(bar).toMatch(/active=\{barActive\(tapped \?\? pathname\)\}/);+ expect(bar).toMatch(/isPlainClick\(e\) && onTap\?\.\(href\)/);+ // A panel's routes (the launcher, Create, More, a phone sheet) wait in the "nav" lane, behind the page's own tabs.+ expect(src("src/components/nav/nav-prefetch.tsx")).toMatch(/queueIdlePrefetch\("nav", href, \(\) => go\(href\)\)/);const link = src("src/components/intent-link.tsx");- // Also the rows scrolled out of view, in the "nav" lane (after the page's own tabs), not the Link's viewport prefetch.+ // A settled link prefetches also when scrolled out of view, in the "nav" lane (after the page's own tabs), not the Link's viewport prefetch.expect(link).toMatch(/useIdlePrefetch\(settled && href \? \[href\] : null, "nav"\);/);expect(link).toMatch(/prefetch=\{eager \|\| intent \? null : false\}/);});@@ -129,7 +128,7 @@ describe("other tab bars switch without a round trip", () => {const marketing = src("src/components/marketing/shell.tsx");expect(marketing).toMatch(/useTappedTab<SuiteTab>\(active\)/);expect(marketing).toMatch(/aria-current=\{t\.id === current \? "page" : undefined\}/);- // The other tools' pages go ahead of the sidebar's routes.+ // The other tools' pages go ahead of the navigation's routes.expect(marketing).toMatch(/useIdlePrefetch\(\s*TABS\.filter\(\(t\) => t\.id !== active\)\.map\(\(t\) => t\.href\),\s*"page",?\s*\)/);});@@ -170,7 +169,7 @@ describe("other tab bars switch without a round trip", () => {});});-describe("idle prefetches: the page's own tabs go before the sidebar's routes", () => {+describe("idle prefetches: the page's own tabs go before the navigation's routes", () => {let clock = 0;let idle: (() => void)[] = [];let observed: ((list: { getEntries(): unknown[] }) => void) | null = null;@@ -219,7 +218,7 @@ describe("idle prefetches: the page's own tabs go before the sidebar's routes",vi.resetModules();});- it("issues the page's tabs first, and the sidebar's rows once the server has answered every tab and gone quiet", async () => {+ it("issues the page's tabs first, and the navigation's routes once the server has answered every tab and gone quiet", async () => {const { queueIdlePrefetch } = await load();queueIdlePrefetch("nav", "/image", () => order.push("row image"));queueIdlePrefetch("page", "/audio/music", () => order.push("tab music"));@@ -245,7 +244,7 @@ describe("idle prefetches: the page's own tabs go before the sidebar's routes",expect(order.at(-1)).toBe("tab loop");});- it("lets the sidebar's rows go after 8 s at the latest", async () => {+ it("lets the navigation's routes go after 8 s at the latest", async () => {const { queueIdlePrefetch } = await load();queueIdlePrefetch("page", "/audio/music", () => order.push("tab music"));queueIdlePrefetch("nav", "/image", () => order.push("row image"));@@ -256,7 +255,7 @@ describe("idle prefetches: the page's own tabs go before the sidebar's routes",expect(order).toEqual(["tab music", "row image"]);});- it("with no tabs on the page, prefetches the sidebar's rows once the page's own prefetches have gone quiet", async () => {+ it("with no tabs on the page, prefetches the navigation's routes once the page's own prefetches have gone quiet", async () => {const { queueIdlePrefetch } = await load();queueIdlePrefetch("nav", "/image", () => order.push("row image"));idle[0]();@@ -269,7 +268,7 @@ describe("idle prefetches: the page's own tabs go before the sidebar's routes",expect(order).toEqual(["row image"]);});- it("drops the sidebar's idle prefetches for someone who asked to save data, never the page's own tabs", async () => {+ it("drops the navigation's idle prefetches for someone who asked to save data, never the page's own tabs", async () => {const { queueIdlePrefetch } = await load();vi.stubGlobal("navigator", { connection: { saveData: true } });queueIdlePrefetch("nav", "/image", () => order.push("row image"));diff --git a/tests/nav-bar.test.ts b/tests/nav-bar.test.tsnew file mode 100644index 00000000..96dc3377--- /dev/null+++ b/tests/nav-bar.test.ts@@ -0,0 +1,382 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { createElement, type ReactNode } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { StatusInfo, ViewerInfo } from "@/lib/api";++/*+ * The top bar (src/components/nav/top-bar.tsx) and what hangs from it: the Studios launcher, the Create menu, the+ * account menu and the status the sidebar's footer used to show. The static shell is the same for everyone and says no+ * status; once the viewer is known, the owner's words go only to the owner.+ */++const state = vi.hoisted(() => ({+ path: "/",+ hydrated: false,+ viewer: undefined as ViewerInfo | undefined,+ status: undefined as StatusInfo | undefined,+ mode: "both" as "both" | "open" | "cloud",+}));++vi.mock("next/navigation", () => ({+ useRouter: () => ({ prefetch: () => {}, push: () => {}, replace: () => {}, back: () => {}, refresh: () => {} }),+ usePathname: () => state.path,+ useSearchParams: () => new URLSearchParams(),+}));+vi.mock("@/lib/api", async (load) => ({+ ...(await load<typeof import("@/lib/api")>()),+ useHydrated: () => state.hydrated,+ useViewer: () => ({ data: state.viewer }),+ useStatus: () => ({ data: state.status }),+ useEngineMode: () => state.mode,+}));++const { TopBar, barActive, prefetchHrefs } = await import("@/components/nav/top-bar");+const { LauncherColumns, launcherCurrent, launcherMove, LAUNCHER_ID } = await import("@/components/nav/studios-launcher");+const { CREATE_HREFS, createColumns } = await import("@/components/nav/create-menu");+const { AccountSections } = await import("@/components/nav/account-menu");+const { avatarDot, refillWords } = await import("@/components/nav/status-chips");+const { COVER_SIZES, CoverThumb } = await import("@/components/nav/cover-thumb");+const { NavUiProvider } = await import("@/components/nav/nav-ui");+const { navCovers } = await import("@/lib/nav-covers");+const { entriesFor, entry, launcherColumns, NAV_ENTRIES, studioCount } = await import("@/lib/nav-model");++const covers = navCovers();+const Nav = NavUiProvider as (p: { covers: typeof covers; children?: ReactNode }) => ReactNode;+const render = (node: ReactNode) => renderToStaticMarkup(createElement(QueryClientProvider, { client: new QueryClient() }, createElement(Nav, { covers }, node)));+/** Every link in the markup: its tag (attributes) and its href (React escapes & as &). */+const anchors = (html: string) => [...html.matchAll(/<a\s[^>]*>/g)].map((m) => ({ tag: m[0], href: (/href="([^"]*)"/.exec(m[0])?.[1] ?? "").replaceAll("&", "&") }));+const hrefs = (html: string) => anchors(html).map((a) => a.href);+const words = (html: string) => html.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ");+const count = (html: string, s: string) => html.split(s).length - 1;++/** What only the owner may read: the install's status and its modes. */+const OWNER_WORDS = ["ComfyUI", "add key", "offline", "Paid APIs only", "Open source only", "Placeholder", "Cloud models", "Your setup", "Models & licences"];++const OWNER: ViewerInfo = { signedIn: true, owner: true, publicSignup: true };+const ACCOUNT: ViewerInfo = { signedIn: true, owner: false, publicSignup: true, account: { email: "[email protected]" } };+const GUEST: ViewerInfo = { signedIn: false, owner: false, publicSignup: true };+const install = (extra: Partial<StatusInfo> = {}): StatusInfo => ({+ providers: { fal: { label: "fal.ai", configured: false }, replicate: { label: "Replicate", configured: false }, comfyui: { label: "ComfyUI", configured: false } },+ demoMode: "on",+ engineMode: "both",+ cloudProvider: "fal",+ ...extra,+});++beforeEach(() => {+ state.path = "/";+ state.hydrated = false;+ state.viewer = undefined;+ state.status = undefined;+ state.mode = "both";+});++describe("launcher keys", () => {+ const cols = [8, 6, 5, 6, 4];++ it("moves up and down a column and stops at its ends", () => {+ expect(launcherMove(cols, { col: 0, row: 0 }, "ArrowDown")).toEqual({ col: 0, row: 1 });+ expect(launcherMove(cols, { col: 0, row: 7 }, "ArrowDown")).toBeNull();+ expect(launcherMove(cols, { col: 2, row: 3 }, "ArrowUp")).toEqual({ col: 2, row: 2 });+ expect(launcherMove(cols, { col: 2, row: 0 }, "ArrowUp")).toBeNull();+ });++ it("goes to the same place in the next column, or its last link when it is shorter", () => {+ expect(launcherMove(cols, { col: 0, row: 2 }, "ArrowRight")).toEqual({ col: 1, row: 2 });+ expect(launcherMove(cols, { col: 0, row: 7 }, "ArrowRight")).toEqual({ col: 1, row: 5 });+ expect(launcherMove(cols, { col: 3, row: 5 }, "ArrowRight")).toEqual({ col: 4, row: 3 });+ expect(launcherMove(cols, { col: 1, row: 4 }, "ArrowLeft")).toEqual({ col: 0, row: 4 });+ expect(launcherMove(cols, { col: 0, row: 4 }, "ArrowLeft")).toBeNull();+ expect(launcherMove(cols, { col: 4, row: 1 }, "ArrowRight")).toBeNull();+ });++ it("jumps to a column's first and last with Home and End, and leaves other keys alone", () => {+ expect(launcherMove(cols, { col: 1, row: 3 }, "Home")).toEqual({ col: 1, row: 0 });+ expect(launcherMove(cols, { col: 1, row: 3 }, "End")).toEqual({ col: 1, row: 5 });+ expect(launcherMove(cols, { col: 1, row: 0 }, "Home")).toBeNull();+ for (const key of ["Enter", " ", "Tab", "Escape", "a"]) expect(launcherMove(cols, { col: 1, row: 1 }, key)).toBeNull();+ });++ it("skips an empty column and does nothing in one", () => {+ expect(launcherMove([3, 0, 2], { col: 0, row: 2 }, "ArrowRight")).toEqual({ col: 2, row: 1 });+ expect(launcherMove([3, 0, 2], { col: 1, row: 0 }, "ArrowDown")).toBeNull();+ });+});++describe("which bar item holds the page", () => {+ it("marks Studios for a studio and its own pages, Create for the create tools", () => {+ expect(barActive("/marketing")).toMatchObject({ studios: true, create: false });+ expect(barActive("/marketing/click-to-ad").studios).toBe(true);+ expect(barActive("/audio/clean").studios).toBe(true);+ expect(barActive("/cinema/abc123").studios).toBe(true);+ expect(barActive("/image")).toMatchObject({ create: true, studios: false });+ expect(barActive("/live-edit").create).toBe(true);+ });++ it("marks the galleries, Canvas, Assist and Library on their pages", () => {+ expect(barActive("/apps")).toMatchObject({ apps: true, studios: false });+ expect(barActive("/apps/app-billboard-ad").apps).toBe(true);+ expect(barActive("/motions").motions).toBe(true);+ expect(barActive("/effects").motions).toBe(true);+ expect(barActive("/canvas/p1").canvas).toBe(true);+ expect(barActive("/assist/skills").assist).toBe(true);+ expect(barActive("/library").library).toBe(true);+ });++ it("marks nothing on Home, Settings or a page outside the nav", () => {+ for (const p of ["/", "/settings", "/privacy", ""]) expect(Object.values(barActive(p)).some(Boolean), p).toBe(false);+ });++ it("names the launcher entry of the open page for aria-current", () => {+ expect(launcherCurrent("/marketing")).toBe("marketing");+ expect(launcherCurrent("/audio/music")).toBe("audio-music");+ expect(launcherCurrent("/audio")).toBe("audio");+ expect(launcherCurrent("/audio/dialogue")).toBe("audio");+ expect(launcherCurrent("/apps/app-x")).toBe("apps");+ expect(launcherCurrent("/image")).toBeUndefined();+ });+});++describe("the launcher's columns", () => {+ const html = render(createElement(LauncherColumns, { kind: undefined, now: Date.parse("2026-11-02") }));++ it("shows every studio, Apps and the Sound column, 8/6/5/6/5/3, each column's lead first", () => {+ const links = hrefs(html);+ expect(links).toHaveLength(33);+ expect(new Set(links).size).toBe(33);+ expect(launcherColumns(undefined).map((c) => 1 + c.rest.length)).toEqual([8, 6, 5, 6, 5, 3]);+ expect(launcherColumns(undefined).map((c) => c.lead.id)).toEqual(["cinema", "shorts", "marketing", "fashion-factory", "audio", "upscale"]);+ expect(html).toContain("grid-cols-6");+ for (const [i, c] of launcherColumns(undefined).entries()) {+ const at = (href: string) => anchors(html).find((a) => a.href === href)?.tag ?? "";+ expect(at(c.lead.href)).toContain(`data-col="${i}" data-row="0"`);+ c.rest.forEach((e, r) => expect(at(e.href), e.id).toContain(`data-col="${i}" data-row="${r + 1}"`));+ }+ expect(studioCount()).toBe(28);+ });++ it("labels the groups, and every link has its studio's real cover in a box of fixed size", () => {+ for (const label of ["Film & video", "Social & shorts", "Sell & advertise", "People & fashion", ">Sound<", "Finish & convert"]) expect(html).toContain(label);+ for (const c of launcherColumns(undefined)) {+ for (const e of [c.lead, ...c.rest]) {+ const cover = covers[e.cover!];+ expect(cover, e.id).toBeDefined();+ expect(html).toContain(`src="${cover.thumb.replaceAll("&", "&")}"`);+ }+ // The lead's 4:3 card picks the poster on sharp screens.+ expect(html).toContain(`${covers[c.lead.cover!].poster} 512w`);+ }+ expect(count(html, 'loading="eager"')).toBe(33);+ expect(count(html, 'alt=""')).toBe(33);+ });++ it("marks the open page's studio, and nothing else", () => {+ expect(html).not.toContain("aria-current");+ const on = render(createElement(LauncherColumns, { kind: undefined, current: "katana", now: 0 }));+ expect(count(on, 'aria-current="page"')).toBe(1);+ expect(anchors(on).find((a) => a.href === "/katana")?.tag).toContain('aria-current="page"');+ });++ it("shows New badges only until their date", () => {+ const newOnes = NAV_ENTRIES.filter((e) => e.group && e.newUntil);+ const before = render(createElement(LauncherColumns, { kind: undefined, now: 0 }));+ expect(count(before, ">New<")).toBe(newOnes.length);+ const after = render(createElement(LauncherColumns, { kind: undefined, now: Date.parse("2100-01-01") }));+ expect(count(after, ">New<")).toBe(0);+ });+});++describe("cover boxes", () => {+ it("keeps the box when a preset has no cover, with the entry's icon in it", () => {+ const html = render(createElement(CoverThumb, { id: "no-such-preset", size: "row", icon: "Clapperboard" }));+ expect(html).not.toContain("<img");+ expect(html).toContain("<svg");+ expect(html).toContain(COVER_SIZES.row.box);+ });++ it("lets a caller resize the box", () => {+ const html = render(createElement(CoverThumb, { id: "app-upscale", size: "row", className: "h-[42px] w-14" }));+ expect(html).toContain("h-[42px] w-14");+ expect(html).not.toContain("h-[27px]");+ expect(html).toContain('loading="lazy"');+ });+});++describe("the bar's shell", () => {+ it("renders the same for everyone before the viewer is known, with no status words and no panel", () => {+ const html = render(createElement(TopBar));+ expect(html).toContain("<header");+ expect(html).toContain('aria-label="Main"');+ expect(html).toContain('aria-label="Fuobe home"');+ // The panel is not on the page until warmed, so nothing points at it yet.+ expect(html).not.toContain(`aria-controls="${LAUNCHER_ID}"`);+ expect(html).toContain('aria-expanded="false"');+ expect(html).not.toContain(`id="${LAUNCHER_ID}"`);+ expect(html).toContain(`>${studioCount()}<`);+ for (const h of ["/", "/apps", "/canvas", "/assist", "/library", "/?new=1"]) expect(hrefs(html), h).toContain(h);+ // Search's name is the words it shows (sr-only below lg).+ expect(html).toContain(">Search Fuobe</span>");+ expect(html).not.toContain('aria-label="Search Fuobe"');+ expect(html).toContain('aria-keyshortcuts="/ Meta+K Control+K"');+ // The viewer's room is kept: Sign up's by default, the avatar's where an account or the owner was last.+ expect(html).toMatch(/data-slot="viewer" class="[^"]*w-\[126px\]/);+ for (const w of OWNER_WORDS) expect(words(html), w).not.toContain(w.replace("&", "&"));+ expect(html).not.toContain("Sign up");+ });++ it("gives a guest Sign up and Log in that come back to the page, and no status", () => {+ state.hydrated = true;+ state.viewer = GUEST;+ state.status = install({ viewer: { kind: "guest", gpu: { connected: false } } });+ state.path = "/marketing";+ const html = render(createElement(TopBar));+ expect(hrefs(html)).toContain("/login?signup=1&next=%2Fmarketing");+ expect(hrefs(html)).toContain("/login?next=%2Fmarketing");+ expect(html).toContain('aria-label="Menu"');+ for (const w of OWNER_WORDS) expect(words(html), w).not.toContain(w.replace("&", "&"));+ expect(html).not.toContain("data-dot");+ // On a studio's page the Studios button is marked.+ expect(html).toMatch(/<button[^>]*data-studios-trigger[^>]*data-active="true"/);+ });++ it("gives an account its avatar, with a dot only when its own GPU answers", () => {+ state.hydrated = true;+ state.viewer = ACCOUNT;+ state.status = install({ viewer: { kind: "account", gpu: { connected: false } } });+ let html = render(createElement(TopBar));+ expect(html).toContain('aria-label="Account: [email protected]"');+ expect(html).not.toContain("data-dot");+ state.status = install({ viewer: { kind: "account", gpu: { connected: true, online: true } } });+ html = render(createElement(TopBar));+ expect(html).toContain('data-dot="ok"');+ for (const w of OWNER_WORDS) expect(words(html), w).not.toContain(w.replace("&", "&"));+ });++ it("gives the owner a dot for the install's status and keeps the words for the menu", () => {+ state.hydrated = true;+ state.viewer = OWNER;+ state.status = install();+ const html = render(createElement(TopBar));+ expect(html).toContain('data-dot="warn"');+ expect(html).toContain("Account and settings, something needs a look");+ // Placeholders on: the owner's pill (it says so itself).+ expect(html).toContain("Placeholders on");+ expect(html).not.toContain("ComfyUI");+ });+});++describe("the account menu's sections (as the phone's You sheet shows them)", () => {+ const sheet = () => render(createElement(AccountSections, { variant: "sheet" }));++ it("shows a guest how to sign up and their own GPU, nothing of the install", () => {+ state.hydrated = true;+ state.viewer = GUEST;+ state.status = install({ viewer: { kind: "guest", gpu: { connected: false } } });+ state.path = "/image";+ const html = sheet();+ expect(words(html)).toContain("Sign up free");+ expect(hrefs(html)).toContain("/login?signup=1&next=%2Fimage");+ expect(hrefs(html)).toContain("/login?signup=1&next=%2Fconnect");+ expect(words(html)).toContain("Your GPU");+ expect(words(html)).toContain("Source on GitHub");+ // Thanks & licences is everyone's to read.+ expect(hrefs(html)).toContain("/settings/licences");+ for (const w of [...OWNER_WORDS, "Settings", "Sign out"]) expect(words(html), w).not.toContain(w.replace("&", "&"));+ });++ it("shows an account its email, its own GPU, Settings and Sign out, nothing of the install", () => {+ state.hydrated = true;+ state.viewer = ACCOUNT;+ state.status = install({ viewer: { kind: "account", gpu: { connected: false } } });+ const html = sheet();+ expect(words(html)).toContain("[email protected]");+ for (const w of ["Settings", "Your GPU", "Sign out", "Source on GitHub"]) expect(words(html), w).toContain(w);+ expect(hrefs(html)).toEqual(expect.arrayContaining(["/settings", "/connect", "/settings/licences"]));+ for (const w of OWNER_WORDS) expect(words(html), w).not.toContain(w.replace("&", "&"));+ });++ it("shows an account's balance instead of the GPU line when the studio bills", () => {+ state.hydrated = true;+ state.viewer = ACCOUNT;+ state.status = install({ viewer: { kind: "account", gpu: { connected: false }, balance: { amount: 3, chip: "3 runs left", text: "Free runs", detail: [] } } });+ const html = sheet();+ expect(words(html)).toContain("3 runs left");+ });++ it("shows the owner the install's status as the sidebar's footer did", () => {+ state.hydrated = true;+ state.viewer = OWNER;+ state.status = install({ providers: { fal: { label: "fal.ai", configured: true }, comfyui: { label: "ComfyUI", configured: false } } });+ const html = sheet();+ for (const w of ["Your setup", "Cloud models", "connected", "ComfyUI", "offline", "Placeholders on", "Models & licences", "Settings"]) expect(words(html).replaceAll("&", "&"), w).toContain(w);+ expect(words(html)).not.toContain("Sign out");+ state.mode = "open";+ expect(words(sheet())).toContain("Open source only");+ expect(words(sheet())).not.toContain("Cloud models");+ });++ it("shows only what anyone may see while the viewer is unknown", () => {+ state.status = install();+ const html = sheet();+ for (const w of [...OWNER_WORDS, "Sign out", "Settings", "Sign up"]) expect(words(html), w).not.toContain(w.replace("&", "&"));+ expect(words(html)).toContain("Source on GitHub");+ });+});++describe("the avatar's dot", () => {+ it("is the owner's install status, green or amber by the engine mode's needs", () => {+ const none = install();+ const cloud = install({ providers: { fal: { label: "", configured: true } } });+ const both = install({ providers: { fal: { label: "", configured: true }, comfyui: { label: "", configured: true } } });+ expect(avatarDot("owner", none, "both")).toBe("warn");+ expect(avatarDot("owner", cloud, "both")).toBe("warn");+ expect(avatarDot("owner", cloud, "cloud")).toBe("ok");+ expect(avatarDot("owner", both, "both")).toBe("ok");+ expect(avatarDot("owner", install({ ownerGpu: { mode: "computer", online: true } }), "open")).toBe("ok");+ expect(avatarDot("owner", install({ ownerGpu: { mode: "computer", online: false } }), "open")).toBe("warn");+ });++ it("is only ever green for an account, and absent for a guest or an unknown status", () => {+ const own = (online: boolean) => install({ viewer: { kind: "account", gpu: { connected: true, online } } });+ expect(avatarDot("account", own(true), "both")).toBe("ok");+ expect(avatarDot("account", own(false), "both")).toBeNull();+ expect(avatarDot("account", install({ viewer: { kind: "account", gpu: { connected: false } } }), "both")).toBeNull();+ expect(avatarDot("guest", own(true), "both")).toBeNull();+ expect(avatarDot("owner", undefined, "both")).toBeNull();+ expect(avatarDot(undefined, install(), "both")).toBeNull();+ // A visitor's status (viewer set) never lights the owner's dot.+ expect(avatarDot("owner", own(true), "both")).toBeNull();+ });++ it("says when a balance refills in the visitor's own time", () => {+ const now = Date.parse("2026-11-02T10:00:00Z");+ expect(refillWords(now + 5 * 3_600_000, now)).toBe("refills in 5 h");+ expect(refillWords(now + 10 * 60_000, now)).toBe("refills in 10 min");+ expect(refillWords(now - 1, now)).toBe("refills soon");+ });+});++describe("create and prefetch", () => {+ it("puts the create tools in two columns of five", () => {+ const cols = createColumns(undefined);+ expect(cols.map((c) => c.label)).toEqual(["Make", "Edit a picture"]);+ expect(cols.map((c) => c.entries.map((e) => e.id))).toEqual([+ ["image", "video", "assist", "canvas", "storyboard"],+ ["edit", "live-edit", "inpaint", "layers", "color-grade"],+ ]);+ expect(CREATE_HREFS).toHaveLength(10);+ for (const kind of ["guest", "account", "owner"] as const) expect(createColumns(kind).flatMap((c) => c.entries)).toHaveLength(10);+ });++ it("prefetches every launcher, create and library route once, and nothing off the site", () => {+ const list = prefetchHrefs(undefined);+ expect(new Set(list).size).toBe(list.length);+ for (const c of launcherColumns(undefined)) for (const e of [c.lead, ...c.rest]) expect(list).toContain(e.href);+ for (const id of ["image", "video", "edit", "live-edit", "inpaint", "layers", "color-grade", "canvas", "assist", "library", "favorites"]) expect(list).toContain(entry(id)!.href);+ for (const h of list) expect(h.startsWith("/") && !h.includes("#"), h).toBe(true);+ // The same for every viewer: none of these is owner-only.+ expect(prefetchHrefs("owner")).toEqual(list);+ expect(list.every((h) => entriesFor("guest").some((e) => e.href === h))).toBe(true);+ });+});diff --git a/tests/nav-explore.test.ts b/tests/nav-explore.test.tsnew file mode 100644index 00000000..f4e85e0a--- /dev/null+++ b/tests/nav-explore.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from "vitest";+import { EXPLORE_KEY, EXPLORE_MAX, explorable, exploreProgress, nextToTry, parseExplored, withExplored } from "@/lib/nav-explore";+import { entry, studioCount } from "@/lib/nav-model";++describe("explored list in storage", () => {+ it("is kept under one key", () => {+ expect(EXPLORE_KEY).toBe("fuobe:explored");+ });++ it("reads anything unexpected as nothing tried", () => {+ expect(parseExplored(null)).toEqual([]);+ expect(parseExplored(undefined)).toEqual([]);+ expect(parseExplored("")).toEqual([]);+ expect(parseExplored("{not json")).toEqual([]);+ expect(parseExplored('{"a":1}')).toEqual([]);+ expect(parseExplored("[1,2,3]")).toEqual([]);+ expect(parseExplored('["cinema", 3, null, "shorts", "cinema", ""]')).toEqual(["cinema", "shorts"]);+ });++ it("adds an id once, at the end, and keeps the newest", () => {+ const one = withExplored([], "cinema");+ expect(one).toEqual(["cinema"]);+ expect(withExplored(one, "cinema")).toBe(one);+ expect(withExplored(one, "shorts")).toEqual(["cinema", "shorts"]);+ expect(withExplored(one, "")).toBe(one);+ const full = Array.from({ length: EXPLORE_MAX }, (_, i) => `x${i}`);+ const more = withExplored(full, "cinema");+ expect(more).toHaveLength(EXPLORE_MAX);+ expect(more[0]).toBe("x1");+ expect(more.at(-1)).toBe("cinema");+ expect(parseExplored(JSON.stringify([...full, "a", "b"]))).toHaveLength(EXPLORE_MAX);+ });+});++describe("explore progress", () => {+ it("counts the studios a viewer sees, in the units shown everywhere else (28 studios)", () => {+ expect(exploreProgress("guest", []).total).toBe(studioCount());+ expect(exploreProgress("owner", []).total).toBe(studioCount());+ for (const e of explorable("guest")) expect(e.kind).toBe("studio");+ expect(explorable("guest").map((e) => e.id)).not.toContain("settings");+ });++ it("counts only what is explorable and visible", () => {+ expect(exploreProgress("guest", ["cinema", "shorts", "marketing"]).done).toBe(3);+ // Settings, tools and ids that don't exist don't count.+ expect(exploreProgress("guest", ["cinema", "settings", "audio-clean", "image", "nope"]).done).toBe(1);+ });+});++describe("next to try", () => {+ it("prefers what shares the most goals with the last one tried", () => {+ const next = nextToTry("guest", ["cinema"], "cinema")!;+ expect(next.goals).toContain("film");+ expect(next.id).not.toBe("cinema");+ const afterSell = nextToTry("guest", ["marketing"], "marketing")!;+ expect(afterSell.goals).toContain("sell");+ });++ it("skips what was tried, and starts with a group's lead (a premium studio)", () => {+ const first = nextToTry("guest", []);+ expect(first?.id).toBe("cinema");+ expect(first?.lead).toBe(true);+ const tried = ["image", "video"];+ const next = nextToTry("guest", tried);+ expect(tried).not.toContain(next?.id);+ expect(next?.popular).toBe(true);+ });++ it("never suggests settings or tools, and nothing once everything is tried", () => {+ const all = explorable("owner").map((e) => e.id);+ expect(nextToTry("owner", all)).toBeUndefined();+ let list: string[] = [];+ for (let i = 0; i < 45; i++) {+ const n = nextToTry("account", list, list.at(-1));+ if (!n) break;+ expect(n.kind).toBe("studio");+ expect(entry(n.id)?.visibility ?? ["account"]).toContain("account");+ list = withExplored(list, n.id);+ }+ expect(exploreProgress("account", list)).toEqual({ done: studioCount(), total: studioCount() });+ });+});diff --git a/tests/nav-model.test.ts b/tests/nav-model.test.tsnew file mode 100644index 00000000..c46eb370--- /dev/null+++ b/tests/nav-model.test.ts@@ -0,0 +1,329 @@+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { NAV } from "@/components/nav-items";+import { APPS, EFFECTS, getPreset, MOTIONS } from "@/lib/catalog";+import { HUB_MODES } from "@/lib/hubs";+import { navCovers } from "@/lib/nav-covers";+import { NAV_ICONS } from "@/lib/nav-icons";+import {+ activeEntry,+ coverIds,+ entriesFor,+ entry,+ GOALS,+ goalBand,+ isNew,+ LAUNCHER_GROUPS,+ launcherColumns,+ launcherEntries,+ NAV_ENTRIES,+ STEP_COVERS,+ studioCount,+ tapHref,+ viewerKindOf,+ visibleTo,+ type ViewerKind,+} from "@/lib/nav-model";+import { PRESET_COVERS } from "@/lib/preset-covers.generated";+import { hubModePaths, studioRoutes } from "./e2e/_routes.mjs";++const root = path.resolve(__dirname, "..");+const routes = (() => {+ const { routes, patterns } = studioRoutes(root);+ return { paths: new Set([...routes, ...hubModePaths(root)]), patterns };+})();+const pathOf = (href: string) => href.split(/[?#]/)[0];+const q = (s = "") => new URLSearchParams(s);+const KINDS: (ViewerKind | undefined)[] = ["guest", "account", "owner", undefined];++/** The sidebar's 44 rows before the navigation model (origin/main), in their groups and order. */+const OLD_NAV: [string, [string, string][]][] = [+ [+ "Create",+ [+ ["/", "Home"],+ ["/assist", "Assist"],+ ["/image", "Image"],+ ["/video", "Video"],+ ["/edit", "Edit"],+ ["/live-edit", "Live edit"],+ ["/layers", "Layers"],+ ["/inpaint", "Inpaint"],+ ["/color-grade", "Color grading"],+ ["/motions", "Camera motions"],+ ["/effects", "Effects"],+ ["/storyboard", "Storyboard"],+ ["/canvas", "Canvas"],+ ["/apps", "Apps"],+ ],+ ],+ [+ "Library",+ [+ ["/library", "All creations"],+ ["/library?tab=favorites", "Favorites"],+ ],+ ],+ [+ "Studios",+ [+ ["/cinema", "Cinema Studio"],+ ["/shorts", "Shorts Studio"],+ ["/mixed-media", "Mixed Media"],+ ["/marketing", "Marketing Studio"],+ ["/ads", "Ads Studio"],+ ["/moodboards", "Moodboards"],+ ["/photodump", "Photodump"],+ ["/fashion-factory", "Fashion Factory"],+ ["/character-sheet", "Character Sheet"],+ ["/influencer", "AI Influencer"],+ ["/faceless", "Faceless Studio"],+ ["/content-factory", "Content Factory"],+ ["/explainer", "Explainer"],+ ["/lipsync", "Lipsync & avatars"],+ ["/genjutsu", "Genjutsu"],+ ["/character-swap", "Character Swap"],+ ["/motion-control", "Motion control"],+ ["/video-edit", "Edit video"],+ ["/extend", "Extend video"],+ ["/reframe", "Reframe"],+ ["/video-tools", "Video tools"],+ ["/elements", "Elements"],+ ["/upscale", "Upscale"],+ ["/audio", "Audio"],+ ["/katana", "Katana"],+ ["/image-to-3d", "Image to 3D"],+ ["/virality", "Hook check"],+ ],+ ],+ ["More", [["/settings", "Settings"]]],+];++describe("nav model: entries", () => {+ it("has unique ids, and unique links apart from a hub's first mode (the hub's own page)", () => {+ const ids = NAV_ENTRIES.map((e) => e.id);+ expect(new Set(ids).size).toBe(ids.length);+ const firstModes = new Set(Object.entries(HUB_MODES).map(([hub, modes]) => `${hub}-${modes[0].id}`));+ const hrefs = NAV_ENTRIES.filter((e) => !firstModes.has(e.id)).map((e) => e.href);+ expect(new Set(hrefs).size).toBe(hrefs.length);+ for (const id of firstModes) expect(entry(id)?.href).toBe(`/${entry(id)!.parent}`);+ });++ it("links only to pages that exist (or a settings section, an action, the source)", () => {+ const form = ["settings-form.tsx", "gpu/account-gpu-section.tsx", "keys/your-keys.tsx", "owner-settings.tsx"]+ .map((f) => fs.readFileSync(path.join(root, "src/components", f), "utf8"))+ .join("\n");+ for (const e of NAV_ENTRIES) {+ if (e.href === "action:theme") continue;+ if (/^https:\/\/github\.com\//.test(e.href)) continue;+ if (e.href.startsWith("/login")) {+ expect(fs.existsSync(path.join(root, "src/app/login/page.tsx")), e.id).toBe(true);+ continue;+ }+ expect(routes.paths.has(pathOf(e.href)), `${e.id} → ${e.href}`).toBe(true);+ const hash = e.href.split("#")[1];+ if (hash) expect(form, `${e.id}: section #${hash}`).toContain(`id="${hash}"`);+ }+ });++ it("keeps every link the sidebar had, with its label", () => {+ for (const [, rows] of OLD_NAV) for (const [href, label] of rows) expect(NAV_ENTRIES.find((e) => e.href === href)?.label, href).toBe(label);+ });++ it("derives the four groups (Create, Library, Studios, More) exactly as they were: 44 rows", () => {+ expect(NAV.map((g) => [g.label, g.items.map((i) => [i.href, i.label])])).toEqual(OLD_NAV);+ expect(NAV.flatMap((g) => g.items)).toHaveLength(44);+ expect(NAV.find((g) => g.label === "Studios")?.collapsible).toBe(true);+ // The same rows prefetch eagerly, with an icon each and search words.+ expect(+ NAV.flatMap((g) => g.items)+ .filter((i) => i.eager)+ .map((i) => i.href),+ ).toEqual(["/", "/assist", "/image", "/video", "/library"]);+ for (const i of NAV.flatMap((g) => g.items)) {+ expect(typeof i.icon === "function" || typeof i.icon === "object", i.href).toBe(true);+ expect(i.keywords?.length, i.href).toBeGreaterThan(0);+ }+ expect(NAV.flatMap((g) => g.items).find((i) => i.href === "/character-swap")?.short).toBe("Character swap");+ });++ it("names only icons the icon map has", () => {+ for (const e of NAV_ENTRIES) expect(Object.hasOwn(NAV_ICONS, e.icon), `${e.id}: ${e.icon}`).toBe(true);+ for (const g of GOALS) expect(Object.hasOwn(NAV_ICONS, g.icon), g.id).toBe(true);+ });++ it("gives every studio a group, a goal, a short line, a phone label and a real cover", () => {+ for (const e of NAV_ENTRIES.filter((x) => x.kind === "studio")) {+ expect(e.group, e.id).toBeTruthy();+ expect(e.goals.length, e.id).toBeGreaterThan(0);+ // A phone tile shows it on up to two lines of 12.+ expect(e.short, e.id).toBeTruthy();+ for (const w of e.short!.split(" ")) expect(w.length, e.id).toBeLessThanOrEqual(12);+ expect(Object.hasOwn(PRESET_COVERS, e.cover!), `${e.id}: ${e.cover}`).toBe(true);+ }+ for (const e of NAV_ENTRIES) {+ expect(e.what.length, `${e.id}: ${e.what}`).toBeLessThanOrEqual(34);+ expect(e.what, e.id).not.toMatch(/\.$/);+ if (e.kind === "presets") expect(Object.hasOwn(PRESET_COVERS, e.cover!), e.id).toBe(true);+ if (e.short) expect(e.short.length, e.id).toBeLessThanOrEqual(16);+ }+ });++ it("makes every hub mode a tool of its studio, owner-only modes for the owner only", () => {+ for (const [hub, modes] of Object.entries(HUB_MODES)) {+ for (const m of modes) {+ const e = entry(`${hub}-${m.id}`);+ expect(e?.kind, `${hub}/${m.id}`).toBe("tool");+ expect(e?.parent).toBe(hub);+ expect(e?.what).not.toBe(m.label);+ expect(!!e?.visibility, `${hub}/${m.id}`).toBe(!!m.ownerOnly);+ if (m.ownerOnly) expect(e?.visibility).toEqual(["owner"]);+ }+ }+ expect(entry("video-tools-captions")?.href).toBe("/video-tools/captions");+ expect(entry("audio-clean")?.href).toBe("/audio/clean");+ });++ it("marks only entries added after the first studios as new, and the badge ends", () => {+ const fresh = NAV_ENTRIES.filter((e) => e.newUntil).map((e) => e.id);+ expect(fresh.length).toBeLessThan(8);+ const day = (s: string) => Date.parse(s);+ for (const e of NAV_ENTRIES.filter((x) => x.newUntil)) {+ expect(isNew(e, day("2026-11-02"))).toBe(true);+ expect(isNew(e, day("2027-01-01"))).toBe(false);+ }+ expect(isNew(entry("cinema")!)).toBe(false);+ });+});++describe("nav model: launcher", () => {+ it("has 28 studios, Apps and four Audio modes in six columns of 8, 6, 5, 6, 5 and 3, one lead each", () => {+ expect(studioCount()).toBe(28);+ const cols = launcherColumns("owner");+ expect(cols.map((c) => c.group.id)).toEqual(["film", "social", "sell", "people", "sound", "finish"]);+ expect(cols.map((c) => 1 + c.rest.length)).toEqual([8, 6, 5, 6, 5, 3]);+ expect(cols.map((c) => c.lead.id)).toEqual(["cinema", "shorts", "marketing", "fashion-factory", "audio", "upscale"]);+ for (const g of LAUNCHER_GROUPS) expect(NAV_ENTRIES.filter((e) => e.group === g.id && e.lead)).toHaveLength(1);+ expect(launcherEntries("guest")).toHaveLength(33);+ expect(launcherEntries("guest", "sell").map((e) => e.id)).toEqual(["marketing", "ads", "mixed-media", "moodboards", "photodump"]);+ expect(launcherEntries(undefined, "finish").map((e) => e.id)).toEqual(["upscale", "image-to-3d", "apps"]);+ // Sound: the Audio studio, then voice's neighbours (music, sound effects, clean-up, translate & dub); Lipsync stays in Social.+ expect(launcherEntries(undefined, "sound").map((e) => e.href)).toEqual(["/audio", "/audio/music", "/audio/sfx", "/audio/clean", "/audio/translate"]);+ expect(launcherEntries(undefined, "sound").map((e) => e.short)).toEqual(["Audio", "Music", "Sound effects", "Clean up", "Translate"]);+ expect(entry("audio-translate")?.label).toBe("Translate & dub");+ expect(entry("lipsync")?.group).toBe("social");+ for (const e of launcherEntries(undefined)) expect(Object.hasOwn(PRESET_COVERS, e.cover!), `${e.id}: ${e.cover}`).toBe(true);+ // Storyboard is a film studio now.+ expect(entry("storyboard")?.group).toBe("film");+ });++ it("shows the same 33 to everyone", () => {+ for (const k of KINDS) expect(launcherEntries(k).map((e) => e.id)).toEqual(launcherEntries("owner").map((e) => e.id));+ });+});++describe("nav model: who sees what", () => {+ const ids = (k: ViewerKind | undefined) => new Set(entriesFor(k).map((e) => e.id));+ const OWNER_ONLY = ["setting-cloud", "setting-comfyui", "setting-engine", "setting-loras", "setting-training", "setting-text-ai", "setting-assist-connectors", "setting-notifications", "setting-security", "setting-demo", "video-tools-restore"];++ it("keeps the install's settings and its own tools from guests and accounts", () => {+ for (const k of ["guest", "account", undefined] as const) for (const id of OWNER_ONLY) expect(ids(k).has(id), `${k} sees ${id}`).toBe(false);+ for (const id of OWNER_ONLY) expect(ids("owner").has(id), id).toBe(true);+ });++ it("gives an account its own GPU, keys and account, and a guest the way in", () => {+ for (const id of ["your-gpu", "your-keys", "account", "connect", "thanks", "settings"]) expect(ids("account").has(id), id).toBe(true);+ for (const id of ["connect", "signup", "login", "thanks"]) expect(ids("guest").has(id), id).toBe(true);+ // Thanks & licences is everyone's to read; Models & licences' switches are the owner's.+ for (const k of ["guest", "account", undefined] as const) expect(ids(k).has("models-licences"), String(k)).toBe(false);+ for (const id of ["thanks", "models-licences"]) expect(ids("owner").has(id), id).toBe(true);+ for (const id of ["your-gpu", "your-keys", "account"]) expect(ids("guest").has(id), id).toBe(false);+ for (const id of ["signup", "login", "connect", "your-gpu"]) expect(ids("owner").has(id), id).toBe(false);+ });++ it("shows a viewer not known yet what a guest sees, and no more", () => {+ expect([...ids(undefined)]).toEqual([...ids("guest")]);+ expect(visibleTo(entry("setting-comfyui")!, undefined)).toBe(false);+ });++ it("reads the viewer as the sidebar did", () => {+ expect(viewerKindOf(undefined)).toBeUndefined();+ expect(viewerKindOf({ owner: true, publicSignup: true })).toBe("owner");+ expect(viewerKindOf({ owner: false, account: { email: "[email protected]" }, publicSignup: true })).toBe("account");+ expect(viewerKindOf({ owner: false, publicSignup: true })).toBe("guest");+ expect(viewerKindOf({ owner: false, publicSignup: false })).toBe("owner");+ });+});++describe("nav model: goal bands", () => {+ it("has the six goals in order, each with cards, one-tap presets and finishing links", () => {+ expect(GOALS.map((g) => g.id)).toEqual(["film", "social", "sell", "people", "edit", "sound"]);+ for (const g of GOALS) {+ const band = goalBand(g.id, "guest");+ expect(band.cards.length, g.id).toBeGreaterThanOrEqual(4);+ expect(band.cards.length, g.id).toBeLessThanOrEqual(5);+ expect(band.finish.length, g.id).toBeGreaterThanOrEqual(2);+ for (const c of band.cards) expect(c.cover, `${g.id}: ${c.id}`).toBeTruthy();+ expect(g.taps.length, g.id).toBeGreaterThanOrEqual(2);+ }+ expect(goalBand("sell", "guest").cards.map((e) => e.label)).toEqual(["Marketing Studio", "Ads Studio", "Photodump", "Mixed Media", "Moodboards"]);+ expect(GOALS.filter((g) => g.assist).map((g) => g.id)).toEqual(["film", "social", "sell"]);+ });++ it("taps only listed presets with real covers, of the kind it says", () => {+ const listed = new Set([...APPS, ...MOTIONS, ...EFFECTS].map((p) => p.id));+ const kinds = { App: "app", "Camera motion": "motion", Effect: "effect" } as const;+ for (const g of GOALS) {+ for (const t of g.taps) {+ expect(listed.has(t.preset), t.preset).toBe(true);+ expect(getPreset(t.preset)?.type, t.preset).toBe(kinds[t.kind]);+ expect(Object.hasOwn(PRESET_COVERS, t.preset), t.preset).toBe(true);+ }+ }+ expect(tapHref("app-giant-product")).toBe("/apps/app-giant-product");+ expect(tapHref("motion-drone-reveal")).toBe("/video?preset=motion-drone-reveal");+ });+});++describe("nav model: the current page", () => {+ const at = (pathname: string, search = "") => activeEntry(pathname, q(search))?.id;++ it("finds the entry a path is on, the best match winning", () => {+ expect(at("/")).toBe("home");+ expect(at("/cinema")).toBe("cinema");+ expect(at("/cinema/abc123")).toBe("cinema");+ expect(at("/library")).toBe("library");+ expect(at("/library", "tab=favorites")).toBe("favorites");+ expect(at("/settings")).toBe("settings");+ expect(at("/settings/models")).toBe("models-licences");+ expect(at("/settings/licences")).toBe("thanks");+ expect(at("/apps/app-face-swap")).toBe("apps");+ expect(at("/nowhere")).toBeUndefined();+ });++ it("counts a hub's modes and a studio's own pages as the studio", () => {+ expect(at("/audio/clean")).toBe("audio");+ expect(at("/upscale/video")).toBe("upscale");+ expect(at("/video-tools/captions")).toBe("video-tools");+ expect(at("/marketing/click-to-ad")).toBe("marketing");+ expect(at("/assist/skills")).toBe("assist");+ });+});++describe("nav model: covers", () => {+ it("names every cover it shows, and every one resolves to a versioned still and its small copy", () => {+ const ids = coverIds();+ expect(new Set(ids).size).toBe(ids.length);+ for (const e of NAV_ENTRIES) if (e.cover) expect(ids).toContain(e.cover);+ for (const id of Object.values(STEP_COVERS)) expect(ids).toContain(id);+ const covers = navCovers();+ expect(Object.keys(covers).sort()).toEqual([...ids].sort());+ for (const [id, c] of Object.entries(covers)) {+ expect(c.poster, id).toMatch(/^\/previews\/[^?]+\.jpg\?v=[0-9a-f]{8}$/);+ expect(c.thumb, id).toMatch(/^\/previews\/[^?]+\/thumbs\/[^?/]+\.jpg\?v=[0-9a-f]{8}$/);+ }+ // Small enough to pass down from the layout on every page.+ expect(JSON.stringify(covers).length).toBeLessThan(12_000);+ });+});diff --git a/tests/nav-nudges.test.ts b/tests/nav-nudges.test.tsnew file mode 100644index 00000000..af2fd54c--- /dev/null+++ b/tests/nav-nudges.test.ts@@ -0,0 +1,299 @@+import { createElement, type FC, type ReactNode } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { Generation, OutputFile } from "@/lib/catalog/types";++// The hooks NextSteps and the covers read: who is looking and the engine mode (the real ones need the app's queries).+const viewer = vi.hoisted(() => ({ visitor: false, engineMode: "both" as "both" | "open" | "cloud" }));+vi.mock("@/lib/api", () => ({+ useEngineMode: () => viewer.engineMode,+ useLikelyVisitor: () => viewer.visitor,+ useHydrated: () => true,+ useViewer: () => ({ data: undefined }),+}));+// IntentLink prefetches through the router, which a static render has no app router for.+vi.mock("next/navigation", async (load) => ({ ...(await load<typeof import("next/navigation")>()), useRouter: () => ({ prefetch() {}, replace() {}, push() {} }) }));++const { NextSteps, handoffFile, keepGoingTitle } = await import("@/components/nav/next-steps");+const { ExploreProgress, ExploreView } = await import("@/components/nav/explore-progress");+const { exploredEntry, markExplored, readExplored, subscribeExplored } = await import("@/components/nav/explore-tracker");+const { NavUiProvider } = await import("@/components/nav/nav-ui");+const { keepGoing } = await import("@/lib/next-steps");+const { EXPLORE_KEY } = await import("@/lib/nav-explore");+const { coverIds, entry } = await import("@/lib/nav-model");+const { getPreset } = await import("@/lib/catalog");++function gen(outputs: Partial<OutputFile>[], over: Partial<Generation> = {}): Generation {+ return {+ id: "g1",+ batchId: null,+ feature: "image",+ presetId: null,+ modelId: "nano-banana-pro",+ engine: "cloud",+ provider: "fal",+ op: "t2i",+ kind: (outputs[0]?.kind ?? "image") as Generation["kind"],+ status: "succeeded",+ progress: 1,+ message: null,+ prompt: "a fox in the snow",+ request: { feature: "image", modelId: "nano-banana-pro", prompt: "a fox in the snow" },+ outputs: outputs.map((o, i) => ({ url: `/api/files/out-${i}.png`, kind: "image", ...o }) as OutputFile),+ error: null,+ costUsd: null,+ favorite: false,+ createdAt: 0,+ updatedAt: 0,+ completedAt: 0,+ ...over,+ };+}++const person = (prompt = "a fashion model in a red velvet suit on a rooftop at dusk") => gen([{ kind: "image" }], { prompt, request: { feature: "image", modelId: "nano-banana-pro", prompt } });+const product = () => gen([{ kind: "image" }], { prompt: "a perfume bottle on black marble", request: { feature: "image", modelId: "nano-banana-pro", prompt: "a perfume bottle on black marble" } });+const clip = () => gen([{ kind: "video", url: "/api/files/clip.mp4" }], { kind: "video", op: "t2v", feature: "video" });+const sound = () => gen([{ kind: "audio", url: "/api/files/voice.mp3" }], { kind: "audio", op: "tts", feature: "audio" });+const model = () =>+ gen([{ kind: "model3d", url: "/api/files/chair.glb", meta: { poster: "/api/files/chair.png" } }], { kind: "model3d", op: "image-to-3d", feature: "image-to-3d", request: { feature: "image-to-3d", modelId: "hunyuan-3d-3-1-pro", inputs: { images: ["/api/files/photo.png"] } } });++/** Every cover the steps can name, as the server would resolve them. */+const COVERS = Object.fromEntries(coverIds().map((id) => [id, { thumb: `/previews/presets/${id}-thumb.jpg`, poster: `/previews/presets/${id}.jpg` }]));+/** The covers context the chrome provides (children passed the way createElement takes them). */+const Covers = NavUiProvider as FC<{ covers: typeof COVERS; children?: ReactNode }>;+const html = (node: ReactNode) => renderToStaticMarkup(createElement(Covers, { covers: COVERS }, node));+const steps = (g: Generation, variant: "row" | "list" = "row", max?: number, skip?: string[]) => html(createElement(NextSteps, { g, index: 0, variant, max, skip }));+const hrefs = (markup: string) => [...markup.matchAll(/<a [^>]*href="([^"]+)"/g)].map((m) => m[1].replaceAll("&", "&"));++afterEach(() => {+ viewer.visitor = false;+ viewer.engineMode = "both";+ vi.unstubAllGlobals();+});++describe("Keep going with this: under a finished result", () => {+ it("names the result by its kind", () => {+ expect(keepGoingTitle("image")).toBe("Keep going with this picture");+ expect(keepGoingTitle("video")).toBe("Keep going with this clip");+ expect(keepGoingTitle("audio")).toBe("Keep going with this sound");+ expect(keepGoingTitle("model3d")).toBe("Keep going with this model");+ });++ it("shows 3 to 5 steps that each carry the picture, in a group named by its heading", () => {+ const out = steps(person());+ const id = /<div role="group" aria-labelledby="([^"]+)"/.exec(out)?.[1];+ expect(id).toBeTruthy();+ expect(out).toContain(`<p id="${id}"`);+ expect(out).toContain("Keep going with this picture</p>");+ const links = hrefs(out);+ expect(links.length).toBeGreaterThanOrEqual(3);+ expect(links.length).toBeLessThanOrEqual(5);+ for (const h of links) expect(h).toContain(`image=${encodeURIComponent("/api/files/out-0.png")}`);+ // A list of links (ul > li > a), each with a verb and where it goes.+ expect(out).toMatch(/<ul[^>]*><li[^>]*><a /);+ });++ it("covers sit in fixed boxes: decorative, lazy, sized", () => {+ const out = steps(product());+ const imgs = [...out.matchAll(/<img [^>]*>/g)].map((m) => m[0]);+ expect(imgs.length).toBeGreaterThan(0);+ for (const img of imgs) {+ expect(img).toContain('alt=""');+ expect(img).toContain('loading="lazy"');+ expect(img).toMatch(/width="40" height="40"/);+ }+ });++ it("honours max, and skips what the view already offers", () => {+ expect(hrefs(steps(person(), "row", 2))).toHaveLength(2);+ const all = keepGoing(person(), 0, { engineMode: "both", visitor: false, adapters: { characterSheet: true, imageTo3d: true } }, 5);+ const first = all[0];+ const out = hrefs(steps(person(), "row", 5, [first.id]));+ expect(out).not.toContain(first.href);+ expect(out.length).toBeGreaterThanOrEqual(Math.min(3, all.length - 1));+ });++ it("sends only the owner to the studios that run on a self-hosted Fuobe (Character Sheet, Image to 3D)", () => {+ viewer.visitor = false;+ expect(hrefs(steps(person())).some((h) => h.startsWith("/character-sheet?image="))).toBe(true);+ expect(hrefs(steps(product())).some((h) => h.startsWith("/image-to-3d?image="))).toBe(true);+ viewer.visitor = true;+ for (const g of [person(), product(), gen([{ kind: "image" }])]) {+ for (const h of hrefs(steps(g))) expect(h).not.toMatch(/^\/(character-sheet|image-to-3d)\b/);+ }+ });++ it("goes on from clips, sounds and 3D models too", () => {+ const v = steps(clip());+ expect(v).toContain("Keep going with this clip");+ expect(hrefs(v)[0]).toBe(`/extend?video=${encodeURIComponent("/api/files/clip.mp4")}`);+ expect(steps(sound())).toContain("Keep going with this sound");+ const m = steps(model(), "row", 3);+ expect(m).toContain("Keep going with this model");+ expect(hrefs(m).length).toBeGreaterThan(0);+ });++ it("is absent where a result can't go on: failed, deleted, text", () => {+ expect(steps(gen([{ kind: "image" }], { status: "failed" }))).toBe("");+ expect(steps(gen([{ kind: "image" }], { deletedAt: 1 }))).toBe("");+ expect(steps(gen([{ kind: "text", url: "/api/files/t.txt", text: "hi" }], { kind: "text", op: "transcribe" }))).toBe("");+ });++ it("the Viewer's list is stacked rows", () => {+ const out = steps(person(), "list");+ expect(out).toContain("Keep going with this picture");+ expect(out).toContain("min-h-12");+ expect(hrefs(out).length).toBeGreaterThanOrEqual(3);+ });++ it("every step's cover is one the server resolves for the nav", () => {+ const ids = new Set(coverIds());+ for (const g of [person(), product(), gen([{ kind: "image" }]), clip(), sound(), model()]) {+ for (const s of keepGoing(g, 0, { engineMode: "both", visitor: false, adapters: { characterSheet: true, imageTo3d: true } }, 5)) {+ if (s.cover) expect(ids, `${s.id} → ${s.cover}`).toContain(s.cover);+ }+ }+ });++ it("an app a step opens takes the picture in its image slot", () => {+ for (const g of [person(), product(), gen([{ kind: "image" }]), model()]) {+ for (const s of keepGoing(g, 0, { engineMode: "both", visitor: false, adapters: { characterSheet: true, imageTo3d: true } }, 5)) {+ const m = /^\/apps\/([\w-]+)\?image=/.exec(s.href);+ if (!m) continue;+ const preset = getPreset(m[1]);+ expect(preset, m[1]).toBeTruthy();+ expect(preset!.inputs.some((slot) => slot.key === "image" && slot.accept === "image"), m[1]).toBe(true);+ }+ }+ });+});++describe("a picture handed to Character Sheet or Image to 3D", () => {+ it("takes only Fuobe files", () => {+ expect(handoffFile("/api/files/abc123.png")).toBe("/api/files/abc123.png");+ expect(handoffFile("/api/files/uploads/my%20photo.jpg")).toBe("/api/files/uploads/my%20photo.jpg");+ for (const bad of [null, undefined, "", "https://example.com/a.png", "//example.com/a.png", "/api/files/", "/api/other/a.png", "javascript:alert(1)", "/api/files/a.png?x=1", "/api/files/../auth/me", "/api/files/%2e%2e/auth/me", "/api/files/%2E%2E/x", `/api/files/${"a".repeat(301)}`]) {+ expect(handoffFile(bad), String(bad)).toBeUndefined();+ }+ });+});++// ---------------------------------------------------------------------------+// Explore: what this browser has opened++function fakeWindow(opts: { throwGet?: boolean; throwSet?: boolean; noStorage?: boolean } = {}) {+ const store = new Map<string, string>();+ const handlers = new Set<(e: { key: string | null }) => void>();+ const localStorage = {+ getItem: (k: string) => {+ if (opts.throwGet) throw new Error("blocked");+ return store.get(k) ?? null;+ },+ setItem: (k: string, v: string) => {+ if (opts.throwSet) throw new Error("QuotaExceededError");+ store.set(k, v);+ },+ };+ const w: Record<string, unknown> = {+ addEventListener: (t: string, h: (e: { key: string | null }) => void) => t === "storage" && handlers.add(h),+ removeEventListener: (t: string, h: (e: { key: string | null }) => void) => handlers.delete(h),+ };+ // Some browsers throw on the accessor itself when site data is blocked.+ if (opts.noStorage)+ Object.defineProperty(w, "localStorage", {+ get() {+ throw new Error("SecurityError");+ },+ });+ else w.localStorage = localStorage;+ vi.stubGlobal("window", w);+ return { store, fire: (key: string | null) => handlers.forEach((h) => h({ key })), handlers };+}++describe("explore progress: storage", () => {+ it("is unknown on the server (no window)", () => {+ expect(readExplored()).toBeNull();+ expect(() => markExplored("cinema")).not.toThrow();+ });++ it("marks once, keeps the snapshot stable, and reads junk as nothing", () => {+ const { store } = fakeWindow();+ expect(readExplored()).toEqual([]);+ markExplored("cinema");+ markExplored("cinema");+ markExplored("shorts");+ expect(JSON.parse(store.get(EXPLORE_KEY)!)).toEqual(["cinema", "shorts"]);+ const a = readExplored();+ expect(readExplored()).toBe(a);+ store.set(EXPLORE_KEY, "{not json");+ expect(readExplored()).toEqual([]);+ });++ it("never throws when storage is blocked or full, and then shows nothing", () => {+ fakeWindow({ throwGet: true });+ expect(readExplored()).toBeNull();+ expect(() => markExplored("cinema")).not.toThrow();+ fakeWindow({ noStorage: true });+ expect(readExplored()).toBeNull();+ expect(() => markExplored("cinema")).not.toThrow();+ const full = fakeWindow({ throwSet: true });+ expect(() => markExplored("cinema")).not.toThrow();+ expect(full.store.size).toBe(0);+ });++ it("tells subscribers about a mark here and about another tab's, and stops when unsubscribed", () => {+ const w = fakeWindow();+ const seen = vi.fn();+ const off = subscribeExplored(seen);+ markExplored("marketing");+ expect(seen).toHaveBeenCalledTimes(1);+ w.fire(EXPLORE_KEY);+ w.fire(null);+ w.fire("fuobe:viewer");+ expect(seen).toHaveBeenCalledTimes(3);+ off();+ markExplored("ads");+ w.fire(EXPLORE_KEY);+ expect(seen).toHaveBeenCalledTimes(3);+ expect(w.handlers.size).toBe(0);+ });++ it("counts studios, create tools and preset hubs, not Home, the Library or Settings", () => {+ const at = (path: string, q = "") => exploredEntry(path, new URLSearchParams(q))?.id;+ expect(at("/cinema")).toBe("cinema");+ expect(at("/cinema/abc123")).toBe("cinema");+ expect(at("/audio/clean")).toBe("audio");+ expect(at("/image")).toBe("image");+ expect(at("/motions")).toBe("motions");+ expect(at("/apps/app-billboard-ad")).toBe("apps");+ for (const path of ["/", "/library", "/settings", "/settings/models", "/connect"]) expect(at(path), path).toBeUndefined();+ expect(at("/library", "tab=favorites")).toBeUndefined();+ });+});++describe("explore progress: what it shows", () => {+ const genjutsu = entry("genjutsu")!;++ it("renders nothing on the server, whatever is stored", () => {+ fakeWindow().store.set(EXPLORE_KEY, JSON.stringify(["cinema"]));+ expect(html(createElement(ExploreProgress, { variant: "sheet" }))).toBe("");+ });++ it("shows the next studio and the count as one small row", () => {+ const out = html(createElement(ExploreView, { variant: "sheet", done: 9, total: 28, next: genjutsu }));+ expect(out).toContain("9 of 28 studios tried</span>");+ expect(out).toContain("Genjutsu");+ expect(hrefs(out)).toEqual(["/genjutsu"]);+ expect(out).toContain(`aria-label="Next to try: Genjutsu, ${genjutsu.what}. 9 of 28 studios tried"`);+ // Its cover at 40 px, decorative; no big card.+ expect(out).toMatch(/<img [^>]*alt=""/);+ expect(out).toContain("size-10");+ expect(out).not.toContain("aspect-video");+ });++ it("says so warmly when everything is tried", () => {+ const all = html(createElement(ExploreView, { variant: "sheet", done: 28, total: 28 }));+ expect(all).toContain("You have tried every studio");+ expect(hrefs(all)).toEqual([]);+ });+});diff --git a/tests/nav-search.test.ts b/tests/nav-search.test.tsnew file mode 100644index 00000000..8a309b97--- /dev/null+++ b/tests/nav-search.test.ts@@ -0,0 +1,245 @@+import { describe, expect, it } from "vitest";+import { indexEntries, presetThumb, skillEntries } from "@/lib/command-search";+import { entriesFor, NAV_ENTRIES, type ViewerKind } from "@/lib/nav-model";+import { INTENTS, navSearchEntries, queryWords, searchNav, stem, STOPWORDS, type SearchEntry } from "@/lib/nav-search";+import { paletteIndex } from "@/lib/palette-index";++const index = paletteIndex();+/** What the palette searches for a viewer, with every app, motion, effect and model (both engines on). */+const entriesOf = (kind: ViewerKind | undefined, mode: "both" | "open" | "cloud" = "both"): SearchEntry[] => [+ ...navSearchEntries(entriesFor(kind)),+ ...indexEntries(index, mode),+];+const OWNER = entriesOf("owner");+const GUEST = entriesOf("guest");+const ACCOUNT = entriesOf("account");++const labels = (q: string, entries = OWNER) => searchNav(q, entries).best.map((h) => h.label);+const all = (q: string, entries = OWNER) => {+ const r = searchNav(q, entries);+ return [...r.best, ...r.also, ...r.groups.flatMap((g) => g.hits)];+};++describe("reading a query", () => {+ it("drops filler words, unless that leaves nothing", () => {+ expect(queryWords("ad for my perfume")).toEqual(["ad", "perfume"]);+ expect(queryWords("make my product video for amazon")).toEqual(["product", "video", "amazon"]);+ expect(queryWords("how do I")).toEqual(["how", "do", "i"]);+ expect(queryWords(" ")).toEqual([]);+ for (const w of ["a", "the", "for", "my", "make", "create", "new"]) expect(STOPWORDS.has(w)).toBe(true);+ });++ it("folds plurals and -ing, and leaves words that only look plural", () => {+ expect(stem("ads")).toBe("ad");+ expect(stem("perfumes")).toBe("perfume");+ expect(stem("dresses")).toBe("dress");+ expect(stem("talking")).toBe("talk");+ expect(stem("dubbing")).toBe("dub");+ expect(stem("dressing")).toBe("dress");+ expect(stem("dress")).toBe("dress");+ expect(stem("canvas")).toBe("canvas");+ expect(stem("sing")).toBe("sing");+ expect(stem("4k")).toBe("4k");+ });++ it("has intents whose targets all exist", () => {+ const ids = new Set([...NAV_ENTRIES.map((e) => e.id), ...[...index.apps, ...index.motions, ...index.effects].map((p) => p.id)]);+ for (const it of INTENTS) for (const t of it.targets) expect(ids.has(t), `${it.id} → ${t}`).toBe(true);+ expect(new Set(INTENTS.map((i) => i.id)).size).toBe(INTENTS.length);+ });+});++describe("search by what you want to make", () => {+ it("“ad for my perfume” → Marketing Studio, Ads Studio, Giant Product", () => {+ expect(labels("ad for my perfume")).toEqual(["Marketing Studio", "Ads Studio", "Giant Product"]);+ expect(labels("ad for my perfume", GUEST)).toEqual(["Marketing Studio", "Ads Studio", "Giant Product"]);+ // The next ideas are presets, with where they come from.+ const also = searchNav("ad for my perfume", OWNER).also;+ expect(also.length).toBe(2);+ for (const h of also) {+ expect(["app", "motion", "effect"]).toContain(h.kind);+ expect(h.from).toBeTruthy();+ }+ });++ it("“talking photo” → Lipsync & avatars and the Talking Photo app", () => {+ const top = labels("talking photo");+ expect(top).toContain("Lipsync & avatars");+ expect(top).toContain("Talking Photo");+ });++ it("“make my product video for amazon” → Marketing Studio first", () => {+ expect(labels("make my product video for amazon")[0]).toBe("Marketing Studio");+ });++ it("“tiktok dance” → Shorts Studio and Motion control", () => {+ const top = labels("tiktok dance");+ expect(top).toContain("Shorts Studio");+ expect(top).toContain("Motion control");+ });++ it("“remove background” → Video tools › Remove background first", () => {+ const first = searchNav("remove background", OWNER).best[0];+ expect(first.label).toBe("Remove background");+ expect(first.kind).toBe("tool");+ expect(first.hint).toBe("Video tools");+ expect(first.href).toBe("/video-tools");+ });++ it("“4k” → Upscale first; “try on a dress” → Fashion Factory; “youtube channel” → Faceless Studio", () => {+ expect(labels("4k")[0]).toBe("Upscale");+ expect(labels("try on a dress")[0]).toBe("Fashion Factory");+ expect(labels("youtube channel")[0]).toBe("Faceless Studio");+ });++ it("“music”, “voiceover”, “sound effect” and “sound” → the Sound studio's modes, then Audio", () => {+ const first = (q: string) => searchNav(q, GUEST).best[0];+ expect(first("music")).toMatchObject({ label: "Music", hint: "Audio", href: "/audio/music" });+ expect(first("background music").label).toBe("Music");+ expect(first("voiceover")).toMatchObject({ label: "Speech", hint: "Audio", href: "/audio" });+ expect(first("voice over for my video").href).toBe("/audio");+ expect(first("sound effect")).toMatchObject({ label: "Sound effects", href: "/audio/sfx" });+ expect(first("whoosh").label).toBe("Sound effects");+ expect(searchNav("sound", GUEST).best.slice(0, 3).map((h) => h.label)).toEqual(expect.arrayContaining(["Audio", "Sound effects"]));+ expect(first("dub my video")).toMatchObject({ label: "Translate & dub", href: "/audio/translate" });+ });++ it("forgives a typo: “cinma” → Cinema Studio", () => {+ expect(labels("cinma")[0]).toBe("Cinema Studio");+ expect(labels("libary")).toContain("All creations");+ });++ it("still matches every word of a name first: “video tools”, “video”, “upscale video”", () => {+ expect(labels("video tools")[0]).toBe("Video tools");+ expect(labels("video")[0]).toBe("Video");+ expect(labels("upscale video")[0]).toBe("Video");+ expect(searchNav("upscale video", OWNER).best[0].hint).toBe("Upscale");+ expect(labels("settings")[0]).toBe("Settings");+ expect(labels("library")[0]).toBe("All creations");+ });++ it("finds apps, motions and effects by name", () => {+ const app = index.apps.find((a) => a.id === "app-packshot")!;+ expect(all(app.name).map((h) => h.label)).toContain(app.name);+ const motion = index.motions[0];+ expect(all(motion.name).map((h) => h.label)).toContain(motion.name);+ });++ it("gives a preset its small cover and a studio its cover id", () => {+ const giant = searchNav("ad for my perfume", OWNER).best.find((h) => h.label === "Giant Product")!;+ expect(giant.cover).toMatch(/^\/previews\/presets\/thumbs\/app-giant-product\.jpg\?v=[0-9a-f]{8}$/);+ expect(searchNav("cinema", OWNER).best[0].cover).toBe("motion-arc-left");+ });++ it("matches nothing for an empty query or a word that means nothing", () => {+ expect(searchNav("", OWNER)).toEqual({ best: [], also: [], groups: [] });+ expect(searchNav(" ", OWNER).best).toEqual([]);+ expect(all("zqx")).toEqual([]);+ });++ it("groups the rest by kind, capped, without repeating the best or the ideas", () => {+ const r = searchNav("zoom", OWNER);+ const keys = [...r.best, ...r.also, ...r.groups.flatMap((g) => g.hits)].map((h) => h.key);+ expect(new Set(keys).size).toBe(keys.length);+ const caps: Record<string, number> = { studio: 6, setting: 4, skill: 4, app: 5, motion: 4, effect: 4, model: 5 };+ for (const g of r.groups) expect(g.hits.length, g.kind).toBeLessThanOrEqual(caps[g.kind]);+ const firsts = r.groups.map((g) => g.hits[0].score);+ expect(firsts).toEqual([...firsts].sort((a, b) => b - a));+ });++ it("finds skills that run by themselves", () => {+ const skills = skillEntries([{ name: "lamp-turntable", title: "Lamp turntable", description: "A turntable from a product photo.", recipe: true, enabled: true }]);+ expect(all("turntable", [...OWNER, ...skills]).map((h) => h.label)).toContain("Run Lamp turntable…");+ });+});++describe("search and who is looking", () => {+ it("finds the ComfyUI server setting for the owner only", () => {+ expect(labels("comfyui server")[0]).toBe("ComfyUI server");+ for (const entries of [GUEST, ACCOUNT, entriesOf(undefined)]) {+ const hits = all("comfyui server", entries);+ expect(hits.map((h) => h.label)).not.toContain("ComfyUI server");+ expect(hits.some((h) => h.key.startsWith("nav:setting-"))).toBe(false);+ }+ // A guest finds the way to connect their own GPU instead.+ expect(labels("comfyui server", GUEST)[0]).toBe("Connect your GPU");+ });++ it("never offers Restore to a guest or an account; Remove dialogue is everyone's (its page says where it runs)", () => {+ for (const entries of [GUEST, ACCOUNT]) {+ for (const q of ["restore colourise", "restore old footage"]) expect(all(q, entries).map((h) => h.id), q).not.toContain("video-tools-restore");+ expect(all("remove dialogue", entries).map((h) => h.id)).toContain("video-tools-remove-dialogue");+ }+ expect(all("restore colourise").map((h) => h.id)).toContain("video-tools-restore");+ });++ it("offers sign-up and log-in to a guest only", () => {+ expect(labels("sign up", GUEST)[0]).toBe("Sign up free");+ expect(all("sign up", OWNER).map((h) => h.id)).not.toContain("signup");+ expect(all("log in", ACCOUNT).map((h) => h.id)).not.toContain("login");+ });++ it("leaves out presets a locked engine can't run", () => {+ const open = entriesOf("guest", "open");+ for (const h of all("ad for my perfume", open)) if (h.kind === "app") expect(index.apps.find((a) => a.name === h.label)?.open, h.label).toBe(true);+ });+});++describe("search speed", () => {+ it("ranks 1,500 entries in under 2 ms on average", () => {+ const base = OWNER;+ const big: SearchEntry[] = [];+ for (let i = 0; big.length < 1500; i++) big.push(...base.map((e) => ({ ...e, key: `${e.key}#${i}` })));+ big.length = 1500;+ const queries = ["ad for my perfume", "talking photo", "4k", "remove background", "cinma", "tiktok dance", "zoom", "video tools", "youtube channel", "x"];+ searchNav("warm up", big);+ // The best of three rounds of 100: other test files share the CPU.+ const rounds = [0, 1, 2].map(() => {+ const t0 = performance.now();+ for (let r = 0; r < 100; r++) searchNav(queries[r % queries.length], big);+ return (performance.now() - t0) / 100;+ });+ expect(Math.min(...rounds)).toBeLessThan(2);+ });+});++describe("the index's covers", () => {+ it("carries a version for a cover at the usual place and a URL for another, and the palette builds the small copy", () => {+ expect(presetThumb("app-x", "1234abcd")).toBe("/previews/presets/thumbs/app-x.jpg?v=1234abcd");+ expect(presetThumb("motion-3d-rotation", "/previews/presets/app-3d-rotation.jpg?v=d6a7603e")).toBe("/previews/presets/thumbs/app-3d-rotation.jpg?v=d6a7603e");+ expect(presetThumb("app-x", undefined)).toBeUndefined();+ const withCover = index.apps.filter((a) => a.cover);+ expect(withCover.length).toBeGreaterThan(index.apps.length / 2);+ for (const a of [...index.apps, ...index.motions, ...index.effects]) if (a.cover) expect(a.cover, a.id).toMatch(/^([0-9a-f]{8}|\/previews\/[^?]+\.jpg\?v=[0-9a-f]{8})$/);+ });+});++describe("plain requests find the right place", () => {+ const top = (q: string) => searchNav(q, GUEST).best.map((h) => h.label);+ it("an intent beats a name that only shares a word", () => {+ expect(top("make a film")[0]).toBe("Cinema Studio");+ expect(top("ad for my perfume")[0]).toBe("Marketing Studio");+ expect(top("product photo")[0]).toBe("Marketing Studio");+ });+ it("an app named for the request comes first", () => {+ expect(top("restore an old photo")[0]).toBe("Restore Photo");+ expect(top("old photo")[0]).toBe("Restore Photo");+ expect(top("turn me into a cartoon")).toContain("Style Transfer");+ expect(top("anime")).not.toContain("Expand Image");+ expect(top("change the sky")).toContain("Change Background");+ expect(top("change the sky")).not.toContain("Voice change");+ });+ it("a short word is never a letters-in-order guess, and a weak match is never the best one", () => {+ expect(all("logo", GUEST).map((h) => h.label)).not.toContain("Log in");+ expect(all("make a song", GUEST).map((h) => h.label)).not.toContain("Source on GitHub");+ expect(all("real estate", GUEST).map((h) => h.label)).not.toContain("Sign up free");+ expect(searchNav("zzqx", GUEST).best).toEqual([]);+ // "photo" alone doesn't fire the photo-pack intent.+ expect(top("restore photo").slice(0, 2)).not.toContain("Photodump");+ });+ it("never names ComfyUI as a maker to a guest or an account, and does to the owner", () => {+ for (const entries of [GUEST, ACCOUNT]) expect(entries.some((e) => /comfy/i.test(e.hint ?? "") && e.kind === "model")).toBe(false);+ const owner = [...navSearchEntries(entriesFor("owner")), ...indexEntries(index, "both", undefined, { owner: true })];+ expect(owner.some((e) => e.kind === "model" && /ComfyUI/.test(e.hint ?? ""))).toBe(true);+ });+});diff --git a/tests/nav.test.ts b/tests/nav.test.tsindex bb54d8e2..7939e21e 100644--- a/tests/nav.test.ts+++ b/tests/nav.test.ts@@ -1,11 +1,11 @@import { describe, expect, it } from "vitest";import { NAV } from "@/components/nav-items";-import { DEFAULT_NAV_CLOSED, fullScreenStudio, groupId, navActive, NEW_CREATION_HREF, NEW_CREATION_PARAM, parseClosed, scrollFades, sidebarCookie, SIDEBAR_STATE_SCRIPT, sidebarOpenFromCookie } from "@/lib/nav";+import { CHROME_HAD_PILLS, CHROME_STATE_SCRIPT, fullScreenStudio, groupId, navActive, NEW_CREATION_HREF, NEW_CREATION_PARAM } from "@/lib/nav";const q = (s = "") => new URLSearchParams(s);const LIBRARY = ["/library", "/library?tab=favorites"];-describe("sidebar active state", () => {+describe("nav links' active state", () => {it("matches a path and the pages below it", () => {expect(navActive("/apps", "/apps", q())).toBe(true);expect(navActive("/apps", "/apps/app-face-swap", q())).toBe(true);@@ -44,42 +44,7 @@ describe("sidebar active state", () => {});});-describe("remembered sidebar state", () => {- it("reads the shadcn cookie", () => {- expect(sidebarOpenFromCookie("")).toBe(true);- expect(sidebarOpenFromCookie("sidebar_state=true")).toBe(true);- expect(sidebarOpenFromCookie("a=1; sidebar_state=false; b=2")).toBe(false);- expect(sidebarOpenFromCookie("sidebar_state=false")).toBe(false);- expect(sidebarOpenFromCookie("my_sidebar_state=false")).toBe(true);- });-- it("parses the collapsed groups defensively", () => {- expect(parseClosed('["studios","more"]')).toEqual(["studios", "more"]);- expect(parseClosed('["studios", 3]')).toEqual(["studios"]);- // The user opened every group: that choice is kept, not replaced by the defaults.- expect(parseClosed("[]")).toEqual([]);- });-- it("opens every group until the user chooses (nothing stored, or nothing readable)", () => {- expect(parseClosed(null)).toEqual([]);- expect(parseClosed(undefined)).toEqual([]);- expect(parseClosed("not json")).toEqual([]);- expect(parseClosed('{"a":1}')).toEqual([]);- // A fresh copy each time: a caller adding to it can't change the defaults.- parseClosed(null).push("create");- expect(parseClosed(null)).toEqual([]);- });-- it("only folds groups that can fold, and keeps Create and Library in view", () => {- const foldable = NAV.filter((g) => g.collapsible).map((g) => groupId(g.label));- for (const id of DEFAULT_NAV_CLOSED) expect(foldable).toContain(id);- expect(NAV.map((g) => g.label).slice(0, 2)).toEqual(["Create", "Library"]);- // The part that can't fold stays short: Create and Library hold 16 rows (Live edit joined Create); Studios below them can be folded away.- const always = NAV.filter((g) => !g.collapsible).flatMap((g) => g.items);- expect(always.length).toBeLessThanOrEqual(16);- expect(DEFAULT_NAV_CLOSED).not.toContain("studios");- });-+describe("nav rows", () => {it("prefetches only the rows most visits go to next", () => {const eager = NAV.flatMap((g) => g.items.filter((i) => i.eager).map((i) => i.href));expect(eager).toEqual(["/", "/assist", "/image", "/video", "/library"]);@@ -92,52 +57,6 @@ describe("remembered sidebar state", () => {expect(groupId("Studios")).toBe("studios");expect(groupId("Shorts & Marketing")).toBe("shorts-marketing");});-- it("ships a pre-paint script that is valid JavaScript", () => {- expect(() => new Function(SIDEBAR_STATE_SCRIPT)).not.toThrow();- expect(SIDEBAR_STATE_SCRIPT).toContain("sidebar_state=false");- expect(SIDEBAR_STATE_SCRIPT).toContain("fuobe:nav-closed");- });-- /** Runs the pre-paint script against a fake DOM with the given cookie, path and stored folds. */- function runScript(cookie: string, pathname: string, stored: string | null) {- const attrs = new Map<string, Record<string, string>>();- const el = (key: string, toggle = true) => ({- setAttribute: (k: string, v: string) => attrs.set(key, { ...attrs.get(key), [k]: v }),- getAttribute: (k: string) => (k === "data-nav-group" ? key : null),- querySelector: (s: string) => (s === "[data-nav-toggle]" && toggle ? el(`${key}/toggle`) : null),- });- const document = {- cookie,- querySelector: (s: string) => (s === '[data-slot="sidebar"]' ? el("sidebar") : null),- // Create and Library can't fold (no toggle); Studios and Engine can.- querySelectorAll: (s: string) => (s === "[data-nav-group]" ? [el("create", false), el("library", false), el("studios"), el("engine")] : []),- };- const localStorage = { getItem: () => stored };- new Function("document", "localStorage", "location", SIDEBAR_STATE_SCRIPT)(document, localStorage, { pathname });- return attrs;- }-- it("applies the cookie and the remembered folds to the DOM", () => {- const attrs = runScript("x=1; sidebar_state=false", "/image", '["studios","gone"]');- expect(attrs.get("sidebar")).toEqual({ "data-state": "collapsed", "data-collapsible": "icon" });- expect(attrs.get("studios")).toEqual({ "data-open": "false" });- expect(attrs.get("studios/toggle")).toEqual({ "aria-expanded": "false" });- // Engine was opened by the user: the server's default fold is undone before paint.- expect(attrs.get("engine")).toEqual({ "data-open": "true" });- expect(attrs.get("engine/toggle")).toEqual({ "aria-expanded": "true" });- expect(attrs.has("create")).toBe(false);- });-- it("leaves the server's default folds alone when nothing is remembered", () => {- const attrs = runScript("", "/image", null);- expect([...attrs.keys()]).toEqual([]);- });-- it("folds the sidebar to its rail on a full-screen studio, whatever the cookie says", () => {- expect(runScript("sidebar_state=true", "/cinema/abc", null).get("sidebar")).toEqual({ "data-state": "collapsed", "data-collapsible": "icon" });- expect(runScript("sidebar_state=true", "/cinema", null).get("sidebar")).toBeUndefined();- });});describe("full-screen studios", () => {@@ -147,7 +66,7 @@ describe("full-screen studios", () => {});it("count every Assist page as one studio, and each project as its own", () => {- // Opening the sidebar on a chat keeps it open on Skills; a different project folds it again.+ // Every Assist page is one studio; each project is its own.expect(fullScreenStudio("/assist")).toBe("/assist");expect(fullScreenStudio("/assist/skills")).toBe(fullScreenStudio("/assist/projects/p1"));expect(fullScreenStudio("/layers/l-2/")).toBe(fullScreenStudio("/layers/l-2"));@@ -156,14 +75,6 @@ describe("full-screen studios", () => {});});-describe("the remembered choice's cookie", () => {- it("is the one the shadcn provider reads, for a week, site-wide", () => {- expect(sidebarCookie(false)).toBe("sidebar_state=false; path=/; max-age=604800");- expect(sidebarOpenFromCookie(sidebarCookie(false).split(";")[0])).toBe(false);- expect(sidebarOpenFromCookie(sidebarCookie(true).split(";")[0])).toBe(true);- });-});-describe("New creation", () => {it("opens Home with its own flag, and Home stays lit while it's in the address", () => {const url = new URL(NEW_CREATION_HREF, "http://localhost");@@ -173,21 +84,45 @@ describe("New creation", () => {});});-describe("the sidebar's fades", () => {- it("are as deep as what's hidden past each edge, up to 24px above and 40px below", () => {- expect(scrollFades({ scrollTop: 0, clientHeight: 637, scrollHeight: 637 })).toEqual({ above: 0, below: 0 });- expect(scrollFades({ scrollTop: 0, clientHeight: 500, scrollHeight: 900 })).toEqual({ above: 0, below: 40 });- expect(scrollFades({ scrollTop: 10, clientHeight: 500, scrollHeight: 900 })).toEqual({ above: 10, below: 40 });- expect(scrollFades({ scrollTop: 400, clientHeight: 500, scrollHeight: 900 })).toEqual({ above: 24, below: 0 });- // A row the edge cuts through fades as far as it's cut.- expect(scrollFades({ scrollTop: 0, clientHeight: 620, scrollHeight: 640 })).toEqual({ above: 0, below: 20 });+describe("the app frame's state before the first paint", () => {+ /** Runs CHROME_STATE_SCRIPT as the browser would, against a fake <html> and storage. */+ function run(pathname: string, stored: Record<string, string> = {}, storage: "ok" | "throws" = "ok") {+ const attrs = new Map<string, string>();+ const document = { documentElement: { setAttribute: (k: string, v: string) => attrs.set(k, v) } };+ const localStorage = {+ getItem: (k: string) => {+ if (storage === "throws") throw new Error("SecurityError");+ return stored[k] ?? null;+ },+ };+ new Function("document", "localStorage", "location", CHROME_STATE_SCRIPT)(document, localStorage, { pathname });+ return attrs;+ }++ it("is valid script", () => {+ expect(() => new Function(CHROME_STATE_SCRIPT)).not.toThrow();+ });++ it("marks full-screen studios (a project, Assist, Live edit), not their lists", () => {+ for (const p of ["/cinema/abc", "/canvas/x1", "/layers/l2", "/assist", "/assist/skills", "/live-edit"]) expect(run(p).has("data-fullscreen-studio"), p).toBe(true);+ for (const p of ["/", "/cinema", "/canvas", "/image", "/library"]) expect(run(p).has("data-fullscreen-studio"), p).toBe(false);+ });++ it("applies the viewer this browser knew, and the bar's remembered pills", () => {+ const attrs = run("/", { "fuobe:viewer": "account", "fuobe:had:balance": "1", "fuobe:had:computer": "0", "fuobe:had:placeholders": "junk" });+ expect(attrs.get("data-viewer")).toBe("account");+ expect(attrs.get("data-had-balance")).toBe("1");+ expect(attrs.has("data-had-computer")).toBe(false);+ expect(attrs.has("data-had-placeholders")).toBe(false);+ expect([...CHROME_HAD_PILLS]).toEqual(["balance", "computer", "placeholders"]);+ // Anything but a known kind is ignored.+ expect(run("/", { "fuobe:viewer": "admin" }).has("data-viewer")).toBe(false);});- it("never dim the last row for a few pixels of padding past the edge", () => {- // fuobe.com at 1440×900: 3px of the last group's padding below the edge used to fade the last 40px.- expect(scrollFades({ scrollTop: 0, clientHeight: 637, scrollHeight: 640 }).below).toBe(3);- // Sub-pixel leftovers at either end are no fade at all.- expect(scrollFades({ scrollTop: 0.4, clientHeight: 500, scrollHeight: 500.9 })).toEqual({ above: 0, below: 0 });- expect(scrollFades({ scrollTop: 399.5, clientHeight: 500, scrollHeight: 900 }).below).toBe(0);+ it("survives storage that throws, and still marks a full-screen studio", () => {+ expect(() => run("/assist", {}, "throws")).not.toThrow();+ const attrs = run("/assist", {}, "throws");+ expect(attrs.has("data-fullscreen-studio")).toBe(true);+ expect(attrs.has("data-viewer")).toBe(false);});});diff --git a/tests/next-steps.test.ts b/tests/next-steps.test.tsnew file mode 100644index 00000000..ec210378--- /dev/null+++ b/tests/next-steps.test.ts@@ -0,0 +1,141 @@+import { describe, expect, it } from "vitest";+import type { Generation, OutputFile } from "@/lib/catalog/types";+import { coverIds } from "@/lib/nav-model";+import { imageSubject, keepGoing, type KeepGoingContext } from "@/lib/next-steps";++function gen(outputs: Partial<OutputFile>[], over: Partial<Generation> = {}): Generation {+ return {+ id: "g1",+ batchId: null,+ feature: "image",+ presetId: null,+ modelId: "nano-banana-pro",+ engine: "cloud",+ provider: "fal",+ op: "t2i",+ kind: (outputs[0]?.kind ?? "image") as Generation["kind"],+ status: "succeeded",+ progress: 1,+ message: null,+ prompt: "a fox in the snow",+ request: { feature: "image", modelId: "nano-banana-pro", prompt: "a fox in the snow" },+ outputs: outputs.map((o, i) => ({ url: `/api/files/out-${i}.png`, kind: "image", ...o }) as OutputFile),+ error: null,+ costUsd: null,+ favorite: false,+ createdAt: 0,+ updatedAt: 0,+ completedAt: 0,+ ...over,+ };+}++const withPrompt = (prompt: string, over: Partial<Generation> = {}) => gen([{ kind: "image", url: "/api/files/pic one.png" }], { prompt, request: { feature: "image", modelId: "nano-banana-pro", prompt }, ...over });+const person = () => withPrompt("a fashion model in a red velvet suit on a rooftop at dusk");+const product = () => withPrompt("a perfume bottle on black marble");+const other = () => withPrompt("a fox in the snow");+const clip = (over: Partial<Generation> = {}) => gen([{ kind: "video", url: "/api/files/clip.mp4" }], { kind: "video", op: "t2v", feature: "video", ...over });+const sound = (over: Partial<Generation> = {}) => gen([{ kind: "audio", url: "/api/files/voice.mp3" }], { kind: "audio", op: "tts", feature: "audio", ...over });+const model = (meta: Record<string, unknown> = { poster: "/api/files/chair.png" }) =>+ gen([{ kind: "model3d", url: "/api/files/chair.glb", meta }], {+ kind: "model3d",+ op: "image-to-3d",+ feature: "image-to-3d",+ request: { feature: "image-to-3d", modelId: "hunyuan-3d-3-1-pro", inputs: { images: ["/api/files/photo.png"] } },+ });++const ALL_ADAPTERS: KeepGoingContext = { engineMode: "both", adapters: { characterSheet: true, imageTo3d: true } };+const ids = (g: Generation, ctx: KeepGoingContext = ALL_ADAPTERS, max = 5) => keepGoing(g, 0, ctx, max).map((s) => s.id);+const U = encodeURIComponent("/api/files/pic one.png");++describe("what a picture is of", () => {+ it("reads its studio first, then its words", () => {+ expect(imageSubject(person())).toBe("person");+ expect(imageSubject(product())).toBe("product");+ expect(imageSubject(other())).toBe("other");+ expect(imageSubject(withPrompt("a fox", { feature: "fashion" }))).toBe("person");+ expect(imageSubject(withPrompt("a fox", { feature: "click-to-ad" }))).toBe("product");+ // A model holding the product: the product wins only with more product words.+ expect(imageSubject(withPrompt("a woman holding a perfume bottle"))).toBe("product");+ expect(imageSubject(withPrompt("a woman in a dress holding a bag"))).toBe("person");+ });+});++describe("Keep going with this", () => {+ it("offers a person's picture: animate, talk, character sheet, an ad, sharpen", () => {+ const steps = keepGoing(person(), 0, ALL_ADAPTERS);+ expect(steps.map((s) => s.id)).toEqual(["animate", "talk", "character-sheet", "billboard", "upscale"]);+ expect(steps.map((s) => s.href)).toEqual([`/video?image=${U}`, `/lipsync?image=${U}`, `/character-sheet?image=${U}`, `/apps/app-billboard-ad?image=${U}`, `/upscale?image=${U}`]);+ expect(steps[0]).toMatchObject({ verb: "Animate it", where: "Video" });+ });++ it("offers a product's picture: animate, an ad, 3D, sharpen, change", () => {+ expect(ids(product())).toEqual(["animate", "giant", "image-to-3d", "upscale", "edit"]);+ expect(keepGoing(product(), 0, ALL_ADAPTERS)[1].href).toBe(`/apps/app-giant-product?image=${U}`);+ });++ it("offers any other picture: animate, change, sharpen, grade, 3D", () => {+ expect(ids(other())).toEqual(["animate", "edit", "upscale", "grade", "image-to-3d"]);+ });++ it("links no studio that can't take the picture yet", () => {+ const off: KeepGoingContext = { engineMode: "both" };+ expect(ids(person(), off)).toEqual(["animate", "talk", "billboard", "upscale"]);+ expect(ids(product(), off)).not.toContain("image-to-3d");+ expect(ids(other(), off)).not.toContain("image-to-3d");+ });++ it("offers a clip: longer first, then sharper, sound, phones, a swap", () => {+ expect(ids(clip())).toEqual(["extend", "upscale", "add-sound", "reframe", "genjutsu"]);+ const steps = keepGoing(clip(), 0, ALL_ADAPTERS);+ expect(steps[0].href).toBe(`/extend?video=${encodeURIComponent("/api/files/clip.mp4")}`);+ expect(steps.every((s) => s.href.includes("video=%2Fapi%2Ffiles%2Fclip.mp4"))).toBe(true);+ });++ it("splits a sounded clip's soundtrack, and offers Remove dialogue to the owner only", () => {+ const sounded = clip({ op: "lipsync", feature: "lipsync" });+ expect(ids(sounded)).toContain("split-soundtrack");+ expect(ids(sounded)).toContain("remove-dialogue");+ expect(ids(sounded, { ...ALL_ADAPTERS, visitor: true })).not.toContain("remove-dialogue");+ expect(ids(sounded, { ...ALL_ADAPTERS, visitor: true })).not.toContain("restore-video");+ });++ it("offers a sound: a photo that says it, another voice, a loop, the parts", () => {+ expect(ids(sound())).toEqual(["lipsync", "voice-change", "loop-audio", "split-soundtrack", "clean-voice"]);+ expect(keepGoing(sound(), 0, ALL_ADAPTERS)[0].href).toBe(`/lipsync?audio=${encodeURIComponent("/api/files/voice.mp3")}`);+ // Music keeps no voice to clean.+ expect(ids(sound({ op: "music" }))).not.toContain("clean-voice");+ });++ it("offers a 3D model its spin, an ad and a sharper still, the last two only with a still", () => {+ expect(ids(model())).toEqual(["animate-spin", "product-360", "upscale"]);+ expect(keepGoing(model(), 0, ALL_ADAPTERS)[1].href).toBe(`/apps/app-product-360?image=${encodeURIComponent("/api/files/chair.png")}`);+ const bare = model({});+ // Its photo still animates; nothing else without a still.+ expect(ids({ ...bare, outputs: bare.outputs })).not.toContain("product-360");+ expect(ids({ ...bare, outputs: bare.outputs })).not.toContain("upscale");+ });++ it("honours the most it may show", () => {+ expect(keepGoing(person(), 0, ALL_ADAPTERS, 3)).toHaveLength(3);+ expect(keepGoing(clip(), 0, ALL_ADAPTERS, 2).map((s) => s.id)).toEqual(["extend", "upscale"]);+ });++ it("offers nothing for a failed, deleted, text or vector result, or a missing output", () => {+ expect(keepGoing(person(), 0, ALL_ADAPTERS).length).toBeGreaterThan(0);+ expect(keepGoing({ ...person(), status: "failed" }, 0, ALL_ADAPTERS)).toEqual([]);+ expect(keepGoing({ ...person(), deletedAt: 1 }, 0, ALL_ADAPTERS)).toEqual([]);+ expect(keepGoing(gen([{ kind: "text", url: "/api/files/t.txt", text: "hi" }], { kind: "text" }), 0, ALL_ADAPTERS)).toEqual([]);+ expect(keepGoing(gen([{ kind: "image", url: "/api/files/logo.svg", contentType: "image/svg+xml" }], { provider: "fal" }), 0, ALL_ADAPTERS)).toEqual([]);+ expect(keepGoing(person(), 3, ALL_ADAPTERS)).toEqual([]);+ });++ it("names only covers the navigation resolves, and no step twice", () => {+ const covers = new Set(coverIds());+ for (const g of [person(), product(), other(), clip(), clip({ op: "lipsync" }), sound(), model()]) {+ const steps = keepGoing(g, 0, ALL_ADAPTERS);+ expect(new Set(steps.map((s) => s.id)).size).toBe(steps.length);+ for (const s of steps) if (s.cover) expect(covers.has(s.cover), s.cover).toBe(true);+ }+ });+});diff --git a/tests/phone-nav.test.ts b/tests/phone-nav.test.tsnew file mode 100644index 00000000..332c2ada--- /dev/null+++ b/tests/phone-nav.test.ts@@ -0,0 +1,302 @@+import fs from "node:fs";+import path from "node:path";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { createElement, type ReactNode } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it, vi } from "vitest";++const nav = vi.hoisted(() => ({ path: "/" }));+const search = vi.hoisted(() => ({ open: () => {}, close: () => {}, warm: () => {}, isOpen: false }));++vi.mock("next/navigation", () => ({+ useRouter: () => ({ prefetch: () => {}, push: () => {}, replace: () => {}, back: () => {}, refresh: () => {} }),+ usePathname: () => nav.path,+ useSearchParams: () => new URLSearchParams(),+}));+vi.mock("@/components/nav/search-context", () => ({ useSearchPalette: () => search }));++import { NavUiProvider } from "@/components/nav/nav-ui";+import { activePhoneTab, KEYBOARD_MIN, keyboardOpen, toggleSheet, typesText } from "@/components/nav/phone-nav";+import { PhoneNavButton } from "@/components/nav/phone-nav-button";+import { PhoneTabs } from "@/components/nav/phone-tabs";+import { StudiosSheet } from "@/components/nav/studios-sheet";+import { PhoneBar } from "@/components/phone-bar";+import { navCovers } from "@/lib/nav-covers";+import { activeEntry, LAUNCHER_GROUPS, launcherEntries, studioCount } from "@/lib/nav-model";++/*+ * The phone's navigation (below md): the tab bar (Home, Create, Studios, Library, You), the Studios sheet with every+ * studio on one screen, and the header button that opens search (or, in a full-screen studio, the menu sheet).+ */++const covers = navCovers();+// The provider as createElement types it with its children passed after the props.+const Nav = NavUiProvider as (p: { covers: typeof covers; children?: ReactNode }) => ReactNode;+const render = (node: ReactNode) => renderToStaticMarkup(createElement(QueryClientProvider, { client: new QueryClient() }, createElement(Nav, { covers }, node)));+const at = (pathname: string, node: () => ReactNode) => {+ nav.path = pathname;+ return render(node());+};+/** Every link's href in the markup, in order (React escapes & as &). */+const hrefs = (html: string) => [...html.matchAll(/<a [^>]*href="([^"]*)"/g)].map((m) => m[1].replaceAll("&", "&"));+/** The markup's words, without its tags. */+const words = (html: string) => html.replace(/<[^>]+>/g, " ").replaceAll("&", "&");+/** The opening tag of the element carrying `attr` (data-tab="home"…). */+const tagWith = (html: string, attr: string) => html.match(new RegExp(`<[a-z]+[^>]*${attr}[^>]*>`))?.[0] ?? "";+const NO_SEARCH = new URLSearchParams();+const tabFor = (pathname: string) => activePhoneTab(pathname, null, activeEntry(pathname, NO_SEARCH));+/** Words that describe the install's own setup: never on the phone's chrome itself (the owner sees them in the You sheet only). */+const STATUS_WORDS = ["ComfyUI", "add key", "offline", "online", "Paid APIs only", "Open source only", "Placeholder"];++describe("the selected tab", () => {+ it("is the open sheet's while one is open", () => {+ expect(activePhoneTab("/", "studios")).toBe("studios");+ expect(activePhoneTab("/library", "create")).toBe("create");+ expect(activePhoneTab("/cinema", "you")).toBe("you");+ });++ it("is the page's tab otherwise", () => {+ expect(tabFor("/")).toBe("home");+ expect(tabFor("/library")).toBe("library");+ expect(tabFor("/library/abc")).toBe("library");+ expect(tabFor("/settings")).toBe("you");+ expect(tabFor("/settings/models")).toBe("you");+ expect(tabFor("/connect")).toBe("you");+ });++ it("is Studios in a studio, its pages and the apps, and Create in a create tool", () => {+ for (const p of ["/cinema", "/cinema/abc", "/marketing/click-to-ad", "/audio/clean", "/apps", "/apps/app-3d-figure", "/fashion-factory"]) expect(tabFor(p), p).toBe("studios");+ for (const p of ["/image", "/video", "/edit", "/assist", "/canvas"]) expect(tabFor(p), p).toBe("create");+ });++ it("is none on a page no tab leads to", () => {+ expect(tabFor("/motions")).toBeNull();+ expect(tabFor("/effects")).toBeNull();+ expect(activePhoneTab("", null)).toBeNull();+ });+});++describe("a sheet tab", () => {+ it("opens its sheet, switches from another, and closes its own when tapped again", () => {+ expect(toggleSheet(null, "studios")).toBe("studios");+ expect(toggleSheet("studios", "studios")).toBeNull();+ expect(toggleSheet("create", "studios")).toBe("studios");+ expect(toggleSheet("studios", "you")).toBe("you");+ });+});++describe("the on-screen keyboard", () => {+ it("counts only fields you type in", () => {+ for (const type of [undefined, "", "text", "search", "email", "url", "tel", "password", "number", "TEXT"]) expect(typesText({ tagName: "INPUT", type }), String(type)).toBe(true);+ for (const type of ["checkbox", "radio", "range", "button", "submit", "file", "color", "date", "time"]) expect(typesText({ tagName: "INPUT", type }), type).toBe(false);+ expect(typesText({ tagName: "TEXTAREA" })).toBe(true);+ expect(typesText({ tagName: "textarea" })).toBe(true);+ expect(typesText({ tagName: "DIV", isContentEditable: true })).toBe(true);+ expect(typesText({ tagName: "DIV" })).toBe(false);+ expect(typesText({ tagName: "BUTTON" })).toBe(false);+ expect(typesText({ tagName: "INPUT", type: "text", readOnly: true })).toBe(false);+ expect(typesText({ tagName: "TEXTAREA", disabled: true })).toBe(false);+ expect(typesText(null)).toBe(false);+ expect(typesText(undefined)).toBe(false);+ });++ it("is up when someone types and the visible viewport lost more than the browser bars do", () => {+ expect(keyboardOpen(844 - 336, 844, true)).toBe(true);+ expect(keyboardOpen(844 - KEYBOARD_MIN - 1, 844, true)).toBe(true);+ expect(keyboardOpen(844 - KEYBOARD_MIN, 844, true)).toBe(false);+ // The address bar showing or hiding moves the viewport by less.+ expect(keyboardOpen(844 - 60, 844, true)).toBe(false);+ // Pinch-zoomed or a short window without a field in focus: not the keyboard.+ expect(keyboardOpen(400, 844, false)).toBe(false);+ });+});++describe("the tab bar", () => {+ it("is a Main nav fixed to the bottom of a phone, clear of the home indicator, and steps aside when it must", () => {+ const html = at("/", () => createElement(PhoneTabs));+ const bar = tagWith(html, "data-phone-tabs");+ expect(bar).toMatch(/^<nav /);+ expect(bar).toContain('aria-label="Main"');+ for (const c of [+ "md:hidden",+ "print:hidden",+ "fixed",+ "bottom-0",+ "grid-cols-5",+ "h-[calc(4rem+env(safe-area-inset-bottom))]",+ "pb-[calc(0.25rem+env(safe-area-inset-bottom))]",+ "pl-[max(0.5rem,env(safe-area-inset-left))]",+ "pr-[max(0.5rem,env(safe-area-inset-right))]",+ "[html[data-fullscreen-studio]_&]:hidden",+ "[html[data-keyboard-open]_&]:hidden",+ "pointer-events-auto",+ "z-40",+ ])+ expect(bar, c).toContain(c);+ });++ it("has Home, Create, Studios, Library and You, in that order; the links prefetch and the sheet tabs say they open a dialog", () => {+ const html = at("/", () => createElement(PhoneTabs));+ expect([...html.matchAll(/data-tab="([a-z]+)"/g)].map((m) => m[1])).toEqual(["home", "create", "studios", "library", "you"]);+ expect(hrefs(html)).toEqual(["/", "/library"]);+ expect(words(html).replace(/\s+/g, " ").trim()).toBe("Home Create Studios Library You");+ for (const tab of ["create", "studios", "you"]) {+ const t = tagWith(html, `data-tab="${tab}"`);+ expect(t).toMatch(/^<button /);+ expect(t).toContain('type="button"');+ expect(t).toContain('aria-haspopup="dialog"');+ expect(t).toContain('aria-expanded="false"');+ }+ });++ it("marks the page's tab: aria-current on a link, the selected look on a sheet tab", () => {+ const home = at("/", () => createElement(PhoneTabs));+ expect(tagWith(home, 'data-tab="home"')).toContain('aria-current="page"');+ expect(tagWith(home, 'data-tab="home"')).toContain("data-active");+ expect(tagWith(home, 'data-tab="library"')).not.toContain("aria-current");++ const library = at("/library", () => createElement(PhoneTabs));+ expect(tagWith(library, 'data-tab="library"')).toContain('aria-current="page"');+ expect(tagWith(library, 'data-tab="home"')).not.toContain("aria-current");++ const studio = at("/cinema/abc", () => createElement(PhoneTabs));+ expect(tagWith(studio, 'data-tab="studios"')).toContain("data-active");+ expect(studio).not.toContain("aria-current");++ const create = at("/image", () => createElement(PhoneTabs));+ expect(tagWith(create, 'data-tab="create"')).toContain("data-active");++ const gallery = at("/motions", () => createElement(PhoneTabs));+ expect(gallery).not.toContain("data-active");+ });++ it("gives each tab the bar's whole 56 px row (4rem less the 1 px border, 3 px above and 4 px below) and a fifth of its width", () => {+ const html = at("/", () => createElement(PhoneTabs));+ for (const tab of ["home", "create", "studios", "library", "you"]) expect(tagWith(html, `data-tab="${tab}"`)).toContain("h-full");+ const bar = tagWith(html, "data-phone-tabs");+ for (const c of ["border-t", "pt-[3px]", "pb-[calc(0.25rem+env(safe-area-inset-bottom))]"]) expect(bar, c).toContain(c);+ });++ it("shows no dot and no setup words in the server's HTML (who is looking is known only after hydration)", () => {+ const html = at("/", () => createElement(PhoneTabs));+ expect(html).not.toContain("data-dot");+ for (const w of STATUS_WORDS) expect(words(html), w).not.toContain(w);+ });+});++describe("the Studios sheet", () => {+ const sheet = (props: { group?: (typeof LAUNCHER_GROUPS)[number]["id"] } = {}) => createElement(StudiosSheet, { ...props, onSearch: () => {} });+ const tiles = (html: string) => hrefs(html).filter((h) => h !== "/" && h !== "/library");++ it("shows every studio, Apps and the Sound modes (33 tiles, 28 studios), in launcher order, each with a real cover", () => {+ const html = at("/", () => sheet());+ const all = launcherEntries(undefined);+ expect(all).toHaveLength(33);+ expect(studioCount()).toBe(28);+ expect(tiles(html)).toEqual(all.map((e) => e.href));+ for (const e of all) {+ expect(e.cover, e.id).toBeTruthy();+ expect(covers[e.cover!], e.id).toBeTruthy();+ expect(html, e.id).toContain(`src="${covers[e.cover!].thumb}"`);+ }+ });++ it("labels tiles short enough for a 5-column phone grid, with the full name for screen readers", () => {+ const html = at("/", () => sheet());+ for (const e of launcherEntries(undefined)) {+ // Up to two lines of 12 (the label wraps; it never shows an abbreviation).+ for (const w of (e.short ?? e.label).split(" ")) expect(w.length, e.id).toBeLessThanOrEqual(12);+ expect(e.short ?? e.label, e.id).not.toContain(".");+ expect(words(html), e.id).toContain(e.label);+ }+ expect(html).toContain("grid-cols-5");+ });++ it("has a chip per group, All first and pressed, in a labelled group", () => {+ const html = at("/", () => sheet());+ expect(html).toContain('role="group"');+ expect(html).toContain('aria-label="Show the studios for one goal"');+ const chips = [...html.matchAll(/<button[^>]*aria-pressed="(true|false)"[^>]*>([^<]*)<\/button>/g)].map((m) => [m[2], m[1]]);+ expect(chips).toEqual([+ ["All", "true"],+ ...LAUNCHER_GROUPS.map((g) => [g.chip, "false"]),+ ]);+ expect(chips.map((c) => c[0])).toEqual(["All", "Film", "Social", "Sell", "People", "Sound", "Finish"]);+ });++ it("starts on the group it was opened for", () => {+ const sizes = { film: 8, social: 6, sell: 5, people: 6, sound: 5, finish: 3 } as const;+ for (const g of LAUNCHER_GROUPS) {+ const html = at("/", () => sheet({ group: g.id }));+ expect(tiles(html), g.id).toEqual(launcherEntries(undefined, g.id).map((e) => e.href));+ expect(tiles(html), g.id).toHaveLength(sizes[g.id]);+ expect(html, g.id).toMatch(new RegExp(`aria-pressed="true"[^>]*>${g.chip}<`));+ }+ });++ it("marks the studio you are in", () => {+ const html = at("/cinema/abc", () => sheet());+ expect(tagWith(html, 'href="/cinema"')).toContain('aria-current="page"');+ expect(html.match(/aria-current="page"/g)).toHaveLength(1);+ });++ it("marks an Audio mode in the Sound group as the one you are in, and only it", () => {+ const html = at("/audio/music", () => sheet());+ expect(tagWith(html, 'href="/audio/music"')).toContain('aria-current="page"');+ expect(html.match(/aria-current="page"/g)).toHaveLength(1);+ const studio = at("/audio/dialogue", () => sheet());+ expect(tagWith(studio, 'href="/audio"')).toContain('aria-current="page"');+ expect(studio.match(/aria-current="page"/g)).toHaveLength(1);+ });++ it("offers Home, Library, You and Search only in a full-screen studio (elsewhere Search everything is in the sheet's title row)", () => {+ const html = at("/", () => sheet());+ expect(hrefs(html).slice(0, 2)).toEqual(["/", "/library"]);+ expect(html).toContain("hidden shrink-0 grid-cols-4");+ expect(html).toContain("[html[data-fullscreen-studio]_&]:grid");+ // The grid takes the room under the chips: Search everything sits next to Close, so 33 tiles fit a 390 x 844 phone.+ expect(words(html)).not.toContain("Search everything");+ });++ it("names nothing about the install's setup", () => {+ const html = at("/", () => sheet());+ for (const w of STATUS_WORDS) expect(words(html), w).not.toContain(w);+ });+});++describe("the header button and the phone bar", () => {+ it("opens search, and is the menu in a full-screen studio (switched by CSS from the pre-paint attribute)", () => {+ const html = at("/", () => createElement(PhoneNavButton));+ const button = tagWith(html, 'aria-haspopup="dialog"');+ expect(button).toMatch(/^<button /);+ expect(button).toContain("md:hidden");+ expect(button).toContain("size-11");+ expect(html).toMatch(/<span class="sr-only \[html\[data-fullscreen-studio\]_&\]:hidden">Search<\/span>/);+ expect(html).toMatch(/<span class="sr-only hidden \[html\[data-fullscreen-studio\]_&\]:inline">Menu<\/span>/);+ });++ it("is the wordmark (home) and search on gallery and settings pages, clear of the notch", () => {+ const html = at("/apps", () => createElement(PhoneBar));+ expect(hrefs(html)).toEqual(["/"]);+ expect(html).toContain('aria-label="Fuobe home"');+ expect(html).toContain("pt-[env(safe-area-inset-top)]");+ expect(html).toContain("md:hidden");+ expect(words(html)).toContain("Search");+ expect(html).not.toContain("Toggle Sidebar");+ });+});++describe("the phone sheets", () => {+ const src = fs.readFileSync(path.join(__dirname, "../src/components/nav/phone-sheets.tsx"), "utf8");++ it("end at the tab bar and let a tap on it be the tab's own", () => {+ expect(src).toContain("bottom-[var(--chrome-bottom,0px)]");+ expect(src).toMatch(/onInteractOutside=\{\(e\) => \{[\s\S]*?closest\("\[data-phone-tabs\]"\)\) e\.preventDefault\(\)/);+ });++ it("animate only for people who allow motion", () => {+ const animated = src.match(/(?<![\w:-])(?:data-open|data-closed):animate-(?:in|out)/g) ?? [];+ expect(animated).toEqual([]);+ expect(src).toContain("motion-safe:data-open:animate-in");+ });+});diff --git a/tests/preset-covers.test.ts b/tests/preset-covers.test.tsindex fd9ff526..644dc491 100644--- a/tests/preset-covers.test.ts+++ b/tests/preset-covers.test.ts@@ -175,12 +175,21 @@ describe("the preset covers manifest", () => {expect(importers(/from "[^"]*preset-covers\.generated"/)).toEqual(["lib/preset-covers.ts"]);// (A type is no code: the cover tile takes a cover without importing the map.) Any Angle's page shows its own cover// above the upload: a tool of its own, whose chunk loads on that app's page only.+ // The navigation's covers and the search index's are resolved on the server: nav-covers.ts is server-only (the+ // studios layout passes them down as props) and palette-index.ts is read by the prerendered GET /api/search-index.expect(importers(/^import (?!type )[^;]*from "[^"]*preset-covers";/m)).toEqual(["components/any-angle/any-angle-tool.tsx","components/cinema/move-list.tsx","components/preset-header.tsx","components/studio/preset-chips.tsx",+ "lib/nav-covers.ts",+ "lib/palette-index.ts",]);+ expect(fs.readFileSync(path.join(root, "src", "lib", "nav-covers.ts"), "utf8")).toMatch(/^import "server-only";$/m);+ // Client code takes the covers' type only (the covers come as props).+ for (const f of importers(/^import (?!type )[^;]*from "[^"]*nav-covers";/m)) expect(sources.find((s) => s.file === f)!.text, f).not.toMatch(/^["']use client["'];?$/m);+ // The index is server code: the prerendered route, and Home's showcase (server-only) for model links.+ expect(importers(/from "[^"]*palette-index"/)).toEqual(["app/api/search-index/route.ts", "lib/home-showcase.ts"]);const composer = fs.readFileSync(path.join(root, "src", "components", "studio", "composer.tsx"), "utf8");expect(composer).toMatch(/dynamic\(\(\) => import\("\.\/preset-chips"\)/);expect(importers(/from "[^"]*\/move-list"/)).toEqual([]);diff --git a/tests/search-palette.test.ts b/tests/search-palette.test.tsnew file mode 100644index 00000000..a95baef9--- /dev/null+++ b/tests/search-palette.test.ts@@ -0,0 +1,175 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { Command as CommandPrimitive } from "cmdk";+import { createElement, type ReactNode } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it, vi } from "vitest";++vi.mock("next/navigation", () => ({+ useRouter: () => ({ prefetch: () => {}, push: () => {}, replace: () => {}, back: () => {}, refresh: () => {} }),+ usePathname: () => "/",+ useSearchParams: () => new URLSearchParams(),+}));++const { isPaletteToggle, PALETTE_INDEX_KEY, SearchPaletteProvider, slashOpens, typesText, useSearchPalette } = await import("@/components/nav/search-context");+const { PaletteBody, startValue } = await import("@/components/nav/search-palette");+const { BestRow, kindTag, StudioTile } = await import("@/components/nav/search-results");+const { paletteIndex } = await import("@/lib/palette-index");+const { entriesFor, entry, launcherEntries } = await import("@/lib/nav-model");+const { navSearchEntries, searchNav } = await import("@/lib/nav-search");+const { indexEntries } = await import("@/lib/command-search");++/** A stand-in element: what `closest` finds above it. */+const el = (inside: string[] = []) => ({ closest: (sel: string) => (inside.some((s) => sel.includes(s)) ? {} : null) }) as unknown as EventTarget;+const key = (k: string, over: Partial<KeyboardEvent> = {}) =>+ ({ key: k, metaKey: false, ctrlKey: false, altKey: false, shiftKey: false, defaultPrevented: false, isComposing: false, target: el(), ...over }) as KeyboardEvent;+const noDialog = { querySelector: () => null };+const dialogOpen = { querySelector: () => ({}) as Element };++describe("the palette's shortcuts", () => {+ it("Ctrl+K and ⌘K toggle it from anywhere, a text field included", () => {+ expect(isPaletteToggle(key("k", { ctrlKey: true }))).toBe(true);+ expect(isPaletteToggle(key("K", { metaKey: true }))).toBe(true);+ expect(isPaletteToggle(key("k", { ctrlKey: true, shiftKey: true }))).toBe(false);+ expect(isPaletteToggle(key("k", { ctrlKey: true, altKey: true }))).toBe(false);+ expect(isPaletteToggle(key("k"))).toBe(false);+ });++ it("/ opens it only when nothing else wants the key", () => {+ expect(slashOpens(key("/"), noDialog)).toBe(true);+ // Typing a slash in a field, an editor or a workspace with keys of its own types a slash.+ expect(slashOpens(key("/", { target: el(["input"]) }), noDialog)).toBe(false);+ expect(slashOpens(key("/", { target: el(["[contenteditable]"]) }), noDialog)).toBe(false);+ expect(slashOpens(key("/", { target: el(["[data-hotkeys-off]"]) }), noDialog)).toBe(false);+ expect(slashOpens(key("/", { ctrlKey: true }), noDialog)).toBe(false);+ expect(slashOpens(key("/", { metaKey: true }), noDialog)).toBe(false);+ expect(slashOpens(key("/", { defaultPrevented: true }), noDialog)).toBe(false);+ expect(slashOpens(key("/", { isComposing: true }), noDialog)).toBe(false);+ expect(slashOpens(key("?"), noDialog)).toBe(false);+ // Over a dialog or a menu that is open.+ expect(slashOpens(key("/"), dialogOpen)).toBe(false);+ });++ it("knows a field from the page", () => {+ expect(typesText(null)).toBe(false);+ expect(typesText(el())).toBe(false);+ expect(typesText(el(["textarea"]))).toBe(true);+ expect(typesText({} as EventTarget)).toBe(false);+ });+});++function withClient(node: ReactNode, seed?: (c: QueryClient) => void) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, enabled: false } } });+ seed?.(client);+ return renderToStaticMarkup(createElement(QueryClientProvider, { client }, node));+}++describe("the palette's provider", () => {+ it("renders the page alone until the palette is wanted (its code loads on its own)", () => {+ function Probe() {+ const s = useSearchPalette();+ return createElement("span", { "data-open": String(s.isOpen) }, "page");+ }+ const html = withClient(createElement(SearchPaletteProvider, null, createElement(Probe)));+ expect(html).toBe('<span data-open="false">page</span>');+ });++ it("does nothing outside the provider", () => {+ let api: ReturnType<typeof useSearchPalette> | undefined;+ function Probe() {+ api = useSearchPalette();+ return null;+ }+ renderToStaticMarkup(createElement(Probe));+ expect(api?.isOpen).toBe(false);+ expect(() => api?.open()).not.toThrow();+ });+});++describe("the palette's rows", () => {+ const inList = (node: ReactNode) => renderToStaticMarkup(createElement(CommandPrimitive, { label: "Search" }, createElement(CommandPrimitive.List, null, node)));++ it("shows a best match with its cover, line and tag, as an option", () => {+ const html = inList(+ createElement(BestRow, {+ hit: { key: "app:app-giant-product", kind: "app", label: "Giant Product", hint: "Product", href: "/apps/app-giant-product", cover: "/previews/presets/thumbs/app-giant-product.jpg?v=1234abcd", score: 50 },+ onPick: () => {},+ }),+ );+ expect(html).toContain('role="option"');+ expect(html).toContain("Giant Product");+ expect(html).toContain('src="/previews/presets/thumbs/app-giant-product.jpg?v=1234abcd"');+ expect(html).toContain('alt=""');+ expect(html).toContain(">App<");+ });++ it("puts a tool under its studio, and tags studios", () => {+ const html = inList(createElement(BestRow, { hit: { key: "nav:audio-clean", kind: "tool", label: "Clean up voice", hint: "Audio", what: "Remove noise and echo", href: "/audio/clean", icon: "Eraser", score: 9 }, onPick: () => {} }));+ expect(html).toMatch(/Audio<\/span>.*Clean up voice/);+ expect(kindTag({ kind: "studio" })).toBe("Studio");+ expect(kindTag({ kind: "page", navKind: "create" })).toBe("Create");+ expect(kindTag({ kind: "setting" })).toBe("Settings");+ });++ it("shows a studio tile with its name (the short one on a phone), on up to two lines, without a badge", () => {+ const html = inList(createElement(StudioTile, { e: entry("character-swap")!, onPick: () => {} }));+ expect(html).toContain("Character swap");+ expect(html).toContain("Character Swap");+ expect(html).toContain("line-clamp-2");+ expect(html).not.toContain(">New<");+ });+});++describe("the palette's body", () => {+ const body = (initialQuery: string, initialGroup?: "sell") =>+ withClient(createElement(PaletteBody, { initialQuery, initialGroup, onPick: () => {}, onOpenRecent: () => {}, onClose: () => {} }), (c) =>+ c.setQueryData(PALETTE_INDEX_KEY, paletteIndex()),+ );++ /** The studio tiles' full names, in order (each tile also carries its short name for phones). */+ const tiles = (html: string) => [...html.matchAll(/<span class="max-md:hidden">([^<]+)<\/span>/g)].map((m) => m[1].replaceAll("&", "&"));++ it("lists every studio before a search, with the goal chips", () => {+ const html = body("");+ expect(html).toContain('placeholder="What do you want to make?"');+ expect(tiles(html)).toEqual(launcherEntries(undefined).map((e) => e.label));+ expect(html).toContain('aria-label="Show the studios for one goal"');+ expect((html.match(/aria-pressed="true"/g) ?? []).length).toBe(1);+ expect(html).toContain('aria-pressed="true" aria-label="All studios"');+ // The Cancel button's name starts with the word it shows.+ expect(html).toContain('>Esc<span class="sr-only"> (close search)</span>');+ // The goal chips are buttons, outside the listbox.+ const list = html.slice(html.indexOf('role="listbox"'));+ expect(list).not.toContain("aria-pressed");+ expect(html).not.toContain("Best matches");+ });++ it("finds what a query means, best first, and keeps every studio below", () => {+ const html = body("ad for my perfume");+ const best = html.slice(html.indexOf("Best matches"), html.indexOf("Also try"));+ const order = ["Marketing Studio", "Ads Studio", "Giant Product"].map((l) => best.indexOf(l));+ expect(order.every((i) => i >= 0)).toBe(true);+ expect(order).toEqual([...order].sort((a, b) => a - b));+ expect(html.indexOf("Every studio")).toBeGreaterThan(html.indexOf("Also try"));+ expect(tiles(html)).toHaveLength(33);+ });++ it("starts filtered to a goal when opened for one", () => {+ const html = body("", "sell");+ expect(tiles(html)).toEqual(["Marketing Studio", "Ads Studio", "Mixed Media", "Moodboards", "Photodump"]);+ expect(html).toContain("5 in Sell & advertise");+ });++ it("starts on the best match, or on the first studio when nothing is typed", () => {+ const E = [...navSearchEntries(entriesFor("guest")), ...indexEntries(paletteIndex(), "both")];+ const studios = launcherEntries("guest");+ expect(startValue(true, searchNav("ad for my perfume", E), [], studios)).toBe("nav:marketing");+ expect(startValue(false, searchNav("", E), [{ id: "g1" }], studios)).toBe("tile:cinema");+ expect(startValue(true, searchNav("zqx", E), [{ id: "g1" }], studios)).toBe("recent:g1");+ expect(startValue(true, searchNav("zqx", E), [], studios)).toBe("tile:cinema");+ expect(startValue(false, searchNav("", E), [], [])).toBe("");+ });++ it("shows no owner setting before the viewer is known", () => {+ expect(body("comfyui server")).not.toContain("ComfyUI server");+ });+});diff --git a/tests/shell-logic.test.ts b/tests/shell-logic.test.tsindex 27196542..ea373c82 100644--- a/tests/shell-logic.test.ts+++ b/tests/shell-logic.test.ts@@ -748,15 +748,15 @@ describe("copyText", () => {});describe("landmarks", () => {- it("leaves one <main> per page: the app frame's inset sheet", () => {- // Pages render inside StudioChrome, whose SidebarInset is the <main>; a second one inside it+ it("leaves one <main> per page: the app frame's", () => {+ // Pages render inside StudioChrome, whose <main id="content"> holds them; a second one inside it// would give screen readers two main landmarks.const files = (dir: string): string[] =>fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? files(path.join(dir, e.name)) : e.name.endsWith(".tsx") ? [path.join(dir, e.name)] : []));const root = path.resolve(__dirname, "../src");const mains = [...files(path.join(root, "components")), ...files(path.join(root, "app/(studio)"))].filter((f) => /<main[\s>]/.test(fs.readFileSync(f, "utf8")))- .map((f) => path.relative(root, f));- expect(mains).toEqual(["components/ui/sidebar.tsx"]);+ .map((f) => path.relative(root, f).split(path.sep).join("/"));+ expect(mains).toEqual(["components/nav/studio-chrome.tsx"]);});});